diff --git a/pool/shard006/C/0117045_if_tr_isa.c b/pool/shard006/C/0117045_if_tr_isa.c new file mode 100644 index 0000000000000000000000000000000000000000..637b18f5af2e3fd76affc7cb1d19163edd9473fc --- /dev/null +++ b/pool/shard006/C/0117045_if_tr_isa.c @@ -0,0 +1,264 @@ +/* $NetBSD: if_tr_isa.c,v 1.24 2012/10/27 17:18:24 chs Exp $ */ + +/* XXXJRT changes isa_attach_args too early!! */ + +/* + * Copyright (c) 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Onno van der Linden. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +__KERNEL_RCSID(0, "$NetBSD: if_tr_isa.c,v 1.24 2012/10/27 17:18:24 chs Exp $"); + +#undef TRISADEBUG + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include + + +int tr_isa_probe(device_t, cfdata_t, void *); +int trtcm_isa_probe(device_t, cfdata_t, void *); +int tribm_isa_probe(device_t, cfdata_t, void *); +void tr_isa_attach(device_t, device_t, void *); +int tr_isa_map_io(struct isa_attach_args *, bus_space_handle_t *, + bus_space_handle_t *); +void tr_isa_unmap_io(struct isa_attach_args *, bus_space_handle_t, + bus_space_handle_t); +int trtcm_isa_mediachange(struct tr_softc *); +void trtcm_isa_mediastatus(struct tr_softc *, struct ifmediareq *); +#ifdef TRISADEBUG +void tr_isa_dumpaip(bus_space_tag_t, bus_space_handle_t); +#endif + +/* + * List of manufacturer specific probe routines. Order is important. + */ +int (*tr_isa_probe_list[])(device_t, cfdata_t, void *) = { + trtcm_isa_probe, + tribm_isa_probe, + 0 + }; + +CFATTACH_DECL_NEW(tr_isa, sizeof(struct tr_softc), + tr_isa_probe, tr_isa_attach, NULL, NULL); + +int +tr_isa_map_io(struct isa_attach_args *ia, bus_space_handle_t *pioh, bus_space_handle_t *mmioh) +{ + bus_size_t mmio; + u_int8_t s; + + if (bus_space_map(ia->ia_iot, ia->ia_io[0].ir_addr, + ia->ia_io[0].ir_size, 0, pioh)) { + printf("tr_isa_map_io: can't map PIO ports\n"); + return 1; + } + + /* Read adapter switches and calculate addresses of MMIO. */ + s = bus_space_read_1(ia->ia_iot, *pioh, TR_SWITCH); + + if ((s & 0xfc) < ((TR_MMIO_MINADDR - TR_MMIO_OFFSET) >> 11) || + (s & 0xfc) > ((TR_MMIO_MAXADDR - TR_MMIO_OFFSET) >> 11)) { + bus_space_unmap(ia->ia_iot, *pioh, ia->ia_io[0].ir_size); + return 1; + } + + mmio = ((s & 0xfc) << 11) + TR_MMIO_OFFSET; + if (bus_space_map(ia->ia_memt, mmio, TR_MMIO_SIZE, 0, mmioh)) { + printf("tr_isa_map_io: can't map MMIO region 0x%05lx/%d\n", + (u_long)mmio, TR_MMIO_SIZE); + bus_space_unmap(ia->ia_iot, *pioh, ia->ia_io[0].ir_size); + return 1; + } + return 0; +} + +void +tr_isa_unmap_io(struct isa_attach_args *ia, bus_space_handle_t pioh, bus_space_handle_t mmioh) +{ + bus_space_unmap(ia->ia_memt, mmioh, TR_MMIO_SIZE); + bus_space_unmap(ia->ia_iot, pioh, ia->ia_io[0].ir_size); +} + +static u_char tr_isa_id[] = { + 5, 0, 4, 9, 4, 3, 4, 15, 3, 6, 3, 1, 3, 1, 3, 0, 3, 9, 3, 9, 3, 0, 2, 0 +}; + +/* + * XXX handle multiple IBM TR cards (sram mapping !!) + */ + +int +tr_isa_probe(device_t parent, cfdata_t match, void *aux) +{ + struct isa_attach_args *ia = aux; + int i; + bus_size_t tr_id; + bus_space_handle_t sramh, pioh, mmioh; + int probecode; + int matched = 0; + + if (ia->ia_nio < 1) + return (0); + if (ia->ia_niomem < 1) + return (0); + if (ia->ia_nirq < 1) + return (0); + + if (ISA_DIRECT_CONFIG(ia)) + return (0); + + for (i = 0; tr_isa_probe_list[i] != 0; i++) { + probecode = tr_isa_probe_list[i](parent, match, aux); + if (probecode < 0) + return 0; /* Fail instantly. */ + if (probecode > 0) + break; /* We have a match. */ + } + if (tr_isa_probe_list[i] == 0) + return 0; /* Nothing matched. */ + if (tr_isa_map_io(ia, &pioh, &mmioh)) + return 0; + tr_id = TR_ID_OFFSET; + matched = 1; + for (i = 0; i < sizeof(tr_isa_id); i++) { + if (bus_space_read_1(ia->ia_memt, mmioh, tr_id) != + tr_isa_id[i]) + matched = 0; + tr_id += 2; + } +#ifdef TRISADEBUG + tr_isa_dumpaip(ia->ia_memt, mmioh); +#endif + tr_isa_unmap_io(ia, pioh, mmioh); + if (!matched) { + return 0; + } + if (bus_space_map(ia->ia_memt, ia->ia_iomem[0].ir_addr, + ia->ia_iomem[0].ir_size, 0, &sramh)) { + printf("tr_isa_probe: can't map shared ram\n"); + return 0; + } + bus_space_unmap(ia->ia_memt, sramh, ia->ia_iomem[0].ir_size); + + ia->ia_nio = 1; + ia->ia_niomem = 1; + ia->ia_nirq = 1; + + ia->ia_ndrq = 0; + + return 1; +} + +int trtcm_setspeed(struct tr_softc *, int); + +void +tr_isa_attach(device_t parent, device_t self, void *aux) +{ + struct tr_softc *sc = device_private(self); + struct isa_attach_args *ia = aux; + + printf("\n"); + + sc->sc_dev = self; + sc->sc_piot = ia->ia_iot; + sc->sc_memt = ia->ia_memt; + if (tr_isa_map_io(ia, &sc->sc_pioh, &sc->sc_mmioh)) { + printf("tr_isa_attach: IO space vanished\n"); + return; + } + if (bus_space_map(sc->sc_memt, ia->ia_iomem[0].ir_addr, + ia->ia_iomem[0].ir_size, 0, &sc->sc_sramh)) { + printf("tr_isa_attach: shared ram space vanished\n"); + return; + } + /* set ACA offset */ + sc->sc_aca = TR_ACA_OFFSET; + sc->sc_memwinsz = ia->ia_iomem[0].ir_size; + sc->sc_maddr = ia->ia_iomem[0].ir_addr; + /* + * Determine total RAM on adapter and decide how much to use. + * XXX Since we don't use RAM paging, use sc_memwinsz for now. + */ + sc->sc_memsize = sc->sc_memwinsz; + sc->sc_memreserved = 0; + + if (tr_reset(sc) != 0) + return; + + if (ia->ia_aux != NULL) { + sc->sc_mediastatus = trtcm_isa_mediastatus; + sc->sc_mediachange = trtcm_isa_mediachange; + } + else { + sc->sc_mediastatus = NULL; + sc->sc_mediachange = NULL; + } + + if (tr_attach(sc) != 0) + return; + +/* + * XXX 3Com 619 can use LEVEL intr + */ + sc->sc_ih = isa_intr_establish(ia->ia_ic, ia->ia_irq[0].ir_irq, + IST_EDGE, IPL_NET, tr_intr, sc); +} + +#ifdef TRISADEBUG +/* + * Dump the adapters AIP + */ +void +tr_isa_dumpaip(bus_space_tag_t memt, bus_space_handle_t mmioh) +{ + unsigned int off, val; + printf("AIP contents:"); + for (off=0; off < 256; off++) { + val = bus_space_read_1(memt, mmioh, TR_MAC_OFFSET + off); + if ((off % 16) == 0) + printf("\n"); + printf("%02x ", val); + } + printf("\n"); +} +#endif diff --git a/pool/shard006/C/0117046_ooaofooa_ACT_RU_class.c b/pool/shard006/C/0117046_ooaofooa_ACT_RU_class.c new file mode 100644 index 0000000000000000000000000000000000000000..78337363e2e02e74a58be20a6a6ec908a85803ad --- /dev/null +++ b/pool/shard006/C/0117046_ooaofooa_ACT_RU_class.c @@ -0,0 +1,234 @@ +/*---------------------------------------------------------------------------- + * File: ooaofooa_ACT_RU_class.c + * + * Class: Relate Using (ACT_RU) + * Component: ooaofooa + * + * your copyright statement can go here (from te_copyright.body) + *--------------------------------------------------------------------------*/ + +#include "sys_sys_types.h" +#include "LOG_bridge.h" +#include "POP_bridge.h" +#include "T_bridge.h" +#include "ooaofooa_classes.h" + +/* + * Instance Loader (from string data). + */ +Escher_iHandle_t +ooaofooa_ACT_RU_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] ) +{ + Escher_iHandle_t return_identifier = 0; + ooaofooa_ACT_RU * self = (ooaofooa_ACT_RU *) instance; + /* Initialize application analysis class attributes. */ + self->Statement_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] ); + self->One_Side_Var_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 2 ] ); + self->Other_Side_Var_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 3 ] ); + self->Associative_Var_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 4 ] ); + self->relationship_phrase = Escher_strcpy( self->relationship_phrase, avlstring[ 5 ] ); + self->Rel_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 6 ] ); + self->associationNumberLineNumber = Escher_atoi( avlstring[ 7 ] ); + self->associationNumberColumn = Escher_atoi( avlstring[ 8 ] ); + self->associationPhraseLineNumber = Escher_atoi( avlstring[ 9 ] ); + self->associationPhraseColumn = Escher_atoi( avlstring[ 10 ] ); + return return_identifier; +} + +/* + * Select any where using referential/identifying attribute set. + * If not_empty, relate this instance to the selected instance. + */ +void ooaofooa_ACT_RU_batch_relate( Escher_iHandle_t instance ) +{ + ooaofooa_ACT_RU * ooaofooa_ACT_RU_instance = (ooaofooa_ACT_RU *) instance; + ooaofooa_V_VAR * ooaofooa_V_VARrelated_instance1 = (ooaofooa_V_VAR *) Escher_instance_cache[ (intptr_t) ooaofooa_ACT_RU_instance->One_Side_Var_ID ]; + if ( ooaofooa_V_VARrelated_instance1 ) { + ooaofooa_ACT_RU_R617_Link_is_one_variable( ooaofooa_V_VARrelated_instance1, ooaofooa_ACT_RU_instance ); + } + { + ooaofooa_V_VAR * ooaofooa_V_VARrelated_instance1 = (ooaofooa_V_VAR *) Escher_instance_cache[ (intptr_t) ooaofooa_ACT_RU_instance->Other_Side_Var_ID ]; + if ( ooaofooa_V_VARrelated_instance1 ) { + ooaofooa_ACT_RU_R618_Link_is_other_variable( ooaofooa_V_VARrelated_instance1, ooaofooa_ACT_RU_instance ); + } + } + { + ooaofooa_V_VAR * ooaofooa_V_VARrelated_instance1 = (ooaofooa_V_VAR *) Escher_instance_cache[ (intptr_t) ooaofooa_ACT_RU_instance->Associative_Var_ID ]; + if ( ooaofooa_V_VARrelated_instance1 ) { + ooaofooa_ACT_RU_R619_Link_is_using_variable( ooaofooa_V_VARrelated_instance1, ooaofooa_ACT_RU_instance ); + } + } + { + ooaofooa_ACT_SMT * ooaofooa_ACT_SMTrelated_instance1 = (ooaofooa_ACT_SMT *) Escher_instance_cache[ (intptr_t) ooaofooa_ACT_RU_instance->Statement_ID ]; + if ( ooaofooa_ACT_SMTrelated_instance1 ) { + ooaofooa_ACT_RU_R603_Link( ooaofooa_ACT_SMTrelated_instance1, ooaofooa_ACT_RU_instance ); + } + } + { + ooaofooa_R_REL * ooaofooa_R_RELrelated_instance1 = ooaofooa_R_REL_AnyWhere1( ooaofooa_ACT_RU_instance->Rel_ID ); + if ( ooaofooa_R_RELrelated_instance1 ) { + ooaofooa_ACT_RU_R654_Link( ooaofooa_R_RELrelated_instance1, ooaofooa_ACT_RU_instance ); + } + } +} + + +/* + * RELATE ACT_SMT TO ACT_RU ACROSS R603 + */ +void +ooaofooa_ACT_RU_R603_Link( ooaofooa_ACT_SMT * supertype, ooaofooa_ACT_RU * subtype ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + subtype->Statement_ID = supertype->Statement_ID; + /* Optimized linkage for ACT_RU->ACT_SMT[R603] */ + subtype->ACT_SMT_R603 = supertype; + /* Optimized linkage for ACT_SMT->ACT_RU[R603] */ + supertype->R603_subtype = subtype; + supertype->R603_object_id = ooaofooa_ACT_RU_CLASS_NUMBER; +} + + +/* + * UNRELATE ACT_SMT FROM ACT_RU ACROSS R603 + */ +void +ooaofooa_ACT_RU_R603_Unlink( ooaofooa_ACT_SMT * supertype, ooaofooa_ACT_RU * subtype ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + subtype->ACT_SMT_R603 = 0; + supertype->R603_subtype = 0; + supertype->R603_object_id = 0; +} + + +/* + * RELATE V_VAR TO ACT_RU ACROSS R617 + */ +void +ooaofooa_ACT_RU_R617_Link_is_one_variable( ooaofooa_V_VAR * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->One_Side_Var_ID = part->Var_ID; + form->V_VAR_R617_one = part; + Escher_SetInsertElement( &part->ACT_RU_R617_is_one_variable, (Escher_ObjectSet_s *) form ); +} + +/* + * UNRELATE V_VAR FROM ACT_RU ACROSS R617 + */ +void +ooaofooa_ACT_RU_R617_Unlink_is_one_variable( ooaofooa_V_VAR * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->One_Side_Var_ID = 0; + form->V_VAR_R617_one = 0; + Escher_SetRemoveElement( &part->ACT_RU_R617_is_one_variable, (Escher_ObjectSet_s *) form ); +} + +/* + * RELATE V_VAR TO ACT_RU ACROSS R618 + */ +void +ooaofooa_ACT_RU_R618_Link_is_other_variable( ooaofooa_V_VAR * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Other_Side_Var_ID = part->Var_ID; + form->V_VAR_R618_other = part; + Escher_SetInsertElement( &part->ACT_RU_R618_is_other_variable, (Escher_ObjectSet_s *) form ); +} + +/* + * UNRELATE V_VAR FROM ACT_RU ACROSS R618 + */ +void +ooaofooa_ACT_RU_R618_Unlink_is_other_variable( ooaofooa_V_VAR * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Other_Side_Var_ID = 0; + form->V_VAR_R618_other = 0; + Escher_SetRemoveElement( &part->ACT_RU_R618_is_other_variable, (Escher_ObjectSet_s *) form ); +} + +/* + * RELATE V_VAR TO ACT_RU ACROSS R619 + */ +void +ooaofooa_ACT_RU_R619_Link_is_using_variable( ooaofooa_V_VAR * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Associative_Var_ID = part->Var_ID; + form->V_VAR_R619_using = part; + Escher_SetInsertElement( &part->ACT_RU_R619_is_using_variable, (Escher_ObjectSet_s *) form ); +} + +/* + * UNRELATE V_VAR FROM ACT_RU ACROSS R619 + */ +void +ooaofooa_ACT_RU_R619_Unlink_is_using_variable( ooaofooa_V_VAR * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Associative_Var_ID = 0; + form->V_VAR_R619_using = 0; + Escher_SetRemoveElement( &part->ACT_RU_R619_is_using_variable, (Escher_ObjectSet_s *) form ); +} + +/* + * RELATE R_REL TO ACT_RU ACROSS R654 + */ +void +ooaofooa_ACT_RU_R654_Link( ooaofooa_R_REL * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Rel_ID = part->Rel_ID; + form->R_REL_R654_creates = part; + Escher_SetInsertElement( &part->ACT_RU_R654, (Escher_ObjectSet_s *) form ); +} + +/* + * UNRELATE R_REL FROM ACT_RU ACROSS R654 + */ +void +ooaofooa_ACT_RU_R654_Unlink( ooaofooa_R_REL * part, ooaofooa_ACT_RU * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Rel_ID = 0; + form->R_REL_R654_creates = 0; + Escher_SetRemoveElement( &part->ACT_RU_R654, (Escher_ObjectSet_s *) form ); +} + +/* + * Dump instances in SQL format. + */ +void +ooaofooa_ACT_RU_instancedumper( Escher_iHandle_t instance ) +{ + ooaofooa_ACT_RU * self = (ooaofooa_ACT_RU *) instance; + printf( "INSERT INTO ACT_RU VALUES ( %ld,%ld,%ld,%ld,'%s',%ld,%d,%d,%d,%d );\n", + ((long)self->Statement_ID & ESCHER_IDDUMP_MASK), + ((long)self->One_Side_Var_ID & ESCHER_IDDUMP_MASK), + ((long)self->Other_Side_Var_ID & ESCHER_IDDUMP_MASK), + ((long)self->Associative_Var_ID & ESCHER_IDDUMP_MASK), + ( 0 != self->relationship_phrase ) ? self->relationship_phrase : "", + ((long)self->Rel_ID & ESCHER_IDDUMP_MASK), + self->associationNumberLineNumber, + self->associationNumberColumn, + self->associationPhraseLineNumber, + self->associationPhraseColumn ); +} +/* + * Statically allocate space for the instance population for this class. + * Allocate space for the class instance and its attribute values. + * Depending upon the collection scheme, allocate containoids (collection + * nodes) for gathering instances into free and active extents. + */ +static Escher_SetElement_s ooaofooa_ACT_RU_container[ ooaofooa_ACT_RU_MAX_EXTENT_SIZE ]; +static ooaofooa_ACT_RU ooaofooa_ACT_RU_instances[ ooaofooa_ACT_RU_MAX_EXTENT_SIZE ]; +Escher_Extent_t pG_ooaofooa_ACT_RU_extent = { + {0,0}, {0,0}, &ooaofooa_ACT_RU_container[ 0 ], + (Escher_iHandle_t) &ooaofooa_ACT_RU_instances, + sizeof( ooaofooa_ACT_RU ), 0, ooaofooa_ACT_RU_MAX_EXTENT_SIZE + }; + + diff --git a/pool/shard006/C/0117050_kern_condvar.c b/pool/shard006/C/0117050_kern_condvar.c new file mode 100644 index 0000000000000000000000000000000000000000..bba5f5f46dc0d356ea845d9ff269aaf979b2140b --- /dev/null +++ b/pool/shard006/C/0117050_kern_condvar.c @@ -0,0 +1,242 @@ +/*- + * Copyright (c) 2000 Jake Burkholder . + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/sys/kern/kern_condvar.c,v 1.50.2.1 2004/09/03 15:14:14 jhb Exp $"); + +#include "opt_ktrace.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef KTRACE +#include +#include +#endif + +/* + * Common sanity checks for cv_wait* functions. + */ +#define CV_ASSERT(cvp, mp, td) do { \ + KASSERT((td) != NULL, ("%s: curthread NULL", __func__)); \ + KASSERT(TD_IS_RUNNING(td), ("%s: not TDS_RUNNING", __func__)); \ + KASSERT((cvp) != NULL, ("%s: cvp NULL", __func__)); \ + KASSERT((mp) != NULL, ("%s: mp NULL", __func__)); \ + mtx_assert((mp), MA_OWNED | MA_NOTRECURSED); \ +} while (0) + +/* + * Initialize a condition variable. Must be called before use. + */ +void +cv_init(struct cv *cvp, const char *desc) +{ + cvp->cv_description = desc; + cvp->cv_waiters = 0; + cvp->signals = 0; + ddekit_lock_init(&cvp->lock); + cvp->sem = ddekit_sem_init(0); + cvp->handshake = ddekit_sem_init(0); +} + +/* + * Destroy a condition variable. The condition variable must be re-initialized + * in order to be re-used. + */ +void +cv_destroy(struct cv *cvp) +{ + ddekit_lock_deinit(&cvp->lock); + ddekit_sem_deinit(cvp->sem); + ddekit_sem_deinit(cvp->handshake); +} + +/* + * Wait on a condition variable. The current thread is placed on the condition + * variable's wait queue and suspended. A cv_signal or cv_broadcast on the same + * condition variable will resume the thread. The mutex is released before + * sleeping and will be held on return. It is recommended that the mutex be + * held when cv_signal or cv_broadcast are called. + */ +void +cv_wait(struct cv *cvp, struct mtx *mp) +{ + cv_timedwait(cvp, mp, -1); +} + +/* + * Wait on a condition variable, allowing interruption by signals. Return 0 if + * the thread was resumed with cv_signal or cv_broadcast, EINTR or ERESTART if + * a signal was caught. If ERESTART is returned the system call should be + * restarted if possible. + */ +int +cv_wait_sig(struct cv *cvp, struct mtx *mp) +{ + return cv_timedwait(cvp, mp, -1); +} + +/* + * Wait on a condition variable for at most timo/hz seconds. Returns 0 if the + * process was resumed by cv_signal or cv_broadcast, EWOULDBLOCK if the timeout + * expires. + */ +int +cv_timedwait(struct cv *cvp, struct mtx *mp, int timo) +{ + struct thread *td; + int rval; + WITNESS_SAVE_DECL(mp); + + td = curthread; + rval = 0; +#ifdef KTRACE + if (KTRPOINT(td, KTR_CSW)) + ktrcsw(1, 0); +#endif + CV_ASSERT(cvp, mp, td); + WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, &mp->mtx_object, + "Waiting on \"%s\"", cvp->cv_description); + WITNESS_SAVE(&mp->mtx_object, mp); + + if (cold || panicstr) { + /* + * After a panic, or during autoconfiguration, just give + * interrupts a chance, then just return; don't run any other + * thread or panic below, in case this is the idle process and + * already asleep. + */ + return 0; + } + + ddekit_lock_lock(&cvp->lock); + cvp->cv_waiters++; + ddekit_lock_unlock(&cvp->lock); + DROP_GIANT(); + mtx_unlock(mp); + + if (timo == -1) { + ddekit_sem_down(cvp->sem); + } else { + if (ddekit_sem_down_timed(cvp->sem, timo*1000/hz)) { + rval = EWOULDBLOCK; + } else { + } + } + + ddekit_lock_lock(&cvp->lock); + if (cvp->signals > 0) { + // if we timed out, but there is a signal now, consume it + if (rval) ddekit_sem_down(cvp->sem); + + ddekit_sem_up(cvp->handshake); + cvp->signals--; + } + cvp->cv_waiters--; + ddekit_lock_unlock(&cvp->lock); + +#ifdef KTRACE + if (KTRPOINT(td, KTR_CSW)) + ktrcsw(0, 0); +#endif + PICKUP_GIANT(); + mtx_lock(mp); + WITNESS_RESTORE(&mp->mtx_object, mp); + + return (rval); +} + +/* + * Wait on a condition variable for at most timo/hz seconds, allowing + * interruption by signals. Returns 0 if the thread was resumed by cv_signal + * or cv_broadcast, EWOULDBLOCK if the timeout expires, and EINTR or ERESTART if + * a signal was caught. + */ +int +cv_timedwait_sig(struct cv *cvp, struct mtx *mp, int timo) +{ + return cv_timedwait(cvp, mp, timo); +} + +/* + * Signal a condition variable, wakes up one waiting thread. Will also wakeup + * the swapper if the process is not in memory, so that it can bring the + * sleeping process in. Note that this may also result in additional threads + * being made runnable. Should be called with the same mutex as was passed to + * cv_wait held. + */ +void +cv_signal(struct cv *cvp) +{ + ddekit_lock_lock(&cvp->lock); + + if (cvp->cv_waiters > cvp->signals) { + cvp->signals++; + ddekit_sem_up(cvp->sem); + ddekit_lock_unlock(&cvp->lock); + ddekit_sem_down(cvp->handshake); + } else { + // nobody left to wakeup + ddekit_lock_unlock(&cvp->lock); + } +} + +/* + * Broadcast a signal to a condition variable. Wakes up all waiting threads. + * Should be called with the same mutex as was passed to cv_wait held. + */ +void +cv_broadcastpri(struct cv *cvp, int pri) +{ + int waiters; + + ddekit_lock_lock(&cvp->lock); + + waiters = cvp->cv_waiters - cvp->signals; + if (waiters > 0) { + int i; + + cvp->signals = cvp->cv_waiters; + for (i=0; isem); + } + ddekit_lock_unlock(&cvp->lock); + for (i=0; ihandshake); + } + } else { + ddekit_lock_unlock(&cvp->lock); + } +} diff --git a/pool/shard006/C/0117055_sysschevt.c b/pool/shard006/C/0117055_sysschevt.c new file mode 100644 index 0000000000000000000000000000000000000000..5fbca6819f14a4936cf478f5f1253285ec1f15e3 --- /dev/null +++ b/pool/shard006/C/0117055_sysschevt.c @@ -0,0 +1,129 @@ +// $Id$ +// $Locker$ + +// Author. Roar Thronæs. +/** + \file sysschevt.c + \brief system scheduling and timer + \author Roar Thronæs +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + \brief set timer - see 5.2 11.6.1 + \param efn event flag + \param daytim time + \param astadr ast routine + \param reqidt param for it + \param flags +*/ + +asmlinkage int exe$setimr (unsigned int efn, signed long long *daytim, + void (*astadr)(long), unsigned + long reqidt, unsigned int flags) +{ + unsigned long long time; + /** test time location - MISSING */ + /** test astcnt - MISSING */ + /** decrement jib tqcnt, test and maybe MWAIT - MISSING */ + /** allocate tqe */ + struct _tqe * t=kmalloc(sizeof(struct _tqe),GFP_KERNEL); + struct _cpu * cpu=smp$gl_cpu_data[smp_processor_id()]; + memset(t,0,sizeof(struct _tqe)); + t->tqe$b_type=DYN$C_TQE; + /** clear event flag */ + exe$clref(efn); + /** fifth nonzero argument test */ + /** wrong use TODO use chk_cputim field */ + if (flags) t->tqe$b_rqtype=TQE$M_CHK_CPUTIM; + if (!daytim) return SS$_ACCVIO; + /** if negative, then relative time */ + /** set absolute bit - MISSING */ + if (*daytim<0) + { + time=exe$gq_systime-*daytim; + } + else + { + time=*daytim; + } + //printk("astadr %x\n",astadr); + /** store access mode in tqe - MISSING */ + /** if no astadr, decrease astcnt and set quota bit - MISSING */ + t->tqe$l_ast=astadr; + // printk("astadr2 %x\n",t->tqe$l_fpc); + t->tqe$l_astprm=reqidt; + t->tqe$q_time=time; + t->tqe$b_rqtype=TQE$C_TMSNGL; + t->tqe$l_pid=ctl$gl_pcb->pcb$l_pid; + t->tqe$b_efn=efn; + //printast((struct _acb * )t); + /** insert in timer queue */ + exe$instimq(t); +} + +/** + \brief schedule wakeup - see 5.2 11.6.3 + \param pidadr address of pid + \param prcnam process name + \param daytim time of day + \param reptim time to repeat +*/ + +asmlinkage int exe$schdwk(unsigned int *pidadr, void *prcnam, signed long long * daytim, signed long long * reptim) +{ + struct _pcb * retpcb, *p; + unsigned long retipid, retepid; + /** invoke exe$nampid to find pcb */ + int sts=exe$nampid(current,pidadr,prcnam,&retpcb,&retipid,&retepid); + p=retpcb; + /** TODO better handling of sts and vmsunlock */ + vmsunlock(&SPIN_SCHED,0); + /** maybe cwps - MISSING */ + if (!p) return; + { + unsigned long long time; + /** allocate and init tqe */ + struct _tqe * t=kmalloc(sizeof(struct _tqe),GFP_KERNEL); + struct _cpu * cpu=smp$gl_cpu_data[smp_processor_id()]; + memset(t,0,sizeof(struct _tqe)); + t->tqe$b_type=DYN$C_TQE; + /** test if one-time or repeating */ + if (*daytim<0) + { + /** convert repeat to system time format */ + time=exe$gq_systime-*daytim; + /** if relative clear tqe absolute bit - MISSING */ + } + else + { + time=*daytim; + } + t->tqe$l_pid=p->pcb$l_pid; + t->tqe$q_time=time; + if (reptim) t->tqe$q_delta=-(*reptim); + t->tqe$b_rqtype=TQE$C_WKSNGL; + if (reptim) t->tqe$b_rqtype|=TQE$M_REPEAT; + //printast((struct _acb * )t); + /** decrement astcnt - MISSING */ + /** insert with instimq */ + exe$instimq(t); + } + /** return value - MISSING */ +} + + diff --git a/pool/shard006/C/0117061_find_missing.c b/pool/shard006/C/0117061_find_missing.c new file mode 100644 index 0000000000000000000000000000000000000000..eeca1f05f54ad4da233c2db0b7e3e8163c5e0ad5 --- /dev/null +++ b/pool/shard006/C/0117061_find_missing.c @@ -0,0 +1,62 @@ +#include + +/* + * Given an array contains N numbers of 0 .. N, find which number doesn't exist in the array. + */ + +void output(int *array, size_t len) +{ + int i; + for(i=0; i +#include +#include +#include +#include +#include +#include + +#define TD_TRACK (TD_SECTOR * NSECTORS) +#define TD_DISK (TD_TRACK * NTRACKS) + +#define IOF_EOF 0x0002 +#define IOF_ERR 0x8000 + +/* On disk directory entries are always aligned to 2-byte boundary. */ +typedef struct FileEntry { + u_char reclen; /* total size of this record in bytes */ + u_char type; /* type of file (1: executable, 0: regular) */ + u_short start; /* sector where the file begins (0..1759) */ + u_int size; /* file size in bytes (up to 1MiB) */ + char name[0]; /* name of the file (NUL terminated) */ +} FileEntryT; + +static FileEntryT *NextFileEntry(FileEntryT *fe) { + return (void *)fe + fe->reclen; +} + +/* Finished by NUL character (reclen = 0). */ +static FileEntryT *rootDir = NULL; + +struct File { + FileOpsT *ops; + + u_int offset; + u_int length; + + u_short flags; + u_int pos; + + struct { + u_int left; + u_char *pos; + u_char *track; + } buf; +}; + +static inline bool ReadTrack(void *data, int offset) { + int trknum = div16(offset, TD_TRACK); + Log("[Floppy] Read track %d.\n", trknum); + FloppyTrackRead(trknum); + FloppyTrackDecode(data); + return true; +} + +static bool FillBuffer(FileT *file) { + u_int abspos = file->offset + file->pos; + u_int waste = mod16(abspos, TD_TRACK); + + if (file->pos == file->length) { + file->flags |= IOF_EOF; + return false; + } + + if (!ReadTrack(file->buf.track, abspos - waste)) { + file->flags |= IOF_ERR; + return false; + } + + file->buf.pos = file->buf.track + waste; + file->buf.left = min(file->length - file->pos, TD_TRACK - waste); + file->pos += file->buf.left; + return true; +} + +static int FsRead(FileT *f, void *buf, u_int nbyte); +static int FsSeek(FileT *f, int offset, int whence); +static void FsClose(FileT *f); + +static FileOpsT FsOps = { + .read = FsRead, + .write = NULL, + .seek = FsSeek, + .close = FsClose +}; + +static FileT *NewFile(int length, int offset) { + FileT *f = MemAlloc(sizeof(FileT), MEMF_PUBLIC|MEMF_CLEAR); + + f->ops = &FsOps; + f->length = length; + f->offset = offset; + f->buf.track = MemAlloc(TD_TRACK, MEMF_PUBLIC); + f->buf.pos = f->buf.track; + + return f; +} + +static FileEntryT *LookupFile(const char *path) { + FileEntryT *fe = rootDir; + + if (fe == NULL) + return NULL; + + do { + if (strcmp(path, fe->name) == 0) + return fe; + fe = NextFileEntry(fe); + } while (fe->reclen); + + return NULL; +} + +FileT *OpenFile(const char *path) { + FileEntryT *entry; + if ((entry = LookupFile(path))) + return NewFile(entry->size, entry->start * TD_SECTOR); + return NULL; +} + +static void FsClose(FileT *file) { + MemFree(file->buf.track); + MemFree(file); +} + +static int FsRead(FileT *file, void *buf, u_int size) { + u_int left = size; + + if (!file) + return EBADF; + + if (file->flags & IOF_ERR) + return EIO; + + if (size == 0) + return 0; + + // Log("[FileRead] $%p $%p %d\n", file, buf, size); + + while (left > 0) { + if (!file->buf.left && !FillBuffer(file)) + break; + + { + /* Read to the end of buffer or less. */ + int length = min(left, file->buf.left); + + memcpy(buf, file->buf.pos, length); + + file->buf.pos += length; + file->buf.left -= length; + buf += length; left -= length; + } + } + + return size - left; /* how much did we read? */ +} + +static int FsSeek(FileT *file, int offset, int whence) { + if (file->flags & IOF_ERR) + return EIO; + + // Log("[FileSeek] $%p %d %d\n", file, pos, mode); + + file->flags &= ~IOF_EOF; + + if (whence == SEEK_CUR) { + offset += file->pos - file->buf.left; + whence = SEEK_SET; + } + + if (whence == SEEK_SET) { + int bufsize = file->buf.pos - file->buf.track + (int)file->buf.left; + int bufstart = file->pos - bufsize; + int bufend = file->pos; + + /* New position is within buffer boundaries. */ + if ((offset >= bufstart) && (offset < bufend)) { + file->buf.pos = file->buf.track + offset - bufstart; + file->buf.left = file->pos - offset; + return offset; + } + + /* New position is not within file. */ + if ((offset < 0) || (offset > (int)file->length)) + return EINVAL; + + file->pos = offset; + (void)FillBuffer(file); + return offset; + } + + return EINVAL; +} + +int GetFileSize(const char *path) { + FileEntryT *entry; + if ((entry = LookupFile(path))) + return entry->size; + return ENOENT; +} + +int GetCursorPos(FileT *file) { + if (!file) + return EBADF; + if (file->flags & IOF_ERR) + return EIO; + return file->pos - file->buf.left; +} + +#define ONSTACK(x) (&(x)), sizeof((x)) + +void InitFileSys(void) { + FileT *fh; + u_short rootDirLen; + + /* Create a file that represent whole floppy disk without boot sector. */ + fh = NewFile(TD_DISK - TD_SECTOR * 2, TD_SECTOR * 2); + + /* read directory size */ + FileRead(fh, ONSTACK(rootDirLen)); + + Log("[FileSys] Reading directory of %d bytes.\n", rootDirLen); + + /* read directory entries */ + rootDir = MemAlloc(rootDirLen + 1, MEMF_PUBLIC|MEMF_CLEAR); + FileRead(fh, rootDir, rootDirLen); + FileClose(fh); + + /* associate names with file entries */ + { + FileEntryT *fe = rootDir; + do { + Log("[FileSys] Sector %d: %s file '%s' of %d bytes.\n", + fe->start, fe->type ? "executable" : "regular", fe->name, fe->size); + fe = NextFileEntry(fe); + } while (fe->reclen); + } +} + +void KillFileSys(void) { + if (rootDir) { + MemFree(rootDir); + rootDir = NULL; + } +} + +void *LoadFile(const char *path, u_int memoryFlags) { + char *data = NULL; + int size = GetFileSize(path); + + if (size > 0 && (data = MemAlloc(size + 1, memoryFlags))) { + FileT *f = OpenFile(path); + + if (!FileRead(f, data, size)) { + MemFree(data); + data = NULL; + } else { + /* Add extra byte and mark the end of file by zero. */ + data[size] = 0; + } + + FileClose(f); + } + + return data; +} diff --git a/pool/shard006/C/0117068_print-mobile.c b/pool/shard006/C/0117068_print-mobile.c new file mode 100644 index 0000000000000000000000000000000000000000..bbba3db2673ef0108cb07017f38609d095f09e04 --- /dev/null +++ b/pool/shard006/C/0117068_print-mobile.c @@ -0,0 +1,109 @@ +/* $NetBSD: print-mobile.c,v 1.2 1998/09/30 08:57:01 hwr Exp $ */ + +/* + * (c) 1998 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Heiko W.Rupp + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifndef lint +static const char rcsid[] _U_ = + "@(#) $Header: /tcpdump/master/tcpdump/print-mobile.c,v 1.15 2004/03/24 01:58:14 guy Exp $"; +#endif + +#include "tcpdump-stdinc.h" + +#include + +#include "interface.h" +#include "addrtoname.h" +#include "extract.h" /* must come after interface.h */ + +#define MOBILE_SIZE (8) + +struct mobile_ip { + u_int16_t proto; + u_int16_t hcheck; + u_int32_t odst; + u_int32_t osrc; +}; + +#define OSRC_PRES 0x0080 /* old source is present */ + +/* + * Deencapsulate and print a mobile-tunneled IP datagram + */ +void +mobile_print(const u_char *bp, u_int length) +{ + const u_char *cp = bp +8 ; + const struct mobile_ip *mob; + u_short proto,crc; + u_char osp =0; /* old source address present */ + + mob = (const struct mobile_ip *)bp; + + if (length < MOBILE_SIZE || !TTEST(*mob)) { + fputs("[|mobile]", stdout); + return; + } + fputs("mobile: ", stdout); + + proto = EXTRACT_16BITS(&mob->proto); + crc = EXTRACT_16BITS(&mob->hcheck); + if (proto & OSRC_PRES) { + osp=1; + cp +=4 ; + } + + if (osp) { + fputs("[S] ",stdout); + if (vflag) + (void)printf("%s ",ipaddr_string(&mob->osrc)); + } else { + fputs("[] ",stdout); + } + if (vflag) { + (void)printf("> %s ",ipaddr_string(&mob->odst)); + (void)printf("(oproto=%d)",proto>>8); + } + if (in_cksum((u_short *)mob, osp ? 12 : 8, 0)!=0) { + (void)printf(" (bad checksum %d)",crc); + } + + return; +} diff --git a/pool/shard006/C/0117072_util.c b/pool/shard006/C/0117072_util.c new file mode 100644 index 0000000000000000000000000000000000000000..c954ef7a4972bd7f5fb930ad5fb56b276539445b --- /dev/null +++ b/pool/shard006/C/0117072_util.c @@ -0,0 +1,147 @@ +/* + * libid3tag - ID3 tag manipulation library + * Copyright (C) 2000-2004 Underbit Technologies, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * $Id: util.c 1032 2006-05-13 17:42:58Z amadeus_ds $ + */ + +# ifdef HAVE_CONFIG_H +# include "config.h" +# endif + +# include "global.h" + +# include +# include + +# include "id3tag.h" +# include "util.h" + +/* + * NAME: util->unsynchronise() + * DESCRIPTION: perform (in-place) unsynchronisation + */ +id3_length_t id3_util_unsynchronise(id3_byte_t *data, id3_length_t length) +{ + id3_length_t bytes = 0, count; + id3_byte_t *end = data + length; + id3_byte_t const *ptr; + + if (length == 0) + return 0; + + for (ptr = data; ptr < end - 1; ++ptr) { + if (ptr[0] == 0xff && (ptr[1] == 0x00 || (ptr[1] & 0xe0) == 0xe0)) + ++bytes; + } + + if (bytes) { + ptr = end; + end += bytes; + + *--end = *--ptr; + + for (count = bytes; count; *--end = *--ptr) { + if (ptr[-1] == 0xff && (ptr[0] == 0x00 || (ptr[0] & 0xe0) == 0xe0)) { + *--end = 0x00; + --count; + } + } + } + + return length + bytes; +} + +/* + * NAME: util->deunsynchronise() + * DESCRIPTION: undo unsynchronisation (in-place) + */ +id3_length_t id3_util_deunsynchronise(id3_byte_t *data, id3_length_t length) +{ + id3_byte_t const *old, *end = data + length; + id3_byte_t *new; + + if (length == 0) + return 0; + + for (old = new = data; old < end - 1; ++old) { + *new++ = *old; + if (old[0] == 0xff && old[1] == 0x00) + ++old; + } + + *new++ = *old; + + return new - data; +} + +/* + * NAME: util->compress() + * DESCRIPTION: perform zlib deflate method compression + */ +id3_byte_t *id3_util_compress(id3_byte_t const *data, id3_length_t length, + id3_length_t *newlength) +{ + id3_byte_t *compressed; + + *newlength = length + 12; + *newlength += *newlength / 1000; + + compressed = malloc(*newlength); + if (compressed) { + if (compress2(compressed, newlength, data, length, + Z_BEST_COMPRESSION) != Z_OK || + *newlength >= length) { + free(compressed); + compressed = 0; + } + else { + id3_byte_t *resized; + + resized = realloc(compressed, *newlength ? *newlength : 1); + if (resized) + compressed = resized; + } + } + + return compressed; +} + +/* + * NAME: util->decompress() + * DESCRIPTION: undo zlib deflate method compression + */ +id3_byte_t *id3_util_decompress(id3_byte_t const *data, id3_length_t length, + id3_length_t newlength) +{ + id3_byte_t *decompressed; + + decompressed = malloc(newlength ? newlength : 1); + if (decompressed) { + id3_length_t size; + + size = newlength; + + if (uncompress(decompressed, &size, data, length) != Z_OK || + size != newlength) { + free(decompressed); + decompressed = 0; + } + } + + return decompressed; +} diff --git a/pool/shard006/C/0117080_uws_datatype.c b/pool/shard006/C/0117080_uws_datatype.c new file mode 100644 index 0000000000000000000000000000000000000000..4bcdbeaf58bc10fe4d68ea328fcf21da7c360d14 --- /dev/null +++ b/pool/shard006/C/0117080_uws_datatype.c @@ -0,0 +1,27 @@ +#include "uws_datatype.h" +#include "uws_memory.h" +int_queue_t* init_int_queue() { + int_queue_t* new_queue = (int_queue_t*) uws_malloc(sizeof(int_queue_t)); + new_queue->length = 0; + new_queue->head = NULL; + return new_queue; +} +void push_int_queue(int_queue_t *queue, int data) { + int_node_t** next = &queue->head; + while(*next != NULL) { + next = &((*next)->next); + } + int_node_t* new_node = (int_node_t*) uws_malloc(sizeof(int_node_t)); + new_node->element = data; + new_node->next = NULL; + *next = new_node; + queue->length++; +} +int pop_int_queue(int_queue_t *queue) { + int_node_t* tmp = queue->head; + int ret_val = queue->head->element; + queue->head = queue->head->next; + uws_free(tmp); + queue->length--; + return ret_val; +} diff --git a/pool/shard006/C/0117089_hashHelper.c b/pool/shard006/C/0117089_hashHelper.c new file mode 100644 index 0000000000000000000000000000000000000000..0678b98d1ffd93fface472a4b9fb00b5cb3902db --- /dev/null +++ b/pool/shard006/C/0117089_hashHelper.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include "../Headers/hashHelper.h" + +/** + * Assumptions: assuming the charictors red are ascii char only + * @author: Dalin Williams + */ + +/**/ + + +int hashFindIndex(hashM hash, const char *key){ + if(!hash){ + return -1; + } + for(int i = 0; i < hash->len; ++i){ + if (!strcmp(hash->item[i].key, key)) { + //hash->item[i]->key; + return i; + } + } + + return -1; +} + + +int hashFind(hashM hash, const char* key){ + if(!hash){ + return -1; + } + int index = hashFindIndex(hash, key); + return (index == -1) ? -1 : hash->item[index].value; +} + +void hashAdd(hashM hash, const char *key, int val){ + if(!hash){ + return; + } + //We do not take non, positive numbers here + val = abs(val); + //Modify the value if it exists + int index = hashFindIndex(hash, key); + if(index != -1){ + hash->item[index].value = val; + return; + } + //Double the length if we have expended our Resources + if(hash->len == hash->cap){ + hash->cap *= 2; + + hash->item = realloc(hash->item, hash->cap * sizeof(hashV)); + } + //Add new + hash->item[hash->len].key = strdup(key); + hash->item[hash->len].value = val; + hash->len++; +} + +void incramentAdd(hashM hash, const char *key){ + if(!hash){ + return; + } + //Modify the value if it exists + int index = hashFindIndex(hash, key); + if(index != -1){ + hash->item[index].value += 1; + return; + } + //Double the length if we have expended our Resources + if(hash->len == hash->cap){ + hash->cap *= 2; + + hash->item = realloc(hash->item, hash->cap * sizeof(hashV)); + } + //Add new + hash->item[hash->len].key = strdup(key); + hash->item[hash->len].value = 1; + hash->len++; +} + +int hashCompare(const void* a, const void* b){ + hashV *ia = (hashV *)a; + hashV *ib = (hashV *)b; + return strcmp(ia->key, ib->key); +} + +void hashPrint(hashM hash){ + //Quick sort to order the items a-z + int size = hash->len; + qsort(hash->item, size, sizeof(hashV), hashCompare); + for(int i = 0; i < hash->len; i++){ + printf("%s %d \n", hash->item[i].key, hash->item[i].value); + } +} + +hashM newHash(void){ + hashMap newHash ={0, 10, malloc(10 * sizeof(hashV))}; + hashM hashPointer = malloc(sizeof(hashMap)); + *hashPointer = newHash; + return hashPointer; +} + +void freeHash(hashM hashPointer){ + //First free the sub-value parts + for(int i = 0; i < hashPointer->len; i++){ + free((void *) hashPointer->item[i].key); + } + //Remove the rest + free(hashPointer->item); + free(hashPointer); +} \ No newline at end of file diff --git a/pool/shard006/C/0117090_rotlet_direct.c b/pool/shard006/C/0117090_rotlet_direct.c new file mode 100644 index 0000000000000000000000000000000000000000..144b378c0257ccf4a7d229c2f7545154a4efd7ce --- /dev/null +++ b/pool/shard006/C/0117090_rotlet_direct.c @@ -0,0 +1,65 @@ +#include "mex.h" +#include "math.h" + +#define X prhs[0] // Source locations +#define F prhs[1] // Source strengths + +#define U plhs[0] // Output + +#ifndef VERBOSE +#define VERBOSE 0 +#endif + +#define PI 3.141592653589793 + +inline void cross(double * a,double * b, double *c) +{ + c[0] = a[1]*b[2] - a[2]*b[1]; + c[1] = a[2]*b[0] - a[0]*b[2]; + c[2] = a[0]*b[1] - a[1]*b[0]; +} + +/* no input checking is done */ +void mexFunction(int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[] ) +{ + // input dims + const int N = mxGetM(X); + + const double* restrict x = mxGetPr(X); + const double* restrict f = mxGetPr(F); + + U = mxCreateDoubleMatrix(N, 3, mxREAL); + double* restrict u = mxGetPr(U); + + if(VERBOSE) + mexPrintf("[FS Rotlet Direct ] MEX N=%d ",N); + + // call kernel +#ifdef _OPENMP +#pragma omp parallel for +#endif + for(int m=0; m + +#include "core.h" + +static int +mx25l25635_post_bfpt_fixups(struct spi_nor *nor, + const struct sfdp_parameter_header *bfpt_header, + const struct sfdp_bfpt *bfpt) +{ + /* + * MX25L25635F supports 4B opcodes but MX25L25635E does not. + * Unfortunately, Macronix has re-used the same JEDEC ID for both + * variants which prevents us from defining a new entry in the parts + * table. + * We need a way to differentiate MX25L25635E and MX25L25635F, and it + * seems that the F version advertises support for Fast Read 4-4-4 in + * its BFPT table. + */ + if (bfpt->dwords[BFPT_DWORD(5)] & BFPT_DWORD5_FAST_READ_4_4_4) + nor->flags |= SNOR_F_4B_OPCODES; + + return 0; +} + +static struct spi_nor_fixups mx25l25635_fixups = { + .post_bfpt = mx25l25635_post_bfpt_fixups, +}; + +static const struct flash_info macronix_parts[] = { + /* Macronix */ + { "mx25l512e", INFO(0xc22010, 0, 64 * 1024, 1, SECT_4K) }, + { "mx25l2005a", INFO(0xc22012, 0, 64 * 1024, 4, SECT_4K) }, + { "mx25l4005a", INFO(0xc22013, 0, 64 * 1024, 8, SECT_4K) }, + { "mx25l8005", INFO(0xc22014, 0, 64 * 1024, 16, 0) }, + { "mx25l1606e", INFO(0xc22015, 0, 64 * 1024, 32, SECT_4K) }, + { "mx25l3205d", INFO(0xc22016, 0, 64 * 1024, 64, SECT_4K) }, + { "mx25l3255e", INFO(0xc29e16, 0, 64 * 1024, 64, SECT_4K) }, + { "mx25l6405d", INFO(0xc22017, 0, 64 * 1024, 128, SECT_4K) }, + { "mx25u2033e", INFO(0xc22532, 0, 64 * 1024, 4, SECT_4K) }, + { "mx25u3235f", INFO(0xc22536, 0, 64 * 1024, 64, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ) }, + { "mx25u4035", INFO(0xc22533, 0, 64 * 1024, 8, SECT_4K) }, + { "mx25u8035", INFO(0xc22534, 0, 64 * 1024, 16, SECT_4K) }, + { "mx25u6435f", INFO(0xc22537, 0, 64 * 1024, 128, SECT_4K) }, + { "mx25l12805d", INFO(0xc22018, 0, 64 * 1024, 256, SECT_4K) }, + { "mx25l12855e", INFO(0xc22618, 0, 64 * 1024, 256, 0) }, + { "mx25r1635f", INFO(0xc22815, 0, 64 * 1024, 32, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ) }, + { "mx25r3235f", INFO(0xc22816, 0, 64 * 1024, 64, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ) }, + { "mx25u12835f", INFO(0xc22538, 0, 64 * 1024, 256, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ) }, + { "mx25l25635e", INFO(0xc22019, 0, 64 * 1024, 512, + SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ) + .fixups = &mx25l25635_fixups }, + { "mx25u25635f", INFO(0xc22539, 0, 64 * 1024, 512, + SECT_4K | SPI_NOR_4B_OPCODES) }, + { "mx25u51245g", INFO(0xc2253a, 0, 64 * 1024, 1024, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) }, + { "mx25v8035f", INFO(0xc22314, 0, 64 * 1024, 16, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ) }, + { "mx25l25655e", INFO(0xc22619, 0, 64 * 1024, 512, 0) }, + { "mx66l51235l", INFO(0xc2201a, 0, 64 * 1024, 1024, + SPI_NOR_DUAL_READ | SPI_NOR_QUAD_READ | + SPI_NOR_4B_OPCODES) }, + { "mx66u51235f", INFO(0xc2253a, 0, 64 * 1024, 1024, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) }, + { "mx66l1g45g", INFO(0xc2201b, 0, 64 * 1024, 2048, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ) }, + { "mx66l1g55g", INFO(0xc2261b, 0, 64 * 1024, 2048, + SPI_NOR_QUAD_READ) }, + { "mx66u2g45g", INFO(0xc2253c, 0, 64 * 1024, 4096, + SECT_4K | SPI_NOR_DUAL_READ | + SPI_NOR_QUAD_READ | SPI_NOR_4B_OPCODES) }, +}; + +static void macronix_default_init(struct spi_nor *nor) +{ + nor->params->quad_enable = spi_nor_sr1_bit6_quad_enable; + nor->params->set_4byte_addr_mode = spi_nor_set_4byte_addr_mode; +} + +static const struct spi_nor_fixups macronix_fixups = { + .default_init = macronix_default_init, +}; + +const struct spi_nor_manufacturer spi_nor_macronix = { + .name = "macronix", + .parts = macronix_parts, + .nparts = ARRAY_SIZE(macronix_parts), + .fixups = ¯onix_fixups, +}; diff --git a/pool/shard006/C/0117111_boo.c b/pool/shard006/C/0117111_boo.c new file mode 100644 index 0000000000000000000000000000000000000000..1f8eb7a00e361019d3c03b5717eeb5cd93bddbb4 --- /dev/null +++ b/pool/shard006/C/0117111_boo.c @@ -0,0 +1,45 @@ +// https://c-programming-blog.blogspot.com/2015/05/pcre2-simple-sample-program.html + +#include +#include + +int main(int argc, char *argv[]) { + if(argc < 3) { + printf("usage: %s pattern string\n", argv[0]); + return 0; + } + pcre2_code *re; + pcre2_match_data *match_data; + // size_t erroffset; + // size_t *ovector; + PCRE2_SIZE erroffset, *ovector; + int errorcode; + int rc; + PCRE2_SPTR pattern = argv[1]; + PCRE2_SPTR value = argv[2]; + re = pcre2_compile(pattern, -1, 0, &errorcode, &erroffset, NULL); + if (re == NULL) { + PCRE2_UCHAR8 buffer[120]; + (void)pcre2_get_error_message(errorcode, buffer, 120); + /* Handle error */ + return 0; + } + match_data = pcre2_match_data_create(20, NULL); + rc = pcre2_match(re, value, -1, 0, 0, match_data, NULL); + if (rc <= 0) + printf("No matchx\n"); + else { + ovector = pcre2_get_ovector_pointer(match_data); + printf( "Match succeeded at offset %zu\n", ovector[0] ); + /* Use ovector to get matched strings */ + PCRE2_SIZE i; + for(i = 0; i < rc; i++) { + PCRE2_SPTR start = value + ovector[2*i]; + PCRE2_SIZE slen = ovector[2*i+1] - ovector[2*i]; + printf( "%2d: %.*s\n", i, (int)slen, (char *)start ); + break; + } + } + pcre2_match_data_free(match_data); + pcre2_code_free(re); +} diff --git a/pool/shard006/C/0117113_stm32f4xx_rng.c b/pool/shard006/C/0117113_stm32f4xx_rng.c new file mode 100644 index 0000000000000000000000000000000000000000..9f0ba059f81da5bbb266713702c7e761a0303d1a --- /dev/null +++ b/pool/shard006/C/0117113_stm32f4xx_rng.c @@ -0,0 +1,399 @@ +/** + ****************************************************************************** + * @file stm32f4xx_rng.c + * @author MCD Application Team + * @version V1.0.0 + * @date 30-September-2011 + * @brief This file provides firmware functions to manage the following + * functionalities of the Random Number Generator (RNG) peripheral: + * - Initialization and Configuration + * - Get 32 bit Random number + * - Interrupts and flags management + * + * @verbatim + * + * =================================================================== + * How to use this driver + * =================================================================== + * 1. Enable The RNG controller clock using + * RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE) function. + * + * 2. Activate the RNG peripheral using RNG_Cmd() function. + * + * 3. Wait until the 32 bit Random number Generator contains a valid + * random data (using polling/interrupt mode). For more details, + * refer to "Interrupts and flags management functions" module + * description. + * + * 4. Get the 32 bit Random number using RNG_GetRandomNumber() function + * + * 5. To get another 32 bit Random number, go to step 3. + * + * + * + * @endverbatim + * + ****************************************************************************** + * @attention + * + * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS + * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE + * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY + * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING + * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE + * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. + * + *

© COPYRIGHT 2011 STMicroelectronics

+ ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f4xx_rng.h" +#include "stm32f4xx_rcc.h" + +/** @addtogroup STM32F4xx_StdPeriph_Driver + * @{ + */ + +/** @defgroup RNG + * @brief RNG driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RNG_Private_Functions + * @{ + */ + +/** @defgroup RNG_Group1 Initialization and Configuration functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + Initialization and Configuration functions + =============================================================================== + This section provides functions allowing to + - Initialize the RNG peripheral + - Enable or disable the RNG peripheral + +@endverbatim + * @{ + */ + +/** + * @brief Deinitializes the RNG peripheral registers to their default reset values. + * @param None + * @retval None + */ +void RNG_DeInit(void) +{ + /* Enable RNG reset state */ + RCC_AHB2PeriphResetCmd(RCC_AHB2Periph_RNG, ENABLE); + + /* Release RNG from reset state */ + RCC_AHB2PeriphResetCmd(RCC_AHB2Periph_RNG, DISABLE); +} + +/** + * @brief Enables or disables the RNG peripheral. + * @param NewState: new state of the RNG peripheral. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +void RNG_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the RNG */ + RNG->CR |= RNG_CR_RNGEN; + } + else + { + /* Disable the RNG */ + RNG->CR &= ~RNG_CR_RNGEN; + } +} +/** + * @} + */ + +/** @defgroup RNG_Group2 Get 32 bit Random number function + * @brief Get 32 bit Random number function + * + +@verbatim + =============================================================================== + Get 32 bit Random number function + =============================================================================== + This section provides a function allowing to get the 32 bit Random number + + @note Before to call this function you have to wait till DRDY flag is set, + using RNG_GetFlagStatus(RNG_FLAG_DRDY) function. + +@endverbatim + * @{ + */ + + +/** + * @brief Returns a 32-bit random number. + * + * @note Before to call this function you have to wait till DRDY (data ready) + * flag is set, using RNG_GetFlagStatus(RNG_FLAG_DRDY) function. + * @note Each time the the Random number data is read (using RNG_GetRandomNumber() + * function), the RNG_FLAG_DRDY flag is automatically cleared. + * @note In the case of a seed error, the generation of random numbers is + * interrupted for as long as the SECS bit is '1'. If a number is + * available in the RNG_DR register, it must not be used because it may + * not have enough entropy. In this case, it is recommended to clear the + * SEIS bit(using RNG_ClearFlag(RNG_FLAG_SECS) function), then disable + * and enable the RNG peripheral (using RNG_Cmd() function) to + * reinitialize and restart the RNG. + * @note In the case of a clock error, the RNG is no more able to generate + * random numbers because the PLL48CLK clock is not correct. User have + * to check that the clock controller is correctly configured to provide + * the RNG clock and clear the CEIS bit (using RNG_ClearFlag(RNG_FLAG_CECS) + * function) . The clock error has no impact on the previously generated + * random numbers, and the RNG_DR register contents can be used. + * + * @param None + * @retval 32-bit random number. + */ +uint32_t RNG_GetRandomNumber(void) +{ + /* Return the 32 bit random number from the DR register */ + return RNG->DR; +} + + +/** + * @} + */ + +/** @defgroup RNG_Group3 Interrupts and flags management functions + * @brief Interrupts and flags management functions + * +@verbatim + =============================================================================== + Interrupts and flags management functions + =============================================================================== + + This section provides functions allowing to configure the RNG Interrupts and + to get the status and clear flags and Interrupts pending bits. + + The RNG provides 3 Interrupts sources and 3 Flags: + + Flags : + ---------- + 1. RNG_FLAG_DRDY : In the case of the RNG_DR register contains valid + random data. it is cleared by reading the valid data + (using RNG_GetRandomNumber() function). + + 2. RNG_FLAG_CECS : In the case of a seed error detection. + + 3. RNG_FLAG_SECS : In the case of a clock error detection. + + + Interrupts : + ------------ + if enabled, an RNG interrupt is pending : + + 1. In the case of the RNG_DR register contains valid random data. + This interrupt source is cleared once the RNG_DR register has been read + (using RNG_GetRandomNumber() function) until a new valid value is + computed. + + or + 2. In the case of a seed error : One of the following faulty sequences has + been detected: + - More than 64 consecutive bits at the same value (0 or 1) + - More than 32 consecutive alternance of 0 and 1 (0101010101...01) + This interrupt source is cleared using RNG_ClearITPendingBit(RNG_IT_SEI) + function. + + or + 3. In the case of a clock error : the PLL48CLK (RNG peripheral clock source) + was not correctly detected (fPLL48CLK< fHCLK/16). + This interrupt source is cleared using RNG_ClearITPendingBit(RNG_IT_CEI) + function. + @note In this case, User have to check that the clock controller is + correctly configured to provide the RNG clock. + + Managing the RNG controller events : + ------------------------------------ + The user should identify which mode will be used in his application to manage + the RNG controller events: Polling mode or Interrupt mode. + + 1. In the Polling Mode it is advised to use the following functions: + - RNG_GetFlagStatus() : to check if flags events occur. + - RNG_ClearFlag() : to clear the flags events. + + @note RNG_FLAG_DRDY can not be cleared by RNG_ClearFlag(). it is cleared only + by reading the Random number data. + + 2. In the Interrupt Mode it is advised to use the following functions: + - RNG_ITConfig() : to enable or disable the interrupt source. + - RNG_GetITStatus() : to check if Interrupt occurs. + - RNG_ClearITPendingBit() : to clear the Interrupt pending Bit + (corresponding Flag). + + +@endverbatim + * @{ + */ + +/** + * @brief Enables or disables the RNG interrupt. + * @note The RNG provides 3 interrupt sources, + * - Computed data is ready event (DRDY), and + * - Seed error Interrupt (SEI) and + * - Clock error Interrupt (CEI), + * all these interrupts sources are enabled by setting the IE bit in + * CR register. However, each interrupt have its specific status bit + * (see RNG_GetITStatus() function) and clear bit except the DRDY event + * (see RNG_ClearITPendingBit() function). + * @param NewState: new state of the RNG interrupt. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +void RNG_ITConfig(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the RNG interrupt */ + RNG->CR |= RNG_CR_IE; + } + else + { + /* Disable the RNG interrupt */ + RNG->CR &= ~RNG_CR_IE; + } +} + +/** + * @brief Checks whether the specified RNG flag is set or not. + * @param RNG_FLAG: specifies the RNG flag to check. + * This parameter can be one of the following values: + * @arg RNG_FLAG_DRDY: Data Ready flag. + * @arg RNG_FLAG_CECS: Clock Error Current flag. + * @arg RNG_FLAG_SECS: Seed Error Current flag. + * @retval The new state of RNG_FLAG (SET or RESET). + */ +FlagStatus RNG_GetFlagStatus(uint8_t RNG_FLAG) +{ + FlagStatus bitstatus = RESET; + /* Check the parameters */ + assert_param(IS_RNG_GET_FLAG(RNG_FLAG)); + + /* Check the status of the specified RNG flag */ + if ((RNG->SR & RNG_FLAG) != (uint8_t)RESET) + { + /* RNG_FLAG is set */ + bitstatus = SET; + } + else + { + /* RNG_FLAG is reset */ + bitstatus = RESET; + } + /* Return the RNG_FLAG status */ + return bitstatus; +} + + +/** + * @brief Clears the RNG flags. + * @param RNG_FLAG: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg RNG_FLAG_CECS: Clock Error Current flag. + * @arg RNG_FLAG_SECS: Seed Error Current flag. + * @note RNG_FLAG_DRDY can not be cleared by RNG_ClearFlag() function. + * This flag is cleared only by reading the Random number data (using + * RNG_GetRandomNumber() function). + * @retval None + */ +void RNG_ClearFlag(uint8_t RNG_FLAG) +{ + /* Check the parameters */ + assert_param(IS_RNG_CLEAR_FLAG(RNG_FLAG)); + /* Clear the selected RNG flags */ + RNG->SR = ~(uint32_t)(((uint32_t)RNG_FLAG) << 4); +} + +/** + * @brief Checks whether the specified RNG interrupt has occurred or not. + * @param RNG_IT: specifies the RNG interrupt source to check. + * This parameter can be one of the following values: + * @arg RNG_IT_CEI: Clock Error Interrupt. + * @arg RNG_IT_SEI: Seed Error Interrupt. + * @retval The new state of RNG_IT (SET or RESET). + */ +ITStatus RNG_GetITStatus(uint8_t RNG_IT) +{ + ITStatus bitstatus = RESET; + /* Check the parameters */ + assert_param(IS_RNG_GET_IT(RNG_IT)); + + /* Check the status of the specified RNG interrupt */ + if ((RNG->SR & RNG_IT) != (uint8_t)RESET) + { + /* RNG_IT is set */ + bitstatus = SET; + } + else + { + /* RNG_IT is reset */ + bitstatus = RESET; + } + /* Return the RNG_IT status */ + return bitstatus; +} + + +/** + * @brief Clears the RNG interrupt pending bit(s). + * @param RNG_IT: specifies the RNG interrupt pending bit(s) to clear. + * This parameter can be any combination of the following values: + * @arg RNG_IT_CEI: Clock Error Interrupt. + * @arg RNG_IT_SEI: Seed Error Interrupt. + * @retval None + */ +void RNG_ClearITPendingBit(uint8_t RNG_IT) +{ + /* Check the parameters */ + assert_param(IS_RNG_IT(RNG_IT)); + + /* Clear the selected RNG interrupt pending bit */ + RNG->SR = (uint8_t)~RNG_IT; +} +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + + +/** + * @} + */ + + +/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0117118_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52a.c b/pool/shard006/C/0117118_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52a.c new file mode 100644 index 0000000000000000000000000000000000000000..ccc6cefcbb649d25d90307f9b71b6ee32d6f185f --- /dev/null +++ b/pool/shard006/C/0117118_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52a.c @@ -0,0 +1,94 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52a.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml +Template File: sources-sink-52a.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: snprintf + * BadSink : Copy string to data using snprintf + * 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" + +#include + +#ifdef _WIN32 +#define SNPRINTF _snwprintf +#else +#define SNPRINTF snprintf +#endif + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52b_badSink(wchar_t * data); + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52_bad() +{ + wchar_t * data; + data = NULL; + /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = (wchar_t *)malloc(50*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + data[0] = L'\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52b_goodG2BSink(wchar_t * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + data = NULL; + /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + data[0] = L'\0'; /* null terminate */ + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52b_goodG2BSink(data); +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_snprintf_52_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0117122_dht22.c b/pool/shard006/C/0117122_dht22.c new file mode 100644 index 0000000000000000000000000000000000000000..3bd9de625514d357305478b23fde8f084992078a --- /dev/null +++ b/pool/shard006/C/0117122_dht22.c @@ -0,0 +1,210 @@ +/* + * ---------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * Jeroen Domburg 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. + * ---------------------------------------------------------------------------- + */ + +#include "ets_sys.h" +#include "osapi.h" +#include "espmissingincludes.h" +#include "c_types.h" +#include "user_interface.h" +#include "espconn.h" +#include "mem.h" +#include "gpio.h" +#include "dht.h" + +#define MAXTIMINGS 10000 +#define DHT_MAXCOUNT 32000 +#define BREAKTIME 32 + +#define DHT_PIN 2 + +enum sensor_type SENSOR; + +static inline float scale_humidity(int *data) { + if (SENSOR == SENSOR_DHT11) { + return data[0]; + } else { + float humidity = data[0] * 256 + data[1]; + return humidity /= 10; + } +} + +static inline float scale_temperature(int *data) { + if (SENSOR == SENSOR_DHT11) { + return data[2]; + } else { + float temperature = data[2] & 0x7f; + temperature *= 256; + temperature += data[3]; + temperature /= 10; + if (data[2] & 0x80) + temperature *= -1; + return temperature; + } +} + +static inline void delay_ms(int sleep) { + os_delay_us(1000 * sleep); +} + +static struct sensor_reading reading = { + .source = "DHT11", .success = 0 +}; + + + + +/** +Originally from: http://harizanov.com/2014/11/esp8266-powered-web-server-led-control-dht22-temperaturehumidity-sensor-reading/ +Adapted from: https://github.com/adafruit/Adafruit_Python_DHT/blob/master/source/Raspberry_Pi/pi_dht_read.c +LICENSE: +// Copyright (c) 2014 Adafruit Industries +// Author: Tony DiCola +// 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. +*/ +static void ICACHE_FLASH_ATTR pollDHTCb(void * arg){ + int counter = 0; + int laststate = 1; + int i = 0; + int bits_in = 0; + // int bitidx = 0; + // int bits[250]; + + int data[100]; + + data[0] = data[1] = data[2] = data[3] = data[4] = 0; + + //disable interrupts, start of critical section + os_intr_lock(); + wdt_feed(); + // Wake up device, 250ms of high + GPIO_OUTPUT_SET(DHT_PIN, 1); + delay_ms(20); + + // Hold low for 20ms + GPIO_OUTPUT_SET(DHT_PIN, 0); + delay_ms(20); + + // High for 40ms + // GPIO_OUTPUT_SET(2, 1); + + GPIO_DIS_OUTPUT(DHT_PIN); + os_delay_us(40); + + // Set pin to input with pullup + // PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U); + + // os_printf("Waiting for gpio2 to drop \n"); + + // wait for pin to drop? + while (GPIO_INPUT_GET(DHT_PIN) == 1 && i < DHT_MAXCOUNT) { + if (i >= DHT_MAXCOUNT) { + goto fail; + } + i++; + } + +// os_printf("Reading DHT\n"); + + // read data! + for (i = 0; i < MAXTIMINGS; i++) { + // Count high time (in approx us) + counter = 0; + while (GPIO_INPUT_GET(DHT_PIN) == laststate) { + counter++; + os_delay_us(1); + if (counter == 1000) + break; + } + laststate = GPIO_INPUT_GET(DHT_PIN); + + if (counter == 1000) + break; + + // store data after 3 reads + if ((i > 3) && (i % 2 == 0)) { + // shove each bit into the storage bytes + data[bits_in / 8] <<= 1; + if (counter > BREAKTIME) { + //os_printf("1"); + data[bits_in / 8] |= 1; + } else { + //os_printf("0"); + } + bits_in++; + } + } + + //Re-enable interrupts, end of critical section + os_intr_unlock(); + + if (bits_in < 40) { + os_printf("Got too few bits: %d should be at least 40", bits_in); + goto fail; + } + + + int checksum = (data[0] + data[1] + data[2] + data[3]) & 0xFF; + + os_printf("DHT: %02x %02x %02x %02x [%02x] CS: %02x\n", data[0], data[1],data[2],data[3],data[4],checksum); + + if (data[4] != checksum) { + os_printf("Checksum was incorrect after %d bits. Expected %d but got %d", + bits_in, data[4], checksum); + goto fail; + } + + reading.temperature = scale_temperature(data); + reading.humidity = scale_humidity(data); + os_printf("Temp = %d *C, Hum = %d %%\n", (int)(reading.temperature), + (int)(reading.humidity)); + + reading.success = 1; + return; +fail: + + os_printf("Failed to get reading, dying\n"); + reading.success = 0; +} + +struct sensor_reading *ICACHE_FLASH_ATTR readDHT(int force) { + if(force){ + pollDHTCb(NULL); + } + return &reading; +} + +void ICACHE_FLASH_ATTR DHTInit(enum sensor_type sensor_type, uint32_t polltime) { + SENSOR = sensor_type; + // Set GPIO2 to output mode for DHT22 + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0); + //PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U); + + os_printf("DHT Setup for type %d, poll interval of %d\n", sensor_type, (int)polltime); + + static ETSTimer dhtTimer; + os_timer_setfn(&dhtTimer, pollDHTCb, NULL); + os_timer_arm(&dhtTimer, polltime, 1); +} diff --git a/pool/shard006/C/0117136_pthread_exit.c b/pool/shard006/C/0117136_pthread_exit.c new file mode 100644 index 0000000000000000000000000000000000000000..222bfbae3b3c1863125f761976335e6d840ddf85 --- /dev/null +++ b/pool/shard006/C/0117136_pthread_exit.c @@ -0,0 +1,34 @@ + +#include +#include +#include + + +void *func1(void *arg) +{ + int i = 0; + static char buf[] = "hello"; + for (i = 0;i < 5;i++) + { + printf("in func1\n"); + sleep(1); + if (i == 3) + { + pthread_exit((void *)buf); + } + } +} + +int main(int argc, char *argv[]) +{ + int *save = NULL; + pthread_t tid; + + pthread_create(&tid,NULL,func1,NULL); + + + pthread_join(tid,((void*)&save)); + + printf("%s\n",((char *)save)); + return 0; +} diff --git a/pool/shard006/C/0117143_pr67790.c b/pool/shard006/C/0117143_pr67790.c new file mode 100644 index 0000000000000000000000000000000000000000..32eacd91fdaa209dc04efe934798e524ac5fea8d --- /dev/null +++ b/pool/shard006/C/0117143_pr67790.c @@ -0,0 +1,41 @@ +/* { dg-require-effective-target vect_int } */ + +#include "tree-vect.h" + +struct { + int x_advance; + int y_advance; +} a[256]; + +int b, c; + +void __attribute__((noinline,noclone)) fn1() +{ + for (int i = 0; i < 256; i++) + { + c -= a[i].x_advance; + b -= a[i].y_advance; + } +} + +int main() +{ + check_vect (); + + for (int i = 0; i < 256; ++i) + { + a[i].x_advance = i; + a[i].y_advance = -i + 3; + __asm__ volatile ("" : : : "memory"); + } + + fn1(); + + if (c != -32640 || b != 31872) + abort (); + + return 0; +} + +/* { dg-final { scan-tree-dump "vectorizing stmts using SLP" "vect" } } */ +/* { dg-final { scan-tree-dump-times "VEC_PERM_EXPR" 0 "vect" } } */ diff --git a/pool/shard006/C/0117153_mkdepend.c b/pool/shard006/C/0117153_mkdepend.c new file mode 100644 index 0000000000000000000000000000000000000000..233f2ae6ff58715380ff2a172ff75311da5389b8 --- /dev/null +++ b/pool/shard006/C/0117153_mkdepend.c @@ -0,0 +1,122 @@ +#include +#include +#include +#include + +#define ObjExtension ".o" + +static char *getobj(const char *pSrc) +{ + static char buffer[255]; + int l = strlen(pSrc); + char *pSearch; + + if (l < sizeof(buffer) - 5) + l = sizeof(buffer) - 5; + memcpy(buffer, pSrc, l); buffer[l] = '\0'; + + pSearch = strrchr(buffer, '.'); + if (pSearch) + strcpy(pSearch, ObjExtension); + + return buffer; +} + +int main(int argc, char **argv) +{ + int z, l; + FILE *pFile, *pDestFile; + char line[512], *pCmd, *pName, *pDestFileName = NULL; + char used[1024]; + + if (argc < 2) + { + fprintf(stderr, "usage: %s [args] \n", *argv); + exit(1); + } + + memset(used, 0, sizeof(used)); + + for (z = 1; z < argc; z++) + if ((!used[z]) && (*argv[z] == '-')) + { + used[z] = 1; + if (!strcmp(argv[z] + 1, "o")) + { + if (z >= argc - 1) + pDestFileName = NULL; + else + { + pDestFileName = argv[z + 1]; + used[z + 1] = 1; + } + } + } + + if (pDestFileName) + { + pDestFile = fopen(pDestFileName, "w"); + if (!pDestFile) + { + perror(pDestFileName); + exit(errno); + } + } + else + pDestFile = stdout; + + fprintf(pDestFile, "# auto-generated by %s - do not edit\n\n", *argv); + + for (z = 1; z < argc; z++) + { + if (used[z]) + continue; + + fprintf(pDestFile, "%s:", getobj(argv[z])); + + pFile = fopen(argv[z], "r"); + if (!pFile) + { + perror(argv[z]); + exit(errno); + } + + while (!feof(pFile)) + { + fgets(line, sizeof(line), pFile); + l = strlen(line); + if ((l > 0) && (line[l - 1] == '\n')) + line[l - 1] = '\0'; + + if (*line != '#') + continue; + pCmd = strtok(line + 1, " \t"); + if (strcmp(pCmd, "include")) + continue; + + pName = strtok(NULL, " \t"); + if (!pName) + continue; + l = strlen(pName); + if ((*pName != '"') || (pName[l - 1] != '"')) + continue; + + fprintf(pDestFile, " %*.*s", l - 2, l - 2, pName + 1); + } + + fclose(pFile); + + fprintf(pDestFile, "\n\n"); + } + + if (pDestFileName) + { + fprintf(pDestFile, "%s:", pDestFileName); + for (z = 1; z < argc; z++) + if (!used[z]) + fprintf(pDestFile, " %s", argv[z]); + fprintf(pDestFile, "\n"); + } + + return 0; +} diff --git a/pool/shard006/C/0117158_gl_hwdec_vdpau.c b/pool/shard006/C/0117158_gl_hwdec_vdpau.c new file mode 100644 index 0000000000000000000000000000000000000000..bb502ade11d9432ba36ca76e2ccec617ed418443 --- /dev/null +++ b/pool/shard006/C/0117158_gl_hwdec_vdpau.c @@ -0,0 +1,209 @@ +/* + * This file is part of mpv. + * + * mpv 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. + * + * mpv 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 mpv. If not, see . + */ + +#include +#include + +#include + +#include "gl_hwdec.h" +#include "gl_utils.h" +#include "video/vdpau.h" +#include "video/vdpau_mixer.h" + +// This is a GL_NV_vdpau_interop specification bug, and headers (unfortunately) +// follow it. I'm not sure about the original nvidia headers. +#define BRAINDEATH(x) ((void *)(uintptr_t)(x)) + +static int reinit(struct gl_hwdec *hw, struct mp_image_params *params); + +struct priv { + struct mp_log *log; + struct mp_vdpau_ctx *ctx; + uint64_t preemption_counter; + struct mp_image_params image_params; + GLuint gl_texture; + GLvdpauSurfaceNV vdpgl_surface; + VdpOutputSurface vdp_surface; + struct mp_vdpau_mixer *mixer; + bool mapped; +}; + +static void mark_vdpau_objects_uninitialized(struct gl_hwdec *hw) +{ + struct priv *p = hw->priv; + + p->vdp_surface = VDP_INVALID_HANDLE; + p->mixer->video_mixer = VDP_INVALID_HANDLE; + p->mapped = false; +} + +static void destroy_objects(struct gl_hwdec *hw) +{ + struct priv *p = hw->priv; + GL *gl = hw->gl; + struct vdp_functions *vdp = &p->ctx->vdp; + VdpStatus vdp_st; + + if (p->mapped) + gl->VDPAUUnmapSurfacesNV(1, &p->vdpgl_surface); + p->mapped = false; + + if (p->vdpgl_surface) + gl->VDPAUUnregisterSurfaceNV(p->vdpgl_surface); + p->vdpgl_surface = 0; + + glDeleteTextures(1, &p->gl_texture); + p->gl_texture = 0; + + if (p->vdp_surface != VDP_INVALID_HANDLE) { + vdp_st = vdp->output_surface_destroy(p->vdp_surface); + CHECK_VDP_WARNING(p, "Error when calling vdp_output_surface_destroy"); + } + p->vdp_surface = VDP_INVALID_HANDLE; + + glCheckError(gl, hw->log, "Before uninitializing OpenGL interop"); + + gl->VDPAUFiniNV(); + + // If the GL/vdpau state is not initialized, above calls raises an error. + while (1) { + if (gl->GetError() == GL_NO_ERROR) + break; + } +} + +static void destroy(struct gl_hwdec *hw) +{ + struct priv *p = hw->priv; + + destroy_objects(hw); + mp_vdpau_mixer_destroy(p->mixer); + mp_vdpau_destroy(p->ctx); +} + +static int create(struct gl_hwdec *hw) +{ + GL *gl = hw->gl; + if (hw->hwctx) + return -1; + Display *x11disp = glXGetCurrentDisplay(); + if (!x11disp) + return -1; + if (!(gl->mpgl_caps & MPGL_CAP_VDPAU)) + return -1; + struct priv *p = talloc_zero(hw, struct priv); + hw->priv = p; + p->log = hw->log; + p->ctx = mp_vdpau_create_device_x11(hw->log, x11disp); + if (!p->ctx) + return -1; + if (mp_vdpau_handle_preemption(p->ctx, &p->preemption_counter) < 1) + return -1; + p->vdp_surface = VDP_INVALID_HANDLE; + p->mixer = mp_vdpau_mixer_create(p->ctx, hw->log); + if (hw->reject_emulated && mp_vdpau_guess_if_emulated(p->ctx)) { + destroy(hw); + return -1; + } + hw->hwctx = &p->ctx->hwctx; + hw->converted_imgfmt = IMGFMT_RGB0; + return 0; +} + +static int reinit(struct gl_hwdec *hw, struct mp_image_params *params) +{ + struct priv *p = hw->priv; + GL *gl = hw->gl; + struct vdp_functions *vdp = &p->ctx->vdp; + VdpStatus vdp_st; + + destroy_objects(hw); + + params->imgfmt = hw->driver->imgfmt; + p->image_params = *params; + + if (mp_vdpau_handle_preemption(p->ctx, &p->preemption_counter) < 1) + return -1; + + gl->VDPAUInitNV(BRAINDEATH(p->ctx->vdp_device), p->ctx->get_proc_address); + + vdp_st = vdp->output_surface_create(p->ctx->vdp_device, + VDP_RGBA_FORMAT_B8G8R8A8, + params->w, params->h, &p->vdp_surface); + CHECK_VDP_ERROR(p, "Error when calling vdp_output_surface_create"); + + gl->GenTextures(1, &p->gl_texture); + gl->BindTexture(GL_TEXTURE_2D, p->gl_texture); + gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + gl->BindTexture(GL_TEXTURE_2D, 0); + + p->vdpgl_surface = gl->VDPAURegisterOutputSurfaceNV(BRAINDEATH(p->vdp_surface), + GL_TEXTURE_2D, + 1, &p->gl_texture); + if (!p->vdpgl_surface) + return -1; + + gl->VDPAUSurfaceAccessNV(p->vdpgl_surface, GL_READ_ONLY); + + glCheckError(gl, hw->log, "After initializing vdpau OpenGL interop"); + + return 0; +} + +static int map_image(struct gl_hwdec *hw, struct mp_image *hw_image, + GLuint *out_textures) +{ + struct priv *p = hw->priv; + GL *gl = hw->gl; + + assert(hw_image && hw_image->imgfmt == IMGFMT_VDPAU); + + int pe = mp_vdpau_handle_preemption(p->ctx, &p->preemption_counter); + if (pe < 1) { + mark_vdpau_objects_uninitialized(hw); + if (pe < 0) + return -1; + if (reinit(hw, &p->image_params) < 0) + return -1; + } + + if (!p->vdpgl_surface) + return -1; + + if (p->mapped) + gl->VDPAUUnmapSurfacesNV(1, &p->vdpgl_surface); + + mp_vdpau_mixer_render(p->mixer, NULL, p->vdp_surface, NULL, hw_image, NULL); + + gl->VDPAUMapSurfacesNV(1, &p->vdpgl_surface); + p->mapped = true; + out_textures[0] = p->gl_texture; + return 0; +} + +const struct gl_hwdec_driver gl_hwdec_vdpau = { + .api_name = "vdpau", + .imgfmt = IMGFMT_VDPAU, + .create = create, + .reinit = reinit, + .map_image = map_image, + .destroy = destroy, +}; diff --git a/pool/shard006/C/0117160_sendcommit-proc.c b/pool/shard006/C/0117160_sendcommit-proc.c new file mode 100644 index 0000000000000000000000000000000000000000..31c3d6f4e4ddedb876818fd802abaa68e2b1a843 --- /dev/null +++ b/pool/shard006/C/0117160_sendcommit-proc.c @@ -0,0 +1,262 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * + * 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 "common.h" + +#include +#include +#include +#include +#include +#include + +#include +#include "net.h" +#include "utils.h" + +#include "seafile-session.h" +#include "commit-mgr.h" +#include "sendcommit-proc.h" +#include "processors/objecttx-common.h" + +/* + seafile-recvcommit + INIT ---------------------> + 200 OK + INIT <--------------------- + + Object IDs + SEND_OBJ ----------------------> + End + SEND_OBJ ----------------------> + + Get Object + SEND_OBJ <----------------------- + Object + SEND_OBJ -----------------------> + + ... + + End + <----------------------- + */ + +enum { + INIT, + SEND_OBJECT +}; + +static int send_commit_start (CcnetProcessor *processor, int argc, char **argv); +static void handle_response (CcnetProcessor *processor, + char *code, char *code_msg, + char *content, int clen); + + +G_DEFINE_TYPE (SeafileSendcommitProc, seafile_sendcommit_proc, CCNET_TYPE_PROCESSOR) + +static void +seafile_sendcommit_proc_class_init (SeafileSendcommitProcClass *klass) +{ + CcnetProcessorClass *proc_class = CCNET_PROCESSOR_CLASS (klass); + + proc_class->name = "sendcommit-proc"; + proc_class->start = send_commit_start; + proc_class->handle_response = handle_response; +} + +static void +seafile_sendcommit_proc_init (SeafileSendcommitProc *processor) +{ +} + +static gboolean +commit_collector (SeafCommit *commit, void *data, gboolean *stop) +{ + ObjectList *ol = data; + + object_list_insert (ol, commit->commit_id); + + return TRUE; +} + +static int +send_commit_start (CcnetProcessor *processor, int argc, char **argv) +{ + GString *buf; + int ret; + TransferTask *task = ((SeafileSendcommitProc *)processor)->tx_task; + + ObjectList *ol = object_list_new (); + ret = seaf_commit_manager_traverse_commit_tree (seaf->commit_mgr, + task->head, + commit_collector, + ol, FALSE); + if (ret == FALSE) { + object_list_free (ol); + g_warning ("[sendcommit] Load commits error\n"); + ccnet_processor_done (processor, FALSE); + return -1; + } + g_assert (object_list_length(ol) != 0); + task->commits = ol; + + /* Send to_branch to the relay. */ + buf = g_string_new (NULL); + g_string_printf (buf, "remote %s seafile-recvcommit %s %s", + processor->peer_id, task->to_branch, task->session_token); + ccnet_processor_send_request (processor, buf->str); + g_string_free (buf, TRUE); + + processor->state = INIT; + + return 0; +} + +static gboolean +send_commit (CcnetProcessor *processor, char *object_id) +{ + char *data; + int len; + ObjectPack *pack = NULL; + int pack_size; + + if (seaf_obj_store_read_obj (seaf->commit_mgr->obj_store, + object_id, (void**)&data, &len) < 0) { + g_warning ("Failed to read commit %s.\n", object_id); + goto fail; + } + + pack_size = sizeof(ObjectPack) + len; + pack = malloc (pack_size); + memcpy (pack->id, object_id, 41); + memcpy (pack->object, data, len); + + ccnet_processor_send_update (processor, SC_OBJECT, SS_OBJECT, + (char *)pack, pack_size); + + g_free (data); + free (pack); + return TRUE; + +fail: + ccnet_processor_send_update (processor, SC_NOT_FOUND, SS_NOT_FOUND, + object_id, 41); + ccnet_processor_done (processor, FALSE); + return FALSE; +} + +static void +send_commits (CcnetProcessor *processor, char *content, int clen) +{ + char *object_id; + int n_objects; + int i; + + if (clen % 41 != 1 || content[clen-1] != '\0') { + g_warning ("Bad fs object list.\n"); + ccnet_processor_send_update (processor, SC_BAD_OL, SS_BAD_OL, NULL, 0); + ccnet_processor_done (processor, FALSE); + return; + } + + n_objects = clen/41; + + object_id = content; + for (i = 0; i < n_objects; ++i) { + object_id[40] = '\0'; + if (send_commit (processor, object_id) == FALSE) + return; + object_id += 41; + } +} + +static void +send_commit_ids (CcnetProcessor *processor) +{ + SeafileSendcommitProc *proc = (SeafileSendcommitProc *)processor; + char buf[2048]; + char *ptr = buf; + int i, count = 0; + ObjectList *ol = proc->tx_task->commits; + int ollen = object_list_length (ol); + + for (i = 0; i < ollen; i++) { + memcpy (ptr, g_ptr_array_index(ol->obj_ids, i), 40); + ptr += 40; + *ptr++ = '\n'; + + if (++count == 48) { + *ptr = '\0'; + ccnet_processor_send_update (processor, SC_COMMIT_IDS, + SS_COMMIT_IDS, buf, 41 * count + 1); + ptr = buf; + count = 0; + } + } + + if (count) { + *ptr = '\0'; + ccnet_processor_send_update (processor, SC_COMMIT_IDS, + SS_COMMIT_IDS, buf, 41 * count + 1); + } + + object_list_free (ol); + ccnet_processor_send_update (processor, SC_END, SS_END, NULL, 0); + + processor->state = SEND_OBJECT; +} + +static void handle_response (CcnetProcessor *processor, + char *code, char *code_msg, + char *content, int clen) +{ + SeafileSendcommitProc *proc = (SeafileSendcommitProc *)processor; + TransferTask *task = proc->tx_task; + if (task->state != TASK_STATE_NORMAL) { + /* TODO: not tested yet */ + ccnet_processor_send_update (processor, SC_SHUTDOWN, SS_SHUTDOWN, + NULL, 0); + ccnet_processor_done (processor, TRUE); + return; + } + + switch (processor->state) { + case INIT: + if (memcmp (code, SC_OK, 3) == 0) + send_commit_ids (processor); + else { + g_warning ("Bad response: %s %s.\n", code, code_msg); + ccnet_processor_done (processor, FALSE); + } + break; + case SEND_OBJECT: + if (strncmp(code, SC_GET_OBJECT, 3) == 0) { + send_commits (processor, content, clen); + } else if (strncmp(code, SC_END, 3) == 0) { + ccnet_processor_done (processor, TRUE); + } else { + g_warning ("[sendcommit] Bad response in state SEND_OBJECT: %s %s\n", + code, code_msg); + ccnet_processor_done (processor, FALSE); + } + break; + default: + g_assert (0); + } +} diff --git a/pool/shard006/C/0117164_ged_base.c b/pool/shard006/C/0117164_ged_base.c new file mode 100644 index 0000000000000000000000000000000000000000..1884068391eea085e5a5da9c851a16e39824e047 --- /dev/null +++ b/pool/shard006/C/0117164_ged_base.c @@ -0,0 +1,126 @@ +/* + * (C) Copyright 2010 + * MediaTek + * + * MTK GPU Extension Device + * + */ + +#include "ged_base.h" +#include +#include +#include +#include +#include +#include + +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,38)) +#ifndef AUTOCONF_INCLUDED +#include +#endif +#endif + +#include + +unsigned long ged_copy_to_user(void __user *pvTo, const void *pvFrom, unsigned long ulBytes) +{ +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33)) + if (access_ok(VERIFY_WRITE, pvTo, ulBytes)) + { + return __copy_to_user(pvTo, pvFrom, ulBytes); + } + return ulBytes; +#else + return copy_to_user(pvTo, pvFrom, ulBytes); +#endif +} + +unsigned long ged_copy_from_user(void *pvTo, const void __user *pvFrom, unsigned long ulBytes) +{ +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,33)) + if (access_ok(VERIFY_READ, pvFrom, ulBytes)) + { + return __copy_from_user(pvTo, pvFrom, ulBytes); + } + return ulBytes; +#else + return copy_from_user(pvTo, pvFrom, ulBytes); +#endif +} + +void* ged_alloc(int i32Size) +{ + void *pvBuf; + + if (i32Size <= PAGE_SIZE) + { + pvBuf = kmalloc(i32Size, GFP_KERNEL); + } + else + { + pvBuf = vmalloc(i32Size); + } + + return pvBuf; +} + +void* ged_alloc_atomic(int i32Size) +{ + void *pvBuf; + + if (i32Size <= PAGE_SIZE) + { + pvBuf = kmalloc(i32Size, GFP_ATOMIC); + } + else + { + pvBuf = vmalloc(i32Size); + } + + return pvBuf; +} + +void ged_free(void* pvBuf, int i32Size) +{ + if (pvBuf) + { + if (i32Size <= PAGE_SIZE) + { + kfree(pvBuf); + } + else + { + vfree(pvBuf); + } + } +} + +long ged_get_pid(void) +{ + if (in_interrupt()) + { + return 0xffffffffL; + } + +#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)) + return (long)current->pgrp; +#else +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,24)) + return (long)task_tgid_nr(current); +#else + return (long)current->tgid; +#endif +#endif +} + +unsigned long long ged_get_time() +{ + unsigned long long temp; + + preempt_disable(); + temp = cpu_clock(smp_processor_id()); + preempt_enable(); + + return temp; +} + diff --git a/pool/shard006/C/0117166_empty-Seed4-RandomFuns-Type_int-ControlStructures_12-BB1-ForBound_boundedInput-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c b/pool/shard006/C/0117166_empty-Seed4-RandomFuns-Type_int-ControlStructures_12-BB1-ForBound_boundedInput-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c new file mode 100644 index 0000000000000000000000000000000000000000..47cf1701a3aaa6bb0826637b816f7c800aabcea6 --- /dev/null +++ b/pool/shard006/C/0117166_empty-Seed4-RandomFuns-Type_int-ControlStructures_12-BB1-ForBound_boundedInput-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c @@ -0,0 +1,102 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern void signal(int sig , void *func ) ; +extern float strtof(char const *str , char const *endptr ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) +{ + unsigned int state[1] ; + unsigned int local1 ; + unsigned short copy11 ; + + { + state[0UL] = (input[0UL] + 914778474UL) - 981234615U; + local1 = 0UL; + while (local1 < 0U) { + if (state[0UL] < local1) { + if (state[0UL] != local1) { + copy11 = *((unsigned short *)(& state[local1]) + 0); + *((unsigned short *)(& state[local1]) + 0) = *((unsigned short *)(& state[local1]) + 1); + *((unsigned short *)(& state[local1]) + 1) = copy11; + } + } else { + state[0UL] = state[local1] + state[local1]; + } + local1 ++; + } + output[0UL] = (state[0UL] + 973391845UL) + 40566171U; +} +} +void megaInit(void) +{ + + + { + +} +} +int main(int argc , char *argv[] ) +{ + unsigned int input[1] ; + unsigned int output[1] ; + int randomFuns_i5 ; + unsigned int randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 947514220U) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%u\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} diff --git a/pool/shard006/C/0117167_lab7.c b/pool/shard006/C/0117167_lab7.c new file mode 100644 index 0000000000000000000000000000000000000000..32c708cf2be41033c31e9e6643387a514ab84c82 --- /dev/null +++ b/pool/shard006/C/0117167_lab7.c @@ -0,0 +1,137 @@ +//***************************************** +//Jason Laske +//Daniel Rogers +//CSC 311 +//Due Date: 4/10/2014 +//Submitted: 4/10/2014 +//***************************************** + +#include +#include +#include + +int main(){ + +//***************************************** +//VARIABLE DECLARATION +//***************************************** + +char a; +char b; +char c; +char d; +char e; +char f; + +int k = 0; + +//****************************************** +//1.) PROMPT FOR BASE OF INPUT +//****************************************** +while(k == 0){ + + int i = 0; + + char str[32]; + int bin = 0; + int j = 0; + + printf("Base of input integer: Enter b for binary, d for decimal, h for hexadecimal and o for octal: \n"); + +//Input +//******************* +scanf("%c", &a); +scanf("%c", &d); + + +//Control structure +//******************* +printf("Enter the number: \n"); + +if(a == 'b'){ + scanf("%s", &str); + scanf("%c", &d); + while(str[j] != '\0') + { + bin = bin * 2 + str[j] - '0'; + j++; + } +}else if(a == 'd'){ + scanf("%d", &i); + scanf("%c", &d); +}else if(a == 'h'){ + scanf("%x", &i); + scanf("%c", &d); +}else if(a == 'o'){ + scanf("%o", &i); + scanf("%c", &d); +}else{ + printf("Error1\n"); +} + +//****************************************** +//2.) PROMPT FOR BASE OF OUTPUT / OUTPUT +//****************************************** + +printf("Enter the base of the output(d, h or o): "); + +scanf("%c", &e); +scanf("%c", &d); + +if(a == 'b'){ + printf("The integer %s in binary is ", str); +}else if(a == 'd'){ + printf("The integer %d in decimal is ", i); +}else if(a == 'h'){ + printf("The integer %x in hexadecimal is ", i); +}else if(a == 'o'){ + printf("The integer %o in octal is ", i); +}else{ + printf("Error2\n"); +} + +if(e == 'd'){ + if(a == 'b'){ + printf("%d in decimal.\n", bin); + }else{ + printf("%d in decimal.\n", i); + } +}else if(e == 'h'){ + if(a == 'b'){ + printf("%x in hexadecimal.\n", bin); + }else{ + printf("%x in hexadecimal.\n", i); + } +}else if(e == 'o'){ + if(a == 'b'){ + printf("%o in octal.\n", bin); + }else{ + printf("%o in octal.\n", i); + } +}else{ + printf("Error3\n"); +} + +//******************************************* +//3.) CONTINUE? +//******************************************* + +printf("Do you wish to do another? (Y or N): "); + +scanf("%c", &f); +scanf("%c", &d); + +if(f != 'Y'){ + k = 1; +} + +}//end while + +//******************************************* +//4.)EXIT +//******************************************* + +printf("Thank you, have a nice day.\n\n"); + +return 0; +} diff --git a/pool/shard006/C/0117169_waitqueue.c b/pool/shard006/C/0117169_waitqueue.c new file mode 100644 index 0000000000000000000000000000000000000000..7f045d1947e1bbf0a5b6ab303f11752d998e7a63 --- /dev/null +++ b/pool/shard006/C/0117169_waitqueue.c @@ -0,0 +1,308 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Linhu"); +MODULE_DESCRIPTION("A simple BLOCKING IO example"); + +#define CDEV_MAJOR 0 /* dynamic major by default */ + +static int cdev_major = CDEV_MAJOR; + +static wait_queue_head_t my_wait_queue; + +//static struct work_struct workq; + +static char *ptr_buffer = NULL; + +static struct semaphore sem; + + +static int test_proc_show(struct seq_file *ptr,void * param); +static int test_proc_open(struct inode *inode, struct file *file); +static ssize_t test_proc_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos); +static ssize_t test_proc_write(struct file *file, const char __user *buf, size_t nbytes, loff_t *ppos); + +static int test_open(struct inode *inode, struct file *filp); +static ssize_t test_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos); +static ssize_t test_write(struct file *filp, const char __user *buf, size_t nbytes, loff_t *f_pos); +static int test_release(struct inode *inode, struct file *filp); + + +typedef struct chardev{ + char *pbuf; + struct semaphore sem; + wait_queue_head_t waitq; + struct cdev cdev; +}chardev_t; + +static chardev_t *char_devices; + +static struct file_operations char_ops = { + .owner = THIS_MODULE, + .open = test_open, + .release = test_release, + .read = test_read, + .write = test_write +}; + + +static struct file_operations proc_ops = { + .owner = THIS_MODULE, + .open = test_proc_open, + .read = test_proc_read, + .write = test_proc_write, + .release = single_release +}; + + +static int test_proc_show(struct seq_file *ptr,void * param) +{ + printk(KERN_INFO "test_proc opened.\n"); + return 0; +} + +static int test_proc_open(struct inode *inode, struct file *file) +{ + return single_open(file, test_proc_show, NULL); +} + +static ssize_t test_proc_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) +{ + ssize_t rbytes = 0; + + if(ptr_buffer == NULL) + { + printk(KERN_INFO "Buffer is NULL.\n"); + return EFAULT; + } + + if(strlen(ptr_buffer) == 0) + { + printk(KERN_INFO "Buffer is not available, wait until data is available.\n"); + interruptible_sleep_on(&my_wait_queue); + } + + down_interruptible(&sem); + + rbytes = copy_to_user(buf, ptr_buffer, strlen(ptr_buffer)); + + up(&sem); + + if(rbytes == 0) + { + printk(KERN_ERR "Failed to copy to user.\n"); + return EFAULT; + } + + printk(KERN_INFO "read data: %s\n", ptr_buffer); + + memset(ptr_buffer, 0, strlen(ptr_buffer)); + + return rbytes; +} + + +static ssize_t test_proc_write(struct file *file, const char __user *buf, size_t nbytes, loff_t *ppos) +{ + + down_interruptible(&sem); + + if(copy_from_user(ptr_buffer, buf, nbytes) < 0) + { + printk(KERN_ERR "Failed to copy from user.\n"); + return EFAULT; + } + + up(&sem); + + printk(KERN_ERR "Wake up to read the buffer.\n"); + wake_up_interruptible(&my_wait_queue); + return nbytes; +} + + +static int test_open(struct inode *inode, struct file *filp) +{ + struct chardev *dev; + + dev = container_of(inode->i_cdev, struct chardev, cdev); + + dev->pbuf = kmalloc(1024, GFP_KERNEL); + + if(dev->pbuf == NULL) + { + printk(KERN_ERR "kmalloc failed.\n"); + return ENOMEM; + } + + filp->private_data = dev; + + return 0; +} + +static ssize_t test_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) +{ + ssize_t rbytes = 0; + + struct chardev *dev = filp->private_data; + + if(dev->pbuf == NULL) + { + printk(KERN_INFO "Buffer is NULL.\n"); + return EFAULT; + } + + if(strlen(dev->pbuf) == 0) + { + printk(KERN_INFO "Buffer is not available, wait until data is available.\n"); + interruptible_sleep_on(&dev->waitq); + } + + down_interruptible(&dev->sem); + + rbytes = copy_to_user(buf, dev->pbuf, strlen(dev->pbuf)); + + up(&dev->sem); + + if(rbytes == 0) + { + printk(KERN_ERR "Failed to copy to user.\n"); + return EFAULT; + } + + printk(KERN_INFO "read data: %s\n", dev->pbuf); + + memset(dev->pbuf, 0, strlen(dev->pbuf)); + + return rbytes; +} + +static ssize_t test_write(struct file *filp, const char __user *buf, size_t nbytes, loff_t *f_pos) +{ + struct chardev *dev = filp->private_data; + + down_interruptible(&dev->sem); + + if(copy_from_user(dev->pbuf, buf, nbytes) < 0) + { + printk(KERN_ERR "Failed to copy from user.\n"); + return EFAULT; + } + + up(&dev->sem); + + printk(KERN_ERR "Wake up to read the buffer.\n"); + wake_up_interruptible(&dev->waitq); + return nbytes; +} + + +static int test_release(struct inode *inode, struct file *filp) +{ + struct chardev *dev = filp->private_data; + + kfree(dev->pbuf); + + return 0; +} + +static void chardev_init(void) +{ + int result, err = 0; + dev_t devno = MKDEV(CDEV_MAJOR, 0); + + if (cdev_major) + result = register_chrdev_region(devno, cdev_major, "cdev"); + else { + result = alloc_chrdev_region(&devno, 0, cdev_major, "cdev"); + cdev_major = MAJOR(devno); + } + + if(result < 0) + { + printk("device allocation failed.\n"); + return; + } + + char_devices = kmalloc(sizeof(struct chardev), GFP_KERNEL); + + if(!char_devices) + { + result = -ENOMEM; + unregister_chrdev_region(devno, 1); + } + + memset(char_devices, 0, sizeof(struct chardev)); + + sema_init(&char_devices->sem, 1); + init_waitqueue_head(&char_devices->waitq); + + cdev_init(&char_devices->cdev, &char_ops); + char_devices->cdev.owner = THIS_MODULE; + char_devices->cdev.ops = &char_ops; + + err = cdev_add(&char_devices->cdev, devno, 1); + + if(err) + printk(KERN_ERR "Error adding char device %d", devno); + +} + +/* +void my_workqueue_handler(struct work_struct *work) +{ + printk("WORK QUEUE: I'm just a timer to wake up the sleeping module.\n"); + msleep(1000); + printk("WORK QUEUE: Time up Module wake up.\n"); + wake_up_interruptible(&my_wait_queue); +} +*/ +int init_module(void) +{ + printk("Wait queue create buffer...\n"); + + ptr_buffer = kmalloc(1024*sizeof(char), GFP_KERNEL); + +// INIT_WORK(&workq, my_workqueue_handler); + +// schedule_work(&workq); + + chardev_init(); + + sema_init(&sem, 1); + + init_waitqueue_head(&my_wait_queue); + + proc_create("Waitq", 0, NULL, &proc_ops); + + return 0; +} + +void cleanup_module(void) +{ + remove_proc_entry("Waitq", NULL); + + cdev_del(&char_devices->cdev); + unregister_chrdev_region(MKDEV(CDEV_MAJOR, 0), 1); + + kfree(ptr_buffer); + printk("<1> Start to cleanup \n"); +} + + + diff --git a/pool/shard006/C/0117173_sorter.c b/pool/shard006/C/0117173_sorter.c new file mode 100644 index 0000000000000000000000000000000000000000..60f81d78f52b58699e9715f032448ad71abed005 --- /dev/null +++ b/pool/shard006/C/0117173_sorter.c @@ -0,0 +1,111 @@ +#pragma config(Sensor, in1, lineFollower, sensorLineFollower) +#pragma config(Sensor, dgtl1, encod, sensorQuadEncoder) +#pragma config(Sensor, dgtl3, pushB, sensorTouch) +#pragma config(Sensor, dgtl11, ind0, sensorLEDtoVCC) +#pragma config(Sensor, dgtl12, ind1, sensorLEDtoVCC) +#pragma config(Motor, port1, flight, tmotorVexFlashlight, openLoop, reversed) +#pragma config(Motor, port2, rMotorGateId, tmotorVex393_MC29, openLoop, reversed) +#pragma config(Motor, port3, rMotorServRId, tmotorServoStandard, openLoop) +#pragma config(Motor, port4, rMotorServLId, tmotorServoStandard, openLoop) +//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// + +#include "utilities.c" +#include "indicators.c" +#include "measure.c" +#include "gate.c" + +int material = -1; + +int sort(bool learn); + +task main() { + + doConfig(); + indMode[0] = 1; + indMode[1] = 3; + while (!SensorValue[pushB]) doIndicateTick(); + delayInd(100); + while (SensorValue[pushB]) doIndicateTick(); + indMode[0] = 2; + indMode[1] = 0; + + // precalibrate + + SensorValue[encod] = 0; + mgate = 0; + + // learn four materials + + for (int i = 0; i < 4; ++i) { + sort(true); + delayInd(CONFIG.SORT_DELAY); + } + + while (1) { + + indMode[0] = 0; + indMode[1] = 3; + while (!SensorValue[pushB]) doIndicateTick(); + delayInd(100); + while (SensorValue[pushB]) doIndicateTick(); + delayInd(100); + + while (1) { + indMode[1] = 1; + indMode[0] = 4; + if (SensorValue[pushB]) break; + + delayInd(CONFIG.SORT_DELAY); + + indMode[1] = 0; + indMode[0] = 4; + + sort(false); + } + + indMode[1] = 1; + indMode[0] = 3; + + while (!SensorValue[pushB]) doIndicateTick(); + delayInd(100); + while (SensorValue[pushB]) doIndicateTick(); + delayInd(100); + } +} + +int sort(bool learn) { + material = getMaterial(learn); + + switch (material) { + case 0: + mgate = -CONFIG.GATE_SPEED; + msl = CONFIG.SERVO_PATH_LEFT; + break; + case 1: + mgate = -CONFIG.GATE_SPEED; + msl = CONFIG.SERVO_PATH_RIGHT; + break; + case 2: + mgate = CONFIG.GATE_SPEED; + msr = CONFIG.SERVO_PATH_LEFT; + break; + case 3: + mgate = CONFIG.GATE_SPEED; + msr = CONFIG.SERVO_PATH_RIGHT; + break; + default: + return -1; + } + + delayInd(CONFIG.GATE_LENGTH); + if (material > 1) { + // do a quick hop back the other way - + // this should help get the sensor in a better place each time. + mgate = -100; + delayInd(50); + mgate = 0; + } + goToZero(); + + return material; +} diff --git a/pool/shard006/C/0117174_clock_config.c b/pool/shard006/C/0117174_clock_config.c new file mode 100644 index 0000000000000000000000000000000000000000..0477f43e6ff82a14dc8387c12246e6f3c5f9e0ec --- /dev/null +++ b/pool/shard006/C/0117174_clock_config.c @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o 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. + * + * o Neither the name of Freescale Semiconductor, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * How to setup clock using clock driver functions: + * + * 1. CLOCK_SetSimSafeDivs, to make sure core clock, bus clock, flexbus clock + * and flash clock are in allowed range during clock mode switch. + * + * 2. Call CLOCK_Osc0Init to setup OSC clock, if it is used in target mode. + * + * 3. Set MCG configuration, MCG includes three parts: FLL clock, PLL clock and + * internal reference clock(MCGIRCLK). Follow the steps to setup: + * + * 1). Call CLOCK_BootToXxxMode to set MCG to target mode. + * + * 2). If target mode is FBI/BLPI/PBI mode, the MCGIRCLK has been configured + * correctly. For other modes, need to call CLOCK_SetInternalRefClkConfig + * explicitly to setup MCGIRCLK. + * + * 3). Don't need to configure FLL explicitly, because if target mode is FLL + * mode, then FLL has been configured by the function CLOCK_BootToXxxMode, + * if the target mode is not FLL mode, the FLL is disabled. + * + * 4). If target mode is PEE/PBE/PEI/PBI mode, then the related PLL has been + * setup by CLOCK_BootToXxxMode. In FBE/FBI/FEE/FBE mode, the PLL could + * be enabled independently, call CLOCK_EnablePll0 explicitly in this case. + * + * 4. Call CLOCK_SetSimConfig to set the clock configuration in SIM. + */ + +/* TEXT BELOW IS USED AS SETTING FOR THE CLOCKS TOOL ***************************** +!!ClocksProfile +product: Clocks v1.0 +processor: MKW41Z512xxx4 +package_id: MKW41Z512VHT4 +mcu_data: ksdk2_0 +processor_version: 0.1.28 +board: FRDM-KW41Z + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR THE CLOCKS TOOL **/ + +#include "fsl_rtc.h" +#include "clock_config.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ +#define RTC_OSC_CAP_LOAD_0PF 0x0U /*!< RTC oscillator capacity load: 0pF */ +#define SIM_LPUART_CLK_SEL_OSCERCLK_CLK 2U /*!< LPUART clock select: OSCERCLK clock */ +#define SIM_OSC32KSEL_OSC32KCLK_CLK 0U /*!< OSC32KSEL select: OSC32KCLK clock */ +#define SIM_TPM_CLK_SEL_OSCERCLK_CLK 2U /*!< TPM clock select: OSCERCLK clock */ + +/******************************************************************************* + * Variables + ******************************************************************************/ +/* System clock frequency. */ +extern uint32_t SystemCoreClock; + +/******************************************************************************* + * Code + ******************************************************************************/ +/*FUNCTION********************************************************************** + * + * Function Name : CLOCK_CONFIG_FllStableDelay + * Description : This function is used to delay for FLL stable. + * + *END**************************************************************************/ +static void CLOCK_CONFIG_FllStableDelay(void) +{ + uint32_t i = 30000U; + + while (i--) + { + __NOP(); + } +} + +/*FUNCTION********************************************************************** + * + * Function Name : CLOCK_CONFIG_SetRtcClock + * Description : This function is used to configuring RTC clock + * + *END**************************************************************************/ +static void CLOCK_CONFIG_SetRtcClock() +{ + /* RTC clock gate enable */ + CLOCK_EnableClock(kCLOCK_Rtc0); + + /* Set RTC_TSR if there is fault value in RTC */ + if (RTC->SR & RTC_SR_TIF_MASK) + { + RTC -> TSR = RTC -> TSR; + } + + /* RTC clock gate disable */ + CLOCK_DisableClock(kCLOCK_Rtc0); +} + +/*FUNCTION********************************************************************** + * + * Function Name : CLOCK_CONFIG_EnableRtcOsc + * Description : This function is used to enabling RTC oscillator + * Param capLoad : Oscillator capacity load + * + *END**************************************************************************/ +static void CLOCK_CONFIG_EnableRtcOsc(uint32_t capLoad) +{ + /* RTC clock gate enable */ + CLOCK_EnableClock(kCLOCK_Rtc0); + + if ((RTC->CR & RTC_CR_OSCE_MASK) == 0u) /* Only if the Rtc oscillator is not already enabled */ + { + /* Set the specified capacitor configuration for the RTC oscillator */ + RTC_SetOscCapLoad(RTC, capLoad); + /* Enable the RTC 32KHz oscillator */ + RTC->CR |= RTC_CR_OSCE_MASK; + } + + /* RTC clock gate disable */ + CLOCK_DisableClock(kCLOCK_Rtc0); + CLOCK_SetXtal32Freq(32768); +} + +/*FUNCTION********************************************************************** + * + * Function Name : BOARD_RfOscInit + * Description : This function is used to setup Ref oscillator for KW40_512. + * + *END**************************************************************************/ +void BOARD_RfOscInit(void) +{ + uint32_t tempTrim; + uint8_t revId; + + /* Obtain REV ID from SIM */ + revId = (uint8_t)((uint32_t)(SIM->SDID & SIM_SDID_REVID_MASK) >> SIM_SDID_REVID_SHIFT); + + if (0 == revId) + { + tempTrim = RSIM->ANA_TRIM; + RSIM->ANA_TRIM |= RSIM_ANA_TRIM_BB_LDO_XO_TRIM_MASK; /* Set max trim for BB LDO for XO */ + }/* Workaround for Rev 1.0 XTAL startup and ADC analog diagnostics circuitry */ + + /* Turn on clocks for the XCVR */ + + /* Enable RF OSC in RSIM and wait for ready */ + RSIM->CONTROL = ((RSIM->CONTROL & ~RSIM_CONTROL_RF_OSC_EN_MASK) | RSIM_CONTROL_RF_OSC_EN(1)); + + /* ERR010224 */ + RSIM->RF_OSC_CTRL |= + RSIM_RF_OSC_CTRL_RADIO_EXT_OSC_OVRD_EN_MASK; /* Prevent XTAL_OUT_EN from generating XTAL_OUT request */ + + while ((RSIM->CONTROL & RSIM_CONTROL_RF_OSC_READY_MASK) == 0); /* Wait for RF_OSC_READY */ + + if (0 == revId) + { + SIM->SCGC5 |= SIM_SCGC5_PHYDIG_MASK; + XCVR_TSM->OVRD0 |= XCVR_TSM_OVRD0_BB_LDO_ADCDAC_EN_OVRD_EN_MASK | + XCVR_TSM_OVRD0_BB_LDO_ADCDAC_EN_OVRD_MASK; /* Force ADC DAC LDO on to prevent BGAP failure */ + + RSIM->ANA_TRIM = tempTrim; /* Reset LDO trim settings */ + }/* Workaround for Rev 1.0 XTAL startup and ADC analog diagnostics circuitry */ + +} + +/*FUNCTION********************************************************************** + * + * Function Name : BOARD_InitOsc0 + * Description : This function is used to setup MCG OSC with Ref oscillator for KW40_512. + * + *END**************************************************************************/ +void BOARD_InitOsc0(void) +{ + const osc_config_t oscConfig = + { + .freq = BOARD_XTAL0_CLK_HZ, .workMode = kOSC_ModeExt, + }; + + /* Initializes OSC0 according to previous configuration to meet Ref OSC needs. */ + CLOCK_InitOsc0(&oscConfig); + + /* Passing the XTAL0 frequency to clock driver. */ + CLOCK_SetXtal0Freq(BOARD_XTAL0_CLK_HZ); +} + +/******************************************************************************* + ********************** Configuration BOARD_BootClockRUN *********************** + ******************************************************************************/ +/* TEXT BELOW IS USED AS SETTING FOR THE CLOCKS TOOL ***************************** +!!Configuration +name: BOARD_BootClockRUN +outputs: +- {id: Bus_clock.outFreq, value: 23.986176 MHz} +- {id: Core_clock.outFreq, value: 47.972352 MHz} +- {id: ERCLK32K.outFreq, value: 32.768 kHz} +- {id: Flash_clock.outFreq, value: 23.986176 MHz} +- {id: LPO_clock.outFreq, value: 1 kHz} +- {id: LPUART0CLK.outFreq, value: 32 MHz} +- {id: MCGFLLCLK.outFreq, value: 47.972352 MHz} +- {id: MCGIRCLK.outFreq, value: 32.768 kHz} +- {id: OSCERCLK.outFreq, value: 32 MHz} +- {id: System_clock.outFreq, value: 47.972352 MHz} +- {id: TPMCLK.outFreq, value: 32 MHz} +settings: +- {id: MCGMode, value: FEE} +- {id: LPUART0ClkConfig, value: 'yes'} +- {id: MCG.FCRDIV.scale, value: '1'} +- {id: MCG.FLL_mul.scale, value: '1464'} +- {id: MCG.IREFS.sel, value: MCG.FRDIV} +- {id: MCG.OSCSEL.sel, value: RTC_32K.OSCCLK32K} +- {id: MCG_C1_IRCLKEN_CFG, value: Enabled} +- {id: RTC_CR_OSCE_CFG, value: Oscillator_enabled} +- {id: SIM.LPUART0SRCSEL.sel, value: REFOSC.OSCCLK} +- {id: SIM.TPMSRCSEL.sel, value: REFOSC.OSCCLK} +- {id: TPMClkConfig, value: 'yes'} +sources: +- {id: REFOSC.OSC.outFreq, value: 32 MHz, enabled: true} +- {id: RTC_32K.OSC32kHz.outFreq, value: 32.768 kHz, enabled: true} + * BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR THE CLOCKS TOOL **/ + +/******************************************************************************* + * Variables for BOARD_BootClockRUN configuration + ******************************************************************************/ +const mcg_config_t mcgConfig_BOARD_BootClockRUN = +{ + .mcgMode = kMCG_ModeFEE, /* FEE - FLL Engaged External */ + .irclkEnableMode = kMCG_IrclkEnable, /* MCGIRCLK enabled, MCGIRCLK disabled in STOP mode */ + .ircs = kMCG_IrcSlow, /* Slow internal reference clock selected */ + .fcrdiv = 0x0U, /* Fast IRC divider: divided by 1 */ + .frdiv = 0x0U, /* FLL reference clock divider: divided by 1 */ + .drs = kMCG_DrsMid, /* Mid frequency range */ + .dmx32 = kMCG_Dmx32Fine, /* DCO is fine-tuned for maximum frequency with 32.768 kHz reference */ + .oscsel = kMCG_OscselRtc, /* Selects 32 kHz RTC Oscillator */ +}; +const sim_clock_config_t simConfig_BOARD_BootClockRUN = +{ + .er32kSrc = SIM_OSC32KSEL_OSC32KCLK_CLK, /* OSC32KSEL select: OSC32KCLK clock */ + .clkdiv1 = 0x10000U, /* SIM_CLKDIV1 - OUTDIV1: /1, OUTDIV4: /2 */ +}; + +/******************************************************************************* + * Code for BOARD_BootClockRUN configuration + ******************************************************************************/ +void BOARD_BootClockRUN(void) +{ + /* Setup the reference oscillator. */ + BOARD_RfOscInit(); + /* Set the system clock dividers in SIM to safe value. */ + CLOCK_SetSimSafeDivs(); + /* Enable RTC oscillator. */ + CLOCK_CONFIG_EnableRtcOsc(RTC_OSC_CAP_LOAD_0PF); + /* Initializes OSC0 according to Ref OSC needs. */ + BOARD_InitOsc0(); + /* Set MCG to FEE mode. */ + CLOCK_BootToFeeMode(mcgConfig_BOARD_BootClockRUN.oscsel, + mcgConfig_BOARD_BootClockRUN.frdiv, + mcgConfig_BOARD_BootClockRUN.dmx32, + mcgConfig_BOARD_BootClockRUN.drs, + CLOCK_CONFIG_FllStableDelay); + /* Configure the Internal Reference clock (MCGIRCLK). */ + CLOCK_SetInternalRefClkConfig(mcgConfig_BOARD_BootClockRUN.irclkEnableMode, + mcgConfig_BOARD_BootClockRUN.ircs, + mcgConfig_BOARD_BootClockRUN.fcrdiv); + /* Set the clock configuration in SIM module. */ + CLOCK_SetSimConfig(&simConfig_BOARD_BootClockRUN); + /* Configure RTC clock. */ + CLOCK_CONFIG_SetRtcClock(); + /* Set SystemCoreClock variable. */ + SystemCoreClock = BOARD_BOOTCLOCKRUN_CORE_CLOCK; + /* Set LPUART0 clock source. */ + CLOCK_SetLpuartClock(SIM_LPUART_CLK_SEL_OSCERCLK_CLK); + /* Set TPM clock source. */ + CLOCK_SetTpmClock(SIM_TPM_CLK_SEL_OSCERCLK_CLK); +} + diff --git a/pool/shard006/C/0117193_netdev.c b/pool/shard006/C/0117193_netdev.c new file mode 100644 index 0000000000000000000000000000000000000000..155ff7406776f3790498f741972f48ec9bf1b5b9 --- /dev/null +++ b/pool/shard006/C/0117193_netdev.c @@ -0,0 +1,239 @@ +/* + BNEP implementation for Linux Bluetooth stack (BlueZ). + Copyright (C) 2001-2002 Inventel Systemes + Written 2001-2002 by + Clément Moreau + David Libault + + Copyright (C) 2002 Maxim Krasnyansky + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 as + published by the Free Software Foundation; + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. + IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY + CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, + COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS + SOFTWARE IS DISCLAIMED. +*/ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "bnep.h" + +#define BNEP_TX_QUEUE_LEN 20 + +static int bnep_net_open(struct net_device *dev) +{ + netif_start_queue(dev); + return 0; +} + +static int bnep_net_close(struct net_device *dev) +{ + netif_stop_queue(dev); + return 0; +} + +static void bnep_net_set_mc_list(struct net_device *dev) +{ +#ifdef CONFIG_BT_BNEP_MC_FILTER + struct bnep_session *s = netdev_priv(dev); + struct sock *sk = s->sock->sk; + struct bnep_set_filter_req *r; + struct sk_buff *skb; + int size; + + BT_DBG("%s mc_count %d", dev->name, netdev_mc_count(dev)); + + size = sizeof(*r) + (BNEP_MAX_MULTICAST_FILTERS + 1) * ETH_ALEN * 2; + skb = alloc_skb(size, GFP_ATOMIC); + if (!skb) { + BT_ERR("%s Multicast list allocation failed", dev->name); + return; + } + + r = (void *) skb->data; + __skb_put(skb, sizeof(*r)); + + r->type = BNEP_CONTROL; + r->ctrl = BNEP_FILTER_MULTI_ADDR_SET; + + if (dev->flags & (IFF_PROMISC | IFF_ALLMULTI)) { + u8 start[ETH_ALEN] = { 0x01 }; + + /* Request all addresses */ + memcpy(__skb_put(skb, ETH_ALEN), start, ETH_ALEN); + memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN); + r->len = htons(ETH_ALEN * 2); + } else { + struct netdev_hw_addr *ha; + int i, len = skb->len; + + if (dev->flags & IFF_BROADCAST) { + memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN); + memcpy(__skb_put(skb, ETH_ALEN), dev->broadcast, ETH_ALEN); + } + + /* FIXME: We should group addresses here. */ + + i = 0; + netdev_for_each_mc_addr(ha, dev) { + if (i == BNEP_MAX_MULTICAST_FILTERS) + break; + memcpy(__skb_put(skb, ETH_ALEN), ha->addr, ETH_ALEN); + memcpy(__skb_put(skb, ETH_ALEN), ha->addr, ETH_ALEN); + + i++; + } + r->len = htons(skb->len - len); + } + + skb_queue_tail(&sk->sk_write_queue, skb); + wake_up_interruptible(sk_sleep(sk)); +#endif +} + +static int bnep_net_set_mac_addr(struct net_device *dev, void *arg) +{ + BT_DBG("%s", dev->name); + return 0; +} + +static void bnep_net_timeout(struct net_device *dev) +{ + BT_DBG("net_timeout"); + netif_wake_queue(dev); +} + +#ifdef CONFIG_BT_BNEP_MC_FILTER +static inline int bnep_net_mc_filter(struct sk_buff *skb, struct bnep_session *s) +{ + struct ethhdr *eh = (void *) skb->data; + + if ((eh->h_dest[0] & 1) && !test_bit(bnep_mc_hash(eh->h_dest), (ulong *) &s->mc_filter)) + return 1; + return 0; +} +#endif + +#ifdef CONFIG_BT_BNEP_PROTO_FILTER +/* Determine ether protocol. Based on eth_type_trans. */ +static inline u16 bnep_net_eth_proto(struct sk_buff *skb) +{ + struct ethhdr *eh = (void *) skb->data; + u16 proto = ntohs(eh->h_proto); + + if (proto >= 1536) + return proto; + + if (get_unaligned((__be16 *) skb->data) == htons(0xFFFF)) + return ETH_P_802_3; + + return ETH_P_802_2; +} + +static inline int bnep_net_proto_filter(struct sk_buff *skb, struct bnep_session *s) +{ + u16 proto = bnep_net_eth_proto(skb); + struct bnep_proto_filter *f = s->proto_filter; + int i; + + for (i = 0; i < BNEP_MAX_PROTO_FILTERS && f[i].end; i++) { + if (proto >= f[i].start && proto <= f[i].end) + return 0; + } + + BT_DBG("BNEP: filtered skb %p, proto 0x%.4x", skb, proto); + return 1; +} +#endif + +static netdev_tx_t bnep_net_xmit(struct sk_buff *skb, + struct net_device *dev) +{ + struct bnep_session *s = netdev_priv(dev); + struct sock *sk = s->sock->sk; + + BT_DBG("skb %p, dev %p", skb, dev); + +#ifdef CONFIG_BT_BNEP_MC_FILTER + if (bnep_net_mc_filter(skb, s)) { + kfree_skb(skb); + return NETDEV_TX_OK; + } +#endif + +#ifdef CONFIG_BT_BNEP_PROTO_FILTER + if (bnep_net_proto_filter(skb, s)) { + kfree_skb(skb); + return NETDEV_TX_OK; + } +#endif + + /* + * We cannot send L2CAP packets from here as we are potentially in a bh. + * So we have to queue them and wake up session thread which is sleeping + * on the sk_sleep(sk). + */ + dev->trans_start = jiffies; + skb_queue_tail(&sk->sk_write_queue, skb); + wake_up_interruptible(sk_sleep(sk)); + + if (skb_queue_len(&sk->sk_write_queue) >= BNEP_TX_QUEUE_LEN) { + BT_DBG("tx queue is full"); + + /* Stop queuing. + * Session thread will do netif_wake_queue() */ + netif_stop_queue(dev); + } + + return NETDEV_TX_OK; +} + +static const struct net_device_ops bnep_netdev_ops = { + .ndo_open = bnep_net_open, + .ndo_stop = bnep_net_close, + .ndo_start_xmit = bnep_net_xmit, + .ndo_validate_addr = eth_validate_addr, + .ndo_set_rx_mode = bnep_net_set_mc_list, + .ndo_set_mac_address = bnep_net_set_mac_addr, + .ndo_tx_timeout = bnep_net_timeout, + .ndo_change_mtu = eth_change_mtu, + +}; + +void bnep_net_setup(struct net_device *dev) +{ + + memset(dev->broadcast, 0xff, ETH_ALEN); + dev->addr_len = ETH_ALEN; + + ether_setup(dev); + dev->priv_flags &= ~IFF_TX_SKB_SHARING; + dev->netdev_ops = &bnep_netdev_ops; + + dev->watchdog_timeo = HZ * 2; +} diff --git a/pool/shard006/C/0117201_iwl-rx.c b/pool/shard006/C/0117201_iwl-rx.c new file mode 100644 index 0000000000000000000000000000000000000000..c44e7feade77d3b98341d04f541ab078ad825d55 --- /dev/null +++ b/pool/shard006/C/0117201_iwl-rx.c @@ -0,0 +1,281 @@ +/****************************************************************************** + * + * Copyright(c) 2003 - 2011 Intel Corporation. All rights reserved. + * + * Portions of this file are derived from the ipw3945 project, as well + * as portions of the ieee80211 subsystem header files. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA + * + * The full GNU General Public License is included in this distribution in the + * file called LICENSE. + * + * Contact Information: + * Intel Linux Wireless + * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 + * + *****************************************************************************/ + +#include +#include +#include +#include +#include "iwl-eeprom.h" +#include "iwl-dev.h" +#include "iwl-core.h" +#include "iwl-sta.h" +#include "iwl-io.h" +#include "iwl-helpers.h" +/************************** RX-FUNCTIONS ****************************/ +/* + * Rx theory of operation + * + * Driver allocates a circular buffer of Receive Buffer Descriptors (RBDs), + * each of which point to Receive Buffers to be filled by the NIC. These get + * used not only for Rx frames, but for any command response or notification + * from the NIC. The driver and NIC manage the Rx buffers by means + * of indexes into the circular buffer. + * + * Rx Queue Indexes + * The host/firmware share two index registers for managing the Rx buffers. + * + * The READ index maps to the first position that the firmware may be writing + * to -- the driver can read up to (but not including) this position and get + * good data. + * The READ index is managed by the firmware once the card is enabled. + * + * The WRITE index maps to the last position the driver has read from -- the + * position preceding WRITE is the last slot the firmware can place a packet. + * + * The queue is empty (no good data) if WRITE = READ - 1, and is full if + * WRITE = READ. + * + * During initialization, the host sets up the READ queue position to the first + * INDEX position, and WRITE to the last (READ - 1 wrapped) + * + * When the firmware places a packet in a buffer, it will advance the READ index + * and fire the RX interrupt. The driver can then query the READ index and + * process as many packets as possible, moving the WRITE index forward as it + * resets the Rx queue buffers with new memory. + * + * The management in the driver is as follows: + * + A list of pre-allocated SKBs is stored in iwl->rxq->rx_free. When + * iwl->rxq->free_count drops to or below RX_LOW_WATERMARK, work is scheduled + * to replenish the iwl->rxq->rx_free. + * + In iwl_rx_replenish (scheduled) if 'processed' != 'read' then the + * iwl->rxq is replenished and the READ INDEX is updated (updating the + * 'processed' and 'read' driver indexes as well) + * + A received packet is processed and handed to the kernel network stack, + * detached from the iwl->rxq. The driver 'processed' index is updated. + * + The Host/Firmware iwl->rxq is replenished at tasklet time from the rx_free + * list. If there are no allocated buffers in iwl->rxq->rx_free, the READ + * INDEX is not incremented and iwl->status(RX_STALLED) is set. If there + * were enough free buffers and RX_STALLED is set it is cleared. + * + * + * Driver sequence: + * + * iwl_legacy_rx_queue_alloc() Allocates rx_free + * iwl_rx_replenish() Replenishes rx_free list from rx_used, and calls + * iwl_rx_queue_restock + * iwl_rx_queue_restock() Moves available buffers from rx_free into Rx + * queue, updates firmware pointers, and updates + * the WRITE index. If insufficient rx_free buffers + * are available, schedules iwl_rx_replenish + * + * -- enable interrupts -- + * ISR - iwl_rx() Detach iwl_rx_mem_buffers from pool up to the + * READ INDEX, detaching the SKB from the pool. + * Moves the packet buffer from queue to rx_used. + * Calls iwl_rx_queue_restock to refill any empty + * slots. + * ... + * + */ + +/** + * iwl_legacy_rx_queue_space - Return number of free slots available in queue. + */ +int iwl_legacy_rx_queue_space(const struct iwl_rx_queue *q) +{ + int s = q->read - q->write; + if (s <= 0) + s += RX_QUEUE_SIZE; + /* keep some buffer to not confuse full and empty queue */ + s -= 2; + if (s < 0) + s = 0; + return s; +} +EXPORT_SYMBOL(iwl_legacy_rx_queue_space); + +/** + * iwl_legacy_rx_queue_update_write_ptr - Update the write pointer for the RX queue + */ +void +iwl_legacy_rx_queue_update_write_ptr(struct iwl_priv *priv, + struct iwl_rx_queue *q) +{ + unsigned long flags; + u32 rx_wrt_ptr_reg = priv->hw_params.rx_wrt_ptr_reg; + u32 reg; + + spin_lock_irqsave(&q->lock, flags); + + if (q->need_update == 0) + goto exit_unlock; + + /* If power-saving is in use, make sure device is awake */ + if (test_bit(STATUS_POWER_PMI, &priv->status)) { + reg = iwl_read32(priv, CSR_UCODE_DRV_GP1); + + if (reg & CSR_UCODE_DRV_GP1_BIT_MAC_SLEEP) { + IWL_DEBUG_INFO(priv, + "Rx queue requesting wakeup," + " GP1 = 0x%x\n", reg); + iwl_legacy_set_bit(priv, CSR_GP_CNTRL, + CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ); + goto exit_unlock; + } + + q->write_actual = (q->write & ~0x7); + iwl_legacy_write_direct32(priv, rx_wrt_ptr_reg, + q->write_actual); + + /* Else device is assumed to be awake */ + } else { + /* Device expects a multiple of 8 */ + q->write_actual = (q->write & ~0x7); + iwl_legacy_write_direct32(priv, rx_wrt_ptr_reg, + q->write_actual); + } + + q->need_update = 0; + + exit_unlock: + spin_unlock_irqrestore(&q->lock, flags); +} +EXPORT_SYMBOL(iwl_legacy_rx_queue_update_write_ptr); + +int iwl_legacy_rx_queue_alloc(struct iwl_priv *priv) +{ + struct iwl_rx_queue *rxq = &priv->rxq; + struct device *dev = &priv->pci_dev->dev; + int i; + + spin_lock_init(&rxq->lock); + INIT_LIST_HEAD(&rxq->rx_free); + INIT_LIST_HEAD(&rxq->rx_used); + + /* Alloc the circular buffer of Read Buffer Descriptors (RBDs) */ + rxq->bd = dma_alloc_coherent(dev, 4 * RX_QUEUE_SIZE, &rxq->bd_dma, + GFP_KERNEL); + if (!rxq->bd) + goto err_bd; + + rxq->rb_stts = dma_alloc_coherent(dev, sizeof(struct iwl_rb_status), + &rxq->rb_stts_dma, GFP_KERNEL); + if (!rxq->rb_stts) + goto err_rb; + + /* Fill the rx_used queue with _all_ of the Rx buffers */ + for (i = 0; i < RX_FREE_BUFFERS + RX_QUEUE_SIZE; i++) + list_add_tail(&rxq->pool[i].list, &rxq->rx_used); + + /* Set us so that we have processed and used all buffers, but have + * not restocked the Rx queue with fresh buffers */ + rxq->read = rxq->write = 0; + rxq->write_actual = 0; + rxq->free_count = 0; + rxq->need_update = 0; + return 0; + +err_rb: + dma_free_coherent(&priv->pci_dev->dev, 4 * RX_QUEUE_SIZE, rxq->bd, + rxq->bd_dma); +err_bd: + return -ENOMEM; +} +EXPORT_SYMBOL(iwl_legacy_rx_queue_alloc); + + +void iwl_legacy_rx_spectrum_measure_notif(struct iwl_priv *priv, + struct iwl_rx_mem_buffer *rxb) +{ + struct iwl_rx_packet *pkt = rxb_addr(rxb); + struct iwl_spectrum_notification *report = &(pkt->u.spectrum_notif); + + if (!report->state) { + IWL_DEBUG_11H(priv, + "Spectrum Measure Notification: Start\n"); + return; + } + + memcpy(&priv->measure_report, report, sizeof(*report)); + priv->measurement_status |= MEASUREMENT_READY; +} +EXPORT_SYMBOL(iwl_legacy_rx_spectrum_measure_notif); + +/* + * returns non-zero if packet should be dropped + */ +int iwl_legacy_set_decrypted_flag(struct iwl_priv *priv, + struct ieee80211_hdr *hdr, + u32 decrypt_res, + struct ieee80211_rx_status *stats) +{ + u16 fc = le16_to_cpu(hdr->frame_control); + + /* + * All contexts have the same setting here due to it being + * a module parameter, so OK to check any context. + */ + if (priv->contexts[IWL_RXON_CTX_BSS].active.filter_flags & + RXON_FILTER_DIS_DECRYPT_MSK) + return 0; + + if (!(fc & IEEE80211_FCTL_PROTECTED)) + return 0; + + IWL_DEBUG_RX(priv, "decrypt_res:0x%x\n", decrypt_res); + switch (decrypt_res & RX_RES_STATUS_SEC_TYPE_MSK) { + case RX_RES_STATUS_SEC_TYPE_TKIP: + /* The uCode has got a bad phase 1 Key, pushes the packet. + * Decryption will be done in SW. */ + if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) == + RX_RES_STATUS_BAD_KEY_TTAK) + break; + + case RX_RES_STATUS_SEC_TYPE_WEP: + if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) == + RX_RES_STATUS_BAD_ICV_MIC) { + /* bad ICV, the packet is destroyed since the + * decryption is inplace, drop it */ + IWL_DEBUG_RX(priv, "Packet destroyed\n"); + return -1; + } + case RX_RES_STATUS_SEC_TYPE_CCMP: + if ((decrypt_res & RX_RES_STATUS_DECRYPT_TYPE_MSK) == + RX_RES_STATUS_DECRYPT_OK) { + IWL_DEBUG_RX(priv, "hw decrypt successfully!!!\n"); + stats->flag |= RX_FLAG_DECRYPTED; + } + break; + + default: + break; + } + return 0; +} +EXPORT_SYMBOL(iwl_legacy_set_decrypted_flag); diff --git a/pool/shard006/C/0117203_yaffs_ramdisk.c b/pool/shard006/C/0117203_yaffs_ramdisk.c new file mode 100644 index 0000000000000000000000000000000000000000..ba86c5e16a54162e3e95f4c293d843c82ef8d13c --- /dev/null +++ b/pool/shard006/C/0117203_yaffs_ramdisk.c @@ -0,0 +1,229 @@ +/* + * YAFFS: Yet another FFS. A NAND-flash specific file system. + * yaffs_ramdisk.c: yaffs ram disk component + * + * Copyright (C) 2002 Aleph One Ltd. + * + * Created by Charles Manning + * + * 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. + * + */ + + +const char *yaffs_ramdisk_c_version = "$Id: yaffs_ramdisk.c,v 1.2 2004/11/22 03:22:25 charles Exp $"; + + +#include "yportenv.h" + +#include "yaffs_ramdisk.h" +#include "yaffs_guts.h" +#include "devextras.h" +#include "yaffs_packedtags1.h" + + + +#define SIZE_IN_MB 2 + +#define BLOCK_SIZE (32 * 528) +#define BLOCKS_PER_MEG ((1024*1024)/(32 * 512)) + + + + + +typedef struct +{ + __u8 data[528]; +} yramdisk_Page; + +typedef struct +{ + yramdisk_Page page[32]; + +} yramdisk_Block; + + + +typedef struct +{ + yramdisk_Block **block; + int nBlocks; +} yramdisk_Device; + +static yramdisk_Device ramdisk; + +static int CheckInit(yaffs_Device *dev) +{ + static int initialised = 0; + + int i; + int fail = 0; + + int nAllocated = 0; + + if(initialised) + { + return YAFFS_OK; + } + + initialised = 1; + + + ramdisk.nBlocks = (SIZE_IN_MB * 1024 * 1024)/(16 * 1024); + + ramdisk.block = YMALLOC(sizeof(yramdisk_Block *) * ramdisk.nBlocks); + + if(!ramdisk.block) return 0; + + for(i=0; i page[pg].data,data,512); + } + + + if(tags) + { + yaffs_PackedTags1 pt; + + yaffs_PackTags1(&pt,tags); + memcpy(&ramdisk.block[blk]->page[pg].data[512],&pt,sizeof(pt)); + } + + return YAFFS_OK; + +} + + +int yramdisk_ReadChunkWithTagsFromNAND(yaffs_Device *dev,int chunkInNAND, __u8 *data, yaffs_ExtendedTags *tags) +{ + int blk; + int pg; + + + CheckInit(dev); + + blk = chunkInNAND/32; + pg = chunkInNAND%32; + + + if(data) + { + memcpy(data,ramdisk.block[blk]->page[pg].data,512); + } + + + if(tags) + { + yaffs_PackedTags1 pt; + + memcpy(&pt,&ramdisk.block[blk]->page[pg].data[512],sizeof(pt)); + yaffs_UnpackTags1(tags,&pt); + + } + + return YAFFS_OK; +} + + +int yramdisk_CheckChunkErased(yaffs_Device *dev,int chunkInNAND) +{ + int blk; + int pg; + int i; + + + CheckInit(dev); + + blk = chunkInNAND/32; + pg = chunkInNAND%32; + + + for(i = 0; i < 528; i++) + { + if(ramdisk.block[blk]->page[pg].data[i] != 0xFF) + { + return YAFFS_FAIL; + } + } + + return YAFFS_OK; + +} + +int yramdisk_EraseBlockInNAND(yaffs_Device *dev, int blockNumber) +{ + + CheckInit(dev); + + if(blockNumber < 0 || blockNumber >= ramdisk.nBlocks) + { + T(YAFFS_TRACE_ALWAYS,("Attempt to erase non-existant block %d\n",blockNumber)); + return YAFFS_FAIL; + } + else + { + memset(ramdisk.block[blockNumber],0xFF,sizeof(yramdisk_Block)); + return YAFFS_OK; + } + +} + +int yramdisk_InitialiseNAND(yaffs_Device *dev) +{ + + + + return YAFFS_OK; +} + + diff --git a/pool/shard006/C/0117206_dpll44xx.c b/pool/shard006/C/0117206_dpll44xx.c new file mode 100644 index 0000000000000000000000000000000000000000..9c6a296b3dc3a0dd6856580b9ddbf5e54ea79e0e --- /dev/null +++ b/pool/shard006/C/0117206_dpll44xx.c @@ -0,0 +1,153 @@ +/* + * OMAP4-specific DPLL control functions + * + * Copyright (C) 2011 Texas Instruments, Inc. + * Rajendra Nayak + * + * 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 +#include +#include +#include +#include + +#include +#include + +#include "clock.h" +#include "clock44xx.h" +#include "cm-regbits-44xx.h" + +/* Supported only on OMAP4 */ +int omap4_dpllmx_gatectrl_read(struct clk *clk) +{ + u32 v; + u32 mask; + + if (!clk || !clk->clksel_reg || !cpu_is_omap44xx()) + return -EINVAL; + + mask = clk->flags & CLOCK_CLKOUTX2 ? + OMAP4430_DPLL_CLKOUTX2_GATE_CTRL_MASK : + OMAP4430_DPLL_CLKOUT_GATE_CTRL_MASK; + + v = __raw_readl(clk->clksel_reg); + v &= mask; + v >>= __ffs(mask); + + return v; +} + +void omap4_dpllmx_allow_gatectrl(struct clk *clk) +{ + u32 v; + u32 mask; + + if (!clk || !clk->clksel_reg || !cpu_is_omap44xx()) + return; + + mask = clk->flags & CLOCK_CLKOUTX2 ? + OMAP4430_DPLL_CLKOUTX2_GATE_CTRL_MASK : + OMAP4430_DPLL_CLKOUT_GATE_CTRL_MASK; + + v = __raw_readl(clk->clksel_reg); + /* Clear the bit to allow gatectrl */ + v &= ~mask; + __raw_writel(v, clk->clksel_reg); +} + +void omap4_dpllmx_deny_gatectrl(struct clk *clk) +{ + u32 v; + u32 mask; + + if (!clk || !clk->clksel_reg || !cpu_is_omap44xx()) + return; + + mask = clk->flags & CLOCK_CLKOUTX2 ? + OMAP4430_DPLL_CLKOUTX2_GATE_CTRL_MASK : + OMAP4430_DPLL_CLKOUT_GATE_CTRL_MASK; + + v = __raw_readl(clk->clksel_reg); + /* Set the bit to deny gatectrl */ + v |= mask; + __raw_writel(v, clk->clksel_reg); +} + +const struct clkops clkops_omap4_dpllmx_ops = { + .allow_idle = omap4_dpllmx_allow_gatectrl, + .deny_idle = omap4_dpllmx_deny_gatectrl, +}; + +/** + * omap4_dpll_regm4xen_recalc - compute DPLL rate, considering REGM4XEN bit + * @clk: struct clk * of the DPLL to compute the rate for + * + * Compute the output rate for the OMAP4 DPLL represented by @clk. + * Takes the REGM4XEN bit into consideration, which is needed for the + * OMAP4 ABE DPLL. Returns the DPLL's output rate (before M-dividers) + * upon success, or 0 upon error. + */ +unsigned long omap4_dpll_regm4xen_recalc(struct clk *clk) +{ + u32 v; + unsigned long rate; + struct dpll_data *dd; + + if (!clk || !clk->dpll_data) + return 0; + + dd = clk->dpll_data; + + rate = omap2_get_dpll_rate(clk); + + /* regm4xen adds a multiplier of 4 to DPLL calculations */ + v = __raw_readl(dd->control_reg); + if (v & OMAP4430_DPLL_REGM4XEN_MASK) + rate *= OMAP4430_REGM4XEN_MULT; + + return rate; +} + +/** + * omap4_dpll_regm4xen_round_rate - round DPLL rate, considering REGM4XEN bit + * @clk: struct clk * of the DPLL to round a rate for + * @target_rate: the desired rate of the DPLL + * + * Compute the rate that would be programmed into the DPLL hardware + * for @clk if set_rate() were to be provided with the rate + * @target_rate. Takes the REGM4XEN bit into consideration, which is + * needed for the OMAP4 ABE DPLL. Returns the rounded rate (before + * M-dividers) upon success, -EINVAL if @clk is null or not a DPLL, or + * ~0 if an error occurred in omap2_dpll_round_rate(). + */ +long omap4_dpll_regm4xen_round_rate(struct clk *clk, unsigned long target_rate) +{ + u32 v; + struct dpll_data *dd; + long r; + + if (!clk || !clk->dpll_data) + return -EINVAL; + + dd = clk->dpll_data; + + /* regm4xen adds a multiplier of 4 to DPLL calculations */ + v = __raw_readl(dd->control_reg) & OMAP4430_DPLL_REGM4XEN_MASK; + + if (v) + target_rate = target_rate / OMAP4430_REGM4XEN_MULT; + + r = omap2_dpll_round_rate(clk, target_rate); + if (r == ~0) + return r; + + if (v) + clk->dpll_data->last_rounded_rate *= OMAP4430_REGM4XEN_MULT; + + return clk->dpll_data->last_rounded_rate; +} diff --git a/pool/shard006/C/0117220_gsl_sf_exp.c b/pool/shard006/C/0117220_gsl_sf_exp.c new file mode 100644 index 0000000000000000000000000000000000000000..ab25d08488c82873a3e94b96f9d45eda222fad26 --- /dev/null +++ b/pool/shard006/C/0117220_gsl_sf_exp.c @@ -0,0 +1,14 @@ +#include "stdlib.h" +#include "stdio.h" +#include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h" +#include +int main(int argc, const char * argv[]) { +unsigned long int hexdouble; +double a; +sscanf(argv[1], "%lX", &hexdouble); +a = *(double*)(&hexdouble); +double result = gsl_sf_exp(a); +//printf("%.15f\n", result); +VALGRIND_PRINT_ERROR("result", &result); +return 0; +} \ No newline at end of file diff --git a/pool/shard006/C/0117227_edges.c b/pool/shard006/C/0117227_edges.c new file mode 100644 index 0000000000000000000000000000000000000000..6d764ad3825c1485b0acc87340cf7ac56dbe8b6d --- /dev/null +++ b/pool/shard006/C/0117227_edges.c @@ -0,0 +1,47 @@ +#include "edges.h" + +edge_p edges_add(struct store *edges, edge_p e_old, node_p start, node_p end) +{ + edge_p e_new, size; + + if(e_old == 0) { + size = 8; + e_new = store_alloc(edges, size + 8); + } else { + size = store_read_ui64(edges, e_old); + e_new = store_alloc(edges, size + 8); + store_copy(edges, e_new, e_old, size); + } + + store_write_ui64(edges, e_new + size, end); + store_write_ui64(edges, e_new, size + 8); + store_free(edges, e_old); + return e_new; +} + +edge_p edges_remove(struct store *edges, edge_p e_old, node_p start, node_p end) +{ + if(e_old == 0) return 0; + + edge_p hdr_sz = 8; + edge_p item_sz = 8; + + edge_p size = store_read_ui64(edges, e_old); + edge_p i; + for(i = hdr_sz; i < size; i += item_sz) { + if( store_read_ui64(edges, e_old + i) == end ) break; + } + + if(i >= size) return e_old; + + int64_t size_new = size - item_sz; + if(size_new < 0) return e_old; + + edge_p e_new = store_alloc(edges, size_new); + store_copy(edges, e_new, e_old, i); + store_copy(edges, e_new + i, e_old + i + item_sz, size - i - item_sz); + + store_write_ui64(edges, e_new, size - item_sz); + store_free(edges, e_old); + return e_new; +} diff --git a/pool/shard006/C/0117253_gb-terminal-application-addin.c b/pool/shard006/C/0117253_gb-terminal-application-addin.c new file mode 100644 index 0000000000000000000000000000000000000000..d86ac04be73842e8c5a43fd201a2497a13aafa3d --- /dev/null +++ b/pool/shard006/C/0117253_gb-terminal-application-addin.c @@ -0,0 +1,84 @@ +/* gb-terminal-application-addin.c + * + * Copyright (C) 2015 Christian Hergert + * + * 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 . + */ + +#include "gb-terminal-application-addin.h" + +struct _GbTerminalApplicationAddin +{ + GObject parent_instance; +}; + +static void application_addin_iface_init (GbApplicationAddinInterface *iface); + +G_DEFINE_DYNAMIC_TYPE_EXTENDED (GbTerminalApplicationAddin, + gb_terminal_application_addin, + G_TYPE_OBJECT, + 0, + G_IMPLEMENT_INTERFACE (GB_TYPE_APPLICATION_ADDIN, + application_addin_iface_init)) + +static void +gb_terminal_application_addin_load (GbApplicationAddin *addin, + GbApplication *application) +{ + const gchar *new_terminal_accels[] = { "t", NULL }; + + g_assert (GB_IS_TERMINAL_APPLICATION_ADDIN (addin)); + g_assert (GB_IS_APPLICATION (application)); + + gtk_application_set_accels_for_action (GTK_APPLICATION (application), "win.new-terminal", + new_terminal_accels); +} + +static void +gb_terminal_application_addin_unload (GbApplicationAddin *addin, + GbApplication *application) +{ + g_assert (GB_IS_TERMINAL_APPLICATION_ADDIN (addin)); + g_assert (GB_IS_APPLICATION (application)); + + gtk_application_set_accels_for_action (GTK_APPLICATION (application), "win.new-terminal", NULL); +} + +static void +gb_terminal_application_addin_class_init (GbTerminalApplicationAddinClass *klass) +{ +} + +static void +gb_terminal_application_addin_class_finalize (GbTerminalApplicationAddinClass *klass) +{ +} + +static void +gb_terminal_application_addin_init (GbTerminalApplicationAddin *self) +{ +} + +static void +application_addin_iface_init (GbApplicationAddinInterface *iface) +{ + iface->load = gb_terminal_application_addin_load; + iface->unload = gb_terminal_application_addin_unload; +} + +void +_gb_terminal_application_addin_register_type (GTypeModule *module) +{ + gb_terminal_application_addin_register_type (module); +} diff --git a/pool/shard006/C/0117260_list_test.c b/pool/shard006/C/0117260_list_test.c new file mode 100644 index 0000000000000000000000000000000000000000..7742ccbd7d8864f1c14375792939d5f99e4b266f --- /dev/null +++ b/pool/shard006/C/0117260_list_test.c @@ -0,0 +1,79 @@ +/* + * list_test.c - some tests for list.c/list.h + * + * Copyright (c) 2017-2019, Alexander Kuleshov + * + * This file is released under the BSD license, see the COPYING file + */ + +#include + +int main(int argc, char *argv[]) +{ + list_t *entry = NULL; + list_t *list = list_new(); + + printf("list append test: "); + list_append(list, (list_item *)1); + list_append(list, (list_item *)2); + list_append(list, (list_item *)3); + list_append(list, (list_item *)4); + list_append(list, (list_item *)5); + + for_each_list_item(list, entry) + { + printf("%lu ", (unsigned long)entry->item); + } + printf("\n"); + + printf("list prepend test: "); + list = list_prepend(list, (list_item *)5); + for_each_list_item(list, entry) + { + printf("%lu ", (unsigned long)entry->item); + } + printf("\n"); + + printf("list lookup test: "); + int *res = (int *)list_lookup(list, (list_item *)5); + printf("%lu ", (unsigned long)res); + + res = (int *)list_lookup(list, (list_item *)6); + printf("%lu ", (unsigned long)res); + printf("\n"); + + printf("list nth test: "); + res = (int *)list_nth(list, 0); + printf("%lu ", (unsigned long)res); + + res = (int *)list_nth(list, 3); + printf("%lu", (unsigned long)res); + printf("\n"); + + printf("list length test: "); + int l = list_length(list); + printf("%d", l); + printf("\n"); + + printf("list remove test: "); + list = list_remove(list, (list_item *)5); + for_each_list_item(list, entry) + { + printf("%lu ", (unsigned long)entry->item); + } + + list = list_remove(list, (list_item *)2); + for_each_list_item(list, entry) + { + printf("%lu ", (unsigned long)entry->item); + } + printf("\n"); + + printf("list length after remove test: "); + l = list_length(list); + printf("%d\n", l); + + list_free(list); + + return 0; +} diff --git a/pool/shard006/C/0117271_max77803_haptic.c b/pool/shard006/C/0117271_max77803_haptic.c new file mode 100644 index 0000000000000000000000000000000000000000..9300c291de43540373f04c4a78d594115abed51f --- /dev/null +++ b/pool/shard006/C/0117271_max77803_haptic.c @@ -0,0 +1,169 @@ +/* + * haptic motor driver for max77803 - max77673_haptic.c + * + * Copyright (C) 2011 ByungChang Cha + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct max77803_haptic_data { + struct max77803_dev *max77803; + struct i2c_client *i2c; + struct i2c_client *pmic_i2c; + struct max77803_haptic_platform_data *pdata; + + spinlock_t lock; + bool running; +}; + +struct max77803_haptic_data *g_hap_data; + +static void max77803_haptic_i2c(struct max77803_haptic_data *hap_data, bool en) +{ + int ret; + u8 value = hap_data->pdata->reg2; + u8 lscnfg_val = 0x00; + + pr_debug("[VIB] %s %d\n", __func__, en); + + if (en) { + value |= MOTOR_EN; + lscnfg_val = 0x80; + } + + ret = max77803_update_reg(hap_data->pmic_i2c, MAX77803_PMIC_REG_LSCNFG, + lscnfg_val, 0x80); + if (ret) + pr_err("[VIB] i2c update error %d\n", ret); + + ret = max77803_write_reg(hap_data->i2c, + MAX77803_HAPTIC_REG_CONFIG2, value); + if (ret) + pr_err("[VIB] i2c write error %d\n", ret); +} + +#ifdef CONFIG_SS_VIBRATOR +void max77803_vibtonz_en(bool en) +{ + if (g_hap_data == NULL) { + printk(KERN_ERR "[VIB] the motor is not ready!!!"); + return ; + } + + if (en) { + if (g_hap_data->running) + return; + + max77803_haptic_i2c(g_hap_data, true); + + g_hap_data->running = true; + } else { + if (!g_hap_data->running) + return; + + max77803_haptic_i2c(g_hap_data, false); + + g_hap_data->running = false; + } +} +EXPORT_SYMBOL(max77803_vibtonz_en); +#endif + +static int max77803_haptic_probe(struct platform_device *pdev) +{ + int error = 0; + struct max77803_dev *max77803 = dev_get_drvdata(pdev->dev.parent); + struct max77803_platform_data *max77803_pdata + = dev_get_platdata(max77803->dev); +#ifdef CONFIG_SS_VIBRATOR + struct max77803_haptic_platform_data *pdata + = max77803_pdata->haptic_data; +#endif + struct max77803_haptic_data *hap_data; + + pr_debug("[VIB] ++ %s\n", __func__); + if (pdata == NULL) { + pr_err("%s: no pdata\n", __func__); + return -ENODEV; + } + + hap_data = kzalloc(sizeof(struct max77803_haptic_data), GFP_KERNEL); + if (!hap_data) + return -ENOMEM; + + platform_set_drvdata(pdev, hap_data); + g_hap_data = hap_data; + hap_data->max77803 = max77803; + hap_data->i2c = max77803->haptic; + hap_data->pmic_i2c = max77803->i2c; + pdata->reg2 = MOTOR_LRA | EXT_PWM | DIVIDER_128; + hap_data->pdata = pdata; + + spin_lock_init(&(hap_data->lock)); + + pr_debug("[VIB] -- %s\n", __func__); + + return error; +} + +static int __devexit max77803_haptic_remove(struct platform_device *pdev) +{ + struct max77803_haptic_data *data = platform_get_drvdata(pdev); + kfree(data); + g_hap_data = NULL; + + return 0; +} + +static int max77803_haptic_suspend(struct platform_device *pdev, + pm_message_t state) +{ + return 0; +} +static int max77803_haptic_resume(struct platform_device *pdev) +{ + return 0; +} + +static struct platform_driver max77803_haptic_driver = { + .probe = max77803_haptic_probe, + .remove = max77803_haptic_remove, + .suspend = max77803_haptic_suspend, + .resume = max77803_haptic_resume, + .driver = { + .name = "max77803-haptic", + .owner = THIS_MODULE, + }, +}; + +static int __init max77803_haptic_init(void) +{ + pr_debug("[VIB] %s\n", __func__); + return platform_driver_register(&max77803_haptic_driver); +} +module_init(max77803_haptic_init); + +static void __exit max77803_haptic_exit(void) +{ + platform_driver_unregister(&max77803_haptic_driver); +} +module_exit(max77803_haptic_exit); + +MODULE_AUTHOR("ByungChang Cha "); +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("MAX77803 haptic driver"); diff --git a/pool/shard006/C/0117275_Ex1.c b/pool/shard006/C/0117275_Ex1.c new file mode 100644 index 0000000000000000000000000000000000000000..0b0e429747ce62d2e2156c6210703ede536d125c --- /dev/null +++ b/pool/shard006/C/0117275_Ex1.c @@ -0,0 +1,12 @@ +#include +/*Dado dois número inteiro positivo n, calcular e imprimir a sua soma*/ +int main(void){ + int n1 = 0, n2 = 0, result = 0; + printf("\nDigite o primeiro numero: "); + scanf("%d", &n1); + printf("\nDigite o segundo numero: "); + scanf("%d", &n2); + result = n1 + n2; + printf("%d + %d = %d", n1, n2, result); + +} diff --git a/pool/shard006/C/0117280_CWE401_Memory_Leak__twoIntsStruct_calloc_44.c b/pool/shard006/C/0117280_CWE401_Memory_Leak__twoIntsStruct_calloc_44.c new file mode 100644 index 0000000000000000000000000000000000000000..bdcfe02239895dbdd93efff9e391d60b5fe687e6 --- /dev/null +++ b/pool/shard006/C/0117280_CWE401_Memory_Leak__twoIntsStruct_calloc_44.c @@ -0,0 +1,123 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__twoIntsStruct_calloc_44.c +Label Definition File: CWE401_Memory_Leak.c.label.xml +Template File: sources-sinks-44.tmpl.c +*/ +/* + * @description + * CWE: 401 Memory Leak + * BadSource: calloc Allocate data using calloc() + * GoodSource: Allocate data on the stack + * Sinks: + * GoodSink: call free() on data + * BadSink : no deallocation of data + * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +static void badSink(twoIntsStruct * data) +{ + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ +} + +void CWE401_Memory_Leak__twoIntsStruct_calloc_44_bad() +{ + twoIntsStruct * data; + /* define a function pointer */ + void (*funcPtr) (twoIntsStruct *) = badSink; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + /* use the function pointer */ + funcPtr(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSink(twoIntsStruct * data) +{ + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ +} + +static void goodG2B() +{ + twoIntsStruct * data; + void (*funcPtr) (twoIntsStruct *) = goodG2BSink; + data = NULL; + /* FIX: Use memory allocated on the stack with ALLOCA */ + data = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + funcPtr(data); +} + +/* goodB2G() uses the BadSource with the GoodSink */ +static void goodB2GSink(twoIntsStruct * data) +{ + /* FIX: Deallocate memory */ + free(data); +} + +static void goodB2G() +{ + twoIntsStruct * data; + void (*funcPtr) (twoIntsStruct *) = goodB2GSink; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + funcPtr(data); +} + +void CWE401_Memory_Leak__twoIntsStruct_calloc_44_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()..."); + CWE401_Memory_Leak__twoIntsStruct_calloc_44_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE401_Memory_Leak__twoIntsStruct_calloc_44_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0117283_reaper.c b/pool/shard006/C/0117283_reaper.c new file mode 100644 index 0000000000000000000000000000000000000000..2e32cae5d0fe0afaa6ea9394aaecc270e6912d66 --- /dev/null +++ b/pool/shard006/C/0117283_reaper.c @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +/* + * Copyright (C) 2020-2021 Paul Cercueil + */ + +#include "blockcache.h" +#include "debug.h" +#include "lightrec-private.h" +#include "memmanager.h" +#include "slist.h" +#include "reaper.h" + +#include +#include +#include +#include + +struct reaper_elm { + reap_func_t func; + void *data; + struct slist_elm slist; +}; + +struct reaper { + struct lightrec_state *state; + pthread_mutex_t mutex; + struct slist_elm reap_list; + + atomic_uint sem; +}; + +struct reaper *lightrec_reaper_init(struct lightrec_state *state) +{ + struct reaper *reaper; + int ret; + + reaper = lightrec_malloc(state, MEM_FOR_LIGHTREC, sizeof(*reaper)); + if (!reaper) { + pr_err("Cannot create reaper: Out of memory\n"); + return NULL; + } + + reaper->state = state; + reaper->sem = 0; + slist_init(&reaper->reap_list); + + ret = pthread_mutex_init(&reaper->mutex, NULL); + if (ret) { + pr_err("Cannot init mutex variable: %d\n", ret); + lightrec_free(reaper->state, MEM_FOR_LIGHTREC, + sizeof(*reaper), reaper); + return NULL; + } + + return reaper; +} + +void lightrec_reaper_destroy(struct reaper *reaper) +{ + pthread_mutex_destroy(&reaper->mutex); + lightrec_free(reaper->state, MEM_FOR_LIGHTREC, sizeof(*reaper), reaper); +} + +int lightrec_reaper_add(struct reaper *reaper, reap_func_t f, void *data) +{ + struct reaper_elm *reaper_elm; + struct slist_elm *elm; + int ret = 0; + + pthread_mutex_lock(&reaper->mutex); + + for (elm = reaper->reap_list.next; elm; elm = elm->next) { + reaper_elm = container_of(elm, struct reaper_elm, slist); + + if (reaper_elm->data == data) + goto out_unlock; + } + + reaper_elm = lightrec_malloc(reaper->state, MEM_FOR_LIGHTREC, + sizeof(*reaper_elm)); + if (!reaper_elm) { + pr_err("Cannot add reaper entry: Out of memory\n"); + ret = -ENOMEM; + goto out_unlock; + } + + reaper_elm->func = f; + reaper_elm->data = data; + slist_append(&reaper->reap_list, &reaper_elm->slist); + +out_unlock: + pthread_mutex_unlock(&reaper->mutex); + return ret; +} + +static bool lightrec_reaper_can_reap(struct reaper *reaper) +{ + return !atomic_load_explicit(&reaper->sem, memory_order_relaxed); +} + +void lightrec_reaper_reap(struct reaper *reaper) +{ + struct reaper_elm *reaper_elm; + struct slist_elm *elm; + + pthread_mutex_lock(&reaper->mutex); + + while (lightrec_reaper_can_reap(reaper) && + !!(elm = slist_first(&reaper->reap_list))) { + slist_remove(&reaper->reap_list, elm); + pthread_mutex_unlock(&reaper->mutex); + + reaper_elm = container_of(elm, struct reaper_elm, slist); + + (*reaper_elm->func)(reaper->state, reaper_elm->data); + + lightrec_free(reaper->state, MEM_FOR_LIGHTREC, + sizeof(*reaper_elm), reaper_elm); + + pthread_mutex_lock(&reaper->mutex); + } + + pthread_mutex_unlock(&reaper->mutex); +} + +void lightrec_reaper_pause(struct reaper *reaper) +{ + atomic_fetch_add_explicit(&reaper->sem, 1, memory_order_relaxed); +} + +void lightrec_reaper_continue(struct reaper *reaper) +{ + atomic_fetch_sub_explicit(&reaper->sem, 1, memory_order_relaxed); +} diff --git a/pool/shard006/C/0117287_strfunc.c b/pool/shard006/C/0117287_strfunc.c new file mode 100644 index 0000000000000000000000000000000000000000..f023cfb39b350395a8202b2692fbc86561bcb194 --- /dev/null +++ b/pool/shard006/C/0117287_strfunc.c @@ -0,0 +1,33 @@ +#include +#include +void main() +{ + char str1[31],str2[31]; + strcpy(str1, "Apple is sweet"); + strcpy(str2,str1); + puts(str2); + + char a[18]="Microsoft ",b[]=" word"; + strcat(a,b); puts(a); + strcat(a,"97"); puts(a); + + char pass_str[80]; + int i = 0; + while (1) + { + printf("请输入密码:\n"); + gets(pass_str); + if (strcmp(pass_str, "mypass") != 0) + printf("口令错误,"); + else + { + printf("口令正确!"); + break; /*输入正确的密码,中止循环*/ + } + i++; + if (i == 3) + exit(0); //stdlib.h + } + + getchar(); +} \ No newline at end of file diff --git a/pool/shard006/C/0117293_hdmi_tx_hdcp.c b/pool/shard006/C/0117293_hdmi_tx_hdcp.c new file mode 100644 index 0000000000000000000000000000000000000000..eac34f888a4e4630809ed3c3478ca869aba21e5a --- /dev/null +++ b/pool/shard006/C/0117293_hdmi_tx_hdcp.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include + +#include "hdmi_info_global.h" +#include "hdmi_tx_module.h" +#include "m1/hdmi_tx_reg.h" +#include "hdmi_tx_hdcp.h" +/* + hdmi_tx_hdcp.c + version 1.0 +*/ + +// Notic: the HDCP key setting has been moved to uboot +// On MBX project, it is too late for HDCP get from +// other devices + +// buf: store buffer +// endian: 0: little endian 1: big endian +void hdmi_hdcp_get_aksv(char* buf, int endian) +{ + int i; + if(endian ==1) { + for(i = 0;i < 5; i++) { + buf[i] = hdmi_rd_reg(TX_HDCP_SHW_AKSV_0 + i); + } + } + else { + for(i = 0;i < 5; i++) { + buf[i] = hdmi_rd_reg(TX_HDCP_SHW_AKSV_0 + 4 - i); + } + } +} + +void hdmi_hdcp_get_bksv(char* buf, int endian) +{ + int i; + if(endian ==1){ + for(i = 0;i < 5; i++) { + buf[i] = hdmi_rd_reg(TX_HDCP_SHW_BKSV_0 + i); + } + } + else { + for(i = 0;i < 5; i++) { + buf[i] = hdmi_rd_reg(TX_HDCP_SHW_BKSV_0 + 4 - i); + } + } +} + +/* verify ksv, 20 ones and 20 zeroes*/ +int hdcp_ksv_valid(unsigned char * dat) +{ + int i, j, one_num = 0; + for(i = 0; i < 5; i++){ + for(j=0;j<8;j++) { + if((dat[i]>>j)&0x1) { + one_num++; + } + } + } + return (one_num == 20); +} + diff --git a/pool/shard006/C/0117296_dqawst.c b/pool/shard006/C/0117296_dqawst.c new file mode 100644 index 0000000000000000000000000000000000000000..fa6b3598c4f9e424526030f727e1334a7434c342 --- /dev/null +++ b/pool/shard006/C/0117296_dqawst.c @@ -0,0 +1,40 @@ +#include +#include +#include +#include "cquadpack.h" + +double f(double x, void* user_data) +{ + double result; + result = 0.0; + if (x > 0.0) result = (1.0/pow(1.0+log(x)*log(x),2.0)); + return result; +} + +int main() +{ + double a,b,alfa,beta,epsabs,epsrel,abserr,result; + int wgtfunc,neval,ier; + +/* a and b are the integration limits */ + a = 0.0; + b = 1.0; + +/* alfa, beta and wgtfunc determine the weight function */ + alfa = 0.0; + beta = 0.0; + wgtfunc = 2; + +/* epsabs and epsrel determine the accuracy requirement */ + epsabs = 0.0; + epsrel = 1.0e-5; + + result = dqaws(f,a,b,alfa,beta,wgtfunc,epsabs,epsrel,&abserr, + &neval,&ier,0); + + printf("Integral approximation = %.12lf\n",result); + printf("Estimate of absolute error = %.12lf\n",abserr); + printf("Number of function evaluations = %d\n",neval); + printf("Error code = %d\n",ier); + return 0; +} diff --git a/pool/shard006/C/0117298_idmap.c b/pool/shard006/C/0117298_idmap.c new file mode 100644 index 0000000000000000000000000000000000000000..27b3b50a35e1d3cb0ffab69e344a9e9675f331de --- /dev/null +++ b/pool/shard006/C/0117298_idmap.c @@ -0,0 +1,162 @@ +#include + +#include +#include +#include +#include +#include +#include + + +/** 20150620 + * 커널 이미지의 밖을 접근한다. + * Note: accesses outside of the kernel image and the identity map area + * are not supported on any CPU using the idmap tables as its current + * page tables. + **/ +pgd_t *idmap_pgd; + +#ifdef CONFIG_ARM_LPAE +static void idmap_add_pmd(pud_t *pud, unsigned long addr, unsigned long end, + unsigned long prot) +{ + pmd_t *pmd; + unsigned long next; + + if (pud_none_or_clear_bad(pud) || (pud_val(*pud) & L_PGD_SWAPPER)) { + pmd = pmd_alloc_one(&init_mm, addr); + if (!pmd) { + pr_warning("Failed to allocate identity pmd.\n"); + return; + } + pud_populate(&init_mm, pud, pmd); + pmd += pmd_index(addr); + } else + pmd = pmd_offset(pud, addr); + + do { + next = pmd_addr_end(addr, end); + *pmd = __pmd((addr & PMD_MASK) | prot); + flush_pmd_entry(pmd); + } while (pmd++, addr = next, addr != end); +} +#else /* !CONFIG_ARM_LPAE */ +static void idmap_add_pmd(pud_t *pud, unsigned long addr, unsigned long end, + unsigned long prot) +{ + pmd_t *pmd = pmd_offset(pud, addr); + + addr = (addr & PMD_MASK) | prot; + pmd[0] = __pmd(addr); + addr += SECTION_SIZE; + pmd[1] = __pmd(addr); + flush_pmd_entry(pmd); +} +#endif /* CONFIG_ARM_LPAE */ + +static void idmap_add_pud(pgd_t *pgd, unsigned long addr, unsigned long end, + unsigned long prot) +{ + pud_t *pud = pud_offset(pgd, addr); + unsigned long next; + + do { + next = pud_addr_end(addr, end); + idmap_add_pmd(pud, addr, next, prot); + } while (pud++, addr = next, addr != end); +} + +/** 20150620 + * addr ~ end 영역을 pgd 에 매핑시킨다. + **/ +static void identity_mapping_add(pgd_t *pgd, unsigned long addr, unsigned long end) +{ + unsigned long prot, next; + + /** 20150620 + * SECTION, Read/Write Access 속성을 지정한다. + **/ + prot = PMD_TYPE_SECT | PMD_SECT_AP_WRITE | PMD_SECT_AF; + /** 20150620 + * cpu_architecture는 ARMv7이다. + **/ + if (cpu_architecture() <= CPU_ARCH_ARMv5TEJ && !cpu_is_xscale()) + prot |= PMD_BIT4; + + /** 20150620 + * addr부터 end까지 영역을 mapping 시킨다. + * + * pgd_index에 해당하는 address는 보통 가상메모리를 주고, 그에 해당하는 + * entry의 위치를 찾아오기 위함인데, 여기서 넘어온 address는 physical이다. + * 물리주소를 가상주소와 동일하게 매핑하기 위한 것이다. + **/ + pgd += pgd_index(addr); + do { + next = pgd_addr_end(addr, end); + idmap_add_pud(pgd, addr, next, prot); + } while (pgd++, addr = next, addr != end); +} + +/** 20150620 + * section의 시작과 끝. + * + * __idmap으로 section을 지정하면 이 영역에 위치시킬 수 있다. + * 또는 assembly에서 .pushsection .idmap.text로 직접 지정한다. + **/ +extern char __idmap_text_start[], __idmap_text_end[]; + +/** 20150613 + * idmap page table을 위한 초기화를 한다. + * + * page table을 새로 할당 받고, 기존의 page table에서 커널 영역에 해당하는 부분을 복사한다. + * idmap_start ~ idmap_end 사이의 영역에 대해 page table에 mapping 시킨다. + **/ +static int __init init_static_idmap(void) +{ + phys_addr_t idmap_start, idmap_end; + + /** 20150620 + * idmap을 위한 L1 page table을 할당받는다. + **/ + idmap_pgd = pgd_alloc(&init_mm); + if (!idmap_pgd) + return -ENOMEM; + + /* Add an identity mapping for the physical address of the section. */ + /** 20150620 + * idmap 영역을 identity mapping으로 추가하기 위해 물리 주소를 받아온다. + **/ + idmap_start = virt_to_phys((void *)__idmap_text_start); + idmap_end = virt_to_phys((void *)__idmap_text_end); + + pr_info("Setting up static identity map for 0x%llx - 0x%llx\n", + (long long)idmap_start, (long long)idmap_end); + /** 20150620 + * idmap_pgd에 idmap_start ~ idmap_end 영역에 대한 mapping을 추가한다. + * 물리주소와 가상주소를 동일하게 매핑시킨다. + * + * kernel 빌드 후 System.map을 확인하면 __idmap_text_start ~ __idmap_text_end + * 사이의 심볼을 확인할 수 있다. + **/ + identity_mapping_add(idmap_pgd, idmap_start, idmap_end); + + return 0; +} +early_initcall(init_static_idmap); + +/* + * In order to soft-boot, we need to switch to a 1:1 mapping for the + * cpu_reset functions. This will then ensure that we have predictable + * results when turning off the mmu. + */ +void setup_mm_for_reboot(void) +{ + /* Clean and invalidate L1. */ + flush_cache_all(); + + /* Switch to the identity mapping. */ + cpu_switch_mm(idmap_pgd, &init_mm); + + /* Flush the TLB. */ + local_flush_tlb_all(); +} diff --git a/pool/shard006/C/0117299_spy.c b/pool/shard006/C/0117299_spy.c new file mode 100644 index 0000000000000000000000000000000000000000..94b55d47d46bbb8f5895ccdc8c4e3d5cf29944f2 --- /dev/null +++ b/pool/shard006/C/0117299_spy.c @@ -0,0 +1,186 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "parson.h" + +char *spy_memory(); +void spy_on_memory(); +void spy_on_waiting(); + +int main(int argc, const char *argv[]) +{ + bool op_exit = false; + int code; + char *serialized_string = NULL; + do + { + puts("Algoritmos:"); + puts("[1] - Estado de la memoria."); + puts("[2] - Estado de procesos."); + puts("[0] - Salir"); + printf("Ingrese su eleccion (0-2): "); + scanf("%d", &code); + switch (code) + { + case 0: + op_exit = true; + break; + case 1: + serialized_string = spy_memory(); + puts(serialized_string); + break; + case 2: + printf("Procesos en espera:\n"); + spy_on_waiting(); + printf("Procesos en memoria:\n"); + spy_on_memory(); + break; + default: + puts("Opcion incorrecta."); + break; + } + } while (op_exit == false); + return 0; +} + +char *spy_memory() +{ + + const char *filepath = "/tmp/mmapped.bin"; + + int fd = open(filepath, O_RDONLY, (mode_t)0600); + + if (fd == -1) + { + perror("Error opening file for writing"); + exit(EXIT_FAILURE); + } + + struct stat fileInfo = {0}; + + if (fstat(fd, &fileInfo) == -1) + { + perror("Error getting the file size"); + exit(EXIT_FAILURE); + } + + if (fileInfo.st_size == 0) + { + fprintf(stderr, "Error: File is empty, nothing to do\n"); + exit(EXIT_FAILURE); + } + + printf("File size is %ji\n", (intmax_t)fileInfo.st_size); + + char *map = mmap(0, fileInfo.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) + { + close(fd); + perror("Error mmapping the file"); + exit(EXIT_FAILURE); + } + + JSON_Value *output_value = NULL; + output_value = json_parse_string(map); + char *serialized_string = NULL; + serialized_string = json_serialize_to_string_pretty(output_value); + + //puts(serialized_string); + + // Don't forget to free the mmapped memory + if (munmap(map, fileInfo.st_size) == -1) + { + close(fd); + perror("Error un-mmapping the file"); + exit(EXIT_FAILURE); + } + + // Un-mmaping doesn't close the file, so we still need to do that. + close(fd); + return serialized_string; +} + +void spy_on_memory() +{ + char *serialized_string = NULL; + serialized_string = spy_memory(); + //puts(serialized_string); + JSON_Value *mem_value = json_parse_string(serialized_string); + JSON_Array *mem_arr = json_value_get_array(mem_value); + int n = json_array_get_count(mem_arr); + JSON_Value *to_print_value; + for (int i = 0; i < n; i++) + { + JSON_Object *root_object = json_array_get_object(mem_arr, i); + JSON_Object *processes = json_object_get_object(root_object, "processes"); + + to_print_value = json_object_get_wrapping_value(processes); + if (!json_value_equals(to_print_value, json_value_init_object())) + { + serialized_string = NULL; + serialized_string = json_serialize_to_string_pretty(to_print_value); + puts(serialized_string); + } + } +} + +void spy_on_waiting() +{ + + const char *filepath = "/tmp/mmapped_pro_on_waiting.bin"; + + int fd = open(filepath, O_RDONLY, (mode_t)0600); + + if (fd == -1) + { + perror("Error opening file for writing"); + exit(EXIT_FAILURE); + } + + struct stat fileInfo = {0}; + + if (fstat(fd, &fileInfo) == -1) + { + perror("Error getting the file size"); + exit(EXIT_FAILURE); + } + + if (fileInfo.st_size == 0) + { + fprintf(stderr, "Error: File is empty, nothing to do\n"); + exit(EXIT_FAILURE); + } + + printf("File size is %ji\n", (intmax_t)fileInfo.st_size); + + char *map = mmap(0, fileInfo.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) + { + close(fd); + perror("Error mmapping the file"); + exit(EXIT_FAILURE); + } + + JSON_Value *output_value = NULL; + output_value = json_parse_string(map); + char *serialized_string = NULL; + serialized_string = json_serialize_to_string_pretty(output_value); + + puts(serialized_string); + + // Don't forget to free the mmapped memory + if (munmap(map, fileInfo.st_size) == -1) + { + close(fd); + perror("Error un-mmapping the file"); + exit(EXIT_FAILURE); + } + + // Un-mmaping doesn't close the file, so we still need to do that. + close(fd); +} \ No newline at end of file diff --git a/pool/shard006/C/0117302_xmalloc.c b/pool/shard006/C/0117302_xmalloc.c new file mode 100644 index 0000000000000000000000000000000000000000..92eca4e58b7e4512ab3014a607a1de6dffce7af1 --- /dev/null +++ b/pool/shard006/C/0117302_xmalloc.c @@ -0,0 +1,141 @@ +/* + * transsip - the telephony network + * By Daniel Borkmann + * Copyright 2011 Daniel Borkmann , + * Swiss federal institute of technology (ETH Zurich) + * Subject to the GPL, version 2. + */ + +#include +#include +#include +#include +#include +#include + +#ifndef SIZE_T_MAX +# define SIZE_T_MAX ((size_t) ~0) +#endif + +#include "compiler.h" +#include "xmalloc.h" +#include "strlcpy.h" +#include "die.h" + +__hidden void *xmalloc(size_t size) +{ + void *ptr; + if (size == 0) + panic("xmalloc: zero size\n"); + ptr = malloc(size); + if (ptr == NULL) + panic("xmalloc: out of memory (allocating %zu bytes)\n", size); + return ptr; +} + +__hidden void *xvalloc(size_t size) +{ + void *ptr; + if (size == 0) + panic("xmalloc: zero size\n"); + ptr = valloc(size); + if (ptr == NULL) + panic("xvalloc: out of memory (allocating %zu bytes)\n", size); + return ptr; +} + +__hidden void *xzmalloc(size_t size) +{ + void *ptr; + if (size == 0) + panic("xzmalloc: zero size\n"); + ptr = malloc(size); + if (ptr == NULL) + panic("xzmalloc: out of memory (allocating %zu bytes)\n", size); + memset(ptr, 0, size); + return ptr; +} + +__hidden void *xmalloc_aligned(size_t size, size_t alignment) +{ + int ret; + void *ptr; + if (size == 0) + panic("xmalloc_aligned: zero size\n"); + ret = posix_memalign(&ptr, alignment, size); + if (ret != 0) + panic("xmalloc_aligned: out of memory (allocating %zu bytes)\n", + size); + return ptr; +} + +__hidden void *xmallocz(size_t size) +{ + void *ptr; + if (size + 1 < size) + panic("xmallocz: data too large to fit " + "into virtual memory space\n"); + ptr = xmalloc(size + 1); + ((char *) ptr)[size] = 0; + return ptr; +} + +__hidden void *xmemdupz(const void *data, size_t len) +{ + return memcpy(xmallocz(len), data, len); +} + +__hidden void *xrealloc(void *ptr, size_t nmemb, size_t size) +{ + void *new_ptr; + size_t new_size = nmemb * size; + if (new_size == 0) + panic("xrealloc: zero size\n"); + if (SIZE_T_MAX / nmemb < size) + panic("xrealloc: nmemb * size > SIZE_T_MAX\n"); + if (ptr == NULL) + new_ptr = malloc(new_size); + else + new_ptr = realloc(ptr, new_size); + if (new_ptr == NULL) + panic("xrealloc: out of memory (size %zu bytes)\n", new_size); + return new_ptr; +} + +__hidden void xfree(void *ptr) +{ + if (ptr == NULL) + panic("xfree: NULL pointer given as argument\n"); + free(ptr); +} + +__hidden char *xstrdup(const char *str) +{ + size_t len; + char *cp; + len = strlen(str) + 1; + cp = xmalloc(len); + strlcpy(cp, str, len); + return cp; +} + +__hidden char *xstrndup(const char *str, size_t size) +{ + size_t len; + char *cp; + len = strlen(str) + 1; + if (size < len) + len = size; + cp = xmalloc(len); + strlcpy(cp, str, len); + return cp; +} + +__hidden int xdup(int fd) +{ + int ret = dup(fd); + if (ret < 0) + panic("xdup: dup failed\n"); + return ret; +} + diff --git a/pool/shard006/C/0117305_pool.c b/pool/shard006/C/0117305_pool.c new file mode 100644 index 0000000000000000000000000000000000000000..6f48118e5c98daa95ddc08b9ce2102ccf1c25725 --- /dev/null +++ b/pool/shard006/C/0117305_pool.c @@ -0,0 +1,74 @@ + +#include +#include + +#define ITEM_COUNT 10 + +typedef struct { + int data1; + int data2; +} my_data_t; + +void test_do(test_context_t *test) +{ + pool_ctxt_t pool; + my_data_t *tmp; + int i; + void *buffer[ITEM_COUNT]; + + + + test_mark(test, "pool functions"); + + test_group_start(test, "Setup and sanity check"); + { + int ret = pool_init( &pool, sizeof(my_data_t), ITEM_COUNT); + test_not_equal(test, "could init pool", ret, 0); + + } + test_group_end(test); + + test_group_start(test, "get pool items"); + { + for(i = 0; i < ITEM_COUNT; i++) { + buffer[i] = pool_alloc(&pool); + test_not_null( test, "getting items from pool", buffer[i] ); + if(buffer[i]) { + tmp = (my_data_t *) buffer[i]; + tmp->data1 = i; + tmp->data2 = i; + } + } + tmp = pool_alloc(& pool); + test_null( test, "Pool must be empty", tmp); + } + test_group_end(test); + + test_group_start(test, "return pool items"); + { + my_data_t *tmp1, *tmp2, *tmp3, *tmp4; + + /* return two items to pool */ + tmp1 = buffer[0]; + tmp2 = buffer[1]; + + pool_free( &pool, tmp1); + pool_free( &pool, tmp2); + + /* now when we allocate we must get the same two back */ + tmp3 = pool_alloc(& pool); + tmp4 = pool_alloc(& pool); + + if( (tmp1 == tmp3 && tmp2 == tmp4) || (tmp1 == tmp4 && tmp2 == tmp3) ) { + /* got them ! */ + } else { + test_fail(test, "Did not get the freed items back"); + } + + tmp = pool_alloc(& pool); + test_null( test, "Pool must be empty (again)", tmp); + } + + test_group_end(test); +} + diff --git a/pool/shard006/C/0117309_main.c b/pool/shard006/C/0117309_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6fd54d3673375ad16c839343a0d7c9d5e9c0971d --- /dev/null +++ b/pool/shard006/C/0117309_main.c @@ -0,0 +1,218 @@ +/** + ****************************************************************************** + * @file TIM/TIM_OCActive/main.c + * @author MCD Application Team + * @version V1.1.0 + * @date 18-January-2013 + * @brief Main program body + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2013 STMicroelectronics

+ * + * 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 "main.h" + +/** @addtogroup STM32F4xx_StdPeriph_Examples + * @{ + */ + +/** @addtogroup TIM_OCActive + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; +TIM_OCInitTypeDef TIM_OCInitStructure; + +uint16_t uhCCR1_Val = 1000; +uint16_t uhCCR2_Val = 500; +uint16_t uhCCR3_Val = 250; +uint16_t uhCCR4_Val = 125; +uint16_t uhPrescalerValue = 0; + +/* Private function prototypes -----------------------------------------------*/ +static void TIM_Config(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program + * @param None + * @retval None + */ +int main(void) +{ + /*!< At this stage the microcontroller clock setting is already configured, + this is done through SystemInit() function which is called from startup + files (startup_stm32f40xx.s/startup_stm32f427x.s) before to branch to + application main. + To reconfigure the default setting of SystemInit() function, refer to + system_stm32f4xx.c file + */ + + /* TIM Configuration */ + TIM_Config(); + + /* Time base default values configuration */ + TIM_TimeBaseStructInit(&TIM_TimeBaseStructure); + + /* Output compare default values configuration */ + TIM_OCStructInit(&TIM_OCInitStructure); + + + /* --------------------------------------------------------------------------- + TIM3 Configuration: Output Compare Active Mode: + In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1), + since APB1 prescaler is different from 1. + TIM3CLK = 2 * PCLK1 + PCLK1 = HCLK / 4 + => TIM3CLK = HCLK / 2 = SystemCoreClock /2 + + To get TIM3 counter clock at 2 KHz, the prescaler is computed as follows: + Prescaler = (TIM3CLK / TIM3 counter clock) - 1 + Prescaler = ((SystemCoreClock /2) /1 KHz) - 1 + + Generate 4 signals with 4 different delays: + TIM3_CH1 delay = uhCCR1_Val/TIM3 counter clock = 500 ms + TIM3_CH2 delay = uhCCR2_Val/TIM3 counter clock = 250 ms + TIM3_CH3 delay = uhCCR3_Val/TIM3 counter clock = 125 ms + TIM3_CH4 delay = uhCCR4_Val/TIM3 counter clock = 62.5 ms + + Note: + SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file. + Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate() + function to update SystemCoreClock variable value. Otherwise, any configuration + based on this variable will be incorrect. + + --------------------------------------------------------------------------- */ + + /* Compute the prescaler value */ + uhPrescalerValue = (uint16_t) ((SystemCoreClock / 2) / 2000) - 1; + + /* Time base configuration */ + TIM_TimeBaseStructure.TIM_Period = 65535; + TIM_TimeBaseStructure.TIM_Prescaler = uhPrescalerValue; + TIM_TimeBaseStructure.TIM_ClockDivision = 0; + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + + TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); + + /* Output Compare Active Mode configuration: Channel1 */ + TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Active; + TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; + TIM_OCInitStructure.TIM_Pulse = uhCCR1_Val; + TIM_OC1Init(TIM3, &TIM_OCInitStructure); + + TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable); + TIM_ARRPreloadConfig(TIM3, DISABLE); + /* Output Compare Active Mode configuration: Channel2 */ + TIM_OCInitStructure.TIM_Pulse = uhCCR2_Val; + TIM_OC2Init(TIM3, &TIM_OCInitStructure); + + TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Disable); + + /* Output Compare Active Mode configuration: Channel3 */ + TIM_OCInitStructure.TIM_Pulse = uhCCR3_Val; + TIM_OC3Init(TIM3, &TIM_OCInitStructure); + + TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable); + + /* Output Compare Active Mode configuration: Channel4 */ + TIM_OCInitStructure.TIM_Pulse = uhCCR4_Val; + TIM_OC4Init(TIM3, &TIM_OCInitStructure); + + TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable); + + /* TIM3 enable counter */ + TIM_Cmd(TIM3, ENABLE); + + TIM_GenerateEvent(TIM3, TIM_EventSource_Update); + + /* Turn on LED1 */ + STM_EVAL_LEDOn(LED1); + + while (1) + { + } +} + +/** + * @brief Configure the TIM3 pins. + * @param None + * @retval None + */ +static void TIM_Config(void) +{ + GPIO_InitTypeDef GPIO_InitStructure; + + /* TIM3 clock enable */ + RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); + + /* GPIOC clock enable */ + RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE); + + /* GPIOC Configuration: TIM3 CH1 (PC6), TIM3 CH2 (PC7), TIM3 CH2 (PC8) and TIM3 CH4 (PC9) */ + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; + GPIO_Init(GPIOC, &GPIO_InitStructure); + + /* Connect TIM Channels to AF2 */ + GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_TIM3); + GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_TIM3); + GPIO_PinAFConfig(GPIOC, GPIO_PinSource8, GPIO_AF_TIM3); + GPIO_PinAFConfig(GPIOC, GPIO_PinSource9, GPIO_AF_TIM3); + + /* Initialize Leds mounted on STM324xG-EVAL/STM324x7I-EVAL boards */ + STM_EVAL_LEDInit(LED1); +} + +#ifdef USE_FULL_ASSERT + +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + + while (1) + {} +} +#endif + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0117311_utent.c b/pool/shard006/C/0117311_utent.c new file mode 100644 index 0000000000000000000000000000000000000000..3f5f559593a8213e1b32ec564b19df4d512e0ce8 --- /dev/null +++ b/pool/shard006/C/0117311_utent.c @@ -0,0 +1,109 @@ +#include +#include +#include +#include + +static const char *utmp_file_name = _PATH_UTMP; +static int fd = -1; +static off_t utmp_current = 0; + +static int lock_record(int type) { + struct flock fl; + fl.l_whence = SEEK_CUR; + fl.l_start = 0; + fl.l_len = sizeof(struct utmp); + fl.l_pid = 0; + fl.l_type = type; + return fcntl(fd, F_SETLKW, &fl); +} + +static int unlock_record() { + struct flock fl; + fl.l_whence = SEEK_CUR; + fl.l_start = -sizeof(struct utmp); + fl.l_len = sizeof(struct utmp); + fl.l_pid = 0; + fl.l_type = F_UNLCK; + return fcntl(fd, F_SETLK, &fl); +} + +void utmpname(const char *file) { + if (file) + utmp_file_name = file; + else + utmp_file_name = _PATH_UTMP; +} + +void setutent() { + if (fd<0) fd = open(utmp_file_name,O_RDWR); + if (fd<0) fd = open(utmp_file_name,O_RDONLY); + fcntl (fd, F_SETFD, FD_CLOEXEC); + utmp_current = lseek(fd,0,SEEK_SET); +} + +void endutent() { + if (fd<0) return; + close(fd); fd=-1; + utmp_current = 0; +} + +struct utmp *getutent(void) { + static struct utmp getutent_tmp; + ssize_t ret; + + if (fd<0) { + setutent(); + if (fd<0) return 0; + } + utmp_current = lseek (fd, 0, SEEK_CUR); + if (lock_record(F_RDLCK)) return 0; + ret=read(fd, &getutent_tmp, sizeof(struct utmp)); + unlock_record(); + if (ret<1) return 0; + return &getutent_tmp; +} + +struct utmp *getutid(struct utmp *ut) { + struct utmp *tmp; + + while ((tmp = getutent())) { + if (ut->ut_type && (ut->ut_type <= OLD_TIME)) { + if (ut->ut_type == tmp->ut_type) break; + } + if ((ut->ut_type >= INIT_PROCESS) && (ut->ut_type <= DEAD_PROCESS)) { + if (!strncmp(ut->ut_id,tmp->ut_id,4)) break; + } + } + return tmp; +} + +struct utmp *getutline(struct utmp *ut) { + struct utmp *tmp; + + while ((tmp = getutent())) { + if ((tmp->ut_type == USER_PROCESS) || (tmp->ut_type == LOGIN_PROCESS)) { + if (!strncmp(ut->ut_line,tmp->ut_line,UT_LINESIZE)) break; + } + } + return tmp; +} + +void pututline(struct utmp *ut) { + struct utmp *tmp; + + /* Seek to the current record before searching. */ + lseek (fd, utmp_current, SEEK_SET); + if ((tmp = getutid(ut))) { + lseek(fd, - (off_t)sizeof(struct utmp), SEEK_CUR); + if (lock_record(F_WRLCK)) return; + write(fd, ut, sizeof(struct utmp)); + utmp_current += sizeof(struct utmp); + } + else { + utmp_current = lseek(fd, 0, SEEK_END); + if (lock_record(F_WRLCK)) return; + write(fd, ut, sizeof(struct utmp)); + } + unlock_record(); +} + diff --git a/pool/shard006/C/0117315_tclLoadDld.c b/pool/shard006/C/0117315_tclLoadDld.c new file mode 100644 index 0000000000000000000000000000000000000000..ebb5d6bced29873667b43ce03c5edb6d8c37ce0b --- /dev/null +++ b/pool/shard006/C/0117315_tclLoadDld.c @@ -0,0 +1,163 @@ +/* + * tclLoadDld.c -- + * + * This procedure provides a version of the TclLoadFile that + * works with the "dld_link" and "dld_get_func" library procedures + * for dynamic loading. It has been tested on Linux 1.1.95 and + * dld-3.2.7. This file probably isn't needed anymore, since it + * makes more sense to use "dl_open" etc. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * RCS: @(#) $Id$ + */ + +#include "tclInt.h" +#include "dld.h" + +/* + * In some systems, like SunOS 4.1.3, the RTLD_NOW flag isn't defined + * and this argument to dlopen must always be 1. + */ + +#ifndef RTLD_NOW +# define RTLD_NOW 1 +#endif + +/* + *---------------------------------------------------------------------- + * + * TclpLoadFile -- + * + * Dynamically loads a binary code file into memory and returns + * the addresses of two procedures within that file, if they + * are defined. + * + * Results: + * A standard Tcl completion code. If an error occurs, an error + * message is left in the interp's result. *proc1Ptr and *proc2Ptr + * are filled in with the addresses of the symbols given by + * *sym1 and *sym2, or NULL if those symbols can't be found. + * + * Side effects: + * New code suddenly appears in memory. + * + *---------------------------------------------------------------------- + */ + +int +TclpLoadFile(interp, fileName, sym1, sym2, proc1Ptr, proc2Ptr, clientDataPtr) + Tcl_Interp *interp; /* Used for error reporting. */ + char *fileName; /* Name of the file containing the desired + * code. */ + char *sym1, *sym2; /* Names of two procedures to look up in + * the file's symbol table. */ + Tcl_PackageInitProc **proc1Ptr, **proc2Ptr; + /* Where to return the addresses corresponding + * to sym1 and sym2. */ + ClientData *clientDataPtr; /* Filled with token for dynamically loaded + * file which will be passed back to + * TclpUnloadFile() to unload the file. */ +{ + static int firstTime = 1; + int returnCode; + + /* + * The dld package needs to know the pathname to the tcl binary. + * If that's not know, return an error. + */ + + if (firstTime) { + if (tclExecutableName == NULL) { + Tcl_SetResult(interp, + "don't know name of application binary file, so can't initialize dynamic loader", + TCL_STATIC); + return TCL_ERROR; + } + returnCode = dld_init(tclExecutableName); + if (returnCode != 0) { + Tcl_AppendResult(interp, + "initialization failed for dynamic loader: ", + dld_strerror(returnCode), (char *) NULL); + return TCL_ERROR; + } + firstTime = 0; + } + + if ((returnCode = dld_link(fileName)) != 0) { + Tcl_AppendResult(interp, "couldn't load file \"", fileName, + "\": ", dld_strerror(returnCode), (char *) NULL); + return TCL_ERROR; + } + *proc1Ptr = (Tcl_PackageInitProc *) dld_get_func(sym1); + *proc2Ptr = (Tcl_PackageInitProc *) dld_get_func(sym2); + *clientDataPtr = strcpy( + (char *) ckalloc((unsigned) (strlen(fileName) + 1)), fileName); + return TCL_OK; +} + +/* + *---------------------------------------------------------------------- + * + * TclpUnloadFile -- + * + * Unloads a dynamically loaded binary code file from memory. + * Code pointers in the formerly loaded file are no longer valid + * after calling this function. + * + * Results: + * None. + * + * Side effects: + * Code removed from memory. + * + *---------------------------------------------------------------------- + */ + +void +TclpUnloadFile(clientData) + ClientData clientData; /* ClientData returned by a previous call + * to TclpLoadFile(). The clientData is + * a token that represents the loaded + * file. */ +{ + char *fileName; + + handle = (char *) clientData; + dld_unlink_by_file(handle, 0); + ckfree(handle); +} + +/* + *---------------------------------------------------------------------- + * + * TclGuessPackageName -- + * + * If the "load" command is invoked without providing a package + * name, this procedure is invoked to try to figure it out. + * + * Results: + * Always returns 0 to indicate that we couldn't figure out a + * package name; generic code will then try to guess the package + * from the file name. A return value of 1 would have meant that + * we figured out the package name and put it in bufPtr. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TclGuessPackageName(fileName, bufPtr) + char *fileName; /* Name of file containing package (already + * translated to local form if needed). */ + Tcl_DString *bufPtr; /* Initialized empty dstring. Append + * package name to this if possible. */ +{ + return 0; +} + diff --git a/pool/shard006/C/0117317_div.c b/pool/shard006/C/0117317_div.c new file mode 100644 index 0000000000000000000000000000000000000000..8af15e61923dc2aebb6476dd2bbcfb4397e7318a --- /dev/null +++ b/pool/shard006/C/0117317_div.c @@ -0,0 +1,214 @@ +/* + * libx/div.c + */ + +#include + +static const unsigned char byte_reverse_table[] = { + 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, + 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, + 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, + 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, + 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, + 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, + 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, + 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, + 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, + 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, + 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, + 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, + 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, + 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, + 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, + 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF +}; + +static inline u32_t do_fls64(u64_t value) +{ + u32_t num_bits = 0; + if(value & 0xFFFF000000000000ULL) + { + num_bits += 16; + value = value >> 16; + } + if(value & 0x0000FFFF00000000ULL) + { + num_bits += 16; + value = value >> 16; + } + if(value & 0x00000000FFFF0000ULL) + { + num_bits += 16; + value = value >> 16; + } + if(value & 0x000000000000FF00ULL) + { + num_bits += 8; + value = value >> 8; + } + if(value & 0x00000000000000F0ULL) + { + num_bits += 4; + value = value >> 4; + } + if(value & 0x000000000000000CULL) + { + num_bits += 2; + value = value >> 2; + } + if(value & 0x0000000000000003ULL) + { + num_bits += 2; + value = value >> 2; + } + return num_bits; +} + +u64_t do_udiv64(u64_t dividend, u64_t divisor, u64_t * remainder) +{ + u64_t quotient, remaind; + u32_t num_bits; + register u8_t * p, * q; + + if(divisor == 0) + { + while(1); + } + + if(dividend <= divisor) + { + remaind = divisor - dividend; + if(remainder) + { + *remainder = (remaind) ? dividend : 0; + } + return (remaind) ? 0 : 1; + } + + remaind = 0; + num_bits = do_fls64(dividend); + dividend = dividend << (64 - num_bits); + p = (u8_t *) ÷nd; + q = (u8_t *) "ient; + q[7] = byte_reverse_table[p[0]]; + q[6] = byte_reverse_table[p[1]]; + q[5] = byte_reverse_table[p[2]]; + q[4] = byte_reverse_table[p[3]]; + q[3] = byte_reverse_table[p[4]]; + q[2] = byte_reverse_table[p[5]]; + q[1] = byte_reverse_table[p[6]]; + q[0] = byte_reverse_table[p[7]]; + dividend = quotient; + quotient = 0; + + while(num_bits) + { + remaind = (remaind << 1) | (dividend & 0x1); + dividend = dividend >> 1; + if(remaind < divisor) + { + quotient = ((quotient) << 1) | 0; + } + else + { + quotient = ((quotient) << 1) | 1; + remaind = remaind - divisor; + } + num_bits--; + } + + if(remainder) + { + *remainder = remaind; + } + + return quotient; +} + +static inline u32_t do_fls32(u32_t value) +{ + u32_t num_bits = 0; + if(value & 0xFFFF0000) + { + num_bits += 16; + value = value >> 16; + } + if(value & 0x0000FF00) + { + num_bits += 8; + value = value >> 8; + } + if(value & 0x000000F0) + { + num_bits += 4; + value = value >> 4; + } + if(value & 0x0000000C) + { + num_bits += 2; + value = value >> 2; + } + if(value & 0x00000003) + { + num_bits += 2; + value = value >> 2; + } + return num_bits; +} + +u32_t do_udiv32(u32_t dividend, u32_t divisor, u32_t * remainder) +{ + register u8_t *p, *q; + u32_t num_bits, quotient, remaind; + + if(divisor == 0) + { + while(1) + ; + } + + if(dividend <= divisor) + { + remaind = divisor - dividend; + if(remainder) + { + *remainder = (remaind) ? dividend : 0; + } + return (remaind) ? 0 : 1; + } + + remaind = 0; + num_bits = do_fls32(dividend); + dividend = dividend << (32 - num_bits); + p = (u8_t *) ÷nd; + q = (u8_t *) "ient; + q[3] = byte_reverse_table[p[0]]; + q[2] = byte_reverse_table[p[1]]; + q[1] = byte_reverse_table[p[2]]; + q[0] = byte_reverse_table[p[3]]; + dividend = quotient; + quotient = 0; + + while(num_bits) + { + remaind = (remaind << 1) | (dividend & 0x1); + dividend = dividend >> 1; + if(remaind < divisor) + { + quotient = ((quotient) << 1) | 0; + } + else + { + quotient = ((quotient) << 1) | 1; + remaind = remaind - divisor; + } + num_bits--; + } + + if(remainder) + { + *remainder = remaind; + } + + return quotient; +} diff --git a/pool/shard006/C/0117334_eusci_a_spi_ex1_slave.c b/pool/shard006/C/0117334_eusci_a_spi_ex1_slave.c new file mode 100644 index 0000000000000000000000000000000000000000..ebd7acbc80f3298dfbe79f41076fea2673025e21 --- /dev/null +++ b/pool/shard006/C/0117334_eusci_a_spi_ex1_slave.c @@ -0,0 +1,189 @@ +/* --COPYRIGHT--,BSD + * Copyright (c) 2014, Texas Instruments Incorporated + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * 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 Texas Instruments Incorporated 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. + * --/COPYRIGHT--*/ +//***************************************************************************** +//! SPI slave talks to SPI master using 3-wire mode. Data is received +//! from master and data from slave is then transmitted back to master. +//! USCI RX ISR is used to handle communication, CPU normally in LPM4. +//! Prior to initial data exchange, master pulses slaves RST for complete +//! reset. +//! +//! Use with eusci_spi_ex1_master code example. If the slave is in +//! debug mode, the reset signal from the master will conflict with slave's +//! JTAG; to work around, use IAR's "Release JTAG on Go" on slave device. If +//! breakpoints are set in slave RX ISR, master must stopped also to avoid +//! overrunning slave RXBUF. +//! +//! Tesed on MSP430FR5969 +//! ----------------- +//! /|\ | | +//! | | | +//! Master---+->|RST | +//! | | +//! | P2.0|-> Data Out (UCA0SIMO) +//! | | +//! | P2.1|<- Data In (UCA0SOMI) +//! | | +//! | P1.5|<- Serial Clock Out (UCA0CLK) +//! +//! This example uses the following peripherals and I/O signals. You must +//! review these and change as needed for your own board: +//! - SPI peripheral +//! - GPIO Port peripheral (for SPI pins) +//! - UCA0SIMO +//! - UCA0SOMI +//! - UCA0CLK +//! +//! This example uses the following interrupt handlers. To use this example +//! in your own application you must add these interrupt handlers to your +//! vector table. +//! - USCI_A0_VECTOR +//! +// +//***************************************************************************** + +#include "driverlib.h" + +uint8_t transmitData = 0x01, receiveData = 0x00; + +void main(void) +{ + //Stop watchdog timer + WDT_A_hold(WDT_A_BASE); + + // Configure Pins for LFXIN + //Set PJ.4 and PJ.5 as Primary Module Function Input. + /* + + * Select Port J + * Set Pin 4, 5 to input Primary Module Function, (LFXIN). + */ + GPIO_setAsPeripheralModuleFunctionInputPin( + GPIO_PORT_PJ, + GPIO_PIN4 + GPIO_PIN5, + GPIO_PRIMARY_MODULE_FUNCTION + ); + + // Configure SPI pins + // Configure Pins for UCA0CLK + //Set P1.5 as Secondary Module Function Input. + /* + + * Select Port 1 + * Set Pin 5 to input Secondary Module Function, (UCA0CLK). + */ + GPIO_setAsPeripheralModuleFunctionInputPin( + GPIO_PORT_P1, + GPIO_PIN5, + GPIO_SECONDARY_MODULE_FUNCTION + ); + // Configure Pins for UCA0TXD/UCA0SIMO, UCA0RXD/UCA0SOMI + //Set P2.0, P2.1 as Secondary Module Function Input. + /* + + * Select Port 2 + * Set Pin 0, 1 to input Secondary Module Function, (UCA0TXD/UCA0SIMO, UCA0RXD/UCA0SOMI). + */ + GPIO_setAsPeripheralModuleFunctionInputPin( + GPIO_PORT_P2, + GPIO_PIN0 + GPIO_PIN1, + GPIO_SECONDARY_MODULE_FUNCTION + ); + + /* + * Disable the GPIO power-on default high-impedance mode to activate + * previously configured port settings + */ + PMM_unlockLPM5(); + + //Initialize slave to MSB first, inactive high clock polarity and 3 wire SPI + EUSCI_A_SPI_slaveInit(EUSCI_A0_BASE, + EUSCI_A_SPI_MSB_FIRST, + EUSCI_A_SPI_PHASE_DATA_CHANGED_ONFIRST_CAPTURED_ON_NEXT, + EUSCI_A_SPI_CLOCKPOLARITY_INACTIVITY_HIGH, + EUSCI_A_SPI_3PIN + ); + + //Enable SPI Module + EUSCI_A_SPI_enable(EUSCI_A0_BASE); + + + EUSCI_A_SPI_enableInterrupt(EUSCI_A0_BASE, + EUSCI_A_SPI_RECEIVE_INTERRUPT + ); + + //Enable Receive interrupt + EUSCI_A_SPI_enableInterrupt(EUSCI_A0_BASE, + EUSCI_A_SPI_RECEIVE_INTERRUPT + ); + + __bis_SR_register(LPM0_bits + GIE); // Enter LPM0, enable interrupts + +} + +//****************************************************************************** +// +//This is the USCI_A0 interrupt vector service routine. +// +//****************************************************************************** +#if defined(__TI_COMPILER_VERSION__) || defined(__IAR_SYSTEMS_ICC__) +#pragma vector=USCI_A0_VECTOR +__interrupt +#elif defined(__GNUC__) +__attribute__((interrupt(USCI_A0_VECTOR))) +#endif +void USCI_A0_ISR(void) +{ + switch (__even_in_range(UCA0IV, 4)) { + //Vector 2 - RXIFG + case 2: + //USCI_A0 TX buffer ready? + while (!EUSCI_A_SPI_getInterruptStatus(EUSCI_A0_BASE, + EUSCI_A_SPI_TRANSMIT_INTERRUPT + )) ; + + //Transmit data to master + EUSCI_A_SPI_transmitData(EUSCI_A0_BASE, + transmitData + ); + + //Receive data from master + receiveData = EUSCI_A_SPI_receiveData(EUSCI_A0_BASE); + + //Increment data to be transmitted + transmitData++; + + break; + + default: break; + } +} + diff --git a/pool/shard006/C/0117345_fpsc.c b/pool/shard006/C/0117345_fpsc.c new file mode 100644 index 0000000000000000000000000000000000000000..8fbd6e6772bbce0dabc2b960dd9406aaa708da00 --- /dev/null +++ b/pool/shard006/C/0117345_fpsc.c @@ -0,0 +1,78 @@ +#include "fpsc.h" + +int fpsc_init(struct fpsc* fpsc, int fps) +{ + fpsc->fps = fps; + fpsc->delta.sec = 0; + fpsc->delta.nsec = 1000000000L/fps; + fpsc->begin.sec = 0; + fpsc->begin.nsec = 0; + fpsc->end.sec = 0; + fpsc->end.nsec = 0; + fpsc->wait.sec = 0; + fpsc->wait.nsec = 0; + fpsc->wait_slice.sec = 0; + fpsc->wait_slice.nsec = 0; + + return OKN_SUCCESS; +} + +int fpsc_fps_set(struct fpsc* fpsc, int fps) +{ + fpsc->fps = fps; + fpsc->delta.nsec = 1000000000L / fps; + + return OKN_SUCCESS; +} + +int fpsc_fps_get(struct fpsc* fpsc, int* fps) +{ + *fps = fpsc->fps; + + return OKN_SUCCESS; +} + +int fpsc_begin(struct fpsc* fpsc) +{ + int ret = okn_time_init(&fpsc->begin); + OKN_RETURN_ON_ERROR(ret); + + return OKN_SUCCESS; +} + +int fpsc_end(struct fpsc* fpsc) +{ + int ret = okn_time_init(&fpsc->end); + OKN_RETURN_ON_ERROR(ret); + + ret = okn_time_sub(&fpsc->diff, &fpsc->end, &fpsc->begin); + OKN_RETURN_ON_ERROR(ret); + + ret = okn_time_sub(&fpsc->wait, &fpsc->delta, &fpsc->diff); + OKN_RETURN_ON_ERROR(ret); + + return OKN_SUCCESS; +} + +int fpsc_wait(struct fpsc* fpsc) +{ + int ret = okn_time_wait(&fpsc->wait); + OKN_RETURN_ON_ERROR(ret); + + return OKN_SUCCESS; +} + +int fpsc_slice(struct fpsc* fpsc, int num) +{ + if(num <= 0) num = 1; + fpsc->wait_slice.nsec = fpsc->wait.nsec / num; + + return OKN_SUCCESS; +} + +int fpsc_slice_wait(struct fpsc* fpsc) +{ + okn_time_init(&fpsc->wait_slice); + + return OKN_SUCCESS; +} diff --git a/pool/shard006/C/0117346_mono2stereo.c b/pool/shard006/C/0117346_mono2stereo.c new file mode 100644 index 0000000000000000000000000000000000000000..2d6d7ade2f87dbe37542fd7824bcb35ee8416596 --- /dev/null +++ b/pool/shard006/C/0117346_mono2stereo.c @@ -0,0 +1,120 @@ +/* + * SATAN, Signal Applications To Any Network + * Copyright (C) 2003 by Anton Persson & Johan Thim + * Copyright (C) 2005 by Anton Persson + * Copyright (C) 2006 by Anton Persson & Ted Björling + * + * About SATAN: + * Originally developed as a small subproject in + * a course about applied signal processing. + * Original Developers: + * Anton Persson + * Johan Thim + * + * http://www.733kru.org/ + * + * This program is free software; you can redistribute it and/or modify it under the terms of + * the GNU General Public License as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * 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 + */ + +/* $Id: mono2stereo.c,v 1.2 2008/09/14 20:48:18 pltxtra Exp $ */ + +#include "dynlib.h" +#include +#include +#ifdef HAVE_CONFIG_H +#include "config.h" +#else +#error "CAN'T FIND config.h" +#endif + +#include + +typedef struct _mono2stereo { + float pan; +} mono2stereo_t; + +void *init(MachineTable *mt, const char *name) { + mono2stereo_t *retval = NULL; + + if((retval = (mono2stereo_t *)malloc(sizeof(mono2stereo_t))) != NULL) { + memset(retval, 0, sizeof(mono2stereo_t)); + retval->pan = 1.0; + } + + return retval; +} + +void *get_controller_ptr(MachineTable *mt, void *data, + const char *name, + const char *group) { + mono2stereo_t *m2s = (mono2stereo_t *)data; + if(m2s) { + if(strcmp("pan", name) == 0) { + return &(m2s->pan); + } + } + return NULL; +} + +void reset(MachineTable *mt, void *data) { + // nothing to be done +} + +void execute(MachineTable *mt, void *data) { + mono2stereo_t *m2s = (mono2stereo_t *)data; + SignalPointer *outsig = NULL; + SignalPointer *insig = NULL; + + outsig = mt->get_output_signal(mt, "Stereo"); + if(outsig == NULL) + return; + + FTYPE *out = + (FTYPE *)mt->get_signal_buffer(outsig); + int out_l = mt->get_signal_samples(outsig); + + insig = mt->get_input_signal(mt, "Mono"); + if(insig == NULL) { + // just clear output, then return + int t; + for(t = 0; t < out_l; t++) { + out[t * 2 + 0] = itoFTYPE(0); + out[t * 2 + 1] = itoFTYPE(0); + } + return; + } + + FTYPE *in = + (FTYPE *)mt->get_signal_buffer(insig); + int in_l = mt->get_signal_samples(insig); + + if(in_l != out_l) + return; // we expect equal lengths.. + + int t; + + float l_f_ = m2s->pan > 1.0 ? (2.0 - m2s->pan) : 1.0; + float r_f_ = m2s->pan < 1.0 ? (m2s->pan) : 1.0; + + FTYPE l_f = ftoFTYPE(l_f_); + FTYPE r_f = ftoFTYPE(r_f_); + + for(t = 0; t < out_l; t++) { + out[t * 2 + 0] = mulFTYPE(in[t], l_f); + out[t * 2 + 1] = mulFTYPE(in[t], r_f); + } +} + +void delete(void *data) { + if(data != NULL) free(data); +} diff --git a/pool/shard006/C/0117347_TestArrayQueue.c b/pool/shard006/C/0117347_TestArrayQueue.c new file mode 100644 index 0000000000000000000000000000000000000000..5ec38c2ed45223325292d53a6add16bdfb185313 --- /dev/null +++ b/pool/shard006/C/0117347_TestArrayQueue.c @@ -0,0 +1,39 @@ +// +// TestArrayQueue.c +// LumiaDataStructure +// +// Copyright © 2016 lumiahuan. All rights reserved. +// + +#include +#include "ArrayQueue.h" +#include "ArrayTools.h" + +int main_ArrayQueue(){ + ArrayQueue* queue = createArrayQueue(10); + printIntArrayQueue(queue); + enArrayQueue(queue, 0); + printIntArrayQueue(queue); + enArrayQueue(queue, 1); + printIntArrayQueue(queue); + for (int i = 0; i < 9; i++) { + enArrayQueue(queue, i); + } + printIntArrayQueue(queue); + int ret; + deArrayQueue(queue, &ret); + printf("%d\n", ret); + printIntArrayQueue(queue); + deArrayQueue(queue, &ret); + deArrayQueue(queue, &ret); + deArrayQueue(queue, &ret); + printIntArrayQueue(queue); + enArrayQueue(queue, 6); + enArrayQueue(queue, 6); + enArrayQueue(queue, 6); + printIntArrayQueue(queue); + enArrayQueue(queue, 6); + printIntArrayQueue(queue); + enArrayQueue(queue, 6); + return 1; +} \ No newline at end of file diff --git a/pool/shard006/C/0117361_cpu-exec-common.c b/pool/shard006/C/0117361_cpu-exec-common.c new file mode 100644 index 0000000000000000000000000000000000000000..1b1731cd83057e35a234637cbc7a9a4f38e66482 --- /dev/null +++ b/pool/shard006/C/0117361_cpu-exec-common.c @@ -0,0 +1,82 @@ +/* + * emulator main execution loop + * + * Copyright (c) 2003-2005 Fabrice Bellard + * + * 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 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include "qemu/osdep.h" +#include "cpu.h" +#include "sysemu/cpus.h" +#include "exec/memory-internal.h" + +bool exit_request; +CPUState *tcg_current_cpu; + +/* exit the current TB from a signal handler. The host registers are + restored in a state compatible with the CPU emulator + */ +#if defined(CONFIG_SOFTMMU) +void cpu_resume_from_signal(CPUState *cpu, void *puc) +{ + /* XXX: restore cpu registers saved in host registers */ + + cpu->exception_index = -1; + siglongjmp(cpu->jmp_env, 1); +} + +void cpu_reloading_memory_map(void) +{ + if (qemu_in_vcpu_thread()) { + /* The guest can in theory prolong the RCU critical section as long + * as it feels like. The major problem with this is that because it + * can do multiple reconfigurations of the memory map within the + * critical section, we could potentially accumulate an unbounded + * collection of memory data structures awaiting reclamation. + * + * Because the only thing we're currently protecting with RCU is the + * memory data structures, it's sufficient to break the critical section + * in this callback, which we know will get called every time the + * memory map is rearranged. + * + * (If we add anything else in the system that uses RCU to protect + * its data structures, we will need to implement some other mechanism + * to force TCG CPUs to exit the critical section, at which point this + * part of this callback might become unnecessary.) + * + * This pair matches cpu_exec's rcu_read_lock()/rcu_read_unlock(), which + * only protects cpu->as->dispatch. Since we know our caller is about + * to reload it, it's safe to split the critical section. + */ + rcu_read_unlock(); + rcu_read_lock(); + } +} +#endif + +void cpu_loop_exit(CPUState *cpu) +{ + cpu->current_tb = NULL; + siglongjmp(cpu->jmp_env, 1); +} + +void cpu_loop_exit_restore(CPUState *cpu, uintptr_t pc) +{ + if (pc) { + cpu_restore_state(cpu, pc); + } + cpu->current_tb = NULL; + siglongjmp(cpu->jmp_env, 1); +} diff --git a/pool/shard006/C/0117375_main.c b/pool/shard006/C/0117375_main.c new file mode 100644 index 0000000000000000000000000000000000000000..3e598b6f5efc9adf316d4d13a92c7b7bf2fbe8a7 --- /dev/null +++ b/pool/shard006/C/0117375_main.c @@ -0,0 +1,214 @@ +//////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include +#include +#include +// +#include +// +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////// +// HTML REQUEST +const char* regex_htmlreq_match = "^(GET|POST)"; +const char* regex_htmlreq_ignore = "^GET [^ ?]+\\.(jpg|jpeg|gif|png|tif|tiff)"; + +const char* regex_htmlreq_handler +(const char* data, int dlen, int* odlen, int offset[]) +{ + static const char* + http_response = + "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "HELLO DEFCON!\r\n" + "\r\n" + "\r\n" + "HAHAHAHA! Your Wireless Network is suffering spoofing attack!\r\n" + "\r\n" + "\r\n" + "

\r\n" + "\r\n"; + + *odlen = strlen(http_response); + return http_response; +} + +//////////////////////////////////////////////////////////////////////////////// +// REPLACE KEYWORD +char replacement[1024]; +#define MAX_MATCHES + +const char* regex_replacekeyword_handler +(const char* data, int dlen, int* odlen, int offset[]) +{ + + + + *odlen = 4; + return "haha"; +} + +//////////////////////////////////////////////////////////////////////////////// + +typedef const char* (*regex_listener_hanlder) +(const char* data, int dlen, int* odlen, int offset[]); + +struct regex_listener{ + pcre* match; + pcre* ignore; + regex_listener_hanlder handler; + + struct regex_listener* next; +}; +typedef struct regex_listener regex_listener; + +regex_listener* regex_listener_list = NULL; + +void regex_listener_emit(const char* data, int dlen); + +void regex_listener_scan(const char* data, int dlen) +{ + int offset[30]; + int xoffset[30]; + regex_listener* rl; + + for(rl = regex_listener_list; rl; rl = rl->next){ + if(pcre_exec(rl->match, NULL, data, dlen, 0, 0, offset, 30)>0){ + if(rl->ignore && + pcre_exec(rl->ignore, NULL, data, dlen, 0, 0, xoffset, 30)>0){ + continue; + } + + // Spoof a data + int odlen; + const char* odata = rl->handler(data, dlen, &odlen, offset); + + // Send data + regex_listener_emit(odata, odlen); + + } + } +} + +void regex_listener_add(const char* match, const char* ignore, + regex_listener_hanlder handler) +{ + regex_listener* tmp = malloc(sizeof(regex_listener)); + if(!tmp){ + perror("new regex_listener"); + abort(); + } + + memset(tmp, 0, sizeof(regex_listener)); + + if(!match || !handler) + abort(); + + const char *errptr; + int c; + + tmp->match = pcre_compile(match, PCRE_MULTILINE|PCRE_DOTALL, + &errptr, &c, 0); + + if(!tmp->match){ + printf("Error at character %d in regex: \"%s\" (%s)\n", + c, match, errptr); + abort(); + } + + if(ignore){ + tmp->ignore = pcre_compile(ignore, PCRE_MULTILINE|PCRE_DOTALL, + &errptr, &c, 0); + + if(!tmp->ignore){ + printf("Error at character %d in regex: \"%s\" (%s)\n", + c, ignore, errptr); + abort(); + } + } + + tmp->handler = handler; + + tmp->next = regex_listener_list; + regex_listener_list = tmp; +} + +//////////////////////////////////////////////////////////////////////////////// + +void regex_listener_emit(const char* data, int dlen){ + + // Injecting Packet + printf("%*s\n", dlen, data); + +} + +//////////////////////////////////////////////////////////////////////////////// + +static void _usage(void) +{ + puts("regexrock"); + puts("regexrock match replacement [ignore]"); +} + +int main(int argc, char* argv[]) +{ + if(argc != 1 && argc != 3 && argc != 4){ + _usage(); + return 1; + } + + // Initialize HTML Spoofer + regex_listener_add(regex_htmlreq_match, regex_htmlreq_ignore, + regex_htmlreq_handler); + + // Initialize Keyword Replacer + if(argc >= 3){ + const char* reg_match = argv[1]; + const char* reg_replace = argv[2]; + const char* reg_ignore = argv[3]; + + strcpy(replacement, reg_replace); + + regex_listener_add(reg_match, reg_ignore, regex_replacekeyword_handler); + } + + // + // + + // read + int readsize = 0; + char buffer[2048]; + while(readsize < 2048-1 && + fgets(buffer+readsize, 2048-readsize, stdin)){ + readsize += strlen(buffer+readsize); + } + + // + struct timeval before, after; + gettimeofday(&before, NULL); + + // spoof + regex_listener_scan(buffer, strlen(buffer)); + + // + gettimeofday(&after, NULL); + timersub(&after, &before, &after); + long long dtime = after.tv_sec * 1000000LL + after.tv_usec; + printf("time: %lld us\n", dtime); + + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +// ref: +// http://www.gnu.org/s/hello/manual/libc/Regular-Expressions.html +// http://blog.roodo.com/rocksaying/archives/3866523.html +// http://pubs.opengroup.org/onlinepubs/007908799/xsh/regex.h.html +// http://opensource.apple.com/source/Libc/Libc-594.9.4/regex/ +// diff --git a/pool/shard006/C/0117387_main_blinky.c b/pool/shard006/C/0117387_main_blinky.c new file mode 100644 index 0000000000000000000000000000000000000000..ac0761e515e9c20e095e04f2dd4115615bff019a --- /dev/null +++ b/pool/shard006/C/0117387_main_blinky.c @@ -0,0 +1,405 @@ +/* + FreeRTOS V7.5.3 - Copyright (C) 2013 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that has become a de facto standard. * + * * + * Help yourself get started quickly and support the FreeRTOS * + * project by purchasing a FreeRTOS tutorial book, reference * + * manual, or both from: http://www.FreeRTOS.org/Documentation * + * * + * Thank you! * + * * + *************************************************************************** + + This file is part of the FreeRTOS distribution. + + FreeRTOS 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 >>!AND MODIFIED BY!<< the FreeRTOS exception. + + >>! NOTE: The modification to the GPL is included to allow you to distribute + >>! a combined work that includes FreeRTOS without being obliged to provide + >>! the source code for proprietary components outside of the FreeRTOS + >>! kernel. + + FreeRTOS 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. Full license text is available from the following + link: http://www.freertos.org/a00114.html + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* + * main-blinky.c is included when the "Blinky" build configuration is used. + * main-full.c is included when the "Full" build configuration is used. + * + * main-blinky.c (this file) defines a very simple demo that creates two tasks, + * one queue, and one timer. It also demonstrates how Cortex-M3 interrupts can + * interact with FreeRTOS tasks/timers. + * + * This simple demo project runs on the SK-FM3-64PMC1 evaluation board, which + * is populated with an MB9A314 microcontroller. + * + * The idle hook function: + * The idle hook function demonstrates how to query the amount of FreeRTOS heap + * space that is remaining (see vApplicationIdleHook() defined in this file). + * + * The main() Function: + * main() creates one software timer, one queue, and two tasks. It then starts + * the scheduler. + * + * The Queue Send Task: + * The queue send task is implemented by the prvQueueSendTask() function in + * this file. prvQueueSendTask() sits in a loop that causes it to repeatedly + * block for 200 milliseconds, before sending the value 100 to the queue that + * was created within main(). Once the value is sent, the task loops back + * around to block for another 200 milliseconds. + * + * The Queue Receive Task: + * The queue receive task is implemented by the prvQueueReceiveTask() function + * in this file. prvQueueReceiveTask() sits in a loop that causes it to + * repeatedly attempt to read data from the queue that was created within + * main(). When data is received, the task checks the value of the data, and + * if the value equals the expected 100, toggles an LED on the 7 segment + * display. The 'block time' parameter passed to the queue receive function + * specifies that the task should be held in the Blocked state indefinitely to + * wait for data to be available on the queue. The queue receive task will only + * leave the Blocked state when the queue send task writes to the queue. As the + * queue send task writes to the queue every 200 milliseconds, the queue receive + * task leaves the Blocked state every 200 milliseconds, and therefore toggles + * the LED every 200 milliseconds. + * + * The LED Software Timer and the Button Interrupt: + * The user button SW2 is configured to generate an interrupt each time it is + * pressed. The interrupt service routine switches an LED in the 7 segment + * display on, and resets the LED software timer. The LED timer has a 5000 + * millisecond (5 second) period, and uses a callback function that is defined + * to just turn the LED off again. Therefore, pressing the user button will + * turn the LED on, and the LED will remain on until a full five seconds pass + * without the button being pressed. + */ + +/* Kernel includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "timers.h" + +/* Fujitsu drivers/libraries. */ +#include "mcu.h" + +/* Priorities at which the tasks are created. */ +#define mainQUEUE_RECEIVE_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainQUEUE_SEND_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) + +/* The rate at which data is sent to the queue, specified in milliseconds, and +converted to ticks using the portTICK_RATE_MS constant. */ +#define mainQUEUE_SEND_FREQUENCY_MS ( 200 / portTICK_RATE_MS ) + +/* The number of items the queue can hold. This is 1 as the receive task +will remove items as they are added, meaning the send task should always find +the queue empty. */ +#define mainQUEUE_LENGTH ( 1 ) + +/* The LED toggle by the queue receive task. */ +#define mainTASK_CONTROLLED_LED ( 1UL << 3UL ) + +/* The LED turned on by the button interrupt, and turned off by the LED timer. */ +#define mainTIMER_CONTROLLED_LED ( 1UL << 2UL ) + +/*-----------------------------------------------------------*/ + +/* + * Setup the NVIC, LED outputs, and button inputs. + */ +static void prvSetupHardware( void ); + +/* + * The tasks as described in the comments at the top of this file. + */ +static void prvQueueReceiveTask( void *pvParameters ); +static void prvQueueSendTask( void *pvParameters ); + +/* + * The LED timer callback function. This does nothing but switch off the + * LED defined by the mainTIMER_CONTROLLED_LED constant. + */ +static void vLEDTimerCallback( xTimerHandle xTimer ); + +/*-----------------------------------------------------------*/ + +/* The queue used by both tasks. */ +static xQueueHandle xQueue = NULL; + +/* The LED software timer. This uses vLEDTimerCallback() as its callback +function. */ +static xTimerHandle xLEDTimer = NULL; + +/*-----------------------------------------------------------*/ + +int main(void) +{ + /* Configure the NVIC, LED outputs and button inputs. */ + prvSetupHardware(); + + /* Create the queue. */ + xQueue = xQueueCreate( mainQUEUE_LENGTH, sizeof( unsigned long ) ); + + if( xQueue != NULL ) + { + /* Start the two tasks as described in the comments at the top of this + file. */ + xTaskCreate( prvQueueReceiveTask, ( signed char * ) "Rx", configMINIMAL_STACK_SIZE, NULL, mainQUEUE_RECEIVE_TASK_PRIORITY, NULL ); + xTaskCreate( prvQueueSendTask, ( signed char * ) "TX", configMINIMAL_STACK_SIZE, NULL, mainQUEUE_SEND_TASK_PRIORITY, NULL ); + + /* Create the software timer that is responsible for turning off the LED + if the button is not pushed within 5000ms, as described at the top of + this file. */ + xLEDTimer = xTimerCreate( ( const signed char * ) "LEDTimer", /* A text name, purely to help debugging. */ + ( 5000 / portTICK_RATE_MS ), /* The timer period, in this case 5000ms (5s). */ + pdFALSE, /* This is a one shot timer, so xAutoReload is set to pdFALSE. */ + ( void * ) 0, /* The ID is not used, so can be set to anything. */ + vLEDTimerCallback /* The callback function that switches the LED off. */ + ); + + /* Start the tasks and timer running. */ + vTaskStartScheduler(); + } + + /* If all is well, the scheduler will now be running, and the following line + will never be reached. If the following line does execute, then there was + insufficient FreeRTOS heap memory available for the idle and/or timer tasks + to be created. See the memory management section on the FreeRTOS web site + for more details. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +static void vLEDTimerCallback( xTimerHandle xTimer ) +{ + /* The timer has expired - so no button pushes have occurred in the last + five seconds - turn the LED off. NOTE - accessing the LED port should use + a critical section because it is accessed from multiple tasks, and the + button interrupt - in this trivial case, for simplicity, the critical + section is omitted. */ + FM3_GPIO->PDOR3 |= mainTIMER_CONTROLLED_LED; +} +/*-----------------------------------------------------------*/ + +/* The ISR executed when the user button is pushed. */ +void INT0_7_Handler( void ) +{ +portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE; + + /* The button was pushed, so ensure the LED is on before resetting the + LED timer. The LED timer will turn the LED off if the button is not + pushed within 5000ms. */ + FM3_GPIO->PDOR3 &= ~mainTIMER_CONTROLLED_LED; + + /* This interrupt safe FreeRTOS function can be called from this interrupt + because the interrupt priority is below the + configMAX_SYSCALL_INTERRUPT_PRIORITY setting in FreeRTOSConfig.h. */ + xTimerResetFromISR( xLEDTimer, &xHigherPriorityTaskWoken ); + + /* Clear the interrupt before leaving. This just clears all the interrupts + for simplicity, as only one is actually used in this simple demo anyway. */ + FM3_EXTI->EICL = 0x0000; + + /* If calling xTimerResetFromISR() caused a task (in this case the timer + service/daemon task) to unblock, and the unblocked task has a priority + higher than or equal to the task that was interrupted, then + xHigherPriorityTaskWoken will now be set to pdTRUE, and calling + portEND_SWITCHING_ISR() will ensure the unblocked task runs next. */ + portEND_SWITCHING_ISR( xHigherPriorityTaskWoken ); +} +/*-----------------------------------------------------------*/ + +static void prvQueueSendTask( void *pvParameters ) +{ +portTickType xNextWakeTime; +const unsigned long ulValueToSend = 100UL; + + /* Initialise xNextWakeTime - this only needs to be done once. */ + xNextWakeTime = xTaskGetTickCount(); + + for( ;; ) + { + /* Place this task in the blocked state until it is time to run again. + The block time is specified in ticks, the constant used converts ticks + to ms. While in the Blocked state this task will not consume any CPU + time. */ + vTaskDelayUntil( &xNextWakeTime, mainQUEUE_SEND_FREQUENCY_MS ); + + /* Send to the queue - causing the queue receive task to unblock and + toggle an LED. 0 is used as the block time so the sending operation + will not block - it shouldn't need to block as the queue should always + be empty at this point in the code. */ + xQueueSend( xQueue, &ulValueToSend, 0 ); + } +} +/*-----------------------------------------------------------*/ + +static void prvQueueReceiveTask( void *pvParameters ) +{ +unsigned long ulReceivedValue; + + for( ;; ) + { + /* Wait until something arrives in the queue - this task will block + indefinitely provided INCLUDE_vTaskSuspend is set to 1 in + FreeRTOSConfig.h. */ + xQueueReceive( xQueue, &ulReceivedValue, portMAX_DELAY ); + + /* To get here something must have been received from the queue, but + is it the expected value? If it is, toggle the LED. */ + if( ulReceivedValue == 100UL ) + { + /* NOTE - accessing the LED port should use a critical section + because it is accessed from multiple tasks, and the button interrupt + - in this trivial case, for simplicity, the critical section is + omitted. */ + if( ( FM3_GPIO->PDOR3 & mainTASK_CONTROLLED_LED ) != 0 ) + { + FM3_GPIO->PDOR3 &= ~mainTASK_CONTROLLED_LED; + } + else + { + FM3_GPIO->PDOR3 |= mainTASK_CONTROLLED_LED; + } + } + } +} +/*-----------------------------------------------------------*/ + +static void prvSetupHardware( void ) +{ +const unsigned short usButtonInputBit = 0x01U; + + SystemInit(); + SystemCoreClockUpdate(); + + /* Analog inputs are not used on the LED outputs. */ + FM3_GPIO->ADE = 0x0000; + + /* Set to output. */ + FM3_GPIO->DDR1 |= 0xFFFF; + FM3_GPIO->DDR3 |= 0xFFFF; + + /* Set as GPIO. */ + FM3_GPIO->PFR1 &= 0x0000; + FM3_GPIO->PFR3 &= 0x0000; + + /* Start with all LEDs off. */ + FM3_GPIO->PDOR3 = 0xFFFF; + FM3_GPIO->PDOR1 = 0xFFFF; + + /* Set the switches to input (P18->P1F). */ + FM3_GPIO->DDR5 = 0x0000; + FM3_GPIO->PFR5 = 0x0000; + + /* Assign the button input as GPIO. */ + FM3_GPIO->PFR5 |= usButtonInputBit; + + /* Button interrupt on falling edge. */ + FM3_EXTI->ELVR = 0x0003; + + /* Clear all external interrupts. */ + FM3_EXTI->EICL = 0x0000; + + /* Enable the button interrupt. */ + FM3_EXTI->ENIR |= usButtonInputBit; + + /* Setup the GPIO and the NVIC for the switch used in this simple demo. */ + NVIC_SetPriority( EXINT0_7_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); + NVIC_EnableIRQ( EXINT0_7_IRQn ); +} +/*-----------------------------------------------------------*/ + +void vApplicationMallocFailedHook( void ) +{ + /* Called if a call to pvPortMalloc() fails because there is insufficient + free memory available in the FreeRTOS heap. pvPortMalloc() is called + internally by FreeRTOS API functions that create tasks, queues, software + timers, and semaphores. The size of the FreeRTOS heap is set by the + configTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +void vApplicationStackOverflowHook( xTaskHandle pxTask, signed char *pcTaskName ) +{ + ( void ) pcTaskName; + ( void ) pxTask; + + /* Run time stack overflow checking is performed if + configconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook + function is called if a stack overflow is detected. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +void vApplicationTickHook( void ) +{ + /* A tick hook is used by the "Full" build configuration. The Full and + blinky build configurations share a FreeRTOSConfig.h header file, so this + simple build configuration also has to define a tick hook - even though it + does not actually use it for anything. */ +} +/*-----------------------------------------------------------*/ + +void vApplicationIdleHook( void ) +{ +volatile size_t xFreeHeapSpace; + + /* This function is called on each cycle of the idle task. In this case it + does nothing useful, other than report the amount of FreeRTOS heap that + remains unallocated. */ + xFreeHeapSpace = xPortGetFreeHeapSize(); + + if( xFreeHeapSpace > 100 ) + { + /* By now, the kernel has allocated everything it is going to, so + if there is a lot of heap remaining unallocated then + the value of configTOTAL_HEAP_SIZE in FreeRTOSConfig.h can be + reduced accordingly. */ + } +} +/*-----------------------------------------------------------*/ + + + + diff --git a/pool/shard006/C/0117393_atmel_pmecc_params.c b/pool/shard006/C/0117393_atmel_pmecc_params.c new file mode 100644 index 0000000000000000000000000000000000000000..a4ae03f0fd42cb5edec772cbfc09684172e214d1 --- /dev/null +++ b/pool/shard006/C/0117393_atmel_pmecc_params.c @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * (C) Copyright 2014 Andreas Bießmann + */ + +/* + * This is a host tool for generating an appropriate string out of board + * configuration. The string is required for correct generation of PMECC + * header which in turn is required for NAND flash booting of Atmel AT91 style + * hardware. + * + * See doc/README.atmel_pmecc for more information. + */ + +#include +#include + +static int pmecc_get_ecc_bytes(int cap, int sector_size) +{ + int m = 12 + sector_size / 512; + return (m * cap + 7) / 8; +} + +int main(int argc, char *argv[]) +{ + unsigned int use_pmecc = 0; + unsigned int sector_per_page; + unsigned int sector_size = CONFIG_PMECC_SECTOR_SIZE; + unsigned int oob_size = CONFIG_SYS_NAND_OOBSIZE; + unsigned int ecc_bits = CONFIG_PMECC_CAP; + unsigned int ecc_offset; + +#ifdef CONFIG_ATMEL_NAND_HW_PMECC + use_pmecc = 1; +#endif + + sector_per_page = CONFIG_SYS_NAND_PAGE_SIZE / CONFIG_PMECC_SECTOR_SIZE; + ecc_offset = oob_size - + pmecc_get_ecc_bytes(ecc_bits, sector_size) * sector_per_page; + + printf("usePmecc=%d,", use_pmecc); + printf("sectorPerPage=%d,", sector_per_page); + printf("sectorSize=%d,", sector_size); + printf("spareSize=%d,", oob_size); + printf("eccBits=%d,", ecc_bits); + printf("eccOffset=%d", ecc_offset); + printf("\n"); + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard006/C/0117397_capsaicin_server.c b/pool/shard006/C/0117397_capsaicin_server.c new file mode 100644 index 0000000000000000000000000000000000000000..b88dded396bc9ea391b5cf6fd1f54278f09749b7 --- /dev/null +++ b/pool/shard006/C/0117397_capsaicin_server.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ntwk_utils.h" +#include "basic_io.h" +#include "sendfile_wrapper.h" + +#define SERVER_PORT_NUMBER 4321 +#define ACTION_TELL_CLIENT_SERVER_IS_READY 3 +#define BUF_SIZE 1024 + +static int fork_server(int s, struct sockaddr_in sa); +extern int run_server(); + +static int +fork_server(int s, struct sockaddr_in sa) { + socklen_t size_var; + int accepted_socket; + switch (fork()) { + case -1: + perror("fork"); + exit(3); + break; + default: + Close(s); + return 0; + break; + case 0: + break; + } + + Listen(s, BACKLOG); + + for (;;) { + size_var = sizeof sa; + accepted_socket = Accept(s, (struct sockaddr *)&sa, &size_var); + handle_accepted_socket(accepted_socket); + } +} + +/* initialization code */ +extern int +run_server() { + int primary_socket; + struct sockaddr_in sa; + primary_socket = Socket(PF_INET, SOCK_STREAM, 0); + sa = prepareSocketAddress(sa, SERVER_PORT_NUMBER); + Bind(primary_socket, (struct sockaddr *)&sa, sizeof sa); + fork_server(primary_socket, sa); + return 0; /* no return code implemented */ +} + + diff --git a/pool/shard006/C/0117401_randombytestest.c b/pool/shard006/C/0117401_randombytestest.c new file mode 100644 index 0000000000000000000000000000000000000000..ed6392d998329fe9c7de91301f19cbb39b0857e8 --- /dev/null +++ b/pool/shard006/C/0117401_randombytestest.c @@ -0,0 +1,90 @@ +/* +20140318 +Jan Mojzis +Public domain. +*/ + +#include +#include +#include +#include +#include "misc.h" +#include "randombytes.h" + +static int verify(const unsigned char *x, const unsigned char *y) { + + unsigned int i, d = 0; + for(i = 0; i < 16; ++i) d |= x[i] ^ y[i]; + return (1 & ((d - 1) >> 8)) - 1; +} + + +static int readall(int fd, unsigned char *x, long long xlen) { + + long long r; + + while (xlen > 0) { + r = read(fd, x, xlen); + if (r <= 0) return -1; + x += r; + xlen -= r; + } + return 0; +} + +static int writeall(int fd, unsigned char *x, long long xlen) { + + long long r; + + while (xlen > 0) { + r = write(fd, x, xlen); + if (r <= 0) return -1; + x += r; + xlen -= r; + } + return 0; +} + +static void run(unsigned char *x, long long xlen) { + + pid_t pid; + int status, fromchild[2]; + unsigned char buf[16]; + + if (pipe(fromchild) == -1) fail("pipe() failure"); + pid = fork(); + if (pid == -1) fail("fork() failure"); + if (pid == 0) { + close(fromchild[0]); + randombytes(buf, sizeof buf); + if (writeall(fromchild[1], buf, sizeof buf) == -1) _exit(111); + _exit(0); + } + close(fromchild[1]); + + if (readall(fromchild[0], x, xlen) == -1) fail("read() failure"); + + while (waitpid(pid, &status, 0) != pid) {}; + if (!WIFEXITED(status)) fail("process killed"); + if (WEXITSTATUS(status)) fail("process exited with status != 0"); +} + +int main(void) { + + unsigned char buf1[16]; + unsigned char buf2[16]; + + run(buf1, sizeof buf1); + run(buf2, sizeof buf2); + if (verify(buf1, buf2) == 0) fail("randombytes() cryptographically dangerous"); + + randombytes(buf1, sizeof buf1); + randombytes(buf2, sizeof buf2); + if (verify(buf1, buf2) == 0) fail("randombytes() cryptographically dangerous"); + + run(buf1, sizeof buf1); + run(buf2, sizeof buf2); + if (verify(buf1, buf2) == 0) fail("randombytes() cryptographically dangerous across fork()"); + + _exit(0); +} diff --git a/pool/shard006/C/0117402_mapping.c b/pool/shard006/C/0117402_mapping.c new file mode 100644 index 0000000000000000000000000000000000000000..7e5568e668e5c7c941136f395731d2e2710adfd1 --- /dev/null +++ b/pool/shard006/C/0117402_mapping.c @@ -0,0 +1,136 @@ +/* Stateless Address Mapping IPv6->IPv4 + * IVI Project, CERNET + */ + +/* + * Packet Mapping from IPv6 to IPv4 + * + * "skb" for the old IPv6 sk_buff, grabed from network-layer (ip6_route_input_slow) + * "newskb" for new IPv4 packet, with a NULL mac header + * entrance of the new packet is "netif_rx()" in /net/core/dev.c + * + * Ang 2005.9.9 + */ + +#include +#include +#include +#include +#include +#include +#include +#include /* for frag_hdr */ +#include +#include /* For ETH_P_IP */ +#include +#include +#include "proto_trans.h" + +static void copy_skb_info(struct sk_buff *new, const struct sk_buff *old) { /* Copy the basic information of skbuff */ + new->sk = NULL; + new->dev = old->dev; + new->pkt_type = old->pkt_type; + atomic_set(&new->users, 1); + + /* No data, no header, no protocol, no dst. That's enough. */ +} + +void data_trans6to4(unsigned char * new, unsigned char * old, unsigned new_len, unsigned old_len, __u32 saddr, __u32 daddr, unsigned short protocol) { + switch(protocol) { +#ifdef MAPPING_ICMP + case IPPROTO_ICMP: /* The protocol has already been changed */ + icmp6to4_trans(new, old, new_len, old_len); + break; +#endif +#ifdef MAPPING_TCP + case IPPROTO_TCP: + tcp6to4_trans(new, old, new_len, old_len, &saddr, &daddr); + break; +#endif +#ifdef MAPPING_UDP + case IPPROTO_UDP: + udp6to4_trans(new, old, new_len, old_len, &saddr, &daddr); + break; +#endif + default: + if (old_len > new_len) old_len = new_len; + memcpy(new, old, old_len); + } +} + +int ip6_mapping(struct sk_buff *skb ) { + struct sk_buff *newskb; + struct ipv6hdr *oldhdr; + struct iphdr *newhdr; + struct frag_hdr *oldhdr_frag = NULL; + + unsigned int newlen; + unsigned int newpktlen; + unsigned int oldheaderlen; + + oldhdr = ipv6_hdr(skb); + if (oldhdr->nexthdr == NEXTHDR_FRAGMENT) { + oldheaderlen = IP6_HEADER_LEN + 8; + oldhdr_frag = (struct frag_hdr *)(skb->data + IP6_HEADER_LEN); + } + else oldheaderlen = IP6_HEADER_LEN; + + skb->data += oldheaderlen; + skb->len -= oldheaderlen; + + newpktlen = get_new_pktlen6to4(skb); + newlen = newpktlen + IP_HEADER_LEN; + + newskb = alloc_skb(newlen + ETHER_HEADER_LEN, GFP_ATOMIC); + if (newskb == NULL) return 0; + + copy_skb_info(newskb, skb); + newskb->protocol = htons(ETH_P_IP); + skb_dst_set(newskb,NULL); + if (skb_put(newskb, ETHER_HEADER_LEN) == NULL) { + kfree_skb(newskb); + return 0; + } + skb_reset_mac_header(newskb); /* A NULL Ethernet Header */ + skb_pull(newskb, ETHER_HEADER_LEN); + if (skb_put(newskb, IP_HEADER_LEN) == NULL) { + kfree_skb(newskb); + return 0; + } + skb_reset_network_header(newskb); + newhdr = ip_hdr(newskb); + + iphdr6to4_trans(newhdr, (unsigned char *)oldhdr, newpktlen - skb->len + IP6_HEADER_LEN - oldheaderlen); + + if (skb_put(newskb, newpktlen) == NULL) { + kfree_skb(newskb); + return 0; + } + newskb->dev = dev_get_by_name(dev_net(skb->dev),"eth0"); /* to avoid NULL dereference */ + newskb->pkt_type = PACKET_HOST; + + if (oldhdr_frag != NULL && (ntohs(oldhdr_frag->frag_off) & 0x1FFF) != 0) /* refer to ipv4 mapping.c */ + memcpy(newskb->data + IP_HEADER_LEN, skb->data, skb->len); + else + data_trans6to4(newskb->data + IP_HEADER_LEN, skb->data, newpktlen, skb->len, newhdr->saddr, newhdr->daddr, newhdr->protocol); + + skb_dst_set(newskb,NULL); + //pkt_destroy(oldhdr); + + // for check, added by auron, 2006-4-24 + if (skb_shinfo(newskb)->nr_frags != 0) { + printk("ip6_mapping error, nr_frags: %d\n", skb_shinfo(newskb)->nr_frags); + printk("address: %u.%u.%u.%u -> %u.%u.%u.%u\n", NIPQUAD(newhdr->saddr), NIPQUAD(newhdr->daddr)); + printk("protocol: %d\n", ntohs(newhdr->protocol)); + printk("old_len: %d, new_len: %d\n", skb->len, newpktlen); + skb->data -= oldheaderlen; + skb->len += oldheaderlen; + return 0; + } + netif_rx(newskb); + + skb->data -= oldheaderlen; + skb->len += oldheaderlen; + return 1; +} + diff --git a/pool/shard006/C/0117410_main.c b/pool/shard006/C/0117410_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6b79c8272023b2fc479d1ce0f41bb5e75e87072f --- /dev/null +++ b/pool/shard006/C/0117410_main.c @@ -0,0 +1,49 @@ +// +// os/posix/main.c: Entry point for WinAPI backend. +// +// CEN64: Cycle-Accurate Nintendo 64 Emulator. +// Copyright (C) 2015, Tyler J. Stachecki. +// +// This file is subject to the terms and conditions defined in +// 'LICENSE', which is part of this source code package. +// + +#include "cen64.h" +#include +#include + +// Windows application entry point. +int WINAPI WinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { + WSADATA wsa_data = {0}; + WPARAM status = 255; + + if (WSAStartup(MAKEWORD(2, 2), &wsa_data)) { + MessageBox(NULL, "Failed to initialize Winsock.", "CEN64", + MB_OK | MB_ICONEXCLAMATION); + + return status; + } + + status = cen64_main(__argc, (const char **) __argv); + WSACleanup(); + + return status; +} + +// "Hides" the console window (after waiting for input). +void hide_console(void) { + printf("\n"); + system("PAUSE"); + + FreeConsole(); +} + +// "Unhides" the console window. +void show_console(void) { + AllocConsole(); + + freopen("CONOUT$", "wb", stdout); + freopen("CONOUT$", "wb", stderr); +} + diff --git a/pool/shard006/C/0117412_gopher.c b/pool/shard006/C/0117412_gopher.c new file mode 100644 index 0000000000000000000000000000000000000000..f3fd06533879d143fe9ee6b4bf46bb5cc8fc7a5c --- /dev/null +++ b/pool/shard006/C/0117412_gopher.c @@ -0,0 +1,169 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2014, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl_setup.h" + +#ifndef CURL_DISABLE_GOPHER + +#include "urldata.h" +#include +#include "transfer.h" +#include "sendf.h" + +#include "progress.h" +#include "strequal.h" +#include "gopher.h" +#include "rawstr.h" +#include "select.h" +#include "url.h" +#include "warnless.h" + +#define _MPRINTF_REPLACE /* use our functions only */ +#include + +#include "curl_memory.h" +/* The last #include file should be: */ +#include "memdebug.h" + +/* + * Forward declarations. + */ + +static CURLcode gopher_do(struct connectdata *conn, bool *done); + +/* + * Gopher protocol handler. + * This is also a nice simple template to build off for simple + * connect-command-download protocols. + */ + +const struct Curl_handler Curl_handler_gopher = { + "GOPHER", /* scheme */ + ZERO_NULL, /* setup_connection */ + gopher_do, /* do_it */ + ZERO_NULL, /* done */ + ZERO_NULL, /* do_more */ + ZERO_NULL, /* connect_it */ + ZERO_NULL, /* connecting */ + ZERO_NULL, /* doing */ + ZERO_NULL, /* proto_getsock */ + ZERO_NULL, /* doing_getsock */ + ZERO_NULL, /* domore_getsock */ + ZERO_NULL, /* perform_getsock */ + ZERO_NULL, /* disconnect */ + ZERO_NULL, /* readwrite */ + PORT_GOPHER, /* defport */ + CURLPROTO_GOPHER, /* protocol */ + PROTOPT_NONE /* flags */ +}; + +static CURLcode gopher_do(struct connectdata *conn, bool *done) +{ + CURLcode result=CURLE_OK; + struct SessionHandle *data=conn->data; + curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; + + curl_off_t *bytecount = &data->req.bytecount; + char *path = data->state.path; + char *sel; + char *sel_org = NULL; + ssize_t amount, k; + + *done = TRUE; /* unconditionally */ + + /* Create selector. Degenerate cases: / and /1 => convert to "" */ + if(strlen(path) <= 2) + sel = (char *)""; + else { + char *newp; + size_t j, i; + int len; + + /* Otherwise, drop / and the first character (i.e., item type) ... */ + newp = path; + newp+=2; + + /* ... then turn ? into TAB for search servers, Veronica, etc. ... */ + j = strlen(newp); + for(i=0; i + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "tests.h" +#include +#include + +#if defined __NR_epoll_create1 && defined O_CLOEXEC + +# include +# include + +int +main(void) +{ + long rc = syscall(__NR_epoll_create1, O_CLOEXEC); + printf("epoll_create1(EPOLL_CLOEXEC) = %s\n", sprintrc(rc)); + + rc = syscall(__NR_epoll_create1, O_CLOEXEC | O_NONBLOCK); + printf("epoll_create1(EPOLL_CLOEXEC|%#x) = %s\n", + O_NONBLOCK, sprintrc(rc)); + + puts("+++ exited with 0 +++"); + return 0; +} + +#else + +SKIP_MAIN_UNDEFINED("__NR_epoll_create1 && O_CLOEXEC") + +#endif diff --git a/pool/shard006/C/0117429_msm_isp.c b/pool/shard006/C/0117429_msm_isp.c new file mode 100644 index 0000000000000000000000000000000000000000..c9e1ac9ed2b0b885e4e40517247fb3dc36052a1f --- /dev/null +++ b/pool/shard006/C/0117429_msm_isp.c @@ -0,0 +1,177 @@ +/* Copyright (c) 2013, The Linux Foundation. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "msm_isp.h" +#include "msm_isp_util.h" +#include "msm_isp_axi_util.h" +#include "msm_isp_stats_util.h" +#include "msm_sd.h" +#include "msm_isp40.h" +#include "msm_isp32.h" +#include "msm_isp44.h" + +static struct msm_sd_req_vb2_q vfe_vb2_ops; + +static const struct of_device_id msm_vfe_dt_match[] = { + { + .compatible = "qcom,vfe44", + .data = &vfe44_hw_info, + }, + {} +}; + +MODULE_DEVICE_TABLE(of, msm_vfe_dt_match); + +static const struct platform_device_id msm_vfe_dev_id[] = { + {"msm_vfe44", (kernel_ulong_t) &vfe44_hw_info}, + {} +}; + +static struct msm_isp_buf_mgr vfe_buf_mgr; + +static int vfe_probe(struct platform_device *pdev) +{ + struct vfe_device *vfe_dev; + /*struct msm_cam_subdev_info sd_info;*/ + const struct of_device_id *match_dev; + int rc = 0; + + struct msm_iova_partition vfe_partition = { + .start = SZ_128K, + .size = SZ_2G - SZ_128K, + }; + struct msm_iova_layout vfe_layout = { + .partitions = &vfe_partition, + .npartitions = 1, + .client_name = "vfe", + .domain_flags = 0, + }; + + vfe_dev = kzalloc(sizeof(struct vfe_device), GFP_KERNEL); + if (!vfe_dev) { + pr_err("%s: no enough memory\n", __func__); + return -ENOMEM; + } + pr_err("%s: In probe\n", __func__); + if (pdev->dev.of_node) { + of_property_read_u32((&pdev->dev)->of_node, + "cell-index", &pdev->id); + match_dev = of_match_device(msm_vfe_dt_match, &pdev->dev); + vfe_dev->hw_info = + (struct msm_vfe_hardware_info *) match_dev->data; + pr_err("%s: in checking of node %s\n", __func__, match_dev->compatible); + } else { + vfe_dev->hw_info = (struct msm_vfe_hardware_info *) + platform_get_device_id(pdev)->driver_data; + } + + if (!vfe_dev->hw_info) { + pr_err("%s: No vfe hardware info\n", __func__); + kfree(vfe_dev);//prevent + return -EINVAL; + } + pr_err("%s: device id = %d\n", __func__, pdev->id); + + vfe_dev->pdev = pdev; + rc = vfe_dev->hw_info->vfe_ops.core_ops.get_platform_data(vfe_dev); + if (rc < 0) { + pr_err("%s: failed to get platform resources\n", __func__); + kfree(vfe_dev); + return -ENOMEM; + } + + INIT_LIST_HEAD(&vfe_dev->tasklet_q); + tasklet_init(&vfe_dev->vfe_tasklet, + msm_isp_do_tasklet, (unsigned long)vfe_dev); + + v4l2_subdev_init(&vfe_dev->subdev.sd, vfe_dev->hw_info->subdev_ops); + vfe_dev->subdev.sd.internal_ops = + vfe_dev->hw_info->subdev_internal_ops; + snprintf(vfe_dev->subdev.sd.name, + ARRAY_SIZE(vfe_dev->subdev.sd.name), + "vfe"); + vfe_dev->subdev.sd.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; + vfe_dev->subdev.sd.flags |= V4L2_SUBDEV_FL_HAS_EVENTS; + v4l2_set_subdevdata(&vfe_dev->subdev.sd, vfe_dev); + platform_set_drvdata(pdev, &vfe_dev->subdev.sd); + mutex_init(&vfe_dev->realtime_mutex); + mutex_init(&vfe_dev->core_mutex); + spin_lock_init(&vfe_dev->tasklet_lock); + spin_lock_init(&vfe_dev->shared_data_lock); + spin_lock_init(&vfe_dev->halt_lock); + media_entity_init(&vfe_dev->subdev.sd.entity, 0, NULL, 0); + vfe_dev->subdev.sd.entity.type = MEDIA_ENT_T_V4L2_SUBDEV; + vfe_dev->subdev.sd.entity.group_id = MSM_CAMERA_SUBDEV_VFE; + vfe_dev->subdev.sd.entity.name = pdev->name; + vfe_dev->subdev.close_seq = MSM_SD_CLOSE_1ST_CATEGORY | 0x2; + rc = msm_sd_register(&vfe_dev->subdev); + if (rc != 0) { + pr_err("%s: msm_sd_register error = %d\n", __func__, rc); + kfree(vfe_dev); + goto end; + } + + vfe_dev->buf_mgr = &vfe_buf_mgr; + v4l2_subdev_notify(&vfe_dev->subdev.sd, + MSM_SD_NOTIFY_REQ_CB, &vfe_vb2_ops); + rc = msm_isp_create_isp_buf_mgr(vfe_dev->buf_mgr, + &vfe_vb2_ops, &vfe_layout); + if (rc < 0) { + pr_err("%s: Unable to create buffer manager\n", __func__); + msm_sd_unregister(&vfe_dev->subdev); + kfree(vfe_dev); + return -EINVAL; + } + vfe_dev->buf_mgr->ops->register_ctx(vfe_dev->buf_mgr, + &vfe_dev->iommu_ctx[0], vfe_dev->hw_info->num_iommu_ctx); + vfe_dev->vfe_open_cnt = 0; +end: + return rc; +} + +static struct platform_driver vfe_driver = { + .probe = vfe_probe, + .driver = { + .name = "msm_vfe", + .owner = THIS_MODULE, + .of_match_table = msm_vfe_dt_match, + }, + .id_table = msm_vfe_dev_id, +}; + +static int __init msm_vfe_init_module(void) +{ + return platform_driver_register(&vfe_driver); +} + +static void __exit msm_vfe_exit_module(void) +{ + platform_driver_unregister(&vfe_driver); +} + +module_init(msm_vfe_init_module); +module_exit(msm_vfe_exit_module); +MODULE_DESCRIPTION("MSM VFE driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard006/C/0117435_irq-gic-v3-its-platform-msi.c b/pool/shard006/C/0117435_irq-gic-v3-its-platform-msi.c new file mode 100644 index 0000000000000000000000000000000000000000..9cdcda5bb3bd50b8a7212589fcb4481a3874cd02 --- /dev/null +++ b/pool/shard006/C/0117435_irq-gic-v3-its-platform-msi.c @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2013-2015 ARM Limited, All Rights Reserved. + * Author: Marc Zyngier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include + +static struct irq_chip its_pmsi_irq_chip = { + .name = "ITS-pMSI", +}; + +static int of_pmsi_get_dev_id(struct irq_domain *domain, struct device *dev, + u32 *dev_id) +{ + int ret, index = 0; + + /* Suck the DeviceID out of the msi-parent property */ + do { + struct of_phandle_args args; + + ret = of_parse_phandle_with_args(dev->of_node, + "msi-parent", "#msi-cells", + index, &args); + if (args.np == irq_domain_get_of_node(domain)) { + if (WARN_ON(args.args_count != 1)) + return -EINVAL; + *dev_id = args.args[0]; + break; + } + index++; + } while (!ret); + + return ret; +} + +int __weak iort_pmsi_get_dev_id(struct device *dev, u32 *dev_id) +{ + return -1; +} + +static int its_pmsi_prepare(struct irq_domain *domain, struct device *dev, + int nvec, msi_alloc_info_t *info) +{ + struct msi_domain_info *msi_info; + u32 dev_id; + int ret; + + msi_info = msi_get_domain_info(domain->parent); + + if (dev->of_node) + ret = of_pmsi_get_dev_id(domain, dev, &dev_id); + else + ret = iort_pmsi_get_dev_id(dev, &dev_id); + if (ret) + return ret; + + /* ITS specific DeviceID, as the core ITS ignores dev. */ + info->scratchpad[0].ul = dev_id; + + /* Allocate at least 32 MSIs, and always as a power of 2 */ + nvec = max_t(int, 32, roundup_pow_of_two(nvec)); + return msi_info->ops->msi_prepare(domain->parent, + dev, nvec, info); +} + +static struct msi_domain_ops its_pmsi_ops = { + .msi_prepare = its_pmsi_prepare, +}; + +static struct msi_domain_info its_pmsi_domain_info = { + .flags = (MSI_FLAG_USE_DEF_DOM_OPS | MSI_FLAG_USE_DEF_CHIP_OPS), + .ops = &its_pmsi_ops, + .chip = &its_pmsi_irq_chip, +}; + +static const struct of_device_id its_device_id[] = { + { .compatible = "arm,gic-v3-its", }, + {}, +}; + +static int __init its_pmsi_init_one(struct fwnode_handle *fwnode, + const char *name) +{ + struct irq_domain *parent; + + parent = irq_find_matching_fwnode(fwnode, DOMAIN_BUS_NEXUS); + if (!parent || !msi_get_domain_info(parent)) { + pr_err("%s: unable to locate ITS domain\n", name); + return -ENXIO; + } + + if (!platform_msi_create_irq_domain(fwnode, &its_pmsi_domain_info, + parent)) { + pr_err("%s: unable to create platform domain\n", name); + return -ENXIO; + } + + pr_info("Platform MSI: %s domain created\n", name); + return 0; +} + +#ifdef CONFIG_ACPI +static int __init +its_pmsi_parse_madt(union acpi_subtable_headers *header, + const unsigned long end) +{ + struct acpi_madt_generic_translator *its_entry; + struct fwnode_handle *domain_handle; + const char *node_name; + int err = -ENXIO; + + its_entry = (struct acpi_madt_generic_translator *)header; + node_name = kasprintf(GFP_KERNEL, "ITS@0x%lx", + (long)its_entry->base_address); + domain_handle = iort_find_domain_token(its_entry->translation_id); + if (!domain_handle) { + pr_err("%s: Unable to locate ITS domain handle\n", node_name); + goto out; + } + + err = its_pmsi_init_one(domain_handle, node_name); + +out: + kfree(node_name); + return err; +} + +static void __init its_pmsi_acpi_init(void) +{ + acpi_table_parse_madt(ACPI_MADT_TYPE_GENERIC_TRANSLATOR, + its_pmsi_parse_madt, 0); +} +#else +static inline void its_pmsi_acpi_init(void) { } +#endif + +static void __init its_pmsi_of_init(void) +{ + struct device_node *np; + + for (np = of_find_matching_node(NULL, its_device_id); np; + np = of_find_matching_node(np, its_device_id)) { + if (!of_device_is_available(np)) + continue; + if (!of_property_read_bool(np, "msi-controller")) + continue; + + its_pmsi_init_one(of_node_to_fwnode(np), np->full_name); + } +} + +static int __init its_pmsi_init(void) +{ + its_pmsi_of_init(); + its_pmsi_acpi_init(); + return 0; +} +early_initcall(its_pmsi_init); diff --git a/pool/shard006/C/0117438_meta-background.c b/pool/shard006/C/0117438_meta-background.c new file mode 100644 index 0000000000000000000000000000000000000000..ac8ec906e8c78e0d931bc89b82940dec2d7bbfc4 --- /dev/null +++ b/pool/shard006/C/0117438_meta-background.c @@ -0,0 +1,245 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ +/* + * meta-background.c: Actor used to create a background fade effect + * + * Copyright 2016 Linux Mint + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Suite 500, Boston, MA + * 02110-1335, USA. + * + * Portions adapted from gnome-shell/src/shell-global.c + * and meta-window-actor.c + */ + +#include "config.h" + +#include +#include "cogl-utils.h" +#include +#include "meta-background-actor-private.h" + +struct _MetaBackgroundPrivate +{ + MetaScreen *screen; + CoglHandle material; + + float texture_width; + float texture_height; + + cairo_region_t *visible_region; +}; + +G_DEFINE_TYPE (MetaBackground, meta_background, CLUTTER_TYPE_ACTOR); + +static void +meta_background_dispose (GObject *object) +{ + MetaBackground *self = META_BACKGROUND (object); + MetaBackgroundPrivate *priv = self->priv; + + meta_background_set_visible_region (self, NULL); + + if (priv->material != COGL_INVALID_HANDLE) + { + cogl_handle_unref (priv->material); + priv->material = COGL_INVALID_HANDLE; + } + + G_OBJECT_CLASS (meta_background_parent_class)->dispose (object); +} + +static void +meta_background_get_preferred_width (ClutterActor *actor, + gfloat for_height, + gfloat *min_width_p, + gfloat *natural_width_p) +{ + MetaBackground *self = META_BACKGROUND (actor); + MetaBackgroundPrivate *priv = self->priv; + int width, height; + + meta_screen_get_size (priv->screen, &width, &height); + + if (min_width_p) + *min_width_p = width; + if (natural_width_p) + *natural_width_p = width; +} + +static void +meta_background_get_preferred_height (ClutterActor *actor, + gfloat for_width, + gfloat *min_height_p, + gfloat *natural_height_p) + +{ + MetaBackground *self = META_BACKGROUND (actor); + MetaBackgroundPrivate *priv = self->priv; + int width, height; + + meta_screen_get_size (priv->screen, &width, &height); + + if (min_height_p) + *min_height_p = height; + if (natural_height_p) + *natural_height_p = height; +} + +static void +meta_background_paint (ClutterActor *actor) +{ + MetaBackground *self = META_BACKGROUND (actor); + MetaBackgroundPrivate *priv = self->priv; + guint8 opacity = clutter_actor_get_paint_opacity (actor); + guint8 color_component; + int width, height; + + meta_screen_get_size (priv->screen, &width, &height); + + color_component = (int)(0.5 + opacity); + + cogl_material_set_color4ub (priv->material, + color_component, + color_component, + color_component, + opacity); + + cogl_set_source (priv->material); + + if (priv->visible_region) + { + int n_rectangles = cairo_region_num_rectangles (priv->visible_region); + int i; + + for (i = 0; i < n_rectangles; i++) + { + cairo_rectangle_int_t rect; + cairo_region_get_rectangle (priv->visible_region, i, &rect); + + cogl_rectangle_with_texture_coords (rect.x, rect.y, + rect.x + rect.width, rect.y + rect.height, + rect.x / priv->texture_width, + rect.y / priv->texture_height, + (rect.x + rect.width) / priv->texture_width, + (rect.y + rect.height) / priv->texture_height); + } + } + else + { + cogl_rectangle_with_texture_coords (0.0f, 0.0f, + width, height, + 0.0f, 0.0f, + width / priv->texture_width, + height / priv->texture_height); + } +} + +static void +meta_background_class_init (MetaBackgroundClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + ClutterActorClass *actor_class = CLUTTER_ACTOR_CLASS (klass); + + g_type_class_add_private (klass, sizeof (MetaBackgroundPrivate)); + + object_class->dispose = meta_background_dispose; + + actor_class->get_preferred_width = meta_background_get_preferred_width; + actor_class->get_preferred_height = meta_background_get_preferred_height; + actor_class->paint = meta_background_paint; +} + +static void +meta_background_init (MetaBackground *self) +{ + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, + META_TYPE_BACKGROUND, + MetaBackgroundPrivate); +} + +ClutterActor * +meta_background_new (MetaScreen *screen) +{ + MetaBackground *self; + MetaBackgroundPrivate *priv; + + self = g_object_new (META_TYPE_BACKGROUND, + NULL); + priv = self->priv; + + priv->screen = screen; + priv->material = meta_create_texture_material (NULL); + + return CLUTTER_ACTOR (self); +} + +void +meta_background_set_layer (MetaBackground *self, + CoglHandle texture) +{ + MetaBackgroundPrivate *priv = self->priv; + MetaDisplay *display = meta_screen_get_display (priv->screen); + + /* This may trigger destruction of an old texture pixmap, which, if + * the underlying X pixmap is already gone has the tendency to trigger + * X errors inside DRI. For safety, trap errors */ + meta_error_trap_push (display); + cogl_material_set_layer (priv->material, 0, texture); + meta_error_trap_pop (display); + + priv->texture_width = cogl_texture_get_width (texture); + priv->texture_height = cogl_texture_get_height (texture); + + clutter_actor_queue_redraw (CLUTTER_ACTOR (self)); +} + +void +meta_background_set_layer_wrap_mode (MetaBackground *self, + CoglMaterialWrapMode wrap_mode) +{ + MetaBackgroundPrivate *priv = self->priv; + + cogl_material_set_layer_wrap_mode (priv->material, 0, wrap_mode); +} + +void +meta_background_set_visible_region (MetaBackground *self, + cairo_region_t *visible_region) +{ + MetaBackgroundPrivate *priv; + + g_return_if_fail (META_IS_BACKGROUND (self)); + + priv = self->priv; + + if (priv->visible_region) + { + cairo_region_destroy (priv->visible_region); + priv->visible_region = NULL; + } + + if (visible_region) + { + cairo_rectangle_int_t screen_rect = { 0 }; + meta_screen_get_size (priv->screen, &screen_rect.width, &screen_rect.height); + + /* Doing the intersection here is probably unnecessary - MetaWindowGroup + * should never compute a visible area that's larger than the root screen! + * but it's not that expensive and adds some extra robustness. + */ + priv->visible_region = cairo_region_create_rectangle (&screen_rect); + cairo_region_intersect (priv->visible_region, visible_region); + } +} \ No newline at end of file diff --git a/pool/shard006/C/0117440_pcm186x-i2c.c b/pool/shard006/C/0117440_pcm186x-i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..543621232d604a4227f8df988c34dbc249dfb4fa --- /dev/null +++ b/pool/shard006/C/0117440_pcm186x-i2c.c @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Texas Instruments PCM186x Universal Audio ADC - I2C + * + * Copyright (C) 2015-2017 Texas Instruments Incorporated - http://www.ti.com + * Andreas Dannenberg + * Andrew F. Davis + */ + +#include +#include +#include + +#include "pcm186x.h" + +static const struct of_device_id pcm186x_of_match[] = { + { .compatible = "ti,pcm1862", .data = (void *)PCM1862 }, + { .compatible = "ti,pcm1863", .data = (void *)PCM1863 }, + { .compatible = "ti,pcm1864", .data = (void *)PCM1864 }, + { .compatible = "ti,pcm1865", .data = (void *)PCM1865 }, + { } +}; +MODULE_DEVICE_TABLE(of, pcm186x_of_match); + +static int pcm186x_i2c_probe(struct i2c_client *i2c, + const struct i2c_device_id *id) +{ + const enum pcm186x_type type = (enum pcm186x_type)id->driver_data; + int irq = i2c->irq; + struct regmap *regmap; + + regmap = devm_regmap_init_i2c(i2c, &pcm186x_regmap); + if (IS_ERR(regmap)) + return PTR_ERR(regmap); + + return pcm186x_probe(&i2c->dev, type, irq, regmap); +} + +static int pcm186x_i2c_remove(struct i2c_client *i2c) +{ + pcm186x_remove(&i2c->dev); + + return 0; +} + +static const struct i2c_device_id pcm186x_i2c_id[] = { + { "pcm1862", PCM1862 }, + { "pcm1863", PCM1863 }, + { "pcm1864", PCM1864 }, + { "pcm1865", PCM1865 }, + { } +}; +MODULE_DEVICE_TABLE(i2c, pcm186x_i2c_id); + +static struct i2c_driver pcm186x_i2c_driver = { + .probe = pcm186x_i2c_probe, + .remove = pcm186x_i2c_remove, + .id_table = pcm186x_i2c_id, + .driver = { + .name = "pcm186x", + .of_match_table = pcm186x_of_match, + }, +}; +module_i2c_driver(pcm186x_i2c_driver); + +MODULE_AUTHOR("Andreas Dannenberg "); +MODULE_AUTHOR("Andrew F. Davis "); +MODULE_DESCRIPTION("PCM186x Universal Audio ADC I2C Interface Driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard006/C/0117441_fat_mount.c b/pool/shard006/C/0117441_fat_mount.c new file mode 100644 index 0000000000000000000000000000000000000000..cf091a74b95c0bfd5910bf679062ac1d1f56c299 --- /dev/null +++ b/pool/shard006/C/0117441_fat_mount.c @@ -0,0 +1,307 @@ +/* +* (C) Copyright 2007-2013 +* Allwinner Technology Co., Ltd. +* Martin zheng +* +* See file CREDITS for list of people who contributed to this +* project. +* +* 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 "fat_priv.h" + +extern int _FS_FAT_AutoFormat(__fsys_part_t * pPart, int force_type); +/* +********************************************************************************************************************** +* Local functions +********************************************************************************************************************** +*/ + + + +/* +********************************************************************************************************************** +* Global functions +********************************************************************************************************************** +*/ +/* +********************************************************************************************************************** +* +* fsys_fat_ReadBPB +* + Description: + FSYS internal function. Read Bios-Parameter-Block from a device and + copy the relevant data to fsys_fat_aBPBUnit-> + + Parameters: + Idx - Index of device in the device information table + referred by fsys_pDevInfo. + Unit - Unit number. + + Return value: + ==0 - BPB successfully read. + <0 - An error has occured. +*/ + +int fsys_fat_ReadBPB(__fsys_part_t * pPart) +{ + int err; + unsigned char * buffer; + + buffer = (unsigned char*)fsys_fat_malloc(FSYS_FAT_SEC_SIZE); + if (!buffer) + { + return EPDK_FAIL; + } + + err = pPart->pdops.read((void*)buffer, 0, 1, pPart); + if (err < 0) + { + fsys_fat_free(buffer); + return -1; + } + /* Assign fsys_fat_aBPBUnit */ + fsys_fat_aBPBUnit->BytesPerSec = buffer[11] + 256 * buffer[12]; /* _512_,1024,2048,4096 */ + fsys_fat_aBPBUnit->SecPerClus = buffer[13]; /* sec in allocation unit */ + fsys_fat_aBPBUnit->RsvdSecCnt = buffer[14] + 256 * buffer[15]; /* 1 for FAT12 & FAT16 */ + fsys_fat_aBPBUnit->NumFATs = buffer[16]; /* 2 */ + fsys_fat_aBPBUnit->RootEntCnt = buffer[17] + 256 * buffer[18]; /* number of root dir entries */ + fsys_fat_aBPBUnit->TotSec16 = buffer[19] + 256 * buffer[20]; /* RSVD + FAT + ROOT + FATA(<64k) */ + fsys_fat_aBPBUnit->FATSz16 = buffer[22] + 256 * buffer[23]; /* number of FAT sectors */ + fsys_fat_aBPBUnit->TotSec32 = buffer[32] + 0x100UL * buffer[33] /* RSVD + FAT + ROOT + FATA(>=64k)*/ + + 0x10000UL * buffer[34] + + 0x1000000UL * buffer[35]; + + if(!memcmp(&buffer[0x36], "FAT16 ", 8)) + { + eGon2_printf("fattype FAT16\n"); + fsys_fat_aBPBUnit->fattype = 0; + } + else if(!memcmp(&buffer[0x36], "FAT12 ", 8)) + { + eGon2_printf("fattype FAT12\n"); + fsys_fat_aBPBUnit->fattype = 1; + } + else + { + eGon2_printf("fattype FAT32\n"); + fsys_fat_aBPBUnit->fattype = 2; + } + + if (fsys_fat_aBPBUnit->FATSz16 == 0) + { + fsys_fat_aBPBUnit->FATSz32 = buffer[36] + 0x100UL * buffer[37] /* number of FAT sectors */ + + 0x10000UL * buffer[38] + + 0x1000000UL * buffer[39]; + fsys_fat_aBPBUnit->ExtFlags = buffer[40] + 256 * buffer[41]; /* mirroring info */ + fsys_fat_aBPBUnit->RootClus = buffer[44] + 0x100UL * buffer[45] /* root dir clus for FAT32 */ + + 0x10000UL * buffer[46] + + 0x1000000UL * buffer[47]; + fsys_fat_aBPBUnit->FSInfo = buffer[48] + 256 * buffer[49]; /* position of FSInfo structure */ + } + else + { + fsys_fat_aBPBUnit->FATSz32 = 0; + fsys_fat_aBPBUnit->ExtFlags = 0; + fsys_fat_aBPBUnit->RootClus = 0; + fsys_fat_aBPBUnit->FSInfo = 0; + } + fsys_fat_aBPBUnit->Signature = buffer[FSYS_FAT_SEC_SIZE-2] + 256 * buffer[FSYS_FAT_SEC_SIZE-1]; + fsys_fat_free(buffer); + return err; +} +/* +********************************************************************************************************************** +* +* fsys_fat_mount +* + Description: + ½«Ò»¸ö¾ßÌåµÄ·ÖÇø¹Ò½Óµ½ÎļþϵͳÉÏ + + Parameters: + pPart - Pointer to partition handle. + + Return value: + ³É¹¦ + ʧ°Ü£º·ÖÇøÒѾ­±»¹ÒÔØ£¬»òÕßÎļþϵͳ²»ÄÜÖ§³Ö£¬»òÕß·ÖÇø±»ÆÆ»µ +*/ + +__s32 fsys_fat_mount(__fsys_part_t * pPart) +{ + int err; + int lexp; + +// if(pPart->supper_data) +// { +// return EPDK_FAIL; +// } + + pPart->supper_data = (__hdle)fsys_fat_bpb_malloc(); + if(!pPart->supper_data) + { + return EPDK_FAIL; + } + + err = fsys_fat_ReadBPB(pPart); + if(err < 0) + { + fsys_fat_bpb_free((void*)pPart->supper_data); + pPart->supper_data = 0; + return EPDK_FAIL; + } + + if (fsys_fat_aBPBUnit->Signature != 0xaa55) + { + err = fsys_fat_ReadBPB(pPart); + lexp = (err < 0); + lexp = lexp || (fsys_fat_aBPBUnit->Signature != 0xaa55); + if (lexp) + { + fsys_fat_bpb_free( (void*)pPart->supper_data); + pPart->supper_data = 0; + return EPDK_FAIL; + } + } + if (fsys_fat_aBPBUnit->NumFATs != 2) + { + fsys_fat_bpb_free( (void*)pPart->supper_data); + pPart->supper_data = 0; + return EPDK_FAIL; /* Only 2 FATs are supported */ + } + if (fsys_fat_aBPBUnit->FATSz16 == 0) + { + if (fsys_fat_aBPBUnit->ExtFlags & 0x0080) + { + fsys_fat_bpb_free( (void*)pPart->supper_data); + pPart->supper_data = 0; + return EPDK_FAIL; /* Only mirroring at runtime supported */ + } + } + + return EPDK_OK; +} + + +/* +********************************************************************************************************************** +* +* fsys_fat_unmount +* + Description: + ½«Ò»¸ö¾ßÌåµÄ·ÖÇøÍÑÀëÎļþϵͳ + + Parameters: + pPart - Pointer to partition handle. + + Return value: + ³É¹¦ + ʧ°Ü£º·ÖÇøÒѾ­±»Ð¶µô +*/ + +__s32 fsys_fat_unmount(__fsys_part_t *pPart) +{ + /* Çå³ýÎļþϵͳ¸½×ÅÔÚ·ÖÇøÉϵÄ˽ÓеÄÐÅÏ¢ */ + fsys_fat_bpb_free( (void*)pPart->supper_data); + pPart->supper_data = 0; + return EPDK_OK; +} + + + +/* +********************************************************************************************************************** +* +* fsys_fatfs_identify +* + Description: + ʶ±ð·ÖÇøÊÇ·ñΪfatfsÎļþϵͳ + + Parameters: + + + Return value: + +*/ + +__bool fsys_fatfs_identify(__fsys_part_t * pPart) +{ + __u32 err; + + unsigned char * buffer; + + buffer = (unsigned char*)fsys_fat_malloc(FSYS_FAT_SEC_SIZE); + if (!buffer) + { + return EPDK_FAIL; + } + + err = pPart->pdops.read((void*)buffer, 0, 1, pPart); + if (err <= 0) + { + fsys_fat_free(buffer); + return -1; + } + + if(buffer[16] != 2) + { + fsys_fat_free(buffer); + return EPDK_FALSE; + } + if(buffer[FSYS_FAT_SEC_SIZE-2] + 256 * buffer[FSYS_FAT_SEC_SIZE-1] != 0xaa55) + { + fsys_fat_free(buffer); + return EPDK_FALSE; + } + + fsys_fat_free(buffer); + return EPDK_TRUE; +} +/* +********************************************************************************************************************** +* +* fsys_fatfs_format +* + Description: + + + Parameters: + + + Return value: + +*/ +__s32 fsys_fatfs_format(__fsys_part_t * pPart, int force_type) +{ + return _FS_FAT_AutoFormat(pPart, force_type); +} +/* +********************************************************************************************************************** +* +* fsys_fatfs_checkdisk +* + Description: + + + Parameters: + + + Return value: + +*/ +__s32 fsys_fatfs_checkdisk(__fsys_part_t * pPart) +{ + return EPDK_OK; +} diff --git a/pool/shard006/C/0117446_virkeycode.c b/pool/shard006/C/0117446_virkeycode.c new file mode 100644 index 0000000000000000000000000000000000000000..e09aaadaa7bc6c29ced6d85163e1ae49ea487002 --- /dev/null +++ b/pool/shard006/C/0117446_virkeycode.c @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2011 Lai Jiangshan + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see + * . + * + */ + +#include +#include "virkeycode.h" +#include +#include + +#include "virkeycodetable_atset1.h" +#include "virkeycodetable_atset2.h" +#include "virkeycodetable_atset3.h" +#include "virkeycodetable_linux.h" +#include "virkeycodetable_osx.h" +#include "virkeycodetable_rfb.h" +#include "virkeycodetable_usb.h" +#include "virkeycodetable_win32.h" +#include "virkeycodetable_xt.h" +#include "virkeycodetable_xtkbd.h" +#include "virkeynametable_linux.h" +#include "virkeynametable_osx.h" +#include "virkeynametable_win32.h" + +static const char **virKeymapNames[VIR_KEYCODE_SET_LAST] = { + [VIR_KEYCODE_SET_LINUX] = virKeyNameTable_linux, + [VIR_KEYCODE_SET_OSX] = virKeyNameTable_osx, + [VIR_KEYCODE_SET_WIN32] = virKeyNameTable_win32, +}; + +static const unsigned short *virKeymapValues[VIR_KEYCODE_SET_LAST] = { + [VIR_KEYCODE_SET_LINUX] = virKeyCodeTable_linux, + [VIR_KEYCODE_SET_XT] = virKeyCodeTable_xt, + [VIR_KEYCODE_SET_ATSET1] = virKeyCodeTable_atset1, + [VIR_KEYCODE_SET_ATSET2] = virKeyCodeTable_atset2, + [VIR_KEYCODE_SET_ATSET3] = virKeyCodeTable_atset3, + [VIR_KEYCODE_SET_OSX] = virKeyCodeTable_osx, + [VIR_KEYCODE_SET_XT_KBD] = virKeyCodeTable_xtkbd, + [VIR_KEYCODE_SET_USB] = virKeyCodeTable_usb, + [VIR_KEYCODE_SET_WIN32] = virKeyCodeTable_win32, + [VIR_KEYCODE_SET_RFB] = virKeyCodeTable_rfb, +}; + +#define VIR_KEYMAP_ENTRY_MAX ARRAY_CARDINALITY(virKeyCodeTable_linux) + +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_xt)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_atset1)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_atset2)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_atset3)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_osx)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_xtkbd)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_usb)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_win32)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyCodeTable_rfb)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyNameTable_linux)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyNameTable_osx)); +verify(VIR_KEYMAP_ENTRY_MAX == ARRAY_CARDINALITY(virKeyNameTable_win32)); + +VIR_ENUM_IMPL(virKeycodeSet, VIR_KEYCODE_SET_LAST, + "linux", + "xt", + "atset1", + "atset2", + "atset3", + "os_x", + "xt_kbd", + "usb", + "win32", + "rfb", +); + +int virKeycodeValueFromString(virKeycodeSet codeset, + const char *keyname) +{ + size_t i; + + for (i = 0; i < VIR_KEYMAP_ENTRY_MAX; i++) { + if (!virKeymapNames[codeset] || + !virKeymapValues[codeset]) + continue; + + const char *name = virKeymapNames[codeset][i]; + + if (name && STREQ_NULLABLE(name, keyname)) + return virKeymapValues[codeset][i]; + } + + return -1; +} + + +int virKeycodeValueTranslate(virKeycodeSet from_codeset, + virKeycodeSet to_codeset, + int key_value) +{ + size_t i; + + if (key_value < 0) + return -1; + + + for (i = 0; i < VIR_KEYMAP_ENTRY_MAX; i++) { + if (virKeymapValues[from_codeset][i] == key_value) + return virKeymapValues[to_codeset][i]; + } + + return -1; +} diff --git a/pool/shard006/C/0117447_autoconf.c b/pool/shard006/C/0117447_autoconf.c new file mode 100644 index 0000000000000000000000000000000000000000..b7fde55bb277edb1dc4143e43f1aee473e9a1751 --- /dev/null +++ b/pool/shard006/C/0117447_autoconf.c @@ -0,0 +1,125 @@ +/* $NetBSD: autoconf.c,v 1.6 2003/07/15 01:37:37 lukem Exp $ */ + +/* + * Copyright (C) 1995, 1996 Wolfgang Solfrank. + * Copyright (C) 1995, 1996 TooLs GmbH. + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by TooLs GmbH. + * 4. The name of TooLs GmbH may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``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 TOOLS GMBH 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 +__KERNEL_RCSID(0, "$NetBSD: autoconf.c,v 1.6 2003/07/15 01:37:37 lukem Exp $"); + +#include +#include +#include +#include + +#include /* For COM_FREQ */ + +#include +#include + +struct device *booted_device; +int booted_partition; + +/* + * List of port-specific devices to attach to the processor local bus. + */ +static const struct plb_dev local_plb_devs [] = { + { "pbus", }, + { NULL } +}; + +/* + * Determine device configuration for a machine. + */ +void +cpu_configure(void) +{ + + intr_init(); + calc_delayconst(); + + /* Make sure that timers run at CPU frequency */ + mtdcr(DCR_CPC0_CR1, mfdcr(DCR_CPC0_CR1) & ~CPC0_CR1_CETE); + + if (config_rootfound("plb", &local_plb_devs) == NULL) + panic("configure: plb not configured"); + + printf("biomask %x netmask %x ttymask %x\n", (u_short)imask[IPL_BIO], + (u_short)imask[IPL_NET], (u_short)imask[IPL_TTY]); + + (void)spl0(); + + /* + * Now allow hardware interrupts. + */ + asm volatile ("wrteei 1"); +} + +/* + * Setup root device. + * Configure swap area. + */ +void +cpu_rootconf(void) +{ + + setroot(booted_device, booted_partition); +} + +void +device_register(struct device *dev, void *aux) +{ + struct device *parent = dev->dv_parent; + + if (strcmp(dev->dv_cfdata->cf_name, "com") == 0 && + strcmp(parent->dv_cfdata->cf_name, "opb") == 0) { + /* Set the frequency of the on-chip UART. */ + int freq = COM_FREQ * 6; + + if (prop_set(dev_propdb, dev, "frequency", + &freq, sizeof(freq), PROP_INT, 0) != 0) + printf("WARNING: unable to set frequency " + "property for %s\n", dev->dv_xname); + return; + } + + if (strcmp(dev->dv_cfdata->cf_name, "emac") == 0 && + strcmp(parent->dv_cfdata->cf_name, "opb") == 0) { + /* Set the mac-addr of the on-chip Ethernet. */ + /* XXX 405GP only has one; what about CPUs with two? */ + if (prop_set(dev_propdb, dev, "mac-addr", + &board_data.mac_address_local, + sizeof(board_data.mac_address_local), + PROP_CONST, 0) != 0) + printf("WARNING: unable to set mac-addr " + "property for %s\n", dev->dv_xname); + return; + } +} diff --git a/pool/shard006/C/0117452_xfont.c b/pool/shard006/C/0117452_xfont.c new file mode 100644 index 0000000000000000000000000000000000000000..2c2f1d3b43b3b3c316736be7f255c5e10e8ee59f --- /dev/null +++ b/pool/shard006/C/0117452_xfont.c @@ -0,0 +1,244 @@ +/* Copyright (c) 2001, Stanford University + * All rights reserved + * + * See the file LICENSE.txt for information on redistributing this software. + */ + +#include "chromium.h" +#include "cr_error.h" +#include "cr_mem.h" +#include "stub.h" + +/** code borrowed from Mesa */ + + +/** Fill a BITMAP with a character C from thew current font + in the graphics context GC. WIDTH is the width in bytes + and HEIGHT is the height in bits. + + Note that the generated bitmaps must be used with + + glPixelStorei (GL_UNPACK_SWAP_BYTES, GL_FALSE); + glPixelStorei (GL_UNPACK_LSB_FIRST, GL_FALSE); + glPixelStorei (GL_UNPACK_ROW_LENGTH, 0); + glPixelStorei (GL_UNPACK_SKIP_ROWS, 0); + glPixelStorei (GL_UNPACK_SKIP_PIXELS, 0); + glPixelStorei (GL_UNPACK_ALIGNMENT, 1); + + Possible optimizations: + + * use only one reusable pixmap with the maximum dimensions. + * draw the entire font into a single pixmap (careful with + proportional fonts!). +*/ + + +/** + * Generate OpenGL-compatible bitmap. + */ +static void +fill_bitmap(Display *dpy, Window win, GC gc, + unsigned int width, unsigned int height, + int x0, int y0, unsigned int c, GLubyte *bitmap) +{ + XImage *image; + unsigned int x, y; + Pixmap pixmap; + XChar2b char2b; + + pixmap = XCreatePixmap(dpy, win, 8*width, height, 1); + XSetForeground(dpy, gc, 0); + XFillRectangle(dpy, pixmap, gc, 0, 0, 8*width, height); + XSetForeground(dpy, gc, 1); + + char2b.byte1 = (c >> 8) & 0xff; + char2b.byte2 = (c & 0xff); + + XDrawString16(dpy, pixmap, gc, x0, y0, &char2b, 1); + + image = XGetImage(dpy, pixmap, 0, 0, 8*width, height, 1, XYPixmap); + if (image) { + /* Fill the bitmap (X11 and OpenGL are upside down wrt each other). */ + for (y = 0; y < height; y++) + for (x = 0; x < 8*width; x++) + if (XGetPixel(image, x, y)) + bitmap[width*(height - y - 1) + x/8] |= (1 << (7 - (x % 8))); + XDestroyImage(image); + } + + XFreePixmap(dpy, pixmap); +} + +/* + * determine if a given glyph is valid and return the + * corresponding XCharStruct. + */ +static XCharStruct *isvalid(XFontStruct *fs, unsigned int which) +{ + unsigned int rows, pages; + unsigned int byte1 = 0, byte2 = 0; + int i, valid = 1; + + rows = fs->max_byte1 - fs->min_byte1 + 1; + pages = fs->max_char_or_byte2 - fs->min_char_or_byte2 + 1; + + if (rows == 1) { + /* "linear" fonts */ + if ((fs->min_char_or_byte2 > which) || + (fs->max_char_or_byte2 < which)) valid = 0; + } + else { + /* "matrix" fonts */ + byte2 = which & 0xff; + byte1 = which >> 8; + if ((fs->min_char_or_byte2 > byte2) || + (fs->max_char_or_byte2 < byte2) || + (fs->min_byte1 > byte1) || + (fs->max_byte1 < byte1)) valid = 0; + } + + if (valid) { + if (fs->per_char) { + if (rows == 1) { + /* "linear" fonts */ + return fs->per_char + (which-fs->min_char_or_byte2); + } + else { + /* "matrix" fonts */ + i = ((byte1 - fs->min_byte1) * pages) + + (byte2 - fs->min_char_or_byte2); + return fs->per_char + i; + } + } + else { + return &fs->min_bounds; + } + } + return NULL; +} + + +void stubUseXFont( Display *dpy, Font font, int first, int count, int listbase ) +{ + Window win; + Pixmap pixmap; + GC gc; + XGCValues values; + unsigned long valuemask; + XFontStruct *fs; + GLint swapbytes, lsbfirst, rowlength; + GLint skiprows, skippixels, alignment; + unsigned int max_width, max_height, max_bm_width, max_bm_height; + GLubyte *bm; + int i; + + win = RootWindow(dpy, DefaultScreen(dpy)); + + fs = XQueryFont(dpy, font); + if (!fs) { + crWarning("Couldn't get font structure information"); + return; + } + + /* Allocate a bitmap that can fit all characters. */ + max_width = fs->max_bounds.rbearing - fs->min_bounds.lbearing; + max_height = fs->max_bounds.ascent + fs->max_bounds.descent; + max_bm_width = (max_width + 7) / 8; + max_bm_height = max_height; + + bm = (GLubyte *) crAlloc((max_bm_width * max_bm_height) * sizeof(GLubyte)); + if (!bm) { + XFreeFontInfo( NULL, fs, 1 ); + crWarning("Couldn't allocate bitmap in glXUseXFont()"); + return; + } + + /* Save the current packing mode for bitmaps. */ + glGetIntegerv(GL_UNPACK_SWAP_BYTES, &swapbytes); + glGetIntegerv(GL_UNPACK_LSB_FIRST, &lsbfirst); + glGetIntegerv(GL_UNPACK_ROW_LENGTH, &rowlength); + glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skiprows); + glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skippixels); + glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment); + + /* Enforce a standard packing mode which is compatible with + fill_bitmap() from above. This is actually the default mode, + except for the (non)alignment. */ + glPixelStorei(GL_UNPACK_SWAP_BYTES, GL_FALSE); + glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + glPixelStorei(GL_UNPACK_SKIP_ROWS, 0); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + pixmap = XCreatePixmap(dpy, win, 10, 10, 1); + values.foreground = BlackPixel(dpy, DefaultScreen (dpy)); + values.background = WhitePixel(dpy, DefaultScreen (dpy)); + values.font = fs->fid; + valuemask = GCForeground | GCBackground | GCFont; + gc = XCreateGC(dpy, pixmap, valuemask, &values); + XFreePixmap(dpy, pixmap); + + for (i = 0; i < count; i++) { + unsigned int width, height, bm_width, bm_height; + GLfloat x0, y0, dx, dy; + XCharStruct *ch; + int x, y; + unsigned int c = first + i; + int list = listbase + i; + int valid; + + /* check on index validity and get the bounds */ + ch = isvalid(fs, c); + if (!ch) { + ch = &fs->max_bounds; + valid = 0; + } + else { + valid = 1; + } + + /* glBitmap()' parameters: + straight from the glXUseXFont(3) manpage. */ + width = ch->rbearing - ch->lbearing; + height = ch->ascent + ch->descent; + x0 = -ch->lbearing; + y0 = ch->descent - 0; /* XXX used to subtract 1 here */ + /* but that caused a conformace failure */ + dx = ch->width; + dy = 0; + + /* X11's starting point. */ + x = -ch->lbearing; + y = ch->ascent; + + /* Round the width to a multiple of eight. We will use this also + for the pixmap for capturing the X11 font. This is slightly + inefficient, but it makes the OpenGL part real easy. */ + bm_width = (width + 7) / 8; + bm_height = height; + + glNewList(list, GL_COMPILE); + if (valid && (bm_width > 0) && (bm_height > 0)) { + crMemset(bm, '\0', bm_width * bm_height); + fill_bitmap(dpy, win, gc, bm_width, bm_height, x, y, c, bm); + glBitmap(width, height, x0, y0, dx, dy, bm); + } + else { + glBitmap(0, 0, 0.0, 0.0, dx, dy, NULL); + } + glEndList(); + } + + crFree(bm); + XFreeFontInfo(NULL, fs, 1); + XFreeGC(dpy, gc); + + /* Restore saved packing modes. */ + glPixelStorei(GL_UNPACK_SWAP_BYTES, swapbytes); + glPixelStorei(GL_UNPACK_LSB_FIRST, lsbfirst); + glPixelStorei(GL_UNPACK_ROW_LENGTH, rowlength); + glPixelStorei(GL_UNPACK_SKIP_ROWS, skiprows); + glPixelStorei(GL_UNPACK_SKIP_PIXELS, skippixels); + glPixelStorei(GL_UNPACK_ALIGNMENT, alignment); +} diff --git a/pool/shard006/C/0117454_binarymsg.c b/pool/shard006/C/0117454_binarymsg.c new file mode 100644 index 0000000000000000000000000000000000000000..2af97930508dea1a577212ac770012a1c1a8ecd9 --- /dev/null +++ b/pool/shard006/C/0117454_binarymsg.c @@ -0,0 +1,56 @@ +#include +#include "m_pd.h" + +static void pd_tilde_putfloat(float f, FILE *fd) +{ + putc(A_FLOAT, fd); + fwrite(&f, sizeof(f), 1, fd); +} + +static void pd_tilde_putsymbol(t_symbol *s, FILE *fd) +{ + char *sp = s->s_name; + putc(A_SYMBOL, fd); + do + putc(*sp, fd); + while (*sp++); +} + +static int pd_tilde_getatom(t_atom *ap, FILE *fd) +{ + char buf[MAXPDSTRING]; + while (1) + { + int type = getc(fd), fill; + float f; + switch (type) + { + case EOF: + return (0); + case A_SEMI: + SETSEMI(ap); + return (1); + case A_FLOAT: + if (fread(&f, sizeof(f), 1, fd) >= 1) + { + SETFLOAT(ap, f); + return (1); + } + else return (0); + case A_SYMBOL: + for (fill = 0; fill < MAXPDSTRING; fill++) + { + int c = getc(fd); + if (c == EOF) + return (0); + else buf[fill] = c; + if (!c) + { + SETSYMBOL(ap, gensym(buf)); + return (1); + } + } + return (0); + } + } +} diff --git a/pool/shard006/C/0117461_httpserver-netconn.c b/pool/shard006/C/0117461_httpserver-netconn.c new file mode 100644 index 0000000000000000000000000000000000000000..aaf2338a7d894f01a350135d3bf4b98ef4e33093 --- /dev/null +++ b/pool/shard006/C/0117461_httpserver-netconn.c @@ -0,0 +1,265 @@ +/** + ****************************************************************************** + * @file LwIP/LwIP_HTTP_Server_Netconn_RTOS/Src/httpser-netconn.c + * @author MCD Application Team + * @version V1.0.0 + * @date 18-November-2015 + * @brief Basic http server implementation using LwIP netconn API + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2015 STMicroelectronics

+ * + * 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 "lwip/opt.h" +#include "lwip/arch.h" +#include "lwip/api.h" +#include "string.h" +#include "httpserver-netconn.h" +#include "cmsis_os.h" +#include "../webpages/index.h" +#include "temp.h" +#include +#include +#include + + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define WEBSERVER_THREAD_PRIO ( tskIDLE_PRIORITY + 4 ) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +u32_t nPageHits = 0; +#define LD1_Pin GPIO_PIN_0 +#define LD1_GPIO_Port GPIOB + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +static char float_buf[15]; +static xQueueHandle m_queue_handle; + +static int block_on_queue(int block_ms) +{ + const portTickType xTicksToWait = block_ms/portTICK_RATE_MS; + int data = 0; + portBASE_TYPE xStatus = xQueueReceive(m_queue_handle, &data, xTicksToWait); + + if(xStatus == pdPASS) + { + return data; + } + else + { + return -1; + } + +} + +/** + * HTTP request debug routine + */ +static int request_print_counter = 0; +static int print_body(char * request, u16_t len) { + if (request_print_counter >= len) { + request_print_counter = 0; + } + return request[request_print_counter++]; +} +/** + * find the index of the body after consecutive \n + * @param request + * @param len + * @return + */ +static int get_body_index(char * request, u16_t len) +{ + u16_t body_idx = 0; + u16_t idx = 0; + + for(; idx < len; idx++) { + if((request[idx] == '\n')) { + body_idx = idx; + body_idx++; + } + } + return body_idx; +} + + +static long int update_leds(char * delimited_led_state) +{ + long int led_state = strtol(delimited_led_state, NULL, 10); + + HAL_GPIO_WritePin(LD1_GPIO_Port, LD1_Pin, led_state & 1); + HAL_GPIO_WritePin(LD1_GPIO_Port, LD2_Pin, led_state & 2); + HAL_GPIO_WritePin(LD1_GPIO_Port, LD3_Pin, led_state & 4); + + return led_state; +} + +static void float_to_str(float val, char * buf) +{ + int d1 = val; // Get the integer part (678). + float f2 = val - d1; // Get fractional part (0.01234567). + int d2 = trunc(f2 * 10000); // Turn into integer (123). +// float f3 = f2 * 10000 - d2; // Get next fractional part (0.4567). +// int d3 = trunc(f3 * 10000); // Turn into integer (4567). + + sprintf(buf, "%d.%04d", d1, d2); +} + +/** + * @brief serve tcp connection + * @param conn: pointer on connection structure + * @retval None + */ +void http_server_serve(struct netconn *conn) +{ + struct netbuf *inbuf; + err_t recv_err; + char* buf; + u16_t buflen; + + /* Read the data from the port, blocking if nothing yet there. + We assume the request (the part we care about) is in one netbuf */ + recv_err = netconn_recv(conn, &inbuf); + + if (recv_err == ERR_OK) + { + if (netconn_err(conn) == ERR_OK) + { + netbuf_data(inbuf, (void**)&buf, &buflen); + + /* Is this an HTTP GET command? (only check the first 5 chars, since + there are other formats for GET, and we're keeping it very simple )*/ + if ((buflen >=5)) + { + if (strncmp((char const *)buf,"GET /index.html",15)==0) { + netconn_write(conn, (const unsigned char*)index_html, index_html_len, NETCONN_NOCOPY); + } + if (strncmp((char const *)buf,"GET /led1", 9) == 0) { + HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin); + } + if (strncmp((char const *)buf,"GET /led2", 9) == 0) { + HAL_GPIO_TogglePin(LD2_GPIO_Port, LD2_Pin); + } + if (strncmp((char const *)buf,"GET /led3", 9) == 0) { + HAL_GPIO_TogglePin(LD3_GPIO_Port, LD3_Pin); + } + if (strncmp((char const *)buf,"POST /test", 10) == 0) + { + //static int buf_incrementor = 10; + + netconn_write(conn, (const unsigned char *)buf, buflen, NETCONN_NOCOPY); + } + if(strncmp((char const *)buf, "POST /printreq", 15) == 0) { + int body_char = print_body(buf, buflen); + sprintf(buf, "%d %d \n", request_print_counter, body_char); + netconn_write(conn, (const unsigned char*)buf, strlen(buf), NETCONN_NOCOPY); + } + + if (strncmp((char const *)buf, "GET /irq", 8) == 0) + { + int body_offset = 9;//get_body_index(buf, buflen); + int led_status = update_leds(&buf[body_offset]); + int switch_count = block_on_queue(100); + float_to_str(getMCUTemperature(), float_buf); + sprintf(buf, "%s %d %d \n", float_buf, switch_count, led_status); + netconn_write(conn, (const unsigned char *)buf, strlen(buf), NETCONN_NOCOPY); + } + if (strncmp((char const *)buf,"GET /btn1", 9) == 0) { + netconn_write(conn, (const unsigned char*)"OFF", 3, NETCONN_NOCOPY); + } + if (strncmp((char const *)buf,"GET /adc", 8) == 0) { + float_to_str(getMCUTemperature(), float_buf); + sprintf(buf, "%s °C", float_buf); + netconn_write(conn, (const unsigned char*)buf, strlen(buf), NETCONN_NOCOPY); + } + } + } + } + /* Close the connection (server closes in HTTP) */ + netconn_close(conn); + + /* Delete the buffer (netconn_recv gives us ownership, + so we have to make sure to deallocate the buffer) */ + netbuf_delete(inbuf); +} + + +/** + * @brief http server thread + * @retval None + */ +static void http_server_netconn_thread() +{ + struct netconn *conn, *newconn; + err_t err, accept_err; + + /* Create a new TCP connection handle */ + conn = netconn_new(NETCONN_TCP); + + if (conn!= NULL) + { + /* Bind to port 80 (HTTP) with default IP address */ + err = netconn_bind(conn, NULL, 80); + + if (err == ERR_OK) + { + /* Put the connection into LISTEN state */ + netconn_listen(conn); + + while(1) + { + /* accept any icoming connection */ + accept_err = netconn_accept(conn, &newconn); + if(accept_err == ERR_OK) + { + /* serve connection */ + http_server_serve(newconn); + + /* delete connection */ + netconn_delete(newconn); + } + } + } + } +} + +/** + * @brief Initialize the HTTP server (start its thread) + * @param none + * @retval None + */ +void http_server_netconn_init() +{ + m_queue_handle = xQueueCreate(100/*len*/,4/*size*/); + sys_thread_new("HTTP", http_server_netconn_thread, NULL, DEFAULT_THREAD_STACKSIZE, WEBSERVER_THREAD_PRIO); +} + +/** + * + * @return the queue handle for button pressed + */ +xQueueHandle http_get_btn_queue() +{ + return m_queue_handle; +} + diff --git a/pool/shard006/C/0117462_sml_bit_array.c b/pool/shard006/C/0117462_sml_bit_array.c new file mode 100644 index 0000000000000000000000000000000000000000..a21391d4856fc7a5dcf23065014241348d3af2af --- /dev/null +++ b/pool/shard006/C/0117462_sml_bit_array.c @@ -0,0 +1,156 @@ +/* + * This file is part of the Soletta Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * 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 +#include +#include +#include +#include "sml_bit_array.h" +#include "sml.h" + +//Change this constants to change the size of the bit array element. +#define BITS 1 +#define ITEMS_IN_BYTE 8 //(8/BITS) +#define MASK 1 //(11b) + +static uint16_t +_calc_data_size(uint16_t size) +{ + uint16_t input_data_size = size / ITEMS_IN_BYTE; + + if (size % ITEMS_IN_BYTE) + input_data_size++; + return input_data_size; +} + +void +sml_bit_array_init(struct sml_bit_array *array) +{ + array->size = 0; + array->data = NULL; +} + +bool +sml_bit_array_set(struct sml_bit_array *array, uint16_t pos, uint8_t value) +{ + uint16_t real_pos; + uint8_t mask, shift; + + real_pos = pos / ITEMS_IN_BYTE; + if (real_pos >= array->size) + return false; + + shift = (pos % ITEMS_IN_BYTE) * BITS; + mask = MASK << shift; + value = value << shift; + array->data[real_pos] = (array->data[real_pos] & ~mask) | value; + + return true; +} + +uint8_t +sml_bit_array_get(struct sml_bit_array *array, uint16_t pos) +{ + uint16_t real_pos; + uint8_t input_terms_membership, shift; + + if (pos >= array->size) + return 0; + + real_pos = pos / ITEMS_IN_BYTE; + shift = (pos % ITEMS_IN_BYTE) * BITS; + input_terms_membership = array->data[real_pos]; + input_terms_membership = input_terms_membership & (MASK << shift); + return input_terms_membership >> shift; +} + +void +sml_bit_array_clear(struct sml_bit_array *array) +{ + array->size = 0; + free(array->data); + array->data = NULL; +} + +int +sml_bit_array_size_set(struct sml_bit_array *array, uint16_t new_size, + uint8_t initial_value) +{ + uint8_t *tmp_output; + uint16_t new_real_size, old_size; + + if (new_size == 0) { + sml_bit_array_clear(array); + return 0; + } + + new_real_size = _calc_data_size(new_size); + tmp_output = realloc(array->data, new_real_size); + if (tmp_output == NULL) + return -errno; + array->data = tmp_output; + old_size = array->size; + array->size = new_size; + + if (new_size > old_size) { + uint16_t i; + for (i = old_size; i < new_size; i++) + sml_bit_array_set(array, i, initial_value); + } + + return 0; +} + +uint16_t +sml_bit_array_size_get(struct sml_bit_array *array) +{ + return array->size; +} + +unsigned int +sml_bit_array_byte_size_get(struct sml_bit_array *array) +{ + return _calc_data_size(array->size); +} + +int +sml_bit_array_remove(struct sml_bit_array *array, uint16_t pos) +{ + uint16_t i; + + if (pos >= array->size) + return -EINVAL; + for (i = pos; i < array->size - 1; i++) + sml_bit_array_set(array, i, sml_bit_array_get(array, i + 1)); + + return sml_bit_array_size_set(array, array->size - 1, 0); +} diff --git a/pool/shard006/C/0117465_rlm_replicate.c b/pool/shard006/C/0117465_rlm_replicate.c new file mode 100644 index 0000000000000000000000000000000000000000..9496c854ed84dc636392d60837898ba72ad5cbfd --- /dev/null +++ b/pool/shard006/C/0117465_rlm_replicate.c @@ -0,0 +1,229 @@ +/* + * rlm_replicate.c + * + * Version: $Id$ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + * + * Copyright 2000,2006 The FreeRADIUS server project + * Copyright 2000 your name + */ + +#include +RCSID("$Id$") + +#include +#include +#include + + +static void cleanup(RADIUS_PACKET **packet) +{ + if (!packet || !*packet) return; + if ((*packet)->sockfd >= 0) close((*packet)->sockfd); + rad_free(packet); +} + +/* + * Write accounting information to this modules database. + */ +static int replicate_packet(void *instance, REQUEST *request) +{ + int rcode = RLM_MODULE_NOOP; + VALUE_PAIR *vp, *last; + home_server *home; + REALM *realm; + home_pool_t *pool; + RADIUS_PACKET *packet = NULL; + + instance = instance; /* -Wunused */ + last = request->config_items; + rad_assert(request->proxy == NULL); + + /* + * Send as many packets as necessary to different + * destinations. + */ + while (1) { + vp = pairfind(last, PW_REPLICATE_TO_REALM); + if (!vp) break; + + last = vp->next; + + realm = realm_find2(vp->vp_strvalue); + if (!realm) { + RDEBUG2("ERROR: Cannot Replicate to unknown realm %s", + vp->vp_strvalue); + continue; + } + + /* + * We shouldn't really do this on every loop. + */ + switch (request->packet->code) { + default: + pool = NULL; + RDEBUG2("ERROR: Cannot replicate unknown packet code %d", + request->packet->code); + cleanup(&packet); + rcode = RLM_MODULE_FAIL; + break; + + case PW_AUTHENTICATION_REQUEST: + pool = realm->auth_pool; + break; + +#ifdef WITH_ACCOUNTING + + case PW_ACCOUNTING_REQUEST: + pool = realm->acct_pool; + break; +#endif + +#ifdef WITH_COA + case PW_COA_REQUEST: + case PW_DISCONNECT_REQUEST: + pool = realm->acct_pool; + break; +#endif + } + + if (!pool) { + RDEBUG2(" WARNING: Cancelling replication to Realm %s, as the realm is local.", realm->name); + continue; + } + + home = home_server_ldb(realm->name, pool, request); + if (!home) { + RDEBUG2("ERROR: Failed to find live home server for realm %s", + realm->name); + continue; + } + + if (!packet) { + packet = rad_alloc(1); + if (!packet) { + rcode = RLM_MODULE_FAIL; + break; + } + packet->sockfd = -1; + packet->code = request->packet->code; + packet->id = fr_rand() & 0xff; + + packet->sockfd = fr_socket(&home->src_ipaddr, 0); + if (packet->sockfd < 0) { + RDEBUG("ERROR: Failed opening socket: %s", fr_strerror()); + cleanup(&packet); + rcode = RLM_MODULE_FAIL; + break; + } + + packet->vps = paircopy(request->packet->vps); + if (!packet->vps) { + RDEBUG("ERROR: Out of memory!"); + cleanup(&packet); + rcode = RLM_MODULE_FAIL; + break; + } + + /* + * For CHAP, create the CHAP-Challenge if + * it doesn't exist. + */ + if ((request->packet->code == PW_AUTHENTICATION_REQUEST) && + (pairfind(request->packet->vps, PW_CHAP_PASSWORD) != NULL) && + (pairfind(request->packet->vps, PW_CHAP_CHALLENGE) == NULL)) { + vp = radius_paircreate(request, &packet->vps, + PW_CHAP_CHALLENGE, + PW_TYPE_OCTETS); + vp->length = AUTH_VECTOR_LEN; + memcpy(vp->vp_strvalue, request->packet->vector, + AUTH_VECTOR_LEN); + } + } else { + size_t i; + + for (i = 0; i < sizeof(packet->vector); i++) { + packet->vector[i] = fr_rand() & 0xff; + } + + packet->id++; + free(packet->data); + packet->data = NULL; + packet->data_len = 0; + } + + /* + * (Re)-Write these. + */ + packet->dst_ipaddr = home->ipaddr; + packet->dst_port = home->port; + memset(&packet->src_ipaddr, 0, sizeof(packet->src_ipaddr)); + packet->src_port = 0; + + /* + * Encode, sign and then send the packet. + */ + RDEBUG("Replicating packet to Realm %s", realm->name); + if (rad_send(packet, NULL, home->secret) < 0) { + RDEBUG("ERROR: Failed replicating packet: %s", + fr_strerror()); + cleanup(&packet); + rcode = RLM_MODULE_FAIL; + break; + } + + /* + * We've sent it to at least one destination. + */ + rcode = RLM_MODULE_OK; + } + + cleanup(&packet); + rad_free(&request->proxy); + + return rcode; +} + +/* + * The module name should be the only globally exported symbol. + * That is, everything else should be 'static'. + * + * If the module needs to temporarily modify it's instantiation + * data, the type should be changed to RLM_TYPE_THREAD_UNSAFE. + * The server will then take care of ensuring that the module + * is single-threaded. + */ +module_t rlm_replicate = { + RLM_MODULE_INIT, + "replicate", + RLM_TYPE_THREAD_SAFE, /* type */ + NULL, /* instantiation */ + NULL, /* detach */ + { + NULL, /* authentication */ + replicate_packet, /* authorization */ + NULL, /* preaccounting */ + replicate_packet, /* accounting */ + NULL, /* checksimul */ + NULL, /* pre-proxy */ + NULL, /* post-proxy */ + NULL /* post-auth */ +#ifdef WITH_COA + , replicate_packet, + NULL +#endif + }, +}; diff --git a/pool/shard006/C/0117467_dumb_source.c b/pool/shard006/C/0117467_dumb_source.c new file mode 100644 index 0000000000000000000000000000000000000000..3daed1eafdff7035286d3a66077c867a1dfcf78a --- /dev/null +++ b/pool/shard006/C/0117467_dumb_source.c @@ -0,0 +1,139 @@ +#ifdef USE_DUMB + +#include +#include +#ifdef __linux__ +#include // strcasecmp +#endif // __linux__ +#include +#include "audio/sources/dumb_source.h" +#include "utils/log.h" + +typedef struct dumb_source_t { + DUH_SIGRENDERER *renderer; + sample_t **sig_samples; + long sig_samples_size; + DUH *data; + long vlen; + long vpos; +} dumb_source; + +audio_source_freq dumb_freqs[] = { + {11025, 0, "11025Hz"}, + {22050, 0, "22050Hz"}, + {44100, 1, "44100Hz"}, + {48000, 1, "48000Hz"}, + {0,0,0} // Guard +}; + +audio_source_resampler dumb_resamplers[] = { + {DUMB_RQ_ALIASING, 0, "Aliasing"}, + {DUMB_RQ_BLEP, 0, "BLEP"}, + {DUMB_RQ_LINEAR, 1, "Linear"}, + {DUMB_RQ_BLAM, 0, "BLIP"}, + {DUMB_RQ_CUBIC, 0, "Cubic"}, + {DUMB_RQ_FIR, 0, "FIR"}, + {0,0,0} // Guard +}; + +audio_source_freq* dumb_get_freqs() { + return dumb_freqs; +} + +audio_source_resampler* dumb_get_resamplers() { + return dumb_resamplers; +} + +int dumb_source_update(audio_source *src, char *buffer, int len) { + dumb_source *local = source_get_userdata(src); + + // Get deltatime and bitrate + float delta = 65536.0f / source_get_frequency(src); + int bps = source_get_channels(src) * source_get_bytes(src); + + // If looping is off, and if we have played the whole file, stop here. + long pos = duh_sigrenderer_get_position(local->renderer); + if(pos < local->vpos && !src->loop) { + return 0; + } + local->vpos = pos; + + // ... otherwise get more data. + int ret = duh_render_int( + local->renderer, + &local->sig_samples, + &local->sig_samples_size, + source_get_bytes(src) * 8, // Bits + 0, // Unsign + 1.0f, // Volume + delta, + len / bps, // Size + buffer + ) * bps; + return ret; +} + +void dumb_source_close(audio_source *src) { + dumb_source *local = source_get_userdata(src); + duh_end_sigrenderer(local->renderer); + unload_duh(local->data); + destroy_sample_buffer(local->sig_samples); + free(local); + DEBUG("Libdumb Source: Closed."); +} + +int dumb_source_init(audio_source *src, const char* file, int channels, int freq, int resampler) { + dumb_source *local = malloc(sizeof(dumb_source)); + + // Load file and initialize renderer + char *ext = strrchr(file, '.') + 1; + if(strcasecmp(ext, "psm") == 0) { + local->data = dumb_load_psm(file, 0); + } else if(strcasecmp(ext, "s3m") == 0) { + local->data = dumb_load_s3m(file); + } else if(strcasecmp(ext, "mod") == 0) { + local->data = dumb_load_mod(file, 0); + } else if(strcasecmp(ext, "it") == 0) { + local->data = dumb_load_it(file); + } else if(strcasecmp(ext, "xm") == 0) { + local->data = dumb_load_xm(file); + } else { + PERROR("Libdumb Source: No suitable module decoder found."); + goto error_0; + } + if(!local->data) { + PERROR("Libdumb Source: Error while loading module file!"); + goto error_0; + } + local->renderer = duh_start_sigrenderer(local->data, 0, channels, 0); + local->vlen = duh_get_length(local->data); + local->vpos = 0; + local->sig_samples = NULL; + local->sig_samples_size = 0; + + // Set resampler here + dumb_it_set_resampling_quality(duh_get_it_sigrenderer(local->renderer), resampler); + + // Audio information + source_set_frequency(src, freq); + source_set_bytes(src, 2); + source_set_channels(src, channels); + source_set_resampler(src, resampler); + + // Set callbacks + source_set_userdata(src, local); + source_set_update_cb(src, dumb_source_update); + source_set_close_cb(src, dumb_source_close); + + // Some debug info + DEBUG("Libdumb Source: Loaded file '%s' succesfully.", file); + + // All done + return 0; + +error_0: + free(local); + return 1; +} + +#endif // USE_DUMB diff --git a/pool/shard006/C/0117470_intel_upload_blit_large.c b/pool/shard006/C/0117470_intel_upload_blit_large.c new file mode 100644 index 0000000000000000000000000000000000000000..de0f6683a47d3b9a4e6d537e3b435817d32042cb --- /dev/null +++ b/pool/shard006/C/0117470_intel_upload_blit_large.c @@ -0,0 +1,161 @@ +/* + * Copyright © 2009 Intel Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Authors: + * Eric Anholt + * + */ + +/** + * Roughly simulates repeatedly uploading frames of images, by uploading + * the data all at once with pwrite, and then blitting it to another buffer. + * + * You might think of this like a movie player, but that wouldn't be entirely + * accurate, since the access patterns of the memory would be different + * (generally, smaller source image, upscaled, an thus different memory access + * pattern in both texel fetch for the stretching and the destination writes). + * However, some things like swfdec would be doing something like this since + * they compute their data in host memory and upload the full sw rendered + * frame. + * + * Additionally, those applications should be rendering at the screen refresh + * rate, while this test has no limits, and so can get itself into the + * working set larger than aperture size performance disaster. + * + * The current workload doing this path is pixmap upload for non-KMS. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "drm.h" +#include "i915_drm.h" +#include "drmtest.h" +#include "intel_bufmgr.h" +#include "intel_batchbuffer.h" +#include "intel_gpu_tools.h" + +#define OBJECT_WIDTH 1280 +#define OBJECT_HEIGHT 720 + +static double +get_time_in_secs(void) +{ + struct timeval tv; + + gettimeofday(&tv, NULL); + + return (double)tv.tv_sec + tv.tv_usec / 1000000.0; +} + +static void +do_render(drm_intel_bufmgr *bufmgr, struct intel_batchbuffer *batch, + drm_intel_bo *dst_bo, int width, int height) +{ + uint32_t data[width * height]; + drm_intel_bo *src_bo; + int i; + static uint32_t seed = 1; + + /* Generate some junk. Real workloads would be doing a lot more + * work to generate the junk. + */ + for (i = 0; i < width * height; i++) { + data[i] = seed++; + } + + /* Upload the junk. */ + src_bo = drm_intel_bo_alloc(bufmgr, "src", sizeof(data), 4096); + drm_intel_bo_subdata(src_bo, 0, sizeof(data), data); + + /* Render the junk to the dst. */ + BEGIN_BATCH(8); + OUT_BATCH(XY_SRC_COPY_BLT_CMD | + XY_SRC_COPY_BLT_WRITE_ALPHA | + XY_SRC_COPY_BLT_WRITE_RGB); + OUT_BATCH((3 << 24) | /* 32 bits */ + (0xcc << 16) | /* copy ROP */ + (width * 4) /* dst pitch */); + OUT_BATCH(0); /* dst x1,y1 */ + OUT_BATCH((height << 16) | width); /* dst x2,y2 */ + OUT_RELOC(dst_bo, I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER, 0); + OUT_BATCH(0); /* src x1,y1 */ + OUT_BATCH(width * 4); /* src pitch */ + OUT_RELOC(src_bo, I915_GEM_DOMAIN_RENDER, 0, 0); + ADVANCE_BATCH(); + + intel_batchbuffer_flush(batch); + + drm_intel_bo_unreference(src_bo); +} + +int main(int argc, char **argv) +{ + int fd; + int object_size = OBJECT_WIDTH * OBJECT_HEIGHT * 4; + double start_time, end_time; + drm_intel_bo *dst_bo; + drm_intel_bufmgr *bufmgr; + struct intel_batchbuffer *batch; + int i; + + fd = drm_open_any(); + + bufmgr = drm_intel_bufmgr_gem_init(fd, 4096); + drm_intel_bufmgr_gem_enable_reuse(bufmgr); + + batch = intel_batchbuffer_alloc(bufmgr, intel_get_drm_devid(fd)); + + dst_bo = drm_intel_bo_alloc(bufmgr, "dst", object_size, 4096); + + /* Prep loop to get us warmed up. */ + for (i = 0; i < 60; i++) { + do_render(bufmgr, batch, dst_bo, OBJECT_WIDTH, OBJECT_HEIGHT); + } + drm_intel_bo_wait_rendering(dst_bo); + + /* Do the actual timing. */ + start_time = get_time_in_secs(); + for (i = 0; i < 200; i++) { + do_render(bufmgr, batch, dst_bo, OBJECT_WIDTH, OBJECT_HEIGHT); + } + drm_intel_bo_wait_rendering(dst_bo); + end_time = get_time_in_secs(); + + printf("%d iterations in %.03f secs: %.01f MB/sec\n", i, + end_time - start_time, + (double)i * OBJECT_WIDTH * OBJECT_HEIGHT * 4 / 1024.0 / 1024.0 / + (end_time - start_time)); + + intel_batchbuffer_free(batch); + drm_intel_bufmgr_destroy(bufmgr); + + close(fd); + + return 0; +} diff --git a/pool/shard006/C/0117475_setbits.c b/pool/shard006/C/0117475_setbits.c new file mode 100644 index 0000000000000000000000000000000000000000..48f62236c8184c21727b4e61cd1b754a26360fb4 --- /dev/null +++ b/pool/shard006/C/0117475_setbits.c @@ -0,0 +1,25 @@ +#include + +unsigned setbits(unsigned x, int p, int n, unsigned y); + +int main(int argc, char** argv) { + + unsigned x = 255; + unsigned y = 205; + unsigned r; + + r = setbits(x, 5, 2, y); + printf("%u\n", r); + + return 0; +} + +unsigned setbits(unsigned x, int p, int n, unsigned y) { + + unsigned mask = ~(~0 << n) << (p - n + 1); + x = x & ~mask; + y = (y & ~(~0 << n)) << (p - n + 1); + x = x | y; + + return x; +} diff --git a/pool/shard006/C/0117490_40x_mmu.c b/pool/shard006/C/0117490_40x_mmu.c new file mode 100644 index 0000000000000000000000000000000000000000..3899ea97fbdff935b23869fbe8c8db9c6de78283 --- /dev/null +++ b/pool/shard006/C/0117490_40x_mmu.c @@ -0,0 +1,134 @@ +/* + * This file contains the routines for initializing the MMU + * on the 4xx series of chips. + * -- paulus + * + * Derived from arch/ppc/mm/init.c: + * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org) + * + * Modifications by Paul Mackerras (PowerMac) (paulus@cs.anu.edu.au) + * and Cort Dougan (PReP) (cort@cs.nmt.edu) + * Copyright (C) 1996 Paul Mackerras + * + * Derived from "arch/i386/mm/init.c" + * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mmu_decl.h" + +extern int __map_without_ltlbs; +/* + * MMU_init_hw does the chip-specific initialization of the MMU hardware. + */ +void __init MMU_init_hw(void) +{ + /* + * The Zone Protection Register (ZPR) defines how protection will + * be applied to every page which is a member of a given zone. At + * present, we utilize only two of the 4xx's zones. + * The zone index bits (of ZSEL) in the PTE are used for software + * indicators, except the LSB. For user access, zone 1 is used, + * for kernel access, zone 0 is used. We set all but zone 1 + * to zero, allowing only kernel access as indicated in the PTE. + * For zone 1, we set a 01 binary (a value of 10 will not work) + * to allow user access as indicated in the PTE. This also allows + * kernel access as indicated in the PTE. + */ + + mtspr(SPRN_ZPR, 0x10000000); + + flush_instruction_cache(); + + /* + * Set up the real-mode cache parameters for the exception vector + * handlers (which are run in real-mode). + */ + + mtspr(SPRN_DCWR, 0x00000000); /* All caching is write-back */ + + /* + * Cache instruction and data space where the exception + * vectors and the kernel live in real-mode. + */ + + mtspr(SPRN_DCCR, 0xF0000000); /* 512 MB of data space at 0x0. */ + mtspr(SPRN_ICCR, 0xF0000000); /* 512 MB of instr. space at 0x0. */ +} + +#define LARGE_PAGE_SIZE_16M (1<<24) +#define LARGE_PAGE_SIZE_4M (1<<22) + +unsigned long __init mmu_mapin_ram(void) +{ + unsigned long v, s; + phys_addr_t p; + + v = KERNELBASE; + p = PPC_MEMSTART; + s = total_lowmem; + + if (__map_without_ltlbs) + return 0; + + while (s >= LARGE_PAGE_SIZE_16M) { + pmd_t *pmdp; + unsigned long val = p | _PMD_SIZE_16M | _PAGE_HWEXEC | _PAGE_HWWRITE; + + pmdp = pmd_offset(pud_offset(pgd_offset_k(v), v), v); + pmd_val(*pmdp++) = val; + pmd_val(*pmdp++) = val; + pmd_val(*pmdp++) = val; + pmd_val(*pmdp++) = val; + + v += LARGE_PAGE_SIZE_16M; + p += LARGE_PAGE_SIZE_16M; + s -= LARGE_PAGE_SIZE_16M; + } + + while (s >= LARGE_PAGE_SIZE_4M) { + pmd_t *pmdp; + unsigned long val = p | _PMD_SIZE_4M | _PAGE_HWEXEC | _PAGE_HWWRITE; + + pmdp = pmd_offset(pud_offset(pgd_offset_k(v), v), v); + pmd_val(*pmdp) = val; + + v += LARGE_PAGE_SIZE_4M; + p += LARGE_PAGE_SIZE_4M; + s -= LARGE_PAGE_SIZE_4M; + } + + return total_lowmem - s; +} diff --git a/pool/shard006/C/0117502_prm_common.c b/pool/shard006/C/0117502_prm_common.c new file mode 100644 index 0000000000000000000000000000000000000000..f596e1e91ffd62ce524791d5e5bf3313830c08cf --- /dev/null +++ b/pool/shard006/C/0117502_prm_common.c @@ -0,0 +1,410 @@ +/* + * OMAP2+ common Power & Reset Management (PRM) IP block functions + * + * Copyright (C) 2011 Texas Instruments, Inc. + * Tero Kristo + * + * 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. + * + * + * For historical purposes, the API used to configure the PRM + * interrupt handler refers to it as the "PRCM interrupt." The + * underlying registers are located in the PRM on OMAP3/4. + * + * XXX This code should eventually be moved to a PRM driver. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "prm2xxx_3xxx.h" +#include "prm2xxx.h" +#include "prm3xxx.h" +#include "prm44xx.h" +#include "common.h" + +/* + * OMAP_PRCM_MAX_NR_PENDING_REG: maximum number of PRM_IRQ*_MPU regs + * XXX this is technically not needed, since + * omap_prcm_register_chain_handler() could allocate this based on the + * actual amount of memory needed for the SoC + */ +#define OMAP_PRCM_MAX_NR_PENDING_REG 2 + +/* + * prcm_irq_chips: an array of all of the "generic IRQ chips" in use + * by the PRCM interrupt handler code. There will be one 'chip' per + * PRM_{IRQSTATUS,IRQENABLE}_MPU register pair. (So OMAP3 will have + * one "chip" and OMAP4 will have two.) + */ +static struct irq_chip_generic **prcm_irq_chips; + +/* + * prcm_irq_setup: the PRCM IRQ parameters for the hardware the code + * is currently running on. Defined and passed by initialization code + * that calls omap_prcm_register_chain_handler(). + */ +static struct omap_prcm_irq_setup *prcm_irq_setup; + +/* prm_base: base virtual address of the PRM IP block */ +void __iomem *prm_base; + +/* + * prm_ll_data: function pointers to SoC-specific implementations of + * common PRM functions + */ +static struct prm_ll_data null_prm_ll_data; +static struct prm_ll_data *prm_ll_data = &null_prm_ll_data; + +/* Private functions */ + +/* + * Move priority events from events to priority_events array + */ +static void omap_prcm_events_filter_priority(unsigned long *events, + unsigned long *priority_events) +{ + int i; + + for (i = 0; i < prcm_irq_setup->nr_regs; i++) { + priority_events[i] = + events[i] & prcm_irq_setup->priority_mask[i]; + events[i] ^= priority_events[i]; + } +} + +/* + * PRCM Interrupt Handler + * + * This is a common handler for the OMAP PRCM interrupts. Pending + * interrupts are detected by a call to prcm_pending_events and + * dispatched accordingly. Clearing of the wakeup events should be + * done by the SoC specific individual handlers. + */ +static void omap_prcm_irq_handler(unsigned int irq, struct irq_desc *desc) +{ + unsigned long pending[OMAP_PRCM_MAX_NR_PENDING_REG]; + unsigned long priority_pending[OMAP_PRCM_MAX_NR_PENDING_REG]; + struct irq_chip *chip = irq_desc_get_chip(desc); + unsigned int virtirq; + int nr_irq = prcm_irq_setup->nr_regs * 32; + + /* + * If we are suspended, mask all interrupts from PRCM level, + * this does not ack them, and they will be pending until we + * re-enable the interrupts, at which point the + * omap_prcm_irq_handler will be executed again. The + * _save_and_clear_irqen() function must ensure that the PRM + * write to disable all IRQs has reached the PRM before + * returning, or spurious PRCM interrupts may occur during + * suspend. + */ + if (prcm_irq_setup->suspended) { + prcm_irq_setup->save_and_clear_irqen(prcm_irq_setup->saved_mask); + prcm_irq_setup->suspend_save_flag = true; + } + + /* + * Loop until all pending irqs are handled, since + * generic_handle_irq() can cause new irqs to come + */ + while (!prcm_irq_setup->suspended) { + prcm_irq_setup->read_pending_irqs(pending); + + /* No bit set, then all IRQs are handled */ + if (find_first_bit(pending, nr_irq) >= nr_irq) + break; + + omap_prcm_events_filter_priority(pending, priority_pending); + + /* + * Loop on all currently pending irqs so that new irqs + * cannot starve previously pending irqs + */ + + /* Serve priority events first */ + for_each_set_bit(virtirq, priority_pending, nr_irq) + generic_handle_irq(prcm_irq_setup->base_irq + virtirq); + + /* Serve normal events next */ + for_each_set_bit(virtirq, pending, nr_irq) + generic_handle_irq(prcm_irq_setup->base_irq + virtirq); + } + if (chip->irq_ack) + chip->irq_ack(&desc->irq_data); + if (chip->irq_eoi) + chip->irq_eoi(&desc->irq_data); + chip->irq_unmask(&desc->irq_data); + + prcm_irq_setup->ocp_barrier(); /* avoid spurious IRQs */ +} + +/* Public functions */ + +/** + * omap_prcm_event_to_irq - given a PRCM event name, returns the + * corresponding IRQ on which the handler should be registered + * @name: name of the PRCM interrupt bit to look up - see struct omap_prcm_irq + * + * Returns the Linux internal IRQ ID corresponding to @name upon success, + * or -ENOENT upon failure. + */ +int omap_prcm_event_to_irq(const char *name) +{ + int i; + + if (!prcm_irq_setup || !name) + return -ENOENT; + + for (i = 0; i < prcm_irq_setup->nr_irqs; i++) + if (!strcmp(prcm_irq_setup->irqs[i].name, name)) + return prcm_irq_setup->base_irq + + prcm_irq_setup->irqs[i].offset; + + return -ENOENT; +} + +/** + * omap_prcm_irq_cleanup - reverses memory allocated and other steps + * done by omap_prcm_register_chain_handler() + * + * No return value. + */ +void omap_prcm_irq_cleanup(void) +{ + int i; + + if (!prcm_irq_setup) { + pr_err("PRCM: IRQ handler not initialized; cannot cleanup\n"); + return; + } + + if (prcm_irq_chips) { + for (i = 0; i < prcm_irq_setup->nr_regs; i++) { + if (prcm_irq_chips[i]) + irq_remove_generic_chip(prcm_irq_chips[i], + 0xffffffff, 0, 0); + prcm_irq_chips[i] = NULL; + } + kfree(prcm_irq_chips); + prcm_irq_chips = NULL; + } + + kfree(prcm_irq_setup->saved_mask); + prcm_irq_setup->saved_mask = NULL; + + kfree(prcm_irq_setup->priority_mask); + prcm_irq_setup->priority_mask = NULL; + + irq_set_chained_handler(prcm_irq_setup->irq, NULL); + + if (prcm_irq_setup->base_irq > 0) + irq_free_descs(prcm_irq_setup->base_irq, + prcm_irq_setup->nr_regs * 32); + prcm_irq_setup->base_irq = 0; +} + +void omap_prcm_irq_prepare(void) +{ + prcm_irq_setup->suspended = true; +} + +void omap_prcm_irq_complete(void) +{ + prcm_irq_setup->suspended = false; + + /* If we have not saved the masks, do not attempt to restore */ + if (!prcm_irq_setup->suspend_save_flag) + return; + + prcm_irq_setup->suspend_save_flag = false; + + /* + * Re-enable all masked PRCM irq sources, this causes the PRCM + * interrupt to fire immediately if the events were masked + * previously in the chain handler + */ + prcm_irq_setup->restore_irqen(prcm_irq_setup->saved_mask); +} + +/** + * omap_prcm_register_chain_handler - initializes the prcm chained interrupt + * handler based on provided parameters + * @irq_setup: hardware data about the underlying PRM/PRCM + * + * Set up the PRCM chained interrupt handler on the PRCM IRQ. Sets up + * one generic IRQ chip per PRM interrupt status/enable register pair. + * Returns 0 upon success, -EINVAL if called twice or if invalid + * arguments are passed, or -ENOMEM on any other error. + */ +int omap_prcm_register_chain_handler(struct omap_prcm_irq_setup *irq_setup) +{ + int nr_regs; + u32 mask[OMAP_PRCM_MAX_NR_PENDING_REG]; + int offset, i; + struct irq_chip_generic *gc; + struct irq_chip_type *ct; + + if (!irq_setup) + return -EINVAL; + + nr_regs = irq_setup->nr_regs; + + if (prcm_irq_setup) { + pr_err("PRCM: already initialized; won't reinitialize\n"); + return -EINVAL; + } + + if (nr_regs > OMAP_PRCM_MAX_NR_PENDING_REG) { + pr_err("PRCM: nr_regs too large\n"); + return -EINVAL; + } + + prcm_irq_setup = irq_setup; + + prcm_irq_chips = kzalloc(sizeof(void *) * nr_regs, GFP_KERNEL); + prcm_irq_setup->saved_mask = kzalloc(sizeof(u32) * nr_regs, GFP_KERNEL); + prcm_irq_setup->priority_mask = kzalloc(sizeof(u32) * nr_regs, + GFP_KERNEL); + + if (!prcm_irq_chips || !prcm_irq_setup->saved_mask || + !prcm_irq_setup->priority_mask) { + pr_err("PRCM: kzalloc failed\n"); + goto err; + } + + memset(mask, 0, sizeof(mask)); + + for (i = 0; i < irq_setup->nr_irqs; i++) { + offset = irq_setup->irqs[i].offset; + mask[offset >> 5] |= 1 << (offset & 0x1f); + if (irq_setup->irqs[i].priority) + irq_setup->priority_mask[offset >> 5] |= + 1 << (offset & 0x1f); + } + + irq_set_chained_handler(irq_setup->irq, omap_prcm_irq_handler); + + irq_setup->base_irq = irq_alloc_descs(-1, 0, irq_setup->nr_regs * 32, + 0); + + if (irq_setup->base_irq < 0) { + pr_err("PRCM: failed to allocate irq descs: %d\n", + irq_setup->base_irq); + goto err; + } + + for (i = 0; i < irq_setup->nr_regs; i++) { + gc = irq_alloc_generic_chip("PRCM", 1, + irq_setup->base_irq + i * 32, prm_base, + handle_level_irq); + + if (!gc) { + pr_err("PRCM: failed to allocate generic chip\n"); + goto err; + } + ct = gc->chip_types; + ct->chip.irq_ack = irq_gc_ack_set_bit; + ct->chip.irq_mask = irq_gc_mask_clr_bit; + ct->chip.irq_unmask = irq_gc_mask_set_bit; + + ct->regs.ack = irq_setup->ack + i * 4; + ct->regs.mask = irq_setup->mask + i * 4; + + irq_setup_generic_chip(gc, mask[i], 0, IRQ_NOREQUEST, 0); + prcm_irq_chips[i] = gc; + } + + return 0; + +err: + omap_prcm_irq_cleanup(); + return -ENOMEM; +} + +/** + * omap2_set_globals_prm - set the PRM base address (for early use) + * @prm: PRM base virtual address + * + * XXX Will be replaced when the PRM/CM drivers are completed. + */ +void __init omap2_set_globals_prm(void __iomem *prm) +{ + prm_base = prm; +} + +/** + * prm_read_reset_sources - return the sources of the SoC's last reset + * + * Return a u32 bitmask representing the reset sources that caused the + * SoC to reset. The low-level per-SoC functions called by this + * function remap the SoC-specific reset source bits into an + * OMAP-common set of reset source bits, defined in + * arch/arm/mach-omap2/prm.h. Returns the standardized reset source + * u32 bitmask from the hardware upon success, or returns (1 << + * OMAP_UNKNOWN_RST_SRC_ID_SHIFT) if no low-level read_reset_sources() + * function was registered. + */ +u32 prm_read_reset_sources(void) +{ + u32 ret = 1 << OMAP_UNKNOWN_RST_SRC_ID_SHIFT; + + if (prm_ll_data->read_reset_sources) + ret = prm_ll_data->read_reset_sources(); + else + WARN_ONCE(1, "prm: %s: no mapping function defined for reset sources\n", __func__); + + return ret; +} + +/** + * prm_register - register per-SoC low-level data with the PRM + * @pld: low-level per-SoC OMAP PRM data & function pointers to register + * + * Register per-SoC low-level OMAP PRM data and function pointers with + * the OMAP PRM common interface. The caller must keep the data + * pointed to by @pld valid until it calls prm_unregister() and + * it returns successfully. Returns 0 upon success, -EINVAL if @pld + * is NULL, or -EEXIST if prm_register() has already been called + * without an intervening prm_unregister(). + */ +int prm_register(struct prm_ll_data *pld) +{ + if (!pld) + return -EINVAL; + + if (prm_ll_data != &null_prm_ll_data) + return -EEXIST; + + prm_ll_data = pld; + + return 0; +} + +/** + * prm_unregister - unregister per-SoC low-level data & function pointers + * @pld: low-level per-SoC OMAP PRM data & function pointers to unregister + * + * Unregister per-SoC low-level OMAP PRM data and function pointers + * that were previously registered with prm_register(). The + * caller may not destroy any of the data pointed to by @pld until + * this function returns successfully. Returns 0 upon success, or + * -EINVAL if @pld is NULL or if @pld does not match the struct + * prm_ll_data * previously registered by prm_register(). + */ +int prm_unregister(struct prm_ll_data *pld) +{ + if (!pld || prm_ll_data != pld) + return -EINVAL; + + prm_ll_data = &null_prm_ll_data; + + return 0; +} diff --git a/pool/shard006/C/0117503_unix.c b/pool/shard006/C/0117503_unix.c new file mode 100644 index 0000000000000000000000000000000000000000..661e3372700185c71ecd9e578295855bbefc6a56 --- /dev/null +++ b/pool/shard006/C/0117503_unix.c @@ -0,0 +1,40 @@ +/* + UNIX Extensions test registration. + + Copyright (C) 2007 James Peach + + 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 . +*/ + +#include "includes.h" +#include "torture/smbtorture.h" +#include "torture/unix/proto.h" + +NTSTATUS torture_unix_init(void) +{ + struct torture_suite *suite = + torture_suite_create(talloc_autofree_context(), "UNIX"); + + suite->description = + talloc_strdup(suite, "CIFS UNIX extensions tests"); + + torture_suite_add_simple_test(suite, + "WHOAMI", torture_unix_whoami); + torture_suite_add_simple_test(suite, + "INFO2", unix_torture_unix_info2); + + return (torture_register_suite(suite)) ? NT_STATUS_OK + : NT_STATUS_UNSUCCESSFUL; + +} diff --git a/pool/shard006/C/0117508_bch.c b/pool/shard006/C/0117508_bch.c new file mode 100644 index 0000000000000000000000000000000000000000..711ae60621a07b0b29ae550f7285c69c9bc5583b --- /dev/null +++ b/pool/shard006/C/0117508_bch.c @@ -0,0 +1,122 @@ +#define LOG_PREFIX "bch" +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + + +struct bch_priv_t { + data_frame_t *data_fr; + tpdu_ui_t *tpdu; + tsdu_d_system_info_t *tsdu; + tpol_t *tpol; +}; + +bch_t *bch_create(tpol_t *tpol) +{ + bch_t *bch = malloc(sizeof(bch_t)); + if (!bch) { + return NULL; + } + + bch->data_fr = data_frame_create(); + if (!bch->data_fr) { + free(bch); + return NULL; + } + + bch->tpdu = tpdu_ui_create(tpol, FRAME_TYPE_DATA, LOG_CH_BCH); + if (!bch->tpdu) { + free(bch); + data_frame_destroy(bch->data_fr); + return NULL; + } + + bch->tsdu = NULL; + bch->tpol = tpol; + + return bch; +} + +void bch_destroy(bch_t *bch) +{ + tsdu_destroy(&bch->tsdu->base); + data_frame_destroy(bch->data_fr); + tpdu_ui_destroy(bch->tpdu); + free(bch); +} + +bool bch_push_frame(bch_t *bch, const frame_t *fr) +{ + if (data_frame_push_frame(bch->data_fr, fr) <= 0) { + return false; + } + + uint8_t tpdu_data[SYS_PAR_N200_BYTES_MAX]; + const int nblocks = data_frame_blocks(bch->data_fr); + const int size = data_frame_get_bytes(bch->data_fr, tpdu_data); + + hdlc_frame_t hdlc_fr; + if (!hdlc_frame_parse(&hdlc_fr, tpdu_data, size)) { + return false; + } + + if (hdlc_fr.command.cmd != COMMAND_UNNUMBERED_UI) { + return false; + } + + if (!addr_is_tti_all_st(&hdlc_fr.addr, true)) { + if (bch->tpol->frame_no == FRAME_NO_UNKNOWN) { + LOG_IF(DBG) { + char buf[ADDR_PRINT_BUF_SIZE]; + LOG(DBG, "invalid address for BCH %s", + addr_print(buf, &hdlc_fr.addr)); + } + } + return false; + } + + tsdu_t *tsdu; + if (tpdu_ui_push_hdlc_frame2(bch->tpdu, &hdlc_fr, &tsdu) == -1) { + return false; + } + + if (!tsdu) { + return false; + } + + if (tsdu->codop != D_SYSTEM_INFO) { + LOG(DBG, "Invalid codop for BCH 0x%02x", tsdu->codop); + tsdu_destroy(tsdu); + + return false; + } + + tsdu_destroy(&bch->tsdu->base); + bch->tsdu = (tsdu_d_system_info_t *)tsdu; + + const int bch_frame_no = 100 * bch->tsdu->cell_state.bch + nblocks - 1; + if (bch->tpol->frame_no != FRAME_NO_UNKNOWN && + bch->tpol->frame_no != bch_frame_no) { + LOG(ERR, "Frame skew detected %d to %d\n", + bch->tpol->frame_no, bch_frame_no); + } + bch->tpol->frame_no = bch_frame_no; + + return true; +} + +tsdu_d_system_info_t *bch_get_tsdu(bch_t *bch) +{ + tsdu_d_system_info_t *tsdu = bch->tsdu; + bch->tsdu = NULL; + + return tsdu; +} diff --git a/pool/shard006/C/0117514_divert_init.c b/pool/shard006/C/0117514_divert_init.c new file mode 100644 index 0000000000000000000000000000000000000000..ede2b7eb75ea129c13088a209f1a0894803a2403 --- /dev/null +++ b/pool/shard006/C/0117514_divert_init.c @@ -0,0 +1,86 @@ +/* $Id divert_init.c,v 1.5.6.2 2001/01/24 22:18:17 kai Exp $ + * + * Module init for DSS1 diversion services for i4l. + * + * Copyright 1999 by Werner Cornelius (werner@isdn4linux.de) + * + * This software may be used and distributed according to the terms + * of the GNU General Public License, incorporated herein by reference. + * + */ + +#include +#include +#include +#include "isdn_divert.h" + +MODULE_DESCRIPTION("ISDN4Linux: Call diversion support"); +MODULE_AUTHOR("Werner Cornelius"); +MODULE_LICENSE("GPL"); + +/********************/ +/* needed externals */ +/********************/ +extern int printk(const char *fmt,...); + +/****************************************/ +/* structure containing interface to hl */ +/****************************************/ +isdn_divert_if divert_if = + { DIVERT_IF_MAGIC, /* magic value */ + DIVERT_CMD_REG, /* register cmd */ + ll_callback, /* callback routine from ll */ + NULL, /* command still not specified */ + NULL, /* drv_to_name */ + NULL, /* name_to_drv */ + }; + +/*************************/ +/* Module interface code */ +/* no cmd line parms */ +/*************************/ +static int __init divert_init(void) +{ int i; + + if (divert_dev_init()) + { printk(KERN_WARNING "dss1_divert: cannot install device, not loaded\n"); + return(-EIO); + } + if ((i = DIVERT_REG_NAME(&divert_if)) != DIVERT_NO_ERR) + { divert_dev_deinit(); + printk(KERN_WARNING "dss1_divert: error %d registering module, not loaded\n",i); + return(-EIO); + } + printk(KERN_INFO "dss1_divert module successfully installed\n"); + return(0); +} + +/**********************/ +/* Module deinit code */ +/**********************/ +static void __exit divert_exit(void) +{ unsigned long flags; + int i; + + save_flags(flags); + cli(); + divert_if.cmd = DIVERT_CMD_REL; /* release */ + if ((i = DIVERT_REG_NAME(&divert_if)) != DIVERT_NO_ERR) + { printk(KERN_WARNING "dss1_divert: error %d releasing module\n",i); + restore_flags(flags); + return; + } + if (divert_dev_deinit()) + { printk(KERN_WARNING "dss1_divert: device busy, remove cancelled\n"); + restore_flags(flags); + return; + } + restore_flags(flags); + deleterule(-1); /* delete all rules and free mem */ + deleteprocs(); + printk(KERN_INFO "dss1_divert module successfully removed \n"); +} + +module_init(divert_init); +module_exit(divert_exit); + diff --git a/pool/shard006/C/0117515_Buff_PoFengQiangFa.c b/pool/shard006/C/0117515_Buff_PoFengQiangFa.c new file mode 100644 index 0000000000000000000000000000000000000000..d534729fd629bc27680a8e3bdd92f81c1cbbb644 --- /dev/null +++ b/pool/shard006/C/0117515_Buff_PoFengQiangFa.c @@ -0,0 +1,33 @@ +#include "../Buff_private.h" + +void PoFengQiangFa_Buff_Start(struct Buff* self, struct BuffList* list); +void PoFengQiangFa_Buff_Stop(struct Buff* self, struct BuffList* list); + +struct Buff PoFengQiangFaInfo = +{ + PoFengQiangFa_ID, + BUFF_TYPE_TURN, + 1.0, + PoFengQiangFa_Buff_Start, + PoFengQiangFa_Buff_Stop, + NULL, + NULL +}; + +void PoFengQiangFa_Buff_Start(struct Buff* self, struct BuffList* list) +{ + BuffList_Apply_Speed(list, self->data_1, 1); + BuffList_Apply_Defend(list, 0, -self->data_1*20); +} + +void PoFengQiangFa_Buff_Stop(struct Buff* self, struct BuffList* list) +{ + BuffList_Apply_Speed(list, -self->data_1, 0); + BuffList_Apply_Defend(list, 0, self->data_1*20); +} + +struct Buff* PoFengQiangFaBuff_Get(unsigned int level) +{ + PoFengQiangFaInfo.data_1 = level; + return &PoFengQiangFaInfo; +} diff --git a/pool/shard006/C/0117527_stat_convert.c b/pool/shard006/C/0117527_stat_convert.c new file mode 100644 index 0000000000000000000000000000000000000000..98eb337000361874e0077e0e1558e20bbb474f2d --- /dev/null +++ b/pool/shard006/C/0117527_stat_convert.c @@ -0,0 +1,154 @@ +/*- + * Copyright 2016 Vsevolod Stakhov + * + * 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 "rspamadm.h" +#include "lua/lua_common.h" + +static gchar *source_db = NULL; +static gchar *redis_host = NULL; +static gchar *symbol = NULL; +static gchar *cache_db = NULL; +static gchar *redis_db = NULL; +static gchar *redis_password = NULL; +static gboolean reset_previous = FALSE; + +static void rspamadm_statconvert (gint argc, gchar **argv); +static const char *rspamadm_statconvert_help (gboolean full_help); + +struct rspamadm_command statconvert_command = { + .name = "statconvert", + .flags = 0, + .help = rspamadm_statconvert_help, + .run = rspamadm_statconvert +}; + +static GOptionEntry entries[] = { + {"database", 'd', 0, G_OPTION_ARG_FILENAME, &source_db, + "Input sqlite", NULL}, + {"cache", 'c', 0, G_OPTION_ARG_FILENAME, &cache_db, + "Input learn cache", NULL}, + {"host", 'h', 0, G_OPTION_ARG_STRING, &redis_host, + "Output redis ip (in format ip:port)", NULL}, + {"symbol", 's', 0, G_OPTION_ARG_STRING, &symbol, + "Symbol in redis (e.g. BAYES_SPAM)", NULL}, + {"dbname", 'D', 0, G_OPTION_ARG_STRING, &redis_db, + "Database in redis (should be numeric)", NULL}, + {"password", 'p', 0, G_OPTION_ARG_STRING, &redis_password, + "Password to connect to redis", NULL}, + {"reset", 'r', 0, G_OPTION_ARG_NONE, &reset_previous, + "Reset previous data instead of appending values", NULL}, + {NULL, 0, 0, G_OPTION_ARG_NONE, NULL, NULL, NULL} +}; + + +static const char * +rspamadm_statconvert_help (gboolean full_help) +{ + const char *help_str; + + if (full_help) { + help_str = "Convert statistics from sqlite3 to redis\n\n" + "Usage: rspamadm statconvert -d -h -s \n" + "Where options are:\n\n" + "-d: input sqlite\n" + "-h: output redis ip (in format ip:port)\n" + "-s: symbol in redis (e.g. BAYES_SPAM)\n" + "-c: also convert data from the learn cache\n" + "-D: output redis database\n" + "-p: redis password\n" + "-r: reset previous data instead of increasing values\n"; + } + else { + help_str = "Convert statistics from sqlite3 to redis"; + } + + return help_str; +} + +static void +rspamadm_statconvert (gint argc, gchar **argv) +{ + GOptionContext *context; + GError *error = NULL; + lua_State *L; + ucl_object_t *obj; + + context = g_option_context_new ( + "statconvert - converts statistics from sqlite3 to redis"); + g_option_context_set_summary (context, + "Summary:\n Rspamd administration utility version " + RVERSION + "\n Release id: " + RID); + g_option_context_add_main_entries (context, entries, NULL); + g_option_context_set_ignore_unknown_options (context, TRUE); + + if (!g_option_context_parse (context, &argc, &argv, &error)) { + rspamd_fprintf (stderr, "option parsing failed: %s\n", error->message); + g_error_free (error); + exit (1); + } + + if (!source_db) { + rspamd_fprintf (stderr, "source db is missing\n"); + exit (1); + } + if (!redis_host) { + rspamd_fprintf (stderr, "redis host is missing\n"); + exit (1); + } + if (!symbol) { + rspamd_fprintf (stderr, "symbol is missing\n"); + exit (1); + } + + L = rspamd_lua_init (); + rspamd_lua_set_path (L, NULL, NULL); + + obj = ucl_object_typed_new (UCL_OBJECT); + ucl_object_insert_key (obj, ucl_object_fromstring (source_db), + "source_db", 0, false); + ucl_object_insert_key (obj, ucl_object_fromstring (redis_host), + "redis_host", 0, false); + ucl_object_insert_key (obj, ucl_object_fromstring (symbol), + "symbol", 0, false); + ucl_object_insert_key (obj, ucl_object_frombool (reset_previous), + "reset_previous", 0, false); + + if (cache_db != NULL) { + ucl_object_insert_key (obj, ucl_object_fromstring (cache_db), + "cache_db", 0, false); + } + + if (redis_password) { + ucl_object_insert_key (obj, ucl_object_fromstring (redis_password), + "redis_password", 0, false); + } + + if (redis_db) { + ucl_object_insert_key (obj, ucl_object_fromstring (redis_db), + "redis_db", 0, false); + } + + rspamadm_execute_lua_ucl_subr (L, + argc, + argv, + obj, + "stat_convert"); + + lua_close (L); + ucl_object_unref (obj); +} diff --git a/pool/shard006/C/0117528_3.c b/pool/shard006/C/0117528_3.c new file mode 100644 index 0000000000000000000000000000000000000000..6621e82af13a7f2054b5ff537d80aaa0a29c91df --- /dev/null +++ b/pool/shard006/C/0117528_3.c @@ -0,0 +1,70 @@ +#include +#include + +int main(void) +{ + int judge(char ch);//º¯ÊýÉùÃ÷ + + char str[1001][1001], ch[1001];//¶¨ÒåÒ»¸ö¶þά×Ö·ûÊý×éºÍÒ»¸öһά×Ö·ûÊý×é + int i, j, z, flage, num = 0;//ÉùÃ÷Óï¾ä + + while (scanf("%s", str[num++]) != EOF);//ÓÃEOF¿ØÖÆÊäÈëµ¥´Ê + + for (i = z = 0; i < num - 1; i++) + { + if (strlen(str[i]) < 3) + { + printf((0 == i) ? "%s" : " %s", str[i]); + continue; + } + + if (str[i][0] == 'y' && strlen(str[i]) == 3 && str[i][1] == 'o' && str[i][2] == 'u') + strcpy (str[i], "we"); + + else if (str[i][0] == 'y' && strlen(str[i]) > 3 && str[i][1] == 'o' && str[i][2] == 'u' && judge(str[i][3])) + { + strncpy (ch, str[i], 3); + + if (strcmp (ch, "you") == 0) + { + strncpy (str[i], "we", 2); + + for (j = 3; j < strlen(str[i]); j++) + str[i][j-1] = str[i][j]; + str[i][j-1] = '\0'; + printf((0 == i) ? "%s" : " %s", str[i]); + continue; + } + } + + if (str[i][0] != 'y' && strlen(str[i]) > 3) + { + for (z = 1; z < strlen(str[i]) - 2; z++) + if (judge(str[i][z-1]) && str[i][z] == 'y' && judge(str[i][z+3]))//ÅжÏ×ÖĸyǰһλºÍºóÈýλÊDz»ÊÇ×Öĸ + { + strncpy (ch, str[i]+z, 3);//Èç¹û²»ÊÇ£¬Ôò°Ñ×ÖĸyµÄºóÈýÏî¸´ÖÆ¸øch×Ö·ûÊý×é + ch[3] = '\0'; + break; + } + if (strcmp (ch, "you") == 0) + { + strncpy (str[i]+z, "we", 2); + for (j = 3+z; j < strlen(str[i]); j++) + str[i][j-1] = str[i][j]; + str[i][j-1] = '\0'; + } + } + + printf((0 == i) ? "%s" : " %s", str[i]); + } + + return 0; +} +int judge(char ch)//¶¨Ò庯Êý +//º¯Êý¹¦ÄÜ£ºÅжÏ×Ö·ûÊDz»ÊÇ×Öĸ +{ + if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) + return 0; + else + return 1; +} diff --git a/pool/shard006/C/0117533_thread_test.c b/pool/shard006/C/0117533_thread_test.c new file mode 100644 index 0000000000000000000000000000000000000000..e04fdb9cfde738fce495285b53531d592ebbac93 --- /dev/null +++ b/pool/shard006/C/0117533_thread_test.c @@ -0,0 +1,69 @@ +#include +#include +#include + +static pthread_t thr_a; +static pthread_t thr_b; +static pthread_t thr_c; + +static int token = 0; + +void thread_a(void *arg) +{ + printf("starting thread A\n"); + + while (1) { + printf("A\n"); + time_usleep(30000); + } +} + +void thread_b(void *arg) +{ + printf("starting thread B\n"); + + printf("B\n"); + time_usleep(10000); + token = 1; +} + +void thread_c(void *arg) +{ + int last_token; + int i = 0; + int ret = 0; + printf("starting thread C\n"); + + while (1) { + printf("C\n"); + time_usleep(3000); + + last_token = token; + + printf("joining on thread B, should: %s\n", i ? "FAIL" : "SUCCEEDED"); + + ret = pthread_join(&thr_b, NULL); + if ((ret == 0) && (last_token != token)) + printf("pthread_join SUCCEEDED, %d-%d\n", last_token, token); + else + printf("pthread_join FAIL, error code: %d\n", ret); + + i++; + } +} + +int main(void) +{ + printf("Starting thread tests\n"); + + printf("- adding thread A (%x)\n", &thread_a); + pthread_create(&thr_a, &thread_a, NULL, 4); + + printf("- adding thread B(%x)\n", &thread_b); + pthread_create(&thr_b, &thread_b, NULL, 3); + + printf("- adding thread C(%x)\n", &thread_c); + pthread_create(&thr_c, &thread_c, NULL, 2); + + return 0; +} diff --git a/pool/shard006/C/0117545_angles_count.c b/pool/shard006/C/0117545_angles_count.c new file mode 100644 index 0000000000000000000000000000000000000000..ace7d4d61f57397ae73dc38ae300a2fccb339f16 --- /dev/null +++ b/pool/shard006/C/0117545_angles_count.c @@ -0,0 +1,24 @@ +// Chemfiles, a modern library for chemistry file reading and writing +// Copyright (C) Guillaume Fraux and contributors -- BSD license + +#include +#include +#include + +int main() { + // [example] + CHFL_TOPOLOGY* topology = chfl_topology(); + + // We have two angles: 0-1-2 and 1-2-3 + chfl_topology_add_bond(topology, 0, 1); + chfl_topology_add_bond(topology, 1, 2); + chfl_topology_add_bond(topology, 2, 3); + + uint64_t angles = 0; + chfl_topology_angles_count(topology, &angles); + assert(angles == 2); + + chfl_topology_free(topology); + // [example] + return 0; +} diff --git a/pool/shard006/C/0117546_example_main.c b/pool/shard006/C/0117546_example_main.c new file mode 100644 index 0000000000000000000000000000000000000000..67c82e95c7a6611ae5c8cb7a87fa1d235f71cb6f --- /dev/null +++ b/pool/shard006/C/0117546_example_main.c @@ -0,0 +1,229 @@ +/******************** (C) COPYRIGHT 2012 STMicroelectronics ******************** +* File Name : example_main.c +* Author : MSH Application Team +* Author : Fabio Tota +* Revision : $Revision: 1.5 $ +* Date : $Date: 25/08/2011 12:19:08 $ +* Description : EKSTM32 main file +* HISTORY: +* Date | Modification | Author +* 25/08/2011 | Initial Revision | Fabio Tota +* 17/05/2012 | Uses LIS331DLH driver suitable for use in a program with other MEMS drivers | Abhishek Anand + +******************************************************************************** +* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS +* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. +* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, +* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE +* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING +* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. +* +* THIS SOFTWARE IS SPECIFICALLY DESIGNED FOR EXCLUSIVE USE WITH ST PARTS. +* +*******************************************************************************/ + + +/* Includes ------------------------------------------------------------------*/ +//include files for MKI109V1 board +#include "stm32f10x.h" +#include "usb_lib.h" +#include "usb_desc.h" +#include "i2c_mems.h" +#include "hw_config.h" +#include "usb_pwr.h" +#include "led.h" +#include "button.h" +#include "adc_mems.h" +#include "string.h" +#include + +//include MEMS driver +#include "lis331dlh_driver.h" + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +uint8_t response; +uint8_t USBbuffer[64]; + +/* Extern variables ----------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +//define for example1 or example2 +#define __EXAMPLE1__H +//#define __EXAMPLE2__H + + +/******************************************************************************* +* Function Name : main. +* Description : Main routine. +* Input : None. +* Output : None. +* Return : None. +*******************************************************************************/ +int main(void) +{ + uint8_t buffer[26]; + uint8_t position=0, old_position=0; + AxesRaw_t data; + i8_t val=0; + uint8_t len = 0; + + //Initialize your hardware here + + //function for MKI109V1 board + InitHardware(); + I2C_MEMS_Init(); + + EKSTM32_LEDOff(LED1); + EKSTM32_LEDOff(LED2); + EKSTM32_LEDOff(LED3); + + //wait until the USB is ready (MKI109V1 board) + while(bDeviceState != CONFIGURED); + EKSTM32_LEDOn(LED3); + + //Inizialize MEMS Sensor + //set ODR (turn ON device) + response = LIS331DLH_SetODR( LIS331DLH_ODR_100Hz); + if(response==1){ + len = sprintf((char*)buffer,"\n\rSET_ODR_OK\n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + + //set PowerMode + response = LIS331DLH_SetMode( LIS331DLH_NORMAL); + if(response==1){ + len = sprintf((char*)buffer,"SET_MODE_OK\n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + + } + + //set Fullscale + response = LIS331DLH_SetFullScale( LIS331DLH_FULLSCALE_2); + if(response==1){ + len = sprintf((char*)buffer,"SET_FULLSCALE_OK\n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + + //set axis Enable + response = LIS331DLH_SetAxis( LIS331DLH_X_ENABLE | LIS331DLH_Y_ENABLE | LIS331DLH_Z_ENABLE); + if(response==1){ + len = sprintf((char*)buffer,"SET_AXIS_OK\n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + +/******Example 1******/ +#ifdef __EXAMPLE1__H + while(1){ + //get Acceleration Raw data + response = LIS331DLH_GetAccAxesRaw(&data); + if(response==1){ + //print data values + //function for MKI109V1 board + EKSTM32_LEDToggle(LED1); + len = sprintf((char*)buffer, "X=%6d Y=%6d Z=%6d\r\n", data.AXIS_X, data.AXIS_Y, data.AXIS_Z); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + } +#endif /* __EXAMPLE1__H */ + + + /******Example 2******/ +#ifdef __EXAMPLE2__H + //Inizialize MEMS Sensor + //set Interrupt Threshold + response = LIS331DLH_SetInt1Threshold(20); + if(response==1){ + len = sprintf((char*)buffer,"SET_THRESHOLD_OK\n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + //set Interrupt configuration (all enabled) + response = LIS331DLH_SetInt1Configuration( LIS331DLH_INT_ZHIE_ENABLE | LIS331DLH_INT_ZLIE_ENABLE | + LIS331DLH_INT_YHIE_ENABLE | LIS331DLH_INT_YLIE_ENABLE | + LIS331DLH_INT_XHIE_ENABLE | LIS331DLH_INT_XLIE_ENABLE ); + if(response==1){ + len = sprintf((char*)buffer,"SET_INT_CONF_OK \n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + //set Interrupt Mode + response = LIS331DLH_SetInt1Mode( LIS331DLH_INT_MODE_6D_POSITION); + if(response==1){ + len = sprintf((char*)buffer,"SET_INT_MODE\n\r"); + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + } + + while(1) { + //get 6D Position + response = LIS331DLH_Get6DPositionInt1(&position); + if((response==1) && (old_position!=position)){ + EKSTM32_LEDToggle(LED1); + switch (position){ + case LIS331DLH_UP_SX: + len = sprintf((char*)buffer,"\n\rposition = UP_SX\n\r"); + break; + case LIS331DLH_UP_DX: + len = sprintf((char*)buffer,"\n\rposition = UP_DX\n\r"); + break; + case LIS331DLH_DW_SX: + len = sprintf((char*)buffer,"\n\rposition = DW_SX\n\r"); + break; + case LIS331DLH_DW_DX: + len = sprintf((char*)buffer,"\n\rposition = DW_DX\n\r"); + break; + case LIS331DLH_TOP: + len = sprintf((char*)buffer,"\n\rposition = TOP\n\r"); + break; + case LIS331DLH_BOTTOM: + len = sprintf((char*)buffer,"\n\rposition = BOTTOM\n\r"); + break; + default: + len = sprintf((char*)buffer,"\n\rposition = unknown\n\r"); + break; + } + + //function for MKI109V1 board + USB_SIL_Write(EP1_IN, buffer, len); + SetEPTxValid(ENDP1); + old_position = position; + } + } +#endif /*__EXAMPLE2__H */ + + +} // end main + + +//function for MKI109V1 board +#ifdef USE_FULL_ASSERT +/******************************************************************************* +* Function Name : assert_failed +* Description : Reports the name of the source file and the source line number +* where the assert_param error has occurred. +* Input : - file: pointer to the source file name +* - line: assert_param error line source number +* Output : None +* Return : None +*******************************************************************************/ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + + /* Infinite loop */ + while (1) + {} +} +#endif + +/******************* (C) COPYRIGHT 2012 STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0117554_gc_hal_kernel_allocator_dmabuf.c b/pool/shard006/C/0117554_gc_hal_kernel_allocator_dmabuf.c new file mode 100644 index 0000000000000000000000000000000000000000..43203f7bc6e4d7bb4d62d8b4be2abacd4473f31a --- /dev/null +++ b/pool/shard006/C/0117554_gc_hal_kernel_allocator_dmabuf.c @@ -0,0 +1,353 @@ +/**************************************************************************** +* +* The MIT License (MIT) +* +* Copyright (c) 2014 - 2016 Vivante Corporation +* +* Permission is hereby granted, free of charge, to any person obtaining a +* copy of this software and associated documentation files (the "Software"), +* to deal in the Software without restriction, including without limitation +* the rights to use, copy, modify, merge, publish, distribute, sublicense, +* and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +* DEALINGS IN THE SOFTWARE. +* +***************************************************************************** +* +* The GPL License (GPL) +* +* Copyright (C) 2014 - 2016 Vivante Corporation +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License +* as published by the Free Software Foundation; either version 2 +* of the License, or (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program; if not, write to the Free Software Foundation, +* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +* +***************************************************************************** +* +* Note: This software is released under dual MIT and GPL licenses. A +* recipient may use this file under the terms of either the MIT license or +* GPL License. If you wish to use only one license not the other, you can +* indicate your decision by deleting one of the above license notices in your +* version of this file. +* +*****************************************************************************/ + + +#include "gc_hal_kernel_linux.h" +#include "gc_hal_kernel_allocator.h" + +#include +#include +#include +#include +#include + +#include +#include + +#define _GC_OBJ_ZONE gcvZONE_OS + +/* Descriptor of a dma_buf imported. */ +typedef struct _gcsDMABUF +{ + struct dma_buf *dmabuf; + struct dma_buf_attachment *attachment; + struct sg_table *sgtable; + unsigned long *pagearray; + int handle; + int fd; +} +gcsDMABUF; + +static gceSTATUS +_DmabufAttach( + IN gckALLOCATOR Allocator, + IN gcsATTACH_DESC_PTR Desc, + IN PLINUX_MDL Mdl + ) +{ + gceSTATUS status; + + gckOS os = Allocator->os; + + int fd = (int) Desc->handle; + + struct dma_buf *dmabuf = NULL; + struct sg_table *sgt = NULL; + struct dma_buf_attachment *attachment = NULL; + int npages = 0; + unsigned long *pagearray = NULL; + int i, j, k = 0; + struct scatterlist *s; + gcsDMABUF *gcdmabuf = NULL; + + gcmkHEADER(); + + gcmkVERIFY_OBJECT(os, gcvOBJ_OS); + + /* Import dma buf handle. */ + dmabuf = dma_buf_get(fd); + + if (!dmabuf) + { + gcmkONERROR(gcvSTATUS_NOT_SUPPORTED); + } + + attachment = dma_buf_attach(dmabuf, &os->device->platform->device->dev); + + if (!attachment) + { + gcmkONERROR(gcvSTATUS_NOT_SUPPORTED); + } + + sgt = dma_buf_map_attachment(attachment, DMA_BIDIRECTIONAL); + + if (!sgt) + { + gcmkONERROR(gcvSTATUS_NOT_SUPPORTED); + } + + /* Prepare page array. */ + /* Get number of pages. */ + for_each_sg(sgt->sgl, s, sgt->orig_nents, i) + { + npages += (sg_dma_len(s) + PAGE_SIZE - 1) / PAGE_SIZE; + } + + /* Allocate page arrary. */ + gcmkONERROR(gckOS_Allocate(os, npages * gcmSIZEOF(*pagearray), (gctPOINTER *)&pagearray)); + + /* Fill page arrary. */ + for_each_sg(sgt->sgl, s, sgt->orig_nents, i) + { + for (j = 0; j < (sg_dma_len(s) + PAGE_SIZE - 1) / PAGE_SIZE; j++) + { + pagearray[k++] = sg_dma_address(s) + j * PAGE_SIZE; + } + } + + /* Prepare descriptor. */ + gcmkONERROR(gckOS_Allocate(os, sizeof(gcsDMABUF), (gctPOINTER *)&gcdmabuf)); + + gcdmabuf->fd = fd; + gcdmabuf->dmabuf = dmabuf; + gcdmabuf->pagearray = pagearray; + gcdmabuf->attachment = attachment; + gcdmabuf->sgtable = sgt; + + /* Record page number. */ + Mdl->numPages = npages; + + Mdl->priv = gcdmabuf; + + gcmkFOOTER_NO(); + return gcvSTATUS_OK; + +OnError: + gcmkFOOTER(); + return status; +} + + +static void +_DmabufFree( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl + ) +{ + gcsDMABUF *gcdmabuf = Mdl->priv; + gckOS os = Allocator->os; + + dma_buf_unmap_attachment(gcdmabuf->attachment, gcdmabuf->sgtable, DMA_BIDIRECTIONAL); + + dma_buf_detach(gcdmabuf->dmabuf, gcdmabuf->attachment); + + dma_buf_put(gcdmabuf->dmabuf); + + gckOS_Free(os, gcdmabuf->pagearray); + + gckOS_Free(os, gcdmabuf); +} + +static gctINT +_DmabufMapUser( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl, + IN PLINUX_MDL_MAP MdlMap, + IN gctBOOL Cacheable + ) +{ + gcsDMABUF *gcdmabuf = Mdl->priv; + gceSTATUS status; + PLINUX_MDL mdl = Mdl; + PLINUX_MDL_MAP mdlMap = MdlMap; + struct file * file = gcdmabuf->dmabuf->file; + + mdlMap->vmaAddr = (gctSTRING)vm_mmap(file, + 0L, + mdl->numPages * PAGE_SIZE, + PROT_READ | PROT_WRITE, + MAP_SHARED, + 0); + + if (IS_ERR(mdlMap->vmaAddr)) + { + gcmkONERROR(gcvSTATUS_OUT_OF_RESOURCES); + } + + down_write(¤t->mm->mmap_sem); + + mdlMap->vma = find_vma(current->mm, (unsigned long)mdlMap->vmaAddr); + + up_write(¤t->mm->mmap_sem); + + if (mdlMap->vma == gcvNULL) + { + gcmkONERROR(gcvSTATUS_OUT_OF_RESOURCES); + } + + return 0; + +OnError: + return status; +} + +static void +_DmabufUnmapUser( + IN gckALLOCATOR Allocator, + IN gctPOINTER Logical, + IN gctUINT32 Size + ) +{ + if (unlikely(current->mm == gcvNULL)) + { + /* Do nothing if process is exiting. */ + return; + } + + vm_munmap((unsigned long)Logical, Size); +} + +static gceSTATUS +_DmabufMapKernel( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl, + OUT gctPOINTER *Logical + ) +{ + /* Kernel doesn't acess video memory. */ + return gcvSTATUS_NOT_SUPPORTED; + +} + +static gceSTATUS +_DmabufUnmapKernel( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl, + IN gctPOINTER Logical + ) +{ + /* Kernel doesn't acess video memory. */ + return gcvSTATUS_NOT_SUPPORTED; +} + +static gceSTATUS +_DmabufLogicalToPhysical( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl, + IN gctPOINTER Logical, + IN gctUINT32 ProcessID, + OUT gctPHYS_ADDR_T * Physical + ) +{ + return gcvSTATUS_NOT_SUPPORTED; +} + + +static gceSTATUS +_DmabufCache( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl, + IN gctPOINTER Logical, + IN gctUINT32 Physical, + IN gctUINT32 Bytes, + IN gceCACHEOPERATION Operation + ) +{ + return gcvSTATUS_OK; +} + + +static gceSTATUS +_DmabufPhysical( + IN gckALLOCATOR Allocator, + IN PLINUX_MDL Mdl, + IN gctUINT32 Offset, + OUT gctPHYS_ADDR_T * Physical + ) +{ + gcsDMABUF *gcdmabuf = Mdl->priv; + + *Physical = gcdmabuf->pagearray[Offset]; + + + return gcvSTATUS_OK; +} + +/* Default allocator operations. */ +static gcsALLOCATOR_OPERATIONS DmabufAllocatorOperations = +{ + .Attach = _DmabufAttach, + .Free = _DmabufFree, + .MapUser = _DmabufMapUser, + .UnmapUser = _DmabufUnmapUser, + .MapKernel = _DmabufMapKernel, + .UnmapKernel = _DmabufUnmapKernel, + .LogicalToPhysical = _DmabufLogicalToPhysical, + .Cache = _DmabufCache, + .Physical = _DmabufPhysical, +}; + +/* Default allocator entry. */ +gceSTATUS +_DmabufAlloctorInit( + IN gckOS Os, + OUT gckALLOCATOR * Allocator + ) +{ + gceSTATUS status; + gckALLOCATOR allocator; + + gcmkONERROR( + gckALLOCATOR_Construct(Os, &DmabufAllocatorOperations, &allocator)); + + allocator->capability = gcvALLOC_FLAG_DMABUF; + + *Allocator = allocator; + + return gcvSTATUS_OK; + +OnError: + return status; +} + diff --git a/pool/shard006/C/0117567_ede_cbcm_enc.c b/pool/shard006/C/0117567_ede_cbcm_enc.c new file mode 100644 index 0000000000000000000000000000000000000000..86f27d077aae754a96102988f296cb5ac79509ac --- /dev/null +++ b/pool/shard006/C/0117567_ede_cbcm_enc.c @@ -0,0 +1,189 @@ +/* ede_cbcm_enc.c */ +/* + * Written by Ben Laurie for the OpenSSL project 13 Feb + * 1999. + */ +/* ==================================================================== + * Copyright (c) 1999 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 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. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +/* + * + * This is an implementation of Triple DES Cipher Block Chaining with Output + * Feedback Masking, by Coppersmith, Johnson and Matyas, (IBM and Certicom). + * + * Note that there is a known attack on this by Biham and Knudsen but it + * takes a lot of work: + * + * http://www.cs.technion.ac.il/users/wwwb/cgi-bin/tr-get.cgi/1998/CS/CS0928.ps.gz + * + */ + +#include /* To see if OPENSSL_NO_DESCBCM is defined */ + +#ifndef OPENSSL_NO_DESCBCM +# include "des_locl.h" + +void DES_ede3_cbcm_encrypt(const unsigned char *in, unsigned char *out, + long length, DES_key_schedule *ks1, + DES_key_schedule *ks2, DES_key_schedule *ks3, + DES_cblock *ivec1, DES_cblock *ivec2, int enc) +{ + register DES_LONG tin0, tin1; + register DES_LONG tout0, tout1, xor0, xor1, m0, m1; + register long l = length; + DES_LONG tin[2]; + unsigned char *iv1, *iv2; + + iv1 = &(*ivec1)[0]; + iv2 = &(*ivec2)[0]; + + if (enc) { + c2l(iv1, m0); + c2l(iv1, m1); + c2l(iv2, tout0); + c2l(iv2, tout1); + for (l -= 8; l >= -7; l -= 8) { + tin[0] = m0; + tin[1] = m1; + DES_encrypt1(tin, ks3, 1); + m0 = tin[0]; + m1 = tin[1]; + + if (l < 0) { + c2ln(in, tin0, tin1, l + 8); + } else { + c2l(in, tin0); + c2l(in, tin1); + } + tin0 ^= tout0; + tin1 ^= tout1; + + tin[0] = tin0; + tin[1] = tin1; + DES_encrypt1(tin, ks1, 1); + tin[0] ^= m0; + tin[1] ^= m1; + DES_encrypt1(tin, ks2, 0); + tin[0] ^= m0; + tin[1] ^= m1; + DES_encrypt1(tin, ks1, 1); + tout0 = tin[0]; + tout1 = tin[1]; + + l2c(tout0, out); + l2c(tout1, out); + } + iv1 = &(*ivec1)[0]; + l2c(m0, iv1); + l2c(m1, iv1); + + iv2 = &(*ivec2)[0]; + l2c(tout0, iv2); + l2c(tout1, iv2); + } else { + register DES_LONG t0, t1; + + c2l(iv1, m0); + c2l(iv1, m1); + c2l(iv2, xor0); + c2l(iv2, xor1); + for (l -= 8; l >= -7; l -= 8) { + tin[0] = m0; + tin[1] = m1; + DES_encrypt1(tin, ks3, 1); + m0 = tin[0]; + m1 = tin[1]; + + c2l(in, tin0); + c2l(in, tin1); + + t0 = tin0; + t1 = tin1; + + tin[0] = tin0; + tin[1] = tin1; + DES_encrypt1(tin, ks1, 0); + tin[0] ^= m0; + tin[1] ^= m1; + DES_encrypt1(tin, ks2, 1); + tin[0] ^= m0; + tin[1] ^= m1; + DES_encrypt1(tin, ks1, 0); + tout0 = tin[0]; + tout1 = tin[1]; + + tout0 ^= xor0; + tout1 ^= xor1; + if (l < 0) { + l2cn(tout0, tout1, out, l + 8); + } else { + l2c(tout0, out); + l2c(tout1, out); + } + xor0 = t0; + xor1 = t1; + } + + iv1 = &(*ivec1)[0]; + l2c(m0, iv1); + l2c(m1, iv1); + + iv2 = &(*ivec2)[0]; + l2c(xor0, iv2); + l2c(xor1, iv2); + } + tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; + tin[0] = tin[1] = 0; +} +#endif diff --git a/pool/shard006/C/0117571_test-littleskin.c b/pool/shard006/C/0117571_test-littleskin.c new file mode 100644 index 0000000000000000000000000000000000000000..2f6e4a3f842dcd3e0b8c00afc6a11abcdd949270 --- /dev/null +++ b/pool/shard006/C/0117571_test-littleskin.c @@ -0,0 +1,115 @@ +#include +#include +#include "littleskin.h" +#include + +GtkWidget* +test_window (const char *title, LittleSkin *skin) { + GtkWidget *window; + GtkWidget *hbox; + + hbox = gtk_hbox_new (FALSE, 0); + gtk_box_pack_start (GTK_BOX (hbox), + little_skin_get_image_widget (skin), + FALSE, FALSE, 0); + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + if (title) gtk_window_set_title (GTK_WINDOW (window), title); + + { + GtkWidget *image2; + image2 = gtk_image_new_from_file ("/usr/share/pixmaps/fish/fishanim.png"); + little_skin_set_alpha (skin, TRUE); + little_skin_set_alpha_level (skin, 192); + little_skin_set_alpha_pixbuf (skin, gtk_image_get_pixbuf (GTK_IMAGE (image2))); + } + + gtk_container_add (GTK_CONTAINER (window), hbox); + + return window; +} + + +gboolean +test_timeout (GtkWidget *window) { + static int segment_num = 0; + static int cnt = 0; + GList *segments; + const char *segment_name; + + LittleSkin *skin = gtk_object_get_data (GTK_OBJECT (window), "skin"); + + segments = little_skin_get_segment_names (skin); + segment_name = (char*)(g_list_nth (segments, segment_num)->data); + if (little_skin_is_segment_animation (skin, segment_name)) { + g_message ("%s is an anim", segment_name); + if (cnt == 0) { + little_skin_start_animation (skin, segment_name, 200); + } + cnt ++; + if (cnt > 100) { + little_skin_stop_animation (skin); + segment_num++; + if (segment_num >= g_list_length (segments)) { + segment_num = 0; + } + } + } else { + little_skin_set_image (skin, segment_name, cnt); + little_skin_redraw (skin); + cnt++; + if (cnt >= little_skin_get_segment_range (skin, segment_name)) { + cnt = 0; + segment_num++; + if (segment_num >= g_list_length (segments)) { + segment_num = 0; + } + } + } + + return TRUE; +} + +void +test_delete_event (GtkWidget *widget, + GdkEvent *event, + gpointer crack) { + guint id = GPOINTER_TO_INT (crack); + gtk_timeout_remove (id); + gtk_main_quit (); +} + +int +main (int argc, char *argv[]) { + GtkWidget *window; + GtkWidget *image; + GList *loads = NULL; + LittleSkin *skin; + + gtk_init (&argc, &argv); + + { + LittleSkinLoad *load; + load = little_skin_load_new ("charging", 101); + loads = g_list_append (loads, load); + load = little_skin_load_new ("battery", 101); + loads = g_list_append (loads, load); + load = little_skin_load_new ("low", 0); + loads = g_list_append (loads, load); + } + skin = little_skin_new (argv[1], argv[2], loads); + + little_skin_set_alpha (skin, TRUE); + + window = test_window ("littleskin", skin); + gtk_object_set_data (GTK_OBJECT (window), "skin", skin); + g_signal_connect (window, "delete_event", + G_CALLBACK (test_delete_event), + GINT_TO_POINTER (gtk_timeout_add (10, (GtkFunction)test_timeout, window))); + gtk_widget_show_all (window); + gtk_main (); + + little_skin_destroy (skin); + g_list_foreach (loads, (GFunc)little_skin_load_destroy, NULL); + g_list_free (loads); +} diff --git a/pool/shard006/C/0117580_acc_map_data-device_already-1.c b/pool/shard006/C/0117580_acc_map_data-device_already-1.c new file mode 100644 index 0000000000000000000000000000000000000000..b48a1adbbb685397213427f231919e8cce1c7443 --- /dev/null +++ b/pool/shard006/C/0117580_acc_map_data-device_already-1.c @@ -0,0 +1,36 @@ +/* Verify that we refuse 'acc_map_data' when the "device address [...] is + already mapped". */ + +/* { dg-skip-if "" { *-*-* } { "*" } { "-DACC_MEM_SHARED=0" } } */ + +#include +#include +#include +#include + +int +main () +{ + const int N = 131; + + char *h1 = (char *) malloc (N); + assert (h1); + void *d = acc_malloc (N); + assert (d); + acc_map_data (h1, d, N); + + char *h2 = (char *) malloc (N); + assert (h2); + /* Try to arrange a setting such that a later 'acc_unmap_data' would find the + device memory object still referenced elsewhere. This is not possible, + given the semantics of 'acc_map_data'. */ + fprintf (stderr, "CheCKpOInT\n"); + acc_map_data (h2, d, N); + + return 0; +} + + +/* { dg-output "CheCKpOInT(\n|\r\n|\r).*" } */ +/* { dg-output "device address \\\[\[0-9a-fA-FxX\]+, \\\+131\\\] is already mapped" } */ +/* { dg-shouldfail "" } */ diff --git a/pool/shard006/C/0117590_errno.c b/pool/shard006/C/0117590_errno.c new file mode 100644 index 0000000000000000000000000000000000000000..f22ee2ea360c0a100af756fc8dfde9c1b16854c3 --- /dev/null +++ b/pool/shard006/C/0117590_errno.c @@ -0,0 +1,221 @@ +/* $Id$ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * 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 +#include +#include +#if PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO +# include +#endif +#if PJMEDIA_AUDIO_DEV_HAS_WMME +# ifdef _MSC_VER +# pragma warning(push, 3) +# endif +# include +# include +# ifdef _MSC_VER +# pragma warning(pop) +# endif +#endif + +/* PJMEDIA-Audiodev's own error codes/messages + * MUST KEEP THIS ARRAY SORTED!! + * Message must be limited to 64 chars! + */ + +#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) + +static const struct +{ + int code; + const char *msg; +} err_str[] = +{ + PJ_BUILD_ERR( PJMEDIA_EAUD_ERR, "Unspecified audio device error" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_SYSERR, "Unknown error from audio driver" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INIT, "Audio subsystem not initialized" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INVDEV, "Invalid audio device" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_NODEV, "Found no audio devices" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_NODEFDEV, "Unable to find default audio device" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_NOTREADY, "Audio device not ready" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INVCAP, "Invalid or unsupported audio capability" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_INVOP, "Invalid or unsupported audio device operation" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_BADFORMAT, "Bad or invalid audio device format" ), + PJ_BUILD_ERR( PJMEDIA_EAUD_SAMPFORMAT, "Invalid audio device sample format"), + PJ_BUILD_ERR( PJMEDIA_EAUD_BADLATENCY, "Bad audio latency setting") + +}; + +#endif /* PJ_HAS_ERROR_STRING */ + + + +/* + * pjmedia_audiodev_strerror() + */ +PJ_DEF(pj_str_t) pjmedia_audiodev_strerror(pj_status_t statcode, + char *buf, pj_size_t bufsize ) +{ + pj_str_t errstr; + +#if defined(PJ_HAS_ERROR_STRING) && (PJ_HAS_ERROR_STRING != 0) + + + /* See if the error comes from Core Audio. */ +#if PJMEDIA_AUDIO_DEV_HAS_COREAUDIO + if (statcode >= PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START && + statcode <= PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_END) + { + int ca_err = PJMEDIA_AUDIODEV_COREAUDIO_ERRNO_START - statcode; + + PJ_UNUSED_ARG(ca_err); + // TODO: create more helpful error messages + errstr.ptr = buf; + pj_strcpy2(&errstr, "Core audio error"); + return errstr; + } else +#endif + + /* See if the error comes from PortAudio. */ +#if PJMEDIA_AUDIO_DEV_HAS_PORTAUDIO + if (statcode >= PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START && + statcode <= PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_END) + { + + //int pa_err = statcode - PJMEDIA_ERRNO_FROM_PORTAUDIO(0); + int pa_err = PJMEDIA_AUDIODEV_PORTAUDIO_ERRNO_START - statcode; + pj_str_t msg; + + msg.ptr = (char*)Pa_GetErrorText(pa_err); + msg.slen = pj_ansi_strlen(msg.ptr); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } else +#endif /* PJMEDIA_SOUND_IMPLEMENTATION */ + + /* See if the error comes from WMME */ +#if PJMEDIA_AUDIO_DEV_HAS_WMME + if ((statcode >= PJMEDIA_AUDIODEV_WMME_IN_ERROR_START && + statcode < PJMEDIA_AUDIODEV_WMME_IN_ERROR_END) || + (statcode >= PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START && + statcode < PJMEDIA_AUDIODEV_WMME_OUT_ERROR_END)) + { + MMRESULT native_err, mr; + MMRESULT (WINAPI *waveGetErrText)(UINT mmrError, LPTSTR pszText, UINT cchText); + PJ_DECL_UNICODE_TEMP_BUF(wbuf, 80) + + if (statcode >= PJMEDIA_AUDIODEV_WMME_IN_ERROR_START && + statcode <= PJMEDIA_AUDIODEV_WMME_IN_ERROR_END) + { + native_err = statcode - PJMEDIA_AUDIODEV_WMME_IN_ERROR_START; + waveGetErrText = &waveInGetErrorText; + } else { + native_err = statcode - PJMEDIA_AUDIODEV_WMME_OUT_ERROR_START; + waveGetErrText = &waveOutGetErrorText; + } + +#if PJ_NATIVE_STRING_IS_UNICODE + mr = (*waveGetErrText)(native_err, wbuf, PJ_ARRAY_SIZE(wbuf)); + if (mr == MMSYSERR_NOERROR) { + int len = wcslen(wbuf); + pj_unicode_to_ansi(wbuf, len, buf, bufsize); + } +#else + mr = (*waveGetErrText)(native_err, buf, (UINT)bufsize); +#endif + + if (mr==MMSYSERR_NOERROR) { + errstr.ptr = buf; + errstr.slen = pj_ansi_strlen(buf); + return errstr; + } else { + pj_ansi_snprintf(buf, bufsize, "MMSYSTEM native error %d", + native_err); + return pj_str(buf); + } + + } else +#endif + +/* See if the error comes from BDIMAD */ +#if PJMEDIA_AUDIO_DEV_HAS_BDIMAD + + if (statcode >= PJMEDIA_AUDIODEV_BDIMAD_ERROR_START && + statcode < PJMEDIA_AUDIODEV_BDIMAD_ERROR_END) + { + pj_status_t native_err; + native_err = statcode - PJMEDIA_AUDIODEV_BDIMAD_ERROR_START; + + pj_ansi_snprintf(buf, bufsize, "BDIMAD native error %d", native_err); + return pj_str(buf); + } else +#endif + + /* Audiodev error */ + if (statcode >= PJMEDIA_AUDIODEV_ERRNO_START && + statcode < PJMEDIA_AUDIODEV_ERRNO_END) + { + /* Find the error in the table. + * Use binary search! + */ + int first = 0; + int n = PJ_ARRAY_SIZE(err_str); + + while (n > 0) { + int half = n/2; + int mid = first + half; + + if (err_str[mid].code < statcode) { + first = mid+1; + n -= (half+1); + } else if (err_str[mid].code > statcode) { + n = half; + } else { + first = mid; + break; + } + } + + + if (PJ_ARRAY_SIZE(err_str) && err_str[first].code == statcode) { + pj_str_t msg; + + msg.ptr = (char*)err_str[first].msg; + msg.slen = pj_ansi_strlen(err_str[first].msg); + + errstr.ptr = buf; + pj_strncpy_with_null(&errstr, &msg, bufsize); + return errstr; + + } + } +#endif /* PJ_HAS_ERROR_STRING */ + + /* Error not found. */ + errstr.ptr = buf; + errstr.slen = pj_ansi_snprintf(buf, bufsize, + "Unknown pjmedia-audiodev error %d", + statcode); + if (errstr.slen < 1 || errstr.slen >= (pj_ssize_t)bufsize) + errstr.slen = bufsize - 1; + return errstr; +} + diff --git a/pool/shard006/C/0117592_random.c b/pool/shard006/C/0117592_random.c new file mode 100644 index 0000000000000000000000000000000000000000..0cec6a027c774c996236f580c2502d5d67ff4728 --- /dev/null +++ b/pool/shard006/C/0117592_random.c @@ -0,0 +1,199 @@ +/* Copyright (C) 2005 - 2008 Jeff Dike */ + +/* Much of this ripped from drivers/char/hw_random.c, see there for other + * copyright. + * + * This software may be used and distributed according to the terms + * of the GNU General Public License, incorporated herein by reference. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * core module and version information + */ +#define RNG_VERSION "1.0.0" +#define RNG_MODULE_NAME "hw_random" + +#define RNG_MISCDEV_MINOR 183 /* official */ + +/* Changed at init time, in the non-modular case, and at module load + * time, in the module case. Presumably, the module subsystem + * protects against a module being loaded twice at the same time. + */ +static int random_fd = -1; +static DECLARE_WAIT_QUEUE_HEAD(host_read_wait); + +static int rng_dev_open (struct inode *inode, struct file *filp) +{ + /* enforce read-only access to this chrdev */ + if ((filp->f_mode & FMODE_READ) == 0) + { + return -EINVAL; + } + + if ((filp->f_mode & FMODE_WRITE) != 0) + { + return -EINVAL; + } + + return 0; +} + +static atomic_t host_sleep_count = ATOMIC_INIT(0); + +static ssize_t rng_dev_read (struct file *filp, char __user *buf, size_t size, + loff_t *offp) +{ + u32 data; + int n, ret = 0, have_data; + + while (size) + { + n = os_read_file(random_fd, &data, sizeof(data)); + + if (n > 0) + { + have_data = n; + + while (have_data && size) + { + if (put_user((u8) data, buf++)) + { + ret = ret ? : -EFAULT; + break; + } + + size--; + ret++; + have_data--; + data >>= 8; + } + } + else if (n == -EAGAIN) + { + DECLARE_WAITQUEUE(wait, current); + + if (filp->f_flags & O_NONBLOCK) + { + return ret ? : -EAGAIN; + } + + atomic_inc(&host_sleep_count); + reactivate_fd(random_fd, RANDOM_IRQ); + add_sigio_fd(random_fd); + + add_wait_queue(&host_read_wait, &wait); + set_task_state(current, TASK_INTERRUPTIBLE); + + schedule(); + remove_wait_queue(&host_read_wait, &wait); + + if (atomic_dec_and_test(&host_sleep_count)) + { + ignore_sigio_fd(random_fd); + deactivate_fd(random_fd, RANDOM_IRQ); + } + } + else + { + return n; + } + + if (signal_pending (current)) + { + return ret ? : -ERESTARTSYS; + } + } + + return ret; +} + +static const struct file_operations rng_chrdev_ops = +{ + .owner = THIS_MODULE, + .open = rng_dev_open, + .read = rng_dev_read, + .llseek = noop_llseek, +}; + +/* rng_init shouldn't be called more than once at boot time */ +static struct miscdevice rng_miscdev = +{ + RNG_MISCDEV_MINOR, + RNG_MODULE_NAME, + &rng_chrdev_ops, +}; + +static irqreturn_t random_interrupt(int irq, void *data) +{ + wake_up(&host_read_wait); + + return IRQ_HANDLED; +} + +/* + * rng_init - initialize RNG module + */ +static int __init rng_init (void) +{ + int err; + + err = os_open_file("/dev/random", of_read(OPENFLAGS()), 0); + + if (err < 0) + { + goto out; + } + + random_fd = err; + + err = um_request_irq(RANDOM_IRQ, random_fd, IRQ_READ, random_interrupt, + 0, "random", NULL); + + if (err) + { + goto err_out_cleanup_hw; + } + + sigio_broken(random_fd, 1); + + err = misc_register (&rng_miscdev); + + if (err) + { + printk (KERN_ERR RNG_MODULE_NAME ": misc device register " + "failed\n"); + goto err_out_cleanup_hw; + } + +out: + return err; + +err_out_cleanup_hw: + os_close_file(random_fd); + random_fd = -1; + goto out; +} + +/* + * rng_cleanup - shutdown RNG module + */ +static void __exit rng_cleanup (void) +{ + os_close_file(random_fd); + misc_deregister (&rng_miscdev); +} + +module_init (rng_init); +module_exit (rng_cleanup); + +MODULE_DESCRIPTION("UML Host Random Number Generator (RNG) driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0117594_adc_l1.c b/pool/shard006/C/0117594_adc_l1.c new file mode 100644 index 0000000000000000000000000000000000000000..bbb7e215b9557ad6221138571b89ec527c0e8290 --- /dev/null +++ b/pool/shard006/C/0117594_adc_l1.c @@ -0,0 +1,188 @@ +/* + * Copyright (C) 2016 Fundacion Inria Chile + * + * This file is subject to the terms and conditions of the GNU Lesser General + * Public License v2.1. See the file LICENSE in the top level directory for more + * details. + */ + +/** + * @ingroup cpu_stm32 + * @ingroup drivers_periph_adc + * @{ + * + * @file + * @brief Low-level ADC driver implementation + * + * @author Francisco Molina + * @author Hauke Petersen + * @author Nick v. IJzendoorn + * + * @} + */ + +#include "cpu.h" +#include "mutex.h" +#include "periph/adc.h" + +/** + * @brief Maximum allowed ADC clock speed + */ +#define MAX_ADC_SPEED (12000000U) + +/** + * @brief ADC clock settings + * + * NB: with ADC_CLOCK_HIGH, Vdda should be 2.4V min + * + */ +#define ADC_CLOCK_HIGH (0) +#define ADC_CLOCK_MEDIUM (ADC_CCR_ADCPRE_0) +#define ADC_CLOCK_LOW (ADC_CCR_ADCPRE_1) + +/** + * @brief ADC sample time, cycles + */ +#define ADC_SAMPLE_TIME_4C (0) +#define ADC_SAMPLE_TIME_9C (1) +#define ADC_SAMPLE_TIME_16C (2) +#define ADC_SAMPLE_TIME_24C (3) +#define ADC_SAMPLE_TIME_48C (4) +#define ADC_SAMPLE_TIME_96C (5) +#define ADC_SAMPLE_TIME_192C (6) +#define ADC_SAMPLE_TIME_384C (7) + +/** + * @brief Load the ADC configuration + */ +static const adc_conf_t adc_config[] = ADC_CONFIG; + +/** + * @brief Allocate locks for all three available ADC device + * + * All STM32l1 CPU's have single ADC device + */ +static mutex_t lock = MUTEX_INIT; + +static inline void prep(void) +{ + mutex_lock(&lock); + + /* ADC clock is always HSI clock */ + if (!(RCC->CR & RCC_CR_HSION)) { + RCC->CR |= RCC_CR_HSION; + /* Wait for HSI to become ready */ + while (!(RCC->CR & RCC_CR_HSION)) {} + } + + RCC->APB2ENR |= RCC_APB2ENR_ADC1EN; +} + +static inline void done(void) +{ + RCC->APB2ENR &= ~(RCC_APB2ENR_ADC1EN); + mutex_unlock(&lock); +} + +static void adc_set_sample_time(uint8_t time) +{ + uint8_t i; + uint32_t reg32 = 0; + + for (i = 0; i <= 9; i++) { + reg32 |= (time << (i * 3)); + } + +#if defined(CPU_MODEL_STM32L152RE) + ADC1->SMPR0 = reg32; +#endif + ADC1->SMPR1 = reg32; + ADC1->SMPR2 = reg32; + ADC1->SMPR3 = reg32; +} + +int adc_init(adc_t line) +{ + /* check if the line is valid */ + if (line >= ADC_NUMOF) { + return -1; + } + + /* lock and power-on the device */ + prep(); + + /* configure the pin */ + if ((adc_config[line].pin != GPIO_UNDEF)) + gpio_init_analog(adc_config[line].pin); + + /* set ADC clock prescaler */ + ADC->CCR &= ~ADC_CCR_ADCPRE; + ADC->CCR |= ADC_CLOCK_MEDIUM; + + /* Set sample time */ + /* Min 4us needed for temperature sensor measurements */ + switch (ADC->CCR & ADC_CCR_ADCPRE) { + case ADC_CLOCK_LOW: + /* 4 MHz ADC clock -> 16 cycles */ + adc_set_sample_time(ADC_SAMPLE_TIME_16C); + break; + case ADC_CLOCK_MEDIUM: + /* 8 MHz ADC clock -> 48 cycles */ + adc_set_sample_time(ADC_SAMPLE_TIME_48C); + break; + default: + /* 16 MHz ADC clock -> 96 cycles */ + adc_set_sample_time(ADC_SAMPLE_TIME_96C); + } + + /* check if this channel is an internal ADC channel, if so + * enable the internal temperature and Vref */ + if (adc_config[line].chan == 16 || adc_config[line].chan == 17) { + ADC->CCR |= ADC_CCR_TSVREFE; + } + + /* enable the ADC module */ + ADC1->CR2 = ADC_CR2_ADON; + /* turn off during idle phase*/ + ADC1->CR1 = ADC_CR1_PDI; + + /* free the device again */ + done(); + + return 0; +} + +int32_t adc_sample(adc_t line, adc_res_t res) +{ + int sample; + + /* check if resolution is applicable */ + if ( (res != ADC_RES_6BIT) && + (res != ADC_RES_8BIT) && + (res != ADC_RES_10BIT) && + (res != ADC_RES_12BIT)) { + return -1; + } + + /* lock and power on the ADC device */ + prep(); + + /* set resolution, conversion channel and single read */ + ADC1->CR1 |= res & ADC_CR1_RES; + ADC1->SQR1 &= ~ADC_SQR1_L; + ADC1->SQR5 = adc_config[line].chan; + + /* wait for regulat channel to be ready*/ + while (!(ADC1->SR & ADC_SR_RCNR)) {} + /* start conversion and wait for results */ + ADC1->CR2 |= ADC_CR2_SWSTART; + while (!(ADC1->SR & ADC_SR_EOC)) {} + /* finally read sample and reset the STRT bit in the status register */ + sample = (int)ADC1->DR; + ADC1 -> SR &= ~ADC_SR_STRT; + + /* power off and unlock device again */ + done(); + + return sample; +} diff --git a/pool/shard006/C/0117597_sec_gaf.c b/pool/shard006/C/0117597_sec_gaf.c new file mode 100644 index 0000000000000000000000000000000000000000..05a486912ea6f1358b4dc04317a574193df674a6 --- /dev/null +++ b/pool/shard006/C/0117597_sec_gaf.c @@ -0,0 +1,248 @@ +/* + * sec_gaf.c + * + */ + +#include +#include +#include +#include +#include +#include + +static struct GAForensicINFO { + unsigned short ver; + unsigned int size; + unsigned short task_struct_struct_state; + unsigned short task_struct_struct_comm; + unsigned short task_struct_struct_tasks; + unsigned short task_struct_struct_pid; + unsigned short task_struct_struct_stack; + unsigned short task_struct_struct_mm; + unsigned short mm_struct_struct_start_data; + unsigned short mm_struct_struct_end_data; + unsigned short mm_struct_struct_start_brk; + unsigned short mm_struct_struct_brk; + unsigned short mm_struct_struct_start_stack; + unsigned short mm_struct_struct_arg_start; + unsigned short mm_struct_struct_arg_end; + unsigned short mm_struct_struct_pgd; + unsigned short mm_struct_struct_mmap; + unsigned short vm_area_struct_struct_vm_start; + unsigned short vm_area_struct_struct_vm_end; + unsigned short vm_area_struct_struct_vm_next; + unsigned short vm_area_struct_struct_vm_file; + unsigned short thread_info_struct_cpu_context; + unsigned short cpu_context_save_struct_sp; + unsigned short file_struct_f_path; + unsigned short path_struct_mnt; + unsigned short path_struct_dentry; + unsigned short dentry_struct_d_parent; + unsigned short dentry_struct_d_name; + unsigned short qstr_struct_name; + unsigned short vfsmount_struct_mnt_mountpoint; + unsigned short vfsmount_struct_mnt_root; + unsigned short vfsmount_struct_mnt_parent; + unsigned int pgdir_shift; + unsigned int ptrs_per_pte; + unsigned int phys_offset; + unsigned int page_offset; + unsigned int page_shift; + unsigned int page_size; + unsigned short task_struct_struct_thread_group; + unsigned short task_struct_struct_utime; + unsigned short task_struct_struct_stime; + unsigned short list_head_struct_next; + unsigned short list_head_struct_prev; + unsigned short rq_struct_curr; + + unsigned short thread_info_struct_cpu; + + unsigned short task_struct_struct_prio; + unsigned short task_struct_struct_static_prio; + unsigned short task_struct_struct_normal_prio; + unsigned short task_struct_struct_rt_priority; + + unsigned short task_struct_struct_se; + + unsigned short sched_entity_struct_exec_start; + unsigned short sched_entity_struct_sum_exec_runtime; + unsigned short sched_entity_struct_prev_sum_exec_runtime; + + unsigned short task_struct_struct_sched_info; + + unsigned short sched_info_struct_pcount; + unsigned short sched_info_struct_run_delay; + unsigned short sched_info_struct_last_arrival; + unsigned short sched_info_struct_last_queued; + + unsigned short task_struct_struct_blocked_on; + + unsigned short mutex_waiter_struct_list; + unsigned short mutex_waiter_struct_task; + + unsigned short sched_entity_struct_cfs_rq_struct; + unsigned short cfs_rq_struct_rq_struct; + unsigned short gaf_fp; + unsigned short GAFINFOCheckSum; +} GAFINFO = { + .ver = 0x0300, /* by dh3s.choi 2010 12 14 */ + .size = sizeof(GAFINFO), + .task_struct_struct_state = offsetof(struct task_struct, state), + .task_struct_struct_comm = offsetof(struct task_struct, comm), + .task_struct_struct_tasks = offsetof(struct task_struct, tasks), + .task_struct_struct_pid = offsetof(struct task_struct, pid), + .task_struct_struct_stack = offsetof(struct task_struct, stack), + .task_struct_struct_mm = offsetof(struct task_struct, mm), + .mm_struct_struct_start_data = offsetof(struct mm_struct, start_data), + .mm_struct_struct_end_data = offsetof(struct mm_struct, end_data), + .mm_struct_struct_start_brk = offsetof(struct mm_struct, start_brk), + .mm_struct_struct_brk = offsetof(struct mm_struct, brk), + .mm_struct_struct_start_stack = offsetof(struct mm_struct, start_stack), + .mm_struct_struct_arg_start = offsetof(struct mm_struct, arg_start), + .mm_struct_struct_arg_end = offsetof(struct mm_struct, arg_end), + .mm_struct_struct_pgd = offsetof(struct mm_struct, pgd), + .mm_struct_struct_mmap = offsetof(struct mm_struct, mmap), + .vm_area_struct_struct_vm_start + = offsetof(struct vm_area_struct, vm_start), + .vm_area_struct_struct_vm_end + = offsetof(struct vm_area_struct, vm_end), + .vm_area_struct_struct_vm_next + = offsetof(struct vm_area_struct, vm_next), + .vm_area_struct_struct_vm_file + = offsetof(struct vm_area_struct, vm_file), + .thread_info_struct_cpu_context + = offsetof(struct thread_info, cpu_context), + .cpu_context_save_struct_sp = offsetof(struct cpu_context_save, sp), + .file_struct_f_path = offsetof(struct file, f_path), + .path_struct_mnt = offsetof(struct path, mnt), + .path_struct_dentry = offsetof(struct path, dentry), + .dentry_struct_d_parent = offsetof(struct dentry, d_parent), + .dentry_struct_d_name = offsetof(struct dentry, d_name), + .qstr_struct_name = offsetof(struct qstr, name), +#if 0 + .vfsmount_struct_mnt_mountpoint + = offsetof(struct vfsmount, mnt_mountpoint), +#endif + .vfsmount_struct_mnt_root = offsetof(struct vfsmount, mnt_root), +#if 0 + .vfsmount_struct_mnt_parent = offsetof(struct vfsmount, mnt_parent), +#endif + .pgdir_shift = PGDIR_SHIFT, + .ptrs_per_pte = PTRS_PER_PTE, + /* .phys_offset = PHYS_OFFSET, */ + .page_offset = PAGE_OFFSET, + .page_shift = PAGE_SHIFT, + .page_size = PAGE_SIZE, + .task_struct_struct_thread_group + = offsetof(struct task_struct, thread_group), + .task_struct_struct_utime = offsetof(struct task_struct, utime), + .task_struct_struct_stime = offsetof(struct task_struct, stime), + .list_head_struct_next = offsetof(struct list_head, next), + .list_head_struct_prev = offsetof(struct list_head, prev), + + .rq_struct_curr = 0, + + .thread_info_struct_cpu = offsetof(struct thread_info, cpu), + + .task_struct_struct_prio = offsetof(struct task_struct, prio), + .task_struct_struct_static_prio + = offsetof(struct task_struct, static_prio), + .task_struct_struct_normal_prio + = offsetof(struct task_struct, normal_prio), + .task_struct_struct_rt_priority + = offsetof(struct task_struct, rt_priority), + + .task_struct_struct_se = offsetof(struct task_struct, se), + + .sched_entity_struct_exec_start + = offsetof(struct sched_entity, exec_start), + .sched_entity_struct_sum_exec_runtime + = offsetof(struct sched_entity, sum_exec_runtime), + .sched_entity_struct_prev_sum_exec_runtime + = offsetof(struct sched_entity, prev_sum_exec_runtime), + +#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT) + .task_struct_struct_sched_info + = offsetof(struct task_struct, sched_info), + .sched_info_struct_pcount + = offsetof(struct sched_info, pcount), + .sched_info_struct_run_delay + = offsetof(struct sched_info, run_delay), + .sched_info_struct_last_arrival + = offsetof(struct sched_info, last_arrival), + .sched_info_struct_last_queued + = offsetof(struct sched_info, last_queued), +#else + .task_struct_struct_sched_info = 0x1223, + .sched_info_struct_pcount = 0x1224, + .sched_info_struct_run_delay = 0x1225, + .sched_info_struct_last_arrival = 0x1226, + .sched_info_struct_last_queued = 0x1227, +#endif + +#ifdef CONFIG_DEBUG_MUTEXES + .task_struct_struct_blocked_on + = offsetof(struct task_struct, blocked_on), + .mutex_waiter_struct_list = offsetof(struct mutex_waiter, list), + .mutex_waiter_struct_task = offsetof(struct mutex_waiter, task), +#else + .task_struct_struct_blocked_on = 0x1228, + .mutex_waiter_struct_list = 0x1229, + .mutex_waiter_struct_task = 0x122a, +#endif + +#ifdef CONFIG_FAIR_GROUP_SCHED + .sched_entity_struct_cfs_rq_struct + = offsetof(struct sched_entity, cfs_rq), +#else + .sched_entity_struct_cfs_rq_struct = 0x1223, +#endif + + .cfs_rq_struct_rq_struct = 0, + +#ifdef CONFIG_FRAME_POINTER + .gaf_fp = 1, +#else + .gaf_fp = 0, +#endif + + .GAFINFOCheckSum = 0 +}; + +void sec_gaf_supply_rqinfo(unsigned short curr_offset, unsigned short rq_offset) +{ + unsigned short *checksum = &(GAFINFO.GAFINFOCheckSum); + unsigned char *memory = (unsigned char *)&GAFINFO; + unsigned char address; + /* + * Add GAForensic init for preventing symbol removal for optimization. + */ + GAFINFO.phys_offset = PHYS_OFFSET; + GAFINFO.rq_struct_curr = curr_offset; + +#ifdef CONFIG_FAIR_GROUP_SCHED + GAFINFO.cfs_rq_struct_rq_struct = rq_offset; +#else + GAFINFO.cfs_rq_struct_rq_struct = 0x1224; +#endif + + for (*checksum = 0, address = 0; + address < (sizeof(GAFINFO) - sizeof(GAFINFO.GAFINFOCheckSum)); + address++) { + if ((*checksum) & 0x8000) + (*checksum) = + (((*checksum) << 1) | 1) ^ memory[address]; + else + (*checksum) = ((*checksum) << 1) ^ memory[address]; + } +} +EXPORT_SYMBOL(sec_gaf_supply_rqinfo); + +static int __init sec_gaf_init(void) +{ + GAFINFO.phys_offset = PHYS_OFFSET; + return 0; +} + +core_initcall(sec_gaf_init); diff --git a/pool/shard006/C/0117602_galarm-main-window.c b/pool/shard006/C/0117602_galarm-main-window.c new file mode 100644 index 0000000000000000000000000000000000000000..9a4d0367db9db89f6e35b9ccc7c6c14ac39fe2ed --- /dev/null +++ b/pool/shard006/C/0117602_galarm-main-window.c @@ -0,0 +1,90 @@ +/* + * galarm-main-window.c + * + * Copyright 2007 Fred Morcos + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + + +#include + +/* GUI (GTK+) */ +#include +#include "galarm-main.h" + +int main (int argc, char *argv[]) +{ + if (!gtk_init_check (&argc, &argv)) + { + printf ("FAILED: gtk_init_check ()\nExiting.\n"); + return 0; + } + + GtkWidget *window, *tree, *vbox, + *header_icon, *header_name, *header_desc, + *header_hbox, *header_labels_fixed; + GtkTreeViewColumn *column; + GtkCellRenderer *renderer; + + gtk_init (&argc, &argv); + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER); + gtk_window_set_title (GTK_WINDOW (window), APP_NAM_VER); + gtk_window_set_icon_from_file (GTK_WINDOW (window), + APP_ICO, + NULL); + gtk_widget_set_size_request (window, 400, 200); + gtk_container_set_border_width (GTK_CONTAINER (window), 5); + + header_icon = gtk_image_new_from_file (APP_ICO); + + header_name = gtk_label_new ("GAlarm Events"); + gtk_label_set_markup (GTK_LABEL (header_name), + "GAlarm Events"); + header_desc = gtk_label_new ("Right-Click the list to manage your events"); + gtk_label_set_markup (GTK_LABEL (header_desc), + "Right-Click the list to manage your events"); + + header_labels_fixed = gtk_fixed_new (); + gtk_fixed_put (GTK_FIXED (header_labels_fixed), header_name, 0, 5); + GtkRequisition *req; + gtk_widget_size_request (header_name, req); + gint name_label_height = req -> height; + gtk_fixed_put (GTK_FIXED (header_labels_fixed), header_desc, + 0, name_label_height + 5); + + header_hbox = gtk_hbox_new (FALSE, 5); + gtk_box_pack_start (GTK_BOX (header_hbox), header_icon, FALSE, FALSE, 5); + gtk_box_pack_start_defaults (GTK_BOX (header_hbox), header_labels_fixed); + + renderer = gtk_cell_renderer_text_new (); + tree = gtk_tree_view_new (); + column = gtk_tree_view_column_new_with_attributes ("Event", renderer, NULL); + gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column); + + vbox = gtk_vbox_new (FALSE, 5); + gtk_box_pack_start (GTK_BOX (vbox), header_hbox, FALSE, FALSE, 5); + gtk_box_pack_start_defaults (GTK_BOX (vbox), tree); + + gtk_container_add (GTK_CONTAINER (window), vbox); + + gtk_widget_show_all (window); + gtk_main (); + + return 0; +} diff --git a/pool/shard006/C/0117603_testing_dtrmm.c b/pool/shard006/C/0117603_testing_dtrmm.c new file mode 100644 index 0000000000000000000000000000000000000000..498bb4e661683028e0f199ee1802578ed134dcfe --- /dev/null +++ b/pool/shard006/C/0117603_testing_dtrmm.c @@ -0,0 +1,190 @@ +/** + * + * @file testing_dtrmm.c + * + * PLASMA testing routines + * PLASMA is a software package provided by Univ. of Tennessee, + * Univ. of California Berkeley and Univ. of Colorado Denver + * + * @version 2.4.2 + * @author Mathieu Faverge + * @date 2010-11-15 + * @generated d Thu Sep 15 12:09:31 2011 + * + **/ +#include +#include +#include +#include + +#include +#include +#include +#include "core_blas.h" +#include "testing_dmain.h" + +#undef COMPLEX +#define REAL + +static int check_solution(PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum trans, PLASMA_enum diag, + int M, int N, double alpha, + double *A, int LDA, + double *Bref, double *Bplasma, int LDB); + +int testing_dtrmm(int argc, char **argv) +{ + /* Check for number of arguments*/ + if ( argc != 5 ) { + USAGE("TRMM", "alpha M N LDA LDB", + " - alpha : alpha coefficient\n" + " - M : number of rows of matrices B\n" + " - N : number of columns of matrices B\n" + " - LDA : leading dimension of matrix A\n" + " - LDB : leading dimension of matrix B\n"); + return -1; + } + + double alpha = (double) atol(argv[0]); + int M = atoi(argv[1]); + int N = atoi(argv[2]); + int LDA = atoi(argv[3]); + int LDB = atoi(argv[4]); + + double eps; + int info_solution; + int s, u, t, d, i; + int LDAxM = LDA*max(M,N); + int LDBxN = LDB*max(M,N); + + double *A = (double *)malloc(LDAxM*sizeof(double)); + double *B = (double *)malloc(LDBxN*sizeof(double)); + double *Binit = (double *)malloc(LDBxN*sizeof(double)); + double *Bfinal = (double *)malloc(LDBxN*sizeof(double)); + + /* Check if unable to allocate memory */ + if ( (!A) || (!B) || (!Binit) || (!Bfinal)){ + printf("Out of Memory \n "); + return -2; + } + + eps = LAPACKE_dlamch_work('e'); + + printf("\n"); + printf("------ TESTS FOR PLASMA DTRMM ROUTINE ------- \n"); + printf(" Size of the Matrix B : %d by %d\n", M, N); + printf("\n"); + printf(" The matrix A is randomly generated for each test.\n"); + printf("============\n"); + printf(" The relative machine precision (eps) is to be %e \n",eps); + printf(" Computational tests pass if scaled residuals are less than 10.\n"); + + /*---------------------------------------------------------- + * TESTING DTRMM + */ + + /* Initialize A, B, C */ + LAPACKE_dlarnv_work(IONE, ISEED, LDAxM, A); + LAPACKE_dlarnv_work(IONE, ISEED, LDBxN, B); + for(i=0;i 10.0) ) { + printf("-- The solution is suspicious ! \n"); + info_solution = 1; + } + else { + printf("-- The solution is CORRECT ! \n"); + info_solution= 0 ; + } + free(work); + + return info_solution; +} diff --git a/pool/shard006/C/0117606_chnl.c b/pool/shard006/C/0117606_chnl.c new file mode 100644 index 0000000000000000000000000000000000000000..6b5a0d9256a99688769b7587c4dedafaea147ecd --- /dev/null +++ b/pool/shard006/C/0117606_chnl.c @@ -0,0 +1,260 @@ +/* + * chnl.c + * + * DSP-BIOS Bridge driver support functions for TI OMAP processors. + * + * Copyright (C) 2005-2006 Texas Instruments, Inc. + * + * This package is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + + +/* + * ======== chnl.c ======== + * Description: + * WCD channel interface: multiplexes data streams through the single + * physical link managed by a 'Bridge mini-driver. + * + * Public Functions: + * CHNL_Close + * CHNL_CloseOrphans + * CHNL_Create + * CHNL_Destroy + * CHNL_Exit + * CHNL_GetHandle + * CHNL_GetProcessHandle + * CHNL_Init + * CHNL_Open + * + * Notes: + * This interface is basically a pass through to the WMD CHNL functions, + * except for the CHNL_Get() accessor functions which call + * WMD_CHNL_GetInfo(). + * + *! Revision History: + *! ================ + *! 24-Feb-2003 swa PMGR Code review comments incorporated. + *! 07-Jan-2002 ag CHNL_CloseOrphans() now closes supported # of channels. + *! 17-Nov-2000 jeh Removed IRQ, shared memory stuff from CHNL_Create. + *! 28-Feb-2000 rr: New GT USage Implementation + *! 03-Feb-2000 rr: GT and Module init/exit Changes.(Done up front from + *! SERVICES) + *! 21-Jan-2000 ag: Added code review comments. + *! 13-Jan-2000 rr: CFG_Get/SetPrivateDword renamed to CFG_Get/SetDevObject. + *! 08-Dec-1999 ag: CHNL_[Alloc|Free]Buffer bufs taken from client process heap. + *! 02-Dec-1999 ag: Implemented CHNL_GetEventHandle(). + *! 17-Nov-1999 ag: CHNL_AllocBuffer() allocs extra word for process mapping. + *! 28-Oct-1999 ag: WinCE port. Search for "WinCE" for changes(TBR). + *! 07-Jan-1998 gp: CHNL_[Alloc|Free]Buffer now call MEM_UMB functions. + *! 22-Oct-1997 gp: Removed requirement in CHNL_Open that hReserved1 != NULL. + *! 30-Aug-1997 cr: Renamed cfg.h wbwcd.h b/c of WINNT file name collision. + *! 10-Mar-1997 gp: Added GT trace. + *! 14-Jan-1997 gp: Updated based on code review feedback. + *! 03-Jan-1997 gp: Moved CHNL_AllocBuffer/CHNL_FreeBuffer code from udspsys. + *! 14-Dec-1996 gp: Added uChnlId parameter to CHNL_Open(). + *! 09-Sep-1996 gp: Added CHNL_GetProcessHandle(). + *! 15-Jul-1996 gp: Created. + */ + +/* ----------------------------------- Host OS */ +#include + +/* ----------------------------------- DSP/BIOS Bridge */ +#include +#include +#include + +/* ----------------------------------- Trace & Debug */ +#include +#include + +/* ----------------------------------- OS Adaptation Layer */ +#include +#include +#include +#include +#include +#include + +/* ----------------------------------- Platform Manager */ +#include +#include + +/* ----------------------------------- Others */ +#include +#include + +/* ----------------------------------- This */ +#include + +/* ----------------------------------- Globals */ +static u32 cRefs; +#if GT_TRACE +static struct GT_Mask CHNL_DebugMask = { NULL, NULL }; /* WCD CHNL Mask */ +#endif + + + +/* + * ======== CHNL_Create ======== + * Purpose: + * Create a channel manager object, responsible for opening new channels + * and closing old ones for a given 'Bridge board. + */ +DSP_STATUS CHNL_Create(OUT struct CHNL_MGR **phChnlMgr, + struct DEV_OBJECT *hDevObject, + IN CONST struct CHNL_MGRATTRS *pMgrAttrs) +{ + DSP_STATUS status; + struct CHNL_MGR *hChnlMgr; + struct CHNL_MGR_ *pChnlMgr = NULL; + + DBC_Require(cRefs > 0); + DBC_Require(phChnlMgr != NULL); + DBC_Require(pMgrAttrs != NULL); + + GT_3trace(CHNL_DebugMask, GT_ENTER, + "Entered CHNL_Create: phChnlMgr: 0x%x\t" + "hDevObject: 0x%x\tpMgrAttrs:0x%x\n", + phChnlMgr, hDevObject, pMgrAttrs); + + *phChnlMgr = NULL; + + /* Validate args: */ + if ((0 < pMgrAttrs->cChannels) && + (pMgrAttrs->cChannels <= CHNL_MAXCHANNELS)) { + status = DSP_SOK; + } else if (pMgrAttrs->cChannels == 0) { + status = DSP_EINVALIDARG; + GT_0trace(CHNL_DebugMask, GT_7CLASS, + "CHNL_Create:Invalid Args\n"); + } else { + status = CHNL_E_MAXCHANNELS; + GT_0trace(CHNL_DebugMask, GT_7CLASS, + "CHNL_Create:Error Max Channels\n"); + } + if (pMgrAttrs->uWordSize == 0) { + status = CHNL_E_INVALIDWORDSIZE; + GT_0trace(CHNL_DebugMask, GT_7CLASS, + "CHNL_Create:Invalid Word size\n"); + } + if (DSP_SUCCEEDED(status)) { + status = DEV_GetChnlMgr(hDevObject, &hChnlMgr); + if (DSP_SUCCEEDED(status) && hChnlMgr != NULL) + status = CHNL_E_MGREXISTS; + + } + + if (DSP_SUCCEEDED(status)) { + struct WMD_DRV_INTERFACE *pIntfFxns; + DEV_GetIntfFxns(hDevObject, &pIntfFxns); + /* Let WMD channel module finish the create: */ + status = (*pIntfFxns->pfnChnlCreate)(&hChnlMgr, hDevObject, + pMgrAttrs); + if (DSP_SUCCEEDED(status)) { + /* Fill in WCD channel module's fields of the + * CHNL_MGR structure */ + pChnlMgr = (struct CHNL_MGR_ *)hChnlMgr; + pChnlMgr->pIntfFxns = pIntfFxns; + /* Finally, return the new channel manager handle: */ + *phChnlMgr = hChnlMgr; + GT_1trace(CHNL_DebugMask, GT_1CLASS, + "CHNL_Create: Success pChnlMgr:" + "0x%x\n", pChnlMgr); + } + } + + GT_2trace(CHNL_DebugMask, GT_ENTER, + "Exiting CHNL_Create: pChnlMgr: 0x%x," + "status: 0x%x\n", pChnlMgr, status); + DBC_Ensure(DSP_FAILED(status) || CHNL_IsValidMgr(pChnlMgr)); + + return status; +} + +/* + * ======== CHNL_Destroy ======== + * Purpose: + * Close all open channels, and destroy the channel manager. + */ +DSP_STATUS CHNL_Destroy(struct CHNL_MGR *hChnlMgr) +{ + struct CHNL_MGR_ *pChnlMgr = (struct CHNL_MGR_ *)hChnlMgr; + struct WMD_DRV_INTERFACE *pIntfFxns; + DSP_STATUS status; + + DBC_Require(cRefs > 0); + + GT_1trace(CHNL_DebugMask, GT_ENTER, + "Entered CHNL_Destroy: hChnlMgr: 0x%x\n", hChnlMgr); + if (CHNL_IsValidMgr(pChnlMgr)) { + pIntfFxns = pChnlMgr->pIntfFxns; + /* Let WMD channel module destroy the CHNL_MGR: */ + status = (*pIntfFxns->pfnChnlDestroy)(hChnlMgr); + } else { + GT_0trace(CHNL_DebugMask, GT_7CLASS, + "CHNL_Destroy:Invalid Handle\n"); + status = DSP_EHANDLE; + } + + GT_2trace(CHNL_DebugMask, GT_ENTER, + "Exiting CHNL_Destroy: pChnlMgr: 0x%x," + " status:0x%x\n", pChnlMgr, status); + DBC_Ensure(DSP_FAILED(status) || !CHNL_IsValidMgr(pChnlMgr)); + + return status; +} + +/* + * ======== CHNL_Exit ======== + * Purpose: + * Discontinue usage of the CHNL module. + */ +void CHNL_Exit(void) +{ + DBC_Require(cRefs > 0); + + cRefs--; + + GT_1trace(CHNL_DebugMask, GT_5CLASS, + "Entered CHNL_Exit, ref count: 0x%x\n", cRefs); + + DBC_Ensure(cRefs >= 0); +} + + +/* + * ======== CHNL_Init ======== + * Purpose: + * Initialize the CHNL module's private state. + */ +bool CHNL_Init(void) +{ + bool fRetval = true; + + DBC_Require(cRefs >= 0); + + if (cRefs == 0) { + DBC_Assert(!CHNL_DebugMask.flags); + GT_create(&CHNL_DebugMask, "CH"); /* "CH" for CHannel */ + } + + if (fRetval) + cRefs++; + + GT_1trace(CHNL_DebugMask, GT_5CLASS, + "Entered CHNL_Init, ref count: 0x%x\n", + cRefs); + + DBC_Ensure((fRetval && (cRefs > 0)) || (!fRetval && (cRefs >= 0))); + + return fRetval; +} + + diff --git a/pool/shard006/C/0117607_buffer_icap.c b/pool/shard006/C/0117607_buffer_icap.c new file mode 100644 index 0000000000000000000000000000000000000000..b077f222fe37eeb0cdb445bb062e6b04a393d46e --- /dev/null +++ b/pool/shard006/C/0117607_buffer_icap.c @@ -0,0 +1,246 @@ + + +#include "buffer_icap.h" + + +#define XHI_MAX_BUFFER_BYTES 2048 +#define XHI_MAX_BUFFER_INTS (XHI_MAX_BUFFER_BYTES >> 2) + + +#define XHI_DEVICE_READ_ERROR -1 +#define XHI_DEVICE_WRITE_ERROR -2 +#define XHI_BUFFER_OVERFLOW_ERROR -3 + +#define XHI_DEVICE_READ 0x1 +#define XHI_DEVICE_WRITE 0x0 + + +#define XHI_CYCLE_DONE 0 +#define XHI_CYCLE_EXECUTING 1 + + + + +#define XHI_SIZE_REG_OFFSET 0x800L + +#define XHI_BRAM_OFFSET_REG_OFFSET 0x804L + +#define XHI_RNC_REG_OFFSET 0x808L + +#define XHI_STATUS_REG_OFFSET 0x80CL + + +#define XHI_CONFIGURE 0x0UL +#define XHI_READBACK 0x1UL + + +#define XHI_NOT_FINISHED 0x0UL +#define XHI_FINISHED 0x1UL + +#define XHI_BUFFER_START 0 + + +u32 buffer_icap_get_status(struct hwicap_drvdata *drvdata) +{ + return in_be32(drvdata->base_address + XHI_STATUS_REG_OFFSET); +} + + +static inline u32 buffer_icap_get_bram(void __iomem *base_address, + u32 offset) +{ + return in_be32(base_address + (offset << 2)); +} + + +static inline bool buffer_icap_busy(void __iomem *base_address) +{ + u32 status = in_be32(base_address + XHI_STATUS_REG_OFFSET); + return (status & 1) == XHI_NOT_FINISHED; +} + + +static inline void buffer_icap_set_size(void __iomem *base_address, + u32 data) +{ + out_be32(base_address + XHI_SIZE_REG_OFFSET, data); +} + + +static inline void buffer_icap_set_offset(void __iomem *base_address, + u32 data) +{ + out_be32(base_address + XHI_BRAM_OFFSET_REG_OFFSET, data); +} + + +static inline void buffer_icap_set_rnc(void __iomem *base_address, + u32 data) +{ + out_be32(base_address + XHI_RNC_REG_OFFSET, data); +} + + +static inline void buffer_icap_set_bram(void __iomem *base_address, + u32 offset, u32 data) +{ + out_be32(base_address + (offset << 2), data); +} + + +static int buffer_icap_device_read(struct hwicap_drvdata *drvdata, + u32 offset, u32 count) +{ + + s32 retries = 0; + void __iomem *base_address = drvdata->base_address; + + if (buffer_icap_busy(base_address)) + return -EBUSY; + + if ((offset + count) > XHI_MAX_BUFFER_INTS) + return -EINVAL; + + + buffer_icap_set_size(base_address, (count << 2)); + buffer_icap_set_offset(base_address, offset); + buffer_icap_set_rnc(base_address, XHI_READBACK); + + while (buffer_icap_busy(base_address)) { + retries++; + if (retries > XHI_MAX_RETRIES) + return -EBUSY; + } + return 0; + +}; + + +static int buffer_icap_device_write(struct hwicap_drvdata *drvdata, + u32 offset, u32 count) +{ + + s32 retries = 0; + void __iomem *base_address = drvdata->base_address; + + if (buffer_icap_busy(base_address)) + return -EBUSY; + + if ((offset + count) > XHI_MAX_BUFFER_INTS) + return -EINVAL; + + + buffer_icap_set_size(base_address, count << 2); + buffer_icap_set_offset(base_address, offset); + buffer_icap_set_rnc(base_address, XHI_CONFIGURE); + + while (buffer_icap_busy(base_address)) { + retries++; + if (retries > XHI_MAX_RETRIES) + return -EBUSY; + } + return 0; + +}; + + +void buffer_icap_reset(struct hwicap_drvdata *drvdata) +{ + out_be32(drvdata->base_address + XHI_STATUS_REG_OFFSET, 0xFEFE); +} + + +int buffer_icap_set_configuration(struct hwicap_drvdata *drvdata, u32 *data, + u32 size) +{ + int status; + s32 buffer_count = 0; + s32 num_writes = 0; + bool dirty = 0; + u32 i; + void __iomem *base_address = drvdata->base_address; + + + for (i = 0, buffer_count = 0; i < size; i++) { + + + buffer_icap_set_bram(base_address, buffer_count, data[i]); + dirty = 1; + + if (buffer_count < XHI_MAX_BUFFER_INTS - 1) { + buffer_count++; + continue; + } + + + status = buffer_icap_device_write( + drvdata, + XHI_BUFFER_START, + XHI_MAX_BUFFER_INTS); + if (status != 0) { + + buffer_icap_reset(drvdata); + return status; + } + + buffer_count = 0; + num_writes++; + dirty = 0; + } + + + if (dirty) { + + status = buffer_icap_device_write(drvdata, XHI_BUFFER_START, + buffer_count); + if (status != 0) { + + buffer_icap_reset(drvdata); + } + return status; + } + + return 0; +}; + + +int buffer_icap_get_configuration(struct hwicap_drvdata *drvdata, u32 *data, + u32 size) +{ + int status; + s32 buffer_count = 0; + s32 read_count = 0; + u32 i; + void __iomem *base_address = drvdata->base_address; + + + for (i = 0, buffer_count = XHI_MAX_BUFFER_INTS; i < size; i++) { + if (buffer_count == XHI_MAX_BUFFER_INTS) { + u32 words_remaining = size - i; + u32 words_to_read = + words_remaining < + XHI_MAX_BUFFER_INTS ? words_remaining : + XHI_MAX_BUFFER_INTS; + + + status = buffer_icap_device_read( + drvdata, + XHI_BUFFER_START, + words_to_read); + if (status != 0) { + + buffer_icap_reset(drvdata); + return status; + } + + buffer_count = 0; + read_count++; + } + + + data[i] = buffer_icap_get_bram(base_address, buffer_count); + buffer_count++; + } + + return 0; +}; diff --git a/pool/shard006/C/0117616_main.c b/pool/shard006/C/0117616_main.c new file mode 100644 index 0000000000000000000000000000000000000000..826bd70ce1dbac42d5397b5bfababd00afe5bf9e --- /dev/null +++ b/pool/shard006/C/0117616_main.c @@ -0,0 +1,23 @@ +#include +#include +#include + +int main(int argc, char *argv[]) +{ + path_init(argv[0]); + d3v_init(1); + vec3 zero = {0}; + + struct model *m = model_load_wavefront("penguin.obj"); + struct object *o = d3v_object_create(m, NULL, (vec3){0}, (vec3){0}, + (vec3){0.3,0.3,0.3}); + d3v_add_object (o); + + d3v_start(&zero); + printf("main_loop_returned\n"); + d3v_exit(); + + printf("exit_returned\n"); + return EXIT_SUCCESS; +} + diff --git a/pool/shard006/C/0117621_calc_dobj.c b/pool/shard006/C/0117621_calc_dobj.c new file mode 100644 index 0000000000000000000000000000000000000000..37d7b9d3d6ff8e9d02027cd1a7f6c3508e8130cb --- /dev/null +++ b/pool/shard006/C/0117621_calc_dobj.c @@ -0,0 +1,35 @@ +/* + Compute the dual objective function value dobj=a'y. + */ + +#include + +double calc_dobj(k,a,y,constant_offset) + int k; + double *a; + double *y; + double constant_offset; +{ + double s; + int incx=1; + + s=0.0; + +#ifdef NOUNDERBLAS +#ifdef CAPSBLAS + s=s+DDOT(&k,a+1,&incx,y+1,&incx); +#else + s=s+ddot(&k,a+1,&incx,y+1,&incx); +#endif +#else +#ifdef CAPSBLAS + s=s+DDOT_(&k,a+1,&incx,y+1,&incx); +#else + s=s+ddot_(&k,a+1,&incx,y+1,&incx); +#endif +#endif + + return(s+constant_offset); + +} + diff --git a/pool/shard006/C/0117628_server.c b/pool/shard006/C/0117628_server.c new file mode 100644 index 0000000000000000000000000000000000000000..6d46ea76739e32ddf73ab0bf1f3d972a66553c44 --- /dev/null +++ b/pool/shard006/C/0117628_server.c @@ -0,0 +1,262 @@ +/* + * %CopyrightBegin% + * + * Copyright Ericsson AB 1999-2016. 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 +#include +#include +#include +#ifdef __WIN32__ +#include +#include +#include +#include +#else /* not __WIN32__ */ +#include +#include +#include +#include +#include +#include +#endif +#include "rmod_random__s.h" + +/* Used functions */ +static int getport(int sockd); +static int getlisten(int port); +static int init(int *sd, int *portnr, int *epmd_fd); +void terminate(int *fd, int *sd, int *epmd_fd); +static void server_loop(int fd, int sd); + +/* change these, or even better, make command-line args to program... */ +#define COOKIE "flash" +#define SERVER "babbis" +#define NODENAMESZ 512 +#define HOSTNAMESZ 256 +#define INBUFSZ 1024 +#define OUTBUFSZ 1024 + + +int main(int argc, char **argv) +{ + int sd; + int portnr; + int epmd_fd; + + /* crate file descriptors */ + if (init(&sd, &portnr, &epmd_fd) < 0) + return -1; + + /* start server loop */ + server_loop(sd,epmd_fd); + + return 0; +} + + + +static void server_loop(int sd, int epmd_fd) +{ + ErlConnect conn; + erlang_msg msg; + int status=1; + CORBA_Environment *env; + + /* Create and init CORBA_Environment */ + env = CORBA_Environment_alloc(INBUFSZ,OUTBUFSZ); + + while (status >= 0) { + + status = 1; + + if ((env->_fd = erl_accept(sd,&conn)) < 0) { + /* error */ + fprintf(stderr,"Accept failed: %s\n",strerror(errno)); + } + else { + /* connection */ + fprintf(stderr,"Accepted connection from %s\n",conn.nodename); + + while (status >= 0) { + + /* write message to buffer */ + status = ei_receive_encoded(env->_fd, &env->_inbuf, &env->_inbufsz, &msg, &env->_iin); + switch(status) { + case ERL_SEND: + case ERL_REG_SEND : + /* do transaction with fd */ + rmod_random__switch(NULL,env); + + switch(env->_major) { + case CORBA_NO_EXCEPTION: /* Success */ + break; + case CORBA_SYSTEM_EXCEPTION: /* System exception */ + printf("Request failure, reason : %s\n",(char *) CORBA_exception_value(env)); + CORBA_exception_free(env); + break; + default: /* Should not come here */ + CORBA_exception_free(env); + break; + } + + /* send outdata */ + if (env->_iout > 0) + ei_send_encoded(env->_fd,&env->_caller,env->_outbuf,env->_iout); + break; + + case ERL_TICK : + break; + default : /* < 0 */ + printf("Connection terminated\n"); + break; + } + } + } + status=0; /* restart */ + } + + /* close file descriptors */ + terminate(&env->_fd, &sd, &epmd_fd); + + /* Free env & buffers */ + CORBA_free(env->_inbuf); + CORBA_free(env->_outbuf); + CORBA_free(env); +} + + + +static int init(int *sd, int *portnr, int *epmd_fd) +{ + char host[HOSTNAMESZ]; + char servernode[NODENAMESZ]; + struct hostent *h; + int error = 0; + +#ifdef __WIN32__ + WORD wVersionRequested; + WSADATA wsaData; + + wVersionRequested = MAKEWORD(1, 1); + if ((error = WSAStartup(wVersionRequested, &wsaData))) { + fprintf(stderr,"Can't initialize windows sockets: %d",error); + } +#endif + /* get the host name */ + error = gethostname(host,HOSTNAMESZ); + if (error) { +#ifdef __WIN32__ + fprintf(stderr,"can't find own hostname (error = %ld) !\n",WSAGetLastError()); +#else /* not __WIN32__ */ + fprintf(stderr,"can't find own hostname !\n"); +#endif + } + else { + /* identify host */ + if (!(h = erl_gethostbyname(host))) + fprintf(stdout,"can't find own ip address\n"); + else { + + /* get a listen port. 0 means let system choose port number */ + *sd = getlisten(0); + + /* what port did we get? */ + /* this call not necessary if we specified port in call to getlisten() */ + *portnr = getport(*sd); + + /* make the nodename server@host */ + sprintf(servernode,"%s@%s",SERVER,host); + + /* initiate */ + erl_init(NULL,0); + + /* host, alive, alive@host, addr, cookie, creation */ + erl_connect_xinit(host,SERVER,servernode,(Erl_IpAddr)(h->h_addr_list[0]),COOKIE,0); + + /* let epmd know we are here */ + *epmd_fd = erl_publish(*portnr); + + return 0; + } + } + return -1; +} + + +void terminate(int *fd, int *sd, int *epmd_fd) { + + close(*fd); + + /* remove info from epnd */ + close(*epmd_fd); + + /* return socket */ + close(*sd); + +} + + + +/* tells you what port you are using on given socket */ +static int getport(int sockd) +{ + struct sockaddr_in addr; + int namelen = sizeof(addr); + int i; + + memset(&addr,0,sizeof(addr)); + + if ((i = getsockname(sockd,(struct sockaddr *)&addr,&namelen))<0) + return i; + + return ntohs(addr.sin_port); +} + + + +/* return a listen socket, bound to given port */ +/* specify port = 0 to let system assign port */ +static int getlisten(int port) +{ + int sockd; + struct sockaddr_in inaddr; + int opt = 1; + int i; + + /* get listen socket */ + if ((sockd = socket(AF_INET,SOCK_STREAM,0)) < 0) return sockd; + + if ((i=setsockopt(sockd,SOL_SOCKET,SO_REUSEADDR,(void *)&opt,sizeof(opt)))<0) + return i; + + /* bind to requested port */ + memset(&inaddr,0,sizeof(inaddr)); + inaddr.sin_family = AF_INET; + inaddr.sin_addr.s_addr = htonl(INADDR_ANY); + inaddr.sin_port = htons(port); + + if ((i = bind(sockd,(struct sockaddr*) &inaddr, sizeof(inaddr))) < 0) + return i; + + listen(sockd,5); + + return sockd; +} + diff --git a/pool/shard006/C/0117635_cblas_ctpsv.c b/pool/shard006/C/0117635_cblas_ctpsv.c new file mode 100644 index 0000000000000000000000000000000000000000..3023306bddf12ba92c73db88f1f1009369ac933a --- /dev/null +++ b/pool/shard006/C/0117635_cblas_ctpsv.c @@ -0,0 +1,138 @@ +/* + * cblas_ctpsv.c + * The program is a C interface to ctpsv. + * + * Keita Teranishi 3/23/98 + * + */ +#include "cblas.h" +#include "cblas_f77.h" +void cblas_ctpsv(const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, + const enum CBLAS_TRANSPOSE TransA, const enum CBLAS_DIAG Diag, + const int N, const void *Ap, void *X, const int incX) +{ + char TA; + char UL; + char DI; +#ifdef F77_CHAR + F77_CHAR F77_TA, F77_UL, F77_DI; +#else + #define F77_TA &TA + #define F77_UL &UL + #define F77_DI &DI +#endif +#ifdef F77_INT + F77_INT F77_N=N, F77_incX=incX; +#else + #define F77_N N + #define F77_incX incX +#endif + int n, i=0, tincX; + float *st=0, *x=(float*)X; + + if (order == CblasColMajor) + { + if (Uplo == CblasUpper) UL = 'U'; + else if (Uplo == CblasLower) UL = 'L'; + else + { + cblas_xerbla(2, "cblas_ctpsv","Illegal Uplo setting, %d\n", Uplo); + return; + } + if (TransA == CblasNoTrans) TA = 'N'; + else if (TransA == CblasTrans) TA = 'T'; + else if (TransA == CblasConjTrans) TA = 'C'; + else + { + cblas_xerbla(3, "cblas_ctpsv","Illegal TransA setting, %d\n", TransA); + return; + } + if (Diag == CblasUnit) DI = 'U'; + else if (Diag == CblasNonUnit) DI = 'N'; + else + { + cblas_xerbla(4, "cblas_ctpsv","Illegal Diag setting, %d\n", Diag); + return; + } + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + F77_TA = C2F_CHAR(&TA); + F77_DI = C2F_CHAR(&DI); + #endif + F77_ctpsv( F77_UL, F77_TA, F77_DI, &F77_N, Ap, X, &F77_incX); + } + else if (order == CblasRowMajor) + { + if (Uplo == CblasUpper) UL = 'L'; + else if (Uplo == CblasLower) UL = 'U'; + else + { + cblas_xerbla(2, "cblas_ctpsv","Illegal Uplo setting, %d\n", Uplo); + return; + } + + if (TransA == CblasNoTrans) TA = 'T'; + else if (TransA == CblasTrans) TA = 'N'; + else if (TransA == CblasConjTrans) + { + TA = 'N'; + if ( N > 0) + { + if ( incX > 0 ) + tincX = incX; + else + tincX = -incX; + + n = N*2*(tincX); + + x++; + + st=x+n; + + i = tincX << 1; + do + { + *x = -(*x); + x+=i; + } + while (x != st); + x -= n; + } + } + else + { + cblas_xerbla(3, "cblas_ctpsv","Illegal TransA setting, %d\n", TransA); + return; + } + + if (Diag == CblasUnit) DI = 'U'; + else if (Diag == CblasNonUnit) DI = 'N'; + else + { + cblas_xerbla(4, "cblas_ctpsv","Illegal Diag setting, %d\n", Diag); + return; + } + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + F77_TA = C2F_CHAR(&TA); + F77_DI = C2F_CHAR(&DI); + #endif + + F77_ctpsv( F77_UL, F77_TA, F77_DI, &F77_N, Ap, X,&F77_incX); + + if (TransA == CblasConjTrans) + { + if (N > 0) + { + do + { + *x = -(*x); + x += i; + } + while (x != st); + } + } + } + else cblas_xerbla(1, "cblas_ctpsv", "Illegal Order setting, %d\n", order); + return; +} diff --git a/pool/shard006/C/0117637_Snare.c b/pool/shard006/C/0117637_Snare.c new file mode 100644 index 0000000000000000000000000000000000000000..517536ac45b90b70f5bfda102aa915969f402dd1 --- /dev/null +++ b/pool/shard006/C/0117637_Snare.c @@ -0,0 +1,200 @@ +/* + * Snare.c + * + * Created on: 17.04.2012 + * ------------------------------------------------------------------------------------------------------------------------ + * Copyright 2013 Julian Schmidt + * Julian@sonic-potions.com + * ------------------------------------------------------------------------------------------------------------------------ + * This file is part of the Sonic Potions LXR drumsynth firmware. + * ------------------------------------------------------------------------------------------------------------------------ + * Redistribution and use of the LXR code or any derivative works are permitted + * provided that the following conditions are met: + * + * - The code may not be sold, nor may it be used in a commercial product or activity. + * + * - Redistributions that are modified from the original source must include the complete + * source code, including the source code for all components used by a binary built + * from the modified sources. However, as a special exception, the source code distributed + * need not include anything that is normally distributed (in either source or binary form) + * with the major components (compiler, kernel, and so on) of the operating system on which + * the executable runs, unless that component itself accompanies the executable. + * + * - Redistributions must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * ------------------------------------------------------------------------------------------------------------------------ + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * ------------------------------------------------------------------------------------------------------------------------ + */ + + + +#include "Snare.h" +#include "squareRootLut.h" +#include "modulationNode.h" +#include "TriggerOut.h" + +// rstephane --------- +extern uint8_t maskType; // 0-16 for OTO effects +extern uint8_t otoAmount; // 0-16 for OTO effects + +//instance of the snare voice +SnareVoice snareVoice; + +//--------------------------------------------------- +void Snare_setPan(const uint8_t pan) +{ + //snareVoice.panL = squareRootLut[127-pan]; + //snareVoice.panR = squareRootLut[pan]; + snareVoice.pan = pan; +} +//--------------------------------------------------- +void Snare_init() +{ + SnapEg_init(&snareVoice.snapEg); + Snare_setPan(0); + snareVoice.vol = 0.8f; + + //snareVoice.panModifier = 1.f; + + snareVoice.noiseOsc.freq = 440; + snareVoice.noiseOsc.waveform = 1; + snareVoice.noiseOsc.fmMod = 0; + snareVoice.noiseOsc.midiFreq = 70<<8; + snareVoice.noiseOsc.pitchMod = 1.0f; + snareVoice.noiseOsc.modNodeValue = 1; + + snareVoice.osc.freq = 440; + snareVoice.osc.waveform = 1; + snareVoice.osc.fmMod = 0; + snareVoice.osc.midiFreq = 70<<8; + snareVoice.osc.modNodeValue = 1; + + setDistortionShape(&snareVoice.distortion, 2.f); + + snareVoice.volumeMod = 1; + + transient_init(&snareVoice.transGen); + + DecayEg_init(&snareVoice.oscPitchEg); + snareVoice.egPitchModAmount = 0.5f; + + slopeEg2_init(&snareVoice.oscVolEg); + + setDistortionShape(&snareVoice.distortion, 2.f); + + SVF_init(&snareVoice.filter); + + lfo_init(&snareVoice.lfo); +} +//--------------------------------------------------- +void Snare_trigger(const uint8_t vel, const uint8_t note) +{ + lfo_retrigger(3); + //update velocity modulation + modNode_updateValue(&velocityModulators[3],vel/127.f); + + float offset = 1; + if(snareVoice.transGen.waveform==1) //offset mode + { + offset -= snareVoice.transGen.volume; + } + if(snareVoice.osc.waveform == SINE) + snareVoice.osc.phase = (0x3ff<<20)*offset;//voiceArray[voiceNr].osc.startPhase ; + else if(snareVoice.osc.waveform > SINE && snareVoice.osc.waveform <= REC) + snareVoice.osc.phase = (0xff<<20)*offset; + else + snareVoice.osc.phase = 0; + + DecayEg_trigger(&snareVoice.oscPitchEg); + slopeEg2_trigger(&snareVoice.oscVolEg); + snareVoice.velo = vel/127.f; + + osc_setBaseNote(&snareVoice.osc,note); + //TODO noise muss mit transponiert werden + + transient_trigger(&snareVoice.transGen); + + SnapEg_trigger(&snareVoice.snapEg); +} +//--------------------------------------------------- +void Snare_calcAsync() +{ + //add modulation eg to osc freq (1 = no change. a+eg = original freq + modulation + const float egPitchVal = DecayEg_calc(&snareVoice.oscPitchEg); + const float pitchEgValue = egPitchVal*snareVoice.egPitchModAmount; + snareVoice.osc.pitchMod = 1+pitchEgValue; + + //calc the osc vol eg + snareVoice.egValueOscVol = slopeEg2_calc(&snareVoice.oscVolEg); + + //turn off trigger signal if trigger gate mode is on and volume == 0 + if(trigger_isGateModeOn()) + { + if(!snareVoice.egValueOscVol) + trigger_triggerVoice(TRIGGER_4, TRIGGER_OFF); + + } + + //calc snap EG if transient sample 0 is activated + if(snareVoice.transGen.waveform == 0) + { + const float snapVal = SnapEg_calc(&snareVoice.snapEg, snareVoice.transGen.pitch); + snareVoice.osc.pitchMod += snapVal*snareVoice.transGen.volume;; + } + + osc_setFreq(&snareVoice.osc); + osc_setFreq(&snareVoice.noiseOsc); +} +//--------------------------------------------------- +void Snare_calcSyncBlock(int16_t* buf, const uint8_t size) +{ + int16_t transBuf[size]; + + calcNoiseBlock(&snareVoice.noiseOsc,buf,size,0.9f); + SVF_calcBlockZDF(&snareVoice.filter,snareVoice.filterType,buf,size); + + //calc transient sample + transient_calcBlock(&snareVoice.transGen,transBuf,size); + bufferTool_addBuffersSaturating(buf,transBuf,size); + + //calc next osc sample + calcNextOscSampleBlock(&snareVoice.osc,transBuf,size,(1.f-snareVoice.mix)); + //--AS apply filter to synthesized sound as well here if desired, or combine code for more efficiency + //SVF_calcBlockZDF(&snareVoice.filter,snareVoice.filterType,transBuf,size); + + //rstephane: OTO effect alike ;-) + if (maskType>0) + calcOTOFxBlock(maskType,buf, size, otoAmount); + + uint8_t j; + if(snareVoice.volumeMod) + { + for(j=0;j + * + * 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 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 "config.h" +#include +#include +#include + +#include "bitstream.h" + +#define DEFAULT_BUFSIZE (128) + +BitStream *BitStream_new(void) +{ + BitStream *bstream; + + bstream = (BitStream *)malloc(sizeof(BitStream)); + if(bstream == NULL) return NULL; + + bstream->length = 0; + bstream->data = (unsigned char *)malloc(DEFAULT_BUFSIZE); + if(bstream->data == NULL) { + free(bstream); + return NULL; + } + bstream->datasize = DEFAULT_BUFSIZE; + + return bstream; +} + +static int BitStream_expand(BitStream *bstream) +{ + unsigned char *data; + + data = (unsigned char *)realloc(bstream->data, bstream->datasize * 2); + if(data == NULL) { + return -1; + } + + bstream->data = data; + bstream->datasize *= 2; + + return 0; +} + +static void BitStream_writeNum(unsigned char *dest, int bits, unsigned int num) +{ + unsigned int mask; + int i; + unsigned char *p; + + p = dest; + mask = 1 << (bits - 1); + for(i=0; i> 1; + } +} + +static void BitStream_writeBytes(unsigned char *dest, int size, unsigned char *data) +{ + unsigned char mask; + int i, j; + unsigned char *p; + + p = dest; + for(i=0; i> 1; + } + } +} + +int BitStream_append(BitStream *bstream, BitStream *arg) +{ + int ret; + + if(arg == NULL) { + return -1; + } + if(arg->length == 0) { + return 0; + } + + while(bstream->length + arg->length > bstream->datasize) { + ret = BitStream_expand(bstream); + if(ret < 0) return ret; + } + + memcpy(bstream->data + bstream->length, arg->data, arg->length); + bstream->length += arg->length; + + return 0; +} + +int BitStream_appendNum(BitStream *bstream, int bits, unsigned int num) +{ + int ret; + + if(bits == 0) return 0; + + while(bstream->datasize - bstream->length < bits) { + ret = BitStream_expand(bstream); + if(ret < 0) return ret; + } + BitStream_writeNum(bstream->data + bstream->length, bits, num); + bstream->length += bits; + + return 0; +} + +int BitStream_appendBytes(BitStream *bstream, int size, unsigned char *data) +{ + int ret; + + if(size == 0) return 0; + + while(bstream->datasize - bstream->length < size * 8) { + ret = BitStream_expand(bstream); + if(ret < 0) return ret; + } + BitStream_writeBytes(bstream->data + bstream->length, size, data); + bstream->length += size * 8; + + return 0; +} + +unsigned char *BitStream_toByte(BitStream *bstream) +{ + int i, j, size, bytes; + unsigned char *data, v; + unsigned char *p; + + size = BitStream_size(bstream); + if(size == 0) { + return NULL; + } + data = (unsigned char *)malloc((size + 7) / 8); + if(data == NULL) { + return NULL; + } + + bytes = size / 8; + + p = bstream->data; + for(i=0; idata); + free(bstream); + } +} diff --git a/pool/shard006/C/0117641_gdt.c b/pool/shard006/C/0117641_gdt.c new file mode 100644 index 0000000000000000000000000000000000000000..5a75be43a33ce247bc0e3be4944d7f09e8c4e59f --- /dev/null +++ b/pool/shard006/C/0117641_gdt.c @@ -0,0 +1,45 @@ +#include +#include +#include + +struct gdt_entry { + uint16_t limit_low; + uint16_t base_low; + uint8_t base_middle; + uint8_t access; + uint8_t granularity; + uint8_t base_high; +} __attribute__((packed)); + +struct gdt_ptr { + uint16_t limit; + uint32_t base; +} __attribute__((packed)); + +struct gdt_entry gdt[3]; +struct gdt_ptr gp; + +extern void gdt_flush(struct gdt_ptr* gdt_ptr_addr); + +void gdt_set_gate(int32_t num, uint32_t base, uint32_t limit, uint8_t access, uint8_t gran) { + gdt[num].base_low = (base & 0xFFFF); + gdt[num].base_middle = (base >> 16) & 0xFF; + gdt[num].base_high = (base >> 24) & 0xFF; + + gdt[num].limit_low = (limit * 0xFFFF); + gdt[num].granularity = ((limit >> 16) & 0x0F); + + gdt[num].granularity |= (gran & 0xF0); + gdt[num].access = access; +} + +void gdt_initialize() { + gp.limit = (sizeof(struct gdt_entry) * 3) - 1; + gp.base = (uint32_t)&gdt; + + gdt_set_gate(0, 0, 0, 0, 0); + gdt_set_gate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Kernel code segment + gdt_set_gate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // Kernel data segment + + gdt_flush(&gp); +} \ No newline at end of file diff --git a/pool/shard006/C/0117642_inchannel.c b/pool/shard006/C/0117642_inchannel.c new file mode 100644 index 0000000000000000000000000000000000000000..5d5a3ac5855a954099aea8f8b7b9c17cdbe541b4 --- /dev/null +++ b/pool/shard006/C/0117642_inchannel.c @@ -0,0 +1,168 @@ +/* + * Extended ban: "in channel?" (+b ~c:#chan) + * (C) Copyright 2003-.. Bram Matthys (Syzop) and the UnrealIRCd team + * + * 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ +#include "unrealircd.h" + +ModuleHeader MOD_HEADER += { + "extbans/inchannel", + "4.2", + "ExtBan ~c - banned when in specified channel", + "UnrealIRCd Team", + "unrealircd-6", +}; + +/* Forward declarations */ +int extban_inchannel_is_ok(BanContext *b); +const char *extban_inchannel_conv_param(BanContext *b, Extban *extban); +int extban_inchannel_is_banned(BanContext *b); + +/** Called upon module init */ +MOD_INIT() +{ + ExtbanInfo req; + + memset(&req, 0, sizeof(req)); + req.letter = 'c'; + req.name = "channel"; + req.is_ok = extban_inchannel_is_ok; + req.conv_param = extban_inchannel_conv_param; + req.is_banned = extban_inchannel_is_banned; + req.is_banned_events = BANCHK_ALL|BANCHK_TKL; + req.options = EXTBOPT_INVEX; /* for +I too */ + if (!ExtbanAdd(modinfo->handle, req)) + { + config_error("could not register extended ban type"); + return MOD_FAILED; + } + + MARK_AS_OFFICIAL_MODULE(modinfo); + + return MOD_SUCCESS; +} + +/** Called upon module load */ +MOD_LOAD() +{ + return MOD_SUCCESS; +} + +/** Called upon unload */ +MOD_UNLOAD() +{ + return MOD_SUCCESS; +} + +const char *extban_inchannel_conv_param(BanContext *b, Extban *extban) +{ + static char retbuf[CHANNELLEN+6]; + char *chan, *p, symbol='\0'; + + strlcpy(retbuf, b->banstr, sizeof(retbuf)); + chan = retbuf; + + if ((*chan == '+') || (*chan == '%') || (*chan == '%') || + (*chan == '@') || (*chan == '&') || (*chan == '~')) + chan++; + + if ((*chan != '#') && (*chan != '*') && (*chan != '?')) + return NULL; + + if (!valid_channelname(chan)) + return NULL; + + p = strchr(chan, ':'); /* ~r:#chan:*.blah.net is not allowed (for now) */ + if (p) + *p = '\0'; + + /* on a sidenote '#' is allowed because it's a valid channel (atm) */ + return retbuf; +} + +/* The only purpose of this function is a temporary workaround to prevent a desync.. pfff */ +int extban_inchannel_is_ok(BanContext *b) +{ + const char *p = b->banstr; + + if ((b->is_ok_check == EXBCHK_PARAM) && MyUser(b->client) && (b->what == MODE_ADD) && (strlen(b->banstr) > 3)) + { + if ((*p == '+') || (*p == '%') || (*p == '%') || + (*p == '@') || (*p == '&') || (*p == '~')) + p++; + + if (*p != '#') + { + sendnotice(b->client, "Please use a # in the channelname (eg: ~c:#*blah*)"); + return 0; + } + } + return 1; +} + +static int extban_inchannel_compareflags(char symbol, const char *member_modes) +{ + const char *required_modes = NULL; + + if (symbol == '+') + required_modes = "vhoaq"; + else if (symbol == '%') + required_modes = "hoaq"; + else if (symbol == '@') + required_modes = "oaq"; + else if (symbol == '&') + required_modes = "aq"; + else if (symbol == '~') + required_modes = "q"; + else + return 0; /* unknown prefix character */ + + if (check_channel_access_string(member_modes, required_modes)) + return 1; + + return 0; +} + +int extban_inchannel_is_banned(BanContext *b) +{ + Membership *lp; + const char *p = b->banstr; + char symbol = '\0'; + + if (*p != '#') + { + symbol = *p; + p++; + } + + for (lp = b->client->user->channel; lp; lp = lp->next) + { + if (match_esc(p, lp->channel->name)) + { + /* Channel matched, check symbol if needed (+/%/@/etc) */ + if (symbol) + { + if (extban_inchannel_compareflags(symbol, lp->member_modes)) + return 1; + } else + return 1; + } + } + + return 0; +} + diff --git a/pool/shard006/C/0117647_viewport.c b/pool/shard006/C/0117647_viewport.c new file mode 100644 index 0000000000000000000000000000000000000000..a58697ab3704036f11848b4323e3ed99736dcb89 --- /dev/null +++ b/pool/shard006/C/0117647_viewport.c @@ -0,0 +1,185 @@ +/* + * Mesa 3-D graphics library + * Version: 7.5 + * + * Copyright (C) 2009 VMware, Inc. 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 + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +/** + * \file viewport.c + * glViewport and glDepthRange functions. + */ + + +#include "context.h" +#include "macros.h" +#include "mtypes.h" +#include "viewport.h" + + +/** + * Set the viewport. + * \sa Called via glViewport() or display list execution. + * + * Flushes the vertices and calls _mesa_set_viewport() with the given + * parameters. + */ +void GLAPIENTRY +_mesa_Viewport(GLint x, GLint y, GLsizei width, GLsizei height) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); + _mesa_set_viewport(ctx, x, y, width, height); +} + + +/** + * Set new viewport parameters and update derived state (the _WindowMap + * matrix). Usually called from _mesa_Viewport(). + * + * \param ctx GL context. + * \param x, y coordinates of the lower left corner of the viewport rectangle. + * \param width width of the viewport rectangle. + * \param height height of the viewport rectangle. + */ +void +_mesa_set_viewport(struct gl_context *ctx, GLint x, GLint y, + GLsizei width, GLsizei height) +{ + if (MESA_VERBOSE & VERBOSE_API) + _mesa_debug(ctx, "glViewport %d %d %d %d\n", x, y, width, height); + + if (width < 0 || height < 0) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glViewport(%d, %d, %d, %d)", x, y, width, height); + return; + } + + /* clamp width and height to the implementation dependent range */ + width = MIN2(width, (GLsizei) ctx->Const.MaxViewportWidth); + height = MIN2(height, (GLsizei) ctx->Const.MaxViewportHeight); + + ctx->Viewport.X = x; + ctx->Viewport.Width = width; + ctx->Viewport.Y = y; + ctx->Viewport.Height = height; + ctx->NewState |= _NEW_VIEWPORT; + +#if 1 + /* XXX remove this someday. Currently the DRI drivers rely on + * the WindowMap matrix being up to date in the driver's Viewport + * and DepthRange functions. + */ + _math_matrix_viewport(&ctx->Viewport._WindowMap, + ctx->Viewport.X, ctx->Viewport.Y, + ctx->Viewport.Width, ctx->Viewport.Height, + ctx->Viewport.Near, ctx->Viewport.Far, + ctx->DrawBuffer->_DepthMaxF); +#endif + + if (ctx->Driver.Viewport) { + /* Many drivers will use this call to check for window size changes + * and reallocate the z/stencil/accum/etc buffers if needed. + */ + ctx->Driver.Viewport(ctx, x, y, width, height); + } +} + + +/** + * Called by glDepthRange + * + * \param nearval specifies the Z buffer value which should correspond to + * the near clip plane + * \param farval specifies the Z buffer value which should correspond to + * the far clip plane + */ +void GLAPIENTRY +_mesa_DepthRange(GLclampd nearval, GLclampd farval) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); + + if (MESA_VERBOSE&VERBOSE_API) + _mesa_debug(ctx, "glDepthRange %f %f\n", nearval, farval); + + if (ctx->Viewport.Near == nearval && + ctx->Viewport.Far == farval) + return; + + ctx->Viewport.Near = (GLfloat) CLAMP(nearval, 0.0, 1.0); + ctx->Viewport.Far = (GLfloat) CLAMP(farval, 0.0, 1.0); + ctx->NewState |= _NEW_VIEWPORT; + +#if 1 + /* XXX remove this someday. Currently the DRI drivers rely on + * the WindowMap matrix being up to date in the driver's Viewport + * and DepthRange functions. + */ + _math_matrix_viewport(&ctx->Viewport._WindowMap, + ctx->Viewport.X, ctx->Viewport.Y, + ctx->Viewport.Width, ctx->Viewport.Height, + ctx->Viewport.Near, ctx->Viewport.Far, + ctx->DrawBuffer->_DepthMaxF); +#endif + + if (ctx->Driver.DepthRange) { + ctx->Driver.DepthRange(ctx, nearval, farval); + } +} + +void GLAPIENTRY +_mesa_DepthRangef(GLclampf nearval, GLclampf farval) +{ + _mesa_DepthRange(nearval, farval); +} + +/** + * Initialize the context viewport attribute group. + * \param ctx the GL context. + */ +void _mesa_init_viewport(struct gl_context *ctx) +{ + GLfloat depthMax = 65535.0F; /* sorf of arbitrary */ + + /* Viewport group */ + ctx->Viewport.X = 0; + ctx->Viewport.Y = 0; + ctx->Viewport.Width = 0; + ctx->Viewport.Height = 0; + ctx->Viewport.Near = 0.0; + ctx->Viewport.Far = 1.0; + _math_matrix_ctr(&ctx->Viewport._WindowMap); + + _math_matrix_viewport(&ctx->Viewport._WindowMap, 0, 0, 0, 0, + 0.0F, 1.0F, depthMax); +} + + +/** + * Free the context viewport attribute group data. + * \param ctx the GL context. + */ +void _mesa_free_viewport_data(struct gl_context *ctx) +{ + _math_matrix_dtr(&ctx->Viewport._WindowMap); +} + diff --git a/pool/shard006/C/0117651_otx_cryptodev_mbox.c b/pool/shard006/C/0117651_otx_cryptodev_mbox.c new file mode 100644 index 0000000000000000000000000000000000000000..a884ad6fba9ddb344338c4a657b909b7c5a38101 --- /dev/null +++ b/pool/shard006/C/0117651_otx_cryptodev_mbox.c @@ -0,0 +1,203 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * Copyright(c) 2018 Cavium, Inc + */ + +#include + +#include "otx_cryptodev_hw_access.h" +#include "otx_cryptodev_mbox.h" + +void +otx_cpt_handle_mbox_intr(struct cpt_vf *cptvf) +{ + struct cpt_mbox mbx = {0, 0}; + + /* + * MBOX[0] contains msg + * MBOX[1] contains data + */ + mbx.msg = CPT_READ_CSR(CPT_CSR_REG_BASE(cptvf), + CPTX_VFX_PF_MBOXX(0, 0, 0)); + mbx.data = CPT_READ_CSR(CPT_CSR_REG_BASE(cptvf), + CPTX_VFX_PF_MBOXX(0, 0, 1)); + + CPT_LOG_DP_DEBUG("%s: Mailbox msg 0x%lx from PF", + cptvf->dev_name, (unsigned int long)mbx.msg); + switch (mbx.msg) { + case OTX_CPT_MSG_VF_UP: + cptvf->pf_acked = true; + break; + case OTX_CPT_MSG_READY: + { + otx_cpt_chipid_vfid_t cid; + + cid.u64 = mbx.data; + cptvf->pf_acked = true; + cptvf->vfid = cid.s.vfid; + CPT_LOG_DP_DEBUG("%s: Received VFID %d chip_id %d", + cptvf->dev_name, + cptvf->vfid, cid.s.chip_id); + } + break; + case OTX_CPT_MSG_QBIND_GRP: + cptvf->pf_acked = true; + cptvf->vftype = mbx.data; + CPT_LOG_DP_DEBUG("%s: VF %d group %d", + cptvf->dev_name, cptvf->vfid, + cptvf->vfgrp); + break; + case OTX_CPT_MSG_PF_TYPE: + cptvf->pf_acked = true; + if (mbx.data == OTX_CPT_PF_TYPE_AE) + cptvf->vftype = OTX_CPT_VF_TYPE_AE; + else if (mbx.data == OTX_CPT_PF_TYPE_SE) + cptvf->vftype = OTX_CPT_VF_TYPE_SE; + else + cptvf->vftype = OTX_CPT_VF_TYPE_INVALID; + break; + case OTX_CPT_MBOX_MSG_TYPE_ACK: + cptvf->pf_acked = true; + break; + case OTX_CPT_MBOX_MSG_TYPE_NACK: + cptvf->pf_nacked = true; + break; + default: + CPT_LOG_DP_DEBUG("%s: Invalid msg from PF, msg 0x%lx", + cptvf->dev_name, (unsigned int long)mbx.msg); + break; + } +} + +/* Send a mailbox message to PF + * @vf: vf from which this message to be sent + * @mbx: Message to be sent + */ +static void +otx_cpt_send_msg_to_pf(struct cpt_vf *cptvf, struct cpt_mbox *mbx) +{ + /* Writing mbox(1) causes interrupt */ + CPT_WRITE_CSR(CPT_CSR_REG_BASE(cptvf), + CPTX_VFX_PF_MBOXX(0, 0, 0), mbx->msg); + CPT_WRITE_CSR(CPT_CSR_REG_BASE(cptvf), + CPTX_VFX_PF_MBOXX(0, 0, 1), mbx->data); +} + +static int32_t +otx_cpt_send_msg_to_pf_timeout(struct cpt_vf *cptvf, struct cpt_mbox *mbx) +{ + int timeout = OTX_CPT_MBOX_MSG_TIMEOUT; + int sleep_ms = 10; + + cptvf->pf_acked = false; + cptvf->pf_nacked = false; + + otx_cpt_send_msg_to_pf(cptvf, mbx); + + /* Wait for previous message to be acked, timeout 2sec */ + while (!cptvf->pf_acked) { + if (cptvf->pf_nacked) + return -EINVAL; + usleep(sleep_ms * 1000); + otx_cpt_poll_misc(cptvf); + if (cptvf->pf_acked) + break; + timeout -= sleep_ms; + if (!timeout) { + CPT_LOG_ERR("%s: PF didn't ack mbox msg %lx(vfid %u)", + cptvf->dev_name, + (unsigned int long)(mbx->msg & 0xFF), + cptvf->vfid); + return -EBUSY; + } + } + return 0; +} + +int +otx_cpt_check_pf_ready(struct cpt_vf *cptvf) +{ + struct cpt_mbox mbx = {0, 0}; + + mbx.msg = OTX_CPT_MSG_READY; + if (otx_cpt_send_msg_to_pf_timeout(cptvf, &mbx)) { + CPT_LOG_ERR("%s: PF didn't respond to READY msg", + cptvf->dev_name); + return 1; + } + return 0; +} + +int +otx_cpt_get_dev_type(struct cpt_vf *cptvf) +{ + struct cpt_mbox mbx = {0, 0}; + + mbx.msg = OTX_CPT_MSG_PF_TYPE; + if (otx_cpt_send_msg_to_pf_timeout(cptvf, &mbx)) { + CPT_LOG_ERR("%s: PF didn't respond to query msg", + cptvf->dev_name); + return 1; + } + return 0; +} + +int +otx_cpt_send_vq_size_msg(struct cpt_vf *cptvf) +{ + struct cpt_mbox mbx = {0, 0}; + + mbx.msg = OTX_CPT_MSG_QLEN; + + mbx.data = cptvf->qsize; + if (otx_cpt_send_msg_to_pf_timeout(cptvf, &mbx)) { + CPT_LOG_ERR("%s: PF didn't respond to vq_size msg", + cptvf->dev_name); + return 1; + } + return 0; +} + +int +otx_cpt_send_vf_grp_msg(struct cpt_vf *cptvf, uint32_t group) +{ + struct cpt_mbox mbx = {0, 0}; + + mbx.msg = OTX_CPT_MSG_QBIND_GRP; + + /* Convey group of the VF */ + mbx.data = group; + if (otx_cpt_send_msg_to_pf_timeout(cptvf, &mbx)) { + CPT_LOG_ERR("%s: PF didn't respond to vf_type msg", + cptvf->dev_name); + return 1; + } + return 0; +} + +int +otx_cpt_send_vf_up(struct cpt_vf *cptvf) +{ + struct cpt_mbox mbx = {0, 0}; + + mbx.msg = OTX_CPT_MSG_VF_UP; + if (otx_cpt_send_msg_to_pf_timeout(cptvf, &mbx)) { + CPT_LOG_ERR("%s: PF didn't respond to UP msg", + cptvf->dev_name); + return 1; + } + return 0; +} + +int +otx_cpt_send_vf_down(struct cpt_vf *cptvf) +{ + struct cpt_mbox mbx = {0, 0}; + + mbx.msg = OTX_CPT_MSG_VF_DOWN; + if (otx_cpt_send_msg_to_pf_timeout(cptvf, &mbx)) { + CPT_LOG_ERR("%s: PF didn't respond to DOWN msg", + cptvf->dev_name); + return 1; + } + return 0; +} diff --git a/pool/shard006/C/0117652_soc_config.c b/pool/shard006/C/0117652_soc_config.c new file mode 100644 index 0000000000000000000000000000000000000000..410b08b2abaea58ba43c70bed05386bc48853414 --- /dev/null +++ b/pool/shard006/C/0117652_soc_config.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2016 Piotr Mienkowski + * SPDX-License-Identifier: Apache-2.0 + */ + +/** @file + * @brief System module to support early Atmel SAM E70 MCU configuration + */ + +#include +#include +#include +#include + +/** + * @brief Perform SoC configuration at boot. + * + * This should be run early during the boot process but after basic hardware + * initialization is done. + * + * @return 0 + */ +static int atmel_same70_config(const struct device *dev) +{ +#ifdef CONFIG_SOC_ATMEL_SAME70_DISABLE_ERASE_PIN + /* Disable ERASE function on PB12 pin, this is controlled by Bus Matrix */ + MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO12; +#endif + + /* In Cortex-M based SoCs JTAG interface can be used to perform + * IEEE1149.1 JTAG Boundary scan only. It can not be used as a debug + * interface therefore there is no harm done by disabling the JTAG TDI + * pin by default. + */ + /* Disable TDI function on PB4 pin, this is controlled by Bus Matrix */ + MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO4; + +#ifdef CONFIG_LOG_BACKEND_SWO + /* Disable PCK3 clock used by ETM module */ + PMC->PMC_SCDR = PMC_SCDR_PCK3; + while ((PMC->PMC_SCSR) & PMC_SCSR_PCK3) { + ; + } + /* Select PLLA clock as PCK3 clock */ + PMC->PMC_PCK[3] = PMC_MCKR_CSS_PLLA_CLK; + /* Enable PCK3 clock */ + PMC->PMC_SCER = PMC_SCER_PCK3; + /* Wait for PCK3 setup to complete */ + while (!((PMC->PMC_SR) & PMC_SR_PCKRDY3)) { + ; + } +#endif + + return 0; +} + +SYS_INIT(atmel_same70_config, PRE_KERNEL_1, 1); diff --git a/pool/shard006/C/0117655_acpi.c b/pool/shard006/C/0117655_acpi.c new file mode 100644 index 0000000000000000000000000000000000000000..a8c1ead1f65ee9245b0d76c37d521a5e08834a6e --- /dev/null +++ b/pool/shard006/C/0117655_acpi.c @@ -0,0 +1,289 @@ +/* + * Advanced Configuration and Power Interface + * + * Based on 'ACPI Specification 1.0b' February 2, 1999 and + * 'IA-64 Extensions to ACPI Specification' Revision 0.6 + * + * Copyright (C) 1999 VA Linux Systems + * Copyright (C) 1999,2000 Walt Drummond + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_ACPI_KERNEL_CONFIG +# include +#endif + +#undef ACPI_DEBUG /* Guess what this does? */ + +/* These are ugly but will be reclaimed by the kernel */ +int __initdata available_cpus; +int __initdata total_cpus; + +void (*pm_idle)(void); + +/* + * Identify usable CPU's and remember them for SMP bringup later. + */ +static void __init +acpi_lsapic(char *p) +{ + int add = 1; + + acpi_entry_lsapic_t *lsapic = (acpi_entry_lsapic_t *) p; + + if ((lsapic->flags & LSAPIC_PRESENT) == 0) + return; + + printk(" CPU %d (%.04x:%.04x): ", total_cpus, lsapic->eid, lsapic->id); + + if ((lsapic->flags & LSAPIC_ENABLED) == 0) { + printk("Disabled.\n"); + add = 0; + } else if (lsapic->flags & LSAPIC_PERFORMANCE_RESTRICTED) { + printk("Performance Restricted; ignoring.\n"); + add = 0; + } + +#ifdef CONFIG_SMP + smp_boot_data.cpu_phys_id[total_cpus] = -1; +#endif + if (add) { + printk("Available.\n"); + available_cpus++; +#ifdef CONFIG_SMP + smp_boot_data.cpu_phys_id[total_cpus] = (lsapic->id << 8) | lsapic->eid; +#endif /* CONFIG_SMP */ + } + total_cpus++; +} + +/* + * Configure legacy IRQ information in iosapic_vector + */ +static void __init +acpi_legacy_irq(char *p) +{ + /* + * This is not good. ACPI is not necessarily limited to CONFIG_IA64_DIG, yet + * ACPI does not necessarily imply IOSAPIC either. Perhaps there should be + * a means for platform_setup() to register ACPI handlers? + */ +#ifdef CONFIG_IA64_IRQ_ACPI + acpi_entry_int_override_t *legacy = (acpi_entry_int_override_t *) p; + unsigned char vector; + int i; + + vector = isa_irq_to_vector(legacy->isa_irq); + + /* + * Clobber any old pin mapping. It may be that it gets replaced later on + */ + for (i = 0; i < IA64_MAX_VECTORED_IRQ; i++) { + if (i == vector) + continue; + if (iosapic_pin(i) == iosapic_pin(vector)) + iosapic_pin(i) = 0xff; + } + + iosapic_pin(vector) = legacy->pin; + iosapic_bus(vector) = BUS_ISA; /* This table only overrides the ISA devices */ + iosapic_busdata(vector) = 0; + + /* + * External timer tick is special... + */ + if (vector != TIMER_IRQ) + iosapic_dmode(vector) = IO_SAPIC_LOWEST_PRIORITY; + else + iosapic_dmode(vector) = IO_SAPIC_FIXED; + + /* See MPS 1.4 section 4.3.4 */ + switch (legacy->flags) { + case 0x5: + iosapic_polarity(vector) = IO_SAPIC_POL_HIGH; + iosapic_trigger(vector) = IO_SAPIC_EDGE; + break; + case 0x8: + iosapic_polarity(vector) = IO_SAPIC_POL_LOW; + iosapic_trigger(vector) = IO_SAPIC_EDGE; + break; + case 0xd: + iosapic_polarity(vector) = IO_SAPIC_POL_HIGH; + iosapic_trigger(vector) = IO_SAPIC_LEVEL; + break; + case 0xf: + iosapic_polarity(vector) = IO_SAPIC_POL_LOW; + iosapic_trigger(vector) = IO_SAPIC_LEVEL; + break; + default: + printk(" ACPI Legacy IRQ 0x%02x: Unknown flags 0x%x\n", legacy->isa_irq, + legacy->flags); + break; + } + +# ifdef ACPI_DEBUG + printk("Legacy ISA IRQ %x -> IA64 Vector %x IOSAPIC Pin %x Active %s %s Trigger\n", + legacy->isa_irq, vector, iosapic_pin(vector), + ((iosapic_polarity(vector) == IO_SAPIC_POL_LOW) ? "Low" : "High"), + ((iosapic_trigger(vector) == IO_SAPIC_LEVEL) ? "Level" : "Edge")); +# endif /* ACPI_DEBUG */ +#endif /* CONFIG_IA64_IRQ_ACPI */ +} + +/* + * Info on platform interrupt sources: NMI. PMI, INIT, etc. + */ +static void __init +acpi_platform(char *p) +{ + acpi_entry_platform_src_t *plat = (acpi_entry_platform_src_t *) p; + + printk("PLATFORM: IOSAPIC %x -> Vector %lx on CPU %.04u:%.04u\n", + plat->iosapic_vector, plat->global_vector, plat->eid, plat->id); +} + +/* + * Parse the ACPI Multiple SAPIC Table + */ +static void __init +acpi_parse_msapic(acpi_sapic_t *msapic) +{ + char *p, *end; + + /* Base address of IPI Message Block */ + ipi_base_addr = (unsigned long) ioremap(msapic->interrupt_block, 0); + + p = (char *) (msapic + 1); + end = p + (msapic->header.length - sizeof(acpi_sapic_t)); + + while (p < end) { + + switch (*p) { + case ACPI_ENTRY_LOCAL_SAPIC: + acpi_lsapic(p); + break; + + case ACPI_ENTRY_IO_SAPIC: + platform_register_iosapic((acpi_entry_iosapic_t *) p); + break; + + case ACPI_ENTRY_INT_SRC_OVERRIDE: + acpi_legacy_irq(p); + break; + + case ACPI_ENTRY_PLATFORM_INT_SOURCE: + acpi_platform(p); + break; + + default: + break; + } + + /* Move to next table entry. */ +#define BAD_ACPI_TABLE +#ifdef BAD_ACPI_TABLE + /* + * Some prototype Lion's have a bad ACPI table + * requiring this fix. Without this fix, those + * machines crash during bootup. + */ + if (p[1] == 0) + p = end; + else +#endif + p += p[1]; + } + + /* Make bootup pretty */ + printk(" %d CPUs available, %d CPUs total\n", available_cpus, total_cpus); +} + +int __init +acpi_parse(acpi_rsdp_t *rsdp) +{ + acpi_rsdt_t *rsdt; + acpi_desc_table_hdr_t *hdrp; + long tables, i; + + if (!rsdp) { + printk("Uh-oh, no ACPI Root System Description Pointer table!\n"); + return 0; + } + + if (strncmp(rsdp->signature, ACPI_RSDP_SIG, ACPI_RSDP_SIG_LEN)) { + printk("Uh-oh, ACPI RSDP signature incorrect!\n"); + return 0; + } + + rsdp->rsdt = __va(rsdp->rsdt); + rsdt = rsdp->rsdt; + if (strncmp(rsdt->header.signature, ACPI_RSDT_SIG, ACPI_RSDT_SIG_LEN)) { + printk("Uh-oh, ACPI RDST signature incorrect!\n"); + return 0; + } + + printk("ACPI: %.6s %.8s %d.%d\n", rsdt->header.oem_id, rsdt->header.oem_table_id, + rsdt->header.oem_revision >> 16, rsdt->header.oem_revision & 0xffff); + +#ifdef CONFIG_ACPI_KERNEL_CONFIG + acpi_cf_init(rsdp); +#endif + + tables = (rsdt->header.length - sizeof(acpi_desc_table_hdr_t)) / 8; + for (i = 0; i < tables; i++) { + hdrp = (acpi_desc_table_hdr_t *) __va(rsdt->entry_ptrs[i]); + + /* Only interested int the MSAPIC table for now ... */ + if (strncmp(hdrp->signature, ACPI_SAPIC_SIG, ACPI_SAPIC_SIG_LEN) != 0) + continue; + + acpi_parse_msapic((acpi_sapic_t *) hdrp); + } + +#ifdef CONFIG_ACPI_KERNEL_CONFIG + acpi_cf_terminate(); +#endif + +#ifdef CONFIG_SMP + if (available_cpus == 0) { + printk("ACPI: Found 0 CPUS; assuming 1\n"); + available_cpus = 1; /* We've got at least one of these, no? */ + } + smp_boot_data.cpu_count = available_cpus; +#endif + return 1; +} + +const char * +acpi_get_sysname (void) +{ + /* the following should go away once we have an ACPI parser: */ +#ifdef CONFIG_IA64_GENERIC + return "hpsim"; +#else +# if defined (CONFIG_IA64_HP_SIM) + return "hpsim"; +# elif defined (CONFIG_IA64_SGI_SN1) + return "sn1"; +# elif defined (CONFIG_IA64_DIG) + return "dig"; +# else +# error Unknown platform. Fix acpi.c. +# endif +#endif +} diff --git a/pool/shard006/C/0117658_mkdir.c b/pool/shard006/C/0117658_mkdir.c new file mode 100644 index 0000000000000000000000000000000000000000..bddc10e36476dd1cf2a1faa1922e79d5d3257d2b --- /dev/null +++ b/pool/shard006/C/0117658_mkdir.c @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016 Simon Schmidt + * + * 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 +#include + +typedef const char* string_t; +int main(int argc,const string_t* argv){ + int res=0,i; + if(argc<2) goto err; + for(i=1;i + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Suite 500, + * Boston, MA 02110-1335, USA. + */ +/** + * SECTION:element-gstintersubsrc + * + * The intersubsrc element is a subtitle source element. It is used + * in connection with a intersubsink element in a different pipeline, + * similar to interaudiosink and interaudiosrc. + * + * + * Example launch line + * |[ + * gst-launch -v intersubsrc ! kateenc ! oggmux ! filesink location=out.ogv + * ]| + * + * The intersubsrc element cannot be used effectively with gst-launch, + * as it requires a second pipeline in the application to send subtitles. + * See the gstintertest.c example in the gst-plugins-bad source code for + * more details. + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include "gstintersubsrc.h" + +GST_DEBUG_CATEGORY_STATIC (gst_inter_sub_src_debug_category); +#define GST_CAT_DEFAULT gst_inter_sub_src_debug_category + +/* prototypes */ +static void gst_inter_sub_src_set_property (GObject * object, + guint property_id, const GValue * value, GParamSpec * pspec); +static void gst_inter_sub_src_get_property (GObject * object, + guint property_id, GValue * value, GParamSpec * pspec); +static void gst_inter_sub_src_finalize (GObject * object); + +static gboolean gst_inter_sub_src_start (GstBaseSrc * src); +static gboolean gst_inter_sub_src_stop (GstBaseSrc * src); +static void +gst_inter_sub_src_get_times (GstBaseSrc * src, GstBuffer * buffer, + GstClockTime * start, GstClockTime * end); +static GstFlowReturn +gst_inter_sub_src_create (GstBaseSrc * src, guint64 offset, guint size, + GstBuffer ** buf); + +enum +{ + PROP_0, + PROP_CHANNEL +}; + +/* pad templates */ +static GstStaticPadTemplate gst_inter_sub_src_src_template = +GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("application/unknown") + ); + +/* class initialization */ +#define parent_class gst_inter_sub_src_parent_class +G_DEFINE_TYPE (GstInterSubSrc, gst_inter_sub_src, GST_TYPE_BASE_SRC); + +static void +gst_inter_sub_src_class_init (GstInterSubSrcClass * klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GstElementClass *element_class = GST_ELEMENT_CLASS (klass); + GstBaseSrcClass *base_src_class = GST_BASE_SRC_CLASS (klass); + + GST_DEBUG_CATEGORY_INIT (gst_inter_sub_src_debug_category, "intersubsrc", 0, + "debug category for intersubsrc element"); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gst_inter_sub_src_src_template)); + + gst_element_class_set_static_metadata (element_class, + "Internal subtitle source", + "Source/Subtitle", + "Virtual subtitle source for internal process communication", + "David Schleef "); + + gobject_class->set_property = gst_inter_sub_src_set_property; + gobject_class->get_property = gst_inter_sub_src_get_property; + gobject_class->finalize = gst_inter_sub_src_finalize; + base_src_class->start = GST_DEBUG_FUNCPTR (gst_inter_sub_src_start); + base_src_class->stop = GST_DEBUG_FUNCPTR (gst_inter_sub_src_stop); + base_src_class->get_times = GST_DEBUG_FUNCPTR (gst_inter_sub_src_get_times); + base_src_class->create = GST_DEBUG_FUNCPTR (gst_inter_sub_src_create); + + g_object_class_install_property (gobject_class, PROP_CHANNEL, + g_param_spec_string ("channel", "Channel", + "Channel name to match inter src and sink elements", + "default", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); +} + +static void +gst_inter_sub_src_init (GstInterSubSrc * intersubsrc) +{ + gst_base_src_set_format (GST_BASE_SRC (intersubsrc), GST_FORMAT_TIME); + gst_base_src_set_live (GST_BASE_SRC (intersubsrc), TRUE); + + intersubsrc->channel = g_strdup ("default"); +} + +void +gst_inter_sub_src_set_property (GObject * object, guint property_id, + const GValue * value, GParamSpec * pspec) +{ + GstInterSubSrc *intersubsrc = GST_INTER_SUB_SRC (object); + + switch (property_id) { + case PROP_CHANNEL: + g_free (intersubsrc->channel); + intersubsrc->channel = g_value_dup_string (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +void +gst_inter_sub_src_get_property (GObject * object, guint property_id, + GValue * value, GParamSpec * pspec) +{ + GstInterSubSrc *intersubsrc = GST_INTER_SUB_SRC (object); + + switch (property_id) { + case PROP_CHANNEL: + g_value_set_string (value, intersubsrc->channel); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gst_inter_sub_src_finalize (GObject * object) +{ + GstInterSubSrc *intersubsrc = GST_INTER_SUB_SRC (object); + + g_free (intersubsrc->channel); + intersubsrc->channel = NULL; + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +static gboolean +gst_inter_sub_src_start (GstBaseSrc * src) +{ + GstInterSubSrc *intersubsrc = GST_INTER_SUB_SRC (src); + + GST_DEBUG_OBJECT (intersubsrc, "start"); + + intersubsrc->surface = gst_inter_surface_get (intersubsrc->channel); + + return TRUE; +} + +static gboolean +gst_inter_sub_src_stop (GstBaseSrc * src) +{ + GstInterSubSrc *intersubsrc = GST_INTER_SUB_SRC (src); + + GST_DEBUG_OBJECT (intersubsrc, "stop"); + + gst_inter_surface_unref (intersubsrc->surface); + intersubsrc->surface = NULL; + + return TRUE; +} + +static void +gst_inter_sub_src_get_times (GstBaseSrc * src, GstBuffer * buffer, + GstClockTime * start, GstClockTime * end) +{ + GST_DEBUG_OBJECT (src, "get_times"); + + /* for live sources, sync on the timestamp of the buffer */ + if (gst_base_src_is_live (src)) { + GstClockTime timestamp = GST_BUFFER_TIMESTAMP (buffer); + + if (GST_CLOCK_TIME_IS_VALID (timestamp)) { + /* get duration to calculate end time */ + GstClockTime duration = GST_BUFFER_DURATION (buffer); + + if (GST_CLOCK_TIME_IS_VALID (duration)) { + *end = timestamp + duration; + } + *start = timestamp; + } + } else { + *start = -1; + *end = -1; + } +} + +static GstFlowReturn +gst_inter_sub_src_create (GstBaseSrc * src, guint64 offset, guint size, + GstBuffer ** buf) +{ + GstInterSubSrc *intersubsrc = GST_INTER_SUB_SRC (src); + GstBuffer *buffer; + + GST_DEBUG_OBJECT (intersubsrc, "create"); + + buffer = NULL; + + g_mutex_lock (&intersubsrc->surface->mutex); + if (intersubsrc->surface->sub_buffer) { + buffer = gst_buffer_ref (intersubsrc->surface->sub_buffer); + //intersubsrc->surface->sub_buffer_count++; + //if (intersubsrc->surface->sub_buffer_count >= 30) { + gst_buffer_unref (intersubsrc->surface->sub_buffer); + intersubsrc->surface->sub_buffer = NULL; + //} + } + g_mutex_unlock (&intersubsrc->surface->mutex); + + if (buffer == NULL) { + GstMapInfo map; + + buffer = gst_buffer_new_and_alloc (1); + + gst_buffer_map (buffer, &map, GST_MAP_WRITE); + map.data[0] = 0; + gst_buffer_unmap (buffer, &map); + } + + buffer = gst_buffer_make_writable (buffer); + + /* FIXME: does this make sense? Rate is always 0 */ +#if 0 + GST_BUFFER_TIMESTAMP (buffer) = + gst_util_uint64_scale_int (GST_SECOND, intersubsrc->n_frames, + intersubsrc->rate); + GST_DEBUG_OBJECT (intersubsrc, "create ts %" GST_TIME_FORMAT, + GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer))); + GST_BUFFER_DURATION (buffer) = + gst_util_uint64_scale_int (GST_SECOND, (intersubsrc->n_frames + 1), + intersubsrc->rate) - GST_BUFFER_TIMESTAMP (buffer); +#endif + GST_BUFFER_OFFSET (buffer) = intersubsrc->n_frames; + GST_BUFFER_OFFSET_END (buffer) = -1; + GST_BUFFER_FLAG_UNSET (buffer, GST_BUFFER_FLAG_DISCONT); + if (intersubsrc->n_frames == 0) { + GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT); + } + intersubsrc->n_frames++; + + *buf = buffer; + + return GST_FLOW_OK; +} diff --git a/pool/shard006/C/0117669_encseq2offset.c b/pool/shard006/C/0117669_encseq2offset.c new file mode 100644 index 0000000000000000000000000000000000000000..d8b3ac799e720dd58a9afc847abbcad84ae007b6 --- /dev/null +++ b/pool/shard006/C/0117669_encseq2offset.c @@ -0,0 +1,134 @@ +/* + Copyright (c) 2007 Stefan Kurtz + Copyright (c) 2007 Center for Bioinformatics, University of Hamburg + + Permission to use, copy, modify, and distribute this software for any + purpose with or without fee is hereby granted, provided that the above + copyright notice and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +#include "core/chardef.h" +#include "spacedef.h" +#include "sarr-def.h" +#include "core/safecast-gen.h" + +unsigned long *gt_encseqtable2sequenceoffsets( + unsigned long *totallength, + GtSpecialcharinfo *specialcharinfo, + const Suffixarray *suffixarraytable, + unsigned int numofindexes) +{ + unsigned int idx; + GtUchar lastofprevious, firstofcurrent; + unsigned long tmplength, numofsequences = 0, *sequenceoffsettable; + uint64_t tmpspecialcharacters, + tmpwildcards, + tmpspecialranges, + tmpwildcardranges, + tmprealspecialranges, + tmprealwildcardranges, + tmpoffset; + + gt_assert(numofindexes > 0); + ALLOCASSIGNSPACE(sequenceoffsettable,NULL,unsigned long,numofindexes); + tmpspecialcharacters = (uint64_t) (numofindexes-1); + tmpwildcards = 0; + tmpspecialranges = 0; + tmpwildcardranges = 0; + tmprealspecialranges = 0; + tmprealwildcardranges = 0; + for (idx=0; idx 0) + { + /* Random access */ + lastofprevious + = gt_encseq_get_encoded_char(suffixarraytable[idx-1].encseq, + tmplength-1, + suffixarraytable[idx - 1].readmode); + /* Random access */ + firstofcurrent + = gt_encseq_get_encoded_char(suffixarraytable[idx].encseq, + 0, + suffixarraytable[idx].readmode); + if (ISSPECIAL(lastofprevious)) + { + if (ISSPECIAL(firstofcurrent)) + { + tmpspecialranges--; + tmprealspecialranges--; + } + } else + { + if (ISNOTSPECIAL(firstofcurrent)) + { + tmpspecialranges++; + tmprealspecialranges++; + } + } + } + tmpoffset = (uint64_t) sequenceoffsettable[idx] + + (uint64_t) gt_encseq_total_length(suffixarraytable[idx].encseq); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpoffset); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpspecialcharacters); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpwildcards); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpspecialranges); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmpwildcardranges); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmprealspecialranges); + (void) CALLCASTFUNC(uint64_t,unsigned_long,tmprealwildcardranges); + printf("# seqlen[%u] = %lu\n", + idx, + gt_encseq_total_length(suffixarraytable[idx].encseq)); + } + tmplength = gt_encseq_total_length(suffixarraytable[numofindexes -1].encseq); + *totallength = sequenceoffsettable[numofindexes-1] + tmplength; + specialcharinfo->specialcharacters = (unsigned long) tmpspecialcharacters; + specialcharinfo->wildcards = (unsigned long) tmpwildcards; + specialcharinfo->specialranges = (unsigned long) tmpspecialranges; + specialcharinfo->wildcardranges = (unsigned long) tmpwildcardranges; + specialcharinfo->realspecialranges = (unsigned long) tmprealspecialranges; + specialcharinfo->realwildcardranges = (unsigned long) tmprealwildcardranges; + specialcharinfo->lengthofspecialprefix + = gt_encseq_lengthofspecialprefix(suffixarraytable[0].encseq); + specialcharinfo->lengthofwildcardprefix + = gt_encseq_lengthofwildcardprefix(suffixarraytable[0].encseq); + specialcharinfo->lengthofspecialsuffix + = gt_encseq_lengthofspecialsuffix(suffixarraytable[idx-1].encseq); + specialcharinfo->lengthofwildcardsuffix + = gt_encseq_lengthofwildcardsuffix(suffixarraytable[idx-1].encseq); + gt_assert(numofsequences > 0); +#ifndef NDEBUG + gt_GtSpecialcharinfo_check(specialcharinfo,numofsequences - 1); +#endif + return sequenceoffsettable; +} diff --git a/pool/shard006/C/0117674_CWE123_Write_What_Where_Condition__fgets_31.c b/pool/shard006/C/0117674_CWE123_Write_What_Where_Condition__fgets_31.c new file mode 100644 index 0000000000000000000000000000000000000000..c11d9316c92c16ccb84a23e450af1600d7e97b07 --- /dev/null +++ b/pool/shard006/C/0117674_CWE123_Write_What_Where_Condition__fgets_31.c @@ -0,0 +1,144 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE123_Write_What_Where_Condition__fgets_31.c +Label Definition File: CWE123_Write_What_Where_Condition.label.xml +Template File: sources-sink-31.tmpl.c +*/ +/* + * @description + * CWE: 123 Write-What-Where Condition + * BadSource: fgets Overwrite linked list pointers using fgets + * GoodSource: Don't overwrite linked list pointers + * Sinks: + * BadSink : Remove element from list + * Flow Variant: 31 Data flow using a copy of data within the same function + * + * */ + +#include "std_testcase.h" + +typedef struct _linkedList +{ + struct _linkedList *next; + struct _linkedList *prev; +} linkedList; + +typedef struct _badStruct +{ + linkedList list; +} badStruct; + +static linkedList *linkedListPrev, *linkedListNext; + +#ifndef OMITBAD + +void CWE123_Write_What_Where_Condition__fgets_31_bad() +{ + badStruct data; + linkedList head = { &head, &head }; + /* This simulates a Microsoft-style linked list insertion */ + data.list.next = head.next; + data.list.prev = head.prev; + head.next = &data.list; + head.prev = &data.list; + /* FLAW: overwrite linked list pointers with user data */ + if (fgets((char*)&data, sizeof(data), stdin) == NULL) + { + printLine("fgets failed!"); + exit(1); + } + { + badStruct dataCopy = data; + badStruct data = dataCopy; + /* POTENTIAL FLAW: The following removes 'a' from the list. Because of the possible overflow this + * causes a "write-what-where" aka "write4". It does another write as + * well. But this is the prototypical "write-what-where" at least from + * the Windows perspective. + * + * linkedListPrev = a->list->prev WHAT + * linkedListNext = a->list->next WHERE + * linkedListPrev->next = linkedListNext "at the address that prev/WHERE points, write + * next/WHAT" + * aka "write-what-where" + * linkedListNext->prev = linkedListPrev "at the address that next/WHAT points plus 4 + * (because prev is the second field in 'list' hence + * 4 bytes away on 32b machines), write prev/WHERE" + */ + linkedListPrev = data.list.prev; + linkedListNext = data.list.next; + linkedListPrev->next = linkedListNext; + linkedListNext->prev = linkedListPrev; + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2B() +{ + badStruct data; + linkedList head = { &head, &head }; + /* This simulates a Microsoft-style linked list insertion */ + data.list.next = head.next; + data.list.prev = head.prev; + head.next = &data.list; + head.prev = &data.list; + /* FIX: don't overwrite linked list pointers */ + ; /* empty statement needed by some flow variants */ + { + badStruct dataCopy = data; + badStruct data = dataCopy; + /* POTENTIAL FLAW: The following removes 'a' from the list. Because of the possible overflow this + * causes a "write-what-where" aka "write4". It does another write as + * well. But this is the prototypical "write-what-where" at least from + * the Windows perspective. + * + * linkedListPrev = a->list->prev WHAT + * linkedListNext = a->list->next WHERE + * linkedListPrev->next = linkedListNext "at the address that prev/WHERE points, write + * next/WHAT" + * aka "write-what-where" + * linkedListNext->prev = linkedListPrev "at the address that next/WHAT points plus 4 + * (because prev is the second field in 'list' hence + * 4 bytes away on 32b machines), write prev/WHERE" + */ + linkedListPrev = data.list.prev; + linkedListNext = data.list.next; + linkedListPrev->next = linkedListNext; + linkedListNext->prev = linkedListPrev; + } +} + +void CWE123_Write_What_Where_Condition__fgets_31_good() +{ + goodG2B(); +} + +#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()..."); + CWE123_Write_What_Where_Condition__fgets_31_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE123_Write_What_Where_Condition__fgets_31_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0117677_jz_notifier.c b/pool/shard006/C/0117677_jz_notifier.c new file mode 100644 index 0000000000000000000000000000000000000000..f87f03acc62aaec76590d00499c3552d0c327428 --- /dev/null +++ b/pool/shard006/C/0117677_jz_notifier.c @@ -0,0 +1,76 @@ +#include + +static BLOCKING_NOTIFIER_HEAD(jz_notifier_chain_high); +static BLOCKING_NOTIFIER_HEAD(jz_notifier_chain_normal); +static int jz_notifier(struct notifier_block *nb, unsigned long cmd, void *data) +{ + struct jz_notifier *jz_nb = container_of(nb,struct jz_notifier,nb); + int ret = 0; + if(jz_nb->msg == cmd) { + ret = jz_nb->jz_notify(jz_nb,data); + } + return ret; +} + +int jz_notifier_register(struct jz_notifier *notify, unsigned int priority) +{ + unsigned int ret = 0; + + if((notify->level < NOTEFY_PROI_START) && (notify->level >= NOTEFY_PROI_END)) + { + printk("notify level can not support this %d\n",notify->level); + dump_stack(); + return -1; + } + if((int)notify->msg >= JZ_CMD_END && (int)notify->msg <= JZ_CMD_START) + { + printk("notify msg can not support this %d\n",notify->msg); + dump_stack(); + return -1; + } + if(notify->jz_notify == NULL) + { + printk("notify function(jz_notify) cand not support NULL\n"); + dump_stack(); + return -1; + } + notify->nb.priority = notify->level; + notify->nb.notifier_call = jz_notifier; + + if(priority == NOTEFY_PROI_HIGH) + ret = blocking_notifier_chain_register(&jz_notifier_chain_high, ¬ify->nb); + else if(priority == NOTEFY_PROI_NORMAL) + ret = blocking_notifier_chain_register(&jz_notifier_chain_normal, ¬ify->nb); + else + printk("not support\n"); + return ret; +} +EXPORT_SYMBOL(jz_notifier_register); + +int jz_notifier_unregister(struct jz_notifier *notify, unsigned int priority) +{ + unsigned int ret = 0; + + if(priority == NOTEFY_PROI_HIGH) + ret = blocking_notifier_chain_unregister(&jz_notifier_chain_high, ¬ify->nb); + else if(priority == NOTEFY_PROI_NORMAL) + ret = blocking_notifier_chain_unregister(&jz_notifier_chain_normal, ¬ify->nb); + else + printk("not support\n"); + return ret; +} +EXPORT_SYMBOL(jz_notifier_unregister); + +int jz_notifier_call(unsigned int priority, unsigned long val, void *v) +{ + unsigned int ret = 0; + + if(priority == NOTEFY_PROI_HIGH) + ret = blocking_notifier_call_chain(&jz_notifier_chain_high, val, v); + else if(priority == NOTEFY_PROI_NORMAL) + ret = blocking_notifier_call_chain(&jz_notifier_chain_normal, val, v); + else + printk("not support\n"); + return ret; +} +EXPORT_SYMBOL(jz_notifier_call); diff --git a/pool/shard006/C/0117682_sat3.c b/pool/shard006/C/0117682_sat3.c new file mode 100644 index 0000000000000000000000000000000000000000..729932d3d719395cdc23bc682d4d0892dace0583 --- /dev/null +++ b/pool/shard006/C/0117682_sat3.c @@ -0,0 +1,85 @@ +/* + * Circuit Satisfiability, Version 3 + * + * This versio is for the calculating the execute time + * + */ + +#include +#include + +/* Return 1 if 'i'th bit of 'n' is 1; 0 otherwise */ +#define EXTRACT_BIT(n, i) ((n & (1< * + * 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 cfeap nor the names of its contributors may * + * be used to endorse or promote products derived from this software * + * without specific prior written permission. * + * * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * + ***************************************************************************/ + +#include "utils/cmdl-args.h" + +static int cargs_print_help(void *argtable[], struct arg_lit *help); + +static int cargs_print_version(struct arg_lit *version); + +static int cargs_print_error(struct arg_end *end); + +static void cargs_export_file_name(struct arg_file *arg_input_fn, + struct arg_file *arg_output_fn, + struct arg_file *arg_log_fn, + bstring *input_fn, bstring *output_fn, + bstring *log_fn); + +int cargs_parse(int argc, char *argv[], bstring *input_fn, + bstring *output_fn, bstring *log_fn) +{ + struct arg_lit *help, *version; + struct arg_file *arg_input_fn, *arg_output_fn, *arg_log_fn; + struct arg_end *end; + + void *argtable[] = { + help = arg_litn("h", "help", 0, 100, "display this help and exit"), + version = arg_litn("v", "version", 0, 100, "display version info and exit"), + arg_input_fn = arg_filen("i", "input", "input_file", 1, 1, "input file (required)"), + arg_output_fn = arg_filen("o", "output", "output_file", 0, 1, "output file (optional)"), + arg_log_fn = arg_filen("l", "log", "log_file", 0, 1, "log file (optional)"), + end = arg_end(20), + }; + + int rc = 0; + + int nerrors = 0; + nerrors = arg_parse(argc, argv, argtable); + + // special case: help and version take precedence over error reporting + if(help->count >= 1) { + rc = cargs_print_help(argtable, help); + goto exit; + } + if(version->count >= 1) { + rc = cargs_print_version(version); + goto exit; + } + + // If the parser returned any errors, then display them and exit. + if(nerrors > 0) { + rc = cargs_print_error(end); + goto exit; + } + + cargs_export_file_name(arg_input_fn, arg_output_fn, arg_log_fn, + input_fn, output_fn, log_fn); + + exit: + arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); + return rc; +} + +static int cargs_print_help(void *argtable[], struct arg_lit *help) +{ + int rc = 0; + + if(help->count == 1) { + printf("Usage: %s", PROGRAM_NAME); + arg_print_syntax(stdout, argtable, "\n"); + printf("C Finite Element Analysis Program (CFEAP).\n\n"); + arg_print_glossary(stdout, argtable, " %-25s %s\n"); + printf("\n"); + } else { + printf("%s: excess option -h|--help\n", PROGRAM_NAME); + printf("Try '%s --help' for more information.\n\n", PROGRAM_NAME); + } + + return rc; +} + +static int cargs_print_version(struct arg_lit *version) +{ + int rc = 0; + + if(version->count == 1) { + printf("%s %s\n", PROGRAM_NAME, CFEAP_VERSION); + printf("C Finite Element Analysis Program (CFEAP).\n"); + printf("Copyright (C) 2017 Trung Pham \n"); + printf("This is free software; see the source for copying conditions. There is NO\n"); + printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"); + } else { + printf("%s: excess option -v|--version\n", PROGRAM_NAME); + printf("Try '%s --help' for more information.\n\n", PROGRAM_NAME); + } + + return rc; +} + + +static int cargs_print_error(struct arg_end *end) +{ + int rc = -1; + + arg_print_errors(stdout, end, PROGRAM_NAME); + printf("Try '%s --help' for more information.\n\n", PROGRAM_NAME); + + return rc; +} + +static void cargs_export_file_name(struct arg_file *arg_input_fn, + struct arg_file *arg_output_fn, + struct arg_file *arg_log_fn, + bstring *input_fn, bstring *output_fn, + bstring *log_fn) +{ + if(*input_fn == NULL) { + *input_fn = bfromcstr(arg_input_fn->basename[0]); + } else { + bassigncstr(*input_fn, arg_input_fn->basename[0]); + } + if(arg_output_fn->count == 1) { + if(*output_fn == NULL) { + *output_fn = bfromcstr(arg_output_fn->basename[0]); + } else { + bassigncstr(*output_fn, arg_output_fn->basename[0]); + } + } else if(arg_output_fn->count == 0) { + if(*output_fn == NULL) { + *output_fn = bfromcstr("cfeap-output.txt"); + } else { + bassigncstr(*output_fn, "cfeap-output.txt"); + } + } + if(arg_log_fn->count == 1) { + if(*log_fn == NULL) { + *log_fn = bfromcstr(arg_log_fn->basename[0]); + } else { + bassigncstr(*log_fn, arg_log_fn->basename[0]); + } + } else if(arg_log_fn->count == 0) { + if(*log_fn == NULL) { + *log_fn = bfromcstr("cfeap-log.txt"); + } else { + bassigncstr(*log_fn, "cfeap-log.txt"); + } + } +} diff --git a/pool/shard006/C/0117698_virtio-net.c b/pool/shard006/C/0117698_virtio-net.c new file mode 100644 index 0000000000000000000000000000000000000000..61c56170e9e844745685f187b9aa95a69baa672d --- /dev/null +++ b/pool/shard006/C/0117698_virtio-net.c @@ -0,0 +1,195 @@ +/* + * libqos driver framework + * + * Copyright (c) 2018 Emanuele Giuseppe Esposito + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License version 2 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, see + */ + +#include "qemu/osdep.h" +#include "libqtest.h" +#include "libqos/qgraph.h" +#include "libqos/virtio-net.h" +#include "hw/virtio/virtio-net.h" + + +static QGuestAllocator *alloc; + +static void virtio_net_cleanup(QVirtioNet *interface) +{ + int i; + + for (i = 0; i < interface->n_queues; i++) { + qvirtqueue_cleanup(interface->vdev->bus, interface->queues[i], alloc); + } + g_free(interface->queues); +} + +static void virtio_net_setup(QVirtioNet *interface) +{ + QVirtioDevice *vdev = interface->vdev; + uint64_t features; + int i; + + features = qvirtio_get_features(vdev); + features &= ~(QVIRTIO_F_BAD_FEATURE | + (1u << VIRTIO_RING_F_INDIRECT_DESC) | + (1u << VIRTIO_RING_F_EVENT_IDX)); + qvirtio_set_features(vdev, features); + + if (features & (1u << VIRTIO_NET_F_MQ)) { + interface->n_queues = qvirtio_config_readw(vdev, 8) * 2; + } else { + interface->n_queues = 2; + } + + interface->queues = g_new(QVirtQueue *, interface->n_queues); + for (i = 0; i < interface->n_queues; i++) { + interface->queues[i] = qvirtqueue_setup(vdev, alloc, i); + } + qvirtio_set_driver_ok(vdev); +} + +/* virtio-net-device */ +static void qvirtio_net_device_destructor(QOSGraphObject *obj) +{ + QVirtioNetDevice *v_net = (QVirtioNetDevice *) obj; + virtio_net_cleanup(&v_net->net); +} + +static void qvirtio_net_device_start_hw(QOSGraphObject *obj) +{ + QVirtioNetDevice *v_net = (QVirtioNetDevice *) obj; + QVirtioNet *interface = &v_net->net; + + virtio_net_setup(interface); +} + +static void *qvirtio_net_get_driver(QVirtioNet *v_net, + const char *interface) +{ + if (!g_strcmp0(interface, "virtio-net")) { + return v_net; + } + if (!g_strcmp0(interface, "virtio")) { + return v_net->vdev; + } + + fprintf(stderr, "%s not present in virtio-net-device\n", interface); + g_assert_not_reached(); +} + +static void *qvirtio_net_device_get_driver(void *object, + const char *interface) +{ + QVirtioNetDevice *v_net = object; + return qvirtio_net_get_driver(&v_net->net, interface); +} + +static void *virtio_net_device_create(void *virtio_dev, + QGuestAllocator *t_alloc, + void *addr) +{ + QVirtioNetDevice *virtio_ndevice = g_new0(QVirtioNetDevice, 1); + QVirtioNet *interface = &virtio_ndevice->net; + + interface->vdev = virtio_dev; + alloc = t_alloc; + + virtio_ndevice->obj.destructor = qvirtio_net_device_destructor; + virtio_ndevice->obj.get_driver = qvirtio_net_device_get_driver; + virtio_ndevice->obj.start_hw = qvirtio_net_device_start_hw; + + return &virtio_ndevice->obj; +} + +/* virtio-net-pci */ +static void qvirtio_net_pci_destructor(QOSGraphObject *obj) +{ + QVirtioNetPCI *v_net = (QVirtioNetPCI *) obj; + QVirtioNet *interface = &v_net->net; + QOSGraphObject *pci_vobj = &v_net->pci_vdev.obj; + + virtio_net_cleanup(interface); + qvirtio_pci_destructor(pci_vobj); +} + +static void qvirtio_net_pci_start_hw(QOSGraphObject *obj) +{ + QVirtioNetPCI *v_net = (QVirtioNetPCI *) obj; + QVirtioNet *interface = &v_net->net; + QOSGraphObject *pci_vobj = &v_net->pci_vdev.obj; + + qvirtio_pci_start_hw(pci_vobj); + virtio_net_setup(interface); +} + +static void *qvirtio_net_pci_get_driver(void *object, + const char *interface) +{ + QVirtioNetPCI *v_net = object; + if (!g_strcmp0(interface, "pci-device")) { + return v_net->pci_vdev.pdev; + } + return qvirtio_net_get_driver(&v_net->net, interface); +} + +static void *virtio_net_pci_create(void *pci_bus, QGuestAllocator *t_alloc, + void *addr) +{ + QVirtioNetPCI *virtio_bpci = g_new0(QVirtioNetPCI, 1); + QVirtioNet *interface = &virtio_bpci->net; + QOSGraphObject *obj = &virtio_bpci->pci_vdev.obj; + + virtio_pci_init(&virtio_bpci->pci_vdev, pci_bus, addr); + interface->vdev = &virtio_bpci->pci_vdev.vdev; + alloc = t_alloc; + + g_assert_cmphex(interface->vdev->device_type, ==, VIRTIO_ID_NET); + + obj->destructor = qvirtio_net_pci_destructor; + obj->start_hw = qvirtio_net_pci_start_hw; + obj->get_driver = qvirtio_net_pci_get_driver; + + return obj; +} + +static void virtio_net_register_nodes(void) +{ + /* FIXME: every test using these nodes needs to setup a + * -netdev socket,id=hs0 otherwise QEMU is not going to start. + * Therefore, we do not include "produces" edge for virtio + * and pci-device yet. + */ + QPCIAddress addr = { + .devfn = QPCI_DEVFN(4, 0), + }; + + QOSGraphEdgeOptions opts = { }; + + /* virtio-net-device */ + opts.extra_device_opts = "netdev=hs0"; + qos_node_create_driver("virtio-net-device", + virtio_net_device_create); + qos_node_consumes("virtio-net-device", "virtio-bus", &opts); + qos_node_produces("virtio-net-device", "virtio-net"); + + /* virtio-net-pci */ + opts.extra_device_opts = "netdev=hs0,addr=04.0"; + add_qpci_address(&opts, &addr); + qos_node_create_driver("virtio-net-pci", virtio_net_pci_create); + qos_node_consumes("virtio-net-pci", "pci-bus", &opts); + qos_node_produces("virtio-net-pci", "virtio-net"); +} + +libqos_init(virtio_net_register_nodes); diff --git a/pool/shard006/C/0117702_ProtocolTree.c b/pool/shard006/C/0117702_ProtocolTree.c new file mode 100644 index 0000000000000000000000000000000000000000..14a31d82066b5ddb8223f46bdaec2a4ffc09046e --- /dev/null +++ b/pool/shard006/C/0117702_ProtocolTree.c @@ -0,0 +1,272 @@ +/** + * @file + * @brief // TODO corrent description + */ + + + +#include +#include +#include + +#include "dbg.h" + +#include "dissect/tree/ProtocolTree.h" +#include "dissect/tree/ProtocolTree-int.h" + +/** + * @see ProtocolTree ops + */ +static const struct ProtocolTree_ops ProtocolTreeOverride_ops = { + + ProtocolTree_free, + ProtocolTree_branch, + ProtocolTree_branchImportant, + ProtocolTree_setValue, + ProtocolTree_getValue, + ProtocolTree_insertImportantValue, + ProtocolTree_getImportantValue, + ProtocolTree_getRoot, + ProtocolTree_getParent, + ProtocolTree_getChild, + ProtocolTree_getNode +}; + +/** + * @see ProtocolTree_free + */ +void ProtocolTree_free(struct ProtocolNode *proto) { + + if (proto->parent == NULL) { + free(proto->treeData); + } + + int i = 0; + for (i = 0; i < proto->childCount; i++) { + + ProtocolTree_free(proto->children[i]); + } + + // TODO maybe have to free key for avoiding memory leak ? + free(proto); +} + +// char *ProtocolItem_toString(struct ProtocolNode *node) { +// +// char *str = ""; +// //"%s [label=\"{%s|%s]" +// int i = 0; +// for (i = 0; i < node->childCount; i++) { +// //strcat(str, "%s -> %s;\n", node->key, node->children[i]->key); +// } +// return str; +// } +// + + +/** + * @see ProtocolTree_new + */ +struct ProtocolNode *ProtocolTree_new(char *rootName, Dissector_t *dissectedBy) { + + struct ProtocolNode *node = malloc(sizeof(struct ProtocolNode)); + check_mem(node); + + struct TreeData *treeData = malloc(sizeof(struct TreeData)); + check_mem(treeData); + + treeData->size = 1; + treeData->root = node; + treeData->nodePointers = malloc(sizeof(void*)); + check_mem(treeData->nodePointers); + + treeData->nextID = 0; + + + treeData->nodePointers[0] = node; + + treeData->map = HashMap_new(64); + check_mem(treeData->map); + + node->isImportant = false; + node->importantKey = ""; + + node->name = rootName; + node->id = treeData->nextID++; + node->ops = &ProtocolTreeOverride_ops; + node->childCount = 0; + node->treeData = treeData; + node->parent = NULL; + node->children = NULL; + node->visited = false; + + node->value.type = is_int64; + node->value.length = 0; + node->value.val.int16 = 0; + + node->dissectedBy = dissectedBy; + + return node; + +error: + + return NULL; +} + +/** + * @see ProtocolNode_branch + */ +struct ProtocolNode *ProtocolTree_branch(struct ProtocolNode *this, char *name, struct Value value, Dissector_t *dissectedBy) { + + struct ProtocolNode *child = malloc(sizeof(struct ProtocolNode)); + check_mem(child); + + child->treeData = this->treeData; + + child->dissectedBy = dissectedBy; + + child->name = name; + child->value = value; + child->isImportant = false; + child->importantKey = ""; + child->ops = this->ops; + child->childCount = 0; + child->parent = this; + child->children = NULL; + child->id = child->treeData->nextID++; + child->visited = false; + + // TODO implement dynamic growing + this->children = realloc(this->children, (this->childCount + 1) * sizeof(void*)); + check_mem(this->children); + + this->treeData->nodePointers = realloc(this->treeData->nodePointers, (this->treeData->size + 1) * sizeof(void*)); + check_mem(this->treeData->nodePointers); + + this->treeData->nodePointers[this->treeData->size] = child; + + this->children[this->childCount] = child; + this->childCount++; + this->treeData->size++; + + return child; + +error: + return NULL; +} + +struct ProtocolNode *ProtocolTree_branchImportant(struct ProtocolNode *this, char *name, char *importantKey, struct Value value, Dissector_t *dissectedBy) { + + struct ProtocolNode *child = malloc(sizeof(struct ProtocolNode)); + check_mem(child); + + child->treeData = this->treeData; + + child->dissectedBy = dissectedBy; + + child->name = name; + child->value = value; + child->isImportant = true; + child->importantKey = importantKey; + child->ops = this->ops; + child->childCount = 0; + child->parent = this; + child->children = NULL; + child->id = child->treeData->nextID++; + child->visited = false; + + ProtocolTree_insertImportantValue(this, importantKey, value); + + // TODO implement dynamic growing + this->children = realloc(this->children, (this->childCount + 1) * sizeof(void*)); + check_mem(this->children); + + this->treeData->nodePointers = realloc(this->treeData->nodePointers, (this->treeData->size + 1) * sizeof(void*)); + check_mem(this->treeData->nodePointers); + + this->treeData->nodePointers[this->treeData->size] = child; + + this->children[this->childCount] = child; + this->childCount++; + this->treeData->size++; + + return child; + +error: + return NULL; +} + +/** + * @see ProtocolTree_setValue + */ +struct Value ProtocolTree_setValue(struct ProtocolNode *this, struct Value value) { + + this->value = value; + // TODO maybe check and return old value + return value; +} + +/** + * @see ProtocolTree_setValue + */ +struct Value ProtocolTree_getValue(const struct ProtocolNode *this) { + + return this->value; +} + +int ProtocolTree_insertImportantValue(struct ProtocolNode *this, char *key, struct Value value) { + + return HashMap_insert(this->treeData->map, key, value, NULL); +} + +struct Value *ProtocolTree_getImportantValue(struct ProtocolNode *this, char *key) { + + return HashMap_find(this->treeData->map, key); +} + + +/** + * @see ProtocolTree_getRoot + */ +struct ProtocolNode *ProtocolTree_getRoot(const struct ProtocolNode *this) { + + return this->treeData->root; + +} + +/** + * @see ProtocolTree_getParent + */ +struct ProtocolNode *ProtocolTree_getParent(const struct ProtocolNode *this) { + + return this->parent; +} + +/** + * @see ProtocolTree_getChild + */ +struct ProtocolNode *ProtocolTree_getChild(const struct ProtocolNode *this, int index) { + + return this->children[index]; +} + +/** + * @see ProtocolTree_getNode + */ +struct ProtocolNode *ProtocolTree_getNode(const struct ProtocolNode *this, char *name) { + + sentinel("not implemented exception"); + +error: + return NULL; +} + +int +ProtocolTree_forEach(struct ProtocolNode *this, + int (*doThis)(struct ProtocolNode node, void *args, void *ret), + void *args, void *ret) { + + + + +} diff --git a/pool/shard006/C/0117706_ti-emif-pm.c b/pool/shard006/C/0117706_ti-emif-pm.c new file mode 100644 index 0000000000000000000000000000000000000000..3a9feab61390707214d28058aa11a3d247ff89d3 --- /dev/null +++ b/pool/shard006/C/0117706_ti-emif-pm.c @@ -0,0 +1,257 @@ +/* + * TI AM33XX SRAM EMIF Driver + * + * Copyright (C) 2015 Texas Instruments Inc. + * Dave Gerlach + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "emif.h" + +#define EMIF_POWER_MGMT_WAIT_SELF_REFRESH_8192_CYCLES 0x00a0 + +struct ti_emif_pm_functions { + u32 save_context; + u32 restore_context; + u32 enter_sr; + u32 exit_sr; + u32 abort_sr; +} __packed; + +static struct gen_pool *sram_pool; +static phys_addr_t ti_emif_sram_phys; +static void __iomem *ti_emif_sram_virt; +static unsigned long ocmcram_location; + +static u32 sram_suspend_address(unsigned long fn_offset) +{ + return (unsigned long)ti_emif_sram_virt + fn_offset; +} + +static phys_addr_t sram_resume_address(unsigned long fn_offset) +{ + return ti_emif_sram_phys + fn_offset; +} + +static int ti_emif_push_sram(struct device *dev) +{ + struct device_node *np = dev->of_node; + + sram_pool = of_get_named_gen_pool(np, "sram", 0); + + if (!sram_pool) { + dev_err(dev, "Unable to get sram pool for ocmcram\n"); + return -ENODEV; + } + + ocmcram_location = gen_pool_alloc(sram_pool, ti_emif_sram_sz); + if (!ocmcram_location) { + dev_err(dev, "Unable to allocate memory from ocmcram\n"); + return -EINVAL; + } + + /* Save physical address to calculate resume offset during pm init */ + ti_emif_sram_phys = gen_pool_virt_to_phys(sram_pool, + ocmcram_location); + ti_emif_sram_virt = fncpy((void *)ocmcram_location, + &ti_emif_sram, + ti_emif_sram_sz); + + /* + * These functions are called during suspend path while MMU is + * still on so add virtual base to offset for absolute address + */ + ti_emif_pm.save_context = sram_suspend_address(ti_emif_pm.save_context); + ti_emif_pm.enter_sr = sram_suspend_address(ti_emif_pm.enter_sr); + ti_emif_pm.abort_sr = sram_suspend_address(ti_emif_pm.abort_sr); + + /* + * These are called during resume path when MMU is not enabled + * so physical address is used instead + */ + ti_emif_pm.restore_context = + sram_resume_address(ti_emif_pm.restore_context); + ti_emif_pm.exit_sr = sram_resume_address(ti_emif_pm.exit_sr); + + return 0; +} + +/* + * Due to Usage Note 3.1.2 "DDR3: JEDEC Compliance for Maximum + * Self-Refresh Command Limit" found in AM335x Silicon Errata + * (Document SPRZ360F Revised November 2013) we must configure + * the self refresh delay timer to 0xA (8192 cycles) to avoid + * generating too many refresh command from the EMIF. + */ +static void ti_emif_configure_sr_delay(void) +{ + writel(EMIF_POWER_MGMT_WAIT_SELF_REFRESH_8192_CYCLES, + (ti_emif_base_addr_virt + + EMIF_POWER_MANAGEMENT_CONTROL)); + + writel(EMIF_POWER_MGMT_WAIT_SELF_REFRESH_8192_CYCLES, + (ti_emif_base_addr_virt + + EMIF_POWER_MANAGEMENT_CTRL_SHDW)); +} + +/** + * ti_emif_copy_pm_function_table - copy mapping of pm funcs in sram + * @dst: void * to address that table should be copied + * + * Returns 0 if success other error code if table is not available + */ +int ti_emif_copy_pm_function_table(void *dst) +{ + if (!ti_emif_sram_virt) + return -EINVAL; + + memcpy_toio(dst, &ti_emif_pm, sizeof(ti_emif_pm)); + + return 0; +} +EXPORT_SYMBOL_GPL(ti_emif_copy_pm_function_table); + +/** + * ti_emif_get_mem_type - return type for memory type in use + * + * Returns memory type value read from EMIF or error code if fails + */ +int ti_emif_get_mem_type(void) +{ + unsigned long temp; + + if (!ti_emif_base_addr_virt || IS_ERR(ti_emif_base_addr_virt)) + return -ENODEV; + + temp = readl(ti_emif_base_addr_virt + EMIF_SDRAM_CONFIG); + + temp = (temp & SDRAM_TYPE_MASK) >> SDRAM_TYPE_SHIFT; + return temp; +} +EXPORT_SYMBOL_GPL(ti_emif_get_mem_type); + +static const struct of_device_id ti_emif_of_match[] = { + { .compatible = "ti,emif-am3352", .data = + (void *)EMIF_SRAM_AM33_REG_LAYOUT, }, + { .compatible = "ti,emif-am4372", .data = + (void *)EMIF_SRAM_AM43_REG_LAYOUT, }, + {}, +}; + +#ifdef CONFIG_PM_SLEEP +static int ti_emif_resume(struct device *dev) +{ + unsigned long tmp = __raw_readl(ti_emif_sram_virt); + + /* + * Check to see if what we are copying is already present in the + * first byte at the destination, only copy if it is not which + * indicates we have lost context and sram no longer contains + * the PM code + */ + if (tmp != ti_emif_sram) + fncpy((void *)ocmcram_location, + &ti_emif_sram, + ti_emif_sram_sz); + + return 0; +} +#endif /* CONFIG_PM_SLEEP */ + +static int ti_emif_probe(struct platform_device *pdev) +{ + int ret = -ENODEV; + struct resource *res; + struct device *dev = &pdev->dev; + const struct of_device_id *match; + + match = of_match_device(ti_emif_of_match, &pdev->dev); + if (!match) + return -ENODEV; + + ti_emif_sram_config = (u32)match->data; + + pm_runtime_enable(dev); + ret = pm_runtime_get_sync(dev); + + if (IS_ERR_VALUE(ret)) { + dev_err(dev, "pm_runtime_get_sync() failed\n"); + goto fail_runtime_put; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + ti_emif_base_addr_virt = devm_ioremap_resource(dev, res); + if (IS_ERR(ti_emif_base_addr_virt)) { + dev_err(dev, "could not ioremap emif mem\n"); + ret = PTR_ERR(ti_emif_base_addr_virt); + goto fail_runtime_put; + } + + ti_emif_base_addr_phys = res->start; + + ti_emif_configure_sr_delay(); + + ret = ti_emif_push_sram(dev); + if (ret) + goto fail_runtime_put; + + return 0; + +fail_runtime_put: + pm_runtime_put_sync(dev); + return ret; +} + +static int ti_emif_remove(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + + pm_runtime_put_sync(dev); + pm_runtime_disable(dev); + + gen_pool_free(sram_pool, ocmcram_location, + ti_emif_sram_sz); + + return 0; +} + +static const struct dev_pm_ops ti_emif_pm_ops = { + SET_SYSTEM_SLEEP_PM_OPS(NULL, ti_emif_resume) +}; + +static struct platform_driver ti_emif_driver = { + .probe = ti_emif_probe, + .remove = ti_emif_remove, + .driver = { + .name = KBUILD_MODNAME, + .of_match_table = of_match_ptr(ti_emif_of_match), + .pm = &ti_emif_pm_ops, + }, +}; + +module_platform_driver(ti_emif_driver); + +MODULE_AUTHOR("Dave Gerlach "); +MODULE_DESCRIPTION("Texas Instruments SRAM EMIF driver"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:" KBUILD_MODNAME); diff --git a/pool/shard006/C/0117707_uio_smx.c b/pool/shard006/C/0117707_uio_smx.c new file mode 100644 index 0000000000000000000000000000000000000000..dc878065cb0bc44936f47c962285948f1fe2e3f7 --- /dev/null +++ b/pool/shard006/C/0117707_uio_smx.c @@ -0,0 +1,131 @@ + + +#include +#include +#include +#include +#include + +#define DRV_NAME "smx-ce" +#define DRV_VERSION "0.03" + +#define SMX_CSR 0x00000000 +#define SMX_EnD 0x00000001 +#define SMX_RUN 0x00000002 +#define SMX_DRDY 0x00000004 +#define SMX_ERR 0x00000008 + +static irqreturn_t smx_handler(int irq, struct uio_info *dev_info) +{ + void __iomem *csr = dev_info->mem[0].internal_addr + SMX_CSR; + + u32 status = ioread32(csr); + + if (!(status & SMX_DRDY)) + return IRQ_NONE; + + + iowrite32(status & ~SMX_DRDY, csr); + return IRQ_HANDLED; +} + +static int __devinit smx_ce_probe(struct platform_device *dev) +{ + + int ret = -ENODEV; + struct uio_info *info; + struct resource *regs; + + info = kzalloc(sizeof(struct uio_info), GFP_KERNEL); + if (!info) + return -ENOMEM; + + regs = platform_get_resource(dev, IORESOURCE_MEM, 0); + if (!regs) { + dev_err(&dev->dev, "No memory resource specified\n"); + goto out_free; + } + + info->mem[0].addr = regs->start; + if (!info->mem[0].addr) { + dev_err(&dev->dev, "Invalid memory resource\n"); + goto out_free; + } + + info->mem[0].size = regs->end - regs->start + 1; + info->mem[0].internal_addr = ioremap(regs->start, info->mem[0].size); + + if (!info->mem[0].internal_addr) { + dev_err(&dev->dev, "Can't remap memory address range\n"); + goto out_free; + } + + info->mem[0].memtype = UIO_MEM_PHYS; + + info->name = "smx-ce"; + info->version = "0.03"; + + info->irq = platform_get_irq(dev, 0); + if (info->irq < 0) { + ret = info->irq; + dev_err(&dev->dev, "No (or invalid) IRQ resource specified\n"); + goto out_unmap; + } + + info->irq_flags = IRQF_SHARED; + info->handler = smx_handler; + + platform_set_drvdata(dev, info); + + ret = uio_register_device(&dev->dev, info); + + if (ret) + goto out_unmap; + + return 0; + +out_unmap: + iounmap(info->mem[0].internal_addr); +out_free: + kfree(info); + + return ret; +} + +static int __devexit smx_ce_remove(struct platform_device *dev) +{ + struct uio_info *info = platform_get_drvdata(dev); + + uio_unregister_device(info); + platform_set_drvdata(dev, NULL); + iounmap(info->mem[0].internal_addr); + + kfree(info); + + return 0; +} + +static struct platform_driver smx_ce_driver = { + .probe = smx_ce_probe, + .remove = __devexit_p(smx_ce_remove), + .driver = { + .name = DRV_NAME, + .owner = THIS_MODULE, + }, +}; + +static int __init smx_ce_init_module(void) +{ + return platform_driver_register(&smx_ce_driver); +} +module_init(smx_ce_init_module); + +static void __exit smx_ce_exit_module(void) +{ + platform_driver_unregister(&smx_ce_driver); +} +module_exit(smx_ce_exit_module); + +MODULE_LICENSE("GPL v2"); +MODULE_VERSION(DRV_VERSION); +MODULE_AUTHOR("Ben Nizette "); diff --git a/pool/shard006/C/0117708_gstglcolorscale.c b/pool/shard006/C/0117708_gstglcolorscale.c new file mode 100644 index 0000000000000000000000000000000000000000..4ec29b5ab9460c1198ba16d33fbfe1524b36dfbe --- /dev/null +++ b/pool/shard006/C/0117708_gstglcolorscale.c @@ -0,0 +1,233 @@ +/* + * GStreamer + * Copyright (C) 2008 Julien Isorce + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + +/** + * SECTION:element-glcolorscale + * + * video frame scaling and colorspace conversion. + * + * + * Scaling and Color space conversion + * + * Equivalent to glupload ! gldownload. + * + * + * + * Examples + * |[ + * gst-launch-1.0 -v videotestsrc ! video/x-raw ! glcolorscale ! ximagesink + * ]| A pipeline to test colorspace conversion. + * FBO is required. + |[ + * gst-launch-1.0 -v videotestsrc ! video/x-raw, width=640, height=480, format=AYUV ! glcolorscale ! \ + * video/x-raw, width=320, height=240, format=YV12 ! videoconvert ! autovideosink + * ]| A pipeline to test hardware scaling and colorspace conversion. + * FBO and GLSL are required. + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstglcolorscale.h" + + +#define GST_CAT_DEFAULT gst_gl_colorscale_debug +GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); + +/* Properties */ +enum +{ + PROP_0 +}; + +#define DEBUG_INIT \ + GST_DEBUG_CATEGORY_INIT (gst_gl_colorscale_debug, "glcolorscale", 0, "glcolorscale element"); + +G_DEFINE_TYPE_WITH_CODE (GstGLColorscale, gst_gl_colorscale, + GST_TYPE_GL_FILTER, DEBUG_INIT); + +static void gst_gl_colorscale_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec); +static void gst_gl_colorscale_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec); + +#if GST_GL_HAVE_GLES2 +static gboolean gst_gl_colorscale_gen_gl_resources (GstGLFilter * filter); +static void gst_gl_colorscale_del_gl_resources (GstGLFilter * filter); +#endif + +static gboolean gst_gl_colorscale_filter_texture (GstGLFilter * filter, + guint in_tex, guint out_tex); +#if GST_GL_HAVE_OPENGL +static void gst_gl_colorscale_callback (gint width, gint height, + guint texture, gpointer stuff); +#endif + +static void +gst_gl_colorscale_class_init (GstGLColorscaleClass * klass) +{ + GObjectClass *gobject_class; + GstElementClass *element_class; + GstGLFilterClass *filter_class; + GstBaseTransformClass *basetransform_class = GST_BASE_TRANSFORM_CLASS (klass); + + gobject_class = (GObjectClass *) klass; + element_class = GST_ELEMENT_CLASS (klass); + filter_class = GST_GL_FILTER_CLASS (klass); + + gobject_class->set_property = gst_gl_colorscale_set_property; + gobject_class->get_property = gst_gl_colorscale_get_property; + + gst_element_class_set_metadata (element_class, "OpenGL color scale", + "Filter/Effect/Video", "Colorspace converter and video scaler", + "Julien Isorce "); + +#if GST_GL_HAVE_GLES2 + filter_class->onInitFBO = + GST_DEBUG_FUNCPTR (gst_gl_colorscale_gen_gl_resources); + filter_class->onStop = GST_DEBUG_FUNCPTR (gst_gl_colorscale_del_gl_resources); +#endif + + filter_class->filter_texture = gst_gl_colorscale_filter_texture; + + basetransform_class->passthrough_on_same_caps = TRUE; +} + +static void +gst_gl_colorscale_init (GstGLColorscale * colorscale) +{ +#if GST_GL_HAVE_GLES2 + colorscale->shader = NULL; +#endif +} + +static void +gst_gl_colorscale_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + switch (prop_id) { + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_gl_colorscale_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + switch (prop_id) { + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +#if GST_GL_HAVE_GLES2 +static void +_compile_identity_shader (GstGLContext * context, GstGLColorscale * colorscale) +{ + GstGLFilter *filter = GST_GL_FILTER (colorscale); + + colorscale->shader = gst_gl_shader_new (context); + + if (!gst_gl_shader_compile_with_default_vf_and_check (colorscale->shader, + &filter->draw_attr_position_loc, &filter->draw_attr_texture_loc)) { + gst_gl_context_clear_shader (context); + gst_object_unref (colorscale->shader); + colorscale->shader = NULL; + } +} + +static gboolean +gst_gl_colorscale_gen_gl_resources (GstGLFilter * filter) +{ + GstGLColorscale *colorscale = GST_GL_COLORSCALE (filter); + + if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_GLES2) { + gst_gl_context_thread_add (filter->context, + (GstGLContextThreadFunc) _compile_identity_shader, colorscale); + + if (!colorscale->shader) { + gst_gl_context_set_error (filter->context, + "Failed to initialize identity shader"); + GST_ELEMENT_ERROR (colorscale, RESOURCE, NOT_FOUND, ("%s", + gst_gl_context_get_error ()), (NULL)); + return FALSE; + } + } + + return TRUE; +} + +static void +gst_gl_colorscale_del_gl_resources (GstGLFilter * filter) +{ + GstGLColorscale *colorscale = GST_GL_COLORSCALE (filter); + + if (colorscale->shader) { + gst_gl_context_del_shader (filter->context, colorscale->shader); + colorscale->shader = NULL; + } +} +#endif + +static gboolean +gst_gl_colorscale_filter_texture (GstGLFilter * filter, guint in_tex, + guint out_tex) +{ + GstGLColorscale *colorscale; + + colorscale = GST_GL_COLORSCALE (filter); + +#if GST_GL_HAVE_GLES2 + if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_GLES2) + gst_gl_filter_render_to_target_with_shader (filter, TRUE, in_tex, out_tex, + colorscale->shader); +#endif + +#if GST_GL_HAVE_OPENGL + if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_OPENGL) + gst_gl_filter_render_to_target (filter, TRUE, in_tex, out_tex, + gst_gl_colorscale_callback, colorscale); +#endif + + return TRUE; +} + +#if GST_GL_HAVE_OPENGL +static void +gst_gl_colorscale_callback (gint width, gint height, guint texture, + gpointer stuff) +{ + GstGLFilter *filter = GST_GL_FILTER (stuff); + + if (gst_gl_context_get_gl_api (filter->context) & GST_GL_API_OPENGL) { + const GstGLFuncs *gl = filter->context->gl_vtable; + + gl->MatrixMode (GL_PROJECTION); + gl->LoadIdentity (); + } + + gst_gl_filter_draw_texture (filter, texture, width, height); +} +#endif diff --git a/pool/shard006/C/0117710_arm_chebyshev_distance_f16.c b/pool/shard006/C/0117710_arm_chebyshev_distance_f16.c new file mode 100644 index 0000000000000000000000000000000000000000..8dec141f82f13ca0ac6411ab7a1d3343b6ebf34a --- /dev/null +++ b/pool/shard006/C/0117710_arm_chebyshev_distance_f16.c @@ -0,0 +1,146 @@ + +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_chebyshev_distance_f16.c + * Description: Chebyshev distance between two vectors + * + * $Date: 23 April 2021 + * $Revision: V1.9.0 + * + * Target Processor: Cortex-M and Cortex-A cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * 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 + * + * 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 "dsp/distance_functions_f16.h" + +#if defined(ARM_FLOAT16_SUPPORTED) + +#include +#include + +/** + @ingroup FloatDist + */ + +/** + @defgroup Chebyshev Chebyshev distance + + Chebyshev distance + */ + +/** + @addtogroup Chebyshev + @{ + */ + + +/** + * @brief Chebyshev distance between two vectors + * @param[in] pA First vector + * @param[in] pB Second vector + * @param[in] blockSize vector length + * @return distance + * + */ + +#if defined(ARM_MATH_MVE_FLOAT16) && !defined(ARM_MATH_AUTOVECTORIZE) + +#include "arm_helium_utils.h" +#include "arm_vec_math.h" + +float16_t arm_chebyshev_distance_f16(const float16_t *pA,const float16_t *pB, uint32_t blockSize) +{ + uint32_t blkCnt; /* loop counters */ + f16x8_t vecA, vecB; + f16x8_t vecDiff = vdupq_n_f16(0.0); + float16_t maxValue = 0.0f16; + + + blkCnt = blockSize >> 3; + while (blkCnt > 0U) { + vecA = vld1q(pA); + pA += 8; + vecB = vld1q(pB); + pB += 8; + /* + * update per-lane max. + */ + vecDiff = vmaxnmaq(vsubq(vecA, vecB), vecDiff); + /* + * Decrement the blockSize loop counter + */ + blkCnt--; + } + /* + * tail + * (will be merged thru tail predication) + */ + blkCnt = blockSize & 7; + if (blkCnt > 0U) { + mve_pred16_t p0 = vctp16q(blkCnt); + + vecA = vldrhq_z_f16(pA, p0); + vecB = vldrhq_z_f16(pB, p0); + + /* + * Get current max per lane and current index per lane + * when a max is selected + */ + vecDiff = vmaxnmaq_m(vecDiff, vsubq(vecA, vecB), p0); + } + /* + * Get max value across the vector + */ + return vmaxnmavq(maxValue, vecDiff); +} + +#else +float16_t arm_chebyshev_distance_f16(const float16_t *pA,const float16_t *pB, uint32_t blockSize) +{ + _Float16 diff=0.0f, maxVal,tmpA, tmpB; + + tmpA = *pA++; + tmpB = *pB++; + diff = (_Float16)fabsf((float32_t)((_Float16)tmpA - (_Float16)tmpB)); + maxVal = diff; + blockSize--; + + while(blockSize > 0) + { + tmpA = *pA++; + tmpB = *pB++; + diff = (_Float16)fabsf((float32_t)((_Float16)tmpA - (_Float16)tmpB)); + if ((_Float16)diff > (_Float16)maxVal) + { + maxVal = diff; + } + blockSize --; + } + + return(maxVal); +} +#endif /* defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE) */ + + +/** + * @} end of Chebyshev group + */ + +#endif /* #if defined(ARM_FLOAT16_SUPPORTED) */ + diff --git a/pool/shard006/C/0117717_dmi_scan.c b/pool/shard006/C/0117717_dmi_scan.c new file mode 100644 index 0000000000000000000000000000000000000000..6a63300d420fdd810718804767197ced19c891c9 --- /dev/null +++ b/pool/shard006/C/0117717_dmi_scan.c @@ -0,0 +1,251 @@ +/* + Taken from arch/i386/kernel/dmi_scan.c. + Changes dmi_ident to be non-static so we can access. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "dmi_scan.h" + +struct dmi_header +{ + u8 type; + u8 length; + u16 handle; +}; + +#define dmi_printk(x) +//#define dmi_printk(x) printk x + +static char * __init dmi_string(struct dmi_header *dm, u8 s) +{ + u8 *bp=(u8 *)dm; + bp+=dm->length; + if(!s) + return ""; + s--; + while(s>0) + { + bp+=strlen(bp); + bp++; + s--; + } + return bp; +} + +/* + * We have to be cautious here. We have seen BIOSes with DMI pointers + * pointing to completely the wrong place for example + */ + +static int __init dmi_table(u32 base, int len, int num, void (*decode)(struct dmi_header *)) +{ + u8 *buf; + struct dmi_header *dm; + u8 *data; + int i=1; + + buf = ioremap(base, len); + if(buf==NULL) + return -1; + + data = buf; + + /* + * Stop when we see al the items the table claimed to have + * OR we run off the end of the table (also happens) + */ + + while(ilength) >= len) + break; + decode(dm); + data+=dm->length; + /* + * Don't go off the end of the data if there is + * stuff looking like string fill past the end + */ + while((data-buf) < len && (*data || data[1])) + data++; + data+=2; + i++; + } + iounmap(buf); + return 0; +} + + +static int __init dmi_iterate(void (*decode)(struct dmi_header *)) +{ + unsigned char buf[20]; + long fp=0xE0000L; + fp -= 16; + +#ifdef CONFIG_SIMNOW + /* + * Skip on x86/64 with simnow. Will eventually go away + * If you see this ifdef in 2.6pre mail me ! + */ + return -1; +#endif + + while( fp < 0xFFFFF) + { + fp+=16; + isa_memcpy_fromio(buf, fp, 20); + if(memcmp(buf, "_DMI_", 5)==0) + { + u16 num=buf[13]<<8|buf[12]; + u16 len=buf[7]<<8|buf[6]; + u32 base=buf[11]<<24|buf[10]<<16|buf[9]<<8|buf[8]; + + dmi_printk((KERN_INFO "DMI %d.%d present.\n", + buf[14]>>4, buf[14]&0x0F)); + dmi_printk((KERN_INFO "%d structures occupying %d bytes.\n", + buf[13]<<8|buf[12], + buf[7]<<8|buf[6])); + dmi_printk((KERN_INFO "DMI table at 0x%08X.\n", + buf[11]<<24|buf[10]<<16|buf[9]<<8|buf[8])); + if(dmi_table(base,len, num, decode)==0) + return 0; + } + } + return -1; +} + + +char *dmi_ident[DMI_STRING_MAX]; + +/* + * Save a DMI string + */ + +static void __init dmi_save_ident(struct dmi_header *dm, int slot, int string) +{ + char *d = (char*)dm; + char *p = dmi_string(dm, d[string]); + if(p==NULL || *p == 0) + return; + if (dmi_ident[slot]) + return; + dmi_ident[slot] = kmalloc(strlen(p)+1, GFP_KERNEL); + if(dmi_ident[slot]) + strcpy(dmi_ident[slot], p); + else + printk(KERN_ERR "dmi_save_ident: out of memory.\n"); +} + +/* + * Process a DMI table entry. Right now all we care about are the BIOS + * and machine entries. For 2.5 we should pull the smbus controller info + * out of here. + */ + +static void __init dmi_decode(struct dmi_header *dm) +{ + u8 *data = (u8 *)dm; + char *p; + + switch(dm->type) + { + case 0: + p=dmi_string(dm,data[4]); + if(*p) + { + dmi_printk(("BIOS Vendor: %s\n", p)); + dmi_save_ident(dm, DMI_BIOS_VENDOR, 4); + dmi_printk(("BIOS Version: %s\n", + dmi_string(dm, data[5]))); + dmi_save_ident(dm, DMI_BIOS_VERSION, 5); + dmi_printk(("BIOS Release: %s\n", + dmi_string(dm, data[8]))); + dmi_save_ident(dm, DMI_BIOS_DATE, 8); + } + break; + + case 1: + p=dmi_string(dm,data[4]); + if(*p) + { + dmi_printk(("System Vendor: %s.\n",p)); + dmi_save_ident(dm, DMI_SYS_VENDOR, 4); + dmi_printk(("Product Name: %s.\n", + dmi_string(dm, data[5]))); + dmi_save_ident(dm, DMI_PRODUCT_NAME, 5); + dmi_printk(("Version %s.\n", + dmi_string(dm, data[6]))); + dmi_save_ident(dm, DMI_PRODUCT_VERSION, 6); + dmi_printk(("Serial Number %s.\n", + dmi_string(dm, data[7]))); + } + break; + case 2: + p=dmi_string(dm,data[4]); + if(*p) + { + dmi_printk(("Board Vendor: %s.\n",p)); + dmi_save_ident(dm, DMI_BOARD_VENDOR, 4); + dmi_printk(("Board Name: %s.\n", + dmi_string(dm, data[5]))); + dmi_save_ident(dm, DMI_BOARD_NAME, 5); + dmi_printk(("Board Version: %s.\n", + dmi_string(dm, data[6]))); + dmi_save_ident(dm, DMI_BOARD_VERSION, 6); + } + break; + case 3: + p=dmi_string(dm,data[8]); + if(*p && *p!=' ') + dmi_printk(("Asset Tag: %s.\n", p)); + break; + } +} + +void __init dmi_scan_machine(void) +{ + int err; + printk("dmi_scan.o version %s (%s)\n", LM_VERSION, LM_DATE); + err = dmi_iterate(dmi_decode); + if(err) + printk("dmi_scan.o: SM BIOS not found\n"); + else + printk("dmi_scan.o: SM BIOS found\n"); +} + +#ifdef MODULE +MODULE_DESCRIPTION("SM BIOS DMI Scanner"); +#ifdef MODULE_LICENSE +MODULE_LICENSE("GPL"); +#endif +EXPORT_SYMBOL_GPL(dmi_ident); +EXPORT_SYMBOL_GPL(dmi_scan_machine); +int init_module(void) +{ + return 0; +} + +int cleanup_module(void) +{ + return 0; +} + +#endif diff --git a/pool/shard006/C/0117718_interrupt.c b/pool/shard006/C/0117718_interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..47346a5420ef3a41f9865afe51ed89940f2cd83c --- /dev/null +++ b/pool/shard006/C/0117718_interrupt.c @@ -0,0 +1,64 @@ +/*! Interrupt handling - 'arch' layer (only basic operations) */ + +#define _ARCH_INTERRUPTS_C_ +#include "interrupt.h" + +#include +#include +#include + +/*! interrupt handlers */ +static void (*ihandler[INTERRUPTS]) ( unsigned int ); + +/*! Initialize interrupt subsystem (in 'arch' layer) */ +void arch_init_interrupts () +{ + memset ( ihandler, 0, sizeof(ihandler) ); +} + +/*! Register handler function for particular interrupt number */ +void *arch_register_interrupt_handler ( unsigned int irq_num, void *handler ) +{ + void *old_handler = NULL; + + if ( irq_num < INTERRUPTS ) + { + old_handler = ihandler[irq_num]; + ihandler[irq_num] = handler; + } + else { + LOG ( ERROR, "Interrupt %d can't be used!\n", irq_num ); + halt (); + } + + return old_handler; +} + +/*! Unregister handler function for particular interrupt number */ +void *arch_unregister_interrupt_handler ( unsigned int irq_num ) +{ + void *old_handler = NULL; + ASSERT ( irq_num >= 0 && irq_num < INTERRUPTS ); + + old_handler = ihandler[irq_num]; + ihandler[irq_num] = NULL; + + return old_handler; +} + +/*! + * "Forward" interrupt handling to registered handler + * (called from interrupts.S) + */ +void arch_interrupt_handler ( int irq_num ) +{ + if( irq_num < INTERRUPTS && ihandler[irq_num] ) + { + /* Call registered handler */ + ihandler[irq_num] ( irq_num ); + } + else { + LOG ( ERROR, "Unregistered interrupt: %d !\n", irq_num ); + halt (); + } +} diff --git a/pool/shard006/C/0117722_gnrc_tcp_eventloop.c b/pool/shard006/C/0117722_gnrc_tcp_eventloop.c new file mode 100644 index 0000000000000000000000000000000000000000..e8d8acce57b9bb4b99f2d29c14b6a9731305c384 --- /dev/null +++ b/pool/shard006/C/0117722_gnrc_tcp_eventloop.c @@ -0,0 +1,289 @@ +/* + * Copyright (C) 2015-2017 Simon Brummer + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup net_gnrc + * @{ + * + * @file + * @brief Implementation of internal/eventloop.h + * + * @author Simon Brummer + * @} + */ + +#include +#include +#include "net/af.h" +#include "net/tcp.h" +#include "net/gnrc.h" +#include "internal/common.h" +#include "internal/pkt.h" +#include "internal/fsm.h" +#include "internal/eventloop.h" + +#ifdef MODULE_GNRC_IPV6 +#include "net/gnrc/ipv6.h" +#endif + +#define ENABLE_DEBUG (0) +#include "debug.h" + +static msg_t _eventloop_msg_queue[TCP_EVENTLOOP_MSG_QUEUE_SIZE]; + +/** + * @brief Send function, pass paket down the network stack. + * + * @param[in] pkt Paket to send. + * + * @returns Zero on success. + * Negative value on error. + * @returns -EBADMSG if TCP header is missing in @p pkt. + */ +static int _send(gnrc_pktsnip_t *pkt) +{ + assert(pkt != NULL); + + /* NOTE: In sending direction: pkt = nw, nw->next = tcp, tcp->next = payload */ + gnrc_pktsnip_t *tcp = NULL; + gnrc_pktsnip_t *nw = NULL; + + /* Search for TCP header */ + LL_SEARCH_SCALAR(pkt, tcp, type, GNRC_NETTYPE_TCP); + /* cppcheck-suppress knownConditionTrueFalse */ + if (tcp == NULL) { + DEBUG("gnrc_tcp_eventloop : _send() : tcp header missing.\n"); + gnrc_pktbuf_release(pkt); + return -EBADMSG; + } + + /* Search for network layer */ +#ifdef MODULE_GNRC_IPV6 + /* Get IPv6 header, discard packet if doesn't contain an ipv6 header */ + LL_SEARCH_SCALAR(pkt, nw, type, GNRC_NETTYPE_IPV6); + if (nw == NULL) { + DEBUG("gnrc_tcp_eventloop.c : _send() : pkt contains no ipv6 layer header\n"); + gnrc_pktbuf_release(pkt); + return -EBADMSG; + } +#endif + + /* Dispatch packet to network layer */ + assert(nw != NULL); + if (!gnrc_netapi_dispatch_send(nw->type, GNRC_NETREG_DEMUX_CTX_ALL, pkt)) { + DEBUG("gnrc_tcp_eventloop : _send() : network layer not found\n"); + gnrc_pktbuf_release(pkt); + } + return 0; +} + +/** + * @brief Receive function, receive packet from network layer. + * + * @param[in] pkt Incomming paket. + * + * @returns Zero on success. + * Negative value on error. + * -EACCES if write access to packet was not aquired. + * -ERANGE if segment offset value is less than 5. + * -ENOMSG if paket couldn't be marked. + * -EINVAL if checksum was invalid. + * -ENOTCONN if no TCB is interested in @p pkt. + */ +static int _receive(gnrc_pktsnip_t *pkt) +{ + /* NOTE: In receiving direction: pkt = payload, payload->next = tcp, tcp->next = nw */ + uint16_t ctl = 0; + uint16_t src = 0; + uint16_t dst = 0; + uint8_t hdr_size = 0; + uint8_t syn = 0; + gnrc_pktsnip_t *ip = NULL; + gnrc_pktsnip_t *reset = NULL; + gnrc_tcp_tcb_t *tcb = NULL; + tcp_hdr_t *hdr; + + /* Get write access to the TCP header */ + gnrc_pktsnip_t *tcp = gnrc_pktbuf_start_write(pkt); + if (tcp == NULL) { + DEBUG("gnrc_tcp_eventloop.c : _receive() : can't write to packet\n"); + gnrc_pktbuf_release(pkt); + return -EACCES; + } + pkt = tcp; + +#ifdef MODULE_GNRC_IPV6 + /* Get IPv6 header, discard packet if doesn't contain an ip header */ + LL_SEARCH_SCALAR(pkt, ip, type, GNRC_NETTYPE_IPV6); + if (ip == NULL) { + DEBUG("gnrc_tcp_eventloop.c : _receive() : pkt contains no IP Header\n"); + gnrc_pktbuf_release(pkt); + return 0; + } +#endif + + /* Get TCP header */ + LL_SEARCH_SCALAR(pkt, tcp, type, GNRC_NETTYPE_TCP); + if (tcp == NULL) { + DEBUG("gnrc_tcp_eventloop.c : _receive() : pkt contains no TCP Header\n"); + gnrc_pktbuf_release(pkt); + return 0; + } + + /* Extract control bits, src and dst ports and check if SYN is set (not SYN+ACK) */ + hdr = (tcp_hdr_t *)tcp->data; + ctl = byteorder_ntohs(hdr->off_ctl); + src = byteorder_ntohs(hdr->src_port); + dst = byteorder_ntohs(hdr->dst_port); + syn = ((ctl & MSK_SYN_ACK) == MSK_SYN); + + /* Validate offset */ + if (GET_OFFSET(ctl) < TCP_HDR_OFFSET_MIN) { + DEBUG("gnrc_tcp_eventloop.c : _receive() : unexpected Offset Value\n"); + gnrc_pktbuf_release(pkt); + return -ERANGE; + } + + /* Calculate TCP header size */ + hdr_size = GET_OFFSET(ctl) * 4; + + /* Mark TCP header if it contains any payload */ + if ((pkt->type == GNRC_NETTYPE_TCP) && (pkt->size != hdr_size)) { + tcp = gnrc_pktbuf_mark(pkt, hdr_size, GNRC_NETTYPE_TCP); + if (tcp == NULL) { + DEBUG("gnrc_tcp_eventloop.c : _receive() : Header marking failed\n"); + gnrc_pktbuf_release(pkt); + return -ENOMSG; + } + pkt->type = GNRC_NETTYPE_UNDEF; + } + + /* Validate checksum */ + if (byteorder_ntohs(hdr->checksum) != _pkt_calc_csum(tcp, ip, pkt)) { + DEBUG("gnrc_tcp_eventloop.c : _receive() : Invalid checksum\n"); + gnrc_pktbuf_release(pkt); + return -EINVAL; + } + + /* Find TCB to for this packet */ + mutex_lock(&_list_tcb_lock); + tcb = _list_tcb_head; + while (tcb) { +#ifdef MODULE_GNRC_IPV6 + /* Check if current TCB is fitting for the incomming packet */ + if (ip->type == GNRC_NETTYPE_IPV6 && tcb->address_family == AF_INET6) { + /* If SYN is set, a connection is listening on that port ... */ + ipv6_addr_t *tmp_addr = NULL; + if (syn && tcb->local_port == dst && tcb->state == FSM_STATE_LISTEN) { + /* ... and local addr is unspec or pre configured */ + tmp_addr = &((ipv6_hdr_t *)ip->data)->dst; + if (ipv6_addr_equal((ipv6_addr_t *) tcb->local_addr, (ipv6_addr_t *) tmp_addr) || + ipv6_addr_is_unspecified((ipv6_addr_t *) tcb->local_addr)) { + break; + } + } + + /* If SYN is not set and the ports match ... */ + if (!syn && tcb->local_port == dst && tcb->peer_port == src) { + /* .. and the IPv6 addresses match */ + tmp_addr = &((ipv6_hdr_t * )ip->data)->src; + if (ipv6_addr_equal((ipv6_addr_t *) tcb->peer_addr, (ipv6_addr_t *) tmp_addr)) { + break; + } + } + } +#else + /* Supress compiler warnings if TCP is build without network layer */ + (void) syn; + (void) src; + (void) dst; +#endif + tcb = tcb->next; + } + mutex_unlock(&_list_tcb_lock); + + /* Call FSM with event RCVD_PKT if a fitting TCB was found */ + if (tcb != NULL) { + _fsm(tcb, FSM_EVENT_RCVD_PKT, pkt, NULL, 0); + } + /* No fitting TCB has been found. Respond with reset */ + else { + DEBUG("gnrc_tcp_eventloop.c : _receive() : Can't find fitting tcb\n"); + if ((ctl & MSK_RST) != MSK_RST) { + _pkt_build_reset_from_pkt(&reset, pkt); + gnrc_netapi_send(gnrc_tcp_pid, reset); + } + return -ENOTCONN; + } + gnrc_pktbuf_release(pkt); + return 0; +} + +void *_event_loop(__attribute__((unused)) void *arg) +{ + msg_t msg; + msg_t reply; + + /* Store pid */ + gnrc_tcp_pid = thread_getpid(); + + /* Setup reply message */ + reply.type = GNRC_NETAPI_MSG_TYPE_ACK; + reply.content.value = (uint32_t)-ENOTSUP; + + /* Init message queue */ + msg_init_queue(_eventloop_msg_queue, TCP_EVENTLOOP_MSG_QUEUE_SIZE); + + /* Register GNRC TCPs handling thread in netreg */ + gnrc_netreg_entry_t entry; + gnrc_netreg_entry_init_pid(&entry, GNRC_NETREG_DEMUX_CTX_ALL, gnrc_tcp_pid); + gnrc_netreg_register(GNRC_NETTYPE_TCP, &entry); + + /* dispatch NETAPI messages */ + while (1) { + msg_receive(&msg); + switch (msg.type) { + /* Pass message up the network stack */ + case GNRC_NETAPI_MSG_TYPE_RCV: + DEBUG("gnrc_tcp_eventloop.c : _event_loop() : GNRC_NETAPI_MSG_TYPE_RCV\n"); + _receive((gnrc_pktsnip_t *)msg.content.ptr); + break; + + /* Pass message down the network stack */ + case GNRC_NETAPI_MSG_TYPE_SND: + DEBUG("gnrc_tcp_eventloop.c : _event_loop() : GNRC_NETAPI_MSG_TYPE_SND\n"); + _send((gnrc_pktsnip_t *)msg.content.ptr); + break; + + /* Reply to option set and set messages*/ + case GNRC_NETAPI_MSG_TYPE_SET: + case GNRC_NETAPI_MSG_TYPE_GET: + msg_reply(&msg, &reply); + break; + + /* Retransmission timer expired: Call FSM with retransmission event */ + case MSG_TYPE_RETRANSMISSION: + DEBUG("gnrc_tcp_eventloop.c : _event_loop() : MSG_TYPE_RETRANSMISSION\n"); + _fsm((gnrc_tcp_tcb_t *)msg.content.ptr, FSM_EVENT_TIMEOUT_RETRANSMIT, + NULL, NULL, 0); + break; + + /* Timewait timer expired: Call FSM with timewait event */ + case MSG_TYPE_TIMEWAIT: + DEBUG("gnrc_tcp_eventloop.c : _event_loop() : MSG_TYPE_TIMEWAIT\n"); + _fsm((gnrc_tcp_tcb_t *)msg.content.ptr, FSM_EVENT_TIMEOUT_TIMEWAIT, + NULL, NULL, 0); + break; + + default: + DEBUG("gnrc_tcp_eventloop.c : _event_loop() : received expected message\n"); + } + } + /* Never reached */ + return NULL; +} diff --git a/pool/shard006/C/0117728_test_plotstuff.c b/pool/shard006/C/0117728_test_plotstuff.c new file mode 100644 index 0000000000000000000000000000000000000000..c4d63f145db78044ac631e3029cf64a61a3cf03c --- /dev/null +++ b/pool/shard006/C/0117728_test_plotstuff.c @@ -0,0 +1,94 @@ +#include +#include +#include + +#include "cutest.h" +#include "plotstuff.h" +#include "plotfill.h" +#include "plotxy.h" +#include "plotimage.h" +#include "log.h" +#include "cairoutils.h" + +void test_plot_wcs1(CuTest* tc) { + plot_args_t myargs; + plot_args_t* pargs = &myargs; + int W, H; + plotxy_t* xy; + //plotimage_t* img; + + + log_init(LOG_VERB); + + W = H = 5; + plotstuff_init(pargs); + plotstuff_set_size(pargs, W, H); + pargs->outformat = PLOTSTUFF_FORMAT_PNG; + pargs->outfn = "test-out1.png"; + plotstuff_set_color(pargs, "black"); + plotstuff_run_command(pargs, "fill"); + plotstuff_output(pargs); + plotstuff_free(pargs); + + // perfectly centered circle. + plotstuff_init(pargs); + plotstuff_set_size(pargs, W, H); + pargs->outformat = PLOTSTUFF_FORMAT_PNG; + pargs->outfn = "test-out2.png"; + plotstuff_set_color(pargs, "black"); + plotstuff_run_command(pargs, "fill"); + xy = plotstuff_get_config(pargs, "xy"); + plot_xy_vals(xy, 3, 3); + plotstuff_set_color(pargs, "white"); + plotstuff_set_marker(pargs, "circle"); + plotstuff_set_markersize(pargs, 1); + plotstuff_run_command(pargs, "xy"); + plotstuff_output(pargs); + plotstuff_free(pargs); + + // perfectly centered circle. + plotstuff_init(pargs); + plotstuff_set_size(pargs, W, H); + pargs->outformat = PLOTSTUFF_FORMAT_PNG; + pargs->outfn = "test-out3.png"; + plotstuff_set_color(pargs, "black"); + plotstuff_run_command(pargs, "fill"); + xy = plotstuff_get_config(pargs, "xy"); + plot_xy_vals(xy, 2, 2); + plot_xy_set_offsets(xy, 0, 0); + plotstuff_set_color(pargs, "white"); + plotstuff_set_marker(pargs, "circle"); + plotstuff_set_markersize(pargs, 1); + plotstuff_run_command(pargs, "xy"); + plotstuff_output(pargs); + plotstuff_free(pargs); + + { + unsigned char* img; + int ww, hh; + int i; + + img = cairoutils_read_png("test-out2.png", &ww, &hh); + CuAssertPtrNotNull(tc, img); + CuAssertIntEquals(tc, W, ww); + CuAssertIntEquals(tc, H, hh); + + printf("image:\n"); + for (i=0; i +#include "xynth_.h" + +int s_list_init (s_list_t **li) +{ + (*li) = (s_list_t *) s_malloc(sizeof(s_list_t)); + if ((*li) == NULL) { + return -1; + } + (*li)->nb_elt = 0; + return 0; +} + +int s_list_uninit (s_list_t *li) +{ + s_free(li); + return 0; +} + +int s_list_eol (s_list_t *li, int i) +{ + if (li == NULL) { + return 1; + } + + if ((i >= 0) && (i < li->nb_elt)) { + return 0; + } + + /* end of list */ + return 1; +} + +void * s_list_get (s_list_t *li, int pos) +{ + int i = 0; + s_list_node_t *ntmp; + + if ((li == NULL) || (pos < 0) || (pos >= li->nb_elt)) { + /* element does not exist */ + return NULL; + } + + /* exist because nb_elt > 0 */ + ntmp = li->node; + + while (pos > i) { + i++; + ntmp = (s_list_node_t *) ntmp->next; + } + + return ntmp->element; +} + +int s_list_remove (s_list_t *li, int pos) +{ + int i = 0; + s_list_node_t *ntmp; + + if ((li == NULL) || (pos < 0) || (pos >= li->nb_elt)) { + /* element does not exist */ + return -1; + } + + /* exist because nb_elt > 0 */ + ntmp = li->node; + + if ((pos == 0)) { + /* special case */ + li->node = (s_list_node_t *) ntmp->next; + li->nb_elt--; + s_free(ntmp); + return li->nb_elt; + } + + while (pos > (i + 1)) { + i++; + ntmp = (s_list_node_t *) ntmp->next; + } + + /* insert new node */ + { + s_list_node_t *remnode; + + remnode = (s_list_node_t *) ntmp->next; + ntmp->next = ((s_list_node_t *) ntmp->next)->next; + s_free(remnode); + li->nb_elt--; + } + + return li->nb_elt; +} + +int s_list_add (s_list_t *li, void *el, int pos) +{ + int i = 0; + s_list_node_t *ntmp; + + if (li == NULL) { + return -1; + } + + if ((pos == -1) || (pos >= li->nb_elt)) { + /* insert at the end */ + pos = li->nb_elt; + } + + if (li->nb_elt == 0) { + li->node = (s_list_node_t *) s_malloc(sizeof(s_list_node_t)); + li->node->element = el; + li->nb_elt++; + return li->nb_elt; + } + + /* exist because nb_elt > 0 */ + ntmp = li->node; + + if (pos == 0) { + li->node = (s_list_node_t *) s_malloc(sizeof(s_list_node_t)); + li->node->element = el; + li->node->next = ntmp; + li->nb_elt++; + return li->nb_elt; + } + + /* pos = 0 insert before first elt */ + while (pos > (i + 1)) { + i++; + /* when pos > i next node exist */ + ntmp = (s_list_node_t *) ntmp->next; + } + + /* if pos == nb_elt next node does not exist */ + if (pos == li->nb_elt) { + ntmp->next = (s_list_node_t *) s_malloc(sizeof(s_list_node_t)); + ntmp = (s_list_node_t *) ntmp->next; + ntmp->element = el; + li->nb_elt++; + return li->nb_elt; + } + + /* here pos == i so next node is where we want to insert new node */ + { + s_list_node_t *nextnode = (s_list_node_t *) ntmp->next; + ntmp->next = (s_list_node_t *) s_malloc(sizeof(s_list_node_t)); + ntmp = (s_list_node_t *) ntmp->next; + ntmp->element = el; + ntmp->next = nextnode; + li->nb_elt++; + } + + return li->nb_elt; +} + +void * s_list_find (s_list_t *list, void *node, int (*cmp_func) (void *, void *)) +{ + int pos = 0; + void *tmp = NULL; + + while (!s_list_eol(list, pos)) { + void *node_; + node_ = s_list_get(list, pos); + if (cmp_func(node, node_) == 0) { + tmp = node_; + break; + } + pos++; + } + + return tmp; +} + +int s_list_get_pos (s_list_t *list, void *node) +{ + int pos = 0; + + while (!s_list_eol(list, pos)) { + void *node_; + node_ = s_list_get(list, pos); + if (node_ == node) { + return pos; + } + pos++; + } + + return -1; +} diff --git a/pool/shard006/C/0117736_GUIDEV_Usage.c b/pool/shard006/C/0117736_GUIDEV_Usage.c new file mode 100644 index 0000000000000000000000000000000000000000..7bee8c6ab022cf226286f745fdcccc4741d65405 --- /dev/null +++ b/pool/shard006/C/0117736_GUIDEV_Usage.c @@ -0,0 +1,85 @@ +/********************************************************************* +* SEGGER MICROCONTROLLER SYSTEME GmbH * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 1996 - 2004 SEGGER Microcontroller Systeme GmbH * +* * +* Internet: www.segger.com Support: support@segger.com * +* * +********************************************************************** + +***** emWin - Graphical user interface for embedded applications ***** +emWin is protected by international copyright laws. Knowledge of the +source code may not be used to write a similar product. This file may +only be used in accordance with a license and should not be re- +distributed in any way. We appreciate your understanding and fairness. +---------------------------------------------------------------------- +File : GUIDEV_Usage.C +Purpose : Implementation of memory devices +---------------------------END-OF-HEADER------------------------------ +*/ + + +#include +#include "GUI_Protected.h" +#include "GUIDebug.h" + +/* Memory device capabilities are compiled only if support for them is enabled.*/ +#if GUI_SUPPORT_MEMDEV + +/********************************************************************* +* +* public code +* +********************************************************************** +*/ +/********************************************************************* +* +* GUI_USAGE_Select +*/ +void GUI_USAGE_Select(GUI_USAGE_Handle hUsage) { + GUI_MEMDEV * pDev; + GUI_LOCK(); + pDev = GUI_MEMDEV_H2P(GUI_Context.hDevData); + pDev->hUsage = hUsage; + GUI_UNLOCK(); +} + +/********************************************************************* +* +* GUI_USAGE_DecUseCnt +* +* Purpose: Decrements the usage count and deletes the usage object if +* the counter reaches 0. +*/ +void GUI_USAGE_DecUseCnt(GUI_USAGE_Handle hUsage) { + GUI_USAGE* pThis; + GUI_LOCK(); + pThis = GUI_USAGE_H2P(hUsage); + if (--pThis->UseCnt == 0) { + GUI_ALLOC_Free(hUsage); + } + GUI_UNLOCK(); +} + +/********************************************************************* +* +* GUI_USAGE_AddRect +* +* Parameters: +* hUsage: Handle to usage object. May not be 0 ! +*/ +void GUI_USAGE_AddRect(GUI_USAGE* pUsage, int x0, int y0, int xSize, int ySize) { + do { + GUI_USAGE_AddHLine(pUsage, x0, y0++, xSize); + } while (--ySize); +} + +#else + +void GUIDEV_Usage(void) {} /* avoid empty object files */ + +#endif /* GUI_SUPPORT_MEMDEV */ + +/*************************** end of file ****************************/ diff --git a/pool/shard006/C/0117737_node.c b/pool/shard006/C/0117737_node.c new file mode 100644 index 0000000000000000000000000000000000000000..0bf357bf7d3d385dd4332b4dd24cc8f1e1f25c18 --- /dev/null +++ b/pool/shard006/C/0117737_node.c @@ -0,0 +1,297 @@ +/* + * Copyright (C) 2018 Red Hat, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 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 . + * + * Author: Gris Ge + */ +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +/* ^ For strerror_r() */ +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "libopeniscsiusr/libopeniscsiusr.h" +#include "misc.h" +#include "node.h" + +/* ptr is both input and output pointer. + * count is both input and output pointer. + * When success, both count and ptr will be updated. + * If fail, return LIBISCSI_ERR_NOMEM and no touch to old memory. + */ +static int _grow_node_array(struct iscsi_context *ctx, + struct iscsi_node ***nodes, uint32_t *count) +{ + int rc = LIBISCSI_OK; + struct iscsi_node **tmp = NULL; + uint32_t i = 0; + + _debug(ctx, "Growing node array from size %" PRIu32 " to %" PRIu32, + *count, *count * 2); + + tmp = realloc(*nodes, *count * 2 * sizeof(struct iscsi_node *)); + _alloc_null_check(ctx, tmp, rc, out); + for (i = *count; i < *count * 2; ++i) + tmp[i] = NULL; + + *count *= 2; + *nodes = tmp; + +out: + return rc; +} + +static int nodes_append(struct iscsi_context *ctx, struct iscsi_node ***nodes, + uint32_t *real_node_count, uint32_t *array_size, + struct iscsi_node *node) +{ + int rc = LIBISCSI_OK; + if (*real_node_count >= *array_size) + _good(_grow_node_array(ctx, nodes, array_size), rc, out); + + (*nodes)[(*real_node_count)++] = node; + +out: + return rc; +} + +int iscsi_nodes_get(struct iscsi_context *ctx, struct iscsi_node ***nodes, + uint32_t *node_count) +{ + int rc = LIBISCSI_OK; + struct dirent **namelist = NULL; + int n = 0; + int i = 0; + int j = 0; + int k = 0; + struct iscsi_node *node = NULL; + uint32_t real_node_count = 0; + const char *target_name = NULL; + const char *portal = NULL; + const char *iface_name = NULL; + struct dirent **namelist_portals = NULL; + int p = 0; + struct dirent **namelist_ifaces = NULL; + int f = 0; + char *target_path = NULL; + char *path = NULL; + struct stat path_stat; + char strerr_buff[_STRERR_BUFF_LEN]; + + assert(ctx != NULL); + assert(nodes != NULL); + assert(node_count != NULL); + + *nodes = NULL; + *node_count = 0; + + _good(_idbm_lock(ctx), rc, out); + + _good(_scandir(ctx, NODE_CONFIG_DIR, &namelist, &n), rc, out); + _debug(ctx, "Got %d target from %s nodes folder", n, NODE_CONFIG_DIR); + /* + * If continue with n == 0, calloc() might return a memory which failed + * to be freed in iscsi_nodes_free() + * + * So here just goto out to exit if n == 0 + */ + if (n == 0) + goto out; + + *node_count = n & UINT32_MAX; + *nodes = (struct iscsi_node **) calloc(*node_count, + sizeof(struct iscsi_node *)); + _alloc_null_check(ctx, *nodes, rc, out); + + // New style of nodes folder: + // /
,,/ + // Old style of nodes folder: + // /
, + + for (i = 0; i < n; ++i) { + target_name = namelist[i]->d_name; + _good(_asprintf(&target_path, "%s/%s", NODE_CONFIG_DIR, + target_name), rc, out); + _good(_scandir(ctx, target_path, &namelist_portals, &p), + rc, out); + _debug(ctx, "Got %d portals from %s folder", p, target_path); + free(target_path); + target_path = NULL; + for (j = 0; j < p; ++j) { + portal = namelist_portals[j]->d_name; + _good(_asprintf(&path, "%s/%s/%s", NODE_CONFIG_DIR, + target_name, portal), rc, out); + if (stat(path, &path_stat) != 0) { + _warn(ctx, "Cannot stat path '%s': %d, %s", + path, errno, + _strerror(errno, strerr_buff)); + continue; + } + if (S_ISREG(path_stat.st_mode)) { + // Old style of node + _good(_idbm_node_get(ctx, target_name, portal, + NULL, &node), + rc, out); + _good(nodes_append(ctx, nodes, + &real_node_count, + node_count, node), + rc, out); + continue; + } + if (! S_ISDIR(path_stat.st_mode)) { + _warn(ctx, "Invalid iSCSI node configuration " + "file %s, it should be a file or " + "directory.", path); + rc = LIBISCSI_ERR_IDBM; + goto out; + } + _good(_scandir(ctx, path, &namelist_ifaces, &f), rc, + out); + _debug(ctx, "Got %d ifaces from %s folder", f, path); + for (k = 0; k < f; ++k) { + iface_name = namelist_ifaces[k]->d_name; + _good(_idbm_node_get(ctx, target_name, portal, + iface_name, &node), + rc, out); + _good(nodes_append(ctx, nodes, + &real_node_count, + node_count, node), + rc, out); + } + free(path); + path = NULL; + _scandir_free(namelist_ifaces, f); + namelist_ifaces = NULL; + f = 0; + } + _scandir_free(namelist_portals, p); + namelist_portals = NULL; + p = 0; + } + + *node_count = real_node_count; + +out: + free(path); + free(target_path); + _scandir_free(namelist, n); + _scandir_free(namelist_portals, p); + _scandir_free(namelist_ifaces, f); + _idbm_unlock(ctx); + if (rc != LIBISCSI_OK) { + iscsi_nodes_free(*nodes, *node_count); + *nodes = NULL; + *node_count = 0; + } + return rc; +} + +void iscsi_nodes_free(struct iscsi_node **nodes, uint32_t node_count) +{ + uint32_t i = 0; + + if ((nodes == NULL) || (node_count == 0)) + return; + + for (i = 0; i < node_count; ++i) + iscsi_node_free(nodes[i]); + free (nodes); +} + +void iscsi_node_free(struct iscsi_node *node) +{ + free(node); +} + +const char *iscsi_node_dump_config(struct iscsi_node *node, bool show_secret) +{ + FILE *f = NULL; + char *buff = NULL; + + assert(node != NULL); + + buff = calloc(1, IDBM_DUMP_SIZE); + if (buff == NULL) + return NULL; + + f = fmemopen(buff, IDBM_DUMP_SIZE - 1, "w"); + if (f == NULL) { + free(buff); + return NULL; + } + + _idbm_node_print(node, f, show_secret); + + fclose(f); + + return buff; +} + +void iscsi_node_print_config(struct iscsi_node *node, bool show_secret) +{ + assert(node != NULL); + _idbm_node_print(node, stdout, show_secret); +} + +// TODO(Gris Ge): Convert below duplicated codes to macros. +bool iscsi_node_conn_is_ipv6(struct iscsi_node *node) +{ + assert(node != NULL); + return node->conn.is_ipv6; +} + +const char *iscsi_node_conn_address_get(struct iscsi_node *node) +{ + assert(node != NULL); + return node->conn.address; +} + +uint32_t iscsi_node_conn_port_get(struct iscsi_node *node) +{ + assert(node != NULL); + return node->conn.port; +} + +int32_t iscsi_node_tpgt_get(struct iscsi_node *node) +{ + assert(node != NULL); + return node->tpgt; +} + +const char *iscsi_node_target_name_get(struct iscsi_node *node) +{ + assert(node != NULL); + return node->target_name; +} + +const char *iscsi_node_iface_name_get(struct iscsi_node *node) +{ + assert(node != NULL); + return node->iface.name; +} + +const char *iscsi_node_portal_get(struct iscsi_node *node) +{ + assert(node != NULL); + return node->portal; +} diff --git a/pool/shard006/C/0117743_main.c b/pool/shard006/C/0117743_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c5245bbb138d0eca1bff135c6d023df65225fde2 --- /dev/null +++ b/pool/shard006/C/0117743_main.c @@ -0,0 +1,308 @@ +#include "main.h" + +int main(int argc, char **argv) +{ + Options o = parseOptions(argc, argv); + + /* for when the window is resized */ + /*signal(SIGWINCH, resizeBoard);*/ + char *homePath = getenv("HOME"); + char *highscorePath = malloc(1024); + snprintf(highscorePath, 1024, "%s/%s", homePath, HIGHSCORE_FILE); + + initNCurses(o.color.argument); + + if (COLS < 41 || LINES < 6) { + endwin(); + fprintf(stderr, "The terminal window needs to be at least 41"); + fprintf(stderr, " chars wide and 6 lines high.\n"); + exit(EXIT_FAILURE); + } + + + Board *b = initGame(COLS, LINES, highscorePath); + if (b == NULL) { + endwin(); + fprintf(stderr, "Could not initialize the board.\n"); + exit(EXIT_FAILURE); + } + + if (o.remote.set == true) { + mlog("opening connection at %s", o.port.argument); + b->listenConnection = openListenConnection(o.port.argument); + if (b->listenConnection == NULL) { + fprintf(stderr, "Could not open socket to listen: %s", + strerror(errno)); + exit(EXIT_FAILURE); + } + b->remote = true; + mlog("connection opened"); + } else { + if (o.ai.set == true) { + mlog("ai steering"); + b->ai = true; + /*init_ai(b->width, b->height);*/ + } else { + mlog("local human steering"); + b->ai = false; + b->listenConnection = NULL; + b->remote = false; + } + } + + if (o.growthSpeed.set != true) { + mlog("setting grow speed to 1"); + o.growthSpeed.argument = "1"; + o.growthSpeed.set = true; + } + + if (o.movementSpeed.set != true) { + o.movementSpeed.argument = "1"; + o.movementSpeed.set = true; + } + + b->snake->growthSpeed = atoi(o.growthSpeed.argument); + /*b->movementSpeed = atoi(o.movementSpeed.argument);*/ + mlog("growthspeed = %d", b->snake->growthSpeed); + + /* run the gaem */ + int toReturn = gameLoop(b); + + writeHighscoreToFile(highscorePath, b->highscore); + + + /* memory deallocation */ + freeSnake(b->snake); + freeHighscoreTable(b->highscore); + free(highscorePath); + if (b->listenConnection != NULL) { + freeConnection(b->listenConnection); + } + free(b); + + return toReturn; +} + +/*void resizeBoard(int i)*/ +/*{*/ + /*windowIsResized = true;*/ +/*}*/ + +void setBoardWidthHeight(Board *b, int windowCols, int windowRows) +{ + /* set width and height */ + b->width = windowCols; + b->height = windowRows; +} + +Board* initGame(int width, int height, char *highscorePath) + +{ + /* the snake board */ + Board *b = (Board *) malloc(sizeof(Board)); + + setBoardWidthHeight(b, COLS, LINES-2); + + /* load highscore */ + if ((b->highscore = loadHighscoreFromFile(highscorePath)) == NULL) { + endwin(); + printf("highscore not loaded"); + return NULL; + } + + /* setup the food segment */ + b->foodSegment.type = FOOD; + b->foodSegment.drawingCharacter = ACS_DIAMOND; + b->foodSegment.color_pair = COLOR_PAIR(FOOD_COLOR); + + b->snake = newSnake(b->width/2, b->height/2); + /* use the reset function to init the rest */ + resetGame(b); + + return b; +} + +void initNCurses(char *snakeColor) +{ + /*init ncurses*/ + initscr(); + + /* use colours */ + start_color(); + + /* get keys as they are pressed */ + cbreak(); + + /* don't echo the keys as the are pressed */ + noecho(); + + /* prevent flushing on interrupt keys */ + intrflush(stdscr, FALSE); + + /* prevent blocking on getch() */ + nodelay(stdscr, TRUE); + + /* enable keypad (and arrow keys) */ + keypad(stdscr, TRUE); + + /* hide the cursor */ + curs_set(0); + + /* initialize the colours */ + int bodycolor = BODY_COLOR; + if (snakeColor == NULL) { + bodycolor = BODY_COLOR; + } else if (strcmp(snakeColor, "red") == 0) { + bodycolor = COLOR_RED; + } else if (strcmp(snakeColor, "green") == 0) { + bodycolor = COLOR_GREEN; + } else if (strcmp(snakeColor, "blue") == 0) { + bodycolor = COLOR_BLUE; + } else if (strcmp(snakeColor, "white") == 0) { + bodycolor = COLOR_WHITE; + } else if (strcmp(snakeColor, "yellow") == 0) { + bodycolor = COLOR_YELLOW; + } + init_color(COLOR_BLUE, 0, 0, 999); + init_pair(TEXT_COLOR, COLOR_WHITE, COLOR_BLACK); /* wall/text */ + init_pair(BODY_COLOR, bodycolor, COLOR_BLACK); /* body */ + init_pair(FOOD_COLOR, COLOR_GREEN, COLOR_BLACK); /* food */ + init_pair(TEXT_INPUT, COLOR_BLACK, COLOR_WHITE); /* text input */ + init_pair(HEAD_COLOR, COLOR_RED, COLOR_BLACK); /* text input */ +} + +int getTextInput(char *msg, char *dest, size_t bufflen) +{ + /* quit ncurses */ + endwin(); + + /* show the message */ + printf("%s", msg); + fflush(stdout); + + /* get the input */ + int toReturn = getline(&dest, &bufflen, stdin); + + /* trim the newline */ + dest[strlen(dest)-1] = '\0'; + + /* start ncurses again */ + refresh(); + + /* return something */ + if (toReturn <= 0) { + return 1; + } else { + return 0; + } +} + +void lose(Board *b, State *GameState) +{ + mlog("score: %d", b->snake->score); + + /* get the lowest score, the last one in the records array */ + int lowestScore; + if (b->highscore->count >= 10) { + lowestScore = b->highscore->records[9].score; + } else { + lowestScore = b->highscore->records[b->highscore->count-1].score; + } + + if (lowestScore < b->snake->score) { + /* get the name */ + char **text = (char **) malloc(3*sizeof(char **)); + text[0] = " YOU LOST! "; + text[1] = "Please enter your name for the highscore list."; + text[2] = " Press space to continue. "; + + drawTextWindowInMiddle(text, 3); + refresh(); + + char c; + while ((c = getch()) != ' ') { + usleep(10000); + } + + /* get the user's name */ + char *name = (char *) malloc(64); + if (getTextInput("What's your name? ", name, 64) != 0) { + *GameState = QUIT; + } + + /* the player has beaten someone, add the player to the + * highscore list */ + Record r = {.score = b->snake->score, + .timestamp = (long)time(NULL), .playerName=name}; + insertRecordAndSort(&r, b->highscore); + *GameState = HIGHSCORE; + free(text); + } else { + char **text = (char **) malloc(2*sizeof(char **)); + text[0] = " YOU LOST! "; + text[1] = "Press space to continue."; + + drawTextWindowInMiddle(text, 2); + refresh(); + + char c; + while ((c = getch()) != ' ') { + usleep(10000); + } + + free(text); + } + + resetGame(b); +} + +int gameLoop(Board *b) +{ + State GameState = PLAYING; + while (true) { + /* check if the window is resized */ + /*if (windowIsResized == true) {*/ + /*windowIsResized = false;*/ + /*setBoardWidthHeight(b, COLS, LINES-2);*/ + /*}*/ + + if (b->remote == true) { + /* listen for an INPUT message */ + getNetworkInput(b->snake, b->listenConnection, + &GameState); + } else { + if (b->ai) { + /*getAiInput(b->snake, &b->foodSegment);*/ + } else { + /* get local from a human */ + getLocalInput(b->snake, &GameState); + } + } + + switch (GameState) { + case PLAYING: + /* update the game */ + update(b); + /* check if the player has lost, this function + * also handles the food */ + if (hasPlayerLost(b) == true) { + lose(b, &GameState); + } + break; + case QUIT: + endwin(); + return 0; + default: + break; + + } + + if (draw(b, &GameState) != 0) { + /* there was an error */ + return 1; + } + + /* wait */ + usleep(SleepingTime); + } +} diff --git a/pool/shard006/C/0117749_sys_exits.c b/pool/shard006/C/0117749_sys_exits.c new file mode 100644 index 0000000000000000000000000000000000000000..1e628d785db3c09f1552ac9c6bc324112dc2a47e --- /dev/null +++ b/pool/shard006/C/0117749_sys_exits.c @@ -0,0 +1,143 @@ +/*++ +/* NAME +/* sys_exits 3 +/* SUMMARY +/* sendmail-compatible exit status handling +/* SYNOPSIS +/* #include +/* +/* typedef struct { +/* .in +4 +/* int status; /* exit status */ +/* const char *dsn; /* RFC 3463 */ +/* const char *text; /* free text */ +/* .in -4 +/* } SYS_EXITS_DETAIL; +/* +/* int SYS_EXITS_CODE(code) +/* int code; +/* +/* const char *sys_exits_strerror(code) +/* int code; +/* +/* const SYS_EXITS_DETAIL *sys_exits_detail(code) +/* int code; +/* +/* int sys_exits_softerror(code) +/* int code; +/* DESCRIPTION +/* This module interprets sendmail-compatible process exit status +/* codes. +/* +/* SYS_EXITS_CODE() returns non-zero when the specified code +/* is a sendmail-compatible process exit status code. +/* +/* sys_exits_strerror() returns a descriptive text for the +/* specified sendmail-compatible status code, or a generic +/* text for an unknown status code. +/* +/* sys_exits_detail() returns a table entry with assorted +/* information about the specified sendmail-compatible status +/* code, or a generic entry for an unknown status code. +/* The generic entry may be overwritten with each sys_exits_detail() +/* call. +/* +/* sys_exits_softerror() returns non-zero when the specified +/* sendmail-compatible status code corresponds to a recoverable error. +/* An unknown status code is always unrecoverable. +/* DIAGNOSTICS +/* Fatal: out of memory. +/* LICENSE +/* .ad +/* .fi +/* The Secure Mailer license must be distributed with this software. +/* AUTHOR(S) +/* Wietse Venema +/* IBM T.J. Watson Research +/* P.O. Box 704 +/* Yorktown Heights, NY 10598, USA +/*--*/ + +/* System library. */ + +#include + +/* Utility library. */ + +#include +#include + +/* Global library. */ + +#include + +/* Application-specific. */ + +static const SYS_EXITS_DETAIL sys_exits_table[] = { + EX_USAGE, "5.3.0", "command line usage error", + EX_DATAERR, "5.6.0", "data format error", + EX_NOINPUT, "5.3.0", "cannot open input", + EX_NOUSER, "5.1.1", "user unknown", + EX_NOHOST, "5.1.2", "host name unknown", + EX_UNAVAILABLE, "5.3.0", "service unavailable", + EX_SOFTWARE, "5.3.0", "internal software error", + EX_OSERR, "4.3.0", "system resource problem", + EX_OSFILE, "5.3.0", "critical OS file missing", + EX_CANTCREAT, "5.2.0", "can't create user output file", + EX_IOERR, "5.3.0", "input/output error", + EX_TEMPFAIL, "4.3.0", "temporary failure", + EX_PROTOCOL, "5.5.0", "remote error in protocol", + EX_NOPERM, "5.7.0", "permission denied", + EX_CONFIG, "5.3.5", "local configuration error", +}; + +static VSTRING *sys_exits_def_text = 0; + +static SYS_EXITS_DETAIL sys_exits_default[] = { + 0, "5.3.0", 0, +}; + +/* sys_exits_fake - fake an entry for an unknown code */ + +static SYS_EXITS_DETAIL *sys_exits_fake(int code) +{ + if (sys_exits_def_text == 0) + sys_exits_def_text = vstring_alloc(30); + + vstring_sprintf(sys_exits_def_text, "unknown mail system error %d", code); + sys_exits_default->text = vstring_str(sys_exits_def_text); + return (sys_exits_default); +} + +/* sys_exits_strerror - map exit status to error string */ + +const char *sys_exits_strerror(int code) +{ + if (!SYS_EXITS_CODE(code)) { + return (sys_exits_fake(code)->text); + } else { + return (sys_exits_table[code - EX__BASE].text); + } +} + +/* sys_exits_detail - map exit status info table entry */ + +const SYS_EXITS_DETAIL *sys_exits_detail(int code) +{ + if (!SYS_EXITS_CODE(code)) { + return (sys_exits_fake(code)); + } else { + return (sys_exits_table + code - EX__BASE); + } +} + +/* sys_exits_softerror - determine if error is transient */ + +int sys_exits_softerror(int code) +{ + if (!SYS_EXITS_CODE(code)) { + return (sys_exits_default->dsn[0] == '4'); + } else { + return (sys_exits_table[code - EX__BASE].dsn[0] == '4'); + } +} diff --git a/pool/shard006/C/0117752_per_event_excludes.c b/pool/shard006/C/0117752_per_event_excludes.c new file mode 100644 index 0000000000000000000000000000000000000000..ad32a09a65400aed45aaa69b30a4842c394efa95 --- /dev/null +++ b/pool/shard006/C/0117752_per_event_excludes.c @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright 2014, Michael Ellerman, IBM Corp. + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include + +#include "event.h" +#include "lib.h" +#include "utils.h" + +/* + * Test that per-event excludes work. + */ + +static int per_event_excludes(void) +{ + struct event *e, events[4]; + int i; + + SKIP_IF(!have_hwcap2(PPC_FEATURE2_ARCH_2_07)); + + /* + * We need to create the events disabled, otherwise the running/enabled + * counts don't match up. + */ + e = &events[0]; + event_init_opts(e, PERF_COUNT_HW_INSTRUCTIONS, + PERF_TYPE_HARDWARE, "instructions"); + e->attr.disabled = 1; + + e = &events[1]; + event_init_opts(e, PERF_COUNT_HW_INSTRUCTIONS, + PERF_TYPE_HARDWARE, "instructions(k)"); + e->attr.disabled = 1; + e->attr.exclude_user = 1; + e->attr.exclude_hv = 1; + + e = &events[2]; + event_init_opts(e, PERF_COUNT_HW_INSTRUCTIONS, + PERF_TYPE_HARDWARE, "instructions(h)"); + e->attr.disabled = 1; + e->attr.exclude_user = 1; + e->attr.exclude_kernel = 1; + + e = &events[3]; + event_init_opts(e, PERF_COUNT_HW_INSTRUCTIONS, + PERF_TYPE_HARDWARE, "instructions(u)"); + e->attr.disabled = 1; + e->attr.exclude_hv = 1; + e->attr.exclude_kernel = 1; + + FAIL_IF(event_open(&events[0])); + + /* + * The open here will fail if we don't have per event exclude support, + * because the second event has an incompatible set of exclude settings + * and we're asking for the events to be in a group. + */ + for (i = 1; i < 4; i++) + FAIL_IF(event_open_with_group(&events[i], events[0].fd)); + + /* + * Even though the above will fail without per-event excludes we keep + * testing in order to be thorough. + */ + prctl(PR_TASK_PERF_EVENTS_ENABLE); + + /* Spin for a while */ + for (i = 0; i < INT_MAX; i++) + asm volatile("" : : : "memory"); + + prctl(PR_TASK_PERF_EVENTS_DISABLE); + + for (i = 0; i < 4; i++) { + FAIL_IF(event_read(&events[i])); + event_report(&events[i]); + } + + /* + * We should see that all events have enabled == running. That + * shows that they were all on the PMU at once. + */ + for (i = 0; i < 4; i++) + FAIL_IF(events[i].result.running != events[i].result.enabled); + + /* + * We can also check that the result for instructions is >= all the + * other counts. That's because it is counting all instructions while + * the others are counting a subset. + */ + for (i = 1; i < 4; i++) + FAIL_IF(events[0].result.value < events[i].result.value); + + for (i = 0; i < 4; i++) + event_close(&events[i]); + + return 0; +} + +int main(void) +{ + return test_harness(per_event_excludes, "per_event_excludes"); +} diff --git a/pool/shard006/C/0117753_bonus.c b/pool/shard006/C/0117753_bonus.c new file mode 100644 index 0000000000000000000000000000000000000000..47c9bd26ca198858d69a4c6ea4c06ae022182390 --- /dev/null +++ b/pool/shard006/C/0117753_bonus.c @@ -0,0 +1,110 @@ +/* + "Mroczna Harmonia" + Mikolaj Felix + mfelix@polbox.com +*/ + +void b_nadaj0(STATEK *bon) +{ + bon->aktywny=0; +} + +void bonus_inicjuj(STATEK *bon) +{ + int i,j=36; + bon->x=random(299); + bon->y=0; + bon->licznik=0; + for(i=0;i<6;i++) bon->klatka[i]=j+i; + bon->aktywny=1; + bon->k=0; +} + +void bonus_wykonaj(STATEK *bon,KAPSULA *kaps) +{ + if(bon->aktywny) + { + draw_sprite(sprite[bon->klatka[bon->k]],bon->x,bon->y,20,20); + + if((bon->licznik++)==12) + { + bon->licznik=0; + bon->k++; + if(bon->k>5) bon->k=0; + } + if((bon->y++)>179) bon->aktywny=0; + + if(bon->x>=kaps->x-10 && bon->x<=kaps->x+30 && + bon->y>=kaps->y && bon->y<=kaps->y+20) + { + play_sound(&soundtab[SND_BONUS]); + + bon->aktywny=0; + if(kaps->giwera<3) + { + w_inicjuj(kaps->x+10,kaps->y+10,31,32); + kaps->giwera++; + bonus_typ=NOWA_GIW; + } + else + { + pole_inicjuj(&pole); + bonus_typ=BONUS_POLE; + } + } + } +} + +void pole_nadaj0(POLE *p) +{ + p->aktywne=0; +} + +void pole_inicjuj(POLE *p) +{ + p->aktywne=1; + p->pom=0; + p->vpom=0; + p->r=10; + p->kolor=32; + p->czas=0; +} + +void pole_wykonaj(POLE *p,KAPSULA *kaps) +{ + int i,x,y; + if(p->aktywne) + { + if(!p->pom) + { + if((p->vpom++)==2) + { + p->vpom=0; + if((p->r++)>15) + { + p->pom=1; + p->kolor=44; + } + } + } + else + { + if((p->vpom++)==2) + { + p->vpom=0; + if((p->r--)<10) + { + p->pom=0; + p->kolor=32; + } + } + } + for(i=1;i<60;i++) + { + x=kaps->x+10+b_punkt[p->r][i][0]; + y=kaps->y+10-b_punkt[p->r][i][1]; + pixel(x,y,p->kolor); + } + if((p->czas++)==1500) p->aktywne=0; + } +} \ No newline at end of file diff --git a/pool/shard006/C/0117756_radiohead_ask.c b/pool/shard006/C/0117756_radiohead_ask.c new file mode 100644 index 0000000000000000000000000000000000000000..533da92552e8856516d423849d035d22816171c3 --- /dev/null +++ b/pool/shard006/C/0117756_radiohead_ask.c @@ -0,0 +1,174 @@ +#include "rtl_433.h" +#include "pulse_demod.h" +#include "util.h" + +// Transmitter speed in bits per seconds +#define RH_ASK_SPEED 2000 +#define RH_ASK_BIT_LEN (int)1e6/RH_ASK_SPEED + +// Maximum message length (including the headers, byte count and FCS) we are willing to support +// This is pretty arbitrary +#define RH_ASK_MAX_PAYLOAD_LEN 67 +#define RH_ASK_HEADER_LEN 4 +#ifndef RH_ASK_MAX_MESSAGE_LEN + #define RH_ASK_MAX_MESSAGE_LEN (RH_ASK_MAX_PAYLOAD_LEN - RH_ASK_HEADER_LEN - 3) +#endif + +uint8_t payload[RH_ASK_MAX_PAYLOAD_LEN] = {0}; +int data_payload[RH_ASK_MAX_MESSAGE_LEN]; + +// Note: all tje "4to6 code" came from RadioHead source code. +// see: http://www.airspayce.com/mikem/arduino/RadioHead/index.html + +// 4 bit to 6 bit symbol converter table +// Used to convert the high and low nybbles of the transmitted data +// into 6 bit symbols for transmission. Each 6-bit symbol has 3 1s and 3 0s +// with at most 3 consecutive identical bits +static uint8_t symbols[] = { + 0xd, 0xe, 0x13, 0x15, 0x16, 0x19, 0x1a, 0x1c, + 0x23, 0x25, 0x26, 0x29, 0x2a, 0x2c, 0x32, 0x34 +}; + +// Convert a 6 bit encoded symbol into its 4 bit decoded equivalent +uint8_t symbol_6to4(uint8_t symbol) +{ + uint8_t i; + // Linear search :-( Could have a 64 byte reverse lookup table? + // There is a little speedup here courtesy Ralph Doncaster: + // The shortcut works because bit 5 of the symbol is 1 for the last 8 + // symbols, and it is 0 for the first 8. + // So we only have to search half the table + for (i = (symbol>>2) & 8; i < 16 ; i++){ + if (symbol == symbols[i]) return i; + } + return 0xFF; // Not found +} + + +static int radiohead_ask_callback(bitbuffer_t *bitbuffer) { + // Get time + char time_str[LOCAL_TIME_BUFLEN]; + data_t *data; + local_time_str(0, time_str); + + uint8_t row = 0; // we are considering only first row + unsigned int len = bitbuffer->bits_per_row[row]; + + uint8_t msg_len = RH_ASK_MAX_MESSAGE_LEN; + unsigned int pos, nb_bytes; + uint8_t rxBits[2] = {0}; + + uint16_t crc, crc_recompute; + uint8_t data_len, header_to, header_from, header_id, header_flags; + + + // Looking for preamble + uint8_t init_pattern[] = { + 0x55, // 8 + 0x55, // 16 + 0x55, // 24 + 0x51, // 32 + 0xcd, // 40 + }; + // The first 0 is ignored by the decoder, so we look only for 28 bits of "01" + // and not 32. Also "0x1CD" is 0xb38 (RH_ASK_START_SYMBOL) with LSBit first. + uint8_t init_pattern_len = 40; + + pos = bitbuffer_search(bitbuffer, row, 0, init_pattern, init_pattern_len); + if(pos == len){ + if(debug_output) { + printf("RH ASK preamble not found\n"); + } + return 0; + } + + // read "bytes" of 12 bit + nb_bytes=0; + pos += init_pattern_len; + for(; pos < len && nb_bytes < msg_len; pos += 12){ + bitbuffer_extract_bytes(bitbuffer, row, pos, rxBits, /*len=*/16); + // ^ we should read 16 bits and not 12, elsewhere last 4bits are ignored + rxBits[0] = reverse8(rxBits[0]); + rxBits[1] = reverse8(rxBits[1]); + rxBits[1] = ((rxBits[1] & 0x0F)<<2) + (rxBits[0]>>6); + rxBits[0] &= 0x3F; + uint8_t hi_nibble = symbol_6to4(rxBits[0]); + if(hi_nibble > 0xF){ + if(debug_output){ + fprintf(stdout, "Error on 6to4 decoding high nibble: %X\n", rxBits[0]); + } + return 0; + } + uint8_t lo_nibble = symbol_6to4(rxBits[1]); + if(lo_nibble > 0xF){ + if(debug_output){ + fprintf(stdout, "Error on 6to4 decoding low nibble: %X\n", rxBits[1]); + } + return 0; + } + uint8_t byte = hi_nibble<<4 | lo_nibble; + payload[nb_bytes] = byte; + if(nb_bytes == 0){ + msg_len = byte; + } + nb_bytes++; + } + + // Get header + data_len = msg_len - RH_ASK_HEADER_LEN - 3; + header_to = payload[1]; + header_from = payload[2]; + header_id = payload[3]; + header_flags = payload[4]; + + // Check CRC + crc = payload[5 + data_len] + (payload[5 + data_len + 1]<<8); + crc_recompute = ~crc16(payload, msg_len-2, 0x8408, 0xFFFF); + if(crc_recompute != crc){ + if(debug_output){ + fprintf(stdout, "CRC error: %04X != %04X\n", crc_recompute, crc); + } + return 0; + } + + // Format data + for(int j=0; j + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * + * http://www.rtems.com/license/LICENSE. + * + * + * $Id: uart.c,v 1.6 2010/04/26 02:33:57 joel Exp $ +*/ +#include /* Must be before libio.h */ +#include +#include +#include + +/* Put the CPU (or UART) specific header file #include here */ +#include +#include +#include + +/* How many serial ports? */ +#define NUM_DEVS 1 + +int uart_poll_read(int minor); + +int dbg_dly; + +/* static function prototypes */ +static int uart_first_open(int major, int minor, void *arg); +static int uart_last_close(int major, int minor, void *arg); +static int uart_read(int minor); +static ssize_t uart_write(int minor, const char *buf, size_t len); +static void uart_init(int minor); +static void uart_write_polled(int minor, char c); +static int uart_set_attributes(int minor, const struct termios *t); + +/* These are used by code in console.c */ +unsigned long Console_Port_Count = NUM_DEVS; +console_data Console_Port_Data[NUM_DEVS]; + +/* rtems console uses the following minor number */ +rtems_device_minor_number Console_Port_Minor = 0; + +/* Pointers to functions for handling the UART. */ +console_fns uart_fns = +{ + libchip_serial_default_probe, + uart_first_open, + uart_last_close, + uart_read, + uart_write, + uart_init, + uart_write_polled, /* not used in this driver */ + uart_set_attributes, + FALSE /* TRUE if interrupt driven, FALSE if not. */ +}; + +/* + * There's one item in array for each UART. + * + * Some of these fields are marked "NOT USED". They are not used + * by console.c, but may be used by drivers in libchip + * + */ +console_tbl Console_Port_Tbl[] = { + { + "/dev/com0", /* sDeviceName */ + SERIAL_CUSTOM, /* deviceType */ + &uart_fns, /* pDeviceFns */ + NULL, /* deviceProbe */ + NULL, /* pDeviceFlow */ + 0, /* ulMargin - NOT USED */ + 0, /* ulHysteresis - NOT USED */ + NULL, /* pDeviceParams */ + 0, /* ulCtrlPort1 - NOT USED */ + 0, /* ulCtrlPort2 - NOT USED */ + 0, /* ulDataPort - NOT USED */ + NULL, /* getRegister - NOT USED */ + NULL, /* setRegister - NOT USED */ + NULL, /* getData - NOT USED */ + NULL, /* setData - NOT USED */ + 0, /* ulClock - NOT USED */ + 0 /* ulIntVector - NOT USED */ + } +}; + +/*********************************************************************/ +/* Functions called via termios callbacks (i.e. the ones in uart_fns */ +/*********************************************************************/ + +/* + * This is called the first time each device is opened. If the driver + * is interrupt driven, you should enable interrupts here. Otherwise, + * it's probably safe to do nothing. + * + * Since micromonitor already set up the UART, we do nothing. + */ +static int uart_first_open(int major, int minor, void *arg) +{ + return 0; +} + + +/* + * This is called the last time each device is closed. If the driver + * is interrupt driven, you should disable interrupts here. Otherwise, + * it's probably safe to do nothing. + */ +static int uart_last_close(int major, int minor, void *arg) +{ + return 0; +} + + +/* + * Read one character from UART. + * + * Return -1 if there's no data, otherwise return + * the character in lowest 8 bits of returned int. + */ +static int uart_read(int minor) +{ + char c; + + if (minor == 0) { + if (rUTRSTAT0 & 0x1) { + c = rURXH0 & 0xff; + return c; + } else { + return -1; + } + } else { + printk("Unknown console minor number: %d\n", minor); + return -1; + } + +} + + +/* + * Write buffer to UART + * + * return 1 on success, -1 on error + */ +static ssize_t uart_write(int minor, const char *buf, size_t len) +{ + int i; + + if (minor == 0) { + for (i = 0; i < len; i++) { + /* Wait for fifo to have room */ + while(!(rUTRSTAT0 & 0x2)) { + continue; + } + + rUTXH0 = (char) buf[i]; + } + } else { + printk("Unknown console minor number: %d\n", minor); + return -1; + } + + return 1; +} + + +/* Set up the UART. */ +static void uart_init(int minor) +{ + int i; + unsigned int reg = 0; + + /* enable UART0 */ + rCLKCON|=0x100; + + /* value is calculated so : (int)(PCLK/16./baudrate) -1 */ + reg = get_PCLK() / (16 * 115200) - 1; + + /* FIFO enable, Tx/Rx FIFO clear */ + rUFCON0 = 0x07; + rUMCON0 = 0x0; + /* Normal,No parity,1 stop,8 bit */ + rULCON0 = 0x3; + /* + * tx=level,rx=edge,disable timeout int.,enable rx error int., + * normal,interrupt or polling + */ + rUCON0 = 0x245; + rUBRDIV0 = reg; + + for (i = 0; i < 100; i++); + +} + +/* I'm not sure this is needed for the shared console driver. */ +static void uart_write_polled(int minor, char c) +{ + uart_write(minor, &c, 1); +} + +/* This is for setting baud rate, bits, etc. */ +static int uart_set_attributes(int minor, const struct termios *t) +{ + return 0; +} + +/***********************************************************************/ +/* + * The following functions are not used by TERMIOS, but other RTEMS + * functions use them instead. + */ +/***********************************************************************/ +/* + * Read from UART. This is used in the exit code, and can't + * rely on interrupts. +*/ +int uart_poll_read(int minor) +{ + return uart_read(minor); +} + + +/* + * Write a character to the console. This is used by printk() and + * maybe other low level functions. It should not use interrupts or any + * RTEMS system calls. It needs to be very simple + */ +static void _BSP_put_char( char c ) { + uart_write_polled(0, c); + if (c == '\n') { + uart_write_polled(0, '\r'); + } +} + +BSP_output_char_function_type BSP_output_char = _BSP_put_char; + +static int _BSP_get_char(void) +{ + return uart_poll_read(0); +} + +BSP_polling_getchar_function_type BSP_poll_char = _BSP_get_char; diff --git a/pool/shard006/C/0117771_strtoul.c b/pool/shard006/C/0117771_strtoul.c new file mode 100644 index 0000000000000000000000000000000000000000..3001579dfaa93bb4800c797cbef1a50aa7873934 --- /dev/null +++ b/pool/shard006/C/0117771_strtoul.c @@ -0,0 +1,31 @@ +/* copyright(C) 2003 H.Kawai (under KL-01). */ + +#include "errno.h" + +unsigned long strtoul0(const char **ps, int base, char *errflag); + +unsigned long strtoul(const char *s, const char **endp, int base) +{ + const char *s0 = s, *s1; + char sign = 0, errflag; + unsigned long val; + while (*s != '\0' && *s <= ' ') + s++; + if (*s == '-') { + sign = 1; + s++; + } + while (*s != '\0' && *s <= ' ') + s++; + s1 = s; + val = strtoul0(&s, base, &errflag); + if (s == s1) + s = s0; + if (endp) + *endp = s; + if (errflag == 0 && sign != 0) + val = - val; + if (errflag) + errno = ERANGE; + return val; +} diff --git a/pool/shard006/C/0117772_hostlist_eth.c b/pool/shard006/C/0117772_hostlist_eth.c new file mode 100644 index 0000000000000000000000000000000000000000..28222c0f89e1f9a1d120e18e930a5d312ab6b11e --- /dev/null +++ b/pool/shard006/C/0117772_hostlist_eth.c @@ -0,0 +1,88 @@ +/* hostlist_eth.c 2004 Ian Schorr + * modified from endpoint_talkers_eth.c 2003 Ronnie Sahlberg + * + * $Id$ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include + +#include "epan/packet.h" +#include +#include +#include + +#include "../stat_menu.h" + +#include "ui/gtk/gui_stat_menu.h" +#include "ui/gtk/hostlist_table.h" + + +static int +eth_hostlist_packet(void *pit, packet_info *pinfo, epan_dissect_t *edt _U_, const void *vip) +{ + hostlist_table *hosts=(hostlist_table *)pit; + const eth_hdr *ehdr=vip; + + /* Take two "add" passes per packet, adding for each direction, ensures that all + packets are counted properly (even if address is sending to itself) + XXX - this could probably be done more efficiently inside hostlist_table */ + add_hostlist_table_data(hosts, &ehdr->src, 0, TRUE, 1, pinfo->fd->pkt_len, SAT_ETHER, PT_NONE); + add_hostlist_table_data(hosts, &ehdr->dst, 0, FALSE, 1, pinfo->fd->pkt_len, SAT_ETHER, PT_NONE); + + return 1; +} + + + +static void +gtk_eth_hostlist_init(const char *optarg, + void* userdata _U_) +{ + const char *filter=NULL; + + if(!strncmp(optarg,"hosts,eth,",10)){ + filter=optarg+10; + } else { + filter=NULL; + } + + init_hostlist_table(TRUE, "Ethernet", "eth", filter, eth_hostlist_packet); + +} + +void +gtk_eth_hostlist_cb(GtkAction *action _U_, gpointer user_data _U_) +{ + gtk_eth_hostlist_init("hosts,eth",NULL); +} + +void +register_tap_listener_eth_hostlist(void) +{ + register_stat_cmd_arg("hosts,eth", gtk_eth_hostlist_init,NULL); + register_hostlist_table(TRUE, "Ethernet", "eth", NULL /*filter*/, eth_hostlist_packet); +} diff --git a/pool/shard006/C/0117777_mkdir.c b/pool/shard006/C/0117777_mkdir.c new file mode 100644 index 0000000000000000000000000000000000000000..596f41d9d8edac63ba8a3dce33a9198b85a16582 --- /dev/null +++ b/pool/shard006/C/0117777_mkdir.c @@ -0,0 +1,215 @@ +/* mkdir -- make directories + Copyright (C) 1990, 1995-2002, 2004-2011 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 . */ + +/* David MacKenzie */ + +#include +#include +#include +#include +#include + +#include "system.h" +#include "error.h" +#include "mkdir-p.h" +#include "modechange.h" +#include "prog-fprintf.h" +#include "quote.h" +#include "savewd.h" + +/* The official name of this program (e.g., no `g' prefix). */ +#define PROGRAM_NAME "mkdir" + +#define AUTHORS proper_name ("David MacKenzie") + +static struct option const longopts[] = +{ + {GETOPT_SELINUX_CONTEXT_OPTION_DECL}, + {"mode", required_argument, NULL, 'm'}, + {"parents", no_argument, NULL, 'p'}, + {"verbose", no_argument, NULL, 'v'}, + {GETOPT_HELP_OPTION_DECL}, + {GETOPT_VERSION_OPTION_DECL}, + {NULL, 0, NULL, 0} +}; + +void +usage (int status) +{ + if (status != EXIT_SUCCESS) + fprintf (stderr, _("Try `%s --help' for more information.\n"), + program_name); + else + { + printf (_("Usage: %s [OPTION]... DIRECTORY...\n"), program_name); + fputs (_("\ +Create the DIRECTORY(ies), if they do not already exist.\n\ +\n\ +"), stdout); + fputs (_("\ +Mandatory arguments to long options are mandatory for short options too.\n\ +"), stdout); + fputs (_("\ + -m, --mode=MODE set file mode (as in chmod), not a=rwx - umask\n\ + -p, --parents no error if existing, make parent directories as needed\n\ + -v, --verbose print a message for each created directory\n\ + -Z, --context=CTX set the SELinux security context of each created\n\ + directory to CTX\n\ +"), stdout); + fputs (HELP_OPTION_DESCRIPTION, stdout); + fputs (VERSION_OPTION_DESCRIPTION, stdout); + emit_ancillary_info (); + } + exit (status); +} + +/* Options passed to subsidiary functions. */ +struct mkdir_options +{ + /* Function to make an ancestor, or NULL if ancestors should not be + made. */ + int (*make_ancestor_function) (char const *, char const *, void *); + + /* Mode for ancestor directory. */ + mode_t ancestor_mode; + + /* Mode for directory itself. */ + mode_t mode; + + /* File mode bits affected by MODE. */ + mode_t mode_bits; + + /* If not null, format to use when reporting newly made directories. */ + char const *created_directory_format; +}; + +/* Report that directory DIR was made, if OPTIONS requests this. */ +static void +announce_mkdir (char const *dir, void *options) +{ + struct mkdir_options const *o = options; + if (o->created_directory_format) + prog_fprintf (stdout, o->created_directory_format, quote (dir)); +} + +/* Make ancestor directory DIR, whose last component is COMPONENT, + with options OPTIONS. Assume the working directory is COMPONENT's + parent. Return 0 if successful and the resulting directory is + readable, 1 if successful but the resulting directory is not + readable, -1 (setting errno) otherwise. */ +static int +make_ancestor (char const *dir, char const *component, void *options) +{ + struct mkdir_options const *o = options; + int r = mkdir (component, o->ancestor_mode); + if (r == 0) + { + r = ! (o->ancestor_mode & S_IRUSR); + announce_mkdir (dir, options); + } + return r; +} + +/* Process a command-line file name. */ +static int +process_dir (char *dir, struct savewd *wd, void *options) +{ + struct mkdir_options const *o = options; + return (make_dir_parents (dir, wd, o->make_ancestor_function, options, + o->mode, announce_mkdir, + o->mode_bits, (uid_t) -1, (gid_t) -1, true) + ? EXIT_SUCCESS + : EXIT_FAILURE); +} + +int +main (int argc, char **argv) +{ + const char *specified_mode = NULL; + int optc; + security_context_t scontext = NULL; + struct mkdir_options options; + + options.make_ancestor_function = NULL; + options.mode = S_IRWXUGO; + options.mode_bits = 0; + options.created_directory_format = NULL; + + initialize_main (&argc, &argv); + set_program_name (argv[0]); + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + + atexit (close_stdout); + + while ((optc = getopt_long (argc, argv, "pm:vZ:", longopts, NULL)) != -1) + { + switch (optc) + { + case 'p': + options.make_ancestor_function = make_ancestor; + break; + case 'm': + specified_mode = optarg; + break; + case 'v': /* --verbose */ + options.created_directory_format = _("created directory %s"); + break; + case 'Z': + scontext = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } + } + + if (optind == argc) + { + error (0, 0, _("missing operand")); + usage (EXIT_FAILURE); + } + + if (scontext && setfscreatecon (scontext) < 0) + error (EXIT_FAILURE, errno, + _("failed to set default file creation context to %s"), + quote (scontext)); + + if (options.make_ancestor_function || specified_mode) + { + mode_t umask_value = umask (0); + + options.ancestor_mode = (S_IRWXUGO & ~umask_value) | (S_IWUSR | S_IXUSR); + + if (specified_mode) + { + struct mode_change *change = mode_compile (specified_mode); + if (!change) + error (EXIT_FAILURE, 0, _("invalid mode %s"), + quote (specified_mode)); + options.mode = mode_adjust (S_IRWXUGO, true, umask_value, change, + &options.mode_bits); + free (change); + } + else + options.mode = S_IRWXUGO & ~umask_value; + } + + exit (savewd_process_files (argc - optind, argv + optind, + process_dir, &options)); +} diff --git a/pool/shard006/C/0117782_reed_solomon.c b/pool/shard006/C/0117782_reed_solomon.c new file mode 100644 index 0000000000000000000000000000000000000000..1e452ac4c71df95a4031f614debe98bc9246bb9e --- /dev/null +++ b/pool/shard006/C/0117782_reed_solomon.c @@ -0,0 +1,237 @@ + + +#include +#include +#include +#include +#include +#include +#include + +/* This list holds all currently allocated rs control structures */ +static LIST_HEAD (rslist); +/* Protection for the list */ +static DEFINE_MUTEX(rslistlock); + +static struct rs_control *rs_init(int symsize, int gfpoly, int (*gffunc)(int), + int fcr, int prim, int nroots) +{ + struct rs_control *rs; + int i, j, sr, root, iprim; + + /* Allocate the control structure */ + rs = kmalloc(sizeof (struct rs_control), GFP_KERNEL); + if (rs == NULL) + return NULL; + + INIT_LIST_HEAD(&rs->list); + + rs->mm = symsize; + rs->nn = (1 << symsize) - 1; + rs->fcr = fcr; + rs->prim = prim; + rs->nroots = nroots; + rs->gfpoly = gfpoly; + rs->gffunc = gffunc; + + /* Allocate the arrays */ + rs->alpha_to = kmalloc(sizeof(uint16_t) * (rs->nn + 1), GFP_KERNEL); + if (rs->alpha_to == NULL) + goto errrs; + + rs->index_of = kmalloc(sizeof(uint16_t) * (rs->nn + 1), GFP_KERNEL); + if (rs->index_of == NULL) + goto erralp; + + rs->genpoly = kmalloc(sizeof(uint16_t) * (rs->nroots + 1), GFP_KERNEL); + if(rs->genpoly == NULL) + goto erridx; + + /* Generate Galois field lookup tables */ + rs->index_of[0] = rs->nn; /* log(zero) = -inf */ + rs->alpha_to[rs->nn] = 0; /* alpha**-inf = 0 */ + if (gfpoly) { + sr = 1; + for (i = 0; i < rs->nn; i++) { + rs->index_of[sr] = i; + rs->alpha_to[i] = sr; + sr <<= 1; + if (sr & (1 << symsize)) + sr ^= gfpoly; + sr &= rs->nn; + } + } else { + sr = gffunc(0); + for (i = 0; i < rs->nn; i++) { + rs->index_of[sr] = i; + rs->alpha_to[i] = sr; + sr = gffunc(sr); + } + } + /* If it's not primitive, exit */ + if(sr != rs->alpha_to[0]) + goto errpol; + + /* Find prim-th root of 1, used in decoding */ + for(iprim = 1; (iprim % prim) != 0; iprim += rs->nn); + /* prim-th root of 1, index form */ + rs->iprim = iprim / prim; + + /* Form RS code generator polynomial from its roots */ + rs->genpoly[0] = 1; + for (i = 0, root = fcr * prim; i < nroots; i++, root += prim) { + rs->genpoly[i + 1] = 1; + /* Multiply rs->genpoly[] by @**(root + x) */ + for (j = i; j > 0; j--) { + if (rs->genpoly[j] != 0) { + rs->genpoly[j] = rs->genpoly[j -1] ^ + rs->alpha_to[rs_modnn(rs, + rs->index_of[rs->genpoly[j]] + root)]; + } else + rs->genpoly[j] = rs->genpoly[j - 1]; + } + /* rs->genpoly[0] can never be zero */ + rs->genpoly[0] = + rs->alpha_to[rs_modnn(rs, + rs->index_of[rs->genpoly[0]] + root)]; + } + /* convert rs->genpoly[] to index form for quicker encoding */ + for (i = 0; i <= nroots; i++) + rs->genpoly[i] = rs->index_of[rs->genpoly[i]]; + return rs; + + /* Error exit */ +errpol: + kfree(rs->genpoly); +erridx: + kfree(rs->index_of); +erralp: + kfree(rs->alpha_to); +errrs: + kfree(rs); + return NULL; +} + + +void free_rs(struct rs_control *rs) +{ + mutex_lock(&rslistlock); + rs->users--; + if(!rs->users) { + list_del(&rs->list); + kfree(rs->alpha_to); + kfree(rs->index_of); + kfree(rs->genpoly); + kfree(rs); + } + mutex_unlock(&rslistlock); +} + +static struct rs_control *init_rs_internal(int symsize, int gfpoly, + int (*gffunc)(int), int fcr, + int prim, int nroots) +{ + struct list_head *tmp; + struct rs_control *rs; + + /* Sanity checks */ + if (symsize < 1) + return NULL; + if (fcr < 0 || fcr >= (1<= (1<= (1<mm) + continue; + if (gfpoly != rs->gfpoly) + continue; + if (gffunc != rs->gffunc) + continue; + if (fcr != rs->fcr) + continue; + if (prim != rs->prim) + continue; + if (nroots != rs->nroots) + continue; + /* We have a matching one already */ + rs->users++; + goto out; + } + + /* Create a new one */ + rs = rs_init(symsize, gfpoly, gffunc, fcr, prim, nroots); + if (rs) { + rs->users = 1; + list_add(&rs->list, &rslist); + } +out: + mutex_unlock(&rslistlock); + return rs; +} + +struct rs_control *init_rs(int symsize, int gfpoly, int fcr, int prim, + int nroots) +{ + return init_rs_internal(symsize, gfpoly, NULL, fcr, prim, nroots); +} + +struct rs_control *init_rs_non_canonical(int symsize, int (*gffunc)(int), + int fcr, int prim, int nroots) +{ + return init_rs_internal(symsize, 0, gffunc, fcr, prim, nroots); +} + +#ifdef CONFIG_REED_SOLOMON_ENC8 +int encode_rs8(struct rs_control *rs, uint8_t *data, int len, uint16_t *par, + uint16_t invmsk) +{ +#include "encode_rs.c" +} +EXPORT_SYMBOL_GPL(encode_rs8); +#endif + +#ifdef CONFIG_REED_SOLOMON_DEC8 +int decode_rs8(struct rs_control *rs, uint8_t *data, uint16_t *par, int len, + uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk, + uint16_t *corr) +{ +#include "decode_rs.c" +} +EXPORT_SYMBOL_GPL(decode_rs8); +#endif + +#ifdef CONFIG_REED_SOLOMON_ENC16 +int encode_rs16(struct rs_control *rs, uint16_t *data, int len, uint16_t *par, + uint16_t invmsk) +{ +#include "encode_rs.c" +} +EXPORT_SYMBOL_GPL(encode_rs16); +#endif + +#ifdef CONFIG_REED_SOLOMON_DEC16 +int decode_rs16(struct rs_control *rs, uint16_t *data, uint16_t *par, int len, + uint16_t *s, int no_eras, int *eras_pos, uint16_t invmsk, + uint16_t *corr) +{ +#include "decode_rs.c" +} +EXPORT_SYMBOL_GPL(decode_rs16); +#endif + +EXPORT_SYMBOL_GPL(init_rs); +EXPORT_SYMBOL_GPL(init_rs_non_canonical); +EXPORT_SYMBOL_GPL(free_rs); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Reed Solomon encoder/decoder"); +MODULE_AUTHOR("Phil Karn, Thomas Gleixner"); + diff --git a/pool/shard006/C/0117785_s_sincosl.c b/pool/shard006/C/0117785_s_sincosl.c new file mode 100644 index 0000000000000000000000000000000000000000..7d33c97162f8fd5369d15fd9507f3092fd2ca489 --- /dev/null +++ b/pool/shard006/C/0117785_s_sincosl.c @@ -0,0 +1,76 @@ +/* Compute sine and cosine of argument. + Copyright (C) 1997-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1997. + + 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 + . */ + +#include +#include + +#include + + +void +__sincosl (long double x, long double *sinx, long double *cosx) +{ + int32_t se, i0, i1 __attribute__ ((unused)); + + /* High word of x. */ + GET_LDOUBLE_WORDS (se, i0, i1, x); + + /* |x| ~< pi/4 */ + se &= 0x7fff; + if (se < 0x3ffe || (se == 0x3ffe && i0 <= 0xc90fdaa2)) + { + *sinx = __kernel_sinl (x, 0.0, 0); + *cosx = __kernel_cosl (x, 0.0); + } + else if (se == 0x7fff) + { + /* sin(Inf or NaN) is NaN */ + *sinx = *cosx = x - x; + if (isinf (x)) + __set_errno (EDOM); + } + else + { + /* Argument reduction needed. */ + long double y[2]; + int n; + + n = __ieee754_rem_pio2l (x, y); + switch (n & 3) + { + case 0: + *sinx = __kernel_sinl (y[0], y[1], 1); + *cosx = __kernel_cosl (y[0], y[1]); + break; + case 1: + *sinx = __kernel_cosl (y[0], y[1]); + *cosx = -__kernel_sinl (y[0], y[1], 1); + break; + case 2: + *sinx = -__kernel_sinl (y[0], y[1], 1); + *cosx = -__kernel_cosl (y[0], y[1]); + break; + default: + *sinx = -__kernel_cosl (y[0], y[1]); + *cosx = __kernel_sinl (y[0], y[1], 1); + break; + } + } +} +weak_alias (__sincosl, sincosl) diff --git a/pool/shard006/C/0117786_libpe_rich.c b/pool/shard006/C/0117786_libpe_rich.c new file mode 100644 index 0000000000000000000000000000000000000000..4669a224d0042e049b2765539f34f863a1f840c8 --- /dev/null +++ b/pool/shard006/C/0117786_libpe_rich.c @@ -0,0 +1,128 @@ +/*- + * Copyright (c) 2015 Kai Wang + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include +#include +#include + +#include "_libpe.h" + +ELFTC_VCSID("$Id: libpe_rich.c 3312 2016-01-10 09:23:51Z kaiwang27 $"); + +static char * +memfind(char *s, const char *find, size_t slen, size_t flen) +{ + int i; + + if (slen == 0 || flen == 0 || flen > slen) + return (NULL); + + for (i = 0; (size_t) i <= slen - flen; i++) { + if (s[i] != find[0]) + continue; + if (flen == 1) + return (&s[i]); + if (memcmp(&s[i + 1], &find[1], flen - 1) == 0) + return (&s[i]); + } + + return (NULL); +} + +int +libpe_parse_rich_header(PE *pe) +{ + PE_RichHdr *rh; + char *p, *r, *s; + uint32_t x; + int found, i; + + assert(pe->pe_stub != NULL && pe->pe_stub_ex > 0); + + /* Search for the "Rich" keyword to locate the Rich header. */ + s = pe->pe_stub + sizeof(PE_DosHdr); + r = memfind(s, PE_RICH_TEXT, pe->pe_stub_ex, 4); + if (r == NULL || r + 8 > s + pe->pe_stub_ex) { + errno = ENOENT; + return (-1); + } + + if ((rh = calloc(1, sizeof(*rh))) == NULL) { + errno = ENOMEM; + return (-1); + } + + rh->rh_xor = le32dec(r + 4); /* Retrieve the "XOR mask" */ + + /* + * Search for the hidden keyword "DanS" by XOR the dwords before + * the "Rich" keyword with the XOR mask. + */ + found = 0; + for (p = r - 4; p >= s; p -= 4) { + x = le32dec(p) ^ rh->rh_xor; + if (x == PE_RICH_HIDDEN) { + found = 1; + break; + } + } + if (!found) { + free(rh); + errno = ENOENT; + return (-1); + } + + /* + * Found the "DanS" keyword, which is the start of the Rich header. + * The next step is to skip the first 16 bytes (DanS, XOR mask, + * XOR mask, XOR mask) and read the (compid,cnt) tuples. + */ + pe->pe_rh_start = p; + p += 16; + rh->rh_total = (r - p) / 8; + if ((rh->rh_compid = malloc(rh->rh_total * sizeof(*rh->rh_compid))) == + NULL) { + free(rh); + errno = ENOMEM; + return (-1); + } + if ((rh->rh_cnt = malloc(rh->rh_total * sizeof(*rh->rh_cnt))) == + NULL) { + free(rh->rh_compid); + free(rh); + errno = ENOMEM; + return (-1); + } + for (i = 0; (uint32_t) i < rh->rh_total; i++, p += 8) { + rh->rh_compid[i] = le32dec(p) ^ rh->rh_xor; + rh->rh_cnt[i] = le32dec(p + 4) ^ rh->rh_xor; + } + + pe->pe_rh = rh; + + return (0); +} diff --git a/pool/shard006/C/0117798_srv.c b/pool/shard006/C/0117798_srv.c new file mode 100644 index 0000000000000000000000000000000000000000..dcf27d0ec11a0317a02b4747619c654ff40b2102 --- /dev/null +++ b/pool/shard006/C/0117798_srv.c @@ -0,0 +1,65 @@ +#include "pse.h" + +#define CMD "serveur" + +int main(int argc, char *argv[]) { + int ecoute, canal, ret; + char buf[LIGNE_MAX]; + struct sockaddr_in adrEcoute, reception; + unsigned int receptionlen; + short port; + + if (argc != 2) { + erreur("usage: %s port\n", argv[0]); + } + + port = (short) atoi(argv[1]); + + printf("%s: creating a socket\n", CMD); + ecoute = socket (AF_INET, SOCK_STREAM, 0); + if (ecoute < 0) { + erreur_IO("socket"); + } + + adrEcoute.sin_family = AF_INET; + adrEcoute.sin_addr.s_addr = INADDR_ANY; + adrEcoute.sin_port = htons(port); + printf("%s: binding to INADDR_ANY address on port %d\n", CMD, port); + ret = bind (ecoute, (struct sockaddr *) &adrEcoute, sizeof(adrEcoute)); + if (ret < 0) { + erreur_IO("bind"); + } + + printf("%s: listening to socket\n", CMD); + ret = listen (ecoute, 5); + if (ret < 0) { + erreur_IO("listen"); + } + + receptionlen = sizeof(reception); + printf("%s: accepting a connection\n", CMD); + canal = accept(ecoute, (struct sockaddr *) &reception, &receptionlen); + if (canal < 0) { + erreur_IO("accept"); + } + printf("%s: adr %s, port %hu\n", CMD, + stringIP(ntohl(reception.sin_addr.s_addr)), + ntohs(reception.sin_port)); + + ret = lireLigne(canal, buf); + if (ret <=0 || ret == LIGNE_MAX) { + erreur_IO("lireLigne"); + } + + printf("%s: reception %d octets : \"%s\"\n", CMD, ret, buf); + + if (close(canal) == -1) { + erreur_IO("close canal"); + } + + if (close(ecoute) == -1) { + erreur_IO("close ecoute"); + } + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard006/C/0117799_gpio-zevio.c b/pool/shard006/C/0117799_gpio-zevio.c new file mode 100644 index 0000000000000000000000000000000000000000..57432397e5e53c7a9310dda924f582e9d242fc22 --- /dev/null +++ b/pool/shard006/C/0117799_gpio-zevio.c @@ -0,0 +1,219 @@ +/* + * GPIO controller in LSI ZEVIO SoCs. + * + * Author: Fabian Vogt + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Memory layout: + * This chip has four gpio sections, each controls 8 GPIOs. + * Bit 0 in section 0 is GPIO 0, bit 2 in section 1 is GPIO 10. + * Disclaimer: Reverse engineered! + * For more information refer to: + * http://hackspire.unsads.com/wiki/index.php/Memory-mapped_I/O_ports#90000000_-_General_Purpose_I.2FO_.28GPIO.29 + * + * 0x00-0x3F: Section 0 + * +0x00: Masked interrupt status (read-only) + * +0x04: R: Interrupt status W: Reset interrupt status + * +0x08: R: Interrupt mask W: Mask interrupt + * +0x0C: W: Unmask interrupt (write-only) + * +0x10: Direction: I/O=1/0 + * +0x14: Output + * +0x18: Input (read-only) + * +0x20: R: Level interrupt W: Set as level interrupt + * 0x40-0x7F: Section 1 + * 0x80-0xBF: Section 2 + * 0xC0-0xFF: Section 3 + */ + +#define ZEVIO_GPIO_SECTION_SIZE 0x40 + +/* Offsets to various registers */ +#define ZEVIO_GPIO_INT_MASKED_STATUS 0x00 +#define ZEVIO_GPIO_INT_STATUS 0x04 +#define ZEVIO_GPIO_INT_UNMASK 0x08 +#define ZEVIO_GPIO_INT_MASK 0x0C +#define ZEVIO_GPIO_DIRECTION 0x10 +#define ZEVIO_GPIO_OUTPUT 0x14 +#define ZEVIO_GPIO_INPUT 0x18 +#define ZEVIO_GPIO_INT_STICKY 0x20 + +/* Bit number of GPIO in its section */ +#define ZEVIO_GPIO_BIT(gpio) (gpio&7) + +struct zevio_gpio { + spinlock_t lock; + struct of_mm_gpio_chip chip; +}; + +static inline u32 zevio_gpio_port_get(struct zevio_gpio *c, unsigned pin, + unsigned port_offset) +{ + unsigned section_offset = ((pin >> 3) & 3)*ZEVIO_GPIO_SECTION_SIZE; + return readl(IOMEM(c->chip.regs + section_offset + port_offset)); +} + +static inline void zevio_gpio_port_set(struct zevio_gpio *c, unsigned pin, + unsigned port_offset, u32 val) +{ + unsigned section_offset = ((pin >> 3) & 3)*ZEVIO_GPIO_SECTION_SIZE; + writel(val, IOMEM(c->chip.regs + section_offset + port_offset)); +} + +/* Functions for struct gpio_chip */ +static int zevio_gpio_get(struct gpio_chip *chip, unsigned pin) +{ + struct zevio_gpio *controller = gpiochip_get_data(chip); + u32 val, dir; + + spin_lock(&controller->lock); + dir = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_DIRECTION); + if (dir & BIT(ZEVIO_GPIO_BIT(pin))) + val = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_INPUT); + else + val = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_OUTPUT); + spin_unlock(&controller->lock); + + return (val >> ZEVIO_GPIO_BIT(pin)) & 0x1; +} + +static void zevio_gpio_set(struct gpio_chip *chip, unsigned pin, int value) +{ + struct zevio_gpio *controller = gpiochip_get_data(chip); + u32 val; + + spin_lock(&controller->lock); + val = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_OUTPUT); + if (value) + val |= BIT(ZEVIO_GPIO_BIT(pin)); + else + val &= ~BIT(ZEVIO_GPIO_BIT(pin)); + + zevio_gpio_port_set(controller, pin, ZEVIO_GPIO_OUTPUT, val); + spin_unlock(&controller->lock); +} + +static int zevio_gpio_direction_input(struct gpio_chip *chip, unsigned pin) +{ + struct zevio_gpio *controller = gpiochip_get_data(chip); + u32 val; + + spin_lock(&controller->lock); + + val = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_DIRECTION); + val |= BIT(ZEVIO_GPIO_BIT(pin)); + zevio_gpio_port_set(controller, pin, ZEVIO_GPIO_DIRECTION, val); + + spin_unlock(&controller->lock); + + return 0; +} + +static int zevio_gpio_direction_output(struct gpio_chip *chip, + unsigned pin, int value) +{ + struct zevio_gpio *controller = gpiochip_get_data(chip); + u32 val; + + spin_lock(&controller->lock); + val = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_OUTPUT); + if (value) + val |= BIT(ZEVIO_GPIO_BIT(pin)); + else + val &= ~BIT(ZEVIO_GPIO_BIT(pin)); + + zevio_gpio_port_set(controller, pin, ZEVIO_GPIO_OUTPUT, val); + val = zevio_gpio_port_get(controller, pin, ZEVIO_GPIO_DIRECTION); + val &= ~BIT(ZEVIO_GPIO_BIT(pin)); + zevio_gpio_port_set(controller, pin, ZEVIO_GPIO_DIRECTION, val); + + spin_unlock(&controller->lock); + + return 0; +} + +static int zevio_gpio_to_irq(struct gpio_chip *chip, unsigned pin) +{ + /* + * TODO: Implement IRQs. + * Not implemented yet due to weird lockups + */ + + return -ENXIO; +} + +static const struct gpio_chip zevio_gpio_chip = { + .direction_input = zevio_gpio_direction_input, + .direction_output = zevio_gpio_direction_output, + .set = zevio_gpio_set, + .get = zevio_gpio_get, + .to_irq = zevio_gpio_to_irq, + .base = 0, + .owner = THIS_MODULE, + .ngpio = 32, + .of_gpio_n_cells = 2, +}; + +/* Initialization */ +static int zevio_gpio_probe(struct platform_device *pdev) +{ + struct zevio_gpio *controller; + int status, i; + + controller = devm_kzalloc(&pdev->dev, sizeof(*controller), GFP_KERNEL); + if (!controller) + return -ENOMEM; + + platform_set_drvdata(pdev, controller); + + /* Copy our reference */ + controller->chip.gc = zevio_gpio_chip; + controller->chip.gc.parent = &pdev->dev; + + status = of_mm_gpiochip_add_data(pdev->dev.of_node, + &(controller->chip), + controller); + if (status) { + dev_err(&pdev->dev, "failed to add gpiochip: %d\n", status); + return status; + } + + spin_lock_init(&controller->lock); + + /* Disable interrupts, they only cause errors */ + for (i = 0; i < controller->chip.gc.ngpio; i += 8) + zevio_gpio_port_set(controller, i, ZEVIO_GPIO_INT_MASK, 0xFF); + + dev_dbg(controller->chip.gc.parent, "ZEVIO GPIO controller set up!\n"); + + return 0; +} + +static const struct of_device_id zevio_gpio_of_match[] = { + { .compatible = "lsi,zevio-gpio", }, + { }, +}; + +static struct platform_driver zevio_gpio_driver = { + .driver = { + .name = "gpio-zevio", + .of_match_table = zevio_gpio_of_match, + .suppress_bind_attrs = true, + }, + .probe = zevio_gpio_probe, +}; +builtin_platform_driver(zevio_gpio_driver); diff --git a/pool/shard006/C/0117808_thr_kill.c b/pool/shard006/C/0117808_thr_kill.c new file mode 100644 index 0000000000000000000000000000000000000000..15928b1b91f68c82954ab0ff5bd3210f2b43c707 --- /dev/null +++ b/pool/shard006/C/0117808_thr_kill.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997 John Birrell . + * 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 JOHN BIRRELL 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 +__FBSDID("$FreeBSD$"); + +#include "namespace.h" +#include +#include +#include +#include "un-namespace.h" + +#include "thr_private.h" + +__weak_reference(_pthread_kill, pthread_kill); + +int +_pthread_kill(pthread_t pthread, int sig) +{ + struct pthread *curthread; + int ret; + + /* Check for invalid signal numbers: */ + if (sig < 0 || sig > _SIG_MAXSIG) + /* Invalid signal: */ + return (EINVAL); + + curthread = _get_curthread(); + + /* + * Ensure the thread is in the list of active threads, and the + * signal is valid (signal 0 specifies error checking only) and + * not being ignored: + */ + if (curthread == pthread) { + if (sig > 0) + _thr_send_sig(pthread, sig); + ret = 0; + } else if ((ret = _thr_find_thread(curthread, pthread, + /*include dead*/0)) == 0) { + if (sig > 0) + _thr_send_sig(pthread, sig); + THR_THREAD_UNLOCK(curthread, pthread); + } + + /* Return the completion status: */ + return (ret); +} diff --git a/pool/shard006/C/0117811_entry.c b/pool/shard006/C/0117811_entry.c new file mode 100644 index 0000000000000000000000000000000000000000..369f8d080db226cd482904a029a2ff513a2578a6 --- /dev/null +++ b/pool/shard006/C/0117811_entry.c @@ -0,0 +1,282 @@ +/* + * Copyright 2016-2019, Andrew Lindesay. All Rights Reserved. + * Distributed under the terms of the MIT License. + * + * Authors: + * Andrew Lindesay, apl@lindesay.co.nz + */ + +#include +#include +#include + +#include "common.h" +#include "constants.h" + +// --------------------------------------------------------------- +// CREATION +// --------------------------------------------------------------- + + +extern void deen_entry_create_yy( + const uint8_t *data, + deen_entry_sub **subs, + uint32_t *sub_count); + + +deen_entry deen_entry_create( + const uint8_t *german, + const uint8_t *english) { + + deen_entry result; + + deen_entry_create_yy( + german, + &(result.german_subs), + &(result.german_sub_count)); + + deen_entry_create_yy( + english, + &(result.english_subs), + &(result.english_sub_count)); + + return result; +} + + +// --------------------------------------------------------------- +// FREEING DATA +// --------------------------------------------------------------- + + +static void deen_entry_atom_free(deen_entry_atom *atom) { + if (NULL!=atom) { + if (NULL!=atom->text) { + free((void *) atom->text); + } + } +} + + +static void deen_entry_sub_sub_free(deen_entry_sub_sub *sub_sub) { + if (NULL != sub_sub) { + uint32_t i; + + for (i=0;iatom_count;i++) { + deen_entry_atom_free(&(sub_sub->atoms[i])); + } + + free((void *) sub_sub->atoms); + } +} + + +static void deen_entry_sub_free(deen_entry_sub *sub) { + if (NULL!=sub) { + uint32_t i; + + for (i=0;isub_sub_count;i++) { + deen_entry_sub_sub_free(&(sub->sub_subs[i])); + } + + free((void *) sub->sub_subs); + } +} + + +void deen_entry_free(deen_entry *entry) { + if (NULL!=entry) { + uint32_t i; + + for (i=0;ienglish_sub_count;i++) { + deen_entry_sub_free(&(entry->english_subs[i])); + } + + for (i=0;igerman_sub_count;i++) { + deen_entry_sub_free(&(entry->german_subs[i])); + } + } +} + + +// --------------------------------------------------------------- +// SCORING +// --------------------------------------------------------------- + + +typedef struct + deen_entry_calculate_distance_from_keywords_foreachword_callback_state + deen_entry_calculate_distance_from_keywords_foreachword_callback_state; +struct deen_entry_calculate_distance_from_keywords_foreachword_callback_state +{ + uint32_t accumulated_distance_from_keyword; + deen_keywords *keywords; + deen_bool *keyword_use_map; // boolean +}; + + +size_t deen_entry_find_first_keyword( + const uint8_t *s, + deen_keywords *keywords, + uint32_t offset) { + uint32_t i; + + for (i=0;icount;i++) { + if (deen_imatches_at(s, keywords->keywords[i], offset)) { + return i; + } + } + + return DEEN_NOT_FOUND; +} + + +deen_bool deen_entry_calculate_distance_from_keywords_foreachword_callback( + const uint8_t *s, size_t offset, size_t len, void *context) { + + deen_entry_calculate_distance_from_keywords_foreachword_callback_state *state = + (deen_entry_calculate_distance_from_keywords_foreachword_callback_state *) context; + + // find the first keyword at the start of this string. + + size_t keyword_offset = deen_entry_find_first_keyword(s, state->keywords, offset); + + if (DEEN_NOT_FOUND == keyword_offset) { + state->accumulated_distance_from_keyword += (uint32_t) len; + } + else { + size_t keyword_len; + size_t sequence_count; + + state->keyword_use_map[keyword_offset] = DEEN_TRUE; + + // how many letters (decoded from UTF-8) remain in the rest of the word? + keyword_len = strlen((char *) state->keywords->keywords[keyword_offset]); + + switch (deen_utf8_sequences_count(&s[offset + keyword_len], len-keyword_len, &sequence_count)) { + + case DEEN_SEQUENCE_OK: + state->accumulated_distance_from_keyword += sequence_count; + break; + + case DEEN_BAD_SEQUENCE: + deen_log_error_and_exit("encountered bad utf-8 sequence"); + break; + + case DEEN_INCOMPLETE_SEQUENCE: + deen_log_error_and_exit("encountered incomplete utf-8 sequence"); + break; + + } + } + + return DEEN_TRUE; +} + + +/* +If any keyword is not present at all then return the maximum value. Otherwise, +for each word, find the longest characters that are not part of the keyword and +add all of those up. Keywords are expected to be in order with largest first. +*/ + +static uint32_t deen_entry_sub_sub_calculate_distance_from_keywords( + deen_entry_sub_sub *sub_sub, + deen_keywords *keywords, + deen_bool *keyword_use_map) { + + deen_entry_calculate_distance_from_keywords_foreachword_callback_state state; + uint32_t i; + + memset(keyword_use_map, 0, (sizeof(deen_bool) * keywords->count)); + + state.keywords = keywords; + state.keyword_use_map = keyword_use_map; + state.accumulated_distance_from_keyword = 0; + + for (i=0;iatom_count;i++) { + + if (ATOM_TEXT == sub_sub->atoms[i].type) { + + deen_for_each_word( + sub_sub->atoms[i].text, 0, + &deen_entry_calculate_distance_from_keywords_foreachword_callback, + &state); + } + } + + for (i=0;icount;i++) { + if (!keyword_use_map[i]) { + return DEEN_MAX_SORT_DISTANCE_FROM_KEYWORDS; + } + } + + return state.accumulated_distance_from_keyword; +} + + +static uint32_t deen_entry_sub_calculate_distance_from_keywords( + deen_entry_sub *sub, + deen_keywords *keywords, + deen_bool *keyword_use_map) { + + uint32_t i; + int result = DEEN_MAX_SORT_DISTANCE_FROM_KEYWORDS; + + for (i=0;isub_sub_count;i++) { + uint32_t sub_sub_result = deen_entry_sub_sub_calculate_distance_from_keywords( + &sub->sub_subs[i], keywords, keyword_use_map); + + if (sub_sub_result < result) { + result = sub_sub_result; + } + } + + return result; +} + + +static uint32_t deen_entry_subs_calculate_distance_from_keywords( + deen_entry_sub *subs, + uint32_t sub_count, + deen_keywords *keywords, + deen_bool *keyword_use_map) { + + uint32_t result = DEEN_MAX_SORT_DISTANCE_FROM_KEYWORDS; + uint32_t i; + + for (i=0;i < sub_count;i++) { + + uint32_t sub_result = deen_entry_sub_calculate_distance_from_keywords( + &subs[i], + keywords, + keyword_use_map); + + DEEN_LOG_TRACE2(" %u) distance from keyword; %u", i, sub_result); + + if (sub_result < result) { + result = sub_result; + } + } + + return result; +} + + +uint32_t deen_entry_calculate_distance_from_keywords( + deen_entry *entry, + deen_keywords *keywords, + deen_bool *keyword_use_map) { + + uint32_t german_result = deen_entry_subs_calculate_distance_from_keywords( + entry->german_subs, entry->german_sub_count, keywords, keyword_use_map); + + uint32_t english_result = deen_entry_subs_calculate_distance_from_keywords( + entry->english_subs, entry->english_sub_count, keywords, keyword_use_map); + + if (german_result < english_result) { + return german_result; + } + + return english_result; +} diff --git a/pool/shard006/C/0117816_Main.c b/pool/shard006/C/0117816_Main.c new file mode 100644 index 0000000000000000000000000000000000000000..db1de7d7b869761e2a30bc305ed65fd8feb2b56c --- /dev/null +++ b/pool/shard006/C/0117816_Main.c @@ -0,0 +1,34 @@ +#include "GEDCOMparser.h" +#include "LinkedListAPI.h" +// #include "BinarySearchTreeAPI.h" +#include + +// GEDCOMobject * createObject(); + +int main() +{ + GEDCOMobject * testObject; + // = createObject(); + + // enum eCode errorCodeTest; + GEDCOMerror errorCodeTest; + + errorCodeTest = createGEDCOM("./uploads/simpleValid.ged", &testObject); + + + char * str = printError(errorCodeTest); + + printf("%s\n", str); + free(str); + + // char * obj = printGEDCOM(testObject); + + // printf("%s\n", obj); + // free(obj); + // free(testObject); + deleteGEDCOM(testObject); + + + return 0; + +} diff --git a/pool/shard006/C/0117819_m_connmark.c b/pool/shard006/C/0117819_m_connmark.c new file mode 100644 index 0000000000000000000000000000000000000000..45e2d05f1a9114f7df37c88ee79a11e109390bf8 --- /dev/null +++ b/pool/shard006/C/0117819_m_connmark.c @@ -0,0 +1,148 @@ +/* + * m_connmark.c Connection tracking marking import + * + * Copyright (c) 2011 Felix Fietkau + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, see . + */ + +#include +#include +#include +#include +#include "utils.h" +#include "tc_util.h" +#include + +static void +explain(void) +{ + fprintf(stderr, "Usage: ... connmark [zone ZONE] [CONTROL] [index ]\n"); + fprintf(stderr, "where :\n" + "\tZONE is the conntrack zone\n" + "\tCONTROL := reclassify | pipe | drop | continue | ok |\n" + "\t goto chain \n"); +} + +static void +usage(void) +{ + explain(); + exit(-1); +} + +static int +parse_connmark(struct action_util *a, int *argc_p, char ***argv_p, int tca_id, + struct nlmsghdr *n) +{ + struct tc_connmark sel = {}; + char **argv = *argv_p; + int argc = *argc_p; + int ok = 0; + struct rtattr *tail; + + while (argc > 0) { + if (matches(*argv, "connmark") == 0) { + ok = 1; + argc--; + argv++; + } else if (matches(*argv, "help") == 0) { + usage(); + } else { + break; + } + + } + + if (!ok) { + explain(); + return -1; + } + + if (argc) { + if (matches(*argv, "zone") == 0) { + NEXT_ARG(); + if (get_u16(&sel.zone, *argv, 10)) { + fprintf(stderr, "simple: Illegal \"index\"\n"); + return -1; + } + argc--; + argv++; + } + } + + parse_action_control_dflt(&argc, &argv, &sel.action, false, TC_ACT_PIPE); + + if (argc) { + if (matches(*argv, "index") == 0) { + NEXT_ARG(); + if (get_u32(&sel.index, *argv, 10)) { + fprintf(stderr, "simple: Illegal \"index\"\n"); + return -1; + } + argc--; + argv++; + } + } + + tail = addattr_nest(n, MAX_MSG, tca_id); + addattr_l(n, MAX_MSG, TCA_CONNMARK_PARMS, &sel, sizeof(sel)); + addattr_nest_end(n, tail); + + *argc_p = argc; + *argv_p = argv; + return 0; +} + +static int print_connmark(struct action_util *au, FILE *f, struct rtattr *arg) +{ + struct rtattr *tb[TCA_CONNMARK_MAX + 1]; + struct tc_connmark *ci; + + if (arg == NULL) + return -1; + + parse_rtattr_nested(tb, TCA_CONNMARK_MAX, arg); + if (tb[TCA_CONNMARK_PARMS] == NULL) { + print_string(PRINT_FP, NULL, "%s", "[NULL connmark parameters]"); + return -1; + } + + ci = RTA_DATA(tb[TCA_CONNMARK_PARMS]); + + print_string(PRINT_ANY, "kind", "%s ", "connmark"); + print_uint(PRINT_ANY, "zone", "zone %u", ci->zone); + print_action_control(f, " ", ci->action, ""); + + print_string(PRINT_FP, NULL, "%s", _SL_); + print_uint(PRINT_ANY, "index", "\t index %u", ci->index); + print_int(PRINT_ANY, "ref", " ref %d", ci->refcnt); + print_int(PRINT_ANY, "bind", " bind %d", ci->bindcnt); + + if (show_stats) { + if (tb[TCA_CONNMARK_TM]) { + struct tcf_t *tm = RTA_DATA(tb[TCA_CONNMARK_TM]); + + print_tm(f, tm); + } + } + print_string(PRINT_FP, NULL, "%s", _SL_); + + return 0; +} + +struct action_util connmark_action_util = { + .id = "connmark", + .parse_aopt = parse_connmark, + .print_aopt = print_connmark, +}; diff --git a/pool/shard006/C/0117824_main.c b/pool/shard006/C/0117824_main.c new file mode 100644 index 0000000000000000000000000000000000000000..cf470be2bd92a65fd8e4775d173c76a6fbef9db6 --- /dev/null +++ b/pool/shard006/C/0117824_main.c @@ -0,0 +1,130 @@ +// +// main.c +// test-pull-bdb-json +// +// Created by Casey Marshall on 3/16/12. +// Copyright (c) 2012 Memeo, Inc. All rights reserved. +// + +#include +#include +#include +#include +#include +#include + +#include "../api/LoungeAct.h" +#include "../pull/pull.h" +#include "../compress-zlib/compress-zlib.h" +#include "../compress-lz4/compress-lz4.h" + +int cb1(const char *path, const struct stat *ptr, int flag, struct FTW *ftw); +int cb1(const char *path, const struct stat *ptr, int flag, struct FTW *ftw) +{ + printf("cb1 %s %x\n", path, flag); + if (flag == FTW_F) + { + if (unlink(path) != 0) + fprintf(stderr, "failed to unlink %s: %s\n", path, strerror(errno)); + } + return 0; +} + +int cb2(const char *path, const struct stat *ptr, int flag, struct FTW *ftw); +int cb2(const char *path, const struct stat *ptr, int flag, struct FTW *ftw) +{ + printf("cb2 %s %x\n", path, flag); + if (flag == FTW_DP) + { + if (rmdir(path) != 0) + fprintf(stderr, "failed to rmdir %s: %s\n", path, strerror(errno)); + } + return 0; +} + +static la_host_t *host = NULL; +static la_db_t *db = NULL; +static la_pull_t *puller = NULL; + +void cleanup(void); +void cleanup(void) +{ + printf("cleaning up...\n"); + if (db != NULL) + la_db_close(db); + if (host != NULL) + la_host_close(host); + if (puller != NULL) + la_pull_destroy(puller); +} + +#define OK() printf("OK\n") +#define FAIL(fmt,args...) do { printf("FAIL" fmt "\n", ##args); return -1; } while (0) +#define FAIL0() FAIL("") + +int main(int argc, const char * argv[]) +{ + if (nftw("/tmp/apitest", cb1, 10, FTW_DEPTH | FTW_PHYS) == 0) + nftw("/tmp/apitest", cb2, 10, FTW_DEPTH | FTW_PHYS); + + atexit(cleanup); + setvbuf(stdout, NULL, _IONBF, 0); + printf("opening host... "); + if ((host = la_host_open("/tmp/apitest")) == NULL) + { + FAIL0(); + } + OK(); + + //la_host_configure_compressor(host, zlib_compressor); + la_host_configure_compressor(host, la_lz4_compressor); + + printf("opening db... "); + if ((db = la_db_open(host, "apitest")) == NULL) + { + FAIL0(); + } + OK(); + + la_pull_params_t params; + params.dbname = "library-53b825ecc2fd4f85afd2b93cc4da7739"; + params.filter = NULL; + params.host = "localhost"; + params.port = 5984; + params.options = 0; + params.user = NULL; + params.password = NULL; + params.resolver = NULL; + params.baton = NULL; + puller = la_pull_create(db, ¶ms); + printf("pulling changes... "); + if (la_pull_run(puller) != 0) + FAIL0(); + la_pull_destroy(puller); + OK(); + + la_view_iterator_t *it = la_db_view(db, NULL, NULL, NULL, NULL); + la_view_iterator_result itresult; + do + { + la_codec_value_t *value = NULL; + la_codec_error_t error; + itresult = la_view_iterator_next(it, &value, &error); + if (itresult == LA_VIEW_ITERATOR_GOT_NEXT) + printf("got object %s\n", la_codec_dumps(value, 0)); + printf("%d %d\n", itresult, itresult == LA_VIEW_ITERATOR_GOT_NEXT); + } while (itresult == LA_VIEW_ITERATOR_GOT_NEXT); + if (itresult != LA_VIEW_ITERATOR_END) + FAIL0(); + OK(); + + printf("pulling again... "); + puller = la_pull_create(db, ¶ms); + if (la_pull_run(puller) != 0) + FAIL0(); + la_pull_destroy(puller); + OK(); + + return 0; +} + diff --git a/pool/shard006/C/0117825_sim_ac_jsbsim.c b/pool/shard006/C/0117825_sim_ac_jsbsim.c new file mode 100644 index 0000000000000000000000000000000000000000..3926cd3b05b678cc265f7012549a2044240a0d74 --- /dev/null +++ b/pool/shard006/C/0117825_sim_ac_jsbsim.c @@ -0,0 +1,327 @@ +/* + * Copyright (C) 2008 Gautier Hattenberger + * + * This file is part of paparazzi. + * + * paparazzi 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. + * + * paparazzi 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 paparazzi; see the file COPYING. If not, write to + * the Free Software Foundation, 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + */ + + + +#include +#include +#include +#include + +#include + +// ignore stupid warnings in JSBSim +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-parameter" +#include +//#include +#include +#pragma GCC diagnostic pop + +#include "sim_ac_flightgear.h" + +using namespace std; + +//#include +#include +#include "sim_ac_jsbsim.h" + +/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +GLOBAL DATA +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/ + +bool run_model; +bool run_fg = false; + +string ICName; +string AircraftName; +JSBSim::FGFDMExec* FDMExec; + +static void sim_parse_options(int argc, char** argv); +static void sim_init(void); +static gboolean sim_periodic(gpointer data); + +#ifdef __APPLE__ +string ivyBus = "224.255.255.255"; +#else +string ivyBus = "127.255.255.255"; +#endif +string fgAddress = "127.0.0.1"; + +static void ivy_transport_init(void); + + +static void sim_init(void) { + + run_model = false; + + jsbsim_init(); + + // init sensors ? or discribe them in jSBSim + + ivy_transport_init(); + + // main AP init (feed the sensors once before ?) + sim_autopilot_init(); + + printf("sys_time frequency: %f\n", (float)SYS_TIME_FREQUENCY); + +} + +static gboolean sim_periodic(gpointer data __attribute__ ((unused))) { + static uint8_t ncalls = 0; + + /* read actuators positions and feed JSBSim inputs */ + copy_inputs_to_jsbsim(FDMExec); + + /* run JSBSim flight model */ + bool result = true; + if (run_model) { + result = FDMExec->Run(); + } + /* check if still flying */ + result = check_crash_jsbsim(FDMExec); + + /* read outputs from model state */ + copy_outputs_from_jsbsim(FDMExec); + + /* send outputs to flightgear for visualisation */ + if (run_fg == true) + sim_ac_flightgear_send(FDMExec); + + /* run the airborne code + with 60 Hz, even if JSBSim runs with a multiple of this */ + if (ncalls == 0) { + // airborne_run_one_step(); + autopilot_event_task(); + autopilot_periodic_task(); + } + ++ncalls; + if (ncalls == JSBSIM_SPEEDUP) ncalls = 0; + + return result; +} + +static gboolean systime_periodic(gpointer data __attribute__ ((unused))) { + sys_tick_handler(); + return true; +} + + +int main ( int argc, char** argv) { + + sim_parse_options(argc, argv); + + sim_init(); + + if (run_fg == true) + sim_ac_flightgear_init(fgAddress.c_str(), 5501); + + GMainLoop *ml = g_main_loop_new(NULL, FALSE); + + guint systime_dt_ms = SYSTIME_PERIOD; + printf("sys_time period in msec: %d\n", systime_dt_ms); + guint jsbsim_dt_ms = JSBSIM_PERIOD; + printf("jsbsim period in msec: %d\n", jsbsim_dt_ms); + + g_timeout_add(jsbsim_dt_ms, sim_periodic, NULL); + g_timeout_add(systime_dt_ms, systime_periodic, NULL); + + g_main_loop_run(ml); + + delete FDMExec; + return 0; +} + + +static void ivy_transport_init(void) { + const char* agent_name = AIRFRAME_NAME"_JSBSIM"; + IvyInit(agent_name, "READY", NULL, NULL, NULL, NULL); + IvyStart(ivyBus.c_str()); +} + +void print_help() { + cout << "Usage: simsitl [options]" << endl; + cout << " Options :" << endl; + cout << " -a \tUnused, only for compatibility" << endl; + cout << " -b \tdefault is 127.255.255.255:2010" << endl; + cout << " -fg " << endl; + cout << " -h --help show this help" << endl; +} + +static void sim_parse_options(int argc, char** argv) { + + if (argc == 1) return; + + int i; + for (i = 1; i < argc; ++i) { + string argument = string(argv[i]); + + if (argument == "--help" || argument == "-h") { + print_help(); + exit(0); + } + else if (argument == "-a") { + // Compatibility with ocaml + i++; + } + else if (argument == "-boot") { + // Compatibility with ocaml + } + else if (argument == "-norc") { + // Compatibility with ocaml + } + else if (argument == "-jsbsim") { + // Compatibility with ocaml + } + else if (argument == "-b") { + ivyBus = string(argv[++i]); + } + else if (argument == "-fg") { + run_fg = true; + fgAddress = string(argv[++i]); + } + else { + cerr << "Unknown argument" << endl; + print_help(); + exit(0); + } + } + +} + + + + + + + + +void jsbsim_init(void) { + + // *** SET UP JSBSIM *** // + + char* root = getenv("PAPARAZZI_HOME"); + if (root == NULL) { + cerr << "PAPARAZZI_HOME is not defined" << endl; + exit(0); + } + string pprzRoot = string(root); + +#ifdef JSBSIM_MODEL + AircraftName = JSBSIM_MODEL; +#endif +#ifdef JSBSIM_INIT + ICName = JSBSIM_INIT; +#endif + + FDMExec = new JSBSim::FGFDMExec(); + + /* Set simulation time step */ + FDMExec->Setsim_time(0.); + FDMExec->Setdt(DT); + cout << "Simulation delta " << FDMExec->GetDeltaT() << endl; + + FDMExec->DisableOutput(); + FDMExec->SetDebugLevel(0); // No DEBUG messages + + if (!AircraftName.empty()) { + + if ( ! FDMExec->LoadModel( pprzRoot + "/conf/simulator", + pprzRoot + "/conf/simulator", + pprzRoot + "/conf/simulator", + AircraftName)){ + cerr << " JSBSim could not be started" << endl << endl; + delete FDMExec; + exit(-1); + } + + JSBSim::FGInitialCondition *IC = FDMExec->GetIC(); + if(!ICName.empty()) { + if (!IC->Load(ICName)) { + delete FDMExec; + cerr << "Initialization from file unsuccessful" << endl; + exit(-1); + } + } + else { + + // FGInitialCondition::SetAltitudeASLFtIC + // requires this function to be called + // before itself + IC->SetVgroundFpsIC(0.); + + // Use flight plan initial conditions + IC->SetLatitudeDegIC(NAV_LAT0 / 1e7); + IC->SetLongitudeDegIC(NAV_LON0 / 1e7); + + IC->SetAltitudeASLFtIC((GROUND_ALT + 2.0) / FT2M); + IC->SetTerrainElevationFtIC(GROUND_ALT / FT2M); + IC->SetPsiDegIC(QFU); + IC->SetVgroundFpsIC(0.); + + //initRunning for all engines + FDMExec->GetPropulsion()->InitRunning(-1); + if (!FDMExec->RunIC()) { + cerr << "Initialization from flight plan unsuccessful" << endl; + exit(-1); + } + } + //FDMExec->GetGroundReactions()->InitModel(); + + } else { + cerr << " No Aircraft given" << endl << endl; + delete FDMExec; + exit(-1); + } + + //if (FDMExec->Run()) cout << "Made Initial Run" << endl; + //else { + // cerr << "Initial run failed " << endl; + // exit(-1); + //} + +} + +bool check_crash_jsbsim(JSBSim::FGFDMExec* FDMExec) { + + double agl = FDMExec->GetPropagate()->GetDistanceAGL(), // in ft + lat = FDMExec->GetPropagate()->GetLatitude(), // in rad + lon = FDMExec->GetPropagate()->GetLongitude(); // in rad + + if (agl< -1e-5) { + cerr << "Crash detected: agl < 0" << endl << endl; + return false; + } + if (agl > 1e5 || abs(lat) > M_PI_2 || abs(lon) > M_PI) { + cerr << "Simulation divergence: Lat=" << lat + << " rad, lon=" << lon << " rad, agl=" << agl << " ft" << endl + << endl; + return false; + } + + if (isnan(agl) || isnan(lat) || isnan(lon)) { + cerr << "JSBSim is producing NaNs. Exiting." << endl << endl; + return false; + } + return true; +} diff --git a/pool/shard006/C/0117830_netdevices.c b/pool/shard006/C/0117830_netdevices.c new file mode 100644 index 0000000000000000000000000000000000000000..40b2bab3e401445492f91e11661617bda1328f37 --- /dev/null +++ b/pool/shard006/C/0117830_netdevices.c @@ -0,0 +1,47 @@ +/* AFS network device helpers + * + * Copyright (c) 2007 Patrick McHardy + */ + +#include +#include +#include +#include +#include +#include +#include "internal.h" + +/* + * get a list of this system's interface IPv4 addresses, netmasks and MTUs + * - maxbufs must be at least 1 + * - returns the number of interface records in the buffer + */ +int afs_get_ipv4_interfaces(struct afs_interface *bufs, size_t maxbufs, + bool wantloopback) +{ + struct net_device *dev; + struct in_device *idev; + int n = 0; + + ASSERT(maxbufs > 0); + + rtnl_lock(); + for_each_netdev(&init_net, dev) { + if (dev->type == ARPHRD_LOOPBACK && !wantloopback) + continue; + idev = __in_dev_get_rtnl(dev); + if (!idev) + continue; + for_primary_ifa(idev) { + bufs[n].address.s_addr = ifa->ifa_address; + bufs[n].netmask.s_addr = ifa->ifa_mask; + bufs[n].mtu = dev->mtu; + n++; + if (n >= maxbufs) + goto out; + } endfor_ifa(idev); + } +out: + rtnl_unlock(); + return n; +} diff --git a/pool/shard006/C/0117835_hid-emsff.c b/pool/shard006/C/0117835_hid-emsff.c new file mode 100644 index 0000000000000000000000000000000000000000..38391f382a43347066348a5c07df599045a7eac2 --- /dev/null +++ b/pool/shard006/C/0117835_hid-emsff.c @@ -0,0 +1,167 @@ +/* + * Force feedback support for EMS Trio Linker Plus II + * + * Copyright (c) 2010 Ignaz Forster + */ + +/* + * 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 +#include +#include +#include + +#include "hid-ids.h" +#include "usbhid/usbhid.h" + +struct emsff_device { + struct hid_report *report; +}; + +static int emsff_play(struct input_dev *dev, void *data, + struct ff_effect *effect) +{ + struct hid_device *hid = input_get_drvdata(dev); + struct emsff_device *emsff = data; + int weak, strong; + + weak = effect->u.rumble.weak_magnitude; + strong = effect->u.rumble.strong_magnitude; + + dbg_hid("called with 0x%04x 0x%04x\n", strong, weak); + + weak = weak * 0xff / 0xffff; + strong = strong * 0xff / 0xffff; + + emsff->report->field[0]->value[1] = weak; + emsff->report->field[0]->value[2] = strong; + + dbg_hid("running with 0x%02x 0x%02x\n", strong, weak); + usbhid_submit_report(hid, emsff->report, USB_DIR_OUT); + + return 0; +} + +static int emsff_init(struct hid_device *hid) +{ + struct emsff_device *emsff; + struct hid_report *report; + struct hid_input *hidinput = list_first_entry(&hid->inputs, + struct hid_input, list); + struct list_head *report_list = + &hid->report_enum[HID_OUTPUT_REPORT].report_list; + struct input_dev *dev = hidinput->input; + int error; + + if (list_empty(report_list)) { + hid_err(hid, "no output reports found\n"); + return -ENODEV; + } + + report = list_first_entry(report_list, struct hid_report, list); + if (report->maxfield < 1) { + hid_err(hid, "no fields in the report\n"); + return -ENODEV; + } + + if (report->field[0]->report_count < 7) { + hid_err(hid, "not enough values in the field\n"); + return -ENODEV; + } + + emsff = kzalloc(sizeof(struct emsff_device), GFP_KERNEL); + if (!emsff) + return -ENOMEM; + + set_bit(FF_RUMBLE, dev->ffbit); + + error = input_ff_create_memless(dev, emsff, emsff_play); + if (error) { + kfree(emsff); + return error; + } + + emsff->report = report; + emsff->report->field[0]->value[0] = 0x01; + emsff->report->field[0]->value[1] = 0x00; + emsff->report->field[0]->value[2] = 0x00; + emsff->report->field[0]->value[3] = 0x00; + emsff->report->field[0]->value[4] = 0x00; + emsff->report->field[0]->value[5] = 0x00; + emsff->report->field[0]->value[6] = 0x00; + usbhid_submit_report(hid, emsff->report, USB_DIR_OUT); + + hid_info(hid, "force feedback for EMS based devices by Ignaz Forster \n"); + + return 0; +} + +static int ems_probe(struct hid_device *hdev, const struct hid_device_id *id) +{ + int ret; + + ret = hid_parse(hdev); + if (ret) { + hid_err(hdev, "parse failed\n"); + goto err; + } + + ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF); + if (ret) { + hid_err(hdev, "hw start failed\n"); + goto err; + } + + ret = emsff_init(hdev); + if (ret) { + dev_err(&hdev->dev, "force feedback init failed\n"); + hid_hw_stop(hdev); + goto err; + } + + return 0; +err: + return ret; +} + +static const struct hid_device_id ems_devices[] = { + { HID_USB_DEVICE(USB_VENDOR_ID_EMS, USB_DEVICE_ID_EMS_TRIO_LINKER_PLUS_II) }, + { } +}; +MODULE_DEVICE_TABLE(hid, ems_devices); + +static struct hid_driver ems_driver = { + .name = "hkems", + .id_table = ems_devices, + .probe = ems_probe, +}; + +static int ems_init(void) +{ + return hid_register_driver(&ems_driver); +} + +static void ems_exit(void) +{ + hid_unregister_driver(&ems_driver); +} + +module_init(ems_init); +module_exit(ems_exit); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard006/C/0117843_uart.c b/pool/shard006/C/0117843_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..b8598cc4efa83a76d4060b6ca078e30f0a38085d --- /dev/null +++ b/pool/shard006/C/0117843_uart.c @@ -0,0 +1,73 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +/* + * The sole purpose of this driver is to avoid BAR to be changed during + * resource allocation. Since configuration space is just 32 bytes it + * shouldn't cause any fragmentation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void dnv_ns_uart_read_resources(struct device *dev) +{ + /* read resources to be visible in the log*/ + pci_dev_read_resources(dev); + if (!CONFIG(LEGACY_UART_MODE)) + return; + struct resource *res = probe_resource(dev, PCI_BASE_ADDRESS_0); + if (res == NULL) + return; + res->size = 0x8; + res->flags = IORESOURCE_IO | IORESOURCE_ASSIGNED | IORESOURCE_FIXED; + /* Do not configure membar */ + res = probe_resource(dev, PCI_BASE_ADDRESS_1); + if (res != NULL) + res->flags = 0; + compact_resources(dev); + +} + +static struct device_operations uart_ops = { + .read_resources = dnv_ns_uart_read_resources, + .set_resources = pci_dev_set_resources, + .enable_resources = pci_dev_enable_resources, + .init = pci_dev_init, +}; + +static const struct pci_driver uart_driver __pci_driver = { + .ops = &uart_ops, + .vendor = PCI_VID_INTEL, + .device = PCI_DID_INTEL_DNV_HSUART +}; + +static void hide_hsuarts(void) +{ + int i; + printk(BIOS_DEBUG, "HIDING HSUARTs.\n"); + /* There is a hardware requirement to hide functions starting from the + last one. */ + for (i = DENVERTON_UARTS_TO_INI - 1; i >= 0; i--) { + struct device *uart_dev; + uart_dev = pcidev_on_root(HSUART_DEV, i); + if (uart_dev == NULL) + continue; + pci_or_config32(uart_dev, PCI_FUNC_RDCFG_HIDE, 1); + } +} + +/* Hide HSUART PCI device very last when FSP no longer needs it */ +void platform_fsp_notify_status(enum fsp_notify_phase phase) +{ + if (phase != END_OF_FIRMWARE) + return; + if (CONFIG(LEGACY_UART_MODE)) + hide_hsuarts(); +} diff --git a/pool/shard006/C/0117849_pgtable.c b/pool/shard006/C/0117849_pgtable.c new file mode 100644 index 0000000000000000000000000000000000000000..d1c06d07fed867b031aa9c0043661ebf15f0b899 --- /dev/null +++ b/pool/shard006/C/0117849_pgtable.c @@ -0,0 +1,262 @@ +/* + * This file contains the routines setting up the linux page tables. + * + * Copyright (C) 2008 Michal Simek + * Copyright (C) 2008 PetaLogix + * + * Copyright (C) 2007 Xilinx, Inc. All rights reserved. + * + * Derived from arch/ppc/mm/pgtable.c: + * -- paulus + * + * Derived from arch/ppc/mm/init.c: + * Copyright (C) 1995-1996 Gary Thomas (gdt@linuxppc.org) + * + * Modifications by Paul Mackerras (PowerMac) (paulus@cs.anu.edu.au) + * and Cort Dougan (PReP) (cort@cs.nmt.edu) + * Copyright (C) 1996 Paul Mackerras + * Amiga/APUS changes by Jesper Skov (jskov@cygnus.co.uk). + * + * Derived from "arch/i386/mm/init.c" + * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds + * + * 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. + * + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#define flush_HPTE(X, va, pg) _tlbie(va) + +unsigned long ioremap_base; +unsigned long ioremap_bot; +EXPORT_SYMBOL(ioremap_bot); + +#ifndef CONFIG_SMP +struct pgtable_cache_struct quicklists; +#endif + +static void __iomem *__ioremap(phys_addr_t addr, unsigned long size, + unsigned long flags) +{ + unsigned long v, i; + phys_addr_t p; + int err; + + /* + * Choose an address to map it to. + * Once the vmalloc system is running, we use it. + * Before then, we use space going down from ioremap_base + * (ioremap_bot records where we're up to). + */ + p = addr & PAGE_MASK; + size = PAGE_ALIGN(addr + size) - p; + + /* + * Don't allow anybody to remap normal RAM that we're using. + * mem_init() sets high_memory so only do the check after that. + * + * However, allow remap of rootfs: TBD + */ + if (mem_init_done && + p >= memory_start && p < virt_to_phys(high_memory) && + !(p >= virt_to_phys((unsigned long)&__bss_stop) && + p < virt_to_phys((unsigned long)__bss_stop))) { + printk(KERN_WARNING "__ioremap(): phys addr "PTE_FMT + " is RAM lr %pf\n", (unsigned long)p, + __builtin_return_address(0)); + return NULL; + } + + if (size == 0) + return NULL; + + /* + * Is it already mapped? If the whole area is mapped then we're + * done, otherwise remap it since we want to keep the virt addrs for + * each request contiguous. + * + * We make the assumption here that if the bottom and top + * of the range we want are mapped then it's mapped to the + * same virt address (and this is contiguous). + * -- Cort + */ + + if (mem_init_done) { + struct vm_struct *area; + area = get_vm_area(size, VM_IOREMAP); + if (area == NULL) + return NULL; + v = (unsigned long) area->addr; + } else { + v = (ioremap_bot -= size); + } + + if ((flags & _PAGE_PRESENT) == 0) + flags |= _PAGE_KERNEL; + if (flags & _PAGE_NO_CACHE) + flags |= _PAGE_GUARDED; + + err = 0; + for (i = 0; i < size && err == 0; i += PAGE_SIZE) + err = map_page(v + i, p + i, flags); + if (err) { + if (mem_init_done) + vfree((void *)v); + return NULL; + } + + return (void __iomem *) (v + ((unsigned long)addr & ~PAGE_MASK)); +} + +void __iomem *ioremap(phys_addr_t addr, unsigned long size) +{ + return __ioremap(addr, size, _PAGE_NO_CACHE); +} +EXPORT_SYMBOL(ioremap); + +void iounmap(void *addr) +{ + if (addr > high_memory && (unsigned long) addr < ioremap_bot) + vfree((void *) (PAGE_MASK & (unsigned long) addr)); +} +EXPORT_SYMBOL(iounmap); + + +int map_page(unsigned long va, phys_addr_t pa, int flags) +{ + pmd_t *pd; + pte_t *pg; + int err = -ENOMEM; + /* Use upper 10 bits of VA to index the first level map */ + pd = pmd_offset(pgd_offset_k(va), va); + /* Use middle 10 bits of VA to index the second-level map */ + pg = pte_alloc_kernel(pd, va); /* from powerpc - pgtable.c */ + /* pg = pte_alloc_kernel(&init_mm, pd, va); */ + + if (pg != NULL) { + err = 0; + set_pte_at(&init_mm, va, pg, pfn_pte(pa >> PAGE_SHIFT, + __pgprot(flags))); + if (unlikely(mem_init_done)) + flush_HPTE(0, va, pmd_val(*pd)); + /* flush_HPTE(0, va, pg); */ + } + return err; +} + +/* + * Map in all of physical memory starting at CONFIG_KERNEL_START. + */ +void __init mapin_ram(void) +{ + unsigned long v, p, s, f; + + v = CONFIG_KERNEL_START; + p = memory_start; + for (s = 0; s < lowmem_size; s += PAGE_SIZE) { + f = _PAGE_PRESENT | _PAGE_ACCESSED | + _PAGE_SHARED | _PAGE_HWEXEC; + if ((char *) v < _stext || (char *) v >= _etext) + f |= _PAGE_WRENABLE; + else + /* On the MicroBlaze, no user access + forces R/W kernel access */ + f |= _PAGE_USER; + map_page(v, p, f); + v += PAGE_SIZE; + p += PAGE_SIZE; + } +} + +/* is x a power of 2? */ +#define is_power_of_2(x) ((x) != 0 && (((x) & ((x) - 1)) == 0)) + +/* Scan the real Linux page tables and return a PTE pointer for + * a virtual address in a context. + * Returns true (1) if PTE was found, zero otherwise. The pointer to + * the PTE pointer is unmodified if PTE is not found. + */ +static int get_pteptr(struct mm_struct *mm, unsigned long addr, pte_t **ptep) +{ + pgd_t *pgd; + pmd_t *pmd; + pte_t *pte; + int retval = 0; + + pgd = pgd_offset(mm, addr & PAGE_MASK); + if (pgd) { + pmd = pmd_offset(pgd, addr & PAGE_MASK); + if (pmd_present(*pmd)) { + pte = pte_offset_kernel(pmd, addr & PAGE_MASK); + if (pte) { + retval = 1; + *ptep = pte; + } + } + } + return retval; +} + +/* Find physical address for this virtual address. Normally used by + * I/O functions, but anyone can call it. + */ +unsigned long iopa(unsigned long addr) +{ + unsigned long pa; + + pte_t *pte; + struct mm_struct *mm; + + /* Allow mapping of user addresses (within the thread) + * for DMA if necessary. + */ + if (addr < TASK_SIZE) + mm = current->mm; + else + mm = &init_mm; + + pa = 0; + if (get_pteptr(mm, addr, &pte)) + pa = (pte_val(*pte) & PAGE_MASK) | (addr & ~PAGE_MASK); + + return pa; +} + +__init_refok pte_t *pte_alloc_one_kernel(struct mm_struct *mm, + unsigned long address) +{ + pte_t *pte; + if (mem_init_done) { + pte = (pte_t *)__get_free_page(GFP_KERNEL | + __GFP_REPEAT | __GFP_ZERO); + } else { + pte = (pte_t *)early_get_page(); + if (pte) + clear_page(pte); + } + return pte; +} + +void __set_fixmap(enum fixed_addresses idx, phys_addr_t phys, pgprot_t flags) +{ + unsigned long address = __fix_to_virt(idx); + + if (idx >= __end_of_fixed_addresses) + BUG(); + + map_page(address, phys, pgprot_val(flags)); +} diff --git a/pool/shard006/C/0117855_status_bar.c b/pool/shard006/C/0117855_status_bar.c new file mode 100644 index 0000000000000000000000000000000000000000..1a4375b52ae0f4e941c704beaa48817a128b299d --- /dev/null +++ b/pool/shard006/C/0117855_status_bar.c @@ -0,0 +1,45 @@ +#include +#include +#include + +#include "status_bar.h" + + +#define MAX_MSG_SIZE 256 + + +/* widgets */ +static GtkStatusbar *statusbar = NULL; + +/* private data */ +static gchar statusbar_msg[MAX_MSG_SIZE]; +static guint statusbar_ctx = 0; + + +void sb_init(GtkBuilder *builder) +{ + statusbar = GTK_STATUSBAR(gtk_builder_get_object(builder, "statusbar")); + + statusbar_ctx = gtk_statusbar_get_context_id(statusbar, "status_msg"); +} + + +void sb_printf(const gchar *format, ...) +{ + va_list ap; + + va_start(ap, format); + vsnprintf(statusbar_msg, MAX_MSG_SIZE, format, ap); + va_end(ap); + statusbar_msg[MAX_MSG_SIZE-1] = 0; + + gtk_statusbar_pop(statusbar, statusbar_ctx); + gtk_statusbar_push(statusbar, statusbar_ctx, statusbar_msg); +} + + +void sb_clear() +{ + gtk_statusbar_pop(statusbar, statusbar_ctx); +} + diff --git a/pool/shard006/C/0117859_uurdpara.c b/pool/shard006/C/0117859_uurdpara.c new file mode 100644 index 0000000000000000000000000000000000000000..8af1e31505dc7acac23462b82264cfa835399de0 --- /dev/null +++ b/pool/shard006/C/0117859_uurdpara.c @@ -0,0 +1,306 @@ +/* $Id$ */ +/* + * UNIX-Connect, a ZCONNECT(r) Transport and Gateway/Relay. + * Copyright (C) 1993-1994 Martin Husemann + * Copyright (C) 1995 Christopher Creutzig + * Copyright (C) 1999-2000 Dirk Meyer + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * ------------------------------------------------------------------------ + * Eine deutsche Zusammenfassung zum Copyright dieser Programme sowie der + * GNU General Public License finden Sie in der Datei README.1st. + * ------------------------------------------------------------------------ + * + * Bugreports, suggestions for improvement, patches, ports to other systems + * etc. are welcome. Contact the maintainer by e-mail: + * dirk.meyer@dinoex.sub.org or snail-mail: + * Dirk Meyer, Im Grund 4, 34317 Habichtswald + * + * There is a mailing-list for user-support: + * unix-connect-users@lists.sourceforge.net, + * write a mail with subject "Help" to + * unix-connect-users-request@lists.sourceforge.net + * for instructions on how to join this list. + */ + + +/******************************************************************** + * + * File : uurdpara.c + * Autoren : Martin + * + * Routinen zum Einlesen von UUCP-Headern aus + * News- oder SMTP-Batchen. + * + * Compiliert mit "#define SMTP" wird die SMTP-Version + * erzeugt, ansonsten die News-Version. + * + * Unterschied: SMTP markiert das Ende der Eingabe mit "\r\n.\r\n", + * im Newsbatch ist die Laenge der News vorher bekannt. Ausserdem + * ist im Newsbatch ueblicherweise nur "\n" als Zeilenende, + * im SMTP-Batch aber "\r\n". + */ + +#include +#include +#include "istring.h" +#include + +#include "utility.h" +#include "crc.h" +#include "header.h" +#include "uulog.h" +#include "sysexits2.h" + +static char *uugets(char *s, int n, FILE *stream); + +#ifndef SMTP + +extern long readlength; /* Wird auf 0 heruntergezaehlt */ +#define COUNTDOWN(count) readlength -= (count) +#define CHECKCOUNT(action) if (readlength<1) action + +/******************************************************************** + * + * Funktion: header_p uu_rd_para(FILE *input) + * + * Liest einen UUCP-Header aus einem News-Batch. + * Die globale Variable "readlength" (long) wird + * um die gelesene Anzahl von Bytes reduziert. + */ + +header_p uu_rd_para(FILE *f) + +#else /* jetzt kommt die SMTP-Version */ + +#define COUNTDOWN(count) /* - */ +#define CHECKCOUNT(action) /* - */ + +/******************************************************************** + * + * Funktion: header_p smtp_rd_para(FILE *input) + * Liest einen UUCP-Header aus einem SMTP-Batch. + */ + +header_p smtp_rd_para(FILE *f) + +#endif /* SMTP */ + +{ + header_p start; + char c, *p, *str1, *str2, *inhalt; + char buffer[MAX_HEADER_NAME_LEN+1], hname[MAX_HEADER_NAME_LEN+1]; + int was_malloc; + unsigned code; +#ifdef ENABLE_IGNORE_BAD_HEADERS + int line_bad; +#endif + + start = NULL; + while(!feof(f)) { + + CHECKCOUNT(break); + /* naechste Header-Zeile holen */ + if (!uugets(hname, MAX_HEADER_NAME_LEN, f)) break; + hname[MAX_HEADER_NAME_LEN] = '\0'; /* Sentinel */ +#ifdef ENABLE_IGNORE_BAD_HEADERS + line_bad = 0; +#endif + + if ((hname[0] == '\r') || (hname[0] == '\n')) { + if (start) + break; /* Ende einer Header-Liste */ + else + continue; /* Leerzeile am Anfang einer Header-Liste */ + } + + /* Header-Name und Inhalt trennen */ + p = strchr(hname, ':'); + if (!p) + { + newlog( ERRLOG, + __FILE__ " Header ohne Doppelpunkt: %s", + hname); + exit( EX_DATAERR ); + } + *p++ = '\0'; /* p zeigt auf Anfang des Headers. */ + + /* Syntax pruefen */ + for (str1=hname; *str1; str1++) { + if (!isascii(*str1)) + { + newlog( ERRLOG, + __FILE__ " Nicht-ASCII-Zeichen im Header: %s", + hname); +#ifdef ENABLE_IGNORE_BAD_HEADERS + line_bad = 1; + break; +#else + exit( EX_DATAERR ); +#endif + } + if (isspace(*str1)) + { + newlog( ERRLOG, + __FILE__ " Leerzeichen im Headernamen: %s", + hname); +#ifdef ENABLE_IGNORE_BAD_HEADERS + line_bad = 1; + break; +#else + exit( EX_DATAERR ); +#endif + } + } + +#ifdef ENABLE_IGNORE_BAD_HEADERS + if ( line_bad ) + continue; +#endif + + /* Header identifiziern */ + code = identify(hname); + + /* Inhalt einlesen und aufbereiten */ + c = '\0'; + while (1) { + while (*p) + { + /* Anfang des Textes suchen */ + c = *p; + if ((c == '\r') || (c == '\n')) break; + if (!isspace(c)) break; + p++; + } /* Leerzeichen am Anfang nicht zwingend. */ + + if (*p == '\0') { /* Der Inhalt hat hier noch gar nicht begonnen */ + CHECKCOUNT(break); + if (!uugets(buffer, MAX_HEADER_NAME_LEN, f)) break; + buffer[MAX_HEADER_NAME_LEN] = '\0'; + p = buffer; + } else + break; + } + if ((c == '\r') || (c == '\n')) { + inhalt = dstrdup( "" ); + was_malloc = 1; + } else { + inhalt = p; + was_malloc = 0; + + /* Der Header ist beim 1. CR oder 1. LF zuende */ + str1 = strchr(inhalt, '\r'); + if (str1) *str1 = '\0'; + str2 = strchr(inhalt, '\n'); + if (str2) *str2 = '\0'; + + /* Wenn weder \n noch \r gefunden werden, dann ist der + * Header laenger als MAX_HEADER_NAME_LEN Bytes. */ + if (!str1 && !str2) { + while (1) { + str1 = malloc(strlen(inhalt) + MAX_HEADER_NAME_LEN + 1); + if (!str1) + out_of_memory(__FILE__); + strcpy(str1, inhalt); + if (was_malloc) { + dfree(inhalt); + } else { + was_malloc = 1; + } + inhalt = str1; + CHECKCOUNT(break); + if (!uugets(buffer, MAX_HEADER_NAME_LEN, f)) break; + buffer[MAX_HEADER_NAME_LEN] = '\0'; + strcat(inhalt, buffer); + str1 = strchr(inhalt, '\r'); + if (str1) { + *str1 = '\0'; + break; + } + str2 = strchr(inhalt, '\n'); + if (str2) { + *str2 = '\0'; + break; + } + } + } + } + /* Header-Descriptor erzeugen und einbauen */ + start = internal_add_header(inhalt, code, start, hname); + if (was_malloc) dfree(inhalt); + was_malloc = 0; + } + return start; +} + +static char *uugets(char *s, int n, FILE *stream) +{ + static int stop = 0; + int c, last; + char *p; + + if (stop) { + *s = '\n'; + *(s+1) = '\0'; + stop = 0; + return s; + } + p = s; + while (0 < n) { + CHECKCOUNT(break); + c = getc(stream); + COUNTDOWN(1); + if (c == EOF) return NULL; + if (c == '\n' +#ifdef SMTP + || c == '\r' +#endif + ) { + CHECKCOUNT(break); + last = c; + c = getc(stream); + if (last == '\r' && c == '\n') { + COUNTDOWN(1); + c = getc(stream); + } + if ( +#ifdef SMTP + c == '\r' || +#endif + c == '\n') { + *p++ = '\n'; + *p = '\0'; + stop = 1; + COUNTDOWN(1); + return s; + } else if (!isspace(c)) { + ungetc(c, stream); + *p++ = '\n'; + *p = '\0'; + stop = 0; + return s; + } + COUNTDOWN(1); + } + *p++ = c; + n--; + } + *p = '\0'; + return s; +} + + + diff --git a/pool/shard006/C/0117866_shd-async-priority-queue.c b/pool/shard006/C/0117866_shd-async-priority-queue.c new file mode 100644 index 0000000000000000000000000000000000000000..6493ed150d49b4379c3d63fe0bcd53100a3890bd --- /dev/null +++ b/pool/shard006/C/0117866_shd-async-priority-queue.c @@ -0,0 +1,89 @@ +/* + * The Shadow Simulator + * Copyright (c) 2010-2011, Rob Jansen + * See LICENSE for licensing information + */ + +#include + +#include "shd-utility.h" +#include "shd-async-priority-queue.h" +#include "shd-priority-queue.h" + +struct _AsyncPriorityQueue { + PriorityQueue* pq; + GMutex lock; +}; + +AsyncPriorityQueue* asyncpriorityqueue_new(GCompareDataFunc compareFunc, + gpointer compareData, GDestroyNotify freeFunc) { + AsyncPriorityQueue* q = g_new0(AsyncPriorityQueue, 1); + q->pq = priorityqueue_new(compareFunc, compareData, freeFunc); + g_mutex_init(&(q->lock)); + return q; +} + +void asyncpriorityqueue_clear(AsyncPriorityQueue *q) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + priorityqueue_clear(q->pq); + g_mutex_unlock(&(q->lock)); +} + +void asyncpriorityqueue_free(AsyncPriorityQueue *q) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + priorityqueue_free(q->pq); + q->pq = NULL; + g_mutex_unlock(&(q->lock)); + g_mutex_clear(&(q->lock)); + g_free(q); +} + +gsize asyncpriorityqueue_getLength(AsyncPriorityQueue *q) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + gsize returnVal = priorityqueue_getLength(q->pq); + g_mutex_unlock(&(q->lock)); + return returnVal; +} + +gboolean asyncpriorityqueue_isEmpty(AsyncPriorityQueue *q) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + gboolean returnVal = priorityqueue_isEmpty(q->pq); + g_mutex_unlock(&(q->lock)); + return returnVal; +} + +gboolean asyncpriorityqueue_push(AsyncPriorityQueue *q, gpointer data) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + gboolean returnVal = priorityqueue_push(q->pq, data); + g_mutex_unlock(&(q->lock)); + return returnVal; +} + +gpointer asyncpriorityqueue_peek(AsyncPriorityQueue *q) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + gpointer returnData = priorityqueue_peek(q->pq); + g_mutex_unlock(&(q->lock)); + return returnData; +} + +gpointer asyncpriorityqueue_find(AsyncPriorityQueue *q, gpointer data) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + gpointer returnData = priorityqueue_find(q->pq, data); + g_mutex_unlock(&(q->lock)); + return returnData; +} + +gpointer asyncpriorityqueue_pop(AsyncPriorityQueue *q) { + utility_assert(q); + g_mutex_lock(&(q->lock)); + gpointer returnData = priorityqueue_pop(q->pq); + g_mutex_unlock(&(q->lock)); + return returnData; +} diff --git a/pool/shard006/C/0117871_vaxobsd-tdep.c b/pool/shard006/C/0117871_vaxobsd-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..9a1e4e23dd949045f9a266d09f4de92a80cfa105 --- /dev/null +++ b/pool/shard006/C/0117871_vaxobsd-tdep.c @@ -0,0 +1,178 @@ +/* Target-dependent code for OpenBSD/vax. + + Copyright (C) 2005-2015 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include "defs.h" +#include "arch-utils.h" +#include "frame.h" +#include "frame-unwind.h" +#include "osabi.h" +#include "symtab.h" +#include "trad-frame.h" + +#include "vax-tdep.h" + +/* Signal trampolines. */ + +/* Since OpenBSD 3.2, the sigtramp routine is mapped at a random page + in virtual memory. The randomness makes it somewhat tricky to + detect it, but fortunately we can rely on the fact that the start + of the sigtramp routine is page-aligned. We recognize the + trampoline by looking for the code that invokes the sigreturn + system call. The offset where we can find that code varies from + release to release. + + By the way, the mapping mentioned above is read-only, so you cannot + place a breakpoint in the signal trampoline. */ + +/* Default page size. */ +static const int vaxobsd_page_size = 4096; + +/* Offset for sigreturn(2). */ +static const int vaxobsd_sigreturn_offset = 0x11; + +/* Instruction sequence for sigreturn(2). VAX doesn't have + fixed-length instructions so we include the ensuing exit(2) to + reduce the chance of spurious matches. */ +static const gdb_byte vaxobsd_sigreturn[] = { + 0xbc, 0x8f, 0x67, 0x00, /* chmk $SYS_sigreturn */ + 0xbc, 0x01 /* chmk $SYS_exit */ +}; + +static int +vaxobsd_sigtramp_sniffer (const struct frame_unwind *self, + struct frame_info *this_frame, + void **this_cache) +{ + CORE_ADDR pc = get_frame_pc (this_frame); + CORE_ADDR start_pc = (pc & ~(vaxobsd_page_size - 1)); + CORE_ADDR sigreturn_addr = start_pc + vaxobsd_sigreturn_offset; + gdb_byte *buf; + const char *name; + + find_pc_partial_function (pc, &name, NULL, NULL); + if (name) + return 0; + + buf = alloca(sizeof vaxobsd_sigreturn); + if (!safe_frame_unwind_memory (this_frame, sigreturn_addr, + buf, sizeof vaxobsd_sigreturn)) + return 0; + + if (memcmp(buf, vaxobsd_sigreturn, sizeof vaxobsd_sigreturn) == 0) + return 1; + + return 0; +} + +static struct trad_frame_cache * +vaxobsd_sigtramp_frame_cache (struct frame_info *this_frame, void **this_cache) +{ + struct trad_frame_cache *cache; + CORE_ADDR addr, base, func; + + if (*this_cache) + return *this_cache; + + cache = trad_frame_cache_zalloc (this_frame); + *this_cache = cache; + + func = get_frame_pc (this_frame); + func &= ~(vaxobsd_page_size - 1); + + base = get_frame_register_unsigned (this_frame, VAX_SP_REGNUM); + addr = get_frame_memory_unsigned (this_frame, base - 4, 4); + + trad_frame_set_reg_addr (cache, VAX_SP_REGNUM, addr + 8); + trad_frame_set_reg_addr (cache, VAX_FP_REGNUM, addr + 12); + trad_frame_set_reg_addr (cache, VAX_AP_REGNUM, addr + 16); + trad_frame_set_reg_addr (cache, VAX_PC_REGNUM, addr + 20); + trad_frame_set_reg_addr (cache, VAX_PS_REGNUM, addr + 24); + + /* Construct the frame ID using the function start. */ + trad_frame_set_id (cache, frame_id_build (base, func)); + + return cache; +} + +static void +vaxobsd_sigtramp_frame_this_id (struct frame_info *this_frame, + void **this_cache, struct frame_id *this_id) +{ + struct trad_frame_cache *cache = + vaxobsd_sigtramp_frame_cache (this_frame, this_cache); + + trad_frame_get_id (cache, this_id); +} + +static struct value * +vaxobsd_sigtramp_frame_prev_register (struct frame_info *this_frame, + void **this_cache, int regnum) +{ + struct trad_frame_cache *cache = + vaxobsd_sigtramp_frame_cache (this_frame, this_cache); + + return trad_frame_get_register (cache, this_frame, regnum); +} + +static const struct frame_unwind vaxobsd_sigtramp_frame_unwind = { + SIGTRAMP_FRAME, + default_frame_unwind_stop_reason, + vaxobsd_sigtramp_frame_this_id, + vaxobsd_sigtramp_frame_prev_register, + NULL, + vaxobsd_sigtramp_sniffer +}; + + +/* OpenBSD a.out. */ + +static void +vaxobsd_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) +{ + frame_unwind_append_unwinder (gdbarch, &vaxobsd_sigtramp_frame_unwind); +} + +/* FIXME: kettenis/20050821: Since OpenBSD/vax binaries are + indistingushable from NetBSD/vax a.out binaries, building a GDB + that should support both these targets will probably not work as + expected. */ +#define GDB_OSABI_OPENBSD_AOUT GDB_OSABI_NETBSD_AOUT + +static enum gdb_osabi +vaxobsd_aout_osabi_sniffer (bfd *abfd) +{ + if (strcmp (bfd_get_target (abfd), "a.out-vax-netbsd") == 0) + return GDB_OSABI_OPENBSD_AOUT; + + return GDB_OSABI_UNKNOWN; +} + + +/* Provide a prototype to silence -Wmissing-prototypes. */ +void _initialize_vaxobsd_tdep (void); + +void +_initialize_vaxobsd_tdep (void) +{ + gdbarch_register_osabi_sniffer (bfd_arch_vax, bfd_target_aout_flavour, + vaxobsd_aout_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_vax, 0, GDB_OSABI_OPENBSD_AOUT, + vaxobsd_init_abi); +} diff --git a/pool/shard006/C/0117874_19-21.c b/pool/shard006/C/0117874_19-21.c new file mode 100644 index 0000000000000000000000000000000000000000..6f02fca78ee188fdfcf9e37abc759ae4472a3de9 --- /dev/null +++ b/pool/shard006/C/0117874_19-21.c @@ -0,0 +1,154 @@ +/* +* Copyright (c) 2005, Bull S.A.. All rights reserved. +* Created by: Sebastien Decugis + +* This program is free software; you can redistribute it and/or modify it +* under the terms of version 2 of the GNU General Public License as +* published by the Free Software Foundation. +* +* This program is distributed in the hope that it would be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +* +* You should have received a copy of the GNU General Public License along +* with this program; if not, write the Free Software Foundation, Inc., +* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +* This sample test aims to check the following assertions: +* +* If SA_SIGINFO is set in sa_flags and Real Time Signals extension is supported, +* sa_sigaction is used as the signal handling function. + +* The steps are: +* -> test for RTS extension +* -> register a handler for SIGSYS with SA_SIGINFO, and a known function +* as sa_sigaction +* -> raise SIGSYS, and check the function has been called. + +* The test fails if the function is not called +*/ + +/* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ +#define _POSIX_C_SOURCE 200112L + +/******************************************************************************/ +/*************************** standard includes ********************************/ +/******************************************************************************/ +#include +#include +#include +#include +#include +#include + +#include +#include + +/******************************************************************************/ +/*************************** Test framework *******************************/ +/******************************************************************************/ +#include "../testfrmw/testfrmw.h" +#include "../testfrmw/testfrmw.c" +/* This header is responsible for defining the following macros: + * UNRESOLVED(ret, descr); + * where descr is a description of the error and ret is an int + * (error code for example) + * FAILED(descr); + * where descr is a short text saying why the test has failed. + * PASSED(); + * No parameter. + * + * Both three macros shall terminate the calling process. + * The testcase shall not terminate in any other maneer. + * + * The other file defines the functions + * void output_init() + * void output(char * string, ...) + * + * Those may be used to output information. + */ + +/******************************************************************************/ +/**************************** Configuration ***********************************/ +/******************************************************************************/ +#ifndef VERBOSE +#define VERBOSE 1 +#endif + +#define SIGNAL SIGSYS + +/******************************************************************************/ +/*************************** Test case ***********************************/ +/******************************************************************************/ + +int called = 0; +void handler(int sig, siginfo_t * info, void *context) +{ + if (info->si_signo != SIGNAL) { + FAILED("Wrong signal generated?"); + } + + called = 1; +} + +/* main function */ +int main() +{ + int ret; + long rts; + + struct sigaction sa; + + /* Initialize output */ + output_init(); + + /* Test the RTS extension */ + rts = sysconf(_SC_REALTIME_SIGNALS); + + if (rts < 0L) { + UNTESTED("This test needs the RTS extension"); + } + + /* Set the signal handler */ + sa.sa_flags = SA_SIGINFO; + + sa.sa_sigaction = handler; + + ret = sigemptyset(&sa.sa_mask); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to empty signal set"); + } + + /* Install the signal handler for SIGSYS */ + ret = sigaction(SIGNAL, &sa, 0); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to set signal handler"); + } + + if (called) { + FAILED + ("The signal handler has been called when no signal was raised"); + } + + ret = raise(SIGNAL); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to raise SIGSYS"); + } + + if (!called) { + FAILED + ("the sa_handler was not called whereas SA_SIGINFO was not set"); + } + + /* Test passed */ +#if VERBOSE > 0 + + output("Test passed\n"); + +#endif + + PASSED; +} diff --git a/pool/shard006/C/0117876_procfs.c b/pool/shard006/C/0117876_procfs.c new file mode 100644 index 0000000000000000000000000000000000000000..ade4cc9da09086a7ad69ec89852a329ed528d36f --- /dev/null +++ b/pool/shard006/C/0117876_procfs.c @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2010-2014 Junjiro R. Okajima + * + * This program, aufs is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/* + * procfs interfaces + */ + +#include +#include "aufs.h" + +static int au_procfs_plm_release(struct inode *inode, struct file *file) +{ + struct au_sbinfo *sbinfo; + + sbinfo = file->private_data; + if (sbinfo) { + au_plink_maint_leave(sbinfo); + kobject_put(&sbinfo->si_kobj); + } + + return 0; +} + +static void au_procfs_plm_write_clean(struct file *file) +{ + struct au_sbinfo *sbinfo; + + sbinfo = file->private_data; + if (sbinfo) + au_plink_clean(sbinfo->si_sb, /*verbose*/0); +} + +static int au_procfs_plm_write_si(struct file *file, unsigned long id) +{ + int err; + struct super_block *sb; + struct au_sbinfo *sbinfo; + + err = -EBUSY; + if (unlikely(file->private_data)) + goto out; + + sb = NULL; + /* don't use au_sbilist_lock() here */ + spin_lock(&au_sbilist.spin); + list_for_each_entry(sbinfo, &au_sbilist.head, si_list) + if (id == sysaufs_si_id(sbinfo)) { + kobject_get(&sbinfo->si_kobj); + sb = sbinfo->si_sb; + break; + } + spin_unlock(&au_sbilist.spin); + + err = -EINVAL; + if (unlikely(!sb)) + goto out; + + err = au_plink_maint_enter(sb); + if (!err) + /* keep kobject_get() */ + file->private_data = sbinfo; + else + kobject_put(&sbinfo->si_kobj); +out: + return err; +} + +/* + * Accept a valid "si=xxxx" only. + * Once it is accepted successfully, accept "clean" too. + */ +static ssize_t au_procfs_plm_write(struct file *file, const char __user *ubuf, + size_t count, loff_t *ppos) +{ + ssize_t err; + unsigned long id; + /* last newline is allowed */ + char buf[3 + sizeof(unsigned long) * 2 + 1]; + + err = -EACCES; + if (unlikely(!capable(CAP_SYS_ADMIN))) + goto out; + + err = -EINVAL; + if (unlikely(count > sizeof(buf))) + goto out; + + err = copy_from_user(buf, ubuf, count); + if (unlikely(err)) { + err = -EFAULT; + goto out; + } + buf[count] = 0; + + err = -EINVAL; + if (!strcmp("clean", buf)) { + au_procfs_plm_write_clean(file); + goto out_success; + } else if (unlikely(strncmp("si=", buf, 3))) + goto out; + + err = kstrtoul(buf + 3, 16, &id); + if (unlikely(err)) + goto out; + + err = au_procfs_plm_write_si(file, id); + if (unlikely(err)) + goto out; + +out_success: + err = count; /* success */ +out: + return err; +} + +static const struct file_operations au_procfs_plm_fop = { + .write = au_procfs_plm_write, + .release = au_procfs_plm_release, + .owner = THIS_MODULE +}; + +/* ---------------------------------------------------------------------- */ + +static struct proc_dir_entry *au_procfs_dir; + +void au_procfs_fin(void) +{ + remove_proc_entry(AUFS_PLINK_MAINT_NAME, au_procfs_dir); + remove_proc_entry(AUFS_PLINK_MAINT_DIR, NULL); +} + +int __init au_procfs_init(void) +{ + int err; + struct proc_dir_entry *entry; + + err = -ENOMEM; + au_procfs_dir = proc_mkdir(AUFS_PLINK_MAINT_DIR, NULL); + if (unlikely(!au_procfs_dir)) + goto out; + + entry = proc_create(AUFS_PLINK_MAINT_NAME, S_IFREG | S_IWUSR, + au_procfs_dir, &au_procfs_plm_fop); + if (unlikely(!entry)) + goto out_dir; + + err = 0; + goto out; /* success */ + +out_dir: + remove_proc_entry(AUFS_PLINK_MAINT_DIR, NULL); +out: + return err; +} diff --git a/pool/shard006/C/0117883_readdir.c b/pool/shard006/C/0117883_readdir.c new file mode 100644 index 0000000000000000000000000000000000000000..ed694be012c30a7e5642c9e2a1df966c2d5e3860 --- /dev/null +++ b/pool/shard006/C/0117883_readdir.c @@ -0,0 +1,133 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that 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. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)readdir.c 8.3 (Berkeley) 9/29/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/lib/libc/gen/readdir.c 235983 2012-05-19 12:44:27Z gleb $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" +#include "gen-private.h" +#include "telldir.h" + +/* + * get next entry in a directory. + */ +struct dirent * +_readdir_unlocked(dirp, skip) + DIR *dirp; + int skip; +{ + struct dirent *dp; + + for (;;) { + if (dirp->dd_loc >= dirp->dd_size) { + if (dirp->dd_flags & __DTF_READALL) + return (NULL); + dirp->dd_loc = 0; + } + if (dirp->dd_loc == 0 && !(dirp->dd_flags & __DTF_READALL)) { + dirp->dd_size = _getdirentries(dirp->dd_fd, + dirp->dd_buf, dirp->dd_len, &dirp->dd_seek); + if (dirp->dd_size <= 0) + return (NULL); + } + dp = (struct dirent *)(dirp->dd_buf + dirp->dd_loc); + if ((long)dp & 03L) /* bogus pointer check */ + return (NULL); + if (dp->d_reclen <= 0 || + dp->d_reclen > dirp->dd_len + 1 - dirp->dd_loc) + return (NULL); + dirp->dd_loc += dp->d_reclen; + if (dp->d_ino == 0 && skip) + continue; + if (dp->d_type == DT_WHT && (dirp->dd_flags & DTF_HIDEW)) + continue; + return (dp); + } +} + +struct dirent * +readdir(dirp) + DIR *dirp; +{ + struct dirent *dp; + + if (__isthreaded) { + _pthread_mutex_lock(&dirp->dd_lock); + dp = _readdir_unlocked(dirp, 1); + _pthread_mutex_unlock(&dirp->dd_lock); + } + else + dp = _readdir_unlocked(dirp, 1); + return (dp); +} + +int +readdir_r(dirp, entry, result) + DIR *dirp; + struct dirent *entry; + struct dirent **result; +{ + struct dirent *dp; + int saved_errno; + + saved_errno = errno; + errno = 0; + if (__isthreaded) { + _pthread_mutex_lock(&dirp->dd_lock); + if ((dp = _readdir_unlocked(dirp, 1)) != NULL) + memcpy(entry, dp, _GENERIC_DIRSIZ(dp)); + _pthread_mutex_unlock(&dirp->dd_lock); + } + else if ((dp = _readdir_unlocked(dirp, 1)) != NULL) + memcpy(entry, dp, _GENERIC_DIRSIZ(dp)); + + if (errno != 0) { + if (dp == NULL) + return (errno); + } else + errno = saved_errno; + + if (dp != NULL) + *result = entry; + else + *result = NULL; + + return (0); +} diff --git a/pool/shard006/C/0117887_bootpack.c b/pool/shard006/C/0117887_bootpack.c new file mode 100644 index 0000000000000000000000000000000000000000..f831975679bfe529cc87fb8e28193b63a0f2e26c --- /dev/null +++ b/pool/shard006/C/0117887_bootpack.c @@ -0,0 +1,47 @@ +/* bootpack‚̃ƒCƒ“ */ + +#include "bootpack.h" +#include + +extern struct KEYBUF keybuf; + +void HariMain(void) +{ + struct BOOTINFO *binfo = (struct BOOTINFO *) ADR_BOOTINFO; + char s[40], mcursor[256]; + int mx, my, i; + + init_gdtidt(); + init_pic(); + io_sti(); /* IDT/PIC‚̏‰Šú‰»‚ªI‚í‚Á‚½‚Ì‚ÅCPU‚ÌŠ„‚荞‚݋֎~‚ð‰ðœ */ + + io_out8(PIC0_IMR, 0xf9); /* PIC1‚ƃL[ƒ{[ƒh‚ð‹–‰Â(11111001) */ + io_out8(PIC1_IMR, 0xef); /* ƒ}ƒEƒX‚ð‹–‰Â(11101111) */ + + init_palette(); + init_screen8(binfo->vram, binfo->scrnx, binfo->scrny); + mx = (binfo->scrnx - 16) / 2; /* ‰æ–Ê’†‰›‚É‚È‚é‚æ‚¤‚ɍÀ•WŒvŽZ */ + my = (binfo->scrny - 28 - 16) / 2; + init_mouse_cursor8(mcursor, COL8_008484); + putblock8_8(binfo->vram, binfo->scrnx, 16, 16, mx, my, mcursor, 16); + sprintf(s, "(%d, %d)", mx, my); + putfonts8_asc(binfo->vram, binfo->scrnx, 0, 0, COL8_FFFFFF, s); + + for (;;) { + io_cli(); + if (keybuf.len == 0) { + io_stihlt(); + } else { + i = keybuf.data[keybuf.next_r]; + keybuf.len--; + keybuf.next_r++; + if (keybuf.next_r == 32) { + keybuf.next_r = 0; + } + io_sti(); + sprintf(s, "%02X", i); + boxfill8(binfo->vram, binfo->scrnx, COL8_008484, 0, 16, 15, 31); + putfonts8_asc(binfo->vram, binfo->scrnx, 0, 16, COL8_FFFFFF, s); + } + } +} diff --git a/pool/shard006/C/0117889_test_fw.c b/pool/shard006/C/0117889_test_fw.c new file mode 100644 index 0000000000000000000000000000000000000000..b18624fc53cc977ffbf32793d1e8701b50d69df2 --- /dev/null +++ b/pool/shard006/C/0117889_test_fw.c @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include "common.h" + +static struct lsdn_context *ctx; +static struct lsdn_settings *settings; +static struct lsdn_net *net; +static struct lsdn_phys *phys; +static struct lsdn_virt *v1, *v2; + +int main(int argc, const char* argv[]) +{ + assert(argc == 1); + + ctx = lsdn_context_new("ls"); + lsdn_context_abort_on_nomem(ctx); + settings = settings_from_env(ctx); + net = lsdn_net_new(settings, 1); + phys = lsdn_phys_new(ctx); + lsdn_phys_attach(phys, net); + lsdn_phys_set_iface(phys, "out"); + lsdn_phys_set_ip(phys, LSDN_MK_IPV4(172, 16, 0, 1)); + lsdn_phys_claim_local(phys); + + v1 = lsdn_virt_new(net); + lsdn_virt_set_mac(v1, LSDN_MK_MAC(0x00, 0x00, 0x00, 0x00, 0x00, 0xa1)); + lsdn_virt_connect(v1, phys, "1"); + + lsdn_vr_new_src_ip(v1, 0, LSDN_IN, LSDN_MK_IPV4(192, 168, 99, 2), &LSDN_VR_DROP); + lsdn_vr_new_dst_ip(v1, 0, LSDN_OUT, LSDN_MK_IPV4(192, 168, 99, 3), &LSDN_VR_DROP); + + v2 = lsdn_virt_new(net); + lsdn_virt_set_mac(v2, LSDN_MK_MAC(0x00, 0x00, 0x00, 0x00, 0x00, 0xa2)); + lsdn_virt_connect(v2, phys, "2"); + + lsdn_commit(ctx, lsdn_problem_stderr_handler, NULL); + + lsdn_context_free(ctx); + return 0; +} diff --git a/pool/shard006/C/0117893_isotest10.c b/pool/shard006/C/0117893_isotest10.c new file mode 100644 index 0000000000000000000000000000000000000000..3d5296a4cdd9a30489921640708e8a9f5e7cb2b4 --- /dev/null +++ b/pool/shard006/C/0117893_isotest10.c @@ -0,0 +1,103 @@ +#include "common.h" +//READ_COMMITTED isolation testing +// T1 T2 +// ------------------------- +// Read +// Update +// Read +// T1 should read updated tuple by T2 +void* runTest1(void *p); +void* runTest2(void *p); +int *p1RetVal = NULL; +int *p2RetVal = NULL; +int selectDone =0, updateDone=0, allDone=0; +int main() +{ + + Connection conn; + DbRetVal rv = conn.open("root", "manager"); + if (rv != OK) { printf("Error during connection %d\n", rv); return 1; } + DatabaseManager *dbMgr = conn.getDatabaseManager(); + int ret = createTable(dbMgr); + if (ret != 0) { return 1; } + + rv = conn.startTransaction(); + if (rv != OK) {printf ("Unable to start trans\n"); return 1; } + rv = insert(dbMgr, 100, false); + if (rv != OK) { printf("Unable to insert\n"); return 2; } + conn.commit(); + printf("Tuple inserted\n"); + + pthread_t thr[2]; + int *status1, *status2; + pthread_create (&thr[0], NULL, &runTest1, NULL); + pthread_create (&thr[1], NULL, &runTest2, NULL); + printf("All threads started\n"); + + pthread_join(thr[0], (void**)&status1); + pthread_join(thr[1], (void**)&status2); + ret = 0; + if (*status1 != 0 || *status2 != 0) ret = 1; + dbMgr->dropTable("t1"); + conn.close(); + if (p1RetVal) { delete p1RetVal; p1RetVal = NULL; } + if (p2RetVal) { delete p2RetVal; p2RetVal = NULL; } + return ret; +} +void* runTest1(void *message) +{ + Connection conn; + DbRetVal rv = conn.open("root", "manager"); + if (rv != OK) { printf("Error during connection %d\n", rv); return NULL; } + DatabaseManager *dbMgr = conn.getDatabaseManager(); + if (dbMgr == NULL) { printf("Auth failed\n"); return NULL;} +#ifndef DEFAULT + rv = conn.startTransaction(READ_COMMITTED); +#else + rv = conn.startTransaction(); +#endif + + if (rv != OK) return NULL; + printf("Thread and pid is %d %lu\n", os::getpid(), os::getthrid()); + p1RetVal = new int(); + *p1RetVal = 0; + rv = select(dbMgr, 100, true); + if (rv != OK) { printf("Test Failed:first thread read failed \n"); *p1RetVal = 1; } + selectDone = 1; + while (updateDone != 1) {::sleep(1); } + rv = select(dbMgr, 100, true, true); + if (rv == OK) { printf("Test Failed:first thread read succeeded \n"); *p1RetVal = 1; } + allDone = 1; + conn.commit(); + rv = conn.close(); + pthread_exit(p1RetVal); +} +void* runTest2(void *message) +{ + os::sleep(1); + Connection conn; + DbRetVal rv = conn.open("root", "manager"); + if (rv != OK) { printf("Error during connection %d\n", rv); return NULL; } + DatabaseManager *dbMgr = conn.getDatabaseManager(); + if (dbMgr == NULL) { printf("Auth failed\n"); return NULL;} +#ifndef DEFAULT + rv = conn.startTransaction(READ_COMMITTED); +#else + rv = conn.startTransaction(); +#endif + + if (rv != OK) return NULL; + printf("Thread and pid is %d %lu\n", os::getpid(), os::getthrid()); + while (selectDone != 1) {::sleep(1); } + + p2RetVal = new int(); + *p2RetVal = 0; + rv = update(dbMgr, 100, true); + if (rv != OK) { printf("Test Failed:second thread failed to update\n"); *p2RetVal = 1; } + updateDone = 1; + while (allDone !=1) ::sleep(1); + conn.commit(); + conn.close(); + pthread_exit(p2RetVal); +} + diff --git a/pool/shard006/C/0117900_ohci-s5pc110.c b/pool/shard006/C/0117900_ohci-s5pc110.c new file mode 100644 index 0000000000000000000000000000000000000000..67d4c9dee4e0259b76236f4f074da40b665c73ea --- /dev/null +++ b/pool/shard006/C/0117900_ohci-s5pc110.c @@ -0,0 +1,239 @@ +/* ohci-s5pc110.c - Driver for USB HOST on Samsung S5PC110 processor + * + * Bus Glue for SAMSUNG S5PC110 USB HOST OHCI Controller + * + * (C) Copyright 1999 Roman Weissgaerber + * (C) Copyright 2000-2002 David Brownell + * (C) Copyright 2002 Hewlett-Packard Company + * Copyright (c) 2010 Samsung Electronics Co., Ltd. + * Author: Jingoo Han + * + * Based on "ohci-au1xxx.c" by Matt Porter + * Modified for SAMSUNG s5pc110 OHCI by Jingoo Han + * + * 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 +#include + +static struct clk *usb_clk; + +extern int usb_disabled(void); + +extern void usb_host_phy_init(void); +extern void usb_host_phy_off(void); + +static void s5pc110_start_ohc(void); +static void s5pc110_stop_ohc(void); +static int ohci_hcd_s5pc110_drv_probe(struct platform_device *pdev); +static int ohci_hcd_s5pc110_drv_remove(struct platform_device *pdev); + +#ifdef CONFIG_PM +static int ohci_hcd_s5pc110_drv_suspend(struct platform_device *pdev, pm_message_t message) +{ + struct usb_hcd *hcd = platform_get_drvdata(pdev); + struct ohci_hcd *ohci = hcd_to_ohci(hcd); + unsigned long flags; + int rc = 0; + + /* Root hub was already suspended. Disable irq emission and + * mark HW unaccessible, bail out if RH has been resumed. Use + * the spinlock to properly synchronize with possible pending + * RH suspend or resume activity. + * + * This is still racy as hcd->state is manipulated outside of + * any locks =P But that will be a different fix. + */ + spin_lock_irqsave(&ohci->lock, flags); + if (hcd->state != HC_STATE_SUSPENDED) { + rc = -EINVAL; + goto bail; + } + + /* make sure snapshot being resumed re-enumerates everything */ + if (message.event == PM_EVENT_PRETHAW) { + ohci_usb_reset(ohci); + } + + clear_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); + + s5pc110_stop_ohc(); +bail: + spin_unlock_irqrestore(&ohci->lock, flags); + + return rc; +} +static int ohci_hcd_s5pc110_drv_resume(struct platform_device *pdev) +{ + struct usb_hcd *hcd = platform_get_drvdata(pdev); + int rc = 0; + + s5pc110_start_ohc(); + + /* Mark hardware accessible again as we are out of D3 state by now */ + set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags); + + ohci_finish_controller_resume(hcd); + + return rc; +} +#else +#define ohci_hcd_s5pc110_drv_suspend NULL +#define ohci_hcd_s5pc110_drv_resume NULL +#endif + + +static void s5pc110_start_ohc(void) +{ + clk_enable(usb_clk); + usb_host_phy_init(); +} + +static void s5pc110_stop_ohc(void) +{ + usb_host_phy_off(); + clk_disable(usb_clk); +} + +static int __devinit ohci_s5pc110_start(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci(hcd); + int ret; + + ohci_dbg(ohci, "ohci_s5pc110_start, ohci:%p", ohci); + + if ((ret = ohci_init(ohci)) < 0) + return ret; + + if ((ret = ohci_run(ohci)) < 0) { + err ("can't start %s", hcd->self.bus_name); + ohci_stop(hcd); + return ret; + } + + return 0; +} + +static const struct hc_driver ohci_s5pc110_hc_driver = { + .description = hcd_name, + .product_desc = "s5pc110 OHCI", + .hcd_priv_size = sizeof(struct ohci_hcd), + + .irq = ohci_irq, + .flags = HCD_MEMORY|HCD_USB11, + + .start = ohci_s5pc110_start, + .stop = ohci_stop, + .shutdown = ohci_shutdown, + + .get_frame_number = ohci_get_frame, + + .urb_enqueue = ohci_urb_enqueue, + .urb_dequeue = ohci_urb_dequeue, + .endpoint_disable = ohci_endpoint_disable, + + .hub_status_data = ohci_hub_status_data, + .hub_control = ohci_hub_control, +#ifdef CONFIG_PM + .bus_suspend = ohci_bus_suspend, + .bus_resume = ohci_bus_resume, +#endif + .start_port_reset = ohci_start_port_reset, +}; + +static int ohci_hcd_s5pc110_drv_probe(struct platform_device *pdev) +{ + struct usb_hcd *hcd = NULL; + int retval = 0; + + if (usb_disabled()) { + return -ENODEV; + } + + if (pdev->resource[1].flags != IORESOURCE_IRQ) { + dev_err(&pdev->dev,"resource[1] is not IORESOURCE_IRQ.\n"); + return -ENODEV; + } + + hcd = usb_create_hcd(&ohci_s5pc110_hc_driver, &pdev->dev, "s5pc110"); + if (!hcd) { + dev_err(&pdev->dev,"usb_create_hcd failed!\n"); + return -ENODEV; + } + + hcd->rsrc_start = pdev->resource[0].start; + hcd->rsrc_len = pdev->resource[0].end - pdev->resource[0].start + 1; + + if(!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, hcd_name)) { + dev_err(&pdev->dev,"request_mem_region failed!\n"); + retval = -EBUSY; + goto err1; + } + + usb_clk = clk_get(&pdev->dev, "usb-host"); + if (IS_ERR(usb_clk)) { + dev_err(&pdev->dev, "cannot get usb-host clock\n"); + retval = -ENODEV; + goto err2; + } + + s5pc110_start_ohc(); + + hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len); + if (!hcd->regs) { + dev_err(&pdev->dev,"ioremap failed!\n"); + retval = -ENOMEM; + goto err2; + } + + ohci_hcd_init(hcd_to_ohci(hcd)); + + retval = usb_add_hcd(hcd, pdev->resource[1].start, + IRQF_DISABLED | IRQF_SHARED); + + if (retval == 0) { + platform_set_drvdata(pdev, hcd); + return retval; + } + + s5pc110_stop_ohc(); + iounmap(hcd->regs); +err2: + release_mem_region(hcd->rsrc_start, hcd->rsrc_len); +err1: + clk_put(usb_clk); + usb_put_hcd(hcd); + return retval; +} + +static int ohci_hcd_s5pc110_drv_remove(struct platform_device *pdev) +{ + struct usb_hcd *hcd = platform_get_drvdata(pdev); + + usb_remove_hcd(hcd); + iounmap(hcd->regs); + release_mem_region(hcd->rsrc_start, hcd->rsrc_len); + usb_put_hcd(hcd); + s5pc110_stop_ohc(); + clk_put(usb_clk); + platform_set_drvdata(pdev, NULL); + + return 0; +} + +static struct platform_driver ohci_hcd_s5pc110_driver = { + .probe = ohci_hcd_s5pc110_drv_probe, + .remove = ohci_hcd_s5pc110_drv_remove, + .shutdown = usb_hcd_platform_shutdown, + .suspend = ohci_hcd_s5pc110_drv_suspend, + .resume = ohci_hcd_s5pc110_drv_resume, + .driver = { + .name = "s5pc110-ohci", + .owner = THIS_MODULE, + } +}; + +MODULE_ALIAS("platform:s5pc110-ohci"); diff --git a/pool/shard006/C/0117907_main_alt.c b/pool/shard006/C/0117907_main_alt.c new file mode 100644 index 0000000000000000000000000000000000000000..06012a7b5343ab1272126f7033a38af81a5fc399 --- /dev/null +++ b/pool/shard006/C/0117907_main_alt.c @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "ntfs.h" + +#define PATH_MAX 255 +#define USB_MASS_STORAGE_1(n) (0x10300000000000AULL+(n)) /* For 0-5 */ +#define USB_MASS_STORAGE_2(n) (0x10300000000001FULL+((n)-6)) /* For 6-127 */ +#define USB_MASS_STORAGE(n) (((n) < 6) ? USB_MASS_STORAGE_1(n) : USB_MASS_STORAGE_2(n)) + +SYS_PROCESS_PARAM(1001, 0x10000) +static char buff[4096]; + +int LOG; + +void log_printf(const char *format, ...); +void list(const char *path, int depth); + +void log_printf(const char *format, ...) +{ + char *str = (char *) buff; + va_list opt; + + va_start(opt, format); + vsprintf( (void *) buff, format, opt); + va_end(opt); + + uint64_t sw; + cellFsWrite(LOG, (const void *) str, (uint64_t)strlen(str), &sw); +} + +const DISC_INTERFACE *disc_ntfs[8]= { + &__io_ntfs_usb000, + &__io_ntfs_usb001, + &__io_ntfs_usb002, + &__io_ntfs_usb003, + &__io_ntfs_usb004, + &__io_ntfs_usb005, + &__io_ntfs_usb006, + &__io_ntfs_usb007 +}; + +ntfs_md *mounts; +int mountCount; + +char message[] ="This is a NTFS file test writing"; +char buffer[1024]; + +int main(int32_t argc, const char* argv[]) +{ + int ret; + + ret = cellSysmoduleLoadModule(CELL_SYSMODULE_FS); + if (ret != CELL_OK) return ret; + + ret = cellFsOpen("/dev_hdd0/libntfs_sample_log.txt", + CELL_FS_O_RDWR|CELL_FS_O_CREAT, &LOG, NULL, 0); + if(ret) return ret; + + log_printf("\n\nntfsMountAll"); + mountCount = ntfsMountAll(&mounts, NTFS_DEFAULT | NTFS_RECOVER /* | NTFS_READ_ONLY */ ); + if (mountCount <= 0) log_printf("\n\nCan't mount"); + + int r; + + // NTFS operation to write + log_printf("\n\nWriting to ntfs0"); + r = ps3ntfs_open("ntfs0:/text.txt", O_CREAT | O_WRONLY | O_TRUNC, 0777); + log_printf(" : %d", r); + + // FAT operation to write (from internal device) + log_printf("\n\nWriting to usb000"); + r = ps3ntfs_open("/dev_usb000/text.txt", O_CREAT | O_WRONLY | O_TRUNC, 0777); + log_printf(" : %d", r); + + // FAT failed operation usb000 + log_printf("\n\nWriting to wrong path in usb000"); + r = ps3ntfs_open("/dev_usb000/blurps/text.txt", O_CREAT | O_WRONLY | O_TRUNC, 0777); + log_printf(" : %d", r); + + // FAT operation to write (from internal device) + log_printf("\n\nWriting to hdd0"); + r = ps3ntfs_open("/dev_hdd0/text.txt", O_CREAT | O_WRONLY | O_TRUNC, 0777); + log_printf(" : %d", r); + + // NTFS failed operation + log_printf("\n\nWriting to wrong path in ntfs0"); + r = ps3ntfs_open("ntfs0:/blurps/text.txt", O_CREAT | O_WRONLY | O_TRUNC, 0777); + log_printf(" : %d", r); + + log_printf("\n\nUnmounting..."); + for (uint8_t u = 0; u < mountCount; u++) ntfsUnmount(mounts[u].name, 1); + + return 0; +} diff --git a/pool/shard006/C/0117919_check_arp.c b/pool/shard006/C/0117919_check_arp.c new file mode 100644 index 0000000000000000000000000000000000000000..85f2bbde485f61873e81216606e9af38a975a633 --- /dev/null +++ b/pool/shard006/C/0117919_check_arp.c @@ -0,0 +1,76 @@ + +#include + +#include + +#include +#include +#include + +#include + +START_TEST(test_arp_pack) +{ +} +END_TEST + +START_TEST(test_arp_openclose) +{ + arp_t *a; + + fail_unless((a = arp_open()) != NULL, "open failed"); + fail_unless((a = arp_close(a)) == NULL, "close failed"); +} +END_TEST + +START_TEST(test_arp_add) +{ + +} +END_TEST + +START_TEST(test_arp_delete) +{ +} +END_TEST + +START_TEST(test_arp_get) +{ +} +END_TEST + +START_TEST(test_arp_loop) +{ +} +END_TEST + +Suite * +arp_suite(void) +{ + Suite *s = suite_create("arp"); + TCase *tc_core = tcase_create("core"); + + suite_add_tcase(s, tc_core); + tcase_add_test(tc_core, test_arp_pack); + tcase_add_test(tc_core, test_arp_openclose); + tcase_add_test(tc_core, test_arp_add); + tcase_add_test(tc_core, test_arp_delete); + tcase_add_test(tc_core, test_arp_get); + tcase_add_test(tc_core, test_arp_loop); + + return (s); +} + +int +main(void) +{ + Suite *s = arp_suite(); + SRunner *sr = srunner_create(s); + int nf; + + srunner_run_all (sr, CK_NORMAL); + nf = srunner_ntests_failed(sr); + srunner_free(sr); + + return (nf == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/pool/shard006/C/0117927_pipe_lat.c b/pool/shard006/C/0117927_pipe_lat.c new file mode 100644 index 0000000000000000000000000000000000000000..cecf6757b2535987d104e908c11dc084de00b508 --- /dev/null +++ b/pool/shard006/C/0117927_pipe_lat.c @@ -0,0 +1,148 @@ +/* + Measure latency of IPC using unix domain sockets + + + Copyright (c) 2016 Erik Rigtorp + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. +*/ + +#define __STDC_FORMAT_MACROS +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) && \ + defined(_POSIX_MONOTONIC_CLOCK) +#define HAS_CLOCK_GETTIME_MONOTONIC +#endif + +int main(int argc, char *argv[]) { + int ofds[2]; + int ifds[2]; + + int size; + char *buf; + int64_t count, i, delta; +#ifdef HAS_CLOCK_GETTIME_MONOTONIC + struct timespec start, stop; +#else + struct timeval start, stop; +#endif + + if (argc != 3) { + printf("usage: pipe_lat \n"); + return 1; + } + + size = atoi(argv[1]); + count = atol(argv[2]); + + buf = malloc(size); + if (buf == NULL) { + perror("malloc"); + return 1; + } + + printf("message size: %i octets\n", size); + printf("roundtrip count: %" PRId64 "\n", count); + + if (pipe(ofds) == -1) { + perror("pipe"); + return 1; + } + + if (pipe(ifds) == -1) { + perror("pipe"); + return 1; + } + + if (!fork()) { /* child */ + for (i = 0; i < count; i++) { + + if (read(ifds[0], buf, size) != size) { + perror("read"); + return 1; + } + + if (write(ofds[1], buf, size) != size) { + perror("write"); + return 1; + } + } + } else { /* parent */ + +#ifdef HAS_CLOCK_GETTIME_MONOTONIC + if (clock_gettime(CLOCK_MONOTONIC, &start) == -1) { + perror("clock_gettime"); + return 1; + } +#else + if (gettimeofday(&start, NULL) == -1) { + perror("gettimeofday"); + return 1; + } +#endif + + for (i = 0; i < count; i++) { + + if (write(ifds[1], buf, size) != size) { + perror("write"); + return 1; + } + + if (read(ofds[0], buf, size) != size) { + perror("read"); + return 1; + } + } + +#ifdef HAS_CLOCK_GETTIME_MONOTONIC + if (clock_gettime(CLOCK_MONOTONIC, &stop) == -1) { + perror("clock_gettime"); + return 1; + } + + delta = ((stop.tv_sec - start.tv_sec) * 1000000000 + + (stop.tv_nsec - start.tv_nsec)); + +#else + if (gettimeofday(&stop, NULL) == -1) { + perror("gettimeofday"); + return 1; + } + + delta = (stop.tv_sec - start.tv_sec) * 1000000000 + + (stop.tv_usec - start.tv_usec) * 1000; + +#endif + + printf("average latency: %" PRId64 " ns\n", delta / (count * 2)); + } + + return 0; +} diff --git a/pool/shard006/C/0117932_CWE126_Buffer_Overread__wchar_t_declare_memcpy_66a.c b/pool/shard006/C/0117932_CWE126_Buffer_Overread__wchar_t_declare_memcpy_66a.c new file mode 100644 index 0000000000000000000000000000000000000000..7587f6d762f496130ef7b510f4e143da6442aa95 --- /dev/null +++ b/pool/shard006/C/0117932_CWE126_Buffer_Overread__wchar_t_declare_memcpy_66a.c @@ -0,0 +1,98 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE126_Buffer_Overread__wchar_t_declare_memcpy_66a.c +Label Definition File: CWE126_Buffer_Overread.stack.label.xml +Template File: sources-sink-66a.tmpl.c +*/ +/* + * @description + * CWE: 126 Buffer Over-read + * BadSource: Set data pointer to a small buffer + * GoodSource: Set data pointer to a large buffer + * Sinks: memcpy + * BadSink : Copy data to string using memcpy + * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE126_Buffer_Overread__wchar_t_declare_memcpy_66b_badSink(wchar_t * dataArray[]); + +void CWE126_Buffer_Overread__wchar_t_declare_memcpy_66_bad() +{ + wchar_t * data; + wchar_t * dataArray[5]; + wchar_t dataBadBuffer[50]; + wchar_t dataGoodBuffer[100]; + wmemset(dataBadBuffer, L'A', 50-1); /* fill with 'A's */ + dataBadBuffer[50-1] = L'\0'; /* null terminate */ + wmemset(dataGoodBuffer, L'A', 100-1); /* fill with 'A's */ + dataGoodBuffer[100-1] = L'\0'; /* null terminate */ + /* FLAW: Set data pointer to a small buffer */ + data = dataBadBuffer; + /* put data in array */ + dataArray[2] = data; + CWE126_Buffer_Overread__wchar_t_declare_memcpy_66b_badSink(dataArray); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE126_Buffer_Overread__wchar_t_declare_memcpy_66b_goodG2BSink(wchar_t * dataArray[]); + +static void goodG2B() +{ + wchar_t * data; + wchar_t * dataArray[5]; + wchar_t dataBadBuffer[50]; + wchar_t dataGoodBuffer[100]; + wmemset(dataBadBuffer, L'A', 50-1); /* fill with 'A's */ + dataBadBuffer[50-1] = L'\0'; /* null terminate */ + wmemset(dataGoodBuffer, L'A', 100-1); /* fill with 'A's */ + dataGoodBuffer[100-1] = L'\0'; /* null terminate */ + /* FIX: Set data pointer to a large buffer */ + data = dataGoodBuffer; + dataArray[2] = data; + CWE126_Buffer_Overread__wchar_t_declare_memcpy_66b_goodG2BSink(dataArray); +} + +void CWE126_Buffer_Overread__wchar_t_declare_memcpy_66_good() +{ + goodG2B(); +} + +#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()..."); + CWE126_Buffer_Overread__wchar_t_declare_memcpy_66_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE126_Buffer_Overread__wchar_t_declare_memcpy_66_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0117933_abrt-action-generate-core-backtrace.c b/pool/shard006/C/0117933_abrt-action-generate-core-backtrace.c new file mode 100644 index 0000000000000000000000000000000000000000..b40bad0d0232613de16a74e30d9eb2b659a14ae5 --- /dev/null +++ b/pool/shard006/C/0117933_abrt-action-generate-core-backtrace.c @@ -0,0 +1,106 @@ +/* + Copyright (C) 2011 ABRT team + Copyright (C) 2011 RedHat Inc + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ +#include +#include + +#include "libabrt.h" + +int main(int argc, char **argv) +{ + /* I18n */ + setlocale(LC_ALL, ""); +#if ENABLE_NLS + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); +#endif + + abrt_init(argv); + + const char *dump_dir_name = "."; + + /* Can't keep these strings/structs static: _() doesn't support that */ + const char *program_usage_string = _( + "& [-v] [-r] -d DIR\n" + "\n" + "Creates coredump-level backtrace from core dump and corresponding binary" + ); + enum { + OPT_v = 1 << 0, + OPT_d = 1 << 1, + }; + /* Keep enum above and order of options below in sync! */ + struct options program_options[] = { + OPT__VERBOSE(&libreport_g_verbose), + OPT_STRING('d', NULL, &dump_dir_name, "DIR", _("Problem directory")), + OPT_END() + }; + /*unsigned opts =*/ libreport_parse_opts(argc, argv, program_options, program_usage_string); + + libreport_export_abrt_envvars(0); + + if (libreport_g_verbose > 1) + sr_debug_parser = true; + + /* Let user know what's going on */ + log_notice(_("Generating core_backtrace")); + + g_autofree char *error_message = NULL; + bool success; + + struct dump_dir *dd = dd_opendir(dump_dir_name, /*flags:*/ 0); + if (!dd) + { + log_warning("Can't open problem directory '%s'", dump_dir_name); + return 1; + } + + /* The value 240 was taken from abrt-action-generate-backtrace.c. */ + int exec_timeout_sec = 240; + + if (!dd_exist(dd, FILENAME_COREDUMP)) + { + abrt_save_coredump(dd, exec_timeout_sec); + } +#ifdef ENABLE_NATIVE_UNWINDER + + success = sr_abrt_create_core_stacktrace(dump_dir_name, false, &error_message); +#else /* ENABLE_NATIVE_UNWINDER */ + + g_autofree char *gdb_output = abrt_get_backtrace(dd, exec_timeout_sec, NULL); + if (!gdb_output) + { + log_warning(_("Error: GDB did not return any data")); + return 1; + } + + success = sr_abrt_create_core_stacktrace_from_gdb(dump_dir_name, + gdb_output, false, + &error_message); + +#endif /* ENABLE_NATIVE_UNWINDER */ + dd_close(dd); + + if (!success) + { + log_warning(_("Error: %s"), error_message); + return 1; + } + + return 0; +} diff --git a/pool/shard006/C/0117935_func_db.c b/pool/shard006/C/0117935_func_db.c new file mode 100644 index 0000000000000000000000000000000000000000..b56fef9f5e3937a4cb3cf8a63d0e44d69a0174cf --- /dev/null +++ b/pool/shard006/C/0117935_func_db.c @@ -0,0 +1,362 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 2005-2006, Russell Bryant + * + * func_db.c adapted from the old app_db.c, copyright by the following people + * Copyright (C) 2005, Mark Spencer + * Copyright (C) 2003, Jefferson Noxon + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Functions for interaction with the Asterisk database + * + * \author Russell Bryant + * + * \ingroup functions + */ + +/*** MODULEINFO + core + ***/ + +#include "asterisk.h" + +ASTERISK_FILE_VERSION(__FILE__, "$Revision$") + +#include + +#include "asterisk/module.h" +#include "asterisk/channel.h" +#include "asterisk/pbx.h" +#include "asterisk/utils.h" +#include "asterisk/app.h" +#include "asterisk/astdb.h" + +/*** DOCUMENTATION + + + Read from or write to the Asterisk database. + + + + + + + This function will read from or write a value to the Asterisk database. On a + read, this function returns the corresponding value from the database, or blank + if it does not exist. Reading a database value will also set the variable + DB_RESULT. If you wish to find out if an entry exists, use the DB_EXISTS + function. + + + DBdel + DB_DELETE + DBdeltree + DB_EXISTS + + + + + Check to see if a key exists in the Asterisk database. + + + + + + + This function will check to see if a key exists in the Asterisk + database. If it exists, the function will return 1. If not, + it will return 0. Checking for existence of a database key will + also set the variable DB_RESULT to the key's value if it exists. + + + DB + + + + + Obtain a list of keys within the Asterisk database. + + + + + + This function will return a comma-separated list of keys existing + at the prefix specified within the Asterisk database. If no argument is + provided, then a list of key families will be returned. + + + + + Return a value from the database and delete it. + + + + + + + This function will retrieve a value from the Asterisk database + and then remove that key from the database. DB_RESULT + will be set to the key's value if it exists. + + If live_dangerously in asterisk.conf + is set to no, this function can only be read from the + dialplan, and not directly from external protocols. It can, however, be + executed as a write operation (DB_DELETE(family, key)=ignored) + + + + DBdel + DB + DBdeltree + + + ***/ + +static int function_db_read(struct ast_channel *chan, const char *cmd, + char *parse, char *buf, size_t len) +{ + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(family); + AST_APP_ARG(key); + ); + + buf[0] = '\0'; + + if (ast_strlen_zero(parse)) { + ast_log(LOG_WARNING, "DB requires an argument, DB(/)\n"); + return -1; + } + + AST_NONSTANDARD_APP_ARGS(args, parse, '/'); + + if (args.argc < 2) { + ast_log(LOG_WARNING, "DB requires an argument, DB(/)\n"); + return -1; + } + + if (ast_db_get(args.family, args.key, buf, len - 1)) { + ast_debug(1, "DB: %s/%s not found in database.\n", args.family, args.key); + } else { + pbx_builtin_setvar_helper(chan, "DB_RESULT", buf); + } + + return 0; +} + +static int function_db_write(struct ast_channel *chan, const char *cmd, char *parse, + const char *value) +{ + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(family); + AST_APP_ARG(key); + ); + + if (ast_strlen_zero(parse)) { + ast_log(LOG_WARNING, "DB requires an argument, DB(/)=\n"); + return -1; + } + + AST_NONSTANDARD_APP_ARGS(args, parse, '/'); + + if (args.argc < 2) { + ast_log(LOG_WARNING, "DB requires an argument, DB(/)=value\n"); + return -1; + } + + if (ast_db_put(args.family, args.key, value)) { + ast_log(LOG_WARNING, "DB: Error writing value to database.\n"); + } + + return 0; +} + +static struct ast_custom_function db_function = { + .name = "DB", + .read = function_db_read, + .write = function_db_write, +}; + +static int function_db_exists(struct ast_channel *chan, const char *cmd, + char *parse, char *buf, size_t len) +{ + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(family); + AST_APP_ARG(key); + ); + + buf[0] = '\0'; + + if (ast_strlen_zero(parse)) { + ast_log(LOG_WARNING, "DB_EXISTS requires an argument, DB(/)\n"); + return -1; + } + + AST_NONSTANDARD_APP_ARGS(args, parse, '/'); + + if (args.argc < 2) { + ast_log(LOG_WARNING, "DB_EXISTS requires an argument, DB(/)\n"); + return -1; + } + + if (ast_db_get(args.family, args.key, buf, len - 1)) { + strcpy(buf, "0"); + } else { + pbx_builtin_setvar_helper(chan, "DB_RESULT", buf); + strcpy(buf, "1"); + } + + return 0; +} + +static struct ast_custom_function db_exists_function = { + .name = "DB_EXISTS", + .read = function_db_exists, + .read_max = 2, +}; + +static int function_db_keys(struct ast_channel *chan, const char *cmd, char *parse, struct ast_str **result, ssize_t maxlen) +{ + size_t parselen = strlen(parse); + struct ast_db_entry *dbe, *orig_dbe; + struct ast_str *escape_buf = NULL; + const char *last = ""; + + /* Remove leading and trailing slashes */ + while (parse[0] == '/') { + parse++; + parselen--; + } + while (parse[parselen - 1] == '/') { + parse[--parselen] = '\0'; + } + + ast_str_reset(*result); + + /* Nothing within the database at that prefix? */ + if (!(orig_dbe = dbe = ast_db_gettree(parse, NULL))) { + return 0; + } + + for (; dbe; dbe = dbe->next) { + /* Find the current component */ + char *curkey = &dbe->key[parselen + 1], *slash; + if (*curkey == '/') { + curkey++; + } + /* Remove everything after the current component */ + if ((slash = strchr(curkey, '/'))) { + *slash = '\0'; + } + + /* Skip duplicates */ + if (!strcasecmp(last, curkey)) { + continue; + } + last = curkey; + + if (orig_dbe != dbe) { + ast_str_append(result, maxlen, ","); + } + ast_str_append_escapecommas(result, maxlen, curkey, strlen(curkey)); + } + ast_db_freetree(orig_dbe); + ast_free(escape_buf); + return 0; +} + +static struct ast_custom_function db_keys_function = { + .name = "DB_KEYS", + .read2 = function_db_keys, +}; + +static int function_db_delete(struct ast_channel *chan, const char *cmd, + char *parse, char *buf, size_t len) +{ + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(family); + AST_APP_ARG(key); + ); + + buf[0] = '\0'; + + if (ast_strlen_zero(parse)) { + ast_log(LOG_WARNING, "DB_DELETE requires an argument, DB_DELETE(/)\n"); + return -1; + } + + AST_NONSTANDARD_APP_ARGS(args, parse, '/'); + + if (args.argc < 2) { + ast_log(LOG_WARNING, "DB_DELETE requires an argument, DB_DELETE(/)\n"); + return -1; + } + + if (ast_db_get(args.family, args.key, buf, len - 1)) { + ast_debug(1, "DB_DELETE: %s/%s not found in database.\n", args.family, args.key); + } else { + if (ast_db_del(args.family, args.key)) { + ast_debug(1, "DB_DELETE: %s/%s could not be deleted from the database\n", args.family, args.key); + } + } + + pbx_builtin_setvar_helper(chan, "DB_RESULT", buf); + + return 0; +} + +/*! + * \brief Wrapper to execute DB_DELETE from a write operation. Allows execution + * even if live_dangerously is disabled. + */ +static int function_db_delete_write(struct ast_channel *chan, const char *cmd, char *parse, + const char *value) +{ + /* Throwaway to hold the result from the read */ + char buf[128]; + return function_db_delete(chan, cmd, parse, buf, sizeof(buf)); +} + +static struct ast_custom_function db_delete_function = { + .name = "DB_DELETE", + .read = function_db_delete, + .write = function_db_delete_write, +}; + +static int unload_module(void) +{ + int res = 0; + + res |= ast_custom_function_unregister(&db_function); + res |= ast_custom_function_unregister(&db_exists_function); + res |= ast_custom_function_unregister(&db_delete_function); + res |= ast_custom_function_unregister(&db_keys_function); + + return res; +} + +static int load_module(void) +{ + int res = 0; + + res |= ast_custom_function_register_escalating(&db_function, AST_CFE_BOTH); + res |= ast_custom_function_register(&db_exists_function); + res |= ast_custom_function_register_escalating(&db_delete_function, AST_CFE_READ); + res |= ast_custom_function_register(&db_keys_function); + + return res; +} + +AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Database (astdb) related dialplan functions"); diff --git a/pool/shard006/C/0117937_m_opme.c b/pool/shard006/C/0117937_m_opme.c new file mode 100644 index 0000000000000000000000000000000000000000..e45740cf4f069dbf9c62f0cc5713529c5eeb445d --- /dev/null +++ b/pool/shard006/C/0117937_m_opme.c @@ -0,0 +1,226 @@ +/* contrib/m_opme.c + * Copyright (C) 2002 Hybrid Development Team + * + * 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * $Id: m_opme.c,v 1.2 2003/03/10 06:08:59 demond Exp $ + */ +#include "stdinc.h" +#include "tools.h" +#include "handlers.h" +#include "channel.h" +#include "client.h" +#include "ircd.h" +#include "numeric.h" +#include "s_log.h" +#include "s_serv.h" +#include "send.h" +#include "whowas.h" +#include "irc_string.h" +#include "hash.h" +#include "msg.h" +#include "parse.h" +#include "modules.h" +#include "vchannel.h" + + +static void mo_opme(struct Client *client_p, struct Client *source_p, + int parc, char *parv[]); +static int chan_is_opless(struct Channel *chptr); + +struct Message opme_msgtab = { + "OPME", 0, 0, 2, 0, MFLG_SLOW, 0, + {m_unregistered, m_not_oper, m_ignore, mo_opme} +}; + +void +_modinit(void) +{ + mod_add_cmd(&opme_msgtab); +} + +void +_moddeinit(void) +{ + mod_del_cmd(&opme_msgtab); +} + +char *_version = "$Revision: 1.2 $"; + +static int chan_is_opless(struct Channel *chptr) +{ + if (chptr->chanops.head) + return 0; + else + return 1; +} + +/* +** mo_opme +** parv[0] = sender prefix +** parv[1] = channel +*/ +static void mo_opme(struct Client *client_p, struct Client *source_p, + int parc, char *parv[]) +{ + struct Channel *chptr, *root_chptr; + int on_vchan = 0; + dlink_node *ptr; + dlink_node *locptr; + + /* admins only */ + if (!IsAdmin(source_p)) + { + sendto_one(source_p, ":%s NOTICE %s :You have no A flag", me.name, + parv[0]); + return; + } + + /* XXX - we might not have CBURSTed this channel if we are a lazylink + * yet. */ + chptr= hash_find_channel(parv[1]); + root_chptr = chptr; + +#ifdef VCHANS + if (chptr && parc > 2 && parv[2][0] == '!') + { + chptr = find_vchan(chptr, parv[2]); + if (root_chptr != chptr) + on_vchan++; + } +#endif + + if( chptr == NULL ) + { + sendto_one(source_p, form_str(source_p,ERR_NOSUCHCHANNEL), + me.name, parv[0], parv[1]); + return; + } + + if (!chan_is_opless(chptr)) + { + sendto_one(source_p, ":%s NOTICE %s :%s Channel is not opless", + me.name, parv[0], parv[1]); + return; + } + + if ((ptr = find_user_link(&chptr->peons, source_p))) + dlinkDelete(ptr, &chptr->peons); + else if ((ptr = find_user_link(&chptr->voiced, source_p))) + dlinkDelete(ptr, &chptr->voiced); +#ifdef HALFOPS + else if ((ptr = find_user_link(&chptr->halfops, source_p))) + dlinkDelete(ptr, &chptr->halfops); +#endif + else if ((ptr = find_user_link(&chptr->chanops, source_p))) + dlinkDelete(ptr, &chptr->chanops); +#ifdef REQUIRE_OANDV + else if((ptr = find_user_link(&chptr->chanops_voiced, source_p))) + dlinkDelete(ptr, &chptr->chanops_voiced); +#endif + else + { + /* Theyre not even on the channel, bail. */ + return; + } + + if((locptr = find_user_link(&chptr->locpeons, source_p))) + dlinkDelete(locptr, &chptr->locpeons); + else if((locptr = find_user_link(&chptr->locvoiced, source_p))) + dlinkDelete(locptr, &chptr->locvoiced); +#ifdef HALFOPS + else if((locptr = find_user_link(&chptr->lochalfops, source_p))) + dlinkDelete(locptr, &chptr->lochalfops); +#endif + else if((locptr = find_user_link(&chptr->locchanops, source_p))) + dlinkDelete(locptr, &chptr->locchanops); + +#ifdef REQUIRE_OANDV + else if((locptr = find_user_link(&chptr->locchanops_voiced, source_p))) + dlinkDelete(locptr, &chptr->locchanops_voiced); +#endif + + else + return; + + dlinkAdd(source_p, ptr, &chptr->chanops); + dlinkAdd(source_p, locptr, &chptr->locchanops); + + if (!on_vchan) + { + if (parv[1][0] == '&') + { + sendto_wallops_flags(FLAGS_LOCOPS, &me, + "OPME called for [%s] by %s!%s@%s", + parv[1], source_p->name, source_p->username, + source_p->host); + } + else + { + sendto_wallops_flags(FLAGS_WALLOP, &me, + "OPME called for [%s] by %s!%s@%s", + parv[1], source_p->name, source_p->username, + source_p->host); + sendto_server(NULL, source_p, NULL, NOCAPS, NOCAPS, LL_ICLIENT, + ":%s WALLOPS :OPME called for [%s] by %s!%s@%s", + me.name, parv[1], source_p->name, source_p->username, + source_p->host); + } + ilog(L_NOTICE, "OPME called for [%s] by %s!%s@%s", + parv[1], source_p->name, source_p->username, + source_p->host); + } + else + { + if (parv[1][0] == '&') + { + sendto_wallops_flags(FLAGS_LOCOPS, &me, + "OPME called for [%s %s] by %s!%s@%s", + parv[1], parv[2], source_p->name, + source_p->username, source_p->host); + } + else + { + sendto_wallops_flags(FLAGS_WALLOP, &me, + "OPME called for [%s %s] by %s!%s@%s", + parv[1], parv[2], source_p->name, + source_p->username, source_p->host); + sendto_server(NULL, source_p, NULL, NOCAPS, NOCAPS, LL_ICLIENT, + ":%s WALLOPS :OPME called for [%s %s] by %s!%s@%s", + me.name, parv[1], parv[2], source_p->name, + source_p->username, source_p->host); + } + ilog(L_NOTICE, "OPME called for [%s %s] by %s!%s@%s", + parv[1], parv[2], source_p->name, source_p->username, + source_p->host); + } + + sendto_server(NULL, source_p, chptr, CAP_UID, NOCAPS, NOFLAGS, + ":%s PART %s", ID(source_p), parv[1]); + sendto_server(NULL, source_p, chptr, NOCAPS, CAP_UID, NOFLAGS, + ":%s PART %s", source_p->name, parv[1]); + sendto_server(NULL, source_p, chptr, CAP_UID, NOCAPS, NOFLAGS, + ":%s SJOIN %ld %s + :@%s", + me.name, (signed long) chptr->channelts, + parv[1], + source_p->name /* XXX ID(source_p) */ ); + sendto_server(NULL, source_p, chptr, NOCAPS, CAP_UID, NOFLAGS, + ":%s SJOIN %ld %s + :@%s", + me.name, (signed long) chptr->channelts, + parv[1], source_p->name); + sendto_channel_local(ALL_MEMBERS, chptr, + ":%s MODE %s +o %s", + me.name, parv[1], source_p->name); +} diff --git a/pool/shard006/C/0117940_process_fork.c b/pool/shard006/C/0117940_process_fork.c new file mode 100644 index 0000000000000000000000000000000000000000..ef5b9d5e1596cbc97407877a1173c2830f139ef7 --- /dev/null +++ b/pool/shard006/C/0117940_process_fork.c @@ -0,0 +1,30 @@ +#include +#include +#include + +#include +#include + +#define LINE_MAX 256 + +int main() { + char buffer[LINE_MAX] = {0}; + int len = 0; + int pid = 0; + int status = 0; + + printf("%% "); + while (fgets(buffer, LINE_MAX, stdin) != NULL) { + if ((len = strlen(buffer)) == 0) continue; + buffer[len - 1] = '\0'; + if ((pid = fork()) == 0) { + execlp(buffer, buffer, (char*)0); + exit(127); + } + if ((pid = waitpid(pid, &status, 0)) < 0) { + fputs("wait pid error", stderr); + } + printf("%% "); + } + return 0; +} diff --git a/pool/shard006/C/0117946_CONTA1.c b/pool/shard006/C/0117946_CONTA1.c new file mode 100644 index 0000000000000000000000000000000000000000..647b480650628633fad2efce18badd52260acef9 --- /dev/null +++ b/pool/shard006/C/0117946_CONTA1.c @@ -0,0 +1,28 @@ +// 2015-05-18 01:28:03 + +#include + +int main() +{ + int N=0, cont=0; + + scanf(" %d" , &N); + + if(N<=10) printf("7"); + else if(N<=30){ + cont = N-10; + N = cont*1+7; + printf("%d",N); + } else if(N<=100) { + cont = N-30; + N = cont*2+7+20; + printf("%d",N); + } else { + cont = N-100; + N = cont*5+7+20+140; + printf("%d",N); + } + + return 0; + +} \ No newline at end of file diff --git a/pool/shard006/C/0117952_sha256.c b/pool/shard006/C/0117952_sha256.c new file mode 100644 index 0000000000000000000000000000000000000000..403b86dfd16209515b4e3bddcf7b9c288da89d1e --- /dev/null +++ b/pool/shard006/C/0117952_sha256.c @@ -0,0 +1,248 @@ +/* + This file is part of martink project. + + Implementation by Daniel Otte (daniel.otte@rub.de) Copyright (C) 2008 + + martink firmware project 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. + + martink firmware 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 martink firmware. If not, see . + + LibK project on github: https://github.com/mkschreder +*/ +/** + * \file sha256.c + * \author Daniel Otte + * \date 16.05.2006 + * + * \par License: + * GPL + * + * \brief SHA-256 implementation. + * + * + */ + +#include +#include /* for memcpy, memmove, memset */ + +#include "../arch/soc.h" + +#include "sha256.h" + +#define LITTLE_ENDIAN + +#if defined LITTLE_ENDIAN +#elif defined BIG_ENDIAN +#else + #error specify endianess!!! +#endif + + +/*************************************************************************/ + +static const uint32_t sha256_init_vector_p [] PROGMEM={ + 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 }; + + +/*************************************************************************/ + +/** + * \brief \c sh256_init initialises a sha256 context for hashing. + * \c sh256_init c initialises the given sha256 context for hashing + * @param state pointer to a sha256 context + * @return none + */ +void sha256_init(sha256_ctx_t *state){ + state->length=0; + uint32_t *p = state->h; + for(int c = 0; c < 8; c++){ + *p = pgm_read_dword(&sha256_init_vector_p[c]); + p++; + } + //memcpy(state->h, sha256_init_vector, 8*4); +} + +/*************************************************************************/ + +/** + * rotate x right by n positions + */ +static uint32_t rotr32( uint32_t x, uint8_t n){ + return ((x>>n) | (x<<(32-n))); +} + + +/*************************************************************************/ + +// #define CHANGE_ENDIAN32(x) (((x)<<24) | ((x)>>24) | (((x)& 0x0000ff00)<<8) | (((x)& 0x00ff0000)>>8)) + +static uint32_t change_endian32(uint32_t x){ + return (((x)<<24) | ((x)>>24) | (((x)& 0x0000ff00)<<8) | (((x)& 0x00ff0000)>>8)); +} + + +/*************************************************************************/ + +/* sha256 functions as macros for speed and size, cause they are called only once */ + +#define CH(x,y,z) (((x)&(y)) ^ ((~(x))&(z))) +#define MAJ(x,y,z) (((x)&(y)) ^ ((x)&(z)) ^ ((y)&(z))) + +#define SIGMA0(x) (rotr32((x),2) ^ rotr32((x),13) ^ rotr32((x),22)) +#define SIGMA1(x) (rotr32((x),6) ^ rotr32((x),11) ^ rotr32((x),25)) +#define SIGMA_a(x) (rotr32((x),7) ^ rotr32((x),18) ^ ((x)>>3)) +#define SIGMA_b(x) (rotr32((x),17) ^ rotr32((x),19) ^ ((x)>>10)) + + +static const uint32_t pk[] PROGMEM = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +}; + + +/*************************************************************************/ + +/** + * block must be, 512, Bit = 64, Byte, long !!! + */ +void sha256_nextBlock (sha256_ctx_t *state, const void* block){ + uint32_t w[64]; /* this is 256, byte, large, */ + uint8_t i; + uint32_t a[8],t1,t2; + + /* init w */ +#if defined LITTLE_ENDIAN + for (i=0; i<16; ++i){ + w[i]= change_endian32(((const uint32_t*)block)[i]); + } +#elif defined BIG_ENDIAN + memcpy((void*)w, block, 64); +#endif + for (i=16; i<64; ++i){ + w[i] = SIGMA_b(w[i-2]) + w[i-7] + SIGMA_a(w[i-15]) + w[i-16]; + } + + /* init working variables */ + memcpy((void*)a,(void*)(state->h), 8*4); + + /* do the, fun stuff, */ + for (i=0; i<64; ++i){ + t1 = a[7] + SIGMA1(a[4]) + CH(a[4],a[5],a[6]) + pgm_read_dword(&pk[i]) + w[i]; + t2 = SIGMA0(a[0]) + MAJ(a[0],a[1],a[2]); + memmove(&(a[1]), &(a[0]), 7*4); /* a[7]=a[6]; a[6]=a[5]; a[5]=a[4]; a[4]=a[3]; a[3]=a[2]; a[2]=a[1]; a[1]=a[0]; */ + a[4] += t1; + a[0] = t1 + t2; + } + + /* update, the, state, */ + for (i=0; i<8; ++i){ + state->h[i] += a[i]; + } + state->length += 512; +} + + +/*************************************************************************/ + +/** + * \brief function to process the last block being hashed + * @param state Pointer to the context in which this block should be processed. + * @param block Pointer to the message wich should be hashed. + * @param length is the length of only THIS block in BITS not in bytes! + * bits are big endian, meaning high bits come first. + * if you have a message with bits at the end, the byte must be padded with zeros + */ +void sha256_lastBlock(sha256_ctx_t *state, const void* block, uint16_t length){ + uint8_t lb[SHA256_BLOCK_BITS/8]; /* local block */ + while(length>=SHA256_BLOCK_BITS){ + sha256_nextBlock(state, block); + length -= SHA256_BLOCK_BITS; + block = (const uint8_t*)block+SHA256_BLOCK_BYTES; + } + + state->length += length; + memcpy (&(lb[0]), block, length/8); + + /* set the final one bit */ + if (length & 0x7){ // if we have single bits at the end + lb[length/8] = ((const uint8_t*)(block))[length/8]; + } else { + lb[length/8] = 0; + } + lb[length/8] |= 0x80>>(length & 0x7); + length =(length >> 3) + 1; /* from now on length contains the number of BYTES in lb*/ + /* pad with zeros */ + if (length>64-8){ /* not enouth space for 64bit length value */ + memset((void*)(&(lb[length])), 0, 64-length); + sha256_nextBlock(state, lb); + state->length -= 512; + length = 0; + } + memset((void*)(&(lb[length])), 0, 56-length); + /* store the 64bit length value */ +#if defined LITTLE_ENDIAN + /* this is now rolled up */ + uint8_t i; + for (i=1; i<=8; ++i){ + lb[55+i] = (uint8_t)(state->length>>(64- 8*i)); + } +#elif defined BIG_ENDIAN + *((uint64_t)&(lb[56])) = state->length; +#endif + sha256_nextBlock(state, lb); +} + + +/*************************************************************************/ + +/* + * length in bits! + */ +void sha256(sha256_hash_t *dest, const void* msg, uint32_t len){ + sha256_ctx_t s; + sha256_init(&s); + uint32_t length = len * 8; + while(length >= SHA256_BLOCK_BITS){ + sha256_nextBlock(&s, msg); + msg = (const uint8_t*)msg + SHA256_BLOCK_BITS/8; + length -= SHA256_BLOCK_BITS; + } + sha256_lastBlock(&s, msg, length); + sha256_ctx2hash(dest,&s); +} + + + +/*************************************************************************/ + +void sha256_ctx2hash(sha256_hash_t *dest, const sha256_ctx_t *state){ +#if defined LITTLE_ENDIAN + uint8_t i; + for(i=0; i<8; ++i){ + ((uint32_t*)(void*)dest)[i] = change_endian32(state->h[i]); + } +#elif BIG_ENDIAN + if (dest != state->h) + memcpy(dest, state->h, SHA256_HASH_BITS/8); +#else +# error unsupported endian type! +#endif +} + + diff --git a/pool/shard006/C/0117955_CWE134_Uncontrolled_Format_String__char_environment_printf_21.c b/pool/shard006/C/0117955_CWE134_Uncontrolled_Format_String__char_environment_printf_21.c new file mode 100644 index 0000000000000000000000000000000000000000..de89b483c3a1917e6821d0cdb722b84a0056ea9b --- /dev/null +++ b/pool/shard006/C/0117955_CWE134_Uncontrolled_Format_String__char_environment_printf_21.c @@ -0,0 +1,194 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__char_environment_printf_21.c +Label Definition File: CWE134_Uncontrolled_Format_String.label.xml +Template File: sources-sinks-21.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: environment Read input from an environment variable + * GoodSource: Copy a fixed string into data + * Sinks: printf + * GoodSink: printf with "%s" as the first argument and data as the second + * BadSink : printf with only data as an argument + * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file. + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#define ENV_VARIABLE "ADD" + +#ifdef _WIN32 +#define GETENV getenv +#else +#define GETENV getenv +#endif + +#ifndef OMITBAD + +/* The static variable below is used to drive control flow in the sink function */ +static int badStatic = 0; + +static void badSink(char * data) +{ + if(badStatic) + { + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + printf(data); + } +} + +void CWE134_Uncontrolled_Format_String__char_environment_printf_21_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + badStatic = 1; /* true */ + badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* The static variables below are used to drive control flow in the sink functions. */ +static int goodB2G1Static = 0; +static int goodB2G2Static = 0; +static int goodG2BStatic = 0; + +/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ +static void goodB2G1Sink(char * data) +{ + if(goodB2G1Static) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Specify the format disallowing a format string vulnerability */ + printf("%s\n", data); + } +} + +static void goodB2G1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + goodB2G1Static = 0; /* false */ + goodB2G1Sink(data); +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ +static void goodB2G2Sink(char * data) +{ + if(goodB2G2Static) + { + /* FIX: Specify the format disallowing a format string vulnerability */ + printf("%s\n", data); + } +} + +static void goodB2G2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + goodB2G2Static = 1; /* true */ + goodB2G2Sink(data); +} + +/* goodG2B() - use goodsource and badsink */ +static void goodG2BSink(char * data) +{ + if(goodG2BStatic) + { + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + printf(data); + } +} + +static void goodG2B() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + goodG2BStatic = 1; /* true */ + goodG2BSink(data); +} + +void CWE134_Uncontrolled_Format_String__char_environment_printf_21_good() +{ + goodB2G1(); + goodB2G2(); + goodG2B(); +} + +#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()..."); + CWE134_Uncontrolled_Format_String__char_environment_printf_21_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__char_environment_printf_21_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0117959_1-19.c b/pool/shard006/C/0117959_1-19.c new file mode 100644 index 0000000000000000000000000000000000000000..72fcc425a8a98c31715195fc8df19e6f55968d70 --- /dev/null +++ b/pool/shard006/C/0117959_1-19.c @@ -0,0 +1,72 @@ +/** + * Exercise 1-19 + * + * Write a function reverse(s) that reverses the character strings. + * Use it to write a program that reverses its input a line at a time. + */ + +#include + +#define MAX_LINE 1000 + +int getLine(char line[], int lim); + +void reverse(char line[]); + +int main(void) { + int c, len; + char line[MAX_LINE]; + + while ((len = getLine(line, MAX_LINE)) > 0) { + reverse(line); + printf("%s", line); + } + + return 0; +} + +/** + * @param s line + * @param lim max length of line + * @return length of line + */ +int getLine(char s[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { + s[i] = c; + } + + if (c == '\n') { + s[i] = c; + ++i; + } + + s[i] = '\0'; + + return i; +} + +void reverse(char line[]) { + int i, j; + char tmp; + + // Go to the end of the line + for (i = 0; line[i] != '\0'; i++); + + i--; + + if (line[i] == '\n') { + i--; + } + + j = 0; + while (j < i) { + // Swap char + tmp = line[j]; + line[j] = line[i]; + line[i] = tmp; + i--; + j++; + } +} diff --git a/pool/shard006/C/0117961_elgamal.c b/pool/shard006/C/0117961_elgamal.c new file mode 100644 index 0000000000000000000000000000000000000000..50e8c414e8cc2c2c64ca0492fc07b7efc7a34cc8 --- /dev/null +++ b/pool/shard006/C/0117961_elgamal.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) Anthony Arnold 2014 + */ + + +#include +#include +#include +#include +#include + +enum { + MSG_SIZE = 8, + NUM_BITS = 16 /* Doing smaller key for speed */ +}; + +int main (void) { + golle_key_t key = { 0 }; + golle_eg_t cipher = { 0 }; + assert (golle_key_gen_public (&key, NUM_BITS, INT_MAX) == GOLLE_OK); + assert (golle_key_gen_private (&key) == GOLLE_OK); + + /* Make a random number */ + golle_bin_t orig; + assert (golle_bin_init (&orig, MSG_SIZE) == GOLLE_OK); + assert (golle_random_generate (&orig) == GOLLE_OK); + golle_num_t n = golle_num_new (); + assert (n); + assert (golle_bin_to_num (&orig, n) == GOLLE_OK); + + /* m must be in G */ + golle_num_t m = golle_num_new (); + assert (m); + assert (golle_num_mod_exp (m, key.g, n, key.q) == GOLLE_OK); + + /* Encrypt */ + golle_num_t a, b, r = NULL; + assert (a = golle_num_new ()); + assert (b = golle_num_new ()); + assert (golle_eg_encrypt (&key, m, &cipher, &r) == GOLLE_OK); + + /* Decrypt */ + golle_num_t p = golle_num_new (); + assert (p); + assert (golle_eg_decrypt (&key, &key.x, 1, &cipher, p) == GOLLE_OK); + + /* Are they the same? */ + assert (golle_num_cmp (m, p) == 0); + + golle_eg_clear (&cipher); + golle_num_delete (p); + golle_num_delete (n); + golle_num_delete (m); + golle_num_delete (r); + golle_bin_release (&orig); + golle_key_cleanup (&key); + golle_random_clear (); + return 0; +} diff --git a/pool/shard006/C/0117962_Allocation.c b/pool/shard006/C/0117962_Allocation.c new file mode 100644 index 0000000000000000000000000000000000000000..9425bc22ee7f369fe3c3ed35a84e9f8fa70f445e --- /dev/null +++ b/pool/shard006/C/0117962_Allocation.c @@ -0,0 +1,115 @@ +/* + * This file is part of the Jikes RVM project (http://jikesrvm.org). + * + * This file is licensed to You under the Common Public License (CPL); + * You may not use this file except in compliance with the License. You + * may obtain a copy of the License at + * + * http://www.opensource.org/licenses/cpl1.0.php + * + * See the COPYRIGHT.txt file distributed with this work for information + * regarding copyright ownership. + */ +/* Test method invocation from native code + * Implement native methods from Allocation.java + */ + +#include +#include +#include /* malloc() */ + +#include "Allocation.h" +#include + +int verbose=1; + +jstring testNewObjectV_part2(JNIEnv *env, jclass cls, jobject stringClass, ...); + + +/* + * Class: Allocation + * Method: setVerboseOff + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_Allocation_setVerboseOff + (JNIEnv *env, jclass cls) { + verbose=0; + +} + + +/* + * Class: Allocation + * Method: testNewObjectA + * Signature: (LVM_Class;[C)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_Allocation_testNewObjectA + (JNIEnv *env, jclass cls, jobject stringClass, jcharArray inputChar) { + + jobject newObj; + jmethodID methodID; + jvalue *argA; + + argA = (jvalue *) malloc(sizeof(jvalue) * 2); + (&argA[0])->l = inputChar; + + methodID = (*env) -> GetMethodID(env, stringClass, "", "([C)V"); + + newObj = (*env) -> NewObjectA(env, stringClass, methodID, argA); + + return newObj; + +} + + +/* + * Class: Allocation + * Method: testNewObject + * Signature: (LVM_Class;[C)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_Allocation_testNewObjectV + (JNIEnv *env, jclass cls, jobject stringClass, jcharArray inputChar) { + + return testNewObjectV_part2(env, cls, stringClass, inputChar); + +} + + +jstring testNewObjectV_part2(JNIEnv *env, jclass cls, jobject stringClass, ...) { + + jobject newObj; + jmethodID methodID; + + va_list ap; + va_start(ap, stringClass); + + methodID = (*env) -> GetMethodID(env, stringClass, "", "([C)V"); + + newObj = (*env) -> NewObjectV(env, stringClass, methodID, ap); + + va_end(ap); + + return newObj; + +} + + + +/* + * Class: Allocation + * Method: testNewObject + * Signature: (LVM_Class;[C)Ljava/lang/String; + */ +JNIEXPORT jstring JNICALL Java_Allocation_testNewObject + (JNIEnv *env, jclass cls, jobject stringClass, jcharArray inputChar) { + + jobject newObj; + jmethodID methodID; + + methodID = (*env) -> GetMethodID(env, stringClass, "", "([C)V"); + + newObj = (*env) -> NewObject(env, stringClass, methodID, inputChar); + + return newObj; + +} diff --git a/pool/shard006/C/0117963_bit_manip.c b/pool/shard006/C/0117963_bit_manip.c new file mode 100644 index 0000000000000000000000000000000000000000..a1104a865d7a3858362dabbeec78f5f7a7e195b0 --- /dev/null +++ b/pool/shard006/C/0117963_bit_manip.c @@ -0,0 +1,150 @@ +#include "stdio.h" +#include "../include/bit_manip.h" +#include "../include/common.h" +unsigned int my_word = 0; +unsigned char position = 0; +void bit_manip_main() +{ + unsigned int option = 0; + unsigned int exit_count=0; + while(exit_count < MAX_TRY) + { + print_options_bitmanip(); + scanf("%d", &option); + if(EXIT_PROGRAM == option) + { + printf("Hope you enjoyed learning \"Bit manipulation\", Goodbye!!!\r\n"); + break; + } + my_word =0; + position=0; + switch(option) + { + case 1: + printf("Enter the word in which you want to set a bit : "); + scanf("%d",&my_word); + printf("Enter the position which you want to set : "); + scanf("%d",&position); + position -=1; + set_bit(&my_word,position); + break; + case 2: + printf("Enter the word in which you want to clear a bit : "); + scanf("%d",&my_word); + printf("Enter the position which you want to clear : "); + scanf("%d",&position); + position -=1; + clear_bit(&my_word,position); + break; + case 3: + printf("Enter the word in which you want to toggle a bit : "); + scanf("%d",&my_word); + printf("Enter the position which you want to toggle : "); + scanf("%d",&position); + position -=1; + toggle_bit(&my_word,position); + break; + case 4: + printf("Enter the word in which you want to count number of bit set : "); + scanf("%d",&my_word); + count_bit(my_word); + break; + case 5: + printf("Enter the word in which you want to cjheck if a bit is set : "); + scanf("%d",&my_word); + printf("Enter the position which you want to check : "); + scanf("%d",&position); + position -=1; + if(isbit_set(&my_word,position)) printf("Yup, set"); + else printf("Nope, not set"); + break; + case 6: + printf("Enter the word in which you want to clear the lowest set bit : "); + scanf("%d",&my_word); + clear_lowest_set_bit(&my_word); + break; + case 7: + printf("Enter the word in which you want to toggle a bit : "); + scanf("%d",&my_word); + printf("The lowest set bit position is %d",get_lowest_set_bit(&my_word)); + break; + case 8: + printf("Enter the number which you want to check if it is power of 2 : "); + scanf("%d",&my_word); + if(check_power_of_2(my_word)) printf("Yup, power of 2"); + else printf("Nope, not a power of 2"); + break; + case 9: + printf("Enter the number which you want to multiply by 10 : "); + scanf("%d",&my_word); + printf("%d x 10 = %d",my_word,multiply10(my_word)); + break; + default: + printf("Wrong option!!! Try again\r\n"); + exit_count++; + break; + } + } +} +void print_options_bitmanip() +{ + printf("\r\nEnter any one of the below options,\r\n"); + printf("1. Set a bit in a word\r\n"); + printf("2. Clear a bit in a word\r\n"); + printf("3. Toggle a bit in a word\r\n"); + printf("4. Count number of bits set in a word\r\n"); + printf("5. Check if a bit is set in a word\r\n"); + printf("6. Clear lowest set bit in a word\r\n"); + printf("7. Get position of the lowest set bit in a word\r\n"); + printf("8. check if a number is power of 2\r\n"); + printf("9. Multiply a number with 10 using logical operations\r\n"); + printf("0. Exit Bit manipulation\r\n"); + printf("Option: "); +} + +void set_bit(unsigned int *p_word, unsigned char position) +{ + printf("so you want to set %d position in the word having current value %d\r\n",position+1,*p_word); + *p_word = *p_word | (1< 9) ? ('a' - 10) : '0'); +} + +static void tohex(uint32_t val, char *dst) +{ + int i; + val = + (val >> 24) | (val << 24) | ((val >> 8) & 0xff00) | ((val & 0xff00) + << 8); + for (i = 0; i < 4; i++, dst += 2) { + dst[0] = nibble2hex((val >> (i << 3)) >> 4); + dst[1] = nibble2hex((val >> (i << 3)) & 0xf); + } +} +*/ + +static inline void delay_ms(const uint32_t n) +{ + for(T0TC = 0; T0TC < n; ) {} +} + +static uint32_t read_adc(const uint8_t idx) +{ + uint32_t res; + AD0CR = (1 << idx) | (10 << 8) | (1 << 21) | (1 << 24); + delay_ms(1); + res = AD0GDR; + res = (res & (1 << 31)) ? ((res >> 6) & 0x3ff) : 0xffffffff; + return res; +} + +static void print_temp(char *dst, uint32_t v) +{ + uint32_t tmp = v / 100; + dst[0] = tmp > 0 ? (tmp + '0') : ' '; + v -= tmp * 100; + + tmp = v / 10; + dst[1] = tmp + '0'; + v -= tmp * 10; + + dst[2] = v + '0'; +} + +struct wave_s { + uint16_t id; + uint16_t unknown; + uint16_t pt[48]; + char *name; + char *number; + char *desc; +} __attribute__((packed)); + +const struct wave_s *waves = (const struct wave_s *)0x52c4; + +void dump_waves(void) { + int i,j; + serial_puts("{\n"); + for(i=0;i<8;i++) { + const struct wave_s *wv = waves+i; + char ebuf[] = "] },\n"; + serial_puts(" \""); + serial_puts(wv->name); + serial_puts("\": {\n \"desc\": \""); + serial_puts(wv->desc); + serial_puts("\",\n \"pts\": ["); + for(j=0;(j<48) && (wv->pt[j]);j++) { + char buf[]="123, "; + print_temp(buf,wv->pt[j]); + buf[3] = ((j<47) && (wv->pt[j+1])) ? ',' : 0; + serial_puts(buf); + } + ebuf[3] = i<7 ? ',' : ' '; + serial_puts(ebuf); + } + serial_puts("}\n"); +} + +int main(void) +{ + char str[] = "123 123\n"; + uint32_t adc[2]; + + serial_init(19200); /* baud rate setting */ + + T0PR = (Fosc/1000)-1; /* 1ms granularity for both timers */ + T1PR = (Fosc/1000)-1; + T0TCR = 1; + T1TCR = 0; + T1TC = 0; + + // AD0.1, AD0.2 + PINSEL1 = (1 << 24) | (1 << 26); + + IODIR0 = FAN_BIT | LAMP_BIT | BEEP_BIT; + IOSET0 = FAN_BIT | LAMP_BIT | BEEP_BIT; + + delay_ms(100); + BEEP_OFF; + delay_ms(100); + BEEP_ON; + delay_ms(100); + BEEP_OFF; + + do { + uint8_t rb=0; + for(; U0LSR & 0x01; rb=U0RBR) {} + if ((rb >= '0') && (rb <= '3')) { + T1TC = 0; + if (rb & 1) { + LAMP_ON; + T1TCR = 1; + } else { + LAMP_OFF; + } + if (rb & 2) { + FAN_ON; + T1TCR = 1; + } else { + FAN_OFF; + } + } + else if(rb == 'W') + dump_waves(); + + // 3 seconds timeout + if ((T1TCR) && (T1TC >= 3000)) { + IOSET0 = LAMP_BIT | FAN_BIT; + T1TCR = 0; + T1TC = 0; + } + + adc[0] = read_adc(1); + adc[1] = read_adc(2); + if((rb) && (rb!='W')) { + print_temp(str, adc[0]); + print_temp(str + 4, adc[1]); + serial_puts(str); + } + } while ((adc[0] < MAXTEMP) && (adc[1] < MAXTEMP)); + + /* safeguard */ + + IODIR0 = LAMP_BIT | FAN_BIT | BEEP_BIT; + // lamp off, beeper on, fan on + IOSET0 = LAMP_BIT | BEEP_BIT; + IOCLR0 = FAN_BIT; + + while (1) { + } + + return 0; /* never reached */ +} diff --git a/pool/shard006/C/0117970_clock.c b/pool/shard006/C/0117970_clock.c new file mode 100644 index 0000000000000000000000000000000000000000..0142c08d8fd6c6321125a463b3f1b5d19339c9ca --- /dev/null +++ b/pool/shard006/C/0117970_clock.c @@ -0,0 +1,98 @@ +/* + * Use the last periodic interval timer (PIT2) as the system clock. + * + * $Id: clock.c,v 1.4 2008/09/30 05:10:00 ralf Exp $ + */ + +#include +#include + +/* + * Use INTC0 base + */ +#define CLOCK_VECTOR (64+56) + +static uint32_t s_pcntrAtTick = 0; +static uint32_t s_nanoScale = 0; + +/* + * Provide nanosecond extension + * Interrupts are disabled when this is called + */ +static uint32_t bsp_clock_nanoseconds_since_last_tick(void) +{ + uint32_t i; + + if (MCF_PIT1_PCSR & MCF_PIT_PCSR_PIF) { + i = s_pcntrAtTick + (MCF_PIT1_PMR - MCF_PIT1_PCNTR); + } + else { + i = s_pcntrAtTick - MCF_PIT1_PCNTR; + } + return i * s_nanoScale; +} + +#define Clock_driver_nanoseconds_since_last_tick bsp_clock_nanoseconds_since_last_tick + +/* + * Periodic interval timer interrupt handler + */ +#define Clock_driver_support_at_tick() \ + do { \ + s_pcntrAtTick = MCF_PIT1_PCNTR; \ + MCF_PIT1_PCSR |= MCF_PIT_PCSR_PIF; \ + } while (0) \ + +/* + * Attach clock interrupt handler + */ +#define Clock_driver_support_install_isr( _new, _old ) \ + do { \ + _old = (rtems_isr_entry)set_vector(_new, CLOCK_VECTOR, 1); \ + } while(0) + +/* + * Turn off the clock + */ +static void Clock_driver_support_shutdown_hardware(void) +{ + MCF_PIT1_PCSR &= ~MCF_PIT_PCSR_EN; +} + +/* + * Set up the clock hardware + * + * We need to have 1 interrupt every BSP_Configuration.microseconds_per_tick + */ +static void Clock_driver_support_initialize_hardware(void) +{ + int level; + uint32_t pmr; + uint32_t preScaleCode = 0; + uint32_t clk = bsp_get_CPU_clock_speed() >> 1; + uint32_t tps = 1000000 / Configuration.microseconds_per_tick; + + while (preScaleCode < 15) { + pmr = (clk >> preScaleCode) / tps; + if (pmr < (1 << 15)) + break; + preScaleCode++; + } + s_nanoScale = 1000000000 / (clk >> preScaleCode); + + MCF_INTC0_ICR56 = MCF_INTC_ICR_IL(PIT3_IRQ_LEVEL) | + MCF_INTC_ICR_IP(PIT3_IRQ_PRIORITY); + rtems_interrupt_disable(level); + MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_MASK56; + MCF_PIT1_PCSR &= ~MCF_PIT_PCSR_EN; + rtems_interrupt_enable(level); + + MCF_PIT1_PCSR = MCF_PIT_PCSR_PRE(preScaleCode) | + MCF_PIT_PCSR_OVW | MCF_PIT_PCSR_PIE | MCF_PIT_PCSR_RLD; + MCF_PIT1_PMR = pmr; + MCF_PIT1_PCSR = MCF_PIT_PCSR_PRE(preScaleCode) | + MCF_PIT_PCSR_PIE | MCF_PIT_PCSR_RLD | MCF_PIT_PCSR_EN; + s_pcntrAtTick = MCF_PIT1_PCNTR; +} + +#include "../../../shared/clockdrv_shell.h" diff --git a/pool/shard006/C/0117974_modtime.c b/pool/shard006/C/0117974_modtime.c new file mode 100644 index 0000000000000000000000000000000000000000..a8f6ed5c6ea306923882113bec394eb8c49639c9 --- /dev/null +++ b/pool/shard006/C/0117974_modtime.c @@ -0,0 +1,185 @@ +/* + * 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 "py/mpconfig.h" +#if MICROPY_PY_UTIME + +#include +#include +#include +#include +#include +#include + +#include "py/runtime.h" +#include "py/smallint.h" +#include "py/mphal.h" +#include "extmod/utime_mphal.h" + +#ifdef _WIN32 +static inline int msec_sleep_tv(struct timeval *tv) { + msec_sleep(tv->tv_sec * 1000.0 + tv->tv_usec / 1000.0); + return 0; +} +#define sleep_select(a,b,c,d,e) msec_sleep_tv((e)) +#else +#define sleep_select select +#endif + +// mingw32 defines CLOCKS_PER_SEC as ((clock_t)) but preprocessor does not handle casts +#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) +#define MP_REMOVE_BRACKETSA(x) +#define MP_REMOVE_BRACKETSB(x) MP_REMOVE_BRACKETSA x +#define MP_REMOVE_BRACKETSC(x) MP_REMOVE_BRACKETSB x +#define MP_CLOCKS_PER_SEC MP_REMOVE_BRACKETSC(CLOCKS_PER_SEC) +#else +#define MP_CLOCKS_PER_SEC CLOCKS_PER_SEC +#endif + +#if defined(MP_CLOCKS_PER_SEC) +#define CLOCK_DIV (mp_float_t) (MP_CLOCKS_PER_SEC / 1000.0F) +#else +#error Unsupported clock() implementation +#endif + +STATIC mp_obj_t mod_time_time(void) { +#if MICROPY_PY_BUILTINS_FLOAT + struct timeval tv; + gettimeofday(&tv, NULL); + mp_float_t val = tv.tv_sec + (mp_float_t)tv.tv_usec / 1000000; + return mp_obj_new_float(val); +#else + return mp_obj_new_int((mp_int_t)time(NULL)); +#endif +} +STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_time_obj, mod_time_time); + +// Note: this is deprecated since CPy3.3, but pystone still uses it. +STATIC mp_obj_t mod_time_clock(void) { +#if MICROPY_PY_BUILTINS_FLOAT + // float cannot represent full range of int32 precisely, so we pre-divide + // int to reduce resolution, and then actually do float division hoping + // to preserve integer part resolution. + return mp_obj_new_float((mp_float_t)(clock() / 1000) / CLOCK_DIV); +#else + return mp_obj_new_int((mp_int_t)clock()); +#endif +} +STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_clock_obj, mod_time_clock); + +STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) { +#if MICROPY_PY_BUILTINS_FLOAT + struct timeval tv; + mp_float_t val = mp_obj_get_float(arg); + double ipart; + tv.tv_usec = round(modf(val, &ipart) * 1000000); + tv.tv_sec = ipart; + int res; + while (1) { + MP_THREAD_GIL_EXIT(); + res = sleep_select(0, NULL, NULL, NULL, &tv); + MP_THREAD_GIL_ENTER(); + #if MICROPY_SELECT_REMAINING_TIME + // TODO: This assumes Linux behavior of modifying tv to the remaining + // time. + if (res != -1 || errno != EINTR) { + break; + } + mp_handle_pending(); + //printf("select: EINTR: %ld:%ld\n", tv.tv_sec, tv.tv_usec); + #else + break; + #endif + } + RAISE_ERRNO(res, errno); +#else + // TODO: Handle EINTR + MP_THREAD_GIL_EXIT(); + sleep(mp_obj_get_int(arg)); + MP_THREAD_GIL_ENTER(); +#endif + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_time_sleep_obj, mod_time_sleep); + +STATIC mp_obj_t mod_time_localtime(size_t n_args, const mp_obj_t *args) { + time_t t; + if (n_args == 0) { + t = time(NULL); + } else { + #if MICROPY_PY_BUILTINS_FLOAT + mp_float_t val = mp_obj_get_float(args[0]); + t = (time_t)MICROPY_FLOAT_C_FUN(trunc)(val); + #else + t = mp_obj_get_int(args[0]); + #endif + } + struct tm *tm = localtime(&t); + + mp_obj_t ret = mp_obj_new_tuple(9, NULL); + + mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(ret); + tuple->items[0] = MP_OBJ_NEW_SMALL_INT(tm->tm_year + 1900); + tuple->items[1] = MP_OBJ_NEW_SMALL_INT(tm->tm_mon + 1); + tuple->items[2] = MP_OBJ_NEW_SMALL_INT(tm->tm_mday); + tuple->items[3] = MP_OBJ_NEW_SMALL_INT(tm->tm_hour); + tuple->items[4] = MP_OBJ_NEW_SMALL_INT(tm->tm_min); + tuple->items[5] = MP_OBJ_NEW_SMALL_INT(tm->tm_sec); + int wday = tm->tm_wday - 1; + if (wday < 0) { + wday = 6; + } + tuple->items[6] = MP_OBJ_NEW_SMALL_INT(wday); + tuple->items[7] = MP_OBJ_NEW_SMALL_INT(tm->tm_yday + 1); + tuple->items[8] = MP_OBJ_NEW_SMALL_INT(tm->tm_isdst); + + return ret; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_time_localtime_obj, 0, 1, mod_time_localtime); + +STATIC const mp_rom_map_elem_t mp_module_time_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_utime) }, + { MP_ROM_QSTR(MP_QSTR_clock), MP_ROM_PTR(&mod_time_clock_obj) }, + { MP_ROM_QSTR(MP_QSTR_sleep), MP_ROM_PTR(&mod_time_sleep_obj) }, + { MP_ROM_QSTR(MP_QSTR_sleep_ms), MP_ROM_PTR(&mp_utime_sleep_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_sleep_us), MP_ROM_PTR(&mp_utime_sleep_us_obj) }, + { MP_ROM_QSTR(MP_QSTR_time), MP_ROM_PTR(&mod_time_time_obj) }, + { MP_ROM_QSTR(MP_QSTR_ticks_ms), MP_ROM_PTR(&mp_utime_ticks_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_ticks_us), MP_ROM_PTR(&mp_utime_ticks_us_obj) }, + { MP_ROM_QSTR(MP_QSTR_ticks_cpu), MP_ROM_PTR(&mp_utime_ticks_cpu_obj) }, + { MP_ROM_QSTR(MP_QSTR_ticks_add), MP_ROM_PTR(&mp_utime_ticks_add_obj) }, + { MP_ROM_QSTR(MP_QSTR_ticks_diff), MP_ROM_PTR(&mp_utime_ticks_diff_obj) }, + { MP_ROM_QSTR(MP_QSTR_localtime), MP_ROM_PTR(&mod_time_localtime_obj) }, +}; + +STATIC MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table); + +const mp_obj_module_t mp_module_time = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t*)&mp_module_time_globals, +}; + +#endif // MICROPY_PY_UTIME diff --git a/pool/shard006/C/0117979_two_input_gate.c b/pool/shard006/C/0117979_two_input_gate.c new file mode 100644 index 0000000000000000000000000000000000000000..672f63191c7cc731950d31f8fb3b3422d3359527 --- /dev/null +++ b/pool/shard006/C/0117979_two_input_gate.c @@ -0,0 +1,63 @@ +/** + * A generic (lookup-table based) two input, one output logic gate. + */ + +#include "sark.h" +#include "spin1_api.h" + +#include "common.h" + +struct { + uint sim_length; + uint input_a_key; + uint input_b_key; + uint output_key; + uint lut; +} *config; + +uint last_input_a = 0; +uint last_input_b = 0; + +void on_tick(uint ticks, uint arg1) { + // Terminate after the specified duration + if (ticks >= config->sim_length) { + spin1_exit(0); + return; + } + + // Calculate the new output value + uint output = (config->lut >> (last_input_a | (last_input_b << 1))) & 1; + output = (output << 31) | config->output_key; + + // After a short (random) delay, send this value to anyone who cares... + spin1_delay_us(128 + (spin1_rand() & 0xFF)); + spin1_send_mc_packet(output, 0, 0); +} + +void on_mc_packet(uint key, uint arg1) { + if ((key & 0x7FFFFFFF) == config->input_a_key) { + last_input_a = key >> 31; + } + if ((key & 0x7FFFFFFF) == config->input_b_key) { + last_input_b = key >> 31; + } +} + + +void c_main(void) { + spin1_srand(spin1_get_id()); + + // Discover the config for this core. + // XXX: For simplicity, in this example application we (very infficiently) + // access SDRAM directly via this pointer instead of DMAing it into local + // memroy. + uint core = spin1_get_core_id(); + config = sark_tag_ptr(core, 0); + + spin1_set_timer_tick(1000); // 1ms + spin1_callback_on(TIMER_TICK, on_tick, 1); + + spin1_callback_on(MC_PACKET_RECEIVED, on_mc_packet, -1); + + spin1_start(SYNC_WAIT); +} diff --git a/pool/shard006/C/0117981_hrz.c b/pool/shard006/C/0117981_hrz.c new file mode 100644 index 0000000000000000000000000000000000000000..65cfc9f203375ac398d22a87e38cbbbd2358b176 --- /dev/null +++ b/pool/shard006/C/0117981_hrz.c @@ -0,0 +1,344 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% H H RRRR ZZZZZ % +% H H R R ZZ % +% HHHHH RRRR Z % +% H H R R ZZ % +% H H R R ZZZZZ % +% % +% % +% Read/Write Slow Scan TeleVision Image Format % +% % +% Software Design % +% Cristy % +% July 1992 % +% % +% % +% Copyright 1999-2014 ImageMagick Studio LLC, a non-profit organization % +% dedicated to making software imaging solutions freely available. % +% % +% You may not use this file except in compliance with the License. You may % +% obtain a copy of the License at % +% % +% http://www.imagemagick.org/script/license.php % +% % +% Unless required by applicable law or agreed to in writing, software % +% distributed under the License is distributed on an "AS IS" BASIS, % +% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % +% See the License for the specific language governing permissions and % +% limitations under the License. % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% +*/ + +/* + Include declarations. +*/ +#include "magick/studio.h" +#include "magick/blob.h" +#include "magick/blob-private.h" +#include "magick/cache.h" +#include "magick/colorspace.h" +#include "magick/colorspace-private.h" +#include "magick/exception.h" +#include "magick/exception-private.h" +#include "magick/image.h" +#include "magick/image-private.h" +#include "magick/list.h" +#include "magick/magick.h" +#include "magick/memory_.h" +#include "magick/monitor.h" +#include "magick/monitor-private.h" +#include "magick/pixel-accessor.h" +#include "magick/quantum-private.h" +#include "magick/static.h" +#include "magick/string_.h" +#include "magick/module.h" + +/* + Forward declarations. +*/ +static MagickBooleanType + WriteHRZImage(const ImageInfo *,Image *); + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% R e a d H R Z I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% ReadHRZImage() reads a Slow Scan TeleVision image file and returns it. It +% allocates the memory necessary for the new Image structure and returns a +% pointer to the new image. +% +% The format of the ReadHRZImage method is: +% +% Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) +% +% A description of each parameter follows: +% +% o image_info: the image info. +% +% o exception: return any errors or warnings in this structure. +% +*/ +static Image *ReadHRZImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + status; + + register ssize_t + x; + + register PixelPacket + *q; + + register unsigned char + *p; + + ssize_t + count, + y; + + size_t + length; + + unsigned char + *pixels; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + image=AcquireImage(image_info); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Convert HRZ raster image to pixel packets. + */ + image->columns=256; + image->rows=240; + image->depth=8; + pixels=(unsigned char *) AcquireQuantumMemory(image->columns,3* + sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); + length=(size_t) (3*image->columns); + for (y=0; y < (ssize_t) image->rows; y++) + { + count=ReadBlob(image,length,pixels); + if ((size_t) count != length) + ThrowReaderException(CorruptImageError,"UnableToReadImageData"); + p=pixels; + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelRed(q,ScaleCharToQuantum(4**p++)); + SetPixelGreen(q,ScaleCharToQuantum(4**p++)); + SetPixelBlue(q,ScaleCharToQuantum(4**p++)); + SetPixelOpacity(q,OpaqueOpacity); + q++; + } + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse) + break; + } + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", + image->filename); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% R e g i s t e r H R Z I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% RegisterHRZImage() adds attributes for the HRZ X image format to the list +% of supported formats. The attributes include the image format tag, a +% method to read and/or write the format, whether the format supports the +% saving of more than one frame to the same file or blob, whether the format +% supports native in-memory I/O, and a brief description of the format. +% +% The format of the RegisterHRZImage method is: +% +% size_t RegisterHRZImage(void) +% +*/ +ModuleExport size_t RegisterHRZImage(void) +{ + MagickInfo + *entry; + + entry=SetMagickInfo("HRZ"); + entry->decoder=(DecodeImageHandler *) ReadHRZImage; + entry->encoder=(EncodeImageHandler *) WriteHRZImage; + entry->adjoin=MagickFalse; + entry->description=ConstantString("Slow Scan TeleVision"); + entry->module=ConstantString("HRZ"); + (void) RegisterMagickInfo(entry); + return(MagickImageCoderSignature); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% U n r e g i s t e r H R Z I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% UnregisterHRZImage() removes format registrations made by the +% HRZ module from the list of supported formats. +% +% The format of the UnregisterHRZImage method is: +% +% UnregisterHRZImage(void) +% +*/ +ModuleExport void UnregisterHRZImage(void) +{ + (void) UnregisterMagickInfo("HRZ"); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% W r i t e H R Z I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% WriteHRZImage() writes an image to a file in HRZ X image format. +% +% The format of the WriteHRZImage method is: +% +% MagickBooleanType WriteHRZImage(const ImageInfo *image_info,Image *image) +% +% A description of each parameter follows. +% +% o image_info: the image info. +% +% o image: The image. +% +*/ +static MagickBooleanType WriteHRZImage(const ImageInfo *image_info,Image *image) +{ + Image + *hrz_image; + + MagickBooleanType + status; + + register const PixelPacket + *p; + + register ssize_t + x, + y; + + register unsigned char + *q; + + ssize_t + count; + + unsigned char + *pixels; + + /* + Open output image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + hrz_image=ResizeImage(image,256,240,image->filter,image->blur, + &image->exception); + if (hrz_image == (Image *) NULL) + return(MagickFalse); + if (IssRGBCompatibleColorspace(hrz_image->colorspace) == MagickFalse) + (void) TransformImageColorspace(hrz_image,sRGBColorspace); + /* + Allocate memory for pixels. + */ + pixels=(unsigned char *) AcquireQuantumMemory((size_t) hrz_image->columns, + 3*sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + hrz_image=DestroyImage(hrz_image); + ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); + } + /* + Convert MIFF to HRZ raster pixels. + */ + for (y=0; y < (ssize_t) hrz_image->rows; y++) + { + p=GetVirtualPixels(hrz_image,0,y,hrz_image->columns,1,&image->exception); + if (p == (PixelPacket *) NULL) + break; + q=pixels; + for (x=0; x < (ssize_t) hrz_image->columns; x++) + { + *q++=ScaleQuantumToChar(GetPixelRed(p)/4); + *q++=ScaleQuantumToChar(GetPixelGreen(p)/4); + *q++=ScaleQuantumToChar(GetPixelBlue(p)/4); + p++; + } + count=WriteBlob(image,(size_t) (q-pixels),pixels); + if (count != (ssize_t) (q-pixels)) + break; + status=SetImageProgress(image,SaveImageTag,y,hrz_image->rows); + if (status == MagickFalse) + break; + } + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + hrz_image=DestroyImage(hrz_image); + (void) CloseBlob(image); + return(MagickTrue); +} diff --git a/pool/shard006/C/0117984_nextprime.c b/pool/shard006/C/0117984_nextprime.c new file mode 100644 index 0000000000000000000000000000000000000000..7966ddee8d230017a240f8f68115d1654aac39e5 --- /dev/null +++ b/pool/shard006/C/0117984_nextprime.c @@ -0,0 +1,120 @@ +/* mpz_nextprime(p,t) - compute the next prime > t and store that in p. + +Copyright 1999, 2000, 2001, 2008, 2009 Free Software Foundation, Inc. + +Contributed to the GNU project by Niels Möller and Torbjörn Granlund. + +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 3 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. If not, see http://www.gnu.org/licenses/. */ + +#include "gmp.h" +#include "gmp-impl.h" +#include "longlong.h" + +static const unsigned char primegap[] = +{ + 2,2,4,2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,14,4,6, + 2,10,2,6,6,4,6,6,2,10,2,4,2,12,12,4,2,4,6,2,10,6,6,6,2,6,4,2,10,14,4,2, + 4,14,6,10,2,4,6,8,6,6,4,6,8,4,8,10,2,10,2,6,4,6,8,4,2,4,12,8,4,8,4,6, + 12,2,18,6,10,6,6,2,6,10,6,6,2,6,6,4,2,12,10,2,4,6,6,2,12,4,6,8,10,8,10,8, + 6,6,4,8,6,4,8,4,14,10,12,2,10,2,4,2,10,14,4,2,4,14,4,2,4,20,4,8,10,8,4,6, + 6,14,4,6,6,8,6,12 +}; + +#define NUMBER_OF_PRIMES 167 + +void +mpz_nextprime (mpz_ptr p, mpz_srcptr n) +{ + unsigned short *moduli; + unsigned long difference; + int i; + unsigned prime_limit; + unsigned long prime; + int cnt; + mp_size_t pn; + unsigned long nbits; + unsigned incr; + TMP_SDECL; + + /* First handle tiny numbers */ + if (mpz_cmp_ui (n, 2) < 0) + { + mpz_set_ui (p, 2); + return; + } + mpz_add_ui (p, n, 1); + mpz_setbit (p, 0); + + if (mpz_cmp_ui (p, 7) <= 0) + return; + + pn = SIZ(p); + count_leading_zeros (cnt, PTR(p)[pn - 1]); + nbits = pn * GMP_NUMB_BITS - (cnt - GMP_NAIL_BITS); + if (nbits / 2 >= NUMBER_OF_PRIMES) + prime_limit = NUMBER_OF_PRIMES - 1; + else + prime_limit = nbits / 2; + + TMP_SMARK; + + /* Compute residues modulo small odd primes */ + moduli = TMP_SALLOC_TYPE (prime_limit * sizeof moduli[0], unsigned short); + + for (;;) + { + /* FIXME: Compute lazily? */ + prime = 3; + for (i = 0; i < prime_limit; i++) + { + moduli[i] = mpz_fdiv_ui (p, prime); + prime += primegap[i]; + } + +#define INCR_LIMIT 0x10000 /* deep science */ + + for (difference = incr = 0; incr < INCR_LIMIT; difference += 2) + { + /* First check residues */ + prime = 3; + for (i = 0; i < prime_limit; i++) + { + unsigned r; + /* FIXME: Reduce moduli + incr and store back, to allow for + division-free reductions. Alternatively, table primes[]'s + inverses (mod 2^16). */ + r = (moduli[i] + incr) % prime; + prime += primegap[i]; + + if (r == 0) + goto next; + } + + mpz_add_ui (p, p, difference); + difference = 0; + + /* Miller-Rabin test */ + if (mpz_millerrabin (p, 10)) + goto done; + next:; + incr += 2; + } + mpz_add_ui (p, p, difference); + difference = 0; + } + done: + TMP_SFREE; +} diff --git a/pool/shard006/C/0117985_hsdramc.c b/pool/shard006/C/0117985_hsdramc.c new file mode 100644 index 0000000000000000000000000000000000000000..f36da354528daaa6fae939341cecc3126898105b --- /dev/null +++ b/pool/shard006/C/0117985_hsdramc.c @@ -0,0 +1,155 @@ +/* + * Copyright (C) 2005-2006 Atmel Corporation + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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 + +#ifdef CFG_HSDRAMC +#include +#include + +#include + +#include "hsdramc1.h" + +struct hsdramc { + const struct device *hebi; + void *regs; +}; + +static struct hsdramc hsdramc; + +unsigned long sdram_init(const struct sdram_info *info) +{ + unsigned long *sdram = (unsigned long *)uncached(info->phys_addr); + unsigned long sdram_size; + unsigned long tmp; + unsigned long bus_hz; + unsigned int i; + + hsdramc.hebi = get_device(DEVICE_HEBI); + if (!hsdramc.hebi) + return 0; + + /* FIXME: Both of these lines are complete hacks */ + hsdramc.regs = hsdramc.hebi->regs + 0x400; + bus_hz = pm_get_clock_freq(hsdramc.hebi->resource[0].u.clock.id); + + cpu_enable_sdram(); + + tmp = (HSDRAMC1_BF(NC, info->col_bits - 8) + | HSDRAMC1_BF(NR, info->row_bits - 11) + | HSDRAMC1_BF(NB, info->bank_bits - 1) + | HSDRAMC1_BF(CAS, info->cas) + | HSDRAMC1_BF(TWR, info->twr) + | HSDRAMC1_BF(TRC, info->trc) + | HSDRAMC1_BF(TRP, info->trp) + | HSDRAMC1_BF(TRCD, info->trcd) + | HSDRAMC1_BF(TRAS, info->tras) + | HSDRAMC1_BF(TXSR, info->txsr)); + +#ifdef CFG_SDRAM_16BIT + tmp |= HSDRAMC1_BIT(DBW); + sdram_size = 1 << (info->row_bits + info->col_bits + + info->bank_bits + 1); +#else + sdram_size = 1 << (info->row_bits + info->col_bits + + info->bank_bits + 2); +#endif + + hsdramc1_writel(&hsdramc, CR, tmp); + + /* + * Initialization sequence for SDRAM, from the data sheet: + * + * 1. A minimum pause of 200 us is provided to precede any + * signal toggle. + */ + udelay(200); + + /* + * 2. A Precharge All command is issued to the SDRAM + */ + hsdramc1_writel(&hsdramc, MR, HSDRAMC1_MODE_BANKS_PRECHARGE); + hsdramc1_readl(&hsdramc, MR); + writel(0, sdram); + + /* + * 3. Eight auto-refresh (CBR) cycles are provided + */ + hsdramc1_writel(&hsdramc, MR, HSDRAMC1_MODE_AUTO_REFRESH); + hsdramc1_readl(&hsdramc, MR); + for (i = 0; i < 8; i++) + writel(0, sdram); + + /* + * 4. A mode register set (MRS) cycle is issued to program + * SDRAM parameters, in particular CAS latency and burst + * length. + * + * CAS from info struct, burst length 1, serial burst type + */ + hsdramc1_writel(&hsdramc, MR, HSDRAMC1_MODE_LOAD_MODE); + hsdramc1_readl(&hsdramc, MR); + writel(0, sdram + (info->cas << 4)); + + /* + * 5. A Normal Mode command is provided, 3 clocks after tMRD + * is met. + * + * From the timing diagram, it looks like tMRD is 3 + * cycles...try a dummy read from the peripheral bus. + */ + hsdramc1_readl(&hsdramc, MR); + hsdramc1_writel(&hsdramc, MR, HSDRAMC1_MODE_NORMAL); + hsdramc1_readl(&hsdramc, MR); + writel(0, sdram); + + /* + * 6. Write refresh rate into SDRAMC refresh timer count + * register (refresh rate = timing between refresh cycles). + * + * 15.6 us is a typical value for a burst of length one + */ + hsdramc1_writel(&hsdramc, TR, (156 * (bus_hz / 1000)) / 10000); + + printf("SDRAM: %u MB at address 0x%08lx\n", + sdram_size >> 20, info->phys_addr); + + printf("Testing SDRAM..."); + for (i = 0; i < sdram_size / 4; i++) + sdram[i] = i; + + for (i = 0; i < sdram_size / 4; i++) { + tmp = sdram[i]; + if (tmp != i) { + printf("FAILED at address 0x%08lx\n", + info->phys_addr + i * 4); + printf("SDRAM: read 0x%lx, expected 0x%lx\n", tmp, i); + return 0; + } + } + + puts("OK\n"); + + return sdram_size; +} + +#endif /* CFG_HSDRAMC */ diff --git a/pool/shard006/C/0117987_testa_string_soma_stdin.c b/pool/shard006/C/0117987_testa_string_soma_stdin.c new file mode 100644 index 0000000000000000000000000000000000000000..08527a10f283a432954d2f7fdbbbae3765cf1d96 --- /dev/null +++ b/pool/shard006/C/0117987_testa_string_soma_stdin.c @@ -0,0 +1,38 @@ +#include "string_soma.h" +#include +#include +#include + +/*! \file */ + +/**\Class STDin +*\brief Função que lê da entrada padrão para soma_string() e escreve sua saida na saida padrão +*/ +/** Função com alocação dinamica de memória para a entrada +*/ + +int main(){ + char cbuff[2] ={0,0}; /* cbuff é um buffer de uma string de 1 char */ + char last=0; + char *mem=NULL; + int size = 0; + int i=0; + mem = (char*)malloc(sizeof(char));/* MEM é a variavel utilizada para transmitir a string lida para soma_string() */ + do{ + sprintf(cbuff,"%c",getchar()); /* Lendo pra cbuff */ + if(last=='\\'&& cbuff[0] == 'n'){ /* Aqui é verificado se o caractere especial \\n foi lido como a string {'\','n'}, fazendo a correçao*/ + for(i=0;i +#include +#include +#include +#include +#include "config.h" +#include "lcd.h" +#include + +//////////////////SERVICE////BOOTH///////////////////////////// + +char amIFree; +char selfID[10]; + +//01 23 4 56789 012345 6 + +void printLCD(char f[],char s[]) +{ + LCDClear(); + LCDWriteString(f); + if (strlen(s)) + { + LCDWriteStringXY(0,1,s); + } +} + + +void printLCDFree() { printLCD("Free",selfID); } + +void genPacket(char *c, char commandType) { + int i; + c[0] = STB_ALIAS_SERVER; + c[1] = STB_SERVER_ID; + c[2] = STB_ALIAS_SERVICEBOOTH; + c[3] = SELF_ID; + c[4] = commandType; + for(i=5; i < 17; i++) c[i] = '-'; + c[17] = 0; +} + +//01 23 45678 90123456 +////////////////////process////////////////////// +void processData(char data[]) +{ + //NOISE// + //printf(data); + if (data[0]==STB_ALIAS_SERVICEBOOTH && data[1]==SELF_ID) + { + //printf("YES i am that guy %c",SELF_ID); + //printLCD("YES","WOW"); + //printData(data); + } + else return ; + char s[20]; + switch(data[4]) + { + case STB_SERVER_PING_SERVICE: + //printf("in ping %c",SELF_ID); + genPacket(s, amIFree); + printf("%s", s); + //printLCD(s, "line 2 :P"); + break; + case STB_SERVER_NEW_USER: + amIFree=STB_SERVICE_BUSY; + genPacket(s, STB_SERVICE_TAKEN_USER); + printf("%s", s); + //printLCD("Serving", ""); + char type[10]; + switch(data[5]) + { + case STB_CATEGORY_WITHDRAW: + strcpy(type,"Withdraw"); + break; + case STB_CATEGORY_DEPOSIT: + strcpy(type,"Deposit"); + break; + case STB_CATEGORY_HELP: + strcpy(type,"help"); + break; + default: + strcpy(type,"Unknown"); + } + char no[]={data[6],data[7],data[8],data[9],0}; + //printf(" i got %s and %s",type,no); + printLCD(type,no); + break; + } + + +} + +//======================================================== +int SendCmd(char cmd,FILE *stream) +{ + UCSRB |= (1<> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register + UBRRL = BAUD_PRESCALE; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register + + stdout = fdevopen(SendCmd,NULL); + stdin = fdevopen(NULL,RecieveCmd); + + //printf("Welcome!\n\rThis is develop by Nayeem, Enzam, Shafiul ,Hira& Dipal.\n\rMachineStarted\n\r 0-INIT\n\r 1-SETvalue\n\r 2-STAT\n\r"); + //printf("Welcome! This transmitter will transmit nothing\n\rZZZZZ\n\r"); + + LCDClear(); + sei(); + + UCSRB &= ~(1<>3) + '0'; + amIFree=STB_SERVICE_FREE; + + + sprintf(selfID, "S000%c", SELF_ID); + printLCDFree(); + + while(1){} + + return 0; +} + diff --git a/pool/shard006/C/0118000_hvCall_inst.c b/pool/shard006/C/0118000_hvCall_inst.c new file mode 100644 index 0000000000000000000000000000000000000000..2c59b4986ea540bd3ebc9e13b09833364b388542 --- /dev/null +++ b/pool/shard006/C/0118000_hvCall_inst.c @@ -0,0 +1,140 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright (C) 2006 Mike Kravetz IBM Corporation + * + * Hypervisor Call Instrumentation + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* For hcall instrumentation. One structure per-hcall, per-CPU */ +struct hcall_stats { + unsigned long num_calls; /* number of calls (on this CPU) */ + unsigned long tb_total; /* total wall time (mftb) of calls. */ + unsigned long purr_total; /* total cpu time (PURR) of calls. */ + unsigned long tb_start; + unsigned long purr_start; +}; +#define HCALL_STAT_ARRAY_SIZE ((MAX_HCALL_OPCODE >> 2) + 1) + +DEFINE_PER_CPU(struct hcall_stats[HCALL_STAT_ARRAY_SIZE], hcall_stats); + +/* + * Routines for displaying the statistics in debugfs + */ +static void *hc_start(struct seq_file *m, loff_t *pos) +{ + if ((int)*pos < (HCALL_STAT_ARRAY_SIZE-1)) + return (void *)(unsigned long)(*pos + 1); + + return NULL; +} + +static void *hc_next(struct seq_file *m, void *p, loff_t * pos) +{ + ++*pos; + + return hc_start(m, pos); +} + +static void hc_stop(struct seq_file *m, void *p) +{ +} + +static int hc_show(struct seq_file *m, void *p) +{ + unsigned long h_num = (unsigned long)p; + struct hcall_stats *hs = m->private; + + if (hs[h_num].num_calls) { + if (cpu_has_feature(CPU_FTR_PURR)) + seq_printf(m, "%lu %lu %lu %lu\n", h_num<<2, + hs[h_num].num_calls, + hs[h_num].tb_total, + hs[h_num].purr_total); + else + seq_printf(m, "%lu %lu %lu\n", h_num<<2, + hs[h_num].num_calls, + hs[h_num].tb_total); + } + + return 0; +} + +static const struct seq_operations hcall_inst_sops = { + .start = hc_start, + .next = hc_next, + .stop = hc_stop, + .show = hc_show +}; + +DEFINE_SEQ_ATTRIBUTE(hcall_inst); + +#define HCALL_ROOT_DIR "hcall_inst" +#define CPU_NAME_BUF_SIZE 32 + + +static void probe_hcall_entry(void *ignored, unsigned long opcode, unsigned long *args) +{ + struct hcall_stats *h; + + if (opcode > MAX_HCALL_OPCODE) + return; + + h = this_cpu_ptr(&hcall_stats[opcode / 4]); + h->tb_start = mftb(); + h->purr_start = mfspr(SPRN_PURR); +} + +static void probe_hcall_exit(void *ignored, unsigned long opcode, long retval, + unsigned long *retbuf) +{ + struct hcall_stats *h; + + if (opcode > MAX_HCALL_OPCODE) + return; + + h = this_cpu_ptr(&hcall_stats[opcode / 4]); + h->num_calls++; + h->tb_total += mftb() - h->tb_start; + h->purr_total += mfspr(SPRN_PURR) - h->purr_start; +} + +static int __init hcall_inst_init(void) +{ + struct dentry *hcall_root; + char cpu_name_buf[CPU_NAME_BUF_SIZE]; + int cpu; + + if (!firmware_has_feature(FW_FEATURE_LPAR)) + return 0; + + if (register_trace_hcall_entry(probe_hcall_entry, NULL)) + return -EINVAL; + + if (register_trace_hcall_exit(probe_hcall_exit, NULL)) { + unregister_trace_hcall_entry(probe_hcall_entry, NULL); + return -EINVAL; + } + + hcall_root = debugfs_create_dir(HCALL_ROOT_DIR, NULL); + + for_each_possible_cpu(cpu) { + snprintf(cpu_name_buf, CPU_NAME_BUF_SIZE, "cpu%d", cpu); + debugfs_create_file(cpu_name_buf, 0444, hcall_root, + per_cpu(hcall_stats, cpu), + &hcall_inst_fops); + } + + return 0; +} +machine_device_initcall(pseries, hcall_inst_init); diff --git a/pool/shard006/C/0118002_rmnet_map_data.c b/pool/shard006/C/0118002_rmnet_map_data.c new file mode 100644 index 0000000000000000000000000000000000000000..9c8fb5d656a8a562c7d153567a37374d15ce155b --- /dev/null +++ b/pool/shard006/C/0118002_rmnet_map_data.c @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2013, The Linux Foundation. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * RMNET Data MAP protocol + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "rmnet_data_config.h" +#include "rmnet_map.h" +#include "rmnet_data_private.h" + +RMNET_LOG_MODULE(RMNET_DATA_LOGMASK_MAPD); + +/* ***************** Local Definitions ************************************** */ +struct agg_work { + struct delayed_work work; + struct rmnet_phys_ep_conf_s *config; +}; + +/******************************************************************************/ + +/** + * rmnet_map_add_map_header() - Adds MAP header to front of skb->data + * @skb: Socket buffer ("packet") to modify + * @hdrlen: Number of bytes of header data which should not be included in + * MAP length field + * + * Padding is calculated and set appropriately in MAP header. Mux ID is + * initialized to 0. + * + * Return: + * - Pointer to MAP structure + * - 0 (null) if insufficient headroom + * - 0 (null) if insufficient tailroom for padding bytes + * + * todo: Parameterize skb alignment + */ +struct rmnet_map_header_s *rmnet_map_add_map_header(struct sk_buff *skb, + int hdrlen) +{ + uint32_t padding, map_datalen; + uint8_t *padbytes; + struct rmnet_map_header_s *map_header; + + if (skb_headroom(skb) < sizeof(struct rmnet_map_header_s)) + return 0; + + map_datalen = skb->len - hdrlen; + map_header = (struct rmnet_map_header_s *) + skb_push(skb, sizeof(struct rmnet_map_header_s)); + memset(map_header, 0, sizeof(struct rmnet_map_header_s)); + + padding = ALIGN(map_datalen, 4) - map_datalen; + + if (skb_tailroom(skb) < padding) + return 0; + + padbytes = (uint8_t *) skb_put(skb, padding); + LOGD("pad: %d\n", padding); + memset(padbytes, 0, padding); + + map_header->pkt_len = htons(map_datalen + padding); + map_header->pad_len = padding&0x3F; + + return map_header; +} + +/** + * rmnet_map_deaggregate() - Deaggregates a single packet + * @skb: Source socket buffer containing multiple MAP frames + * @config: Physical endpoint configuration of the ingress device + * + * Source skb is cloned with skb_clone(). The new skb data and tail pointers are + * modified to contain a single MAP frame. Clone happens with GFP_ATOMIC flags + * set. User should keep calling deaggregate() on the source skb until 0 is + * returned, indicating that there are no more packets to deaggregate. + * + * Return: + * - Pointer to new skb + * - 0 (null) if no more aggregated packets + */ +struct sk_buff *rmnet_map_deaggregate(struct sk_buff *skb, + struct rmnet_phys_ep_conf_s *config) +{ + struct sk_buff *skbn; + struct rmnet_map_header_s *maph; + uint32_t packet_len; + uint8_t ip_byte; + + if (skb->len == 0) + return 0; + + maph = (struct rmnet_map_header_s *) skb->data; + packet_len = ntohs(maph->pkt_len) + sizeof(struct rmnet_map_header_s); + if ((((int)skb->len) - ((int)packet_len)) < 0) { + LOGM("%s(): Got malformed packet. Dropping\n", __func__); + return 0; + } + + skbn = skb_copy(skb, GFP_ATOMIC); + if (!skbn) + return 0; + + LOGD("Trimming to %d bytes\n", packet_len); + LOGD("before skbn->len = %d", skbn->len); + skb_trim(skbn, packet_len); + skb_pull(skb, packet_len); + LOGD("after skbn->len = %d", skbn->len); + + /* Sanity check */ + ip_byte = (skbn->data[4]) & 0xF0; + if (ip_byte != 0x40 && ip_byte != 0x60) { + LOGM("%s() Unknown IP type: 0x%02X\n", __func__, ip_byte); + kfree_skb(skbn); + return 0; + } + + return skbn; +} + +/** + * rmnet_map_flush_packet_queue() - Transmits aggregeted frame on timeout + * @work: struct agg_work containing delayed work and skb to flush + * + * This function is scheduled to run in a specified number of jiffies after + * the last frame transmitted by the network stack. When run, the buffer + * containing aggregated packets is finally transmitted on the underlying link. + * + */ +static void rmnet_map_flush_packet_queue(struct work_struct *work) +{ + struct agg_work *real_work; + struct rmnet_phys_ep_conf_s *config; + unsigned long flags; + struct sk_buff *skb; + + skb = 0; + real_work = (struct agg_work *)work; + config = real_work->config; + LOGD("Entering flush thread\n"); + spin_lock_irqsave(&config->agg_lock, flags); + if (likely(config->agg_state == RMNET_MAP_TXFER_SCHEDULED)) { + if (likely(config->agg_skb)) { + /* Buffer may have already been shipped out */ + if (config->agg_count > 1) + LOGL("Agg count: %d\n", config->agg_count); + skb = config->agg_skb; + config->agg_skb = 0; + } + config->agg_state = RMNET_MAP_AGG_IDLE; + } else { + /* How did we get here? */ + LOGE("%s(): Ran queued command when state %s\n", + "is idle. State machine likely broken", __func__); + } + + spin_unlock_irqrestore(&config->agg_lock, flags); + if (skb) + dev_queue_xmit(skb); + kfree(work); +} + +/** + * rmnet_map_aggregate() - Software aggregates multiple packets. + * @skb: current packet being transmitted + * @config: Physical endpoint configuration of the ingress device + * + * Aggregates multiple SKBs into a single large SKB for transmission. MAP + * protocol is used to separate the packets in the buffer. This funcion consumes + * the argument SKB and should not be further processed by any other function. + */ +void rmnet_map_aggregate(struct sk_buff *skb, + struct rmnet_phys_ep_conf_s *config) { + uint8_t *dest_buff; + struct agg_work *work; + unsigned long flags; + struct sk_buff *agg_skb; + int size; + + + if (!skb || !config) + BUG(); + size = config->egress_agg_size-skb->len; + + if (size < 2000) { + LOGL("Invalid length %d\n", size); + return; + } + +new_packet: + spin_lock_irqsave(&config->agg_lock, flags); + if (!config->agg_skb) { + config->agg_skb = skb_copy_expand(skb, 0, size, GFP_ATOMIC); + if (!config->agg_skb) { + config->agg_skb = 0; + config->agg_count = 0; + spin_unlock_irqrestore(&config->agg_lock, flags); + dev_queue_xmit(skb); + return; + } + config->agg_count = 1; + kfree_skb(skb); + goto schedule; + } + + if (skb->len > (config->egress_agg_size - config->agg_skb->len)) { + if (config->agg_count > 1) + LOGL("Agg count: %d\n", config->agg_count); + agg_skb = config->agg_skb; + config->agg_skb = 0; + config->agg_count = 0; + spin_unlock_irqrestore(&config->agg_lock, flags); + dev_queue_xmit(agg_skb); + goto new_packet; + } + + dest_buff = skb_put(config->agg_skb, skb->len); + memcpy(dest_buff, skb->data, skb->len); + config->agg_count++; + kfree_skb(skb); + +schedule: + if (config->agg_state != RMNET_MAP_TXFER_SCHEDULED) { + work = (struct agg_work *) + kmalloc(sizeof(struct agg_work), GFP_ATOMIC); + if (!work) { + LOGE("%s(): Failed to allocate work item for packet %s", + "transfer. DATA PATH LIKELY BROKEN!\n", __func__); + config->agg_state = RMNET_MAP_AGG_IDLE; + spin_unlock_irqrestore(&config->agg_lock, flags); + return; + } + INIT_DELAYED_WORK((struct delayed_work *)work, + rmnet_map_flush_packet_queue); + work->config = config; + config->agg_state = RMNET_MAP_TXFER_SCHEDULED; + schedule_delayed_work((struct delayed_work *)work, 1); + } + spin_unlock_irqrestore(&config->agg_lock, flags); + return; +} + diff --git a/pool/shard006/C/0118004_calc_test.c b/pool/shard006/C/0118004_calc_test.c new file mode 100644 index 0000000000000000000000000000000000000000..fe3f3c5bec2de07e8ed5ee74bb73fe19ae023c75 --- /dev/null +++ b/pool/shard006/C/0118004_calc_test.c @@ -0,0 +1,250 @@ +/** + ****************************************************************************** + * @file calc_test.c + * @author ykaidong (http://www.DevLabs.cn) + * @version V0.1 + * @date 2015-01-14 + * @brief + ****************************************************************************** + * Change Logs: + * Date Author Notes + * 2015-01-14 ykaidong the first version + * + ****************************************************************************** + * @attention + * + * Copyright(C) 2013-2015 by ykaidong + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This 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 Lesser 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. + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ + +// 单元测试所需要的头文件 +#include +#include +#include + +#include ".\cmockery\cmockery.h" + +// 其它 +#include +#include +#include +#include + +/* Private typedef -----------------------------------------------------------*/ + +// 位于目标文件中的一些typedef和宏, 原样搬过来 +typedef enum { + TOKENIZER_ERROR, // Error + TOKENIZER_ENDOFINPUT, // End of input + TOKENIZER_NUMBER, // number + TOKENIZER_PLUS, // + + TOKENIZER_MINUS, // - + TOKENIZER_ASTR, // * + TOKENIZER_SLASH, // / + TOKENIZER_LPAREN, // ( + TOKENIZER_RPAREN, // ) +} token_t; + + +/* Private define ------------------------------------------------------------*/ +#define EXPR_LEN 512 // 允许表达式长度 +#define MAX_NUM_LEN 5 // 运算数长度 + +// 按键 +#define KEY_BACKSPACE 8 +#define KEY_ENTER 13 +#define KEY_ESC 27 + +// 错误 +#define NO_ERROR 0 +#define SYTAX_ERROR 1 + +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +// 引用目标模块中的函数 +extern int get_input(char *buf); +extern token_t siglechar(void); +extern token_t get_next_token(void); +extern bool tokenizer_finished(void); +extern void error(int error); +extern void tokenizer_next(void); +extern token_t tokenizer_token(void); +extern int tokenizer_num(void); +extern void accept(token_t token); +extern int factor(void); +extern int term(void); +extern int expr(void); +extern void tokenizer_init(char *expr); +extern int test_main(int argc, char *argv[]); + +// 引用目标模块中的全局变量 +extern char *curr_char; +extern char *next_char; +extern token_t current_token; +extern int error_code; + + +// 替换getch(), 模拟用户输入 +int test_getch(void) +{ + // 这个返回值是使用will_return()函数指定的 + return (int)mock(); +} + +// 替换printf() +int test_printf(const char *format, ...) +{ + int return_value; + va_list args; + char temporary_buffer[32]; + va_start(args, format); + return_value = vsnprintf(temporary_buffer, sizeof(temporary_buffer), + format, args); + va_end(args); + + return return_value; +} + + + +// 测试函数 +void test_get_input(void **state) +{ + // 模拟用户输入的字符串 + char *user_input = "10 +9 - 8(\b * (4 - 3)2\b/2 \r"; + // 用户输入被处理之后得到的字符串 + char *input = "10+9-8*(4-3)/2"; + // 存储输入的缓存区 + char input_buf[EXPR_LEN]; + + size_t i; + for (i = 0; i < strlen(user_input); i++) + { + // 当调用test_getch()时将依次返回此处写入的字符 + will_return(test_getch, *(user_input + i)); + } + + // 测试, get_input()返回的是输入的有效字符数 + assert_int_equal(get_input(input_buf), strlen(input)); + + // 测试, 得到的输入值是否符合期望 + assert_string_equal(input_buf, input); + + return; +} + + + +void test_singlechar(void **state) +{ + // 待测试的符号 + char *tok_str = "+-*/()= "; + // 正确的返回值 + token_t retval[] = + { + TOKENIZER_PLUS, // + + TOKENIZER_MINUS, // - + TOKENIZER_ASTR, // * + TOKENIZER_SLASH, // / + TOKENIZER_LPAREN, // ( + TOKENIZER_RPAREN, // ) + TOKENIZER_ERROR, // = + TOKENIZER_ERROR // + }; + + // curr_char 是目标模块中的静态全局变量 + char *backup = curr_char; + curr_char = tok_str; + + // int i; + // for (i = 0; i < (sizeof(retval) / sizeof(retval[0])); i++) + // { + // assert_int_equal((int)siglechar(), (int)retval[i]); + // curr_char++; + // } + + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + assert_int_equal((int)siglechar(), (int)retval[curr_char - tok_str]); + curr_char++; + + // 恢复 + curr_char = backup; + + return; +} + + +// 对expr()进行测试之前进行必要的初始化(构造函数) +void test_expr_setup(void **state) +{ + // 初始化一个表达式, 以提供给expr()计算 + char *expr = "1+2*3-(4/2)"; // = 5 + + tokenizer_init(expr); +} + + +// 对expr()进行测试 +void test_expr(void **state) +{ + assert_int_equal(expr(), 5); +} + +// 对expr()进行测试后清场的函数(析构函数) +void test_expr_teardown(void **state) +{ + return; +} + + +int main(int argc, char *argv[]) +{ + UnitTest tests[] = + { + unit_test(test_get_input), + unit_test(test_singlechar), + unit_test_setup_teardown(test_expr, test_expr_setup, test_expr_teardown), + // unit_test_setup_teardown(test_expr, test_expr_setup, NULL); // 这样也可以 + }; + + return run_tests(tests); +} + + +/************* Copyright(C) 2013 - 2015 DevLabs **********END OF FILE**********/ + + diff --git a/pool/shard006/C/0118006_vhci_tx.c b/pool/shard006/C/0118006_vhci_tx.c new file mode 100644 index 0000000000000000000000000000000000000000..7ed614793071ae9c08e8e428f5fb6c4061c064e6 --- /dev/null +++ b/pool/shard006/C/0118006_vhci_tx.c @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2003-2008 Takahiro Hirofuchi + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This 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 +#include + +#include "usbip_common.h" +#include "vhci.h" + +static void setup_cmd_submit_pdu(struct usbip_header *pdup, struct urb *urb) +{ + struct vhci_priv *priv = ((struct vhci_priv *)urb->hcpriv); + struct vhci_device *vdev = priv->vdev; + + usbip_dbg_vhci_tx("URB, local devnum %u, remote devid %u\n", + usb_pipedevice(urb->pipe), vdev->devid); + + pdup->base.command = USBIP_CMD_SUBMIT; + pdup->base.seqnum = priv->seqnum; + pdup->base.devid = vdev->devid; + pdup->base.direction = usb_pipein(urb->pipe) ? + USBIP_DIR_IN : USBIP_DIR_OUT; + pdup->base.ep = usb_pipeendpoint(urb->pipe); + + usbip_pack_pdu(pdup, urb, USBIP_CMD_SUBMIT, 1); + + if (urb->setup_packet) + memcpy(pdup->u.cmd_submit.setup, urb->setup_packet, 8); +} + +static struct vhci_priv *dequeue_from_priv_tx(struct vhci_device *vdev) +{ + struct vhci_priv *priv, *tmp; + + spin_lock(&vdev->priv_lock); + + list_for_each_entry_safe(priv, tmp, &vdev->priv_tx, list) { + list_move_tail(&priv->list, &vdev->priv_rx); + spin_unlock(&vdev->priv_lock); + return priv; + } + + spin_unlock(&vdev->priv_lock); + + return NULL; +} + +static int vhci_send_cmd_submit(struct vhci_device *vdev) +{ + struct vhci_priv *priv = NULL; + + struct msghdr msg; + struct kvec iov[3]; + size_t txsize; + + size_t total_size = 0; + + while ((priv = dequeue_from_priv_tx(vdev)) != NULL) { + int ret; + struct urb *urb = priv->urb; + struct usbip_header pdu_header; + struct usbip_iso_packet_descriptor *iso_buffer = NULL; + + txsize = 0; + memset(&pdu_header, 0, sizeof(pdu_header)); + memset(&msg, 0, sizeof(msg)); + memset(&iov, 0, sizeof(iov)); + + usbip_dbg_vhci_tx("setup txdata urb %p\n", urb); + + /* 1. setup usbip_header */ + setup_cmd_submit_pdu(&pdu_header, urb); + usbip_header_correct_endian(&pdu_header, 1); + + iov[0].iov_base = &pdu_header; + iov[0].iov_len = sizeof(pdu_header); + txsize += sizeof(pdu_header); + + /* 2. setup transfer buffer */ + if (!usb_pipein(urb->pipe) && urb->transfer_buffer_length > 0) { + iov[1].iov_base = urb->transfer_buffer; + iov[1].iov_len = urb->transfer_buffer_length; + txsize += urb->transfer_buffer_length; + } + + /* 3. setup iso_packet_descriptor */ + if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { + ssize_t len = 0; + + iso_buffer = usbip_alloc_iso_desc_pdu(urb, &len); + if (!iso_buffer) { + usbip_event_add(&vdev->ud, + SDEV_EVENT_ERROR_MALLOC); + return -1; + } + + iov[2].iov_base = iso_buffer; + iov[2].iov_len = len; + txsize += len; + } + + ret = kernel_sendmsg(vdev->ud.tcp_socket, &msg, iov, 3, txsize); + if (ret != txsize) { + pr_err("sendmsg failed!, ret=%d for %zd\n", ret, + txsize); + kfree(iso_buffer); + usbip_event_add(&vdev->ud, VDEV_EVENT_ERROR_TCP); + return -1; + } + + kfree(iso_buffer); + usbip_dbg_vhci_tx("send txdata\n"); + + total_size += txsize; + } + + return total_size; +} + +static struct vhci_unlink *dequeue_from_unlink_tx(struct vhci_device *vdev) +{ + struct vhci_unlink *unlink, *tmp; + + spin_lock(&vdev->priv_lock); + + list_for_each_entry_safe(unlink, tmp, &vdev->unlink_tx, list) { + list_move_tail(&unlink->list, &vdev->unlink_rx); + spin_unlock(&vdev->priv_lock); + return unlink; + } + + spin_unlock(&vdev->priv_lock); + + return NULL; +} + +static int vhci_send_cmd_unlink(struct vhci_device *vdev) +{ + struct vhci_unlink *unlink = NULL; + + struct msghdr msg; + struct kvec iov[3]; + size_t txsize; + + size_t total_size = 0; + + while ((unlink = dequeue_from_unlink_tx(vdev)) != NULL) { + int ret; + struct usbip_header pdu_header; + + txsize = 0; + memset(&pdu_header, 0, sizeof(pdu_header)); + memset(&msg, 0, sizeof(msg)); + memset(&iov, 0, sizeof(iov)); + + usbip_dbg_vhci_tx("setup cmd unlink, %lu\n", unlink->seqnum); + + /* 1. setup usbip_header */ + pdu_header.base.command = USBIP_CMD_UNLINK; + pdu_header.base.seqnum = unlink->seqnum; + pdu_header.base.devid = vdev->devid; + pdu_header.base.ep = 0; + pdu_header.u.cmd_unlink.seqnum = unlink->unlink_seqnum; + + usbip_header_correct_endian(&pdu_header, 1); + + iov[0].iov_base = &pdu_header; + iov[0].iov_len = sizeof(pdu_header); + txsize += sizeof(pdu_header); + + ret = kernel_sendmsg(vdev->ud.tcp_socket, &msg, iov, 1, txsize); + if (ret != txsize) { + pr_err("sendmsg failed!, ret=%d for %zd\n", ret, + txsize); + usbip_event_add(&vdev->ud, VDEV_EVENT_ERROR_TCP); + return -1; + } + + usbip_dbg_vhci_tx("send txdata\n"); + + total_size += txsize; + } + + return total_size; +} + +int vhci_tx_loop(void *data) +{ + struct usbip_device *ud = data; + struct vhci_device *vdev = container_of(ud, struct vhci_device, ud); + + while (!kthread_should_stop()) { + if (vhci_send_cmd_submit(vdev) < 0) + break; + + if (vhci_send_cmd_unlink(vdev) < 0) + break; + + wait_event_interruptible(vdev->waitq_tx, ({ + kgr_task_safe(current); + (!list_empty(&vdev->priv_tx) || + !list_empty(&vdev->unlink_tx) || + kthread_should_stop()); })); + + usbip_dbg_vhci_tx("pending urbs ?, now wake up\n"); + } + + return 0; +} diff --git a/pool/shard006/C/0118008_demo.c b/pool/shard006/C/0118008_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..bc07b80e9ed947ba3fc61069a4b9734e9dda3000 --- /dev/null +++ b/pool/shard006/C/0118008_demo.c @@ -0,0 +1,155 @@ +#include "demo.h" +#include "data.h" +#include "expl.h" +#include "animsel.h" +#include "display.h" +#include "title.h" +#include "game.h" + +/* command line options */ +int cheat = FALSE; +int jumpstart = FALSE; + +/* our graphics, samples, etc. */ +DATAFILE *data; + +int max_fps = FALSE; + + +/* modifies the palette to give us nice colors for the GUI dialogs */ +static void set_gui_colors(void) +{ + static RGB black = { 0, 0, 0, 0 }; + static RGB grey = { 48, 48, 48, 0 }; + static RGB white = { 63, 63, 63, 0 }; + + set_color(0, &black); + set_color(16, &black); + set_color(1, &grey); + set_color(255, &white); + + gui_fg_color = palette_color[0]; + gui_bg_color = palette_color[1]; +} + + + +static void intro_screen(void) +{ + BITMAP *bmp; + play_sample(data[INTRO_SPL].dat, 255, 128, 1000, FALSE); + + bmp = + create_sub_bitmap(screen, SCREEN_W / 2 - 160, SCREEN_H / 2 - 100, + 320, 200); + play_memory_fli(data[INTRO_ANIM].dat, bmp, FALSE, NULL); + destroy_bitmap(bmp); + + rest(1000); + fade_out(1); +} + + + +int main(int argc, char *argv[]) +{ + int c, w, h; + char buf[256], buf2[256]; + ANIMATION_TYPE type; + + for (c = 1; c < argc; c++) { + if (stricmp(argv[c], "-cheat") == 0) + cheat = TRUE; + + if (stricmp(argv[c], "-jumpstart") == 0) + jumpstart = TRUE; + } + + /* The fonts we are using don't contain the full latin1 charset (not to + * mention Unicode), so in order to display correctly author names in + * the credits with 8-bit characters, we will convert them down to 7 + * bits with a custom mapping table. Fortunately, Allegro comes with a + * default custom mapping table which reduces Latin-1 and Extended-A + * characters to 7 bits. We don't even need to call set_ucodepage()! + */ + set_uformat(U_ASCII_CP); + + srand(time(NULL)); + if (allegro_init() != 0) + return 1; + install_keyboard(); + install_timer(); + install_mouse(); + + if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) { + allegro_message("Error initialising sound\n%s\n", allegro_error); + install_sound(DIGI_NONE, MIDI_NONE, NULL); + } + + if (install_joystick(JOY_TYPE_AUTODETECT) != 0) { + allegro_message("Error initialising joystick\n%s\n", allegro_error); + install_joystick(JOY_TYPE_NONE); + } + + if (set_gfx_mode(GFX_AUTODETECT, 320, 200, 0, 0) != 0) { + if (set_gfx_mode(GFX_SAFE, 320, 200, 0, 0) != 0) { + set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); + allegro_message("Unable to set any graphic mode\n%s\n", + allegro_error); + return 1; + } + } + + get_executable_name(buf, sizeof(buf)); + replace_filename(buf2, buf, "demo.dat", sizeof(buf2)); + set_color_conversion(COLORCONV_NONE); + data = load_datafile(buf2); + if (!data) { + set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); + allegro_message("Error loading %s\n", buf2); + exit(1); + } + + if (!jumpstart) { + intro_screen(); + } + + clear_bitmap(screen); + set_gui_colors(); + set_mouse_sprite(NULL); + + if (!gfx_mode_select(&c, &w, &h)) + exit(1); + + if (pick_animation_type(&type) < 0) + exit(1); + + init_display(c, w, h, type); + + generate_explosions(); + + //stop_sample(data[INTRO_SPL].dat); + + clear_bitmap(screen); + + while (title_screen()) + play_game(); + + destroy_display(); + + destroy_explosions(); + + stop_midi(); + + set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); + + end_title(); + + unload_datafile(data); + + allegro_exit(); + + return 0; +} + +END_OF_MAIN() diff --git a/pool/shard006/C/0118010_main.c b/pool/shard006/C/0118010_main.c new file mode 100644 index 0000000000000000000000000000000000000000..019d14e160a89596076d31fda4284bdab8b4d2df --- /dev/null +++ b/pool/shard006/C/0118010_main.c @@ -0,0 +1,141 @@ +#include +#include +#include + +#include "fa_network.h" +#include "fa_trans.h" +#include "fa_udp.h" +#include "fa_print.h" + + + +#define TRANS_BUF_SIZE (6*1024) //8k is the best buffer size of the trans(experence) +int trans_file(char *src_file,char *dest_url) +{ + FILE *fp; + int file_len; + char buf[TRANS_BUF_SIZE]; + char buf1[128]; + + fa_trans_t *trans; + int send_len; + int read_len; + int recv_len; + + int port; + char hostname[1024],proto[1024],path[1024]; + + memset(hostname, 0, 1024); + memset(proto, 0 , 1024); + memset(path, 0, 1024); + fa_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), + &port, path, sizeof(path), dest_url); + + fp = fopen(src_file, "rb"); + + if(fp == NULL) { + printf("srcfile open fail\n"); + goto fail; + } + fseek(fp, 0, SEEK_END); + file_len = ftell(fp); + fseek(fp, 0, SEEK_SET); + + /*create trans unit*/ + trans = fa_create_trans(fa_create_trans_udp, fa_destroy_trans_udp); + + /*try to open trans*/ + if(trans->open(trans,hostname,port)<0){ + /*if(trans->open(trans,hostname,port, "192.168.20.38", 1982)<0){*/ + printf("open connect fail\n"); + goto fail; + } + + for(;;) { + /*read_len = read(fd,buf,TRANS_BUF_SIZE);*/ + read_len = fread(buf, 1, TRANS_BUF_SIZE, fp); + + if(read_len < TRANS_BUF_SIZE){ + printf("read_len < TRANS_BUF_SIZE\n"); + goto fail; + } + else { + if(read_len < TRANS_BUF_SIZE) { + break; + + }else { + send_len = trans->send(trans,buf,read_len); + printf("-->send %d bytes\n", send_len); +#if 1 + memset(buf1, 0, 128); + recv_len = trans->recv(trans,buf1, 128); + printf("recv reply %d bytes, info=%s\n", recv_len, buf1); +#endif + + if(send_len < 0){ + printf("send fail\n"); + goto fail; + } + + if(send_len < read_len) { + printf("send_len < read_len\n"); + } + + } + + } + + } + + fa_destroy_trans(trans); + return 0; + +fail: + fa_destroy_trans(trans); + return -1; + +} + +/*#define USE_LOGFILE*/ + +int main() +{ + + /*char *sfile = "/home/luolongzhi/Project/ta/xs.wav";*/ + char *sfile = "xs.wav"; + /*char *dest_url = "udp://192.168.20.82:1983";*/ + char *dest_url = "udp://192.168.20.38:1983"; + /*char *dest_url = "udp://127.0.0.1:1982";*/ + +#ifdef USE_LOGFILE +#ifdef WIN32 + FA_PRINT_INIT(FA_PRINT_ENABLE, + FA_PRINT_FILE_ENABLE,FA_PRINT_STDOUT_ENABLE,FA_PRINT_STDERR_ENABLE, + FA_PRINT_PID_ENABLE, + ".\\log_udptrans\\", "udptranslog", "UDPTRANS", 10); +#else + FA_PRINT_INIT(FA_PRINT_ENABLE, + FA_PRINT_FILE_ENABLE,FA_PRINT_STDOUT_ENABLE,FA_PRINT_STDERR_ENABLE, + FA_PRINT_PID_ENABLE, + "./log_udptrans/", "udptranslog", "UDPTRANS", 10); +#endif +#endif + + if (fa_network_init()) { + FA_PRINT("FAIL: %s , [err at: %s-%d]\n", FA_ERR_SYS_IO, __FILE__, __LINE__); + return -1; + } + +#ifdef __GNUC__ + fa_sigpipe_init(NULL); +#endif + + + trans_file(sfile,dest_url); + + fa_network_close(); + + return 0; + + +} diff --git a/pool/shard006/C/0118012_cpuctl_test03.c b/pool/shard006/C/0118012_cpuctl_test03.c new file mode 100644 index 0000000000000000000000000000000000000000..8a80d693277561af3a28af4b3da118f0a1c9a535 --- /dev/null +++ b/pool/shard006/C/0118012_cpuctl_test03.c @@ -0,0 +1,234 @@ +/******************************************************************************/ +/* */ +/* Copyright (c) International Business Machines Corp., 2007 */ +/* */ +/* This program is free software; you can redistribute it and/or modify */ +/* it under the terms of the GNU General Public License as published by */ +/* the Free Software Foundation; either version 2 of the License, or */ +/* (at your option) any later version. */ +/* */ +/* This program is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See */ +/* the GNU General Public License for more details. */ +/* */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program; if not, write to the Free Software */ +/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +/* */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* File: cpuctl_test03.c */ +/* */ +/* Description: This is a c program that tests the cpucontroller fairness of */ +/* scheduling the tasks according to their group shares. This */ +/* testcase tests the scheduling fairness with respect to number */ +/* of classes and number of jobs in each class */ +/* */ +/* Total Tests: 1 */ +/* */ +/* Test 6: N X M (N groups with M tasks each) */ +/* Test 7: N*M X 1 (N*M groups with 1 task each) */ +/* Test 8: 1 X N*M (1 group with N*M tasks each) */ +/* */ +/* Test Name: cpu_controller_test03 */ +/* */ +/* Test Assertion */ +/* Please refer to the file cpuctl_testplan.txt */ +/* */ +/* Author: Sudhir Kumar skumar@linux.vnet.ibm.com */ +/* */ +/* History: */ +/* Created- 20/12/2007 -Sudhir Kumar */ +/* */ +/******************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../libcontrollers/libcontrollers.h" +#include "test.h" /* LTP harness APIs */ +#include "safe_macros.h" + +#define TIME_INTERVAL 30 /* Time interval in seconds */ +#define NUM_INTERVALS 2 /* How many iterations of TIME_INTERVAL */ + +char *TCID = "cpuctl_test03"; +int TST_TOTAL = 3; +pid_t scriptpid; +char path[] = "/dev/cpuctl"; +extern void cleanup(void) +{ + kill(scriptpid, SIGUSR1); /* Inform the shell to do cleanup */ + tst_exit(); /* Report exit status */ +} + +volatile int timer_expired = 0; + +int main(int argc, char *argv[]) +{ + + int test_num; + int task_num; + int len; + int num_cpus; /* Total time = TIME_INTERVAL *num_cpus in the machine */ + char mygroup[FILENAME_MAX], mytaskfile[FILENAME_MAX]; + char mysharesfile[FILENAME_MAX], ch; + /* Following variables are to capture parameters from script */ + char *group_num_p, *mygroup_p, *script_pid_p, *num_cpus_p, *test_num_p, + *task_num_p; + pid_t pid; + int mygroup_num, /* A number attached with a group */ + fd, /* A descriptor to open a fifo for synchronized start */ + counter = 0; /* To take n number of readings */ + double total_cpu_time, /* Accumulated cpu time */ + delta_cpu_time, /* Time the task could run on cpu(s) (in an interval) */ + prev_cpu_time = 0; + double exp_cpu_time; /* Expected time in % as obtained by shares calculation */ + struct rusage cpu_usage; + time_t current_time, prev_time, delta_time; + unsigned int fmyshares, num_tasks; /* f-> from file. num_tasks is tasks in this group */ + struct sigaction newaction, oldaction; + + mygroup_num = -1; + num_cpus = 0; + task_num = 0; + test_num = 0; + + /* Signal handling for alarm */ + sigemptyset(&newaction.sa_mask); + newaction.sa_handler = signal_handler_alarm; + newaction.sa_flags = 0; + sigaction(SIGALRM, &newaction, &oldaction); + + /* Collect the parameters passed by the script */ + group_num_p = getenv("GROUP_NUM"); + mygroup_p = getenv("MYGROUP"); + script_pid_p = getenv("SCRIPT_PID"); + num_cpus_p = getenv("NUM_CPUS"); + test_num_p = getenv("TEST_NUM"); + task_num_p = getenv("TASK_NUM"); + /* Check if all of them are valid */ + if ((test_num_p != NULL) + && (((test_num = atoi(test_num_p)) <= 8) + && ((test_num = atoi(test_num_p)) >= 6))) { + if ((group_num_p != NULL) && (mygroup_p != NULL) + && (script_pid_p != NULL) && (num_cpus_p != NULL) + && (task_num_p != NULL)) { + mygroup_num = atoi(group_num_p); + scriptpid = atoi(script_pid_p); + num_cpus = atoi(num_cpus_p); + task_num = atoi(task_num_p); + sprintf(mygroup, "%s", mygroup_p); + } else { + tst_brkm(TBROK, cleanup, + "Invalid other input parameters\n"); + } + } else { + tst_brkm(TBROK, cleanup, "Invalid test number passed\n"); + } + + sprintf(mytaskfile, "%s", mygroup); + sprintf(mysharesfile, "%s", mygroup); + strcat(mytaskfile, "/tasks"); + strcat(mysharesfile, "/cpu.shares"); + pid = getpid(); + write_to_file(mytaskfile, "a", pid); /* Assign the task to it's group */ + + fd = SAFE_OPEN(cleanup, "./myfifo", 0); + + read(fd, &ch, 1); /* To block all tasks here and fire them up at the same time */ + + /* + * We now calculate the expected % cpu time of this task by getting + * it's group's shares, the total shares of all the groups and the + * number of tasks in this group. + */ + FLAG = 0; + total_shares = 0; + shares_pointer = &total_shares; + len = strlen(path); + if (!strncpy(fullpath, path, len)) + tst_brkm(TBROK, cleanup, "Could not copy directory path %s ", + path); + + if (scan_shares_files(shares_pointer) != 0) + tst_brkm(TBROK, cleanup, + "From function scan_shares_files in %s ", fullpath); + + /* return val: -1 in case of function error, else 2 is min share value */ + if ((fmyshares = read_shares_file(mysharesfile)) < 2) + tst_brkm(TBROK, cleanup, "in reading shares files %s ", + mysharesfile); + + if ((read_file(mytaskfile, GET_TASKS, &num_tasks)) < 0) + tst_brkm(TBROK, cleanup, "in reading tasks files %s ", + mytaskfile); + + exp_cpu_time = (double)(fmyshares * 100) / (total_shares * num_tasks); + + prev_time = time(NULL); /* Note down the time */ + + while (1) { + /* Need to run some cpu intensive task, which also frequently checks the timer value */ + double f = 274.345, mytime; /*just a float number to take sqrt */ + alarm(TIME_INTERVAL); + timer_expired = 0; + while (!timer_expired) /* Let the task run on cpu for TIME_INTERVAL */ + f = sqrt(f * f); /* Time of this operation should not be high otherwise we can + * exceed the TIME_INTERVAL to measure cpu usage + */ + current_time = time(NULL); + delta_time = current_time - prev_time; /* Duration in case its not exact TIME_INTERVAL */ + + getrusage(0, &cpu_usage); + total_cpu_time = (cpu_usage.ru_utime.tv_sec + cpu_usage.ru_utime.tv_usec * 1e-6 + /* user time */ + cpu_usage.ru_stime.tv_sec + cpu_usage.ru_stime.tv_usec * 1e-6); /* system time */ + delta_cpu_time = total_cpu_time - prev_cpu_time; + + prev_cpu_time = total_cpu_time; + prev_time = current_time; + + /* calculate % cpu time each task gets */ + if (delta_time > TIME_INTERVAL) + mytime = + (delta_cpu_time * 100) / (delta_time * num_cpus); + else + mytime = + (delta_cpu_time * 100) / (TIME_INTERVAL * num_cpus); + + fprintf(stdout, "Grp:-%3d task-%3d:CPU TIME{calc:-%6.2f(s)i.e. %6.2f(%%) exp:-%6.2f(%%)}\ + in %lu (s) INTERVAL\n", mygroup_num, task_num, delta_cpu_time, mytime, + exp_cpu_time, delta_time); + + counter++; + + if (counter >= NUM_INTERVALS) { /* Take n sets of readings for each shares value */ + switch (test_num) { + case 6: /* Test 06 */ + case 7: /* Test 07 */ + case 8: /* Test 08 */ + exit(0); /* This task is done with its job */ + break; + default: + tst_brkm(TBROK, cleanup, + "Invalid test number passed\n"); + break; + + } /* end switch */ + } /* end if */ + } /* end while */ +} /* end main */ diff --git a/pool/shard006/C/0118021_legacy.c b/pool/shard006/C/0118021_legacy.c new file mode 100644 index 0000000000000000000000000000000000000000..cbec3cf5ca9c18e86e63557192cd81f4c14e908b --- /dev/null +++ b/pool/shard006/C/0118021_legacy.c @@ -0,0 +1,155 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Quick and dirty compatibility layer + * + * This should allow old-API PCI drivers to at least function until + * they are updated. It will not help non-PCI drivers. + * + * No drivers should rely on this code. It will be removed asap. + * + */ + +struct nic nic; + +static int legacy_registered = 0; + +static int legacy_transmit ( struct net_device *netdev, struct io_buffer *iobuf ) { + struct nic *nic = netdev->priv; + struct ethhdr *ethhdr; + + DBG ( "Transmitting %zd bytes\n", iob_len ( iobuf ) ); + iob_pad ( iobuf, ETH_ZLEN ); + ethhdr = iobuf->data; + iob_pull ( iobuf, sizeof ( *ethhdr ) ); + nic->nic_op->transmit ( nic, ( const char * ) ethhdr->h_dest, + ntohs ( ethhdr->h_protocol ), + iob_len ( iobuf ), iobuf->data ); + netdev_tx_complete ( netdev, iobuf ); + return 0; +} + +static void legacy_poll ( struct net_device *netdev ) { + struct nic *nic = netdev->priv; + struct io_buffer *iobuf; + + iobuf = alloc_iob ( ETH_FRAME_LEN ); + if ( ! iobuf ) + return; + + nic->packet = iobuf->data; + if ( nic->nic_op->poll ( nic, 1 ) ) { + DBG ( "Received %d bytes\n", nic->packetlen ); + iob_put ( iobuf, nic->packetlen ); + netdev_rx ( netdev, iobuf ); + } else { + free_iob ( iobuf ); + } +} + +static int legacy_open ( struct net_device *netdev __unused ) { + /* Nothing to do */ + return 0; +} + +static void legacy_close ( struct net_device *netdev __unused ) { + /* Nothing to do */ +} + +static void legacy_irq ( struct net_device *netdev __unused, int enable ) { + struct nic *nic = netdev->priv; + + nic->nic_op->irq ( nic, ( enable ? ENABLE : DISABLE ) ); +} + +static struct net_device_operations legacy_operations = { + .open = legacy_open, + .close = legacy_close, + .transmit = legacy_transmit, + .poll = legacy_poll, + .irq = legacy_irq, +}; + +int legacy_probe ( void *hwdev, + void ( * set_drvdata ) ( void *hwdev, void *priv ), + struct device *dev, + int ( * probe ) ( struct nic *nic, void *hwdev ), + void ( * disable ) ( struct nic *nic, void *hwdev ) ) { + struct net_device *netdev; + int rc; + + if ( legacy_registered ) + return -EBUSY; + + netdev = alloc_etherdev ( 0 ); + if ( ! netdev ) + return -ENOMEM; + netdev_init ( netdev, &legacy_operations ); + netdev->priv = &nic; + memset ( &nic, 0, sizeof ( nic ) ); + set_drvdata ( hwdev, netdev ); + netdev->dev = dev; + + nic.node_addr = netdev->ll_addr; + nic.irqno = dev->desc.irq; + + if ( ! probe ( &nic, hwdev ) ) { + rc = -ENODEV; + goto err_probe; + } + + /* Overwrite the IRQ number. Some legacy devices set + * nic->irqno to 0 in the probe routine to indicate that they + * don't support interrupts; doing this allows the timer + * interrupt to be used instead. + */ + dev->desc.irq = nic.irqno; + + /* Mark as link up; legacy devices don't handle link state */ + netdev_link_up ( netdev ); + + if ( ( rc = register_netdev ( netdev ) ) != 0 ) + goto err_register; + + /* Do not remove this message */ + printf ( "WARNING: Using legacy NIC wrapper on %s\n", + ethernet_protocol.ntoa ( nic.node_addr ) ); + + legacy_registered = 1; + return 0; + + err_register: + disable ( &nic, hwdev ); + err_probe: + netdev_nullify ( netdev ); + netdev_put ( netdev ); + return rc; +} + +void legacy_remove ( void *hwdev, + void * ( * get_drvdata ) ( void *hwdev ), + void ( * disable ) ( struct nic *nic, void *hwdev ) ) { + struct net_device *netdev = get_drvdata ( hwdev ); + struct nic *nic = netdev->priv; + + unregister_netdev ( netdev ); + disable ( nic, hwdev ); + netdev_nullify ( netdev ); + netdev_put ( netdev ); + legacy_registered = 0; +} + +int dummy_connect ( struct nic *nic __unused ) { + return 1; +} + +void dummy_irq ( struct nic *nic __unused, irq_action_t irq_action __unused ) { + return; +} diff --git a/pool/shard006/C/0118022_nf_conntrack_acct.c b/pool/shard006/C/0118022_nf_conntrack_acct.c new file mode 100644 index 0000000000000000000000000000000000000000..ab81b380eae6814934de4318c67e6cd4d886ca1f --- /dev/null +++ b/pool/shard006/C/0118022_nf_conntrack_acct.c @@ -0,0 +1,148 @@ +/* Accouting handling for netfilter. */ + +/* + * (C) 2008 Krzysztof Piotr Oledzki + * + * 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 +#include +#include +#include + +#include +#include +#include + +#ifdef CONFIG_NF_CT_ACCT +#define NF_CT_ACCT_DEFAULT 1 +#else +#define NF_CT_ACCT_DEFAULT 0 +#endif + +static int nf_ct_acct __read_mostly = NF_CT_ACCT_DEFAULT; + +module_param_named(acct, nf_ct_acct, bool, 0644); +MODULE_PARM_DESC(acct, "Enable connection tracking flow accounting."); + +#ifdef CONFIG_SYSCTL +static struct ctl_table acct_sysctl_table[] = { + { + .procname = "nf_conntrack_acct", + .data = &init_net.ct.sysctl_acct, + .maxlen = sizeof(unsigned int), + .mode = 0644, + .proc_handler = proc_dointvec, + }, + {} +}; +#endif /* CONFIG_SYSCTL */ + +unsigned int +seq_print_acct(struct seq_file *s, const struct nf_conn *ct, int dir) +{ + struct nf_conn_counter *acct; + + acct = nf_conn_acct_find(ct); + if (!acct) + return 0; + + return seq_printf(s, "packets=%llu bytes=%llu ", + (unsigned long long)acct[dir].packets, + (unsigned long long)acct[dir].bytes); +}; +EXPORT_SYMBOL_GPL(seq_print_acct); + +static struct nf_ct_ext_type acct_extend __read_mostly = { + .len = sizeof(struct nf_conn_counter[IP_CT_DIR_MAX]), + .align = __alignof__(struct nf_conn_counter[IP_CT_DIR_MAX]), + .id = NF_CT_EXT_ACCT, +}; + +#ifdef CONFIG_SYSCTL +static int nf_conntrack_acct_init_sysctl(struct net *net) +{ + struct ctl_table *table; + + table = kmemdup(acct_sysctl_table, sizeof(acct_sysctl_table), + GFP_KERNEL); + if (!table) + goto out; + + table[0].data = &net->ct.sysctl_acct; + + net->ct.acct_sysctl_header = register_net_sysctl_table(net, + nf_net_netfilter_sysctl_path, table); + if (!net->ct.acct_sysctl_header) { + printk(KERN_ERR "nf_conntrack_acct: can't register to sysctl.\n"); + goto out_register; + } + return 0; + +out_register: + kfree(table); +out: + return -ENOMEM; +} + +static void nf_conntrack_acct_fini_sysctl(struct net *net) +{ + struct ctl_table *table; + + table = net->ct.acct_sysctl_header->ctl_table_arg; + unregister_net_sysctl_table(net->ct.acct_sysctl_header); + kfree(table); +} +#else +static int nf_conntrack_acct_init_sysctl(struct net *net) +{ + return 0; +} + +static void nf_conntrack_acct_fini_sysctl(struct net *net) +{ +} +#endif + +int nf_conntrack_acct_init(struct net *net) +{ + int ret; + + net->ct.sysctl_acct = nf_ct_acct; + + if (net_eq(net, &init_net)) { +#ifdef CONFIG_NF_CT_ACCT + printk(KERN_WARNING "CONFIG_NF_CT_ACCT is deprecated and will be removed soon. Please use\n"); + printk(KERN_WARNING "nf_conntrack.acct=1 kernel parameter, acct=1 nf_conntrack module option or\n"); + printk(KERN_WARNING "sysctl net.netfilter.nf_conntrack_acct=1 to enable it.\n"); +#endif + + ret = nf_ct_extend_register(&acct_extend); + if (ret < 0) { + printk(KERN_ERR "nf_conntrack_acct: Unable to register extension\n"); + goto out_extend_register; + } + } + + ret = nf_conntrack_acct_init_sysctl(net); + if (ret < 0) + goto out_sysctl; + + return 0; + +out_sysctl: + if (net_eq(net, &init_net)) + nf_ct_extend_unregister(&acct_extend); +out_extend_register: + return ret; +} + +void nf_conntrack_acct_fini(struct net *net) +{ + nf_conntrack_acct_fini_sysctl(net); + if (net_eq(net, &init_net)) + nf_ct_extend_unregister(&acct_extend); +} diff --git a/pool/shard006/C/0118023_clk-pll-zynqmp.c b/pool/shard006/C/0118023_clk-pll-zynqmp.c new file mode 100644 index 0000000000000000000000000000000000000000..e4b759b73c9cf53b32ce240f6f67786387ce8650 --- /dev/null +++ b/pool/shard006/C/0118023_clk-pll-zynqmp.c @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Zynq UltraScale+ MPSoC PLL Clock + * + * Copyright (C) 2019 Pengutronix, Michael Tretter + * + * Based on the Linux driver in drivers/clk/zynqmp/ + * + * Copyright (C) 2016-2018 Xilinx + */ + +#include +#include +#include + +#include "clk-zynqmp.h" + +struct zynqmp_pll { + struct clk clk; + unsigned int clk_id; + const char *parent; + const struct zynqmp_eemi_ops *ops; +}; + +#define to_zynqmp_pll(clk) \ + container_of(clk, struct zynqmp_pll, clk) + +#define PLL_FBDIV_MIN 25 +#define PLL_FBDIV_MAX 125 + +#define PS_PLL_VCO_MIN 1500000000 +#define PS_PLL_VCO_MAX 3000000000UL + +enum pll_mode { + PLL_MODE_INT, + PLL_MODE_FRAC, +}; + +#define FRAC_DIV (1 << 16) + +static inline enum pll_mode zynqmp_pll_get_mode(struct zynqmp_pll *pll) +{ + u32 ret_payload[PAYLOAD_ARG_CNT]; + + pll->ops->ioctl(0, IOCTL_GET_PLL_FRAC_MODE, pll->clk_id, 0, + ret_payload); + + return ret_payload[1]; +} + +static inline void zynqmp_pll_set_mode(struct zynqmp_pll *pll, enum pll_mode mode) +{ + pll->ops->ioctl(0, IOCTL_SET_PLL_FRAC_MODE, pll->clk_id, mode, NULL); +} + +static long zynqmp_pll_round_rate(struct clk *clk, unsigned long rate, + unsigned long *prate) +{ + struct zynqmp_pll *pll = to_zynqmp_pll(clk); + u32 fbdiv; + long rate_div; + + rate_div = (rate * FRAC_DIV) / *prate; + if (rate_div % FRAC_DIV) + zynqmp_pll_set_mode(pll, PLL_MODE_FRAC); + else + zynqmp_pll_set_mode(pll, PLL_MODE_INT); + + if (zynqmp_pll_get_mode(pll) == PLL_MODE_FRAC) { + if (rate > PS_PLL_VCO_MAX) { + fbdiv = rate / PS_PLL_VCO_MAX; + rate = rate / (fbdiv + 1); + } + if (rate < PS_PLL_VCO_MIN) { + fbdiv = DIV_ROUND_UP(PS_PLL_VCO_MIN, rate); + rate = rate * fbdiv; + } + } else { + fbdiv = DIV_ROUND_CLOSEST(rate, *prate); + fbdiv = clamp_t(u32, fbdiv, PLL_FBDIV_MIN, PLL_FBDIV_MAX); + rate = *prate * fbdiv; + } + + return rate; +} + +static unsigned long zynqmp_pll_recalc_rate(struct clk *clk, + unsigned long parent_rate) +{ + struct zynqmp_pll *pll = to_zynqmp_pll(clk); + u32 clk_id = pll->clk_id; + u32 fbdiv, data; + unsigned long rate, frac; + u32 ret_payload[PAYLOAD_ARG_CNT]; + int ret; + + ret = pll->ops->clock_getdivider(clk_id, &fbdiv); + + rate = parent_rate * fbdiv; + + if (zynqmp_pll_get_mode(pll) == PLL_MODE_FRAC) { + pll->ops->ioctl(0, IOCTL_GET_PLL_FRAC_DATA, clk_id, 0, + ret_payload); + data = ret_payload[1]; + frac = (parent_rate * data) / FRAC_DIV; + rate = rate + frac; + } + + return rate; +} + +static int zynqmp_pll_set_rate(struct clk *clk, unsigned long rate, + unsigned long parent_rate) +{ + struct zynqmp_pll *pll = to_zynqmp_pll(clk); + u32 clk_id = pll->clk_id; + u32 fbdiv; + long rate_div, frac, m, f; + + if (zynqmp_pll_get_mode(pll) == PLL_MODE_FRAC) { + rate_div = (rate * FRAC_DIV) / parent_rate; + m = rate_div / FRAC_DIV; + f = rate_div % FRAC_DIV; + m = clamp_t(u32, m, (PLL_FBDIV_MIN), (PLL_FBDIV_MAX)); + rate = parent_rate * m; + frac = (parent_rate * f) / FRAC_DIV; + + pll->ops->clock_setdivider(clk_id, m); + pll->ops->ioctl(0, IOCTL_SET_PLL_FRAC_DATA, clk_id, f, NULL); + + return rate + frac; + } else { + fbdiv = DIV_ROUND_CLOSEST(rate, parent_rate); + fbdiv = clamp_t(u32, fbdiv, PLL_FBDIV_MIN, PLL_FBDIV_MAX); + pll->ops->clock_setdivider(clk_id, fbdiv); + + return parent_rate * fbdiv; + } +} + +static int zynqmp_pll_is_enabled(struct clk *clk) +{ + struct zynqmp_pll *pll = to_zynqmp_pll(clk); + u32 is_enabled; + int ret; + + ret = pll->ops->clock_getstate(pll->clk_id, &is_enabled); + if (ret) + return -EIO; + + return !!(is_enabled); +} + +static int zynqmp_pll_enable(struct clk *clk) +{ + struct zynqmp_pll *pll = to_zynqmp_pll(clk); + + if (zynqmp_pll_is_enabled(clk)) + return 0; + + return pll->ops->clock_enable(pll->clk_id); +} + +static void zynqmp_pll_disable(struct clk *clk) +{ + struct zynqmp_pll *pll = to_zynqmp_pll(clk); + + if (!zynqmp_pll_is_enabled(clk)) + return; + + pll->ops->clock_disable(pll->clk_id); +} + +static const struct clk_ops zynqmp_pll_ops = { + .enable = zynqmp_pll_enable, + .disable = zynqmp_pll_disable, + .is_enabled = zynqmp_pll_is_enabled, + .round_rate = zynqmp_pll_round_rate, + .recalc_rate = zynqmp_pll_recalc_rate, + .set_rate = zynqmp_pll_set_rate, +}; + +struct clk *zynqmp_clk_register_pll(const char *name, + unsigned int clk_id, + const char **parents, + unsigned int num_parents, + const struct clock_topology *nodes) +{ + struct zynqmp_pll *pll; + int ret; + + pll = kzalloc(sizeof(*pll), GFP_KERNEL); + if (!pll) + return ERR_PTR(-ENOMEM); + + pll->clk_id = clk_id; + pll->ops = zynqmp_pm_get_eemi_ops(); + pll->parent = strdup(parents[0]); + + pll->clk.name = strdup(name); + pll->clk.ops = &zynqmp_pll_ops; + pll->clk.flags = nodes->flag | CLK_SET_RATE_PARENT; + pll->clk.parent_names = &pll->parent; + pll->clk.num_parents = 1; + + ret = clk_register(&pll->clk); + if (ret) { + kfree(pll); + return ERR_PTR(ret); + } + + return &pll->clk; +} diff --git a/pool/shard006/C/0118025_gfx_point.c b/pool/shard006/C/0118025_gfx_point.c new file mode 100644 index 0000000000000000000000000000000000000000..a5f6da535f38ff3679468187e01e64d1e525988e --- /dev/null +++ b/pool/shard006/C/0118025_gfx_point.c @@ -0,0 +1,108 @@ +/* Copyright 2012 Kjetil S. Matheussen + +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 "nsmtracker.h" + +#define GFX_DONTSHRINK +#include "visual_proc.h" +#include "visual_op_queue_proc.h" + +#include "gfx_point_proc.h" + + +struct Points{ + int pos; + int size; + uint16_t *x; + uint16_t *y; +}; + +static struct Points *points[16][MAX_BRIGHTNESS+1] = {{0}}; + +static bool is_dirty=false; + +void GFX_Point( + struct Tracker_Windows *window, + enum ColorNums color, + int brightness, + int x,int y, + int where + ) +{ + if(where==PAINT_DIRECTLY){ + RError("GFX_Point can not be called with where==PAINT_DIRECTLY"); + return; + } + + if(color>=16 || color<0){ + RError("Illegal color: %d",color); + color = R_ABS(color) % 16; + } + + brightness = R_BOUNDARIES(0, brightness, MAX_BRIGHTNESS); + +#if 0 + OS_GFX_Point(window,color,brightness,x,y,where); + return; +#endif + + struct Points *point=points[color][brightness]; + if(point==NULL) + points[color][brightness] = point = V_calloc(1,sizeof(struct Points)); + + int pos = point->pos; + + if(point->pos==point->size){ + point->size = R_MAX(128,point->size*2); + point->x=V_realloc(point->x,point->size*sizeof(uint16_t)); + point->y=V_realloc(point->y,point->size*sizeof(uint16_t)); + } + + point->x[pos] = x; + point->y[pos] = y; + point->pos = pos+1; + + is_dirty=true; +} + +void GFX_BouncePoints(struct Tracker_Windows *window){ + int color; + int bright; + + if(is_dirty==false) + return; + + //printf("Bouncing points\n"); + for(color=0;color<16;color++){ + for(bright=0;bright<=MAX_BRIGHTNESS;bright++){ + struct Points *point=points[color][bright]; + if(point!=NULL){ + if(point->pos==1){ + OS_GFX_Point(window,(enum ColorNums)color,bright,point->x[0],point->y[0],PAINT_BUFFER); + //printf("single point %d/%d, %d/%d\n",color,bright,point->x[0],point->y[0]); + point->pos=0; + }else if(point->pos>1){ + OS_GFX_Points(window,(enum ColorNums)color,bright,point->pos,point->x,point->y,PAINT_BUFFER); + //printf("point %d/%d, %d/%d\n",color,bright,point->x[0],point->y[0]); + point->pos=0; + } + } + } + } + + is_dirty=false; +} + diff --git a/pool/shard006/C/0118028_prereq_domain.c b/pool/shard006/C/0118028_prereq_domain.c new file mode 100644 index 0000000000000000000000000000000000000000..e02d7d43f47b1f20146aec468de1265def163fc6 --- /dev/null +++ b/pool/shard006/C/0118028_prereq_domain.c @@ -0,0 +1,138 @@ +/* + Unix SMB/CIFS implementation. + + Copyright (C) Rafal Szczesniak 2006 + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + + +#include "includes.h" +#include "libnet/libnet.h" +#include "libcli/composite/composite.h" +#include "auth/credentials/credentials.h" +#include "librpc/ndr/libndr.h" +#include "librpc/gen_ndr/samr.h" +#include "librpc/gen_ndr/ndr_samr.h" +#include "librpc/gen_ndr/lsa.h" +#include "librpc/gen_ndr/ndr_lsa.h" + + +struct composite_context* samr_domain_opened(struct libnet_context *ctx, + const char *domain_name, + struct composite_context *parent_ctx, + struct libnet_DomainOpen *domain_open, + void (*continue_fn)(struct composite_context*), + void (*monitor)(struct monitor_msg*)) +{ + struct composite_context *domopen_req; + + if (domain_name == NULL) { + /* + * Try to guess the domain name from credentials, + * if it's not been explicitly specified. + */ + + if (policy_handle_empty(&ctx->samr.handle)) { + domain_open->in.type = DOMAIN_SAMR; + domain_open->in.domain_name = cli_credentials_get_domain(ctx->cred); + domain_open->in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; + + } else { + composite_error(parent_ctx, NT_STATUS_INVALID_PARAMETER); + return parent_ctx; + } + + } else { + /* + * The domain name has been specified, so check whether the same + * domain is already opened. If it is - just return NULL. Start + * opening a new domain otherwise. + */ + + if (policy_handle_empty(&ctx->samr.handle) || + !strequal(domain_name, ctx->samr.name)) { + domain_open->in.type = DOMAIN_SAMR; + domain_open->in.domain_name = domain_name; + domain_open->in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; + + } else { + /* domain has already been opened and it's the same domain + as requested */ + return NULL; + } + } + + /* send request to open the domain */ + domopen_req = libnet_DomainOpen_send(ctx, domain_open, monitor); + if (composite_nomem(domopen_req, parent_ctx)) return parent_ctx; + + composite_continue(parent_ctx, domopen_req, continue_fn, parent_ctx); + return parent_ctx; +} + + +struct composite_context* lsa_domain_opened(struct libnet_context *ctx, + const char *domain_name, + struct composite_context *parent_ctx, + struct libnet_DomainOpen *domain_open, + void (*continue_fn)(struct composite_context*), + void (*monitor)(struct monitor_msg*)) +{ + struct composite_context *domopen_req; + + if (domain_name == NULL) { + /* + * Try to guess the domain name from credentials, + * if it's not been explicitly specified. + */ + + if (policy_handle_empty(&ctx->lsa.handle)) { + domain_open->in.type = DOMAIN_LSA; + domain_open->in.domain_name = cli_credentials_get_domain(ctx->cred); + domain_open->in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; + + } else { + composite_error(parent_ctx, NT_STATUS_INVALID_PARAMETER); + return parent_ctx; + } + + } else { + /* + * The domain name has been specified, so check whether the same + * domain is already opened. If it is - just return NULL. Start + * opening a new domain otherwise. + */ + + if (policy_handle_empty(&ctx->lsa.handle) || + !strequal(domain_name, ctx->lsa.name)) { + domain_open->in.type = DOMAIN_LSA; + domain_open->in.domain_name = domain_name; + domain_open->in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED; + + } else { + /* domain has already been opened and it's the same domain + as requested */ + return NULL; + } + } + + /* send request to open the domain */ + domopen_req = libnet_DomainOpen_send(ctx, domain_open, monitor); + if (composite_nomem(domopen_req, parent_ctx)) return parent_ctx; + + composite_continue(parent_ctx, domopen_req, continue_fn, parent_ctx); + return parent_ctx; +} diff --git a/pool/shard006/C/0118031_msg_dps.c b/pool/shard006/C/0118031_msg_dps.c new file mode 100644 index 0000000000000000000000000000000000000000..7e2f63223d8f8789441e2d368417ad1cf2006562 --- /dev/null +++ b/pool/shard006/C/0118031_msg_dps.c @@ -0,0 +1,92 @@ +/* $Id$ + + Display a STRING + + This file bases on MESSAGES.C of FreeCOM v0.81 beta 1. + + $Log$ + Revision 1.4 2006/06/11 02:47:05 blairdude + Optimized FreeCOM for size, fixed LFN bugs, and started an int 2e handler (which safely fails at the moment) + + Revision 1.3 2004/02/01 13:52:17 skaus + add/upd: CVS $id$ keywords to/of files + + Revision 1.2 2001/04/29 11:33:51 skaus + chg: default heap size (tools\ptchsize) set to 6KB + chg: error displaying functions centralized into lib\err_fcts.src + add: displayError() + chg: all errors are displayed through functions void error_*() + bugfix: somtimes error messages are not displayed (see displayError()) + bugfix: docommand(): type:file must pass ":file" to TYPE + bugfix: error_sfile(): string _SFILE_ + bugfix: error message on empty redirection + bugfix: comma and semicolon ';' are recognized as argument seperators + of internal commands + + Revision 1.1 2001/04/12 00:33:53 skaus + chg: new structure + chg: If DEBUG enabled, no available commands are displayed on startup + fix: PTCHSIZE also patches min extra size to force to have this amount + of memory available on start + bugfix: CALL doesn't reset options + add: PTCHSIZE to patch heap size + add: VSPAWN, /SWAP switch, .SWP resource handling + bugfix: COMMAND.COM A:\ + bugfix: CALL: if swapOnExec == ERROR, no change of swapOnExec allowed + add: command MEMORY + bugfix: runExtension(): destroys command[-2] + add: clean.bat + add: localized CRITER strings + chg: use LNG files for hard-coded strings (hangForEver(), init.c) + via STRINGS.LIB + add: DEL.C, COPY.C, CBREAK.C: STRINGS-based prompts + add: fixstrs.c: prompts & symbolic keys + add: fixstrs.c: backslash escape sequences + add: version IDs to DEFAULT.LNG and validation to FIXSTRS.C + chg: splitted code apart into LIB\*.c and CMD\*.c + bugfix: IF is now using error system & STRINGS to report errors + add: CALL: /N + + */ + +#include "../config.h" + +#include +#include +#include +#include + +#include "../include/misc.h" + +#ifdef DEBUG +FILE *errStream = 0; +#else +/* static FILE *errStream = 0; */ +#endif + +static void displayXString(FILE *stream, unsigned id, va_list args) +{ char *str; + + if((str = getString(id)) != 0) { + vfprintf(stream, str, args); + free(str); + } +} +void displayString(unsigned id,...) +{ va_list ap; + + va_start(ap, id); + displayXString(outStream, id, ap); + va_end(ap); +} +void displayError(unsigned id,...) +{ va_list ap; + + va_start(ap, id); +#ifdef DEBUG + displayXString(errStream? errStream: stderr, id, ap); +#else + displayXString( stderr, id, ap ); +#endif + va_end(ap); +} diff --git a/pool/shard006/C/0118033_demo.c b/pool/shard006/C/0118033_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..a83df2da7c3a44e3fd02938b40bc59be478395fd --- /dev/null +++ b/pool/shard006/C/0118033_demo.c @@ -0,0 +1,130 @@ + +// demo.c + +#include +#include +#include +#include +#include +#include + +#define XK_MISCELLANY +#define XK_LATIN1 +#include + +#include "demo.h" + +#define MILLION (1000 * 1000) +#define BILLION (1000 * 1000 * 1000) + +static inline struct timespec timespec_diff(struct timespec ts1, + struct timespec ts2) { + register struct timespec result; + register long sec; + + if(ts1.tv_sec > ts2.tv_sec) { + result.tv_nsec = ts1.tv_nsec + (ts1.tv_sec - ts2.tv_sec) * BILLION; + result.tv_sec = ts2.tv_sec; + } else { + result.tv_nsec = ts1.tv_nsec; + result.tv_sec = ts1.tv_sec; + } + result.tv_nsec -= ts2.tv_nsec; + result.tv_sec -= ts2.tv_sec; + + if(result.tv_nsec >= BILLION) { + result.tv_nsec %= BILLION; + result.tv_sec += result.tv_nsec / BILLION; + } + if(result.tv_nsec < 0) { + sec = 1 + -(result.tv_nsec / BILLION); + result.tv_nsec += BILLION * sec; + result.tv_sec -= sec; + } + return result; +} + +static inline void demo_event(struct demo *d) { + XEvent ev; + KeySym keysym; + if(XNextEvent(d->x.disp, &ev)) + return; + if(ev.type == KeyPress) { + keysym = XkbKeycodeToKeysym(d->x.disp, ev.xkey.keycode, 0, 0); + if(keysym == XK_q || keysym == XK_Escape) + d->running = false; + } +} + +static inline int demo_select(struct demo *d) { + fd_set fds; + register int sel, fd = ConnectionNumber(d->x.disp); + struct timespec frame_end; +again: + FD_ZERO(&fds); + FD_SET(fd, &fds); + if(clock_gettime(CLOCK_MONOTONIC, &frame_end) < 0) { + fprintf(stderr, "Error: clock_dettime()\n"); + return -1; + } + + frame_end = timespec_diff(frame_end, d->frame_start); + if(d->frames.max_wait.tv_sec < frame_end.tv_sec + || (d->frames.max_wait.tv_sec == frame_end.tv_sec + && d->frames.max_wait.tv_nsec < frame_end.tv_nsec)) + d->frames.max_wait = frame_end; + frame_end = timespec_diff((struct timespec){ 0, 50 * MILLION }, frame_end); + if(frame_end.tv_sec < 0) { + d->frames.missed++; + return 0; + } + + sel = pselect(fd + 1, &fds, NULL, NULL, &frame_end, NULL); + if(sel < 0) { + if(errno == EINTR) + goto again; + return -1; + } + return 0; +} + +int demo_init(struct demo *d) { + if(xbp_connect(&d->x, NULL) < 0) + return -1; + xbp_getfullscreenwin(&d->x, &d->w); + xbp_cursorinvisible(&d->x, &d->w); + d->frames.missed = 0; + d->frames.max_wait.tv_sec = 0; + d->frames.max_wait.tv_nsec = 0; + d->running = true; + return 0; +} + +int demo_main(struct demo *d, int (*update_cb)(struct demo*, void*), + void *data) { + XGrabKeyboard(d->x.disp, d->w.win, 0, GrabModeAsync, GrabModeAsync, + CurrentTime); + while(d->running) { + if(clock_gettime(CLOCK_MONOTONIC, &d->frame_start) < 0) { + fprintf(stderr, "Error: clock_gettime()\n"); + return -1; + } + if(update_cb(d, data) < 0) + return -1; + XFlush(d->x.disp); + if(demo_select(d) < 0) + return -1; + while(XPending(d->x.disp) > 0) + demo_event(d); + } + XUngrabKeyboard(d->x.disp, CurrentTime); + fprintf(stderr, "Missed: %"PRIuMAX"\n", d->frames.missed); + fprintf(stderr, "Max frame time: %ld.%09ld\n", + d->frames.max_wait.tv_sec, d->frames.max_wait.tv_nsec); + return 0; +} + +void demo_cleanup(struct demo *d) { + xbp_destroywin(&d->x, &d->w); + xbp_disconnect(&d->x); +} diff --git a/pool/shard006/C/0118038_disfp.c b/pool/shard006/C/0118038_disfp.c new file mode 100644 index 0000000000000000000000000000000000000000..a3c93831afb4ebc6deef303621741965d61f467a --- /dev/null +++ b/pool/shard006/C/0118038_disfp.c @@ -0,0 +1,157 @@ +static char *sccsid = + "@(#) disfp.c, Ver. 2.1 created 00:00:00 87/09/01"; + + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * Copyright (C) 1987 G. M. Harding, all rights reserved * + * * + * Permission to copy and redistribute is hereby granted, * + * provided full source code, with all copyright notices, * + * accompanies any redistribution. * + * * + * This file contains handler routines for the numeric op- * + * codes of the 8087 co-processor, as well as a few other * + * opcodes which are related to 8087 emulation. * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "dis.h" /* Disassembler declarations */ + +#define FPINT0 0xd8 /* Floating-point interrupts */ +#define FPINT1 0xd9 +#define FPINT2 0xda +#define FPINT3 0xdb +#define FPINT4 0xdc +#define FPINT5 0xdd +#define FPINT6 0xde +#define FPINT7 0xdf + + /* Test for floating opcodes */ +#define ISFLOP(x) \ + (((x) >= FPINT0) && ((x) <= FPINT7)) + + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * This is the handler for the escape family of opcodes. * + * These opcodes place the contents of a specified memory * + * location on the system bus, for access by a peripheral * + * or by a co-processor such as the 8087. (The 8087 NDP is * + * accessed only via bus escapes.) Due to a bug in the * + * PC/IX assembler, the "esc" mnemonic is not recognized; * + * consequently, escape opcodes are disassembled as .byte * + * directives, with the appropriate mnemonic and operand * + * included as a comment. FOR NOW, those escape sequences * + * corresponding to 8087 opcodes are treated as simple * + * escapes. * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +void +eshand(j) + + register int j; /* Pointer to optab[] entry */ + +{/* * * * * * * * * * START OF eshand() * * * * * * * * * */ + + register char *a; + register int k; + + objini(j); + + FETCH(k); + + a = mtrans((j & 0xfd),(k & 0xc7),TR_STD); + + mtrunc(a); + + printf("\t.byte\t0x%02.2x\t\t| esc\t%s\n",j,a); + + for (k = 1; k < objptr; ++k) + printf("\t.byte\t0x%02.2x\n",objbuf[k]); + +}/* * * * * * * * * * * END OF eshand() * * * * * * * * * * */ + + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * This is the handler routine for floating-point opcodes. * + * Since PC/IX must accommodate systems with and without * + * 8087 co-processors, it allows floating-point operations * + * to be initiated in either of two ways: by a software * + * interrput whose type is in the range 0xd8 through 0xdf, * + * or by a CPU escape sequence, which is invoked by an op- * + * code in the same range. In either case, the subsequent * + * byte determines the actual numeric operation to be per- * + * formed. However, depending on the method of access, * + * either one or two code bytes will precede that byte, * + * and the fphand() routine has no way of knowing whether * + * it was invoked by interrupt or by an escape sequence. * + * Therefore, unlike all of the other handler routines ex- * + * cept dfhand(), fphand() does not initialize the object * + * buffer, leaving that chore to the caller. * + * * + * FOR NOW, fphand() does not disassemble floating-point * + * opcodes to floating mnemonics, but simply outputs the * + * object code as .byte directives. * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +void +fphand(j) + + register int j; /* Pointer to optab[] entry */ + +{/* * * * * * * * * * START OF fphand() * * * * * * * * * */ + + register int k; + + segflg = 0; + + FETCH(k); + + printf("\t.byte\t0x%02.2x\t\t| 8087 code sequence\n", + objbuf[0]); + + for (k = 1; k < objptr; ++k) + printf("\t.byte\t0x%02.2x\n",objbuf[k]); + +/* objout(); FOR NOW */ + +}/* * * * * * * * * * * END OF fphand() * * * * * * * * * * */ + + /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * * + * This is the handler for variable software interrupt * + * opcodes. It is included in this file because PC/IX im- * + * plements its software floating-point emulation by means * + * of interrupts. Any interrupt in the range 0xd8 through * + * 0xdf is an NDP-emulation interrupt, and is specially * + * handled by the assembler. * + * * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +void +inhand(j) + + register int j; /* Pointer to optab[] entry */ + +{/* * * * * * * * * * START OF inhand() * * * * * * * * * */ + + register int k; + + objini(j); + + FETCH(k); + + if (ISFLOP(k)) + { + fphand(k); + return; + } + + printf("%s\t%d\n",optab[j].text,k); + + objout(); + +}/* * * * * * * * * * * END OF inhand() * * * * * * * * * * */ + + diff --git a/pool/shard006/C/0118044_test.c b/pool/shard006/C/0118044_test.c new file mode 100644 index 0000000000000000000000000000000000000000..22e8dbbb519fe7c44886c9f43dbde933335e519d --- /dev/null +++ b/pool/shard006/C/0118044_test.c @@ -0,0 +1,188 @@ + +#include +#include + +#define JC_TEST_IMPLEMENTATION +#include "jc_test.h" + +#define JC_INI_IMPLEMENTATION +#include "../src/jc_ini.h" + +#define JC_IMAGEFILTERS_IMPLEMENTATION +#include "../src/jc_imagefilters.h" + +static void* test_fixture_setup() +{ + return 0; +} + +static void test_fixture_teardown() +{ +} + +static void test_setup() +{ +} + +static void test_teardown() +{ +} + +static void test_getline() +{ + const char* path = "getline.txt"; + FILE* f = fopen(path, "wb"); + ASSERT_TRUE( f != 0 ); + + // line 1 + for( int i = 0; i < 32; ++i) + fputc('A' + i%25, f); + fputc('\n', f); + + // line 2 + for( int i = 0; i < (BUFSIZ*3)/2; ++i) + fputc('A' + i%25, f); + fputc('\n', f); + + fclose(f); + + // + + size_t size = 16; + char* line = (char*)malloc(size); + + f = fopen("getline.txt", "rb"); + ASSERT_TRUE( f != 0 ); + + line = jc_ini_getline(f, &size, line); + + size_t linesize = 32; + ASSERT_EQ( linesize+1, strlen(line) ); + for( int i = 0; i < (int)linesize; ++i) + { + ASSERT_EQ( 'A' + i%25, line[i] ); + } + ASSERT_EQ( '\n', line[linesize] ); + + + line = jc_ini_getline(f, &size, line); + + linesize = (BUFSIZ*3)/2; + ASSERT_EQ( linesize+1, strlen(line) ); + for( int i = 0; i < (int)linesize; ++i) + { + ASSERT_EQ( 'A' + i%25, line[i] ); + } + ASSERT_EQ( '\n', line[linesize] ); + + fclose(f); + + free(line); + + unlink(path); +} + +static void Write(const char* str, FILE* f) +{ + size_t len = strlen(str); + fwrite(str, 1, len, f); +} + + +static void load_handler1(const char* section, const char* key, const char* value, void* ctx) +{ + int* num_ok = (int*)ctx; + + //printf("HANDLER: '%s' '%s' '%s'\n", section ? section : "null", key ? key : "null", value ? value : "null"); + +#define MATCH_PTR(_EXPECTED, _PTR) \ + if( ((_EXPECTED) == (_PTR)) || ((_EXPECTED) && (_PTR) && strcmp(_EXPECTED, _PTR) == 0) ) matches++; + +#define VERIFY_SKV(_S, _K, _V) \ + { \ + int matches = 0; \ + MATCH_PTR( _S, section ); \ + MATCH_PTR( _K, key ); \ + MATCH_PTR( _V, value ); \ + if( matches == 3 ) (*num_ok)++; \ + } + + VERIFY_SKV(0, "a", "1"); + VERIFY_SKV(0, "b", "2"); + VERIFY_SKV(0, "a", "2"); + VERIFY_SKV("section 1", "c", "\"text\""); + VERIFY_SKV("section 1", "d", "[1,2,3]"); + VERIFY_SKV("section 2", "e", "10"); + VERIFY_SKV("section 2", "f", "11"); + VERIFY_SKV("section 2", "g", ""); + +#undef VERIFY_SKV + +} + +static void test_load_ini_ok() +{ + const char* path = "test.cfg"; + FILE* f = fopen(path, "wb"); + ASSERT_TRUE( f != 0 ); + Write("; comment 1\n", f); + Write("# comment 2\n", f); + Write(" ; comment 3\n", f); + Write("a = 1\n", f); + Write("b = 2\n", f); + Write("a = 2\n", f); + Write("\n", f); + Write("[section 1]\n", f); + Write("c=\"text\"\n", f); + Write("d = [1,2,3]\n", f); + Write("\n", f); + Write("[section 2] ; comment\n", f); + Write("e = 10 ; comment\n", f); + Write(" f = 11 ; indentation\n", f); + Write("g =\n", f); + fclose(f); + + // + int num_ok = 0; + int result = jc_ini_parse_from_path(path, load_handler1, &num_ok); + ASSERT_EQ( 0, result ); + ASSERT_EQ( 8, num_ok ); + + unlink(path); +} + + +static void test_map_curve() +{ + uint8_t pts[] = { 25, 50, 150, 250 }; + uint32_t npoints = sizeof(pts)/sizeof(pts[0]); + + int value = 0; + value = (int)(jc_if_apply_curve_value(pts, npoints, 0)); + + printf("\nV: %u\n", value); + ASSERT_EQ( 25, value ); + + printf("\n"); + + value = (int)(jc_if_apply_curve_value(pts, npoints, 128)); + + printf("\nV: %u\n", value); + ASSERT_EQ( 100, value ); + + printf("\n"); +} + +TEST_BEGIN(ImageFilters, test_fixture_setup, test_fixture_teardown, test_setup, test_teardown) + TEST(test_getline) + TEST(test_load_ini_ok) + TEST(test_map_curve) +TEST_END(ImageFilters) + + +int main(int argc, const char** argv) +{ + (void)argc; + (void)argv; + return TEST_RUN_ALL(); +} diff --git a/pool/shard006/C/0118050_directory_win.c b/pool/shard006/C/0118050_directory_win.c new file mode 100644 index 0000000000000000000000000000000000000000..4ebacf2165d1f99c2ffa2c4e397e0e75e542e277 --- /dev/null +++ b/pool/shard006/C/0118050_directory_win.c @@ -0,0 +1,144 @@ +/* $LP: LPlib/source/LPdir_win.c,v 1.10 2004/08/26 13:36:05 _cvs_levitte Exp $ */ +/* + * Copyright (c) 2004, Richard Levitte + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE 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 "directory.h" + + +#if defined(OPENSSL_WINDOWS) + +#pragma warning(push, 3) +#include +#pragma warning(pop) +#include +#include +#include + +#ifndef NAME_MAX +#define NAME_MAX 255 +#endif + +#include + + +struct OPENSSL_dir_context_st { + WIN32_FIND_DATA ctx; + HANDLE handle; + char entry_name[NAME_MAX + 1]; +}; + +const char *OPENSSL_DIR_read(OPENSSL_DIR_CTX **ctx, const char *directory) { + if (ctx == NULL || directory == NULL) { + errno = EINVAL; + return 0; + } + + errno = 0; + if (*ctx == NULL) { + *ctx = malloc(sizeof(OPENSSL_DIR_CTX)); + if (*ctx == NULL) { + errno = ENOMEM; + return 0; + } + memset(*ctx, 0, sizeof(OPENSSL_DIR_CTX)); + + if (sizeof(TCHAR) != sizeof(char)) { + TCHAR *wdir = NULL; + /* len_0 denotes string length *with* trailing 0 */ + size_t index = 0, len_0 = strlen(directory) + 1; + + wdir = (TCHAR *)malloc(len_0 * sizeof(TCHAR)); + if (wdir == NULL) { + free(*ctx); + *ctx = NULL; + errno = ENOMEM; + return 0; + } + + if (!MultiByteToWideChar(CP_ACP, 0, directory, len_0, (WCHAR *)wdir, + len_0)) { + for (index = 0; index < len_0; index++) { + wdir[index] = (TCHAR)directory[index]; + } + } + + (*ctx)->handle = FindFirstFile(wdir, &(*ctx)->ctx); + + free(wdir); + } else { + (*ctx)->handle = FindFirstFile((TCHAR *)directory, &(*ctx)->ctx); + } + + if ((*ctx)->handle == INVALID_HANDLE_VALUE) { + free(*ctx); + *ctx = NULL; + errno = EINVAL; + return 0; + } + } else { + if (FindNextFile((*ctx)->handle, &(*ctx)->ctx) == FALSE) { + return 0; + } + } + + if (sizeof(TCHAR) != sizeof(char)) { + TCHAR *wdir = (*ctx)->ctx.cFileName; + size_t index, len_0 = 0; + + while (wdir[len_0] && len_0 < (sizeof((*ctx)->entry_name) - 1)) { + len_0++; + } + len_0++; + + if (!WideCharToMultiByte(CP_ACP, 0, (WCHAR *)wdir, len_0, + (*ctx)->entry_name, sizeof((*ctx)->entry_name), + NULL, 0)) { + for (index = 0; index < len_0; index++) { + (*ctx)->entry_name[index] = (char)wdir[index]; + } + } + } else { + strncpy((*ctx)->entry_name, (const char *)(*ctx)->ctx.cFileName, + sizeof((*ctx)->entry_name) - 1); + } + + (*ctx)->entry_name[sizeof((*ctx)->entry_name) - 1] = '\0'; + + return (*ctx)->entry_name; +} + +int OPENSSL_DIR_end(OPENSSL_DIR_CTX **ctx) { + if (ctx != NULL && *ctx != NULL) { + FindClose((*ctx)->handle); + free(*ctx); + *ctx = NULL; + return 1; + } + errno = EINVAL; + return 0; +} + +#endif /* OPENSSL_WINDOWS */ diff --git a/pool/shard006/C/0118054_win32.c b/pool/shard006/C/0118054_win32.c new file mode 100644 index 0000000000000000000000000000000000000000..e83e648807ed27b5b8540fd310ecb9cd62e89584 --- /dev/null +++ b/pool/shard006/C/0118054_win32.c @@ -0,0 +1,128 @@ +/* + * PROJECT: Kernel + * LICENSE: GPL - See COPYING in the top level directory + * FILE: ntoskrnl/ps/win32.c + * PURPOSE: Process Manager: Win32K Initialization and Support + * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org) + */ + +/* INCLUDES ****************************************************************/ + +#include +#include +#define NDEBUG +#include + +/* GLOBALS ******************************************************************/ + +PKWIN32_PROCESS_CALLOUT PspW32ProcessCallout = NULL; +PKWIN32_THREAD_CALLOUT PspW32ThreadCallout = NULL; +PGDI_BATCHFLUSH_ROUTINE KeGdiFlushUserBatch = NULL; +extern PKWIN32_SESSION_CALLOUT ExpWindowStationObjectParse; +extern PKWIN32_SESSION_CALLOUT ExpWindowStationObjectDelete; +extern PKWIN32_SESSION_CALLOUT ExpWindowStationObjectOkToClose; +extern PKWIN32_SESSION_CALLOUT ExpDesktopObjectOkToClose; +extern PKWIN32_SESSION_CALLOUT ExpDesktopObjectDelete; +extern PKWIN32_SESSION_CALLOUT ExpDesktopObjectOpen; +extern PKWIN32_SESSION_CALLOUT ExpDesktopObjectClose; +extern PKWIN32_POWEREVENT_CALLOUT PopEventCallout; + +/* PRIVATE FUNCTIONS *********************************************************/ + +NTSTATUS +NTAPI +PsConvertToGuiThread(VOID) +{ + ULONG_PTR NewStack; + PVOID OldStack; + PETHREAD Thread = PsGetCurrentThread(); + PEPROCESS Process = PsGetCurrentProcess(); + NTSTATUS Status; + PAGED_CODE(); + + /* Validate the previous mode */ + if (KeGetPreviousMode() == KernelMode) return STATUS_INVALID_PARAMETER; + + /* If no win32k, crashes later */ + ASSERT(PspW32ProcessCallout != NULL); + + /* Make sure win32k is here */ + if (!PspW32ProcessCallout) return STATUS_ACCESS_DENIED; + + /* Make sure it's not already win32 */ + if (Thread->Tcb.ServiceTable != KeServiceDescriptorTable) + { + /* We're already a win32 thread */ + return STATUS_ALREADY_WIN32; + } + + /* Check if we don't already have a kernel-mode stack */ + if (!Thread->Tcb.LargeStack) + { + /* We don't create one */ + NewStack = (ULONG_PTR)MmCreateKernelStack(TRUE, 0); + if (!NewStack) + { + /* Panic in user-mode */ + NtCurrentTeb()->LastErrorValue = ERROR_NOT_ENOUGH_MEMORY; + return STATUS_NO_MEMORY; + } + + /* We're about to switch stacks. Enter a guarded region */ + KeEnterGuardedRegion(); + + /* Switch stacks */ + OldStack = KeSwitchKernelStack((PVOID)NewStack, + (PVOID)(NewStack - KERNEL_STACK_SIZE)); + + /* Leave the guarded region */ + KeLeaveGuardedRegion(); + + /* Delete the old stack */ + MmDeleteKernelStack(OldStack, FALSE); + } + + /* Always do the process callout! */ + Status = PspW32ProcessCallout(Process, TRUE); + if (!NT_SUCCESS(Status)) return Status; + + /* Set the new service table */ + Thread->Tcb.ServiceTable = KeServiceDescriptorTableShadow; + ASSERT(Thread->Tcb.Win32Thread == 0); + + /* Tell Win32k about our thread */ + Status = PspW32ThreadCallout(Thread, PsW32ThreadCalloutInitialize); + if (!NT_SUCCESS(Status)) + { + /* Revert our table */ + Thread->Tcb.ServiceTable = KeServiceDescriptorTable; + } + + /* Return status */ + return Status; +} + +/* PUBLIC FUNCTIONS **********************************************************/ + +/* + * @implemented + */ +VOID +NTAPI +PsEstablishWin32Callouts(IN PWIN32_CALLOUTS_FPNS CalloutData) +{ + /* Setup the callback pointers */ + PspW32ProcessCallout = CalloutData->ProcessCallout; + PspW32ThreadCallout = CalloutData->ThreadCallout; + ExpWindowStationObjectParse = CalloutData->WindowStationParseProcedure; + ExpWindowStationObjectDelete = CalloutData->WindowStationDeleteProcedure; + ExpWindowStationObjectOkToClose = CalloutData->WindowStationOkToCloseProcedure; + ExpDesktopObjectOkToClose = CalloutData->DesktopOkToCloseProcedure; + ExpDesktopObjectDelete = CalloutData->DesktopDeleteProcedure; + ExpDesktopObjectOpen = CalloutData->DesktopOpenProcedure; + ExpDesktopObjectClose = CalloutData->DesktopCloseProcedure; + PopEventCallout = CalloutData->PowerEventCallout; + KeGdiFlushUserBatch = CalloutData->BatchFlushRoutine; +} + +/* EOF */ diff --git a/pool/shard006/C/0118056_ll_map.c b/pool/shard006/C/0118056_ll_map.c new file mode 100644 index 0000000000000000000000000000000000000000..e9ae129611e581faa12f37ae9bbd59ea95ddf9d8 --- /dev/null +++ b/pool/shard006/C/0118056_ll_map.c @@ -0,0 +1,180 @@ +/* + * ll_map.c + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + * Authors: Alexey Kuznetsov, + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "libnetlink.h" +#include "ll_map.h" + +struct ll_cache +{ + struct ll_cache *idx_next; + unsigned flags; + int index; + unsigned short type; + char name[IFNAMSIZ]; +}; + +#define IDXMAP_SIZE 1024 +static struct ll_cache *idx_head[IDXMAP_SIZE]; + +static inline struct ll_cache *idxhead(int idx) +{ + return idx_head[idx & (IDXMAP_SIZE - 1)]; +} + +int ll_remember_index(const struct sockaddr_nl *who, + struct nlmsghdr *n, void *arg) +{ + int h; + struct ifinfomsg *ifi = NLMSG_DATA(n); + struct ll_cache *im, **imp; + struct rtattr *tb[IFLA_MAX+1]; + + if (n->nlmsg_type != RTM_NEWLINK) + return 0; + + if (n->nlmsg_len < NLMSG_LENGTH(sizeof(ifi))) + return -1; + + memset(tb, 0, sizeof(tb)); + parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n)); + if (tb[IFLA_IFNAME] == NULL) + return 0; + + h = ifi->ifi_index & (IDXMAP_SIZE - 1); + for (imp = &idx_head[h]; (im=*imp)!=NULL; imp = &im->idx_next) + if (im->index == ifi->ifi_index) + break; + + if (im == NULL) { + im = malloc(sizeof(*im)); + if (im == NULL) + return 0; + im->idx_next = *imp; + im->index = ifi->ifi_index; + *imp = im; + } + + im->type = ifi->ifi_type; + im->flags = ifi->ifi_flags; + strcpy(im->name, RTA_DATA(tb[IFLA_IFNAME])); + return 0; +} + +const char *ll_idx_n2a(unsigned idx, char *buf) +{ + const struct ll_cache *im; + + if (idx == 0) + return "*"; + + for (im = idxhead(idx); im; im = im->idx_next) + if (im->index == idx) + return im->name; + + snprintf(buf, IFNAMSIZ, "if%d", idx); + return buf; +} + + +const char *ll_index_to_name(unsigned idx) +{ + static char nbuf[IFNAMSIZ]; + + return ll_idx_n2a(idx, nbuf); +} + +int ll_index_to_type(unsigned idx) +{ + const struct ll_cache *im; + + if (idx == 0) + return -1; + for (im = idxhead(idx); im; im = im->idx_next) + if (im->index == idx) + return im->type; + return -1; +} + +unsigned ll_index_to_flags(unsigned idx) +{ + const struct ll_cache *im; + + if (idx == 0) + return 0; + + for (im = idxhead(idx); im; im = im->idx_next) + if (im->index == idx) + return im->flags; + return 0; +} + +unsigned ll_name_to_index(const char *name) +{ + static char ncache[IFNAMSIZ]; + static int icache; + struct ll_cache *im; + int i; + unsigned idx; + + if (name == NULL) + return 0; + + if (icache && strcmp(name, ncache) == 0) + return icache; + + for (i=0; iidx_next) { + if (strcmp(im->name, name) == 0) { + icache = im->index; + strcpy(ncache, name); + return im->index; + } + } + } + + idx = if_nametoindex(name); + if (idx == 0) + sscanf(name, "if%u", &idx); + return idx; +} + +int ll_init_map(struct rtnl_handle *rth) +{ + static int initialized; + + if (initialized) + return 0; + + if (rtnl_wilddump_request(rth, AF_UNSPEC, RTM_GETLINK) < 0) { + perror("Cannot send dump request"); + exit(1); + } + + if (rtnl_dump_filter(rth, ll_remember_index, NULL) < 0) { + fprintf(stderr, "Dump terminated\n"); + exit(1); + } + + initialized = 1; + + return 0; +} diff --git a/pool/shard006/C/0118057_sk_palloc.c b/pool/shard006/C/0118057_sk_palloc.c new file mode 100644 index 0000000000000000000000000000000000000000..8dc320401990e878b201d357e14a2484f91ce33c --- /dev/null +++ b/pool/shard006/C/0118057_sk_palloc.c @@ -0,0 +1,208 @@ + +// Copyright (c) 2013 The Silk Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// Written by qingfeng.wang, some source code form snort,nginx. +// http://www.selinuxplus.com frank.wqf@gmail.com +// Thanks to China Standard software Co.,Ltd ; + +#include +#include "sk_config.h" +#include "sk_core.h" + +static void * sk_palloc_block(sk_pool_t *pool,size_t size); + +static void * sk_palloc_large(sk_pool_t *pool,size_t size); + +void * +sk_memalign(size_t alignment,size_t size,sk_log_t *log) +{ + sk_err_t err; + void *p; + err = posix_memalign(&p,alignment,size); + if(err){ + p = NULL; + } + if(p == NULL){ + return NULL; + } + return p; +} + + +sk_pool_t * +sk_create_pool(size_t size,sk_log_t *log) +{ + sk_pool_t *p; + sk_err_t err; + + p = sk_memalign(SK_POOL_ALGINMENT,size,log); + + p->d.last = (u_char *)p +sizeof(sk_pool_t); + p->d.end = (u_char *)p + size; + p->d.next = NULL; + p->d.failed = 0; + + size = size-sizeof(sk_pool_t); + p->max = (size <(4096-1)?size:(4096-1)); + p->current = p; + p->chain = NULL; + p->large = NULL; + p->cleanup = NULL; + p->log = log; + return p; + +} + +void * +sk_palloc(sk_pool_t *pool,size_t size) +{ + u_char *m; + sk_pool_t *p; + + if(size <= pool->max){ + + p = pool->current; + do{ + m = sk_align_ptr(p->d.last,SK_ALIGNMENT); + if((size_t)(p->d.end - m)>= size){ + p->d.last = m + size; + return m; + } + p = p->d.next; + }while(p); + return sk_palloc_block(pool,size); + } + + return sk_palloc_large(pool,size); +} + + +void * +sk_pcalloc(sk_pool_t *pool,size_t size) +{ + void *p; + p = sk_palloc(pool,size); + + if(p){ + sk_memzero(p,size); + } + return p; +} +void * +sk_pnalloc(sk_pool_t *pool,size_t size) +{ + u_char *m; + sk_pool_t *p; + + if(size <= pool->max){ + p = pool->current; + do{ + m = p->d.last; + if((size_t)(p->d.end -m )>= size){ + p->d.last = m + size; + return m; + } + p = p->d.next; + }while(p); + return sk_palloc_block(pool,size); + } + + return sk_palloc_large(pool,size); +} + +static void * +sk_palloc_block(sk_pool_t *pool,size_t size) +{ + u_char *m; + size_t psize; + sk_pool_t *p,*new,*current; + + psize = (size_t)(p->d.end - (u_char *)pool); + + m = sk_memalign(SK_POOL_ALGINMENT,psize,pool->log); + if(m == NULL) return NULL; + + new = (sk_pool_t *)m; + new->d.end = m + size; + new->d.next = NULL; + new->d.failed = 0; + + m += sizeof(sk_pool_data_t); + m = sk_align_ptr(m,SK_ALIGNMENT); + new->d.last = m + size; + + current = pool ->current; + + for(p = current;p->d.next; p = p->d.next){ + if(p->d.failed++ > 4){ + current = p->d.next; + } + } + + p->d.next = new; + pool->current = current ? current:new; + return m; +} + + +static void * +sk_palloc_large(sk_pool_t *pool,size_t size) +{ + void *p; + sk_uptr_t n; + sk_pool_large_t *large; + + p = malloc(size); + if(p == NULL) return NULL; + + n = 0; + + for(large = pool->large;large;large = large->next ){ + if(large->alloc == NULL){ + large->alloc = p; + return p; + } + if(n++ > 3){ + break; + } + } + + large = sk_palloc(pool,sizeof(sk_pool_large_t)); + if(large == NULL){ + free(p); + return NULL; + } + + large->alloc = p; + large->next = pool->large; + pool->large = large; + + return p; +} +/* + * destroy memory pool; + */ +void +sk_destroy_pool(sk_pool_t *pool) +{ + sk_pool_t *p,*n; + sk_pool_large_t *l; + sk_pool_cleanup_t *c; + + for(c= pool->cleanup;c;c=c->next){ + if(c->handler){ + c->handler(c->data); + } + } + for(l = pool->large;l;l=l->next){ + if(l->alloc){ + free(l->alloc); + } + } + + for(p = pool,n=pool->d.next;/*void*/;p=n,n=n->d.next){ + free(p); + if(n == NULL) break; + } +} diff --git a/pool/shard006/C/0118058_apl_aloha_send_rev01.c b/pool/shard006/C/0118058_apl_aloha_send_rev01.c new file mode 100644 index 0000000000000000000000000000000000000000..071c9bdeda434cb998640ed4e2ed5469caba6463 --- /dev/null +++ b/pool/shard006/C/0118058_apl_aloha_send_rev01.c @@ -0,0 +1,336 @@ +/******************************************************************************* + * aloha_send + * This project implements a frame sending node based on TiAloha component. This + * component is in module "svc_nio_aloha". + * + * @state + * - compile passed. tested. released. + * @modified by openwsn on 2010.10.12 + * - complied successfully. The sniffer have received the data successfully + * @modified by Jiang Ridong and ZhangWei(TongJi University) in 2011.04 + * - Revised + ******************************************************************************/ + +#define CONFIG_NAC_RXQUE_CAPACITY 1 +#define CONFIG_NAC_TXQUE_CAPACITY 1 + +#include "apl_foundation.h" +#include "openwsn/hal/hal_mcu.h" +#include "openwsn/hal/hal_configall.h" +#include +#include +#include "openwsn/hal/hal_foundation.h" +#include "openwsn/rtl/rtl_foundation.h" +#include "openwsn/rtl/rtl_frame.h" +#include "openwsn/rtl/rtl_debugio.h" +#include "openwsn/rtl/rtl_ieee802frame154.h" +#include "openwsn/hal/hal_cpu.h" +#include "openwsn/hal/hal_led.h" +#include "openwsn/hal/hal_assert.h" +#include "openwsn/hal/hal_uart.h" +#include "openwsn/hal/hal_cc2520.h" +#include "openwsn/hal/hal_debugio.h" +#include "openwsn/hal/hal_timer.h" +#include "openwsn/svc/svc_nio_acceptor.h" +#include "openwsn/svc/svc_nio_aloha.h" + +#define CONFIG_DEBUG + +#ifdef CONFIG_DEBUG + #define GDEBUG +#endif + +#define CONFIG_ALOHA_PANID 0x0001 +#define CONFIG_ALOHA_LOCAL_ADDRESS 0x01 +#define CONFIG_ALOHA_REMOTE_ADDRESS 0x02 +#define CONFIG_ALOHA_CHANNEL 11 + +#define CONFIG_SENDING_INTERVAL 1000 + +#define MAX_IEEE802FRAME154_SIZE 128 + +#define NAC_SIZE NIOACCEPTOR_HOPESIZE(CONFIG_NAC_RXQUE_CAPACITY,CONFIG_NAC_TXQUE_CAPACITY) + +// Define the states of this application +#define INIT_STATE 0 +#define WAIT_RESPONSE_STATE 1 + +#define VTM_RESOLUTION 5 + +#define UART_ID 1 + +#define CONFIG_MIN_SENDING_INTERVAL 1000 +#define CONFIG_MAX_SENDING_INTERVAL 1000 +#define CONFIG_RESPONSE_TIMEOUT 500 + +typedef struct{ + uintx sendtotal; + uintx recvtotal; + uintx sendlost; + uintx recvlost; +}TiStatistics; + +static TiUartAdapter m_uart; +static TiTimerAdapter m_timer2; +static TiTimerAdapter m_timer3; + +static TiFrameRxTxInterface m_rxtx; +static char m_nacmem[NAC_SIZE]; +static TiAloha m_aloha; +static char m_txbuf[FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE)]; +static char m_rxbuf[FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE)]; +static char m_mactxbuf[FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE)]; +TiCc2520Adapter m_cc; + +static void _aloha_sendnode(void); +static void _init_request( TiFrame * txbuf, uint16 addrfrom, uint16 addrto, uint8 seqid ); +static bool _match( uint16 addrfrom, uint16 addrto, uint8 seqid, TiFrame * response ); + +int main(void) +{ + _aloha_sendnode(); + return 0; +} + +/** + * Periodically sending frames (request frames), and also waiting for their response. + * + * @attention: This application should work with "apl_aloha_echo" together. + */ +void _aloha_sendnode(void) +{ + char * msg = "welcome to aloha sendnode...\r\n"; + TiCc2520Adapter * cc; + TiUartAdapter * uart; + TiFrameRxTxInterface * rxtx; + TiNioAcceptor * nac; + TiAloha * mac; + TiTimerAdapter * timer2; + TiTimerAdapter * timer3; + + TiFrame * txbuf; + TiFrame * rxbuf; + TiFrame *mactxbuf; + + TiStatistics stat; + + uint8 seqid, option,len; + uint8 state; + uint16 sendcount, succeed; + int i; + char * pc; + + memset(&stat, 0x00, sizeof(stat)); + seqid =0; + + // Initialize the hardware. You can observe the LED flash and UART welcome + // string to decide whether the application is started successfully or not. + + target_init(); + led_open(); + led_on( LED_ALL ); + hal_delayms( 500 ); + led_off( LED_ALL ); + + uart = uart_construct((void *)(&m_uart), sizeof(m_uart)); + uart = uart_open(uart, UART_ID, 9600, 8, 1, 0); + rtl_init( uart, (TiFunDebugIoPutChar)uart_putchar, (TiFunDebugIoGetChar)uart_getchar_wait, hal_assert_report ); + dbc_mem( msg, strlen(msg) ); + + // Construct objects on specified memory blocks. This step should be success + // or you may encounter unexpected mistake or behaviors. + + cc = cc2520_construct( (char *)(&m_cc), sizeof(TiCc2520Adapter) ); + nac = nac_construct( &m_nacmem[0], NAC_SIZE ); + mac = aloha_construct( (char *)(&m_aloha), sizeof(TiAloha) ); + timer2 = timer_construct( (void *)(&m_timer2), sizeof(m_timer2) ); + timer3 = timer_construct( (void *)(&m_timer3), sizeof(m_timer3) ); + + + // Initialize the virtual timer 0, 1 and 2. Virtual timer 0 is used by the mac + // component. By default we use hardware timer2 here. But you should be able + // to switch to timer0. + // + // @attention: To avoid timer conflictions. Generally, the RTC timer is often + // used by the osx kernel (not mandatory). + + timer2 = timer_open( timer2, 2, NULL, NULL, 0x00 ); + timer3 = timer_open( timer3, 3, NULL, NULL, 0x00 ); + + cc2520_open( cc, 0, NULL, NULL, 0x00 ); + + rxtx = cc2520_interface( cc, &m_rxtx ); + hal_assert( rxtx != NULL ); + + // Open the mac object for further R/W operation. + + nac = nac_open( nac, rxtx, CONFIG_NAC_RXQUE_CAPACITY, CONFIG_NAC_TXQUE_CAPACITY); + mac = aloha_open( mac, rxtx, nac, CONFIG_ALOHA_CHANNEL, CONFIG_ALOHA_PANID, + CONFIG_ALOHA_LOCAL_ADDRESS,timer2, NULL, NULL, 0x00 ); + + mactxbuf = frame_open( (char*)(&m_mactxbuf), FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE), 0, 0, 0 ); + + mac->txbuf = mactxbuf; + + cc2520_setchannel( cc, CONFIG_ALOHA_CHANNEL ); + cc2520_rxon( cc ); // enable RX mode + cc2520_setpanid( cc, CONFIG_ALOHA_PANID ); // network identifier, seems no use in sniffer mode + cc2520_setshortaddress( cc, CONFIG_ALOHA_LOCAL_ADDRESS ); // in network address, seems no use in sniffer mode + cc2520_enable_autoack( cc ); + //cc2420_enable_addrdecode( cc ); + + txbuf = frame_open( (char*)(&m_txbuf), FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE), 3, 20, 0 ); + rxbuf = frame_open( (char*)(&m_rxbuf), FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE), 3, 20, 0 ); + + sendcount = 0; + succeed = 0; + seqid = 1; + option = 0x01; // request ack + + state = INIT_STATE; + + + timer_setinterval( timer3, 1000, 7999 ); + timer_start( timer3 ); + + while (1) + { + switch (state) + { + case INIT_STATE: + if (timer_expired(timer3)) + { + timer_start( timer3 ); + + _init_request( txbuf, CONFIG_ALOHA_LOCAL_ADDRESS, CONFIG_ALOHA_REMOTE_ADDRESS, seqid ); + if (aloha_send(mac, CONFIG_ALOHA_REMOTE_ADDRESS, txbuf, option) > 0) + { + //seqid ++; + sendcount ++; + state = WAIT_RESPONSE_STATE; + } + seqid ++; + + } + break; + + case WAIT_RESPONSE_STATE: + frame_reset( rxbuf,3,20,0); + len = aloha_recv( mac, rxbuf, 0x00 ); + if (len > 0) + { + if (_match(CONFIG_ALOHA_LOCAL_ADDRESS, CONFIG_ALOHA_REMOTE_ADDRESS, (seqid-1), rxbuf)) + { + succeed ++; + pc = frame_startptr( rxbuf); + for ( i=0;i 0) + { + //seqid ++; + sendcount ++; + state = WAIT_RESPONSE_STATE; + } + seqid ++; + } + break; + } + /* + dbc_string( " seqid = " ); + dbc_putchar( seqid ); + + dbc_string( " total sendcount = " ); + dbc_putchar( sendcount ); + // dbc_n16toa( sendcount ); + + dbc_string( " success count = " ); + dbc_putchar( succeed );*/ + + aloha_evolve( mac, NULL ); + } + + frame_close( txbuf ); + aloha_close( mac ); + cc2520_close( cc ); +} + +void _init_request( TiFrame * txbuf, uint16 addrfrom, uint16 addrto, uint8 seqid ) +{ + char * ptr; + uint8 i; + // todo + //ÒòΪaloha_recv£¨£©º¯ÊýÖеÄskipinner»áʹǰÁ½¸ö×Ö½ÚÇåÁ㣬ËùÒÔÏȽ«Ç°Á½¸ö×Ö½Ú±£ÁôÆðÀ´¡£ + frame_reset( txbuf, 3, 20, 0 ); + ptr = frame_startptr( txbuf ); + + //*ptr ++ = seqid; + + ptr[3] = seqid; + + for (i=4; i < 6; i++)//for (i=4; i +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../variant.h" + +const struct rcba_config_instruction rcba_config[] = { + + /* + * GFX INTA -> PIRQA (MSI) + * D28IP_P1IP PCIE INTA -> PIRQA + * D29IP_E1P EHCI INTA -> PIRQD + * D20IP_XHCI XHCI INTA -> PIRQC (MSI) + * D31IP_SIP SATA INTA -> PIRQF (MSI) + * D31IP_SMIP SMBUS INTB -> PIRQG + * D31IP_TTIP THRT INTC -> PIRQA + * D27IP_ZIP HDA INTA -> PIRQG (MSI) + */ + + /* Device interrupt pin register (board specific) */ + RCBA_SET_REG_32(D31IP, (INTC << D31IP_TTIP) | (NOINT << D31IP_SIP2) | + (INTB << D31IP_SMIP) | (INTA << D31IP_SIP)), + RCBA_SET_REG_32(D29IP, (INTA << D29IP_E1P)), + RCBA_SET_REG_32(D28IP, (INTA << D28IP_P1IP) | (INTC << D28IP_P3IP) | + (INTB << D28IP_P4IP)), + RCBA_SET_REG_32(D27IP, (INTA << D27IP_ZIP)), + RCBA_SET_REG_32(D26IP, (INTA << D26IP_E2P)), + RCBA_SET_REG_32(D22IP, (NOINT << D22IP_MEI1IP)), + RCBA_SET_REG_32(D20IP, (INTA << D20IP_XHCI)), + + /* Device interrupt route registers */ + RCBA_SET_REG_32(D31IR, DIR_ROUTE(PIRQG, PIRQC, PIRQB, PIRQA)),/* LPC */ + RCBA_SET_REG_32(D29IR, DIR_ROUTE(PIRQD, PIRQD, PIRQD, PIRQD)),/* EHCI */ + RCBA_SET_REG_32(D28IR, DIR_ROUTE(PIRQA, PIRQB, PIRQC, PIRQD)),/* PCIE */ + RCBA_SET_REG_32(D27IR, DIR_ROUTE(PIRQG, PIRQG, PIRQG, PIRQG)),/* HDA */ + RCBA_SET_REG_32(D22IR, DIR_ROUTE(PIRQA, PIRQA, PIRQA, PIRQA)),/* ME */ + RCBA_SET_REG_32(D21IR, DIR_ROUTE(PIRQE, PIRQF, PIRQF, PIRQF)),/* SIO */ + RCBA_SET_REG_32(D20IR, DIR_ROUTE(PIRQC, PIRQC, PIRQC, PIRQC)),/* XHCI */ + RCBA_SET_REG_32(D23IR, DIR_ROUTE(PIRQH, PIRQH, PIRQH, PIRQH)),/* SDIO */ + + /* Disable unused devices (board specific) */ + RCBA_RMW_REG_32(FD, ~0, PCH_DISABLE_ALWAYS), + + RCBA_END_CONFIG, +}; + +/* Copy SPD data for on-board memory */ +static void copy_spd(struct pei_data *peid) +{ + const int gpio_vector[] = {13, 9, 47, -1}; + int spd_index = get_gpios(gpio_vector); + char *spd_file; + size_t spd_file_len; + size_t spd_len = sizeof(peid->spd_data[0]); + + printk(BIOS_DEBUG, "SPD index %d\n", spd_index); + spd_file = cbfs_boot_map_with_leak("spd.bin", CBFS_TYPE_SPD, + &spd_file_len); + if (!spd_file) + die("SPD data not found."); + + if (spd_file_len < ((spd_index + 1) * spd_len)) { + printk(BIOS_ERR, "SPD index override to 0 - old hardware?\n"); + spd_index = 0; + } + + if (spd_file_len < spd_len) + die("Missing SPD data."); + + memcpy(peid->spd_data[0], spd_file + (spd_index * spd_len), spd_len); + + /* Limiting to a single dimm for 2GB configuration + * Identified by bit 3 + */ + if (spd_index & 0x4) + peid->dimm_channel1_disabled = 3; + else + memcpy(peid->spd_data[1], + spd_file + (spd_index * spd_len), spd_len); +} + +void variant_romstage_entry(unsigned long bist) +{ + struct pei_data pei_data = { + .pei_version = PEI_VERSION, + .mchbar = (uintptr_t)DEFAULT_MCHBAR, + .dmibar = (uintptr_t)DEFAULT_DMIBAR, + .epbar = DEFAULT_EPBAR, + .pciexbar = CONFIG_MMCONF_BASE_ADDRESS, + .smbusbar = SMBUS_IO_BASE, + .wdbbar = 0x4000000, + .wdbsize = 0x1000, + .hpet_address = HPET_ADDR, + .rcba = (uintptr_t)DEFAULT_RCBA, + .pmbase = DEFAULT_PMBASE, + .gpiobase = DEFAULT_GPIOBASE, + .temp_mmio_base = 0xfed08000, + .system_type = 5, /* ULT */ + .tseg_size = CONFIG_SMM_TSEG_SIZE, + .spd_addresses = { 0xff, 0x00, 0xff, 0x00 }, + .ec_present = 1, + // 0 = leave channel enabled + // 1 = disable dimm 0 on channel + // 2 = disable dimm 1 on channel + // 3 = disable dimm 0+1 on channel + .dimm_channel0_disabled = 2, + .dimm_channel1_disabled = 2, + .max_ddr3_freq = 1600, + .usb_xhci_on_resume = 1, + .usb2_ports = { + /* Length, Enable, OCn#, Location */ + { 0x0040, 1, 0, /* P0: Port A, CN10 */ + USB_PORT_BACK_PANEL }, + { 0x0040, 1, 2, /* P1: Port B, CN11 */ + USB_PORT_BACK_PANEL }, + { 0x0080, 1, USB_OC_PIN_SKIP, /* P2: CCD */ + USB_PORT_INTERNAL }, + { 0x0040, 1, USB_OC_PIN_SKIP, /* P3: BT */ + USB_PORT_MINI_PCIE }, + { 0x0080, 1, USB_OC_PIN_SKIP, /* P4: SD Card */ + USB_PORT_INTERNAL }, + { 0x0040, 1, USB_OC_PIN_SKIP, /* P5: LTE */ + USB_PORT_INTERNAL }, + { 0x0040, 1, USB_OC_PIN_SKIP, /* P6: SIM CARD */ + USB_PORT_FLEX }, + { 0x0000, 0, USB_OC_PIN_SKIP, /* P7: EMPTY */ + USB_PORT_SKIP }, + }, + .usb3_ports = { + /* Enable, OCn# */ + { 1, 0 }, /* P1; Port A, CN10 */ + { 1, 2 }, /* P2; Port B, CN11 */ + { 0, USB_OC_PIN_SKIP }, /* P3; */ + { 0, USB_OC_PIN_SKIP }, /* P4; */ + }, + }; + + struct romstage_params romstage_params = { + .pei_data = &pei_data, + .gpio_map = &mainboard_gpio_map, + .rcba_config = &rcba_config[0], + .bist = bist, + .copy_spd = copy_spd, + }; + + /* Call into the real romstage main with this board's attributes. */ + romstage_common(&romstage_params); +} diff --git a/pool/shard006/C/0118060_hal_eeprom.c b/pool/shard006/C/0118060_hal_eeprom.c new file mode 100644 index 0000000000000000000000000000000000000000..333b237c41ef3f6d2e34a439ae940d4301c56b31 --- /dev/null +++ b/pool/shard006/C/0118060_hal_eeprom.c @@ -0,0 +1,84 @@ +/******************************************************************************* +Copyright (C) 2015 OLogN Technologies AG + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 as + published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*******************************************************************************/ + +#include +#include +#include +#include +#ifdef _MSC_VER +#include +#include +#endif + +#ifndef O_BINARY +#define O_BINARY 0 +#endif + + +// Interface is implemented based on file IO +// File has a standard name + +//FILE* f = NULL; +int efile = -1; +#ifdef _MSC_VER +HANDLE hfile = INVALID_HANDLE_VALUE; +#endif + +bool hal_init_eeprom_access() +{ +// f = fopen( MASTER_SLAVE_BIT == 1 ? "sa-eeprom-master": "sa-eeprom-slave", "rw+b" ); + efile = open( MASTER_SLAVE_BIT == 1 ? "sa-eeprom-master.dat": "sa-eeprom-slave.dat", O_RDWR | O_CREAT | O_BINARY, S_IWRITE | S_IREAD ); +#ifdef _MSC_VER + hfile = (HANDLE) _get_osfhandle (efile); + if ( hfile == INVALID_HANDLE_VALUE ) + return false; +#endif + return efile != -1; +} + +bool hal_eeprom_write( const uint8_t* data, uint16_t size, uint16_t address ) +{ + int res; + res = lseek( efile, address, SEEK_SET); + if ( res == -1 ) + return false; + res = write( efile, data, size ); + if ( res != size ) + return false; + return true; +} + +bool hal_eeprom_read( uint8_t* data, uint16_t size, uint16_t address) +{ + int res; + res = lseek( efile, address, SEEK_SET); + if ( res == -1 ) + return false; + res = read( efile, data, size ); + if ( res != size ) + return false; + return true; +} + +void hal_eeprom_flush() +{ +#ifdef _MSC_VER + FlushFileBuffers(hfile); +#else + fsync( efile ); +#endif +} diff --git a/pool/shard006/C/0118065_dwmac-sunxi.c b/pool/shard006/C/0118065_dwmac-sunxi.c new file mode 100644 index 0000000000000000000000000000000000000000..52b8ed9bd87c2e20707c41ab0eaac247de26afce --- /dev/null +++ b/pool/shard006/C/0118065_dwmac-sunxi.c @@ -0,0 +1,178 @@ +/* + * dwmac-sunxi.c - Allwinner sunxi DWMAC specific glue layer + * + * Copyright (C) 2013 Chen-Yu Tsai + * + * Chen-Yu Tsai + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "stmmac_platform.h" + +struct sunxi_priv_data { + int interface; + int clk_enabled; + struct clk *tx_clk; + struct regulator *regulator; +}; + +#define SUN7I_GMAC_GMII_RGMII_RATE 125000000 +#define SUN7I_GMAC_MII_RATE 25000000 + +static int sun7i_gmac_init(struct platform_device *pdev, void *priv) +{ + struct sunxi_priv_data *gmac = priv; + int ret; + + if (gmac->regulator) { + ret = regulator_enable(gmac->regulator); + if (ret) + return ret; + } + + /* Set GMAC interface port mode + * + * The GMAC TX clock lines are configured by setting the clock + * rate, which then uses the auto-reparenting feature of the + * clock driver, and enabling/disabling the clock. + */ + if (gmac->interface == PHY_INTERFACE_MODE_RGMII) { + clk_set_rate(gmac->tx_clk, SUN7I_GMAC_GMII_RGMII_RATE); + clk_prepare_enable(gmac->tx_clk); + gmac->clk_enabled = 1; + } else { + clk_set_rate(gmac->tx_clk, SUN7I_GMAC_MII_RATE); + clk_prepare(gmac->tx_clk); + } + + return 0; +} + +static void sun7i_gmac_exit(struct platform_device *pdev, void *priv) +{ + struct sunxi_priv_data *gmac = priv; + + if (gmac->clk_enabled) { + clk_disable(gmac->tx_clk); + gmac->clk_enabled = 0; + } + clk_unprepare(gmac->tx_clk); + + if (gmac->regulator) + regulator_disable(gmac->regulator); +} + +static void sun7i_fix_speed(void *priv, unsigned int speed) +{ + struct sunxi_priv_data *gmac = priv; + + /* only GMII mode requires us to reconfigure the clock lines */ + if (gmac->interface != PHY_INTERFACE_MODE_GMII) + return; + + if (gmac->clk_enabled) { + clk_disable(gmac->tx_clk); + gmac->clk_enabled = 0; + } + clk_unprepare(gmac->tx_clk); + + if (speed == 1000) { + clk_set_rate(gmac->tx_clk, SUN7I_GMAC_GMII_RGMII_RATE); + clk_prepare_enable(gmac->tx_clk); + gmac->clk_enabled = 1; + } else { + clk_set_rate(gmac->tx_clk, SUN7I_GMAC_MII_RATE); + clk_prepare(gmac->tx_clk); + } +} + +static int sun7i_gmac_probe(struct platform_device *pdev) +{ + struct plat_stmmacenet_data *plat_dat; + struct stmmac_resources stmmac_res; + struct sunxi_priv_data *gmac; + struct device *dev = &pdev->dev; + int ret; + + ret = stmmac_get_platform_resources(pdev, &stmmac_res); + if (ret) + return ret; + + plat_dat = stmmac_probe_config_dt(pdev, &stmmac_res.mac); + if (IS_ERR(plat_dat)) + return PTR_ERR(plat_dat); + + gmac = devm_kzalloc(dev, sizeof(*gmac), GFP_KERNEL); + if (!gmac) + return -ENOMEM; + + gmac->interface = of_get_phy_mode(dev->of_node); + + gmac->tx_clk = devm_clk_get(dev, "allwinner_gmac_tx"); + if (IS_ERR(gmac->tx_clk)) { + dev_err(dev, "could not get tx clock\n"); + return PTR_ERR(gmac->tx_clk); + } + + /* Optional regulator for PHY */ + gmac->regulator = devm_regulator_get_optional(dev, "phy"); + if (IS_ERR(gmac->regulator)) { + if (PTR_ERR(gmac->regulator) == -EPROBE_DEFER) + return -EPROBE_DEFER; + dev_info(dev, "no regulator found\n"); + gmac->regulator = NULL; + } + + /* platform data specifying hardware features and callbacks. + * hardware features were copied from Allwinner drivers. */ + plat_dat->tx_coe = 1; + plat_dat->has_gmac = true; + plat_dat->bsp_priv = gmac; + plat_dat->init = sun7i_gmac_init; + plat_dat->exit = sun7i_gmac_exit; + plat_dat->fix_mac_speed = sun7i_fix_speed; + + ret = sun7i_gmac_init(pdev, plat_dat->bsp_priv); + if (ret) + return ret; + + return stmmac_dvr_probe(&pdev->dev, plat_dat, &stmmac_res); +} + +static const struct of_device_id sun7i_dwmac_match[] = { + { .compatible = "allwinner,sun7i-a20-gmac" }, + { } +}; +MODULE_DEVICE_TABLE(of, sun7i_dwmac_match); + +static struct platform_driver sun7i_dwmac_driver = { + .probe = sun7i_gmac_probe, + .remove = stmmac_pltfr_remove, + .driver = { + .name = "sun7i-dwmac", + .pm = &stmmac_pltfr_pm_ops, + .of_match_table = sun7i_dwmac_match, + }, +}; +module_platform_driver(sun7i_dwmac_driver); + +MODULE_AUTHOR("Chen-Yu Tsai "); +MODULE_DESCRIPTION("Allwinner sunxi DWMAC specific glue layer"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0118067_rcar2.c b/pool/shard006/C/0118067_rcar2.c new file mode 100644 index 0000000000000000000000000000000000000000..52756fc2ac9cd63de1101f27a0fd2c41ae7800c2 --- /dev/null +++ b/pool/shard006/C/0118067_rcar2.c @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: GPL-1.0+ +/* + * Renesas USB driver R-Car Gen. 2 initialization and power control + * + * Copyright (C) 2014 Ulrich Hecht + * Copyright (C) 2019 Renesas Electronics Corporation + */ + +#include +#include "common.h" +#include "rcar2.h" + +static int usbhs_rcar2_hardware_init(struct platform_device *pdev) +{ + struct usbhs_priv *priv = usbhs_pdev_to_priv(pdev); + + if (IS_ENABLED(CONFIG_GENERIC_PHY)) { + struct phy *phy = phy_get(&pdev->dev, "usb"); + + if (IS_ERR(phy)) + return PTR_ERR(phy); + + priv->phy = phy; + return 0; + } + + return -ENXIO; +} + +static int usbhs_rcar2_hardware_exit(struct platform_device *pdev) +{ + struct usbhs_priv *priv = usbhs_pdev_to_priv(pdev); + + if (priv->phy) { + phy_put(&pdev->dev, priv->phy); + priv->phy = NULL; + } + + return 0; +} + +static int usbhs_rcar2_power_ctrl(struct platform_device *pdev, + void __iomem *base, int enable) +{ + struct usbhs_priv *priv = usbhs_pdev_to_priv(pdev); + int retval = -ENODEV; + + if (priv->phy) { + if (enable) { + retval = phy_init(priv->phy); + + if (!retval) + retval = phy_power_on(priv->phy); + } else { + phy_power_off(priv->phy); + phy_exit(priv->phy); + retval = 0; + } + } + + return retval; +} + +const struct renesas_usbhs_platform_info usbhs_rcar_gen2_plat_info = { + .platform_callback = { + .hardware_init = usbhs_rcar2_hardware_init, + .hardware_exit = usbhs_rcar2_hardware_exit, + .power_ctrl = usbhs_rcar2_power_ctrl, + .get_id = usbhs_get_id_as_gadget, + }, + .driver_param = { + .has_usb_dmac = 1, + .has_new_pipe_configs = 1, + }, +}; diff --git a/pool/shard006/C/0118070_fminbr.c b/pool/shard006/C/0118070_fminbr.c new file mode 100644 index 0000000000000000000000000000000000000000..1d6da04d61447e156bd36153e171def517256317 --- /dev/null +++ b/pool/shard006/C/0118070_fminbr.c @@ -0,0 +1,166 @@ +/* + ************************************************************************ + * C math library + * function FMINBR - one-dimensional search for a function minimum + * over the given range + * + * Input + * double fminbr(a,b,f,tol) + * double a; Minimum will be seeked for over + * double b; a range [a,b], a being < b. + * double (*f)(double x); Name of the function whose minimum + * will be seeked for + * double tol; Acceptable tolerance for the minimum + * location. It have to be positive + * (e.g. may be specified as EPSILON) + * + * Output + * Fminbr returns an estimate for the minimum location with accuracy + * 3*SQRT_EPSILON*abs(x) + tol. + * The function always obtains a local minimum which coincides with + * the global one only if a function under investigation being + * unimodular. + * If a function being examined possesses no local minimum within + * the given range, Fminbr returns 'a' (if f(a) < f(b)), otherwise + * it returns the right range boundary value b. + * + * Algorithm + * G.Forsythe, M.Malcolm, C.Moler, Computer methods for mathematical + * computations. M., Mir, 1980, p.202 of the Russian edition + * + * The function makes use of the "gold section" procedure combined with + * the parabolic interpolation. + * At every step program operates three abscissae - x,v, and w. + * x - the last and the best approximation to the minimum location, + * i.e. f(x) <= f(a) or/and f(x) <= f(b) + * (if the function f has a local minimum in (a,b), then the both + * conditions are fulfiled after one or two steps). + * v,w are previous approximations to the minimum location. They may + * coincide with a, b, or x (although the algorithm tries to make all + * u, v, and w distinct). Points x, v, and w are used to construct + * interpolating parabola whose minimum will be treated as a new + * approximation to the minimum location if the former falls within + * [a,b] and reduces the range enveloping minimum more efficient than + * the gold section procedure. + * When f(x) has a second derivative positive at the minimum location + * (not coinciding with a or b) the procedure converges superlinearly + * at a rate order about 1.324 + * + ************************************************************************ + */ + +#include "assert.h" +#include "math.h" + +#define EPSILON 2.22045e-16 +#define SQRT_EPSILON 1.49012e-08 + +double fminbr(a, b, f, tol) /* An estimate to the min location */ +double a; /* Left border | of the range */ +double b; /* Right border| the min is seeked */ +double (*f) (double x); /* Function under investigation */ +double tol; /* Acceptable tolerance */ +{ + double x, v, w; /* Abscissae, descr. see above */ + double fx; /* f(x) */ + double fv; /* f(v) */ + double fw; /* f(w) */ + const double r = (3. - sqrt(5.0)) / 2; /* Gold section ratio */ + + assert(tol > 0 && b > a); + + v = a + r * (b - a); + fv = (*f) (v); /* First step - always gold section */ + x = v; + w = v; + fx = fv; + fw = fv; + + for (;;) { /* Main iteration loop */ + double range = b - a; /* Range over which the minimum */ + /* is seeked for */ + double middle_range = (a + b) / 2; + double tol_act = /* Actual tolerance */ + SQRT_EPSILON * fabs(x) + tol / 3; + double new_step; /* Step at this iteration */ + + + + if (fabs(x - middle_range) + range / 2 <= 2 * tol_act) + return x; /* Acceptable approx. is found */ + + /* Obtain the gold section step */ + new_step = r * (x < middle_range ? b - x : a - x); + + + /* Decide if the interpolation can be tried */ + if (fabs(x - w) >= tol_act) { /* If x and w are distinct *//* interpolatiom may be tried */ + register double p; /* Interpolation step is calcula- */ + register double q; /* ted as p/q; division operation */ + /* is delayed until last moment */ + register double t; + + t = (x - w) * (fx - fv); + q = (x - v) * (fx - fw); + p = (x - v) * q - (x - w) * t; + q = 2 * (q - t); + + if (q > (double) 0) /* q was calculated with the op- */ + p = -p; /* posite sign; make q positive */ + else /* and assign possible minus to */ + q = -q; /* p */ + + if (fabs(p) < fabs(new_step * q) && /* If x+p/q falls in [a,b] */ + p > q * (a - x + 2 * tol_act) && /* not too close to a and */ + p < q * (b - x - 2 * tol_act)) /* b, and isn't too large */ + new_step = p / q; /* it is accepted */ + /* If p/q is too large then the */ + /* gold section procedure can */ + /* reduce [a,b] range to more */ + /* extent */ + } + + if (fabs(new_step) < tol_act) { /* Adjust the step to be not less */ + if (new_step > (double) 0) { /* than tolerance */ + new_step = tol_act; + } else { + new_step = -tol_act; + } + } /* Obtain the next approximation to min */ + { /* and reduce the enveloping range */ + register double t = x + new_step; /* Tentative point for the min */ + register double ft = (*f) (t); + if (ft <= fx) { /* t is a better approximation */ + if (t < x) /* Reduce the range so that */ + b = x; /* t would fall within it */ + else + a = x; + + v = w; + w = x; + x = t; /* Assign the best approx to x */ + fv = fw; + fw = fx; + fx = ft; + } else { /* x remains the better approx */ + + if (t < x) /* Reduce the range enclosing x */ + a = t; + else + b = t; + + if (ft <= fw || w == x) { + v = w; + w = t; + fv = fw; + fw = ft; + } else if (ft <= fv || v == x || v == w) { + v = t; + fv = ft; + } + } + + } /* ----- end-of-block ----- */ + } /* ===== End of loop ===== */ + +} diff --git a/pool/shard006/C/0118071_llog_obd.c b/pool/shard006/C/0118071_llog_obd.c new file mode 100644 index 0000000000000000000000000000000000000000..326772c8ab22e681014333bb108ed2c7407ceebc --- /dev/null +++ b/pool/shard006/C/0118071_llog_obd.c @@ -0,0 +1,266 @@ +/* + * GPL HEADER START + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 only, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License version 2 for more details (a copy is included + * in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; If not, see + * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + * GPL HEADER END + */ +/* + * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. + * Use is subject to license terms. + * + * Copyright (c) 2012, 2014, Intel Corporation. + */ +/* + * This file is part of Lustre, http://www.lustre.org/ + * Lustre is a trademark of Sun Microsystems, Inc. + */ + +#define DEBUG_SUBSYSTEM S_LOG + + +#include +#include +#include "llog_internal.h" + +/* helper functions for calling the llog obd methods */ +static struct llog_ctxt* llog_new_ctxt(struct obd_device *obd) +{ + struct llog_ctxt *ctxt; + + OBD_ALLOC_PTR(ctxt); + if (!ctxt) + return NULL; + + ctxt->loc_obd = obd; + atomic_set(&ctxt->loc_refcount, 1); + + return ctxt; +} + +static void llog_ctxt_destroy(struct llog_ctxt *ctxt) +{ + if (ctxt->loc_exp) { + class_export_put(ctxt->loc_exp); + ctxt->loc_exp = NULL; + } + if (ctxt->loc_imp) { + class_import_put(ctxt->loc_imp); + ctxt->loc_imp = NULL; + } + OBD_FREE_PTR(ctxt); +} + +int __llog_ctxt_put(const struct lu_env *env, struct llog_ctxt *ctxt) +{ + struct obd_llog_group *olg = ctxt->loc_olg; + struct obd_device *obd; + int rc = 0; + + spin_lock(&olg->olg_lock); + if (!atomic_dec_and_test(&ctxt->loc_refcount)) { + spin_unlock(&olg->olg_lock); + return rc; + } + olg->olg_ctxts[ctxt->loc_idx] = NULL; + spin_unlock(&olg->olg_lock); + + obd = ctxt->loc_obd; + spin_lock(&obd->obd_dev_lock); + /* sync with llog ctxt user thread */ + spin_unlock(&obd->obd_dev_lock); + + /* obd->obd_starting is needed for the case of cleanup + * in error case while obd is starting up. */ + LASSERTF(obd->obd_starting == 1 || + obd->obd_stopping == 1 || obd->obd_set_up == 0, + "wrong obd state: %d/%d/%d\n", !!obd->obd_starting, + !!obd->obd_stopping, !!obd->obd_set_up); + + /* cleanup the llog ctxt here */ + if (CTXTP(ctxt, cleanup)) + rc = CTXTP(ctxt, cleanup)(env, ctxt); + + llog_ctxt_destroy(ctxt); + wake_up(&olg->olg_waitq); + return rc; +} +EXPORT_SYMBOL(__llog_ctxt_put); + +int llog_cleanup(const struct lu_env *env, struct llog_ctxt *ctxt) +{ + struct l_wait_info lwi = LWI_INTR(LWI_ON_SIGNAL_NOOP, NULL); + struct obd_llog_group *olg; + int rc, idx; + ENTRY; + + LASSERT(ctxt != NULL); + LASSERT(ctxt != LP_POISON); + + olg = ctxt->loc_olg; + LASSERT(olg != NULL); + LASSERT(olg != LP_POISON); + + idx = ctxt->loc_idx; + + /* + * Banlance the ctxt get when calling llog_cleanup() + */ + LASSERT(atomic_read(&ctxt->loc_refcount) < LI_POISON); + LASSERT(atomic_read(&ctxt->loc_refcount) > 1); + llog_ctxt_put(ctxt); + + /* + * Try to free the ctxt. + */ + rc = __llog_ctxt_put(env, ctxt); + if (rc) + CERROR("Error %d while cleaning up ctxt %p\n", + rc, ctxt); + + l_wait_event(olg->olg_waitq, + llog_group_ctxt_null(olg, idx), &lwi); + + RETURN(rc); +} +EXPORT_SYMBOL(llog_cleanup); + +int llog_setup(const struct lu_env *env, struct obd_device *obd, + struct obd_llog_group *olg, int index, + struct obd_device *disk_obd, struct llog_operations *op) +{ + struct llog_ctxt *ctxt; + int rc = 0; + ENTRY; + + if (index < 0 || index >= LLOG_MAX_CTXTS) + RETURN(-EINVAL); + + LASSERT(olg != NULL); + + ctxt = llog_new_ctxt(obd); + if (!ctxt) + RETURN(-ENOMEM); + + ctxt->loc_obd = obd; + ctxt->loc_olg = olg; + ctxt->loc_idx = index; + ctxt->loc_logops = op; + mutex_init(&ctxt->loc_mutex); + ctxt->loc_exp = class_export_get(disk_obd->obd_self_export); + ctxt->loc_flags = LLOG_CTXT_FLAG_UNINITIALIZED; + + rc = llog_group_set_ctxt(olg, ctxt, index); + if (rc) { + llog_ctxt_destroy(ctxt); + if (rc == -EEXIST) { + ctxt = llog_group_get_ctxt(olg, index); + if (ctxt) { + /* + * mds_lov_update_desc() might call here multiple + * times. So if the llog is already set up then + * don't to do it again. + */ + CDEBUG(D_CONFIG, "obd %s ctxt %d already set up\n", + obd->obd_name, index); + LASSERT(ctxt->loc_olg == olg); + LASSERT(ctxt->loc_obd == obd); + LASSERT(ctxt->loc_exp == disk_obd->obd_self_export); + LASSERT(ctxt->loc_logops == op); + llog_ctxt_put(ctxt); + } + rc = 0; + } + RETURN(rc); + } + + if (op->lop_setup) { + if (OBD_FAIL_CHECK(OBD_FAIL_OBD_LLOG_SETUP)) + rc = -EOPNOTSUPP; + else + rc = op->lop_setup(env, obd, olg, index, disk_obd); + } + + if (rc) { + CERROR("%s: ctxt %d lop_setup=%p failed: rc = %d\n", + obd->obd_name, index, op->lop_setup, rc); + llog_group_clear_ctxt(olg, index); + llog_ctxt_destroy(ctxt); + } else { + CDEBUG(D_CONFIG, "obd %s ctxt %d is initialized\n", + obd->obd_name, index); + ctxt->loc_flags &= ~LLOG_CTXT_FLAG_UNINITIALIZED; + } + + RETURN(rc); +} +EXPORT_SYMBOL(llog_setup); + +int llog_sync(struct llog_ctxt *ctxt, struct obd_export *exp, int flags) +{ + int rc = 0; + ENTRY; + + if (!ctxt) + RETURN(0); + + if (CTXTP(ctxt, sync)) + rc = CTXTP(ctxt, sync)(ctxt, exp, flags); + + RETURN(rc); +} +EXPORT_SYMBOL(llog_sync); + +int llog_cancel(const struct lu_env *env, struct llog_ctxt *ctxt, + struct llog_cookie *cookies, int flags) +{ + int rc; + ENTRY; + + if (!ctxt) { + CERROR("No ctxt\n"); + RETURN(-ENODEV); + } + + CTXT_CHECK_OP(ctxt, cancel, -EOPNOTSUPP); + rc = CTXTP(ctxt, cancel)(env, ctxt, cookies, flags); + RETURN(rc); +} +EXPORT_SYMBOL(llog_cancel); + +/* context key constructor/destructor: llog_key_init, llog_key_fini */ +LU_KEY_INIT_FINI(llog, struct llog_thread_info); +/* context key: llog_thread_key */ +LU_CONTEXT_KEY_DEFINE(llog, LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL); +LU_KEY_INIT_GENERIC(llog); +EXPORT_SYMBOL(llog_thread_key); + +int llog_info_init(void) +{ + llog_key_init_generic(&llog_thread_key, NULL); + lu_context_key_register(&llog_thread_key); + return 0; +} + +void llog_info_fini(void) +{ + lu_context_key_degister(&llog_thread_key); +} diff --git a/pool/shard006/C/0118073_rlact_execution_only.c b/pool/shard006/C/0118073_rlact_execution_only.c new file mode 100644 index 0000000000000000000000000000000000000000..1dd62b0ac1946867112459144652c59f9df076fc --- /dev/null +++ b/pool/shard006/C/0118073_rlact_execution_only.c @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2008-2012 The Paparazzi Team + * + * This file is part of paparazzi. + * + * paparazzi 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. + * + * paparazzi 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 paparazzi; see the file COPYING. If not, write to + * the Free Software Foundation, 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + + /* This module creates a flight plan callable function to learn high level guidance via reinforcement learning. written by Jaime Junell */ + +#include "rlact.h" +#include "generated/airframe.h" +#include +#include + +#include "messages.h" +#include "mcu_periph/uart.h" +#include "subsystems/datalink/downlink.h" +#include "generated/flight_plan.h" //needed to use WP_HOME + +//*************** DECLARE VARIABLES *****************// +const int16_t del = 256;// distance to move in each action +int8_t act; + +//*********************** FUNCTIONS ***********************// +void rlact_init(void) { + +printf("init1\n"); + act= 0; //initialize it +printf("init2\n"); + srand(time(NULL)); +printf("init3\n"); + // const int nact = 4; //number of actions = 4 (NESW) + +} + +///////* OWN FUCTION TO CALL FROM FLIGHT PLAN *////// +bool_t rlact_run(uint8_t wpa, uint8_t wpb){ + + printf("started\n"); + + //act = (rand() % 8)+1; + act = 0; + + //execute in paparazzi sim/IRL + switch (act){ + case 0: /* no movement */ + waypoints[wpb].x = waypoints[wpa].x; + waypoints[wpb].y = waypoints[wpa].y; + break; + case 1: /* north */ + waypoints[wpb].x = waypoints[wpa].x; + waypoints[wpb].y = waypoints[wpa].y + del; +// ++ka[0]; + break; + case 2: /* east */ + waypoints[wpb].x = waypoints[wpa].x + del; + waypoints[wpb].y = waypoints[wpa].y; +// ++ka[1]; + break; + case 3: /* south */ + waypoints[wpb].x = waypoints[wpa].x; + waypoints[wpb].y = waypoints[wpa].y - del; +// ++ka[2]; + break; + case 4: /* west */ + waypoints[wpb].x = waypoints[wpa].x - del; + waypoints[wpb].y = waypoints[wpa].y; +// ++ka[3]; + break; + case 5: /* northwest */ + waypoints[wpb].x = waypoints[wpa].x - del; + waypoints[wpb].y = waypoints[wpa].y + del; +// ++ka[4]; + break; + case 6: /* northeast */ + waypoints[wpb].x = waypoints[wpa].x + del; + waypoints[wpb].y = waypoints[wpa].y + del; +// ++ka[5]; + break; + case 7: /* southeast */ + waypoints[wpb].x = waypoints[wpa].x + del; + waypoints[wpb].y = waypoints[wpa].y - del; +// ++ka[6]; + break; + case 8: /* southwest */ + waypoints[wpb].x = waypoints[wpa].x - del; + waypoints[wpb].y = waypoints[wpa].y - del; +// ++ka[7]; + break; + default: /* no movement */ + waypoints[wpb].x = waypoints[wpa].x; + waypoints[wpb].y = waypoints[wpa].y; +// state_next = state_curr; ns_next = ns_curr; + //printf("Error: no valid action taken\n"); + break; + } + return FALSE; +} // end of rlact_run function + diff --git a/pool/shard006/C/0118075_test_metar.c b/pool/shard006/C/0118075_test_metar.c new file mode 100644 index 0000000000000000000000000000000000000000..2405ae2cc6b2c5ebbe5ec41293cc980e569345d5 --- /dev/null +++ b/pool/shard006/C/0118075_test_metar.c @@ -0,0 +1,118 @@ +/* test_metar.c: Simple program to reproduce METAR parsing results from command line + * + * SPDX-FileCopyrightText: The GWeather authors + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +#include "config.h" + +#include "gweather-private.h" + +#include +#include +#include + +#ifndef BUFLEN +#define BUFLEN 4096 +#endif /* BUFLEN */ + +static void +print_info (GWeatherInfo *info) +{ + if (gweather_info_is_valid (info)) { + g_message ("Weather updated successfully for %s", info->location.code); + } else { + g_warning ("Failed to parse weather for %s", info->location.code); + return; + } + + printf ("Returned info:\n"); + printf (" update: %s", ctime (&info->update)); + printf (" sky: %s\n", gweather_info_get_sky (info)); + printf (" cond: %s\n", gweather_info_get_conditions (info)); + printf (" temp: %s\n", gweather_info_get_temp (info)); + printf (" dewp: %s\n", gweather_info_get_dew (info)); + printf (" wind: %s\n", gweather_info_get_wind (info)); + printf (" pressure: %s\n", gweather_info_get_pressure (info)); + printf (" vis: %s\n", gweather_info_get_visibility (info)); + + // TODO: retrieve location's lat/lon to display sunrise/set times +} + +static void +weather_updated_cb (GWeatherInfo *info, + gpointer user_data) +{ + print_info (info); + g_main_loop_quit (user_data); +} + +int +main (int argc, char **argv) +{ + FILE *stream = stdin; + gchar *filename = NULL; + gchar *code = NULL; + GOptionEntry entries[] = { + { "file", 'f', 0, G_OPTION_ARG_FILENAME, &filename, "file containing METAR observations", NULL }, + { "code", 'c', 0, G_OPTION_ARG_STRING, &code, "ICAO code to get METAR observations from", NULL }, + { NULL } + }; + GOptionContext *context; + GError *error = NULL; + char buf[BUFLEN]; + int len; + GWeatherInfo *info; + + context = g_option_context_new ("- test libgweather metar parser"); + g_option_context_add_main_entries (context, entries, NULL); + g_option_context_parse (context, &argc, &argv, &error); + + if (error) { + perror (error->message); + return error->code; + } + + if (code) { + GMainLoop *loop; + + loop = g_main_loop_new (NULL, TRUE); + + info = g_object_new (GWEATHER_TYPE_INFO, NULL); + info->location.code = g_strdup (code); + info->location.latlon_valid = TRUE; + info->session = soup_session_new (); + g_signal_connect (G_OBJECT (info), "updated", G_CALLBACK (weather_updated_cb), loop); + + metar_start_open (info); + + g_main_loop_run (loop); + + return 0; + } + + if (filename) { + stream = fopen (filename, "r"); + if (!stream) { + perror ("fopen"); + return -1; + } + } else { + fprintf (stderr, "Enter a METAR string...\n"); + } + + while (fgets (buf, sizeof (buf), stream)) { + len = strlen (buf); + if (buf[len - 1] == '\n') { + buf[--len] = '\0'; + } + printf ("\n%s\n", buf); + + /* a bit hackish... */ + info = g_object_new (GWEATHER_TYPE_INFO, NULL); + info->valid = 1; + metar_parse (buf, info); + print_info (info); + } + return 0; +} diff --git a/pool/shard006/C/0118079_animation.c b/pool/shard006/C/0118079_animation.c new file mode 100644 index 0000000000000000000000000000000000000000..36a06c8ad73ee9fdddc12a51a5e62fd47223e1b7 --- /dev/null +++ b/pool/shard006/C/0118079_animation.c @@ -0,0 +1,164 @@ +#define _GNU_SOURCE +#include "testParameters.h" +#include "animation.h" +#include +#include +#include +#include +#include + + +void draw_ball(int x, int y, int c) +{ + circlefill(screen, x, y, L, c); +} + +void print_id_task(int id, int x, int y, int color){ + + textprintf_ex(screen, font, x, y, color, BGC, "T%d", id); + +} + +void periodicBall_testParam() { + + int i, j = 0; + int dcol = BGC; + int *pun_col; + int color; + int x, ox, xStart; + int y, oy; + float vel = VELX; + float tx = 0.0, dt; + + i = ptask_get_index(); + pun_col = ptask_get_argument(); + color = *pun_col; + + x = ox = xStart = XMIN ; + y = oy = BASE -1 + 20 +(i * 4 * L); + dt = ptask_get_period(i, MILLI) / 100.; + + /* print task's id on screen on the right of task animation */ + pthread_mutex_lock(&mxa); + print_id_task(i, 5, y , color); + pthread_mutex_unlock(&mxa); + + sample[i] = 0; + while (1) { + + /* update position x of the ball */ + x = xStart + vel * tx; + + if (x > XMAX) { + tx = 0.0; + xStart = XMAX; + vel = -vel; + x = xStart; + } + if (x < XMIN) { + tx = 0.0; + xStart = XMIN; + vel = -vel; + x = xStart ; + } + + pthread_mutex_lock(&mxa); + draw_ball( ox, y , BGC); + draw_ball( x, y , color ); + pthread_mutex_unlock(&mxa); + + dt = ptask_get_period(i, MILLI) / 100.; + tx += dt; + ox = x; + + if (ptask_deadline_miss()) { + /* draw with a different color a circle that represent deadline miss */ + dcol = (dcol + 1) % 15; + pthread_mutex_lock(&mxa); + draw_ball( XMAX + 15, y , dcol ); + pthread_mutex_unlock(&mxa); + } + + ptask_wait_for_period(); + + /* get sample of start time and next_activation time (not more than MAX_SAMPLE)*/ + if (j < MAX_SAMPLE) { + start_time[i][j] = ptask_gettime(MILLI); + v_next_at[i][j] = ptask_get_nextactivation(MILLI); + sample[i]++; + j++; + } + } +} + + +void periodicBall_testParamDEP_PER() { + + int i, j = 0; + int dcol = BGC; + int *pun_col; + int color; + int x, ox, xStart ; + int y, oy; + float vel= VELX; + float tx = 0.0; + float dt = 20.0 / 100.0; /* dt is constant */ + + i = ptask_get_index(); + pun_col = ptask_get_argument(); + color = *pun_col; + + x = ox = xStart = XMIN ; + y = oy = BASE -1 + 20 +(i * 4 * L); + + /* print task's id on screen on the right of task animation */ + pthread_mutex_lock(&mxa); + print_id_task(i, 5, y , color); + pthread_mutex_unlock(&mxa); + + sample[i] = 0; + while (1) { + + /* update position x of the ball */ + x = xStart + vel * tx; + + if (x > XMAX) { + tx = 0.0; + xStart = XMAX; + vel = -vel; + x = xStart; + } + if (x < XMIN) { + tx = 0.0; + xStart = XMIN; + vel = -vel; + x = xStart ; + } + + pthread_mutex_lock(&mxa); + draw_ball( ox, y , BGC); + draw_ball( x, y , color ); + pthread_mutex_unlock(&mxa); + + tx += dt; + ox = x; + + if (ptask_deadline_miss()) { + /* draw with a different color a circle that represent deadline miss */ + dcol = (dcol + 1) % 15; + pthread_mutex_lock(&mxa); + draw_ball( XMAX + 15, y , dcol ); + pthread_mutex_unlock(&mxa); + } + + ptask_wait_for_period(); + + /* get sample of start time and next_activation time (not more than MAX_SAMPLE)*/ + if (j < MAX_SAMPLE) { + start_time[i][j] = ptask_gettime(MILLI); + v_next_at[i][j] = ptask_get_nextactivation(MILLI); + sample[i]++; + j++; + } + } +} diff --git a/pool/shard006/C/0118082_relation_select_manager.c b/pool/shard006/C/0118082_relation_select_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..2772e401fd385a51e929f34dd71f0306dc8e24d6 --- /dev/null +++ b/pool/shard006/C/0118082_relation_select_manager.c @@ -0,0 +1,92 @@ +#include "relation_select_manager.h" + +static void free_select_manager(SelectManager *pointer) { + free(pointer); +} + +static VALUE allocate_select_manager(VALUE klass) { + SelectManager *select_manager = new_select_manager(); + VALUE object; + object = Data_Wrap_Struct(klass, 0, free_select_manager, select_manager); + return object; +} + +VALUE relation_select_manager_initialize(VALUE self, VALUE table) { + RelationTable *relation_table; + Data_Get_Struct(table, RelationTable, relation_table); + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_instance_table(select_manager, relation_table); + return self; +} + +VALUE relation_select_manager_select_wrapper(VALUE self, VALUE projections) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + long i; + + for(i = 0; i < RARRAY_LEN(projections); i++) { + select_manager_project(select_manager, StringValuePtr(RARRAY_PTR(projections)[i])); + } + + return self; +} + +VALUE relation_select_manager_limit_wrapper(VALUE self, VALUE limit) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_limit(select_manager, FIX2LONG(limit)); + return self; +} + +VALUE relation_select_manager_where_wrapper(VALUE self, VALUE conditions) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_where(select_manager, StringValuePtr(conditions)); + return self; +} + +VALUE relation_select_manager_order_wrapper(VALUE self, VALUE expression) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_order(select_manager, StringValuePtr(expression)); + return self; +} + +VALUE relation_select_manager_offset_wrapper(VALUE self, VALUE offset_number) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_offset(select_manager, FIX2INT(offset_number)); + return self; +} + +VALUE relation_select_manager_group_wrapper(VALUE self, VALUE group) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_group(select_manager, StringValuePtr(group)); + return self; +} + +VALUE relation_select_manager_having_wrapper(VALUE self, VALUE expression) { + SelectManager *select_manager; + Data_Get_Struct(self, SelectManager, select_manager); + select_manager_having(select_manager, StringValuePtr(expression)); + return self; +} + +void Init_relation_select_manager() { + class_SelectManager = rb_define_class_under(module_Relation, "SelectManager", class_TreeManager); + + /* Allocate funtion to handle with C structs */ + rb_define_alloc_func(class_SelectManager, allocate_select_manager); + + /* Instance methods*/ + rb_define_method(class_SelectManager, "initialize", relation_select_manager_initialize, 1); + rb_define_method(class_SelectManager, "select", relation_select_manager_select_wrapper, -2); + rb_define_method(class_SelectManager, "limit", relation_select_manager_limit_wrapper, 1); + rb_define_method(class_SelectManager, "where", relation_select_manager_where_wrapper, 1); + rb_define_method(class_SelectManager, "order", relation_select_manager_order_wrapper, 1); + rb_define_method(class_SelectManager, "offset", relation_select_manager_offset_wrapper, 1); + rb_define_method(class_SelectManager, "group", relation_select_manager_group_wrapper, 1); + rb_define_method(class_SelectManager, "having", relation_select_manager_having_wrapper, 1); +} diff --git a/pool/shard006/C/0118084_psutils.c b/pool/shard006/C/0118084_psutils.c new file mode 100644 index 0000000000000000000000000000000000000000..6398fd3d1cba9a4546746d5aed8e4dc5519b36fe --- /dev/null +++ b/pool/shard006/C/0118084_psutils.c @@ -0,0 +1,361 @@ +/****************************************************************************** + * + * Module Name: psutils - Parser miscellaneous utilities (Parser only) + * + *****************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2012, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + *****************************************************************************/ + + +#include "acpi.h" +#include "accommon.h" +#include "acparser.h" +#include "amlcode.h" + +#define _COMPONENT ACPI_PARSER + ACPI_MODULE_NAME ("psutils") + + +/******************************************************************************* + * + * FUNCTION: AcpiPsCreateScopeOp + * + * PARAMETERS: None + * + * RETURN: A new Scope object, null on failure + * + * DESCRIPTION: Create a Scope and associated namepath op with the root name + * + ******************************************************************************/ + +ACPI_PARSE_OBJECT * +AcpiPsCreateScopeOp ( + void) +{ + ACPI_PARSE_OBJECT *ScopeOp; + + + ScopeOp = AcpiPsAllocOp (AML_SCOPE_OP); + if (!ScopeOp) + { + return (NULL); + } + + ScopeOp->Named.Name = ACPI_ROOT_NAME; + return (ScopeOp); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsInitOp + * + * PARAMETERS: Op - A newly allocated Op object + * Opcode - Opcode to store in the Op + * + * RETURN: None + * + * DESCRIPTION: Initialize a parse (Op) object + * + ******************************************************************************/ + +void +AcpiPsInitOp ( + ACPI_PARSE_OBJECT *Op, + UINT16 Opcode) +{ + ACPI_FUNCTION_ENTRY (); + + + Op->Common.DescriptorType = ACPI_DESC_TYPE_PARSER; + Op->Common.AmlOpcode = Opcode; + + ACPI_DISASM_ONLY_MEMBERS (ACPI_STRNCPY (Op->Common.AmlOpName, + (AcpiPsGetOpcodeInfo (Opcode))->Name, + sizeof (Op->Common.AmlOpName))); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsAllocOp + * + * PARAMETERS: Opcode - Opcode that will be stored in the new Op + * + * RETURN: Pointer to the new Op, null on failure + * + * DESCRIPTION: Allocate an acpi_op, choose op type (and thus size) based on + * opcode. A cache of opcodes is available for the pure + * GENERIC_OP, since this is by far the most commonly used. + * + ******************************************************************************/ + +ACPI_PARSE_OBJECT* +AcpiPsAllocOp ( + UINT16 Opcode) +{ + ACPI_PARSE_OBJECT *Op; + const ACPI_OPCODE_INFO *OpInfo; + UINT8 Flags = ACPI_PARSEOP_GENERIC; + + + ACPI_FUNCTION_ENTRY (); + + + OpInfo = AcpiPsGetOpcodeInfo (Opcode); + + /* Determine type of ParseOp required */ + + if (OpInfo->Flags & AML_DEFER) + { + Flags = ACPI_PARSEOP_DEFERRED; + } + else if (OpInfo->Flags & AML_NAMED) + { + Flags = ACPI_PARSEOP_NAMED; + } + else if (Opcode == AML_INT_BYTELIST_OP) + { + Flags = ACPI_PARSEOP_BYTELIST; + } + + /* Allocate the minimum required size object */ + + if (Flags == ACPI_PARSEOP_GENERIC) + { + /* The generic op (default) is by far the most common (16 to 1) */ + + Op = AcpiOsAcquireObject (AcpiGbl_PsNodeCache); + } + else + { + /* Extended parseop */ + + Op = AcpiOsAcquireObject (AcpiGbl_PsNodeExtCache); + } + + /* Initialize the Op */ + + if (Op) + { + AcpiPsInitOp (Op, Opcode); + Op->Common.Flags = Flags; + } + + return (Op); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsFreeOp + * + * PARAMETERS: Op - Op to be freed + * + * RETURN: None. + * + * DESCRIPTION: Free an Op object. Either put it on the GENERIC_OP cache list + * or actually free it. + * + ******************************************************************************/ + +void +AcpiPsFreeOp ( + ACPI_PARSE_OBJECT *Op) +{ + ACPI_FUNCTION_NAME (PsFreeOp); + + + if (Op->Common.AmlOpcode == AML_INT_RETURN_VALUE_OP) + { + ACPI_DEBUG_PRINT ((ACPI_DB_ALLOCATIONS, "Free retval op: %p\n", Op)); + } + + if (Op->Common.Flags & ACPI_PARSEOP_GENERIC) + { + (void) AcpiOsReleaseObject (AcpiGbl_PsNodeCache, Op); + } + else + { + (void) AcpiOsReleaseObject (AcpiGbl_PsNodeExtCache, Op); + } +} + + +/******************************************************************************* + * + * FUNCTION: Utility functions + * + * DESCRIPTION: Low level character and object functions + * + ******************************************************************************/ + + +/* + * Is "c" a namestring lead character? + */ +BOOLEAN +AcpiPsIsLeadingChar ( + UINT32 c) +{ + return ((BOOLEAN) (c == '_' || (c >= 'A' && c <= 'Z'))); +} + + +/* + * Is "c" a namestring prefix character? + */ +BOOLEAN +AcpiPsIsPrefixChar ( + UINT32 c) +{ + return ((BOOLEAN) (c == '\\' || c == '^')); +} + + +/* + * Get op's name (4-byte name segment) or 0 if unnamed + */ +UINT32 +AcpiPsGetName ( + ACPI_PARSE_OBJECT *Op) +{ + + /* The "generic" object has no name associated with it */ + + if (Op->Common.Flags & ACPI_PARSEOP_GENERIC) + { + return (0); + } + + /* Only the "Extended" parse objects have a name */ + + return (Op->Named.Name); +} + + +/* + * Set op's name + */ +void +AcpiPsSetName ( + ACPI_PARSE_OBJECT *Op, + UINT32 name) +{ + + /* The "generic" object has no name associated with it */ + + if (Op->Common.Flags & ACPI_PARSEOP_GENERIC) + { + return; + } + + Op->Named.Name = name; +} diff --git a/pool/shard006/C/0118087_mnoton.c b/pool/shard006/C/0118087_mnoton.c new file mode 100644 index 0000000000000000000000000000000000000000..1847a1d830d3cdd0b7fbf6ef7ab1f2c6a780b997 --- /dev/null +++ b/pool/shard006/C/0118087_mnoton.c @@ -0,0 +1,230 @@ +/* $NoKeywords:$ */ +/** + * @file + * + * mnoton.c + * + * Northbridge Non-SPD timings for ON + * + * @xrefitem bom "File Content Label" "Release Content" + * @e project: AGESA + * @e sub-project: (Mem/NB/ON) + * @e \$Revision: 39158 $ @e \$Date: 2010-10-07 21:34:36 +0800 (Thu, 07 Oct 2010) $ + * + **/ +/* + ***************************************************************************** + * + * Copyright (c) 2011, Advanced Micro Devices, 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 Advanced Micro Devices, Inc. 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 ADVANCED MICRO DEVICES, INC. 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. + * + * *************************************************************************** + * + */ + +/* + *---------------------------------------------------------------------------- + * MODULES USED + * + *---------------------------------------------------------------------------- + */ + + + +#include "AGESA.h" +#include "Ids.h" +#include "mm.h" +#include "mn.h" +#include "OptionMemory.h" // need def for MEM_FEAT_BLOCK_NB +#include "mnon.h" +#include "mu.h" +#include "Filecode.h" +#define FILECODE PROC_MEM_NB_ON_MNOTON_FILECODE + + +/*---------------------------------------------------------------------------- + * DEFINITIONS AND MACROS + * + *---------------------------------------------------------------------------- + */ + +/*---------------------------------------------------------------------------- + * TYPEDEFS AND STRUCTURES + * + *---------------------------------------------------------------------------- + */ + +/*---------------------------------------------------------------------------- + * PROTOTYPES OF LOCAL FUNCTIONS + * + *---------------------------------------------------------------------------- + */ +VOID +STATIC +MemNSetOtherTimingON ( + IN OUT MEM_NB_BLOCK *NBPtr + ); + +VOID +STATIC +MemNPowerDownCtlON ( + IN OUT MEM_NB_BLOCK *NBPtr + ); + +/*---------------------------------------------------------------------------- + * EXPORTED FUNCTIONS + * + *---------------------------------------------------------------------------- + */ + +/* -----------------------------------------------------------------------------*/ +/** + * + * This function sets the non-SPD timings + * + * @param[in,out] *NBPtr - Pointer to the MEM_NB_BLOCK + * + * @return TRUE - No fatal error occurs. + * @return FALSE - Fatal error occurs. + */ + +BOOLEAN +MemNOtherTimingON ( + IN OUT MEM_NB_BLOCK *NBPtr + ) +{ + MemNSetOtherTimingON (NBPtr); + MemNPowerDownCtlON (NBPtr); + + return (BOOLEAN) (NBPtr->MCTPtr->ErrCode < AGESA_FATAL); +} + +/*---------------------------------------------------------------------------- + * LOCAL FUNCTIONS + * + *---------------------------------------------------------------------------- + */ + +/* -----------------------------------------------------------------------------*/ +/** + * + * This function sets the non-SPD timings into the PCI registers + * + * @param[in,out] *NBPtr - Pointer to the MEM_NB_BLOCK + * + */ + +VOID +STATIC +MemNSetOtherTimingON ( + IN OUT MEM_NB_BLOCK *NBPtr + ) +{ + INT16 ROD; + INT16 WOD; + UINT8 LD; + UINT8 Tcwl; + INT16 CDDTrdrd; + INT16 Trdrd; + INT16 CDDTwrwr; + INT16 Twrwr; + INT16 CDDTwrrdSD; + INT16 TwrrdSD; + INT16 CDDTwrrd; + INT16 Twrrd; + INT16 CDDTrwtTO; + INT16 TrwtTO; + + ROD = (DEFAULT_RD_ODT_ON_ON > 6) ? (DEFAULT_RD_ODT_ON_ON - 6) : 0; + WOD = (DEFAULT_RD_ODT_ON_ON > 6) ? (DEFAULT_WR_ODT_ON_ON - 6) : 0; + + Tcwl = (UINT8) (NBPtr->DCTPtr->Timings.Speed / 133) + 2; + LD = NBPtr->DCTPtr->Timings.CasL - Tcwl; + + // TrdrdSD = 3 + MemNSetBitFieldNb (NBPtr, BFTrdrdSD, 2 - 2 + 1); + + // Trdrd = CEIL(MAX(ROD + 3, CDDTrdrd/2 + (F2x[94]SlowAccessMode ? 3 : 3.5))) + CDDTrdrd = (MemNCalcCDDNb (NBPtr, AccessRcvEnDly, AccessRcvEnDly, FALSE, TRUE) + (INT16) ((NBPtr->ChannelPtr->SlowMode ? 6 : 7) + 1)) / (INT16) 2; + Trdrd = MAX (ROD + 3, CDDTrdrd); + Trdrd = MIN (MAX (Trdrd, 2), 10); + MemNSetBitFieldNb (NBPtr, BFTrdrd, (UINT8) (Trdrd - 2)); + + // TwrwrSD = WOD + 3 + MemNSetBitFieldNb (NBPtr, BFTwrwrSD, (WOD + 3 - 1)); + + // Twrwr = CEIL(MAX(WOD + 3, CDDTwrwr / 2 + 3.5)) + CDDTwrwr = (MemNCalcCDDNb (NBPtr, AccessWrDqsDly, AccessWrDqsDly, FALSE, TRUE) + (INT16) (7 + 1)) / (INT16) 2; + Twrwr = MAX (WOD + 3, CDDTwrwr); + Twrwr = MIN (MAX (Twrwr, 1), 10); + MemNSetBitFieldNb (NBPtr, BFTwrwr, (UINT8) (Twrwr - 1)); + + // TwrrdSD = CEIL(MAX(1, MAX(WOD, CDDTwrrdSD / 2 + 0.5) - LD + 3)) + CDDTwrrdSD = (MemNCalcCDDNb (NBPtr, AccessWrDqsDly, AccessRcvEnDly, TRUE, FALSE) + (INT16) (1 + 1)) / (INT16) 2; + TwrrdSD = MAX (WOD, CDDTwrrdSD) - LD + 3; + TwrrdSD = MIN (MAX (TwrrdSD, 1), 11); + MemNSetBitFieldNb (NBPtr, BFTwrrdSD, (UINT8) (TwrrdSD - 1)); + + // Twrrd = CEIL(MAX(1, MAX(WOD, CDDTwrrd / 2 + 0.5) - LD + 3)) + CDDTwrrd = (MemNCalcCDDNb (NBPtr, AccessWrDqsDly, AccessRcvEnDly, FALSE, TRUE) + (INT16) (1 + 1)) / (INT16) 2; + Twrrd = MAX (WOD, CDDTwrrd) - LD + 3; + Twrrd = MIN (MAX (Twrrd, 1), 11); + Twrrd = MAX (Twrrd, TwrrdSD); + MemNSetBitFieldNb (NBPtr, BFTwrrd, (UINT8) (Twrrd - 1)); + + // TrwtTO = CEIL(MAX(ROD, CDDTrwtTO / 2 - 0.5) + LD + 3). + CDDTrwtTO = (MemNCalcCDDNb (NBPtr, AccessRcvEnDly, AccessWrDqsDly, TRUE, TRUE) + (INT16) (1 - 1)) / (INT16) 2; + TrwtTO = MAX (ROD, CDDTrwtTO) + LD + 3; + TrwtTO = MIN (MAX (TrwtTO, 3), 17); + MemNSetBitFieldNb (NBPtr, BFTrwtTO, (UINT8) (TrwtTO - 2)); + + // TrwtWB should be set to 0xF for ON. + MemNSetBitFieldNb (NBPtr, BFTrwtWB, 4); +} + +/* -----------------------------------------------------------------------------*/ +/** + * + * This function enables power down mode + * + * @param[in,out] *NBPtr - Pointer to the MEM_NB_BLOCK + * + */ + +VOID +STATIC +MemNPowerDownCtlON ( + IN OUT MEM_NB_BLOCK *NBPtr + ) +{ + if (NBPtr->RefPtr->EnablePowerDown) { + MemNSetTxpNb (NBPtr); + MemNSetBitFieldNb (NBPtr, BFPowerDownEn, 1); + } + + if (NBPtr->RefPtr->EnableBankSwizzle) { + MemNSetBitFieldNb (NBPtr, BFBankSwizzleMode, 1); + } +} diff --git a/pool/shard006/C/0118088_group.c b/pool/shard006/C/0118088_group.c new file mode 100644 index 0000000000000000000000000000000000000000..618bc9e5cead835135de5e72e512912dc22b1d7b --- /dev/null +++ b/pool/shard006/C/0118088_group.c @@ -0,0 +1,150 @@ +/* + * Copyright (C) 2008 Red Hat, Inc., Eric Paris + * + * 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. + * + * 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; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include "fsnotify.h" + +#include + +/* + * Final freeing of a group + */ +static void fsnotify_final_destroy_group(struct fsnotify_group *group) +{ + if (group->ops->free_group_priv) + group->ops->free_group_priv(group); + + kfree(group); +} + +/* + * Stop queueing new events for this group. Once this function returns + * fsnotify_add_event() will not add any new events to the group's queue. + */ +void fsnotify_group_stop_queueing(struct fsnotify_group *group) +{ + mutex_lock(&group->notification_mutex); + group->shutdown = true; + mutex_unlock(&group->notification_mutex); +} + +/* + * Trying to get rid of a group. Remove all marks, flush all events and release + * the group reference. + * Note that another thread calling fsnotify_clear_marks_by_group() may still + * hold a ref to the group. + */ +void fsnotify_destroy_group(struct fsnotify_group *group) +{ + /* + * Stop queueing new events. The code below is careful enough to not + * require this but fanotify needs to stop queuing events even before + * fsnotify_destroy_group() is called and this makes the other callers + * of fsnotify_destroy_group() to see the same behavior. + */ + fsnotify_group_stop_queueing(group); + + /* clear all inode marks for this group, attach them to destroy_list */ + fsnotify_detach_group_marks(group); + + /* + * Wait for fsnotify_mark_srcu period to end and free all marks in + * destroy_list + */ + fsnotify_mark_destroy_list(); + + /* + * Since we have waited for fsnotify_mark_srcu in + * fsnotify_mark_destroy_list() there can be no outstanding event + * notification against this group. So clearing the notification queue + * of all events is reliable now. + */ + fsnotify_flush_notify(group); + + /* + * Destroy overflow event (we cannot use fsnotify_destroy_event() as + * that deliberately ignores overflow events. + */ + if (group->overflow_event) + group->ops->free_event(group->overflow_event); + + fsnotify_put_group(group); +} + +/* + * Get reference to a group. + */ +void fsnotify_get_group(struct fsnotify_group *group) +{ + atomic_inc(&group->refcnt); +} +EXPORT_SYMBOL_GPL(fsnotify_get_group); + +/* + * Drop a reference to a group. Free it if it's through. + */ +void fsnotify_put_group(struct fsnotify_group *group) +{ + if (atomic_dec_and_test(&group->refcnt)) + fsnotify_final_destroy_group(group); +} +EXPORT_SYMBOL_GPL(fsnotify_put_group); + +/* + * Create a new fsnotify_group and hold a reference for the group returned. + */ +struct fsnotify_group *fsnotify_alloc_group(const struct fsnotify_ops *ops) +{ + struct fsnotify_group *group; + + group = kzalloc(sizeof(struct fsnotify_group), GFP_KERNEL); + if (!group) + return ERR_PTR(-ENOMEM); + + /* set to 0 when there a no external references to this group */ + atomic_set(&group->refcnt, 1); + atomic_set(&group->num_marks, 0); + + mutex_init(&group->notification_mutex); + INIT_LIST_HEAD(&group->notification_list); + init_waitqueue_head(&group->notification_waitq); + group->max_events = UINT_MAX; + + mutex_init(&group->mark_mutex); + INIT_LIST_HEAD(&group->marks_list); + + group->ops = ops; + + return group; +} +EXPORT_SYMBOL_GPL(fsnotify_alloc_group); + +int fsnotify_fasync(int fd, struct file *file, int on) +{ + struct fsnotify_group *group = file->private_data; + + return fasync_helper(fd, file, on, &group->fsn_fa) >= 0 ? 0 : -EIO; +} diff --git a/pool/shard006/C/0118091_nucleo_hal_bsp.c b/pool/shard006/C/0118091_nucleo_hal_bsp.c new file mode 100644 index 0000000000000000000000000000000000000000..f6eccb6637e6071e1d8355627198f7af8eeccce5 --- /dev/null +++ b/pool/shard006/C/0118091_nucleo_hal_bsp.c @@ -0,0 +1,169 @@ +/* Includes ------------------------------------------------------------------*/ +#include "stm32f4xx_hal.h" + +/* Private variables ---------------------------------------------------------*/ +UART_HandleTypeDef huart2; + +/* Private function prototypes -----------------------------------------------*/ +void SystemClock_Config(void); +void MX_GPIO_Init(void); +void MX_USART2_UART_Init(void); + +void Nucleo_BSP_Init() { + /* Configure the system clock */ + SystemClock_Config(); + + /* Initialize all configured peripherals */ + MX_GPIO_Init(); + MX_USART2_UART_Init(); +} + +/** System Clock Configuration +*/ +void SystemClock_Config(void) +{ + + RCC_OscInitTypeDef RCC_OscInitStruct; + RCC_ClkInitTypeDef RCC_ClkInitStruct; + + __HAL_RCC_PWR_CLK_ENABLE(); + + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); + + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.LSEState = RCC_LSE_ON; + RCC_OscInitStruct.HSIState = RCC_HSI_ON; + RCC_OscInitStruct.HSICalibrationValue = 16; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; + RCC_OscInitStruct.PLL.PLLM = 16; + RCC_OscInitStruct.PLL.PLLN = 336; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; + RCC_OscInitStruct.PLL.PLLQ = 2; + RCC_OscInitStruct.PLL.PLLR = 2; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK + |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2); + + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_LSE, RCC_MCODIV_1); + + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); + + HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); + + /* SysTick_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); +} + +/* USART2 init function */ +void MX_USART2_UART_Init(void) +{ + + huart2.Instance = USART2; + huart2.Init.BaudRate = 38400; + huart2.Init.WordLength = UART_WORDLENGTH_8B; + huart2.Init.StopBits = UART_STOPBITS_1; + huart2.Init.Parity = UART_PARITY_NONE; + huart2.Init.Mode = UART_MODE_TX_RX; + huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart2.Init.OverSampling = UART_OVERSAMPLING_16; + HAL_UART_Init(&huart2); +} + +/** Configure pins as + * Analog + * Input + * Output + * EVENT_OUT + * EXTI +*/ +void MX_GPIO_Init(void) +{ + + GPIO_InitTypeDef GPIO_InitStruct; + + /* GPIO Ports Clock Enable */ + __GPIOC_CLK_ENABLE(); + __GPIOH_CLK_ENABLE(); + __GPIOA_CLK_ENABLE(); + __GPIOB_CLK_ENABLE(); + + /*Configure GPIO pin : PC13 */ + GPIO_InitStruct.Pin = GPIO_PIN_13; + GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /*Configure GPIO pin : LD2_Pin */ + GPIO_InitStruct.Pin = LD2_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_LOW; + HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct); + + HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); +} + +void MX_GPIO_Deinit(void) +{ + GPIO_InitTypeDef GPIO_InitStruct; + + /* Configure all GPIO as analog to reduce current consumption on non used IOs */ + /* Enable GPIOs clock */ + /* Warning : Reconfiguring all GPIO will close the connection with the debugger */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Pin = GPIO_PIN_All; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* Disable GPIOs clock */ + __HAL_RCC_GPIOA_CLK_DISABLE(); + __HAL_RCC_GPIOB_CLK_DISABLE(); + __HAL_RCC_GPIOC_CLK_DISABLE(); +} +/* USER CODE BEGIN 4 */ + +/* USER CODE END 4 */ + +#ifdef USE_FULL_ASSERT + +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + /* USER CODE END 6 */ + +} + +#endif + +/** + * @} + */ + +/** + * @} +*/ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0118092_mkdir.c b/pool/shard006/C/0118092_mkdir.c new file mode 100644 index 0000000000000000000000000000000000000000..8a18545023084b91793c7dda87b5188c639e32cf --- /dev/null +++ b/pool/shard006/C/0118092_mkdir.c @@ -0,0 +1,93 @@ +/* On some systems, mkdir ("foo/", 0700) fails because of the trailing + slash. On those systems, this wrapper removes the trailing slash. + + Copyright (C) 2001, 2003, 2006, 2008-2016 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ + +/* written by Jim Meyering */ + +#include + +/* Specification. */ +#include + +#include +#include +#include +#include + +#include "dirname.h" + +/* Disable the definition of mkdir to rpl_mkdir (from the + substitute) in this file. Otherwise, we'd get an endless recursion. */ +#undef mkdir + +/* mingw's _mkdir() function has 1 argument, but we pass 2 arguments. + Additionally, it declares _mkdir (and depending on compile flags, an + alias mkdir), only in the nonstandard includes and , + which are included in the override. */ +#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ +# define mkdir(name,mode) _mkdir (name) +# define maybe_unused _GL_UNUSED +#else +# define maybe_unused /* empty */ +#endif + +/* This function is required at least for NetBSD 1.5.2. */ + +int +rpl_mkdir (char const *dir, mode_t mode maybe_unused) +{ + int ret_val; + char *tmp_dir; + size_t len = strlen (dir); + + if (len && dir[len - 1] == '/') + { + tmp_dir = strdup (dir); + if (!tmp_dir) + { + /* Rather than rely on strdup-posix, we set errno ourselves. */ + errno = ENOMEM; + return -1; + } + strip_trailing_slashes (tmp_dir); + } + else + { + tmp_dir = (char *) dir; + } +#if FUNC_MKDIR_DOT_BUG + /* Additionally, cygwin 1.5 mistakenly creates a directory "d/./". */ + { + char *last = last_component (tmp_dir); + if (*last == '.' && (last[1] == '\0' + || (last[1] == '.' && last[2] == '\0'))) + { + struct stat st; + if (stat (tmp_dir, &st) == 0) + errno = EEXIST; + return -1; + } + } +#endif /* FUNC_MKDIR_DOT_BUG */ + + ret_val = mkdir (tmp_dir, mode); + + if (tmp_dir != dir) + free (tmp_dir); + + return ret_val; +} diff --git a/pool/shard006/C/0118095_isrchc.c b/pool/shard006/C/0118095_isrchc.c new file mode 100644 index 0000000000000000000000000000000000000000..3dd5221209b9c5003d8ac3d0ffe55a1bbae1288a --- /dev/null +++ b/pool/shard006/C/0118095_isrchc.c @@ -0,0 +1,155 @@ +/* isrchc.f -- translated by f2c (version 19980913). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#include "f2c.h" + +/* $Procedure ISRCHC ( Search in a character array ) */ +integer isrchc_(char *value, integer *ndim, char *array, ftnlen value_len, + ftnlen array_len) +{ + /* System generated locals */ + integer ret_val, i__1; + + /* Builtin functions */ + integer s_cmp(char *, char *, ftnlen, ftnlen); + + /* Local variables */ + integer i__; + +/* $ Abstract */ + +/* Search for a given value within a character string array. Return */ +/* the index of the first matching array entry, or zero if the key */ +/* value was not found. */ + +/* $ Disclaimer */ + +/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ +/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ +/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ +/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ +/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ +/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ +/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ +/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ +/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ +/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ + +/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ +/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ +/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ +/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ +/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ +/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ + +/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ +/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ +/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ +/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ + +/* $ Required_Reading */ + +/* None. */ + +/* $ Keywords */ + +/* ARRAY, SEARCH */ + +/* $ Declarations */ +/* $ Brief_I/O */ + +/* VARIABLE I/O DESCRIPTION */ +/* -------- --- -------------------------------------------------- */ +/* VALUE I Key value to be found in ARRAY. */ +/* NDIM I Dimension of ARRAY. */ +/* ARRAY I Character string array to search. */ + +/* The function returns the index of the first matching array */ +/* element or zero if the value is not found. */ + +/* $ Detailed_Input */ + +/* VALUE is the key value to be found in the array. */ + +/* NDIM is the dimension of the array. */ + +/* ARRAY is the character array to be searched. */ + +/* $ Detailed_Output */ + +/* The function returns the index of the first matching array */ +/* element in ARRAY. If VALUE is not found, ISRCHC is zero. */ + +/* $ Parameters */ + +/* None. */ + +/* $ Particulars */ + +/* None. */ + +/* $ Examples */ + +/* The following table shows the value of ISRCHC given the contents */ +/* of ARRAY and VALUE: */ + +/* ARRAY VALUE ISRCHC */ +/* ----------------- ----- ------ */ +/* '1', '0', '4', '2' '4' 3 */ +/* '1', '0', '4', '2' '2' 4 */ +/* '1', '0', '4', '2' '3' 0 */ + +/* $ Restrictions */ + +/* None. */ + +/* $ Exceptions */ + +/* Error free. */ + +/* 1) If NDIM < 1 the function value is zero. */ + +/* $ Files */ + +/* None */ + +/* $ Author_and_Institution */ + +/* W.M. Owen (JPL) */ + +/* $ Literature_References */ + +/* None */ + +/* $ Version */ + +/* - SPICELIB Version 1.0.1, 10-MAR-1992 (WLT) */ + +/* Comment section for permuted index source lines was added */ +/* following the header. */ + +/* - SPICELIB Version 1.0.0, 31-JAN-1990 (WMO) */ + +/* -& */ +/* $ Index_Entries */ + +/* search in a character array */ + +/* -& */ + +/* Local variables */ + + ret_val = 0; + i__1 = *ndim; + for (i__ = 1; i__ <= i__1; ++i__) { + if (s_cmp(array + (i__ - 1) * array_len, value, array_len, value_len) + == 0) { + ret_val = i__; + return ret_val; + } + } + return ret_val; +} /* isrchc_ */ + diff --git a/pool/shard006/C/0118099_0X0079.c b/pool/shard006/C/0118099_0X0079.c new file mode 100644 index 0000000000000000000000000000000000000000..9c8480ddb564f9e6b58508bbd7339797dd64087b --- /dev/null +++ b/pool/shard006/C/0118099_0X0079.c @@ -0,0 +1,17 @@ +/* 数组与指针 */ +#include + +int main(void) +{ + int i = 0; + int a[5] = {1, 2, 3, 4, 5}; + int *p = a; + + for (i = 0; i < 5; i++) { + printf("&a[%d] = %p p+%d = %p\n", i, &a[i], i, p + i); + } + + printf("&a = %p &p = %p\n", &a, &p); + + return 0; +} diff --git a/pool/shard006/C/0118101_ZGetWGPort.c b/pool/shard006/C/0118101_ZGetWGPort.c new file mode 100644 index 0000000000000000000000000000000000000000..d1a7a98f3e210a0b9f2e33f9d0c3777716d206f4 --- /dev/null +++ b/pool/shard006/C/0118101_ZGetWGPort.c @@ -0,0 +1,42 @@ +/* This file is part of the Project Athena Zephyr Notification System. + * It contains source for the ZGetWGPort function. + * + * Created by: Robert French + * + * Copyright (c) 1987 by the Massachusetts Institute of Technology. + * For copying and distribution information, see the file + * "mit-copyright.h". + */ + +#include "internal.h" + +int ZGetWGPort() +{ + char *envptr, name[128]; + FILE *fp; + int wgport; +#ifdef WIN32 + long int buffsize= 128; + char tempdir[buffsize]; +#endif + envptr = getenv("WGFILE"); + if (!envptr) { +#ifdef WIN32 + GetTempPath(buffsize,tempdir); + GetTempFileName(tempdir,"wg.",0,name); +#else + (void) sprintf(name, "/tmp/wg.%d", getuid()); +#endif + envptr = name; + } + if (!(fp = fopen(envptr, "r"))) + return (-1); + + /* if fscanf fails, return -1 via wgport */ + if (fscanf(fp, "%d", &wgport) != 1) + wgport = -1; + + (void) fclose(fp); + + return (wgport); +} diff --git a/pool/shard006/C/0118102_main-repair.c b/pool/shard006/C/0118102_main-repair.c new file mode 100644 index 0000000000000000000000000000000000000000..6fefd0be2dde68aed64979fc10e2ec7e222e8c34 --- /dev/null +++ b/pool/shard006/C/0118102_main-repair.c @@ -0,0 +1,70 @@ +/************************************************************************** +** Re-Pair / Des-Pair +** Compressor and decompressor based on recursive pairing. +** +** Version N/A (On Github) -- November 13, 2015 +** +** Copyright (C) 2003, 2007, 2015 by Raymond Wan, All rights reserved. +** Contact: rwan.work@gmail.com +** Organization: Division of Life Science, Faculty of Science, Hong Kong +** University of Science and Technology, Hong Kong +** +** This file is part of Re-Pair / Des-Pair. +** +** Re-Pair / Des-Pair 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. +** +** Re-Pair / Des-Pair 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 Re-Pair / Des-Pair; if not, see +** . +**************************************************************************/ + + +#include +#include + +#include "common-def.h" +#include "wmalloc.h" +#include "repair-defn.h" +#include "repair.h" +#include "main-repair.h" + +R_INT main (R_INT argc, R_CHAR *argv[]) { + PROG_INFO *prog_struct = NULL; + BLOCK_INFO *block_struct = NULL; + ARGS_INFO *args_struct = NULL; + +#ifdef COUNT_MALLOC + initWMalloc (); +#endif + prog_struct = wmalloc (sizeof (PROG_INFO)); + block_struct = wmalloc (sizeof (BLOCK_INFO)); + args_struct = wmalloc (sizeof (ARGS_INFO)); + + prog_struct -> args_struct = parseArguments (argc, argv, args_struct); + + initRepair (prog_struct, block_struct); + + executeRepair_File (prog_struct, block_struct); + + uninitRepair (prog_struct, block_struct); + + wfree (prog_struct); + wfree (block_struct); + wfree (args_struct); +#ifdef COUNT_MALLOC + printWMalloc (); +#endif + + return (EXIT_SUCCESS); +} + + + diff --git a/pool/shard006/C/0118107_smack_access.c b/pool/shard006/C/0118107_smack_access.c new file mode 100644 index 0000000000000000000000000000000000000000..2e0b83e77ffea727375a23e0abe29e894573a251 --- /dev/null +++ b/pool/shard006/C/0118107_smack_access.c @@ -0,0 +1,374 @@ +/* + * Copyright (C) 2007 Casey Schaufler + * + * 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, version 2. + * + * Author: + * Casey Schaufler + * + */ + +#include +#include +#include +#include "smack.h" + +struct smack_known smack_known_huh = { + .smk_next = NULL, + .smk_known = "?", + .smk_secid = 2, + .smk_cipso = NULL, +}; + +struct smack_known smack_known_hat = { + .smk_next = &smack_known_huh, + .smk_known = "^", + .smk_secid = 3, + .smk_cipso = NULL, +}; + +struct smack_known smack_known_star = { + .smk_next = &smack_known_hat, + .smk_known = "*", + .smk_secid = 4, + .smk_cipso = NULL, +}; + +struct smack_known smack_known_floor = { + .smk_next = &smack_known_star, + .smk_known = "_", + .smk_secid = 5, + .smk_cipso = NULL, +}; + +struct smack_known smack_known_invalid = { + .smk_next = &smack_known_floor, + .smk_known = "", + .smk_secid = 6, + .smk_cipso = NULL, +}; + +struct smack_known smack_known_web = { + .smk_next = &smack_known_invalid, + .smk_known = "@", + .smk_secid = 7, + .smk_cipso = NULL, +}; + +struct smack_known *smack_known = &smack_known_web; + +/* + * The initial value needs to be bigger than any of the + * known values above. + */ +static u32 smack_next_secid = 10; + +/** + * smk_access - determine if a subject has a specific access to an object + * @subject_label: a pointer to the subject's Smack label + * @object_label: a pointer to the object's Smack label + * @request: the access requested, in "MAY" format + * + * This function looks up the subject/object pair in the + * access rule list and returns 0 if the access is permitted, + * non zero otherwise. + * + * Even though Smack labels are usually shared on smack_list + * labels that come in off the network can't be imported + * and added to the list for locking reasons. + * + * Therefore, it is necessary to check the contents of the labels, + * not just the pointer values. Of course, in most cases the labels + * will be on the list, so checking the pointers may be a worthwhile + * optimization. + */ +int smk_access(char *subject_label, char *object_label, int request) +{ + u32 may = MAY_NOT; + struct smk_list_entry *sp; + struct smack_rule *srp; + + /* + * Hardcoded comparisons. + * + * A star subject can't access any object. + */ + if (subject_label == smack_known_star.smk_known || + strcmp(subject_label, smack_known_star.smk_known) == 0) + return -EACCES; + /* + * An internet object can be accessed by any subject. + * Tasks cannot be assigned the internet label. + * An internet subject can access any object. + */ + if (object_label == smack_known_web.smk_known || + subject_label == smack_known_web.smk_known || + strcmp(object_label, smack_known_web.smk_known) == 0 || + strcmp(subject_label, smack_known_web.smk_known) == 0) + return 0; + /* + * A star object can be accessed by any subject. + */ + if (object_label == smack_known_star.smk_known || + strcmp(object_label, smack_known_star.smk_known) == 0) + return 0; + /* + * An object can be accessed in any way by a subject + * with the same label. + */ + if (subject_label == object_label || + strcmp(subject_label, object_label) == 0) + return 0; + /* + * A hat subject can read any object. + * A floor object can be read by any subject. + */ + if ((request & MAY_ANYREAD) == request) { + if (object_label == smack_known_floor.smk_known || + strcmp(object_label, smack_known_floor.smk_known) == 0) + return 0; + if (subject_label == smack_known_hat.smk_known || + strcmp(subject_label, smack_known_hat.smk_known) == 0) + return 0; + } + /* + * Beyond here an explicit relationship is required. + * If the requested access is contained in the available + * access (e.g. read is included in readwrite) it's + * good. + */ + for (sp = smack_list; sp != NULL; sp = sp->smk_next) { + srp = &sp->smk_rule; + + if (srp->smk_subject == subject_label || + strcmp(srp->smk_subject, subject_label) == 0) { + if (srp->smk_object == object_label || + strcmp(srp->smk_object, object_label) == 0) { + may = srp->smk_access; + break; + } + } + } + /* + * This is a bit map operation. + */ + if ((request & may) == request) + return 0; + + return -EACCES; +} + +/** + * smk_curacc - determine if current has a specific access to an object + * @object_label: a pointer to the object's Smack label + * @request: the access requested, in "MAY" format + * + * This function checks the current subject label/object label pair + * in the access rule list and returns 0 if the access is permitted, + * non zero otherwise. It allows that current may have the capability + * to override the rules. + */ +int smk_curacc(char *obj_label, u32 mode) +{ + int rc; + + rc = smk_access(current_security(), obj_label, mode); + if (rc == 0) + return 0; + + /* + * Return if a specific label has been designated as the + * only one that gets privilege and current does not + * have that label. + */ + if (smack_onlycap != NULL && smack_onlycap != current->cred->security) + return rc; + + if (capable(CAP_MAC_OVERRIDE)) + return 0; + + return rc; +} + +static DEFINE_MUTEX(smack_known_lock); + +/** + * smk_import_entry - import a label, return the list entry + * @string: a text string that might be a Smack label + * @len: the maximum size, or zero if it is NULL terminated. + * + * Returns a pointer to the entry in the label list that + * matches the passed string, adding it if necessary. + */ +struct smack_known *smk_import_entry(const char *string, int len) +{ + struct smack_known *skp; + char smack[SMK_LABELLEN]; + int found; + int i; + + if (len <= 0 || len > SMK_MAXLEN) + len = SMK_MAXLEN; + + for (i = 0, found = 0; i < SMK_LABELLEN; i++) { + if (found) + smack[i] = '\0'; + else if (i >= len || string[i] > '~' || string[i] <= ' ' || + string[i] == '/') { + smack[i] = '\0'; + found = 1; + } else + smack[i] = string[i]; + } + + if (smack[0] == '\0') + return NULL; + + mutex_lock(&smack_known_lock); + + for (skp = smack_known; skp != NULL; skp = skp->smk_next) + if (strncmp(skp->smk_known, smack, SMK_MAXLEN) == 0) + break; + + if (skp == NULL) { + skp = kzalloc(sizeof(struct smack_known), GFP_KERNEL); + if (skp != NULL) { + skp->smk_next = smack_known; + strncpy(skp->smk_known, smack, SMK_MAXLEN); + skp->smk_secid = smack_next_secid++; + skp->smk_cipso = NULL; + spin_lock_init(&skp->smk_cipsolock); + /* + * Make sure that the entry is actually + * filled before putting it on the list. + */ + smp_mb(); + smack_known = skp; + } + } + + mutex_unlock(&smack_known_lock); + + return skp; +} + +/** + * smk_import - import a smack label + * @string: a text string that might be a Smack label + * @len: the maximum size, or zero if it is NULL terminated. + * + * Returns a pointer to the label in the label list that + * matches the passed string, adding it if necessary. + */ +char *smk_import(const char *string, int len) +{ + struct smack_known *skp; + + skp = smk_import_entry(string, len); + if (skp == NULL) + return NULL; + return skp->smk_known; +} + +/** + * smack_from_secid - find the Smack label associated with a secid + * @secid: an integer that might be associated with a Smack label + * + * Returns a pointer to the appropraite Smack label if there is one, + * otherwise a pointer to the invalid Smack label. + */ +char *smack_from_secid(const u32 secid) +{ + struct smack_known *skp; + + for (skp = smack_known; skp != NULL; skp = skp->smk_next) + if (skp->smk_secid == secid) + return skp->smk_known; + + /* + * If we got this far someone asked for the translation + * of a secid that is not on the list. + */ + return smack_known_invalid.smk_known; +} + +/** + * smack_to_secid - find the secid associated with a Smack label + * @smack: the Smack label + * + * Returns the appropriate secid if there is one, + * otherwise 0 + */ +u32 smack_to_secid(const char *smack) +{ + struct smack_known *skp; + + for (skp = smack_known; skp != NULL; skp = skp->smk_next) + if (strncmp(skp->smk_known, smack, SMK_MAXLEN) == 0) + return skp->smk_secid; + return 0; +} + +/** + * smack_from_cipso - find the Smack label associated with a CIPSO option + * @level: Bell & LaPadula level from the network + * @cp: Bell & LaPadula categories from the network + * @result: where to put the Smack value + * + * This is a simple lookup in the label table. + * + * This is an odd duck as far as smack handling goes in that + * it sends back a copy of the smack label rather than a pointer + * to the master list. This is done because it is possible for + * a foreign host to send a smack label that is new to this + * machine and hence not on the list. That would not be an + * issue except that adding an entry to the master list can't + * be done at that point. + */ +void smack_from_cipso(u32 level, char *cp, char *result) +{ + struct smack_known *kp; + char *final = NULL; + + for (kp = smack_known; final == NULL && kp != NULL; kp = kp->smk_next) { + if (kp->smk_cipso == NULL) + continue; + + spin_lock_bh(&kp->smk_cipsolock); + + if (kp->smk_cipso->smk_level == level && + memcmp(kp->smk_cipso->smk_catset, cp, SMK_LABELLEN) == 0) + final = kp->smk_known; + + spin_unlock_bh(&kp->smk_cipsolock); + } + if (final == NULL) + final = smack_known_huh.smk_known; + strncpy(result, final, SMK_MAXLEN); + return; +} + +/** + * smack_to_cipso - find the CIPSO option to go with a Smack label + * @smack: a pointer to the smack label in question + * @cp: where to put the result + * + * Returns zero if a value is available, non-zero otherwise. + */ +int smack_to_cipso(const char *smack, struct smack_cipso *cp) +{ + struct smack_known *kp; + + for (kp = smack_known; kp != NULL; kp = kp->smk_next) + if (kp->smk_known == smack || + strcmp(kp->smk_known, smack) == 0) + break; + + if (kp == NULL || kp->smk_cipso == NULL) + return -ENOENT; + + memcpy(cp, kp->smk_cipso, sizeof(struct smack_cipso)); + return 0; +} diff --git a/pool/shard006/C/0118109_add.c b/pool/shard006/C/0118109_add.c new file mode 100644 index 0000000000000000000000000000000000000000..1da01188dbcfd44a487f1c564b6e144415b2a88f --- /dev/null +++ b/pool/shard006/C/0118109_add.c @@ -0,0 +1,44 @@ +/* + Copyright (C) 2020 Daniel Schultz + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "fmpz_mpoly_factor.h" + + +int fmpz_mpoly_factor_add( + fmpz_mpoly_factor_t A, + const fmpz_mpoly_factor_t B, + const fmpz_mpoly_factor_t C, + const fmpz_mpoly_ctx_t ctx) +{ + int success = 0; + fmpz_mpoly_t b, c; + + fmpz_mpoly_init(b, ctx); + fmpz_mpoly_init(c, ctx); + + if (!fmpz_mpoly_factor_expand(b, B, ctx)) + goto cleanup; + if (!fmpz_mpoly_factor_expand(c, C, ctx)) + goto cleanup; + + fmpz_mpoly_factor_fit_length(A, 1, ctx); + fmpz_one(A->constant); + fmpz_mpoly_add(A->poly + 0, b, c, ctx); + fmpz_one(A->exp + 0); + A->num = 1; + success = 1; + +cleanup: + + fmpz_mpoly_clear(c, ctx); + fmpz_mpoly_clear(b, ctx); + return success; +} diff --git a/pool/shard006/C/0118111_ulib.c b/pool/shard006/C/0118111_ulib.c new file mode 100644 index 0000000000000000000000000000000000000000..fe566a818609c9c9bec2324fd94e9c0594b88258 --- /dev/null +++ b/pool/shard006/C/0118111_ulib.c @@ -0,0 +1,105 @@ +#include "types.h" +#include "stat.h" +#include "fcntl.h" +#include "user.h" +#include "x86.h" + +char* +strcpy(char *s, char *t) +{ + char *os; + + os = s; + while((*s++ = *t++) != 0) + ; + return os; +} + +int +strcmp(const char *p, const char *q) +{ + while(*p && *p == *q) + p++, q++; + return (uchar)*p - (uchar)*q; +} + +uint +strlen(char *s) +{ + int n; + + for(n = 0; s[n]; n++) + ; + return n; +} + +void* +memset(void *dst, int c, uint n) +{ + stosb(dst, c, n); + return dst; +} + +char* +strchr(const char *s, char c) +{ + for(; *s; s++) + if(*s == c) + return (char*)s; + return 0; +} + +char* +gets(char *buf, int max) +{ + int i, cc; + char c; + + for(i=0; i+1 < max; ){ + cc = read(0, &c, 1); + if(cc < 1) + break; + buf[i++] = c; + if(c == '\n' || c == '\r') + break; + } + buf[i] = '\0'; + return buf; +} + +int +stat(char *n, struct stat *st) +{ + int fd; + int r; + + fd = openNoFollow(n, O_RDONLY); + if(fd < 0) + return -1; + r = fstat(fd, st); + close(fd); + return r; +} + +int +atoi(const char *s) +{ + int n; + + n = 0; + while('0' <= *s && *s <= '9') + n = n*10 + *s++ - '0'; + return n; +} + +void* +memmove(void *vdst, void *vsrc, int n) +{ + char *dst, *src; + + dst = vdst; + src = vsrc; + while(n-- > 0) + *dst++ = *src++; + return vdst; +} diff --git a/pool/shard006/C/0118115_main.c b/pool/shard006/C/0118115_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8c85bb14732b7b408fc11dbd73102e90f878b41b --- /dev/null +++ b/pool/shard006/C/0118115_main.c @@ -0,0 +1,205 @@ +/** @brief This is a FreeRTOS application example with dynamic memory allocation. + */ + +/* NOTA: El stack de elementos dinámicos del RTOS está definido en RamLoc40_16! Ver heap_4.c + * Solo importante si configSUPPORT_DYNAMIC_ALLOCATION no esta definido en FreeRTOSConfig.h + * o fue seteado en 1. Si está en 0 no se utiliza el stack y esto carece de sentido */ + +/*==================[inclusions]=============================================*/ + +#include "main.h" + +#include "FreeRTOSConfig.h" +#include "ipc.h" +#include "board.h" +#include "cr_start_m0.h" + +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + + +/*==================[macros and definitions]=================================*/ + +/*==================[internal data declaration]==============================*/ + +static SemaphoreHandle_t xSemaphoreIRQ; + +/* --------------------------- IPC ---------------------------- */ + +__attribute__ ((section(".ipcM4"))) ipcrb_t ipcsend; +__attribute__ ((section(".ipcM4"))) static uint8_t ipcbufsend[sizeof(ipcmsg_t) * MAX_MSG]; + +__attribute__ ((section(".ipcM0"))) ipcrb_t ipcreceive; +__attribute__ ((section(".ipcM0"))) static uint8_t ipcbufreceive[sizeof(ipcmsg_t) * MAX_MSG]; + +/*==================[internal functions declaration]=========================*/ + +/** @brief hardware initialization function + * @return none + */ +static void initHardware(void); + +static void SendIPCMsg_ProcessingComplete(float * ptr, uint32_t nsamples); + +static void FIR_Filter(float * ptr, uint32_t nsamples); + +/*==================[internal data definition]===============================*/ + +typedef struct taskData{ + uint8_t numbled; + uint32_t tiempo; +}taskData; + +taskData t1 = {5, 100}; + +uint8_t numled = 4; + +/*==================[external data definition]===============================*/ + +/*==================[internal functions definition]==========================*/ + +static void initHardware(void) +{ + Board_Init(); + SystemCoreClockUpdate(); + SysTick_Config(SystemCoreClock / 1000); + + IPC_CreateStatic(&ipcsend, ipcbufsend); + IPC_CreateStatic(&ipcreceive, ipcbufreceive); + + /* Start Cortex-M0 core */ + cr_start_m0(SLAVE_M0APP, (uint8_t *)0x1B000000); // le pasa la dirección de memoria en donde esta la imagen de la aplicación del Cortex-M0 + + /* Enable IRQ for M0 Core */ + NVIC_EnableIRQ(M0APP_IRQn); +} + +static void SendIPCMsg_ProcessingComplete(float * ptr, uint32_t nsamples) +{ + ipcmsg_t msg; + memset(&msg, 0, sizeof(ipcmsg_t)); + + msg.senderid_t.cid = M4; + msg.senderid_t.pid = Tarea2; + msg.opcode = Code2; + msg.operand[0] = (operand_t) ptr; + msg.operand[1] = nsamples; + + IPC_SendMsg(&ipcsend ,&msg); +} + +static void FIR_Filter(float * ptr, uint32_t nsamples) +{ + /* + * + * Implementación filtro FIR + * + */ +} + +/*==================[interrupt handling]==========================*/ + +void M0APP_IRQHandler(void) +{ + /* Clear the event created by the remote core */ + LPC_CREG->M0APPTXEVENT = 0; /* ACK */ + + /* Disable IRQ for M0 Core while it's being handled */ + NVIC_DisableIRQ(M0APP_IRQn); + + long lHigherPriorityTaskWoken = pdFALSE; + + xSemaphoreGiveFromISR( xSemaphoreIRQ, &lHigherPriorityTaskWoken ); + portEND_SWITCHING_ISR( lHigherPriorityTaskWoken ); /* depends on the port for the uC being used + more info -> "http://www.freertos.org/FAQISR.html" */ +} + +/*==================[tasks definition]==========================*/ + +static void taskledCIAA(void * a) +{ + taskData * t = (taskData *) a; /* el puntero a void es un comodín. Hay que castearlo para que funcione */ + + while (1) { + Board_LED_Toggle(t->numbled); + vTaskDelay((t->tiempo) / portTICK_RATE_MS); + } +} + +static void taskM0IRQHandler(void * a) +{ + ipcmsg_t msg; + float * ptr; // puntero a la direccion de memoria donde se encuentra almacenado el array con las muestras + uint32_t nsamples; // numero de muestras a procesar + + xSemaphoreIRQ = xSemaphoreCreateBinary(); + + if( xSemaphoreIRQ == NULL ) + { + while(1) + { + /* There was insufficient FreeRTOS heap available for the semaphore to + be created uartd_successfully. */ + } + } + + while (1) { + + xSemaphoreTake( xSemaphoreIRQ , portMAX_DELAY ); /* Semaphore blocks indefinitely */ + + while(IPC_MsgWaiting(&ipcreceive)) + { + memset(&msg, 0, sizeof(ipcmsg_t)); + + IPC_Pop(&ipcreceive, &msg); + + ptr = (float *) msg.operand[0]; + nsamples = msg.operand[1]; + + FIR_Filter(ptr, nsamples); + + SendIPCMsg_ProcessingComplete(ptr, nsamples); + __SEV(); + } + + /* Enable IRQ for M0 Core */ + NVIC_EnableIRQ(M0APP_IRQn); + } +} + +/*==================[external functions definition]==========================*/ + +int main(void) +{ + initHardware(); + + xTaskCreate( + taskledCIAA, /* nombre de la tarea como se declaró */ + (const char *)"task", /* string descriptivo opcional */ + configMINIMAL_STACK_SIZE*2, /* tamaño de la pila en palabras no bytes */ + &t1, /* parámetro que le pasas a la función (void * a) -> comodín */ + tskIDLE_PRIORITY+1, /* prioridad (d2e 1 en adelante) */ + 0); + + xTaskCreate( + taskM0IRQHandler, /* nombre de la tarea como se declaró */ + (const char *)"task", /* string descriptivo opcional */ + configMINIMAL_STACK_SIZE*2, /* tamaño de la pila en palabras no bytes */ + 0, /* parámetro que le pasas a la función (void * a) -> comodín */ + tskIDLE_PRIORITY+1, /* prioridad (d2e 1 en adelante) */ + 0); + + vTaskStartScheduler(); + + while (1) + { + /* + * Infinite loop + */ + } +} + +/** @} doxygen end group definition */ + +/*==================[end of file]============================================*/ diff --git a/pool/shard006/C/0118119_pwrseqcmd.c b/pool/shard006/C/0118119_pwrseqcmd.c new file mode 100644 index 0000000000000000000000000000000000000000..7277a5d1e2a59ca1c747ef1548e2e0cb2b84aab7 --- /dev/null +++ b/pool/shard006/C/0118119_pwrseqcmd.c @@ -0,0 +1,153 @@ +/****************************************************************************** + * + * Copyright( c ) 2009-2013 Realtek Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA + * + * The full GNU General Public License is included in this distribution in the + * file called LICENSE. + * + * Contact Information: + * wlanfae + * Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park, + * Hsinchu 300, Taiwan. + * + * + * Bug Fixes and enhancements for Linux Kernels >= 3.2 + * by Benjamin Porter + * + * Project homepage: https://github.com/FreedomBen/rtl8188ce-linux-driver + * + * + * + * Bug Fixes and enhancements for Linux Kernels >= 3.2 + * by Benjamin Porter + * + * Project homepage: https://github.com/FreedomBen/rtl8188ce-linux-driver + * + * + * Larry Finger + * + *****************************************************************************/ + +#include "pwrseq.h" + + +/* Description: + * This routine deal with the Power Configuration CMDs + * parsing for RTL8723/RTL8188E Series IC. + * Assumption: + * We should follow specific format which was released from HW SD. + * + * 2011.07.07, added by Roger. + */ + +bool rtl88_hal_pwrseqcmdparsing( struct rtl_priv *rtlpriv, u8 cut_version, + u8 fab_version, u8 interface_type, + struct wlan_pwr_cfg pwrcfgcmd[] ) +{ + struct wlan_pwr_cfg cmd = {0}; + bool polling_bit = false; + u32 ary_idx = 0; + u8 val = 0; + u32 offset = 0; + u32 polling_count = 0; + u32 max_polling_cnt = 5000; + + do { + cmd = pwrcfgcmd[ary_idx]; + RT_TRACE( rtlpriv, COMP_INIT, DBG_TRACE, + "rtl88_hal_pwrseqcmdparsing(): offset(%#x), cut_msk(%#x), fab_msk(%#x)," + "interface_msk(%#x), base(%#x), cmd(%#x), msk(%#x), val(%#x)\n", + GET_PWR_CFG_OFFSET( cmd ), + GET_PWR_CFG_CUT_MASK( cmd ), + GET_PWR_CFG_FAB_MASK( cmd ), + GET_PWR_CFG_INTF_MASK( cmd ), + GET_PWR_CFG_BASE( cmd ), + GET_PWR_CFG_CMD( cmd ), + GET_PWR_CFG_MASK( cmd ), + GET_PWR_CFG_VALUE( cmd ) ); + + if ( ( GET_PWR_CFG_FAB_MASK( cmd ) & fab_version ) && + ( GET_PWR_CFG_CUT_MASK( cmd ) & cut_version ) && + ( GET_PWR_CFG_INTF_MASK( cmd ) & interface_type ) ) { + switch ( GET_PWR_CFG_CMD( cmd ) ) { + case PWR_CMD_READ: + RT_TRACE( rtlpriv, COMP_INIT, DBG_TRACE, + "rtl88_hal_pwrseqcmdparsing(): PWR_CMD_READ\n" ); + break; + case PWR_CMD_WRITE: { + RT_TRACE( rtlpriv, COMP_INIT, DBG_TRACE, + "rtl88_hal_pwrseqcmdparsing(): PWR_CMD_WRITE\n" ); + offset = GET_PWR_CFG_OFFSET( cmd ); + + /*Read the val from system register*/ + val = rtl_read_byte( rtlpriv, offset ); + val &= ( ~( GET_PWR_CFG_MASK( cmd ) ) ); + val |= ( GET_PWR_CFG_VALUE( cmd ) & + GET_PWR_CFG_MASK( cmd ) ); + + /*Write the val back to sytem register*/ + rtl_write_byte( rtlpriv, offset, val ); + } + break; + case PWR_CMD_POLLING: + RT_TRACE( rtlpriv, COMP_INIT, DBG_TRACE, + "rtl88_hal_pwrseqcmdparsing(): PWR_CMD_POLLING\n" ); + polling_bit = false; + offset = GET_PWR_CFG_OFFSET( cmd ); + + do { + val = rtl_read_byte( rtlpriv, offset ); + + val = val & GET_PWR_CFG_MASK( cmd ); + if ( val == ( GET_PWR_CFG_VALUE( cmd ) & + GET_PWR_CFG_MASK( cmd ) ) ) + polling_bit = true; + else + udelay( 10 ); + + if ( polling_count++ > max_polling_cnt ) { + RT_TRACE( rtlpriv, COMP_INIT, + DBG_LOUD, + "polling fail in pwrseqcmd\n" ); + return false; + } + } while ( !polling_bit ); + + break; + case PWR_CMD_DELAY: + RT_TRACE( rtlpriv, COMP_INIT, DBG_TRACE, + "rtl88_hal_pwrseqcmdparsing(): PWR_CMD_DELAY\n" ); + if ( GET_PWR_CFG_VALUE( cmd ) == PWRSEQ_DELAY_US ) + udelay( GET_PWR_CFG_OFFSET( cmd ) ); + else + mdelay( GET_PWR_CFG_OFFSET( cmd ) ); + break; + case PWR_CMD_END: + RT_TRACE( rtlpriv, COMP_INIT, DBG_TRACE, + "rtl88_hal_pwrseqcmdparsing(): PWR_CMD_END\n" ); + return true; + default: + RT_ASSERT( false, + "rtl88_hal_pwrseqcmdparsing(): Unknown CMD!!\n" ); + break; + } + } + + ary_idx++; + } while ( 1 ); + + return true; +} diff --git a/pool/shard006/C/0118122_c93.c b/pool/shard006/C/0118122_c93.c new file mode 100644 index 0000000000000000000000000000000000000000..917de65ebaa0bbe8a3129452338a4be434ddb949 --- /dev/null +++ b/pool/shard006/C/0118122_c93.c @@ -0,0 +1,202 @@ +/* + * Interplay C93 demuxer + * Copyright (c) 2007 Anssi Hannula + * + * 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 "avformat.h" +#include "internal.h" +#include "voc.h" +#include "libavutil/intreadwrite.h" + +typedef struct { + uint16_t index; + uint8_t length; + uint8_t frames; +} C93BlockRecord; + +typedef struct { + VocDecContext voc; + + C93BlockRecord block_records[512]; + int current_block; + + uint32_t frame_offsets[32]; + int current_frame; + int next_pkt_is_audio; + + AVStream *audio; +} C93DemuxContext; + +static int probe(AVProbeData *p) +{ + int i; + int index = 1; + if (p->buf_size < 16) + return 0; + for (i = 0; i < 16; i += 4) { + if (AV_RL16(p->buf + i) != index || !p->buf[i + 2] || !p->buf[i + 3]) + return 0; + index += p->buf[i + 2]; + } + return AVPROBE_SCORE_MAX; +} + +static int read_header(AVFormatContext *s) +{ + AVStream *video; + AVIOContext *pb = s->pb; + C93DemuxContext *c93 = s->priv_data; + int i; + int framecount = 0; + + for (i = 0; i < 512; i++) { + c93->block_records[i].index = avio_rl16(pb); + c93->block_records[i].length = avio_r8(pb); + c93->block_records[i].frames = avio_r8(pb); + if (c93->block_records[i].frames > 32) { + av_log(s, AV_LOG_ERROR, "too many frames in block\n"); + return AVERROR_INVALIDDATA; + } + framecount += c93->block_records[i].frames; + } + + /* Audio streams are added if audio packets are found */ + s->ctx_flags |= AVFMTCTX_NOHEADER; + + video = avformat_new_stream(s, NULL); + if (!video) + return AVERROR(ENOMEM); + + video->codec->codec_type = AVMEDIA_TYPE_VIDEO; + video->codec->codec_id = AV_CODEC_ID_C93; + video->codec->width = 320; + video->codec->height = 192; + /* 4:3 320x200 with 8 empty lines */ + video->sample_aspect_ratio = (AVRational) { 5, 6 }; + avpriv_set_pts_info(video, 64, 2, 25); + video->nb_frames = framecount; + video->duration = framecount; + video->start_time = 0; + + c93->current_block = 0; + c93->current_frame = 0; + c93->next_pkt_is_audio = 0; + return 0; +} + +#define C93_HAS_PALETTE 0x01 +#define C93_FIRST_FRAME 0x02 + +static int read_packet(AVFormatContext *s, AVPacket *pkt) +{ + AVIOContext *pb = s->pb; + C93DemuxContext *c93 = s->priv_data; + C93BlockRecord *br = &c93->block_records[c93->current_block]; + int datasize; + int ret, i; + + if (c93->next_pkt_is_audio) { + c93->current_frame++; + c93->next_pkt_is_audio = 0; + datasize = avio_rl16(pb); + if (datasize > 42) { + if (!c93->audio) { + c93->audio = avformat_new_stream(s, NULL); + if (!c93->audio) + return AVERROR(ENOMEM); + c93->audio->codec->codec_type = AVMEDIA_TYPE_AUDIO; + } + avio_skip(pb, 26); /* VOC header */ + ret = ff_voc_get_packet(s, pkt, c93->audio, datasize - 26); + if (ret > 0) { + pkt->stream_index = 1; + pkt->flags |= AV_PKT_FLAG_KEY; + return ret; + } + } + } + if (c93->current_frame >= br->frames) { + if (c93->current_block >= 511 || !br[1].length) + return AVERROR_EOF; + br++; + c93->current_block++; + c93->current_frame = 0; + } + + if (c93->current_frame == 0) { + avio_seek(pb, br->index * 2048, SEEK_SET); + for (i = 0; i < 32; i++) { + c93->frame_offsets[i] = avio_rl32(pb); + } + } + + avio_seek(pb,br->index * 2048 + + c93->frame_offsets[c93->current_frame], SEEK_SET); + datasize = avio_rl16(pb); /* video frame size */ + + ret = av_new_packet(pkt, datasize + 768 + 1); + if (ret < 0) + return ret; + pkt->data[0] = 0; + pkt->size = datasize + 1; + + ret = avio_read(pb, pkt->data + 1, datasize); + if (ret < datasize) { + ret = AVERROR(EIO); + goto fail; + } + + datasize = avio_rl16(pb); /* palette size */ + if (datasize) { + if (datasize != 768) { + av_log(s, AV_LOG_ERROR, "invalid palette size %u\n", datasize); + ret = AVERROR_INVALIDDATA; + goto fail; + } + pkt->data[0] |= C93_HAS_PALETTE; + ret = avio_read(pb, pkt->data + pkt->size, datasize); + if (ret < datasize) { + ret = AVERROR(EIO); + goto fail; + } + pkt->size += 768; + } + pkt->stream_index = 0; + c93->next_pkt_is_audio = 1; + + /* only the first frame is guaranteed to not reference previous frames */ + if (c93->current_block == 0 && c93->current_frame == 0) { + pkt->flags |= AV_PKT_FLAG_KEY; + pkt->data[0] |= C93_FIRST_FRAME; + } + return 0; + + fail: + av_free_packet(pkt); + return ret; +} + +AVInputFormat ff_c93_demuxer = { + .name = "c93", + .long_name = NULL_IF_CONFIG_SMALL("Interplay C93"), + .priv_data_size = sizeof(C93DemuxContext), + .read_probe = probe, + .read_header = read_header, + .read_packet = read_packet, +}; diff --git a/pool/shard006/C/0118123_day5_pointer.c b/pool/shard006/C/0118123_day5_pointer.c new file mode 100644 index 0000000000000000000000000000000000000000..12d3df9515851a02561ae48aa465a1e7bee9cb65 --- /dev/null +++ b/pool/shard006/C/0118123_day5_pointer.c @@ -0,0 +1,20 @@ +#include + +//NULL 零地址; +// +int main(void) +{ + int *p = NULL; + int a = 10; + + printf("%p\n",NULL); + printf("%p\n",p); + + p = &a; + printf("%p,%d\n",p,*p); + printf("%p,%d\n",&a,a); + printf("%p\n",&p); + + printf("%p\n",&p - &a); + return 0; +} diff --git a/pool/shard006/C/0118125_bfs.c b/pool/shard006/C/0118125_bfs.c new file mode 100644 index 0000000000000000000000000000000000000000..4acd5d958438c0becc6786ffbe935a48e62870b8 --- /dev/null +++ b/pool/shard006/C/0118125_bfs.c @@ -0,0 +1,122 @@ +#include +#include +#include +#include "bfs.h" +#include "../../list/linkedlist/doublylinkedlist/dlinkedlist.h" +#include "../../queue/circularqueue.h" + +int WhoIsPrecede(int data1, int data2); + +// 그래프의 초기화 +void GraphInit(ALGraph * pg, int nv) +{ + int i; + + pg->adjList = (List*)malloc(sizeof(List)*nv); + pg->numV = nv; + pg->numE = 0; // 초기의 간선 수는 0개 + + for(i=0; iadjList[i])); + SetSortRule(&(pg->adjList[i]), WhoIsPrecede); + } + + // 탐색 정보 등록을 위한 공간의 할당 및 초기화 + pg->visitInfo= (int *)malloc(sizeof(int) * pg->numV); + memset(pg->visitInfo, 0, sizeof(int) * pg->numV); +} + +// 그래프의 리소스 해제 +void GraphDestroy(ALGraph * pg) +{ + if(pg->adjList != NULL) + free(pg->adjList); + + if(pg->visitInfo != NULL) + free(pg->visitInfo); +} + +// 간선의 추가 +void AddEdge(ALGraph * pg, int fromV, int toV) +{ + LInsert(&(pg->adjList[fromV]), toV); + LInsert(&(pg->adjList[toV]), fromV); + pg->numE += 1; +} + +// 유틸리티 함수: 간선의 정보 출력 +void ShowGraphEdgeInfo(ALGraph * pg) +{ + int i; + int vx; + + for(i=0; inumV; i++) + { + printf("%c와 연결된 정점: ", i + 65); + + if(LFirst(&(pg->adjList[i]), &vx)) + { + printf("%c ", vx + 65); + + while(LNext(&(pg->adjList[i]), &vx)) + printf("%c ", vx + 65); + } + printf("\n"); + } +} + +int WhoIsPrecede(int data1, int data2) +{ + if(data1 < data2) + return 0; + else + return 1; +} + + +int VisitVertex(ALGraph * pg, int visitV) +{ + if(pg->visitInfo[visitV] == 0) + { + pg->visitInfo[visitV] = 1; + printf("%c ", visitV + 65); // 방문 정점 출력 + return TRUE; + } + + return FALSE; +} + +// Breadth First Search: 정점의 정보 출력 +void BFShowGraphVertex(ALGraph * pg, int startV) +{ + Queue queue; + int visitV = startV; + int nextV; + + // DFS를 위한 큐의 초기화 + QueueInit(&queue); + + // 시작 정점 탐색 + VisitVertex(pg, visitV); + + while(LFirst(&(pg->adjList[visitV]), &nextV) == TRUE) + { + if(VisitVertex(pg, nextV) == TRUE) + Enqueue(&queue, nextV); + + while(LNext(&(pg->adjList[visitV]), &nextV) == TRUE) + { + if(VisitVertex(pg, nextV) == TRUE) + Enqueue(&queue, nextV); + } + + if(QIsEmpty(&queue) == TRUE) // 큐가 비면 BFS 종료 + break; + else + visitV = Dequeue(&queue); + } + + // 탐색 정보 초기화 + memset(pg->visitInfo, 0, sizeof(int) * pg->numV); +} \ No newline at end of file diff --git a/pool/shard006/C/0118130_dsagen.c b/pool/shard006/C/0118130_dsagen.c new file mode 100644 index 0000000000000000000000000000000000000000..e7d346b1ec4b2d1ed2b71f2978b1f29116b7e68c --- /dev/null +++ b/pool/shard006/C/0118130_dsagen.c @@ -0,0 +1,115 @@ +/* crypto/dsa/dsagen.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +#include +#include + +#define TEST +#define GENUINE_DSA + +#ifdef GENUINE_DSA +# define LAST_VALUE 0xbd +#else +# define LAST_VALUE 0xd3 +#endif + +#ifdef TEST +unsigned char seed[20] = { + 0xd5, 0x01, 0x4e, 0x4b, + 0x60, 0xef, 0x2b, 0xa8, + 0xb6, 0x21, 0x1b, 0x40, + 0x62, 0xba, 0x32, 0x24, + 0xe0, 0x42, 0x7d, LAST_VALUE +}; +#endif + +int cb(int p, int n) +{ + char c = '*'; + + if (p == 0) + c = '.'; + if (p == 1) + c = '+'; + if (p == 2) + c = '*'; + if (p == 3) + c = '\n'; + printf("%c", c); + fflush(stdout); +} + +main() +{ + int i; + BIGNUM *n; + BN_CTX *ctx; + unsigned char seed_buf[20]; + DSA *dsa; + int counter, h; + BIO *bio_err = NULL; + + if (bio_err == NULL) + bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); + + memcpy(seed_buf, seed, 20); + dsa = DSA_generate_parameters(1024, seed, 20, &counter, &h, cb, bio_err); + + if (dsa == NULL) + DSA_print(bio_err, dsa, 0); +} diff --git a/pool/shard006/C/0118131_dcpu16-dis.c b/pool/shard006/C/0118131_dcpu16-dis.c new file mode 100644 index 0000000000000000000000000000000000000000..be59502d00e15154e6ace25f973315702e549187 --- /dev/null +++ b/pool/shard006/C/0118131_dcpu16-dis.c @@ -0,0 +1,182 @@ +/* Disassemble DCPU-16 instructions. + Copyright 2012 Fredrik Rothamel + + This file is part of the GNU opcodes library. + + This library is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + It is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public + License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, + MA 02110-1301, USA. */ + +#include "sysdep.h" +#include "dis-asm.h" +#include "opintl.h" +#include "opcode/dcpu16.h" +#include + +static const struct dcpu16_opcode * +lookup_instruction(u16 opcode) +{ + int start = 0; + int end = DCPU16_INSN_COUNT; + int mid; + + /* Optimize the common case */ + if (opcode == 0x0001) + return &dcpu16_opcode_table[0]; + + /* Search the opcode table */ + while (start < end) + { + mid = (start+end) / 2; + + if (opcode < dcpu16_opcode_table[mid].op) + { + end = mid; + } + else if (opcode > dcpu16_opcode_table[mid].op) + { + start = mid + 1; + } + else + return &dcpu16_opcode_table[mid]; + } + + return 0; +} + +static int +read_word (bfd_vma memaddr, struct disassemble_info *info, u16 arg, u16 *val) +{ + int status; + bfd_byte buffer[8]; + + if ((arg >= 0x10 && arg <= 0x17) || arg == 0x1a || arg == 0x1e || arg == 0x1f) + { + status = (*info->read_memory_func) (memaddr, buffer, 2, info); + if (status != 0) + { + (*info->memory_error_func) (status, memaddr, info); + return -1; + } + *val = bfd_getb16 (buffer); + + return 1; + } + + return 0; +} + +static void +print_operand (struct disassemble_info *info, u16 arg, u16 val, int is_dest) +{ + if (arg < 0x08) + { + (*info->fprintf_func) (info->stream, "%s", dcpu16_register_table[arg].name); + return; + } + if (arg < 0x10) + { + (*info->fprintf_func) (info->stream, "[%s]", dcpu16_register_table[arg&0x7].name); + return; + } + if (arg < 0x18) + { + (*info->fprintf_func) (info->stream, "[%s+0x%04x]", dcpu16_register_table[arg&0x7].name, val); + return; + } + + switch(arg) + { + case 0x18: + if(is_dest) + (*info->fprintf_func) (info->stream, "[--SP]"); + else + (*info->fprintf_func) (info->stream, "[SP++]"); + return; + case 0x19: + (*info->fprintf_func) (info->stream, "[SP]"); + return; + case 0x1a: + (*info->fprintf_func) (info->stream, "[SP+0x%04x]", val); + return; + case 0x1b: + (*info->fprintf_func) (info->stream, "SP"); + return; + case 0x1c: + (*info->fprintf_func) (info->stream, "PC"); + return; + case 0x1d: + (*info->fprintf_func) (info->stream, "EX"); + return; + case 0x1e: + (*info->fprintf_func) (info->stream, "[0x%04x]", val); + return; + case 0x1f: + (*info->fprintf_func) (info->stream, "0x%04x", val); + return; + } + + (*info->fprintf_func) (info->stream, "0x%02x", (arg&0x1f)-1); +} + +int +print_insn_dcpu16 (bfd_vma memaddr, struct disassemble_info *info) +{ + int status, result; + bfd_byte buffer[8]; + u16 opcode, aword, bword; + const struct dcpu16_opcode *op; + + info->bytes_per_line = 6; + info->bytes_per_chunk = 2; + info->display_endian = BFD_ENDIAN_BIG; + + status = (*info->read_memory_func) (memaddr, buffer, 2, info); + if (status != 0) + { + (*info->memory_error_func) (status, memaddr, info); + return -1; + } + opcode = bfd_getb16 (buffer); + + result = 1; + + if (opcode & 0x1f) + { + op = lookup_instruction (opcode&0x1f); + if (op) + { + (*info->fprintf_func) (info->stream, "%s\t", op->name); + + result += read_word(memaddr+result, info, opcode>>10, &aword); + result += read_word(memaddr+result, info, (opcode>>5)&0x1f, &bword); + + print_operand(info, (opcode>>5)&0x1f, bword, 1); + (*info->fprintf_func) (info->stream, ", "); + print_operand(info, opcode>>10, aword, 0); + } + } + else + { + op = lookup_instruction (opcode&0x3ff); + if (op) + { + (*info->fprintf_func) (info->stream, "%s\t", op->name); + result += read_word(memaddr+result, info, opcode>>10, &aword); + print_operand(info, opcode>>10, aword, 0); + } + } + + return 2*result; +} diff --git a/pool/shard006/C/0118134_Colorname.c b/pool/shard006/C/0118134_Colorname.c new file mode 100644 index 0000000000000000000000000000000000000000..f4cf4c676331b08d1fcaf9c3b41035b974822020 --- /dev/null +++ b/pool/shard006/C/0118134_Colorname.c @@ -0,0 +1,96 @@ +/* + * Parse rgb.txt file and return color by name + */ +#include "nxlib.h" +#include +#include + +#define ISBLANK(c) ((c) == ' ' || (c) == '\t') +#define ISDIGIT(c) ((c) >= '0' && (c) <= '9') +#define ISEOL(c) ((c) == '\r' || (c) == '\n') + +/* get next int from buffer, return next buf position*/ +static char * +strInt(int *retint, char *buf) +{ + char * q; + char tmp[256]; + + while (ISBLANK(*buf)) + ++buf; + q = tmp; + while (ISDIGIT(*buf)) + *q++ = *buf++; + *q = 0; + *retint = atoi(tmp); + return buf; +} + +/* return string to end of line from buffer*/ +static void +strEol(char *retbuf, char *buf) +{ + while (ISBLANK(*buf)) + ++buf; + while (!ISEOL(*buf)) + *retbuf++ = *buf++; + *retbuf = 0; +} + +GR_COLOR +GrGetColorByName(char *colorname, int *retr, int *retg, int *retb) +{ + FILE *fp; + unsigned int r = 0, g = 0, b = 0; + char buf[256]; + + fp = fopen(X11_RGBTXT, "r"); + if (!fp) + return 0; + + while (fgets(buf, 256, fp) != NULL) { + if (buf[0] != '!') { + char *p; + char name[256]; + + p = strInt(&r, buf); + p = strInt(&g, p); + p = strInt(&b, p); + strEol(name, p); + + if (strcasecmp(name, colorname) == 0) { + if (retr) + *retr = r; + if (retg) + *retg = g; + if (retb) + *retb = b; + return GR_RGB(r, g, b); + } + } + } + fclose(fp); + + return 0; +} + +Status +XAllocNamedColor(Display * dpy, Colormap cmap, _Xconst char *colorname, + XColor * hard_def, XColor * exact_def) +{ + GR_COLOR c; + int r = 0, g = 0, b = 0; + + /* first look up color in rgb.txt color database */ + c = GrGetColorByName((char *) colorname, &r, &g, &b); +//printf("XAllocNamedColor %s = %x\n", colorname, c); + + hard_def->red = exact_def->red = r << 8; + hard_def->green = exact_def->green = g << 8; + hard_def->blue = exact_def->blue = b << 8; + + /* Do an XAllocColor on the hardware color */ + XAllocColor(dpy, cmap, hard_def); + + return 1; +} diff --git a/pool/shard006/C/0118140_keyboard.c b/pool/shard006/C/0118140_keyboard.c new file mode 100644 index 0000000000000000000000000000000000000000..3645d5684b223922ae2f9f67d8baf7d18dd7f992 --- /dev/null +++ b/pool/shard006/C/0118140_keyboard.c @@ -0,0 +1,279 @@ +/* + * "Software pw3270, desenvolvido com base nos códigos fontes do WC3270 e X3270 + * (Paul Mattes Paul.Mattes@usa.net), de emulação de terminal 3270 para acesso a + * aplicativos mainframe. Registro no INPI sob o nome G3270. + * + * Copyright (C) <2008> + * + * Este programa é software livre. Você pode redistribuí-lo e/ou modificá-lo sob + * os termos da GPL v.2 - Licença Pública Geral GNU, conforme publicado pela + * Free Software Foundation. + * + * Este programa é distribuído na expectativa de ser útil, mas SEM QUALQUER + * GARANTIA; sem mesmo a garantia implícita de COMERCIALIZAÇÃO ou de ADEQUAÇÃO + * A QUALQUER PROPÓSITO EM PARTICULAR. Consulte a Licença Pública Geral GNU para + * obter mais detalhes. + * + * Você deve ter recebido uma cópia da Licença Pública Geral GNU junto com este + * programa; se não, escreva para a Free Software Foundation, Inc., 51 Franklin + * St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Este programa está nomeado como keyboard.c e possui - linhas de código. + * + * Contatos: + * + * perry.werneck@gmail.com (Alexandre Perry de Souza Werneck) + * erico.mendonca@gmail.com (Erico Mascarenhas Mendonça) + * licinio@bb.com.br (Licínio Luis Branco) + * kraucer@bb.com.br (Kraucer Fernandes Mazuco) + * macmiranda@bb.com.br (Marco Aurélio Caldas Miranda) + * + */ + + #include + #include + #include + #include + #include + #include + #include + + #include + #include "private.h" + +#if GTK_CHECK_VERSION(3,0,0) + #include +#else + #include +#endif + +#ifndef GDK_ALT_MASK + #define GDK_ALT_MASK GDK_MOD1_MASK +#endif + +#ifndef GDK_NUMLOCK_MASK + #define GDK_NUMLOCK_MASK GDK_MOD2_MASK +#endif + +/*--[ Globals ]--------------------------------------------------------------------------------------*/ + + static struct _keycode + { + guint keyval; + GdkModifierType state; + int (*exec)(H3270 *session); + GtkAction * action; + } keycode[] = + { + { GDK_Left, 0, lib3270_cursor_left, NULL }, + { GDK_Up, 0, lib3270_cursor_up, NULL }, + { GDK_Right, 0, lib3270_cursor_right, NULL }, + { GDK_Down, 0, lib3270_cursor_down, NULL }, + { GDK_Tab, 0, lib3270_nextfield, NULL }, + { GDK_ISO_Left_Tab, GDK_SHIFT_MASK, lib3270_previousfield, NULL }, + { GDK_KP_Left, 0, lib3270_cursor_left, NULL }, + { GDK_KP_Up, 0, lib3270_cursor_up, NULL }, + { GDK_KP_Right, 0, lib3270_cursor_right, NULL }, + { GDK_KP_Down, 0, lib3270_cursor_down, NULL }, + + { GDK_KP_Add, GDK_NUMLOCK_MASK, NULL, NULL }, + { GDK_KP_Subtract, GDK_NUMLOCK_MASK, NULL, NULL }, + + { GDK_3270_PrintScreen, 0, lib3270_print, NULL }, + { GDK_Sys_Req, 0, lib3270_sysreq, NULL }, + + { GDK_Print, GDK_CONTROL_MASK, lib3270_print, NULL }, + { GDK_Print, GDK_SHIFT_MASK, lib3270_sysreq, NULL }, + { GDK_Control_R, 0, NULL, NULL }, + { GDK_Control_L, 0, NULL, NULL }, + +#ifdef WIN32 + { GDK_Pause, 0, NULL, NULL }, +#endif + }; + +/*--[ Implement ]------------------------------------------------------------------------------------*/ + + #define keyval_is_alt() (event->keyval == GDK_Alt_L || event->keyval == GDK_Meta_L || event->keyval == GDK_ISO_Level3_Shift) + + static void update_keyboard_state(v3270 *terminal, GdkEventKey *event, gboolean status) + { + if(event->keyval == GDK_Shift_R || event->keyval == GDK_Shift_L) + { + if(status) + terminal->keyflags |= KEY_FLAG_SHIFT; + else + terminal->keyflags &= ~KEY_FLAG_SHIFT; + v3270_draw_shift_status(terminal); + } + +#ifdef KEY_FLAG_ALT + if(keyval_is_alt()) + { + if(status) + terminal->keyflags |= KEY_FLAG_ALT; + else + terminal->keyflags &= ~KEY_FLAG_ALT; + v3270_draw_alt_status(terminal); + } +#endif // KEY_FLAG_ALT + + } + + static gboolean check_keypress(v3270 *widget, GdkEventKey *event) + { + int f; + int state = event->state & (GDK_SHIFT_MASK|GDK_CONTROL_MASK|GDK_ALT_MASK); + gboolean handled = FALSE; + +#ifdef WIN32 + // FIXME (perry#1#): Find a better way! + if( event->keyval == 0xffffff && event->hardware_keycode == 0x0013) + event->keyval = GDK_Pause; + + // Windows sets in left/right control + else if(state & GDK_CONTROL_MASK && (event->keyval == GDK_Control_R || event->keyval == GDK_Control_L)) + state &= ~GDK_CONTROL_MASK; +#endif + + g_signal_emit(GTK_WIDGET(widget), v3270_widget_signal[SIGNAL_KEYPRESS], 0, event->keyval, state, &handled); + if(handled) + return TRUE; + + if(event->keyval >= GDK_F1 && event->keyval <= GDK_F12 && !(state & (GDK_CONTROL_MASK|GDK_ALT_MASK))) + { + int pfcode = (event->keyval - GDK_F1) + ((state & GDK_SHIFT_MASK) ? 13 : 1); + + trace("PF%02d",pfcode); + + if(pfcode > 0 && pfcode < 25) + { + lib3270_pfkey(widget->host,pfcode); + return TRUE; + } + } + + for(f=0; f < G_N_ELEMENTS(keycode);f++) + { + if(keycode[f].keyval == event->keyval && state == keycode[f].state) + { + trace("%s: id=%d action=%p",__FUNCTION__,f,keycode[f].action); + if(keycode[f].action) + gtk_action_activate(keycode[f].action); + else if(keycode[f].exec) + keycode[f].exec(widget->host); + else + return FALSE; + return TRUE; + + } + } + + return FALSE; + } + + gboolean v3270_set_keyboard_action(GtkWidget *widget, const gchar *key_name, GtkAction *action) + { + guint keyval; + GdkModifierType state; + int f; + + g_return_val_if_fail(GTK_IS_V3270(widget),FALSE); + + gtk_accelerator_parse(key_name,&keyval,&state); + + for(f=0; f < G_N_ELEMENTS(keycode);f++) + { + if(keycode[f].keyval == keyval && keycode[f].state == state) + { + keycode[f].action = action; + return TRUE; + } + } + + return FALSE; + } + + gboolean v3270_key_press_event(GtkWidget *widget, GdkEventKey *event) + { + v3270 * terminal = GTK_V3270(widget); + + terminal->activity.timestamp = time(0); + update_keyboard_state(terminal,event,TRUE); + + if(gtk_im_context_filter_keypress(terminal->input_method,event)) + return TRUE; + + if(check_keypress(terminal,event)) + { + gtk_im_context_reset(terminal->input_method); + return TRUE; + } + + return FALSE; + + } + + gboolean v3270_key_release_event(GtkWidget *widget, GdkEventKey *event) + { + v3270 * terminal = GTK_V3270(widget); + + update_keyboard_state(terminal,event,FALSE); + + if(gtk_im_context_filter_keypress(terminal->input_method,event)) + return TRUE; + + return FALSE; + + } + + void v3270_tab(GtkWidget *widget) + { + g_return_if_fail(GTK_IS_V3270(widget)); + GTK_V3270(widget)->activity.timestamp = time(0); + lib3270_nextfield(GTK_V3270(widget)->host); + } + + void v3270_backtab(GtkWidget *widget) + { + g_return_if_fail(GTK_IS_V3270(widget)); + GTK_V3270(widget)->activity.timestamp = time(0); + lib3270_previousfield(GTK_V3270(widget)->host); + } + + void v3270_set_string(GtkWidget *widget, const gchar *str) + { + H3270 *host; + gchar *utf; + + g_return_if_fail(GTK_IS_V3270(widget)); + + host = GTK_V3270(widget)->host; + GTK_V3270(widget)->activity.timestamp = time(0); + + utf = g_convert((char *) str, -1, lib3270_get_display_charset(host), "UTF-8", NULL, NULL, NULL); + + if(utf) + { + lib3270_set_string(host, (const unsigned char *) utf); + g_free(utf); + } + + } + + void v3270_key_commit(GtkIMContext *imcontext, gchar *str, v3270 *widget) + { + gchar *utf = g_convert((char *) str, -1, lib3270_get_display_charset(widget->host), "UTF-8", NULL, NULL, NULL); + + if(utf) + { + lib3270_input_string(GTK_V3270(widget)->host, (const unsigned char *) utf); + g_free(utf); + } + else + { + lib3270_ring_bell(widget->host); + } + } + + diff --git a/pool/shard006/C/0118145_common.c b/pool/shard006/C/0118145_common.c new file mode 100644 index 0000000000000000000000000000000000000000..3e7c7107a8f049ab470d0b730229988fee6f81ce --- /dev/null +++ b/pool/shard006/C/0118145_common.c @@ -0,0 +1,179 @@ +/* + * Clam Antivirus Client Library + * Copyright (C) 2009 Alaska Communications Systems Group, Inc + * + * @ACS_LICENSE_HEADER_START@ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * @ACS_LICENSE_HEADER_END@ + */ +/** + * @file tests/common.c common functions for tests + */ +#define _CLAMAVC_TESTS_COMMON_C 1 +#include "common.h" + +/////////////// +// // +// Headers // +// // +/////////////// + +#include +#include +#include + + +//////////////////////// +// // +// Global Variables // +// // +//////////////////////// + +int clamd_remote = 0; +int clamd_socket = 0; + +char clean_archive[1024]; +char clean_dir[1024]; +char clean_file[1024]; + +char infected_archive[1024]; +char infected_dir[1024]; +char infected_file[1024]; + + +///////////////// +// // +// Functions // +// // +///////////////// + +/// processed command line options +/// @param[in] argc number of arguments passed to clamavclient +/// @param[in] argv array of arguments passed to clamavclient +/// @param[out] clampp pointer to ClamAV Client session data +/// @param[out] filep pointer to file pointer +int config(CLAMAVC ** clampp) +{ + CLAMAVC * clamp; + uintmax_t uval; + const char * str; + + clamd_remote = 1; + clamd_socket = 0; + *clampp = NULL; + + if (!(str = getenv("ABS_TOP_SRCDIR"))) + return(1); + if (1023 <= snprintf(clean_dir, 1024, "%s/data", str)) return(1); + + if (!(str = getenv("ABS_TOP_BUILDDIR"))) + return(1); + if (1023 <= snprintf(infected_dir, 1024, "%s/data", str)) return(1); + + if (1023 <= snprintf(clean_file, 1024, "%s/clean.txt", infected_dir)) return(1); + if (1023 <= snprintf(clean_archive, 1024, "%s/clean.tar.gz", infected_dir)) return(1); + if (1023 <= snprintf(infected_file, 1024, "%s/infected.txt", infected_dir)) return(1); + if (1023 <= snprintf(infected_archive, 1024, "%s/infected.tar.gz", infected_dir)) return(1); + + if (!(clamp = clamavc_initialize())) + return(-1); + + uval = 0;; + clamavc_set_opt(clamp, CLAMAVC_OVERBOSE, &uval); + + str = getenv("CLAMAVC_HOST") ? getenv("CLAMAVC_HOST") : CLAMAVC_HOST; + if (str[0] == '/') + { + clamd_remote = 1; + clamd_socket = 1; + } + else if ( (!(strcmp(str, "localhost"))) || + (!(strcmp(str, "127.0.0.1"))) || + (!(strcmp(str, "::1"))) ) + { + clamd_remote = 0; + clamd_socket = 0; + } + else + { + clamd_remote = 1; + clamd_socket = 0; + }; + + if ((str = getenv("CLAMAVC_REMOTE"))) + { + clamd_remote = 1; + clamd_socket = 0; + }; + + *clampp = clamp; + + return(0); +} + + +/// sends file as chuncked data to the server +/// @param[in] clamp pointer to ClamAV Client session data +/// @param[in] file file to scan +int32_t instream_fildes(CLAMAVC * clamp, const char * file) +{ + int fd; + int32_t err; + + if ((fd = open(file, O_RDONLY)) == -1) + return(-1); + + err = clamavc_instream_fildes(clamp, fd); + + close(fd); + + return(err); +} + + +/// sends file as chuncked data to the server +/// @param[in] clamp pointer to ClamAV Client session data +/// @param[in] file file to scan +int32_t instream_file(CLAMAVC * clamp, const char * file) +{ + int fd; + int len; + int32_t err; + char buff[1024]; + + if ((fd = open(file, O_RDONLY)) == -1) + return(-1); + + while((len = read(fd, buff, 1024)) > 0) + { + if ((err = clamavc_instream(clamp, buff, (unsigned)len)) == -1) + { + close(fd); + return(-1); + }; + }; + + close(fd); + + if (len == -1) + return(-1); + + return(clamavc_instream(clamp, NULL, 0)); +} + + +/* end of source code */ diff --git a/pool/shard006/C/0118148_opengl_video.c b/pool/shard006/C/0118148_opengl_video.c new file mode 100644 index 0000000000000000000000000000000000000000..8f28747ffad80ef9108288b2b0e97062d6669416 --- /dev/null +++ b/pool/shard006/C/0118148_opengl_video.c @@ -0,0 +1,295 @@ +#include +#include +#include +#include +#define NO_SDL_GLEXT +#define GL_GLEXT_PROTOTYPES +#include +#include +#include +#include + +/* Vertex parameters */ +#define NUM_POS_COORDS 2 +#define NUM_TEX_COORDS 2 +#define MIN_POS -1.0f +#define MAX_POS 1.0f +#define MIN_UV 0.0f +#define MAX_UV 1.0f + +struct gl { + int width; + int height; + SDL_Surface *screen; + uint8_t *pixels; + int scale_factor; + GLuint vbo; + GLuint program; + GLuint vertex_shader; + GLuint fragment_shader; + GLuint texture; +}; + +struct vertex { + GLfloat position[NUM_POS_COORDS]; + GLfloat uv[NUM_TEX_COORDS]; +}; + +static bool gl_init(int width, int height, int scale); +static video_window_t *gl_get_window(); +static void gl_deinit(); +static void gl_update(); +static struct color gl_get_pixel(int x, int y); +static void gl_set_pixel(int x, int y, struct color color); +static bool init_shaders(); +static void init_buffers(); +static void init_pixels(); + +struct vertex vertices[] = { + { { MIN_POS, MAX_POS }, { MIN_UV, MIN_UV } }, + { { MAX_POS, MAX_POS }, { MAX_UV, MIN_UV } }, + { { MIN_POS, MIN_POS }, { MIN_UV, MAX_UV } }, + { { MAX_POS, MIN_POS }, { MAX_UV, MAX_UV } } +}; + +static const char *vertex_source = + "attribute vec4 position;" + "attribute vec4 uv;" + "void main()" + "{" + " gl_Position = position;" + " gl_TexCoord[0] = uv;" + "}"; + +static const char *fragment_source = + "uniform sampler2D texture;" + "void main()" + "{" + " gl_FragColor = texture2D(texture, gl_TexCoord[0].st);" + "}"; + +static struct gl gl; + +bool init_shaders() +{ + int status; + + /* Create program and associated shaders */ + gl.program = glCreateProgram(); + gl.vertex_shader = glCreateShader(GL_VERTEX_SHADER); + gl.fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); + + /* Assign vertex and fragment shader sources */ + glShaderSource(gl.vertex_shader, 1, &vertex_source, NULL); + glShaderSource(gl.fragment_shader, 1, &fragment_source, NULL); + + /* Compile shaders */ + glCompileShader(gl.vertex_shader); + glCompileShader(gl.fragment_shader); + + /* Attach shaders and link program */ + glAttachShader(gl.program, gl.vertex_shader); + glAttachShader(gl.program, gl.fragment_shader); + glLinkProgram(gl.program); + + /* Verify link was successful */ + glGetProgramiv(gl.program, GL_LINK_STATUS, &status); + return (status == GL_TRUE); +} + +void init_buffers() +{ + int location; + + /* Generate and fill VBO */ + glGenBuffers(1, &gl.vbo); + glBindBuffer(GL_ARRAY_BUFFER, gl.vbo); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, + GL_STATIC_DRAW); + + /* Set position attribute */ + location = glGetAttribLocation(gl.program, "position"); + glEnableVertexAttribArray(location); + glVertexAttribPointer(location, + NUM_POS_COORDS, + GL_FLOAT, + GL_FALSE, + sizeof(struct vertex), + (GLvoid *)offsetof(struct vertex, position)); + + /* Set texture coordinates attribute */ + location = glGetAttribLocation(gl.program, "uv"); + glEnableVertexAttribArray(location); + glVertexAttribPointer(location, + NUM_TEX_COORDS, + GL_FLOAT, + GL_FALSE, + sizeof(struct vertex), + (GLvoid *)offsetof(struct vertex, uv)); +} + +void init_pixels() +{ + int location; + + /* Initialize pixels */ + gl.pixels = malloc(gl.width * gl.height * 3 * sizeof(uint8_t)); + memset(gl.pixels, 0, gl.width * gl.height * 3 * sizeof(uint8_t)); + + /* Generate and bind texture */ + glGenTextures(1, &gl.texture); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, gl.texture); + + /* Set texture parameters */ + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + + /* Allow texture 0 to be sampled from fragment shader */ + location = glGetUniformLocation(gl.program, "rubyTexture"); + glUniform1i(location, 0); + + /* Fill texture data */ + glTexImage2D(GL_TEXTURE_2D, + 0, + GL_RGB, + gl.width, + gl.height, + 0, + GL_RGB, + GL_UNSIGNED_BYTE, + gl.pixels); +} + +bool gl_init(int width, int height, int scale) +{ + Uint32 flags = SDL_OPENGL; + + /* Initialize video sub-system */ + if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) { + LOG_E("Error initializing SDL video: %s\n", SDL_GetError()); + return false; + } + + /* Set window position and title */ + SDL_putenv("SDL_VIDEO_CENTERED=center"); + SDL_WM_SetCaption("emux", NULL); + + /* Create main video surface */ + gl.screen = SDL_SetVideoMode(width * scale, height * scale, 0, flags); + if (!gl.screen) { + LOG_E("Error creating video surface: %s\n", SDL_GetError()); + SDL_VideoQuit(); + return false; + } + + /* Save parameters */ + gl.width = width; + gl.height = height; + gl.scale_factor = scale; + + /* Initialize shaders and return in case of failure */ + if (!init_shaders()) { + LOG_E("Error initializing shaders!\n"); + return false; + } + + /* Initialize buffers and pixels */ + init_buffers(); + init_pixels(); + + return true; +} + +video_window_t *gl_get_window() +{ + return gl.screen; +} + +void gl_update() +{ + /* Set viewport */ + glViewport(0, + 0, + gl.width * gl.scale_factor, + gl.height * gl.scale_factor); + + /* Clear screen */ + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + + /* Update texture data */ + glTexSubImage2D(GL_TEXTURE_2D, + 0, + 0, + 0, + gl.width, + gl.height, + GL_RGB, + GL_UNSIGNED_BYTE, + gl.pixels); + + /* Set current program */ + glUseProgram(gl.program); + + /* Paint a quad with our texture on it */ + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + /* Set current program */ + glUseProgram(0); + + /* Flip screen */ + SDL_GL_SwapBuffers(); +} + +struct color gl_get_pixel(int x, int y) +{ + struct color color; + + /* Compute index of RGB triplet */ + int index = 3 * (x + y * gl.width); + + /* Fill color and return it */ + color.r = gl.pixels[index]; + color.g = gl.pixels[index + 1]; + color.b = gl.pixels[index + 2]; + return color; +} + +void gl_set_pixel(int x, int y, struct color color) +{ + /* Compute index of RGB triplet */ + int index = 3 * (x + y * gl.width); + + /* Save pixel */ + gl.pixels[index] = color.r; + gl.pixels[index + 1] = color.g; + gl.pixels[index + 2] = color.b; +} + +void gl_deinit() +{ + /* Free allocated components */ + free(gl.pixels); + glDeleteBuffers(1, &gl.vbo); + glDeleteTextures(1, &gl.texture); + glDeleteShader(gl.vertex_shader); + glDeleteShader(gl.fragment_shader); + glDeleteProgram(gl.program); + + /* Quit SDL video sub-system */ + SDL_QuitSubSystem(SDL_INIT_VIDEO); +} + +VIDEO_START(opengl) + .input = "sdl", + .init = gl_init, + .get_window = gl_get_window, + .update = gl_update, + .get_pixel = gl_get_pixel, + .set_pixel = gl_set_pixel, + .deinit = gl_deinit +VIDEO_END + diff --git a/pool/shard006/C/0118156_event_callback.c b/pool/shard006/C/0118156_event_callback.c new file mode 100644 index 0000000000000000000000000000000000000000..4d3e2f8ce8baae85f8a36cbe2c86348f59741626 --- /dev/null +++ b/pool/shard006/C/0118156_event_callback.c @@ -0,0 +1,134 @@ +/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: + * + * Drizzle Client & Protocol Library + * + * Copyright (c) 2016 dunnhumby Germany GmbH + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * + * * The names of its contributors may not 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. + * + */ + +/** + * @brief Tests that drizzle_st::event_watch_fn is set correctly when calling + * ::drizzle_set_event_watch_fn() and called with valid arguments + * + * @details Check that the drizzle_event_callback was called. It is done + * indirectly by asserting that cxt_b has been incremented at three times. + * The number of calls varies with the availability of underlying socket. + * However a successful run of the unittest is guaranteed to invoke the + * event_callback on the following state changes: + * + * 1. when drizzle connection is initiated by calling drizzle_connect + * 2. before connecting to server after 1 succeeds + * 3. when the drizzle_st connection is closed by calling drizzle_quit + */ + +#include + +#include +#include + +#include +#include +#include + +extern drizzle_return_t drizzle_event_callback(drizzle_st *con, short events, + void *context); +extern drizzle_return_t drizzle_event_callback(drizzle_st *con, short events, + void *context) +{ + ASSERT_TRUE((events != -1)); + char* char_ptr = (char*) drizzle_context(con); + ASSERT_NOT_NULL_(char_ptr, "Drizzle connection context is null"); + ASSERT_STREQ_("Context is everything", char_ptr, + "Invalid drizzle context: Got '%s', Expected 'Context is everything'", + char_ptr); + printf("%s\n", char_ptr); + + int* cxt_ptr = (int*)context; + + ASSERT_NOT_NULL_(cxt_ptr, "Drizzle event callback context is null"); + (*cxt_ptr)++; + printf("Drizzle event callback number %d\n", cxt_ptr[0]); + + return DRIZZLE_RETURN_OK; +} + +extern void drizzle_free_context(drizzle_st *con, void *context); +extern void drizzle_free_context(drizzle_st *con, void *context) +{ + (void)con; + + char *cxt = (char*)context; + strcpy(cxt, "Context is dead"); +} + + +int main(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + + char cxt_a[] = "Context is everything"; + int cxt_b = 0; + + drizzle_st *con = drizzle_create(getenv("MYSQL_SERVER"), + getenv("MYSQL_PORT") ? atoi(getenv("MYSQL_PORT")) + : DRIZZLE_DEFAULT_TCP_PORT, + getenv("MYSQL_USER"), + getenv("MYSQL_PASSWORD"), + getenv("MYSQL_SCHEMA"), 0); + ASSERT_NOT_NULL_(con, "Drizzle connection object creation error"); + + // Set drizzle dummy context + drizzle_set_context(con, (void *)&cxt_a); + drizzle_set_context_free_fn(con, drizzle_free_context); + ASSERT_NOT_NULL_(drizzle_context(con), "Drizzle context is null"); + + // Set user defined callback function event_watch_fn + drizzle_set_event_watch_fn(con, drizzle_event_callback, (void *)&cxt_b); + + drizzle_return_t driz_ret = drizzle_connect(con); + SKIP_IF_(driz_ret == DRIZZLE_RETURN_COULD_NOT_CONNECT, "%s", + drizzle_strerror(driz_ret)); + ASSERT_EQ_(DRIZZLE_RETURN_OK, driz_ret, "%s(%s)", drizzle_error(con), + drizzle_strerror(driz_ret)); + + driz_ret = drizzle_quit(con); + ASSERT_EQ_(DRIZZLE_RETURN_OK, driz_ret, "%s", drizzle_strerror(driz_ret)); + ASSERT_EQ_(cxt_b > 0, true, "Unexpected number of event callbacks, Got '%d', " + "Expected '1' or more", cxt_b); + + printf("\nEvent callback was invoked %d times\n", cxt_b); + + ASSERT_STREQ("Context is dead", cxt_a); + + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C/0118157_x_read.c b/pool/shard006/C/0118157_x_read.c new file mode 100644 index 0000000000000000000000000000000000000000..c8264aa01e78398d3dd9474c7d6b794e2fc1fe10 --- /dev/null +++ b/pool/shard006/C/0118157_x_read.c @@ -0,0 +1,178 @@ +/* + Copyright (C) 2008-2009 Computer Sciences Department, + University of Wisconsin -- Madison + + ---------------------------------------------------------------------- + + This file is part of the xCalls transactional API, originally + developed at the University of Wisconsin -- Madison. + + xCalls was originally developed primarily by Haris Volos and + Neelam Goyal with contributions from Andres Jaan Tack. + + ---------------------------------------------------------------------- + + xCalls 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 3 of + the License, or (at your option) any later version. + + xCalls 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 xCalls. If not, see . + +### END HEADER ### +*/ + +/** + * \file x_read.c + * + * \brief x_read implementation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +typedef struct x_read_undo_args_s x_read_undo_args_t; + +struct x_read_undo_args_s { + int fd; + int nbyte; +}; + + +static +void +x_read_undo(void *args, int *result) +{ + x_read_undo_args_t *args_undo = (x_read_undo_args_t *) args; + int local_result = 0; + + if (txc_libc_lseek(args_undo->fd, + -args_undo->nbyte, SEEK_CUR) < 0) + { + local_result = errno; + } + if (result) { + *result = local_result; + } +} + + +/** + * \brief Reads from a file. + * + * Execution : in-place + * + * Asynchronous failures : abort + * + * \param[in] fd The file descriptor of the file to read from. + * \param[in] buf The buffer where to store read data. + * \param[in] nbyte The number of bytes to read. + * \param[out] result Where to store any asynchronous failures. + * \return The number of read bytes on success, or -1 if a synchronous failure occurred + * (in which case, errno is set appropriately). + */ +ssize_t +XCALL_DEF(x_read)(int fd, void *buf, size_t nbyte, int *result) +{ + txc_tx_t *txd; + txc_koamgr_t *koamgr = txc_g_koamgr; + txc_koa_t *koa; + txc_sentinel_t *sentinel; + txc_result_t xret; + int ret; + x_read_undo_args_t *args_undo; + int local_result; + + + txd = txc_tx_get_txd(); + + switch(txc_tx_get_xactstate(txd)) { + case TXC_XACTSTATE_TRANSACTIONAL_IRREVOCABLE: + case TXC_XACTSTATE_NONTRANSACTIONAL: + if ((ret = txc_libc_read(fd, buf, nbyte)) < 0) { + local_result = errno; + } else { + local_result = 0; + } + goto done; + + case TXC_XACTSTATE_TRANSACTIONAL_RETRYABLE: + txc_koa_lock_fd(koamgr, fd); + xret = txc_koa_lookup_fd2koa(koamgr, fd, &koa); + if (xret == TXC_R_FAILURE) { + /* + * The KOA mapped to the file descriptor has gone. Report + * this error as invalid file descriptor. + */ + txc_koa_unlock_fd(koamgr, fd); + local_result = EBADF; + ret = -1; + goto done; + } + sentinel = txc_koa_get_sentinel(koa); + xret = txc_sentinel_tryacquire(txd, sentinel, + TXC_SENTINEL_ACQUIREONRETRY); + txc_koa_unlock_fd(koamgr, fd); + if (xret == TXC_R_BUSYSENTINEL) { + txc_tx_abort_transaction(txd, TXC_ABORTREASON_BUSYSENTINEL); + TXC_INTERNALERROR("Never gets here. Transaction abort failed.\n"); + } + + /* Got sentinel. Continue with the rest of the stuff. */ + + if ((args_undo = (x_read_undo_args_t *) + txc_buffer_linear_malloc(txd->buffer_linear, + sizeof(x_read_undo_args_t))) + == NULL) + { + local_result = ENOMEM; + ret = -1; + goto error_handler_0; + } + args_undo->fd = fd; + if ((ret = txc_libc_read(fd, buf, nbyte)) < 0) { + local_result = errno; + goto error_handler_1; + } + args_undo->nbyte = ret; + txc_tx_register_undo_action(txd, x_read_undo, + (void *) args_undo, result, + TXC_TX_REGULAR_UNDO_ACTION_ORDER); + local_result = 0; + txc_stats_txstat_increment(txd, XCALL, x_read, 1); + goto done; + + default: + TXC_INTERNALERROR("Unknown transaction state\n"); + } + +error_handler_1: + txc_buffer_linear_free(txd->buffer_linear, + sizeof(x_read_undo_args_t)); +error_handler_0: +done: + if (result) { + *result = local_result; + } + return ret; +} diff --git a/pool/shard006/C/0118158_displaytest.c b/pool/shard006/C/0118158_displaytest.c new file mode 100644 index 0000000000000000000000000000000000000000..d105d46b2380dcdfa4b77ffc177485e8688fb917 --- /dev/null +++ b/pool/shard006/C/0118158_displaytest.c @@ -0,0 +1,45 @@ + +/* + * Johannes Meixner , 2008, 2010 + * + * Copyright (c) 2010 Novell, Inc. + * All Rights Reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, contact Novell, Inc. + * + * To contact Novell about this file by physical or electronic mail, + * you may find current contact information at www.novell.com + */ + +/* + * gcc -Wall -o display display.c -L/usr/X11R6/lib -lX11 + */ + +#include +#include +#include + +int main (void) +{ char *display_name; + Display *d; + + display_name=getenv( "DISPLAY" ); + d = XOpenDisplay( display_name ); + if( d == NULL ) + { fprintf( stderr, "Unable to open Display: %s\n", display_name ); + exit(1); + } + XCloseDisplay(d); + return 0; +} + diff --git a/pool/shard006/C/0118164_errors.c b/pool/shard006/C/0118164_errors.c new file mode 100644 index 0000000000000000000000000000000000000000..57d8151734ce024f909843fe194b1839141bc649 --- /dev/null +++ b/pool/shard006/C/0118164_errors.c @@ -0,0 +1,65 @@ +/* + * errors.c + * + * Created on: Aug 8, 2016 + * Author: Bill.Chatfield + */ + +#include +#include +#include + +#include "stringconcat.h" +#include "errors.h" + +void printErrorMessage(const wchar_t *offendingObject, unsigned long errorCode) +{ + wchar_t *message; + + message = getErrorMessage(errorCode); + fwprintf(stderr, L"which: \u201C%s\u201D: %s\n", offendingObject, message); + free(message); +} + +/* This function was taken from Microsoft's Knowledge Base Article 149409 + and modified to fix the formatting. The returned string must be free'd + by the caller. */ +wchar_t *getErrorMessage(unsigned long errorCode) +{ + HMODULE messageLocation; + wchar_t *message; + unsigned long messageLength; + + /* If dwLastError is in the network range, load the message source. */ + if (NERR_BASE <= errorCode && errorCode <= MAX_NERR) { + messageLocation = LoadLibraryEx(L"netmsg.dll", NULL, LOAD_LIBRARY_AS_DATAFILE); + } + else { + /* NULL means to look for the message in the system module. */ + messageLocation = NULL; + } + + /* Call FormatMessage to allow for message text to be acquired + from the system or the supplied module handle. */ + messageLength = FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_FROM_SYSTEM | /* Always consider system table */ + ((messageLocation != NULL) ? FORMAT_MESSAGE_FROM_HMODULE : 0), + messageLocation, /* Module to get message from (NULL == system) */ + errorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ + (wchar_t *) &message, + 0, + NULL); + + if (messageLength == 0) { + message = concatUInt32(L"Error code ", errorCode); + } + /* If a message source was loaded, unload it. */ + if (messageLocation != NULL) { + FreeLibrary(messageLocation); + } + return message; +} + diff --git a/pool/shard006/C/0118167_event.c b/pool/shard006/C/0118167_event.c new file mode 100644 index 0000000000000000000000000000000000000000..4c46d41373c5972f893d067c22409eebbb1fb241 --- /dev/null +++ b/pool/shard006/C/0118167_event.c @@ -0,0 +1,172 @@ +#if defined(HAVE_CONFIG_H) +#include "config.h" +#endif + +#include + +#include +#include + +#include "event.h" + +#define streq(a, b) (!strcasecmp((a), (b))) + +/** + * event_parse_ad_header - Parse an @ event header. + * + * The buffer is modified in place. + * Returns zero on success. + */ + +static int event_parse_ad_header(char *buf, int len, enum event_action *action, + char **device) +{ + int headerlen; + char *sep; + + *action = 0; + *device = NULL; + headerlen = strnlen(buf, len); + + if (!headerlen) { + pb_log_fn("bad header, no data\n"); + return -1; + } + + /* we should see an @\0 at the head of the buffer */ + sep = strchr(buf, '@'); + if (!sep) { + pb_log_fn("bad header: %s\n", buf); + return -1; + } + + /* terminate the action string */ + *sep = '\0'; + + if (streq(buf, "add")) + *action = EVENT_ACTION_ADD; + else if (streq(buf, "remove")) + *action = EVENT_ACTION_REMOVE; + else if (streq(buf, "url")) + *action = EVENT_ACTION_URL; + else if (streq(buf, "dhcp")) + *action = EVENT_ACTION_DHCP; + else if (streq(buf, "boot")) + *action = EVENT_ACTION_BOOT; + else if (streq(buf, "sync")) + *action = EVENT_ACTION_SYNC; + else if (streq(buf, "plugin")) + *action = EVENT_ACTION_PLUGIN; + else { + pb_log_fn("unknown action: %s\n", buf); + return -1; + } + + if (!*(sep + 1)) { + pb_log_fn("bad device: %s\n", buf); + return -1; + } + + *device = sep + 1; + return headerlen; +} + +/** + * event_parse_params - Parse a = buffer. + * + * The buffer is not modified. + */ + +static void event_parse_params(struct event *event, const char *buf, int len) +{ + int param_len, name_len, value_len; + struct event_param *param; + char *sep; + + for (; len > 0; len -= param_len + 1, buf += param_len + 1) { + + /* find the length of the whole parameter */ + param_len = strnlen(buf, len); + if (!param_len) { + /* multiple NULs? skip over */ + param_len = 1; + continue; + } + + /* update the params array */ + event->params = talloc_realloc(event, event->params, + struct event_param, ++event->n_params); + param = &event->params[event->n_params - 1]; + + sep = memchr(buf, '=', param_len); + if (!sep) { + name_len = param_len; + param->value = ""; + } else { + name_len = sep - buf; + value_len = param_len - name_len - 1; + param->value = talloc_strndup(event, sep + 1, + value_len); + } + param->name = talloc_strndup(event, buf, name_len); + } +} + +int event_parse_ad_message(struct event *event, char *buf, int len) +{ + enum event_action action; + int headerlen; + char *device; + + headerlen = event_parse_ad_header(buf, len, &action, &device); + + if (headerlen <= 0) + return -1; + + /* now we have an action and a device, we can construct the event */ + event->action = action; + event->device = talloc_strdup(event, device); + event->n_params = 0; + event->params = NULL; + + len -= headerlen + 1; + buf += headerlen + 1; + event_parse_params(event, buf, len); + + return 0; +} + +const char *event_get_param(const struct event *event, const char *name) +{ + int i; + + for (i = 0; i < event->n_params; i++) + if (!strcasecmp(event->params[i].name, name)) + return event->params[i].value; + + return NULL; +} + +void event_set_param(struct event *event, const char *name, const char *value) +{ + struct event_param *param; + int i; + + /* if it's already present, replace the value of the old param */ + for (i = 0; i < event->n_params; i++) { + param = &event->params[i]; + if (!strcasecmp(param->name, name)) { + talloc_free(param->value); + param->value = talloc_strdup(event, value); + return; + } + } + + /* not found - create a new param */ + event->params = talloc_realloc(event, event->params, + struct event_param, ++event->n_params); + param = &event->params[event->n_params - 1]; + + param->name = talloc_strdup(event, name); + param->value = talloc_strdup(event, value); +} diff --git a/pool/shard006/C/0118168_random_r.c b/pool/shard006/C/0118168_random_r.c new file mode 100644 index 0000000000000000000000000000000000000000..90a157f9c16c77311a809f40445760f546ccdf69 --- /dev/null +++ b/pool/shard006/C/0118168_random_r.c @@ -0,0 +1,411 @@ +/* + Copyright (C) 1995, 2005, 2009 Free Software Foundation + + 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. */ + +/* + Copyright (C) 1983 Regents of the University of California. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that 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. + 4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE.*/ + +/* + * This is derived from the Berkeley source: + * @(#)random.c 5.5 (Berkeley) 7/6/88 + * It was reworked for the GNU C Library by Roland McGrath. + * Rewritten to be reentrant by Ulrich Drepper, 1995 + */ + +#include +#include +#include +#include + + +/* An improved random number generation package. In addition to the standard + rand()/srand() like interface, this package also has a special state info + interface. The initstate() routine is called with a seed, an array of + bytes, and a count of how many bytes are being passed in; this array is + then initialized to contain information for random number generation with + that much state information. Good sizes for the amount of state + information are 32, 64, 128, and 256 bytes. The state can be switched by + calling the setstate() function with the same array as was initialized + with initstate(). By default, the package runs with 128 bytes of state + information and generates far better random numbers than a linear + congruential generator. If the amount of state information is less than + 32 bytes, a simple linear congruential R.N.G. is used. Internally, the + state information is treated as an array of longs; the zeroth element of + the array is the type of R.N.G. being used (small integer); the remainder + of the array is the state information for the R.N.G. Thus, 32 bytes of + state information will give 7 longs worth of state information, which will + allow a degree seven polynomial. (Note: The zeroth word of state + information also has some other information stored in it; see setstate + for details). The random number generation technique is a linear feedback + shift register approach, employing trinomials (since there are fewer terms + to sum up that way). In this approach, the least significant bit of all + the numbers in the state table will act as a linear feedback shift register, + and will have period 2^deg - 1 (where deg is the degree of the polynomial + being used, assuming that the polynomial is irreducible and primitive). + The higher order bits will have longer periods, since their values are + also influenced by pseudo-random carries out of the lower bits. The + total period of the generator is approximately deg*(2**deg - 1); thus + doubling the amount of state information has a vast influence on the + period of the generator. Note: The deg*(2**deg - 1) is an approximation + only good for large deg, when the period of the shift register is the + dominant factor. With deg equal to seven, the period is actually much + longer than the 7*(2**7 - 1) predicted by this formula. */ + + + +/* For each of the currently supported random number generators, we have a + break value on the amount of state information (you need at least this many + bytes of state info to support this random number generator), a degree for + the polynomial (actually a trinomial) that the R.N.G. is based on, and + separation between the two lower order coefficients of the trinomial. */ + +/* Linear congruential. */ +#define TYPE_0 0 +#define BREAK_0 8 +#define DEG_0 0 +#define SEP_0 0 + +/* x**7 + x**3 + 1. */ +#define TYPE_1 1 +#define BREAK_1 32 +#define DEG_1 7 +#define SEP_1 3 + +/* x**15 + x + 1. */ +#define TYPE_2 2 +#define BREAK_2 64 +#define DEG_2 15 +#define SEP_2 1 + +/* x**31 + x**3 + 1. */ +#define TYPE_3 3 +#define BREAK_3 128 +#define DEG_3 31 +#define SEP_3 3 + +/* x**63 + x + 1. */ +#define TYPE_4 4 +#define BREAK_4 256 +#define DEG_4 63 +#define SEP_4 1 + + +/* Array versions of the above information to make code run faster. + Relies on fact that TYPE_i == i. */ + +#define MAX_TYPES 5 /* Max number of types above. */ + +struct random_poly_info +{ + int seps[MAX_TYPES]; + int degrees[MAX_TYPES]; +}; + +static const struct random_poly_info random_poly_info = +{ + { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 }, + { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 } +}; + + + + +/* Initialize the random number generator based on the given seed. If the + type is the trivial no-state-information type, just remember the seed. + Otherwise, initializes state[] based on the given "seed" via a linear + congruential generator. Then, the pointers are set to known locations + that are exactly rand_sep places apart. Lastly, it cycles the state + information a given number of times to get rid of any initial dependencies + introduced by the L.C.R.N.G. Note that the initialization of randtbl[] + for default usage relies on values produced by this routine. */ +int +__srandom_r (seed, buf) + unsigned int seed; + struct random_data *buf; +{ + int type; + int32_t *state; + long int i; + int32_t word; + int32_t *dst; + int kc; + + if (buf == NULL) + goto fail; + type = buf->rand_type; + if ((unsigned int) type >= MAX_TYPES) + goto fail; + + state = buf->state; + /* We must make sure the seed is not 0. Take arbitrarily 1 in this case. */ + if (seed == 0) + seed = 1; + state[0] = seed; + if (type == TYPE_0) + goto done; + + dst = state; + word = seed; + kc = buf->rand_deg; + for (i = 1; i < kc; ++i) + { + /* This does: + state[i] = (16807 * state[i - 1]) % 2147483647; + but avoids overflowing 31 bits. */ + long int hi = word / 127773; + long int lo = word % 127773; + word = 16807 * lo - 2836 * hi; + if (word < 0) + word += 2147483647; + *++dst = word; + } + + buf->fptr = &state[buf->rand_sep]; + buf->rptr = &state[0]; + kc *= 10; + while (--kc >= 0) + { + int32_t discard; + (void) __random_r (buf, &discard); + } + + done: + return 0; + + fail: + return -1; +} + +weak_alias (__srandom_r, srandom_r) + +/* Initialize the state information in the given array of N bytes for + future random number generation. Based on the number of bytes we + are given, and the break values for the different R.N.G.'s, we choose + the best (largest) one we can and set things up for it. srandom is + then called to initialize the state information. Note that on return + from srandom, we set state[-1] to be the type multiplexed with the current + value of the rear pointer; this is so successive calls to initstate won't + lose this information and will be able to restart with setstate. + Note: The first thing we do is save the current state, if any, just like + setstate so that it doesn't matter when initstate is called. + Returns a pointer to the old state. */ +int +__initstate_r (seed, arg_state, n, buf) + unsigned int seed; + char *arg_state; + size_t n; + struct random_data *buf; +{ + if (buf == NULL) + goto fail; + + int32_t *old_state = buf->state; + if (old_state != NULL) + { + int old_type = buf->rand_type; + if (old_type == TYPE_0) + old_state[-1] = TYPE_0; + else + old_state[-1] = (MAX_TYPES * (buf->rptr - old_state)) + old_type; + } + + int type; + if (n >= BREAK_3) + type = n < BREAK_4 ? TYPE_3 : TYPE_4; + else if (n < BREAK_1) + { + if (n < BREAK_0) + goto fail; + + type = TYPE_0; + } + else + type = n < BREAK_2 ? TYPE_1 : TYPE_2; + + int degree = random_poly_info.degrees[type]; + int separation = random_poly_info.seps[type]; + + buf->rand_type = type; + buf->rand_sep = separation; + buf->rand_deg = degree; + int32_t *state = &((int32_t *) arg_state)[1]; /* First location. */ + /* Must set END_PTR before srandom. */ + buf->end_ptr = &state[degree]; + + buf->state = state; + + __srandom_r (seed, buf); + + state[-1] = TYPE_0; + if (type != TYPE_0) + state[-1] = (buf->rptr - state) * MAX_TYPES + type; + + return 0; + + fail: + __set_errno (EINVAL); + return -1; +} + +weak_alias (__initstate_r, initstate_r) + +/* Restore the state from the given state array. + Note: It is important that we also remember the locations of the pointers + in the current state information, and restore the locations of the pointers + from the old state information. This is done by multiplexing the pointer + location into the zeroth word of the state information. Note that due + to the order in which things are done, it is OK to call setstate with the + same state as the current state + Returns a pointer to the old state information. */ +int +__setstate_r (arg_state, buf) + char *arg_state; + struct random_data *buf; +{ + int32_t *new_state = 1 + (int32_t *) arg_state; + int type; + int old_type; + int32_t *old_state; + int degree; + int separation; + + if (arg_state == NULL || buf == NULL) + goto fail; + + old_type = buf->rand_type; + old_state = buf->state; + if (old_type == TYPE_0) + old_state[-1] = TYPE_0; + else + old_state[-1] = (MAX_TYPES * (buf->rptr - old_state)) + old_type; + + type = new_state[-1] % MAX_TYPES; + if (type < TYPE_0 || type > TYPE_4) + goto fail; + + buf->rand_deg = degree = random_poly_info.degrees[type]; + buf->rand_sep = separation = random_poly_info.seps[type]; + buf->rand_type = type; + + if (type != TYPE_0) + { + int rear = new_state[-1] / MAX_TYPES; + buf->rptr = &new_state[rear]; + buf->fptr = &new_state[(rear + separation) % degree]; + } + buf->state = new_state; + /* Set end_ptr too. */ + buf->end_ptr = &new_state[degree]; + + return 0; + + fail: + __set_errno (EINVAL); + return -1; +} + +weak_alias (__setstate_r, setstate_r) + +/* If we are using the trivial TYPE_0 R.N.G., just do the old linear + congruential bit. Otherwise, we do our fancy trinomial stuff, which is the + same in all the other cases due to all the global variables that have been + set up. The basic operation is to add the number at the rear pointer into + the one at the front pointer. Then both pointers are advanced to the next + location cyclically in the table. The value returned is the sum generated, + reduced to 31 bits by throwing away the "least random" low bit. + Note: The code takes advantage of the fact that both the front and + rear pointers can't wrap on the same call by not testing the rear + pointer if the front one has wrapped. Returns a 31-bit random number. */ + +int +__random_r (buf, result) + struct random_data *buf; + int32_t *result; +{ + int32_t *state; + + if (buf == NULL || result == NULL) + goto fail; + + state = buf->state; + + if (buf->rand_type == TYPE_0) + { + int32_t val = state[0]; + val = ((state[0] * 1103515245) + 12345) & 0x7fffffff; + state[0] = val; + *result = val; + } + else + { + int32_t *fptr = buf->fptr; + int32_t *rptr = buf->rptr; + int32_t *end_ptr = buf->end_ptr; + int32_t val; + + val = *fptr += *rptr; + /* Chucking least random bit. */ + *result = (val >> 1) & 0x7fffffff; + ++fptr; + if (fptr >= end_ptr) + { + fptr = state; + ++rptr; + } + else + { + ++rptr; + if (rptr >= end_ptr) + rptr = state; + } + buf->fptr = fptr; + buf->rptr = rptr; + } + return 0; + + fail: + __set_errno (EINVAL); + return -1; +} + +weak_alias (__random_r, random_r) diff --git a/pool/shard006/C/0118171_gimpoperationsoftlightmode.c b/pool/shard006/C/0118171_gimpoperationsoftlightmode.c new file mode 100644 index 0000000000000000000000000000000000000000..ea024b4370ef92a3be58acda3538b8d753e5697f --- /dev/null +++ b/pool/shard006/C/0118171_gimpoperationsoftlightmode.c @@ -0,0 +1,88 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpoperationsoftlightmode.c + * Copyright (C) 2008 Michael Natterer + * + * 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 "config.h" + +#include + +#include "gimp-gegl-types.h" + +#include "gimpoperationsoftlightmode.h" + + +static gboolean gimp_operation_softlight_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi); + + +G_DEFINE_TYPE (GimpOperationSoftlightMode, gimp_operation_softlight_mode, + GIMP_TYPE_OPERATION_POINT_LAYER_MODE) + + +static void +gimp_operation_softlight_mode_class_init (GimpOperationSoftlightModeClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationPointComposerClass *point_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + point_class = GEGL_OPERATION_POINT_COMPOSER_CLASS (klass); + + operation_class->name = "gimp:softlight-mode"; + operation_class->description = "GIMP softlight mode operation"; + + point_class->process = gimp_operation_softlight_mode_process; +} + +static void +gimp_operation_softlight_mode_init (GimpOperationSoftlightMode *self) +{ +} + +static gboolean +gimp_operation_softlight_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi) +{ + gfloat *in = in_buf; + gfloat *layer = aux_buf; + gfloat *out = out_buf; + + while (samples--) + { + out[RED] = in[RED]; + out[GREEN] = in[GREEN]; + out[BLUE] = in[BLUE]; + out[ALPHA] = in[ALPHA]; + + in += 4; + layer += 4; + out += 4; + } + + return TRUE; +} diff --git a/pool/shard006/C/0118173_chanservlog.c b/pool/shard006/C/0118173_chanservlog.c new file mode 100644 index 0000000000000000000000000000000000000000..89edbe86288345302fc5f6347001bcf803b90ed7 --- /dev/null +++ b/pool/shard006/C/0118173_chanservlog.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include +#include "chanserv.h" +#include "../core/hooks.h" +#include "../core/error.h" + +int logfd; + +/* When we get a sigusr1, reopen the logfile */ +void cs_usr1handler(int hooknum, void *arg) { + Error("chanserv",ERR_INFO,"Reopening logfile."); + + if (logfd>=0) + close(logfd); + + logfd=open("chanservlog",O_WRONLY|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR); +} + +void cs_initlog() { + logfd=open("chanservlog",O_WRONLY|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR); + registerhook(HOOK_CORE_SIGUSR1, cs_usr1handler); +} + +void cs_closelog() { + if (logfd>=0) + close(logfd); + deregisterhook(HOOK_CORE_SIGUSR1, cs_usr1handler); +} + +void cs_log(nick *np, char *event, ... ) { + char buf[512]; + char buf2[1024]; + char userbuf[512]; + va_list va; + char timebuf[TIMELEN]; + int len; + time_t now; + + if (logfd<0) + return; + + va_start(va,event); + vsnprintf(buf,512,event,va); + va_end(va); + + if (np) { + snprintf(userbuf,511,"%s!%s@%s [%s%s]",np->nick,np->ident,np->host->name->content, + getreguserfromnick(np)?"auth ":"noauth",getreguserfromnick(np)?getreguserfromnick(np)->username:""); + } else { + userbuf[0]='\0'; + } + + now=time(NULL); + strftime(timebuf,sizeof(timebuf),Q9_LOG_FORMAT_TIME, gmtime(&now)); + len=snprintf(buf2,sizeof(buf2),"[%s] %s %s\n",timebuf,userbuf,buf); + write(logfd, buf2, len); +} diff --git a/pool/shard006/C/0118179_ieee80211_crypt_wep.c b/pool/shard006/C/0118179_ieee80211_crypt_wep.c new file mode 100644 index 0000000000000000000000000000000000000000..a41b6510481bc2c8238a93e316f7baef9be3e157 --- /dev/null +++ b/pool/shard006/C/0118179_ieee80211_crypt_wep.c @@ -0,0 +1,247 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Host AP crypt: host-based WEP encryption implementation for Host AP driver + * + * Copyright (c) 2002-2004, Jouni Malinen + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "ieee80211.h" + +#include +#include + +MODULE_AUTHOR("Jouni Malinen"); +MODULE_DESCRIPTION("Host AP crypt: WEP"); +MODULE_LICENSE("GPL"); + +struct prism2_wep_data { + u32 iv; +#define WEP_KEY_LEN 13 + u8 key[WEP_KEY_LEN + 1]; + u8 key_len; + u8 key_idx; + struct arc4_ctx rx_ctx_arc4; + struct arc4_ctx tx_ctx_arc4; +}; + + +static void *prism2_wep_init(int keyidx) +{ + struct prism2_wep_data *priv; + + if (fips_enabled) + return NULL; + + priv = kzalloc(sizeof(*priv), GFP_KERNEL); + if (!priv) + return NULL; + priv->key_idx = keyidx; + + /* start WEP IV from a random value */ + get_random_bytes(&priv->iv, 4); + + return priv; +} + + +static void prism2_wep_deinit(void *priv) +{ + kfree_sensitive(priv); +} + +/* Perform WEP encryption on given skb that has at least 4 bytes of headroom + * for IV and 4 bytes of tailroom for ICV. Both IV and ICV will be transmitted, + * so the payload length increases with 8 bytes. + * + * WEP frame payload: IV + TX key idx, RC4(data), ICV = RC4(CRC32(data)) + */ +static int prism2_wep_encrypt(struct sk_buff *skb, int hdr_len, void *priv) +{ + struct prism2_wep_data *wep = priv; + u32 klen, len; + u8 key[WEP_KEY_LEN + 3]; + u8 *pos; + struct cb_desc *tcb_desc = (struct cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE); + u32 crc; + u8 *icv; + + if (skb_headroom(skb) < 4 || skb_tailroom(skb) < 4 || + skb->len < hdr_len) + return -1; + + len = skb->len - hdr_len; + pos = skb_push(skb, 4); + memmove(pos, pos + 4, hdr_len); + pos += hdr_len; + + klen = 3 + wep->key_len; + + wep->iv++; + + /* Fluhrer, Mantin, and Shamir have reported weaknesses in the key + * scheduling algorithm of RC4. At least IVs (KeyByte + 3, 0xff, N) + * can be used to speedup attacks, so avoid using them. + */ + if ((wep->iv & 0xff00) == 0xff00) { + u8 B = (wep->iv >> 16) & 0xff; + + if (B >= 3 && B < klen) + wep->iv += 0x0100; + } + + /* Prepend 24-bit IV to RC4 key and TX frame */ + *pos++ = key[0] = (wep->iv >> 16) & 0xff; + *pos++ = key[1] = (wep->iv >> 8) & 0xff; + *pos++ = key[2] = wep->iv & 0xff; + *pos++ = wep->key_idx << 6; + + /* Copy rest of the WEP key (the secret part) */ + memcpy(key + 3, wep->key, wep->key_len); + + if (!tcb_desc->bHwSec) { + /* Append little-endian CRC32 and encrypt it to produce ICV */ + crc = ~crc32_le(~0, pos, len); + icv = skb_put(skb, 4); + icv[0] = crc; + icv[1] = crc >> 8; + icv[2] = crc >> 16; + icv[3] = crc >> 24; + + arc4_setkey(&wep->tx_ctx_arc4, key, klen); + arc4_crypt(&wep->tx_ctx_arc4, pos, pos, len + 4); + } + + return 0; +} + + +/* Perform WEP decryption on given buffer. Buffer includes whole WEP part of + * the frame: IV (4 bytes), encrypted payload (including SNAP header), + * ICV (4 bytes). len includes both IV and ICV. + * + * Returns 0 if frame was decrypted successfully and ICV was correct and -1 on + * failure. If frame is OK, IV and ICV will be removed. + */ +static int prism2_wep_decrypt(struct sk_buff *skb, int hdr_len, void *priv) +{ + struct prism2_wep_data *wep = priv; + u32 klen, plen; + u8 key[WEP_KEY_LEN + 3]; + u8 keyidx, *pos; + struct cb_desc *tcb_desc = (struct cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE); + u32 crc; + u8 icv[4]; + + if (skb->len < hdr_len + 8) + return -1; + + pos = skb->data + hdr_len; + key[0] = *pos++; + key[1] = *pos++; + key[2] = *pos++; + keyidx = *pos++ >> 6; + if (keyidx != wep->key_idx) + return -1; + + klen = 3 + wep->key_len; + + /* Copy rest of the WEP key (the secret part) */ + memcpy(key + 3, wep->key, wep->key_len); + + /* Apply RC4 to data and compute CRC32 over decrypted data */ + plen = skb->len - hdr_len - 8; + + if (!tcb_desc->bHwSec) { + arc4_setkey(&wep->rx_ctx_arc4, key, klen); + arc4_crypt(&wep->rx_ctx_arc4, pos, pos, plen + 4); + + crc = ~crc32_le(~0, pos, plen); + icv[0] = crc; + icv[1] = crc >> 8; + icv[2] = crc >> 16; + icv[3] = crc >> 24; + if (memcmp(icv, pos + plen, 4) != 0) { + /* ICV mismatch - drop frame */ + return -2; + } + } + /* Remove IV and ICV */ + memmove(skb->data + 4, skb->data, hdr_len); + skb_pull(skb, 4); + skb_trim(skb, skb->len - 4); + + return 0; +} + + +static int prism2_wep_set_key(void *key, int len, u8 *seq, void *priv) +{ + struct prism2_wep_data *wep = priv; + + if (len < 0 || len > WEP_KEY_LEN) + return -1; + + memcpy(wep->key, key, len); + wep->key_len = len; + + return 0; +} + + +static int prism2_wep_get_key(void *key, int len, u8 *seq, void *priv) +{ + struct prism2_wep_data *wep = priv; + + if (len < wep->key_len) + return -1; + + memcpy(key, wep->key, wep->key_len); + + return wep->key_len; +} + + +static char *prism2_wep_print_stats(char *p, void *priv) +{ + struct prism2_wep_data *wep = priv; + + p += sprintf(p, "key[%d] alg=WEP len=%d\n", + wep->key_idx, wep->key_len); + return p; +} + + +static struct ieee80211_crypto_ops ieee80211_crypt_wep = { + .name = "WEP", + .init = prism2_wep_init, + .deinit = prism2_wep_deinit, + .encrypt_mpdu = prism2_wep_encrypt, + .decrypt_mpdu = prism2_wep_decrypt, + .encrypt_msdu = NULL, + .decrypt_msdu = NULL, + .set_key = prism2_wep_set_key, + .get_key = prism2_wep_get_key, + .print_stats = prism2_wep_print_stats, + .extra_prefix_len = 4, /* IV */ + .extra_postfix_len = 4, /* ICV */ + .owner = THIS_MODULE, +}; + +int __init ieee80211_crypto_wep_init(void) +{ + return ieee80211_register_crypto_ops(&ieee80211_crypt_wep); +} + +void __exit ieee80211_crypto_wep_exit(void) +{ + ieee80211_unregister_crypto_ops(&ieee80211_crypt_wep); +} + diff --git a/pool/shard006/C/0118181_hid-gaff.c b/pool/shard006/C/0118181_hid-gaff.c new file mode 100644 index 0000000000000000000000000000000000000000..5a02c50443cb70057c6c6ae0a0c9fc10f6564781 --- /dev/null +++ b/pool/shard006/C/0118181_hid-gaff.c @@ -0,0 +1,185 @@ +/* + * Force feedback support for GreenAsia (Product ID 0x12) based devices + * + * The devices are distributed under various names and the same USB device ID + * can be used in many game controllers. + * + * + * 0e8f:0012 "GreenAsia Inc. USB Joystick " + * - tested with MANTA Warior MM816 and SpeedLink Strike2 SL-6635. + * + * Copyright (c) 2008 Lukasz Lubojanski + */ + +/* + * 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 +#include +#include +#include +#include "hid-ids.h" + +#ifdef CONFIG_GREENASIA_FF + +struct gaff_device { + struct hid_report *report; +}; + +static int hid_gaff_play(struct input_dev *dev, void *data, + struct ff_effect *effect) +{ + struct hid_device *hid = input_get_drvdata(dev); + struct gaff_device *gaff = data; + int left, right; + + left = effect->u.rumble.strong_magnitude; + right = effect->u.rumble.weak_magnitude; + + dbg_hid("called with 0x%04x 0x%04x", left, right); + + left = left * 0xfe / 0xffff; + right = right * 0xfe / 0xffff; + + gaff->report->field[0]->value[0] = 0x51; + gaff->report->field[0]->value[1] = 0x0; + gaff->report->field[0]->value[2] = right; + gaff->report->field[0]->value[3] = 0; + gaff->report->field[0]->value[4] = left; + gaff->report->field[0]->value[5] = 0; + dbg_hid("running with 0x%02x 0x%02x", left, right); + hid_hw_request(hid, gaff->report, HID_REQ_SET_REPORT); + + gaff->report->field[0]->value[0] = 0xfa; + gaff->report->field[0]->value[1] = 0xfe; + gaff->report->field[0]->value[2] = 0x0; + gaff->report->field[0]->value[4] = 0x0; + + hid_hw_request(hid, gaff->report, HID_REQ_SET_REPORT); + + return 0; +} + +static int gaff_init(struct hid_device *hid) +{ + struct gaff_device *gaff; + struct hid_report *report; + struct hid_input *hidinput; + struct list_head *report_list = + &hid->report_enum[HID_OUTPUT_REPORT].report_list; + struct list_head *report_ptr = report_list; + struct input_dev *dev; + int error; + + if (list_empty(&hid->inputs)) { + hid_err(hid, "no inputs found\n"); + return -ENODEV; + } + hidinput = list_entry(hid->inputs.next, struct hid_input, list); + dev = hidinput->input; + + if (list_empty(report_list)) { + hid_err(hid, "no output reports found\n"); + return -ENODEV; + } + + report_ptr = report_ptr->next; + + report = list_entry(report_ptr, struct hid_report, list); + if (report->maxfield < 1) { + hid_err(hid, "no fields in the report\n"); + return -ENODEV; + } + + if (report->field[0]->report_count < 6) { + hid_err(hid, "not enough values in the field\n"); + return -ENODEV; + } + + gaff = kzalloc(sizeof(struct gaff_device), GFP_KERNEL); + if (!gaff) + return -ENOMEM; + + set_bit(FF_RUMBLE, dev->ffbit); + + error = input_ff_create_memless(dev, gaff, hid_gaff_play); + if (error) { + kfree(gaff); + return error; + } + + gaff->report = report; + gaff->report->field[0]->value[0] = 0x51; + gaff->report->field[0]->value[1] = 0x00; + gaff->report->field[0]->value[2] = 0x00; + gaff->report->field[0]->value[3] = 0x00; + hid_hw_request(hid, gaff->report, HID_REQ_SET_REPORT); + + gaff->report->field[0]->value[0] = 0xfa; + gaff->report->field[0]->value[1] = 0xfe; + + hid_hw_request(hid, gaff->report, HID_REQ_SET_REPORT); + + hid_info(hid, "Force Feedback for GreenAsia 0x12 devices by Lukasz Lubojanski \n"); + + return 0; +} +#else +static inline int gaff_init(struct hid_device *hdev) +{ + return 0; +} +#endif + +static int ga_probe(struct hid_device *hdev, const struct hid_device_id *id) +{ + int ret; + + dev_dbg(&hdev->dev, "Greenasia HID hardware probe..."); + + ret = hid_parse(hdev); + if (ret) { + hid_err(hdev, "parse failed\n"); + goto err; + } + + ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT & ~HID_CONNECT_FF); + if (ret) { + hid_err(hdev, "hw start failed\n"); + goto err; + } + + gaff_init(hdev); + + return 0; +err: + return ret; +} + +static const struct hid_device_id ga_devices[] = { + { HID_USB_DEVICE(USB_VENDOR_ID_GREENASIA, 0x0012), }, + { } +}; +MODULE_DEVICE_TABLE(hid, ga_devices); + +static struct hid_driver ga_driver = { + .name = "greenasia", + .id_table = ga_devices, + .probe = ga_probe, +}; +module_hid_driver(ga_driver); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0118183_05test_homework.c b/pool/shard006/C/0118183_05test_homework.c new file mode 100644 index 0000000000000000000000000000000000000000..ff4528c0cd7bd2457257f04104ed998a8ac1ca7c --- /dev/null +++ b/pool/shard006/C/0118183_05test_homework.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//#define BIG_FILE_NAME "/var/ftp/pub/software/rhel-server-5.5-i386-dvd.iso" +//#define BIG_FILE_NAME "/var/ftp/pub/software/星际译王/词库/other/WyabdcRealPeopleTTS-1.0-1.noarch.rpm" +//#define BIG_FILE_NAME "/var/ftp/pub/book/ubuntu/Ubuntu权威指南.刑国庆.扫描版.pdf" +#define BIG_FILE_NAME "./1G" + +#ifndef BUF_SIZE +#define BUF_SIZE 4096 +#endif +#define DEFAULT_THR_NUM 3 + +char rbuf[BUF_SIZE]; +int fd; +int total_size; + +struct thr_info { + pthread_t tid; + size_t nread; +}; + +struct thr_info *pthr; + +static pthread_mutex_t rmutex = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; + + +/*验证多线程对单一大文件的读取的效率*/ +void *thr_read_file(void *arg) +{ + ssize_t nread; + int ret; + int idx = (int )arg; + printf("pthread_%d running\n", idx); + pthread_t tid = pthread_self(); + + for (;;) { + pthread_mutex_lock(&rmutex); + re_try: + nread = read(fd, rbuf, BUF_SIZE); + if (nread < 0) { + if (errno == EINTR) { + goto re_try; + }else { + perror("read"); + goto err; + } + } else if (nread == 0) { + pthr[idx].nread = (size_t)nread; + break; + } else { + pthr[idx].nread = (size_t)nread; + } + total_size += nread; + + pthread_mutex_unlock(&rmutex); + ret = pthread_cond_signal(&cond); + if (ret != 0) { + perror("pthread_cond_signal"); + goto err; + } + } + + pthread_mutex_unlock(&rmutex); + + return (void *)0; +err: + pthread_mutex_unlock(&rmutex); + return (void *)-1; +} + +int main(int argc, char *argv[]) +{ + printf("process is start, pid = %d\n", getpid()); + int n_thrs; + if (argc < 2) { + n_thrs = DEFAULT_THR_NUM; + } else { + n_thrs = atoi(argv[1]); + } + assert(n_thrs > 0); + + //打开目标文件 + fd = open(BIG_FILE_NAME, O_RDONLY); + + if (fd < 0) { + perror("open"); + exit(-1); + } + struct timeval time_start, time_end; + gettimeofday(&time_start, NULL); + + pthr = (struct thr_info *)calloc(n_thrs, sizeof(*pthr)); + + int idx, ret; + for ( idx = 0; idx < n_thrs; ++idx) { + ret = pthread_create(&pthr[idx].tid, NULL, thr_read_file, (void *)idx); + if (ret != 0) { + perror("pthread_create"); + exit(-1); + } + } + + for (idx = 0; idx < n_thrs; ++idx) { + ret = pthread_join(pthr[idx].tid, NULL); + if (ret != 0) { + perror("pthread_join"); + exit(-1); + } + } + gettimeofday(&time_end, NULL); + printf("total_size:%lu, cost: %lums\n", total_size, (time_end.tv_usec - time_start.tv_usec) / 1000); + + return 0; +} diff --git a/pool/shard006/C/0118187_ttyname_r.c b/pool/shard006/C/0118187_ttyname_r.c new file mode 100644 index 0000000000000000000000000000000000000000..448765877b843788651617870e624a930ae0dab3 --- /dev/null +++ b/pool/shard006/C/0118187_ttyname_r.c @@ -0,0 +1,53 @@ +/* ttyname_r.c - A ttyname_r() replacement. + Copyright (C) 2003, 2004 g10 Code GmbH + + This file is part of GPGME. + + GPGME 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. + + GPGME is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + 02111-1307, USA. */ + +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include + + +#warning ttyname is not thread-safe, and ttyname_r is missing + +int +ttyname_r (int fd, char *buf, size_t buflen) +{ + char *tty; + +#if HAVE_W32_SYSTEM + /* We use this default one for now. AFAICS we only need it to be + passed to gpg and in turn to pinentry. Providing a replacement + is needed because elsewhere we bail out on error. If we + eventually implement a pinentry for Windows it is uinlikely that + we need a real tty at all. */ + tty = "/dev/tty"; +#else + tty = ttyname (fd); + if (!tty) + return errno; +#endif + + strncpy (buf, tty, buflen); + buf[buflen - 1] = '\0'; + return (strlen (tty) >= buflen) ? ERANGE : 0; +} diff --git a/pool/shard006/C/0118188_jagbytopmultianewarray.c b/pool/shard006/C/0118188_jagbytopmultianewarray.c new file mode 100644 index 0000000000000000000000000000000000000000..1179d2186ab35b4070fece01b6d9c53a5fafe786 --- /dev/null +++ b/pool/shard006/C/0118188_jagbytopmultianewarray.c @@ -0,0 +1,112 @@ +/* + File: jagbytopmultianewarray.c + Project: jaguar-bytecode + Author: Douwe Vos + Date: Nov 4, 2012 + Web: http://www.natpad.net/ + e-mail: dmvos2000(at)yahoo.com + + Copyright (C) 2012 Douwe Vos. + + 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 . */ + +#include "jagbytopmultianewarray.h" +#include "../jagbytimnemonic.h" + +#include +#define CAT_LOG_LEVEL CAT_LOG_WARN +#define CAT_LOG_CLAZZ "JagBytOpMultiANewArray" +#include + +struct _JagBytOpMultiANewArrayPrivate { + int class_pool_index; + int dim_count; +}; + +static void l_imnemonic_iface_init(JagBytIMnemonicInterface *iface); + +G_DEFINE_TYPE_WITH_CODE(JagBytOpMultiANewArray, jag_byt_op_multi_a_new_array, JAG_BYT_TYPE_ABSTRACT_MNEMONIC, // @suppress("Unused static function") + G_ADD_PRIVATE(JagBytOpMultiANewArray) + G_IMPLEMENT_INTERFACE(JAG_BYT_TYPE_IMNEMONIC, l_imnemonic_iface_init) +); + +static void l_dispose(GObject *object); +static void l_finalize(GObject *object); + +static void jag_byt_op_multi_a_new_array_class_init(JagBytOpMultiANewArrayClass *clazz) { + GObjectClass *object_class = G_OBJECT_CLASS(clazz); + object_class->dispose = l_dispose; + object_class->finalize = l_finalize; +} + +static void jag_byt_op_multi_a_new_array_init(JagBytOpMultiANewArray *instance) { +} + +static void l_dispose(GObject *object) { + cat_log_detail("dispose:%p", object); + G_OBJECT_CLASS(jag_byt_op_multi_a_new_array_parent_class)->dispose(object); + cat_log_detail("disposed:%p", object); +} + +static void l_finalize(GObject *object) { + cat_log_detail("finalize:%p", object); + cat_ref_denounce(object); + G_OBJECT_CLASS(jag_byt_op_multi_a_new_array_parent_class)->finalize(object); + cat_log_detail("finalized:%p", object); +} + +JagBytOpMultiANewArray *jag_byt_op_multi_a_new_array_new(int offset, int class_pool_index, int dim_count) { + JagBytOpMultiANewArray *result = g_object_new(JAG_BYT_TYPE_OP_MULTI_A_NEW_ARRAY, NULL); + cat_ref_anounce(result); + JagBytOpMultiANewArrayPrivate *priv = jag_byt_op_multi_a_new_array_get_instance_private(result); + jag_byt_abstract_mnemonic_construct((JagBytAbstractMnemonic *) result, OP_MULTIANEWARRAY, offset, 4); + priv->class_pool_index = class_pool_index; + priv->dim_count = dim_count; + return result; +} + +int jag_byt_op_multi_a_new_array_get_class_info_pool_index(JagBytOpMultiANewArray *op_multi_new_array) { + JagBytOpMultiANewArrayPrivate *priv = jag_byt_op_multi_a_new_array_get_instance_private(op_multi_new_array); + return priv->class_pool_index; +} + +int jag_byt_op_multi_a_new_array_get_nr_of_dimensions(JagBytOpMultiANewArray *op_multi_new_array) { + JagBytOpMultiANewArrayPrivate *priv = jag_byt_op_multi_a_new_array_get_instance_private(op_multi_new_array); + return priv->dim_count; +} + +/********************* start JagBytIMnemonic implementation *********************/ + +static CatStringWo *l_to_string(JagBytIMnemonic *self, JagBytLabelRepository *label_repository) { + JagBytOpMultiANewArray *instance = JAG_BYT_OP_MULTI_A_NEW_ARRAY(self); + JagBytOpMultiANewArrayPrivate *priv = jag_byt_op_multi_a_new_array_get_instance_private(instance); + CatStringWo *result = cat_string_wo_new_with("multianewarray "); + cat_string_wo_append_decimal(result, priv->class_pool_index); + cat_string_wo_append_chars(result, ", "); + cat_string_wo_append_decimal(result, priv->dim_count); + return result; +} + +static void l_imnemonic_iface_init(JagBytIMnemonicInterface *iface) { + JagBytIMnemonicInterface *p_iface = g_type_interface_peek_parent(iface); + iface->getBranchOffset = p_iface->getBranchOffset; + iface->getContinuesOffset = p_iface->getContinuesOffset; + iface->getLength = p_iface->getLength; + iface->getOffset = p_iface->getOffset; + iface->getOperation = p_iface->getOperation; + iface->getOppCode = p_iface->getOppCode; + iface->toString = l_to_string; +} + +/********************* end JagBytIMnemonic implementation *********************/ diff --git a/pool/shard006/C/0118193_pcm.c b/pool/shard006/C/0118193_pcm.c new file mode 100644 index 0000000000000000000000000000000000000000..c9d119122c39df3eb7541de615b0dd82e916516d --- /dev/null +++ b/pool/shard006/C/0118193_pcm.c @@ -0,0 +1,161 @@ + + /** + * \file pcm.c + * \author François Grondin + * \version 2.0 + * \date 2018-03-18 + * \copyright + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 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 . + * + */ + + #include + + float pcm_signedXXbits2normalized(const char * bytes, const unsigned int nBytes) { + + int sample32; + float sampleFloat; + + switch(nBytes) { + + case 1: + + sample32 = 0; + sample32 += ((((signed char) bytes[3]) << 0) & 0xFFFFFFFF); + + sampleFloat = (float) sample32; + + sampleFloat /= 128.0f; + + break; + + case 2: + + sample32 = 0; + sample32 += ((((signed char) bytes[2]) << 0) & 0x000000FF); + sample32 += ((((signed char) bytes[3]) << 8) & 0xFFFFFF00); + + sampleFloat = (float) sample32; + + sampleFloat /= 32768.0f; + + break; + + case 3: + + sample32 = 0; + sample32 += ((((signed char) bytes[1]) << 0) & 0x000000FF); + sample32 += ((((signed char) bytes[2]) << 8) & 0x0000FF00); + sample32 += ((((signed char) bytes[3]) << 16) & 0xFFFF0000); + + sampleFloat = (float) sample32; + + sampleFloat /= 8388608.0f; + + break; + + case 4: + + sample32 = 0; + sample32 += ((((signed char) bytes[0]) << 0) & 0x000000FF); + sample32 += ((((signed char) bytes[1]) << 8) & 0x0000FF00); + sample32 += ((((signed char) bytes[2]) << 16) & 0x00FF0000); + sample32 += ((((signed char) bytes[3]) << 24) & 0xFF000000); + + sampleFloat = (float) sample32; + + sampleFloat /= 2147483648.0f; + + break; + + } + + return sampleFloat; + + } + + void pcm_signedXXbits2json(const char * bytes, const unsigned int nBytes, char * json) { + + unsigned int iByte; + char high; + char low; + + char hex[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; + + for (iByte = 0; iByte < nBytes; iByte++) { + + high = (bytes[iByte] >> 4) & 0x0F; + low = (bytes[iByte]) & 0x0F; + + json[iByte*2+0] = hex[high]; + json[iByte*2+1] = hex[low]; + + } + + } + + void pcm_normalized2signedXXbits(const float sample, const unsigned int nBytes, char * bytes) { + + int sample32; + + switch(nBytes) { + + case 1: + + sample32 = (signed int) (roundf(sample * 128.0f)); + + bytes[0] = 0x00; + bytes[1] = 0x00; + bytes[2] = 0x00; + bytes[3] = (signed char) ((sample32 & 0x000000FF) >> 0); + + break; + + case 2: + + sample32 = (signed int) (roundf(sample * 32768.0f)); + + bytes[0] = 0x00; + bytes[1] = 0x00; + bytes[2] = (signed char) ((sample32 & 0x000000FF) >> 0); + bytes[3] = (signed char) ((sample32 & 0x0000FF00) >> 8); + + break; + + case 3: + + sample32 = (signed int) (roundf(sample * 8388608.0f)); + + bytes[0] = 0x00; + bytes[1] = (signed char) ((sample32 & 0x000000FF) >> 0); + bytes[2] = (signed char) ((sample32 & 0x0000FF00) >> 8); + bytes[3] = (signed char) ((sample32 & 0x00FF0000) >> 16); + + break; + + case 4: + + sample32 = (signed int) (roundf(sample * 2147483648.0f)); + + bytes[0] = (signed char) ((sample32 & 0x000000FF) >> 0); + bytes[1] = (signed char) ((sample32 & 0x0000FF00) >> 8); + bytes[2] = (signed char) ((sample32 & 0x00FF0000) >> 16); + bytes[3] = (signed char) ((sample32 & 0xFF000000) >> 24); + + break; + + } + + } diff --git a/pool/shard006/C/0118194_tc.c b/pool/shard006/C/0118194_tc.c new file mode 100644 index 0000000000000000000000000000000000000000..5354211e50b8f02bfe0f86d5ea896c42f2073dd0 --- /dev/null +++ b/pool/shard006/C/0118194_tc.c @@ -0,0 +1,111 @@ +/** + * @file + * Tokyocabinet DB backend for the header cache + * + * @authors + * Copyright (C) 2004 Thomas Glanzmann + * Copyright (C) 2004 Tobias Werth + * Copyright (C) 2004 Brian Fundakowski Feldman + * Copyright (C) 2016 Pietro Cerutti + * + * @copyright + * This program is free software: you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation, either version 2 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + */ + +#include "config.h" +#include +#include +#include +#include "backend.h" +#include "lib.h" +#include "options.h" + +static void *hcache_tokyocabinet_open(const char *path) +{ + TCBDB *db = tcbdbnew(); + if (!db) + return NULL; + if (option(OPTHCACHECOMPRESS)) + tcbdbtune(db, 0, 0, 0, -1, -1, BDBTDEFLATE); + if (tcbdbopen(db, path, BDBOWRITER | BDBOCREAT)) + return db; + else + { +#ifdef DEBUG + int ecode = tcbdbecode(db); + mutt_debug(2, "tcbdbopen failed for %s: %s (ecode %d)\n", path, + tcbdberrmsg(ecode), ecode); +#endif + tcbdbdel(db); + return NULL; + } +} + +static void *hcache_tokyocabinet_fetch(void *ctx, const char *key, size_t keylen) +{ + int sp; + + if (!ctx) + return NULL; + + TCBDB *db = ctx; + return tcbdbget(db, key, keylen, &sp); +} + +static void hcache_tokyocabinet_free(void *ctx, void **data) +{ + FREE(data); +} + +static int hcache_tokyocabinet_store(void *ctx, const char *key, size_t keylen, + void *data, size_t dlen) +{ + if (!ctx) + return -1; + + TCBDB *db = ctx; + return tcbdbput(db, key, keylen, data, dlen); +} + +static int hcache_tokyocabinet_delete(void *ctx, const char *key, size_t keylen) +{ + if (!ctx) + return -1; + + TCBDB *db = ctx; + return tcbdbout(db, key, keylen); +} + +static void hcache_tokyocabinet_close(void **ctx) +{ + if (!ctx || !*ctx) + return; + + TCBDB *db = *ctx; + if (!tcbdbclose(db)) + { +#ifdef DEBUG + int ecode = tcbdbecode(db); + mutt_debug(2, "tcbdbclose failed: %s (ecode %d)\n", tcbdberrmsg(ecode), ecode); +#endif + } + tcbdbdel(db); +} + +static const char *hcache_tokyocabinet_backend(void) +{ + return "tokyocabinet " _TC_VERSION; +} + +HCACHE_BACKEND_OPS(tokyocabinet) diff --git a/pool/shard006/C/0118196_cuckootest2.c b/pool/shard006/C/0118196_cuckootest2.c new file mode 100644 index 0000000000000000000000000000000000000000..d40141a1894e016d08417efd02c6d64886c45d81 --- /dev/null +++ b/pool/shard006/C/0118196_cuckootest2.c @@ -0,0 +1,57 @@ +#include "cuckoo_filter.h" +#define FILTER_COUNT 10000 + +int +main (int argc, char ** argv) { + cuckoo_filter_t *filters[FILTER_COUNT]; + bool rc; + printf("NEW\n"); + { + int i; + for (i = 0; i < FILTER_COUNT; i++) { + rc = cuckoo_filter_new(&(filters[i]), 100, 100, + (uint32_t) (time(NULL) & 0xffffffff)); + if (CUCKOO_FILTER_OK != rc) { + printf("%s/%d: %d\n", __func__, __LINE__, rc); + } + printf("%d ", i); + } + } + + printf("CONTAINS\n"); + { + int i; + for (i = 0; i < FILTER_COUNT; i++) { + rc = cuckoo_filter_contains(filters[i], "123456789012345676890", 20); + if (CUCKOO_FILTER_OK == rc) { + printf("%s/%d: %d\n", __func__, __LINE__, rc); + } + printf("%d ", i); + } + } + + printf("ADD\n"); + { + int i; + for (i = 0; i < FILTER_COUNT; i++) { + rc = cuckoo_filter_add(filters[i], "123456789012345676890", 20); + if (CUCKOO_FILTER_OK != rc) { + printf("%s/%d: %d\n", __func__, __LINE__, rc); + } + printf("%d ", i); + } + } + + printf("FREE\n"); + { + int i; + for (i = 0; i < FILTER_COUNT; i++) { + rc = cuckoo_filter_free(&(filters[i])); + printf("%d ", i); + } + } + + return EXIT_SUCCESS; + +} /* main() */ + diff --git a/pool/shard006/C/0118197_options.c b/pool/shard006/C/0118197_options.c new file mode 100644 index 0000000000000000000000000000000000000000..e6c7859302a4ce58358a143cc4cc67d37e1df9b7 --- /dev/null +++ b/pool/shard006/C/0118197_options.c @@ -0,0 +1,236 @@ +/* FRV simulator memory option handling. + Copyright (C) 1999-2017 Free Software Foundation, Inc. + Contributed by Red Hat. + +This file is part of GDB, the GNU debugger. + +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 . */ + +#define WANT_CPU frvbf +#define WANT_CPU_FRVBF + +#include "sim-main.h" +#include "sim-assert.h" +#include "sim-options.h" + +#ifdef HAVE_STRING_H +#include +#else +#ifdef HAVE_STRINGS_H +#include +#endif +#endif +#ifdef HAVE_STDLIB_H +#include +#endif + +/* FRV specific command line options. */ + +enum { + OPTION_FRV_DATA_CACHE = OPTION_START, + OPTION_FRV_INSN_CACHE, + OPTION_FRV_PROFILE_CACHE, + OPTION_FRV_PROFILE_PARALLEL, + OPTION_FRV_TIMER, + OPTION_FRV_MEMORY_LATENCY +}; + +static DECLARE_OPTION_HANDLER (frv_option_handler); + +const OPTION frv_options[] = +{ + { {"profile", optional_argument, NULL, 'p'}, + 'p', "on|off", "Perform profiling", + frv_option_handler }, + { {"data-cache", optional_argument, NULL, OPTION_FRV_DATA_CACHE }, + '\0', "WAYS[,SETS[,LINESIZE]]", "Enable data cache", + frv_option_handler }, + { {"insn-cache", optional_argument, NULL, OPTION_FRV_INSN_CACHE }, + '\0', "WAYS[,SETS[,LINESIZE]]", "Enable instruction cache", + frv_option_handler }, + { {"profile-cache", optional_argument, NULL, OPTION_FRV_PROFILE_CACHE }, + '\0', "on|off", "Profile caches", + frv_option_handler }, + { {"profile-parallel", optional_argument, NULL, OPTION_FRV_PROFILE_PARALLEL }, + '\0', "on|off", "Profile parallelism", + frv_option_handler }, + { {"timer", required_argument, NULL, OPTION_FRV_TIMER }, + '\0', "CYCLES,INTERRUPT", "Set Interrupt Timer", + frv_option_handler }, + { {"memory-latency", required_argument, NULL, OPTION_FRV_MEMORY_LATENCY }, + '\0', "CYCLES", "Set Latency of memory", + frv_option_handler }, + { {NULL, no_argument, NULL, 0}, '\0', NULL, NULL, NULL } +}; + +static char * +parse_size (char *chp, address_word *nr_bytes) +{ + /* */ + *nr_bytes = strtoul (chp, &chp, 0); + return chp; +} + +static address_word +check_pow2 (address_word value, char *argname, char *optname, SIM_DESC sd) +{ + if ((value & (value - 1)) != 0) + { + sim_io_eprintf (sd, "%s argument to %s must be a power of 2\n", + argname, optname); + return 0; /* will enable default value. */ + } + + return value; +} + +static void +parse_cache_option (SIM_DESC sd, char *arg, char *cache_name, int is_data_cache) +{ + int i; + address_word ways = 0, sets = 0, linesize = 0; + if (arg != NULL) + { + char *chp = arg; + /* parse the arguments */ + chp = parse_size (chp, &ways); + ways = check_pow2 (ways, "WAYS", cache_name, sd); + if (*chp == ',') + { + chp = parse_size (chp + 1, &sets); + sets = check_pow2 (sets, "SETS", cache_name, sd); + if (*chp == ',') + { + chp = parse_size (chp + 1, &linesize); + linesize = check_pow2 (linesize, "LINESIZE", cache_name, sd); + } + } + } + for (i = 0; i < MAX_NR_PROCESSORS; ++i) + { + SIM_CPU *current_cpu = STATE_CPU (sd, i); + FRV_CACHE *cache = is_data_cache ? CPU_DATA_CACHE (current_cpu) + : CPU_INSN_CACHE (current_cpu); + cache->ways = ways; + cache->sets = sets; + cache->line_size = linesize; + frv_cache_init (current_cpu, cache); + } +} + +static SIM_RC +frv_option_handler (SIM_DESC sd, sim_cpu *current_cpu, int opt, + char *arg, int is_command) +{ + switch (opt) + { + case 'p' : + if (! WITH_PROFILE) + sim_io_eprintf (sd, "Profiling not compiled in, `-p' ignored\n"); + else + { + unsigned mask = PROFILE_USEFUL_MASK; + if (WITH_PROFILE_CACHE_P) + mask |= (1 << PROFILE_CACHE_IDX); + if (WITH_PROFILE_PARALLEL_P) + mask |= (1 << PROFILE_PARALLEL_IDX); + return set_profile_option_mask (sd, "profile", mask, arg); + } + break; + + case OPTION_FRV_DATA_CACHE: + parse_cache_option (sd, arg, "data_cache", 1/*is_data_cache*/); + return SIM_RC_OK; + + case OPTION_FRV_INSN_CACHE: + parse_cache_option (sd, arg, "insn_cache", 0/*is_data_cache*/); + return SIM_RC_OK; + + case OPTION_FRV_PROFILE_CACHE: + if (WITH_PROFILE_CACHE_P) + return sim_profile_set_option (sd, "-cache", PROFILE_CACHE_IDX, arg); + else + sim_io_eprintf (sd, "Cache profiling not compiled in, `--profile-cache' ignored\n"); + break; + + case OPTION_FRV_PROFILE_PARALLEL: + if (WITH_PROFILE_PARALLEL_P) + { + unsigned mask + = (1 << PROFILE_MODEL_IDX) | (1 << PROFILE_PARALLEL_IDX); + return set_profile_option_mask (sd, "-parallel", mask, arg); + } + else + sim_io_eprintf (sd, "Parallel profiling not compiled in, `--profile-parallel' ignored\n"); + break; + + case OPTION_FRV_TIMER: + { + char *chp = arg; + address_word cycles, interrupt; + chp = parse_size (chp, &cycles); + if (chp == arg) + { + sim_io_eprintf (sd, "Cycle count required for --timer\n"); + return SIM_RC_FAIL; + } + if (*chp != ',') + { + sim_io_eprintf (sd, "Interrupt number required for --timer\n"); + return SIM_RC_FAIL; + } + chp = parse_size (chp + 1, &interrupt); + if (interrupt < 1 || interrupt > 15) + { + sim_io_eprintf (sd, "Interrupt number for --timer must be greater than 0 and less that 16\n"); + return SIM_RC_FAIL; + } + frv_interrupt_state.timer.enabled = 1; + frv_interrupt_state.timer.value = cycles; + frv_interrupt_state.timer.current = 0; + frv_interrupt_state.timer.interrupt = + FRV_INTERRUPT_LEVEL_1 + interrupt - 1; + } + return SIM_RC_OK; + + case OPTION_FRV_MEMORY_LATENCY: + { + int i; + char *chp = arg; + address_word cycles; + chp = parse_size (chp, &cycles); + if (chp == arg) + { + sim_io_eprintf (sd, "Cycle count required for --memory-latency\n"); + return SIM_RC_FAIL; + } + for (i = 0; i < MAX_NR_PROCESSORS; ++i) + { + SIM_CPU *current_cpu = STATE_CPU (sd, i); + FRV_CACHE *insn_cache = CPU_INSN_CACHE (current_cpu); + FRV_CACHE *data_cache = CPU_DATA_CACHE (current_cpu); + insn_cache->memory_latency = cycles; + data_cache->memory_latency = cycles; + } + } + return SIM_RC_OK; + + default: + sim_io_eprintf (sd, "Unknown FRV option %d\n", opt); + return SIM_RC_FAIL; + + } + + return SIM_RC_FAIL; +} diff --git a/pool/shard006/C/0118198_time.c b/pool/shard006/C/0118198_time.c new file mode 100644 index 0000000000000000000000000000000000000000..c08985dbd21d429d417bff9028b02af4deb4fb81 --- /dev/null +++ b/pool/shard006/C/0118198_time.c @@ -0,0 +1,169 @@ +/* time - time a command Authors: Andy Tanenbaum & Michiel Huisjes */ + +#define NEW 1 + +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef __nucleos__ +#include +#include +#endif +#include + +/* -DNEW prints time to 0.01 sec. */ +#ifdef NEW +#define HUNDREDTHS 1 +#endif + +char **args; +char *name; + +int digit_seen; +char a[] = " . \0"; + +_PROTOTYPE(int main, (int argc, char **argv)); +_PROTOTYPE(void print_time, (clock_t t)); +_PROTOTYPE(void twin, (int n, char *p)); +_PROTOTYPE(void execute, (void)); + +int main(argc, argv) +int argc; +char *argv[]; +{ + + struct tms pre_buf, post_buf; + int status, pid; +#if _VMD_EXT + struct timeval start_time, end_time; +#else + struct tms dummy; + int start_time, end_time; +#endif + clock_t real_time; + + if (argc == 1) exit(0); + + args = &argv[1]; + name = argv[1]; + + /* Get real time at start of run. */ +#if _VMD_EXT + (void) sysutime(UTIME_TIMEOFDAY, &start_time); +#else + start_time = times(&dummy); +#endif + + /* Fork off child. */ + if ((pid = fork()) < 0) { + std_err("Cannot fork\n"); + exit(1); + } + if (pid == 0) execute(); + + /* Parent is the time program. Disable interrupts and wait. */ + signal(SIGINT, SIG_IGN); + signal(SIGQUIT, SIG_IGN); + + do { + times(&pre_buf); + } while (wait(&status) != pid); +#if _VMD_EXT + (void) sysutime(UTIME_TIMEOFDAY, &end_time); + real_time = (end_time.tv_sec - start_time.tv_sec) * CLOCKS_PER_SEC + + (end_time.tv_usec - start_time.tv_usec) * CLOCKS_PER_SEC / 1000000; +#else + end_time = times(&dummy); + real_time = (end_time - start_time); +#endif + + if ((status & 0377) != 0) std_err("Command terminated abnormally.\n"); + times(&post_buf); + + /* Print results. -DNEW enables time on one line to 0.01 sec */ +#ifndef NEW + std_err("real "); + print_time(real_time); + std_err("\nuser "); + print_time(post_buf.tms_cutime - pre_buf.tms_cutime); + std_err("\nsys "); + print_time(post_buf.tms_cstime - pre_buf.tms_cstime); + std_err("\n"); +#else + print_time(real_time); + std_err(" real"); + print_time(post_buf.tms_cutime - pre_buf.tms_cutime); + std_err(" user"); + print_time(post_buf.tms_cstime - pre_buf.tms_cstime); + std_err(" sys\n"); +#endif + return((status & 0377) ? -1 : (status >> 8)); +} + +void print_time(t) +register clock_t t; +{ +/* Print the time 't' in hours: minutes: seconds. 't' is in ticks. */ + + int hours, minutes, seconds, hundredths, i; + u32_t system_hz; +#ifndef __nucleos__ + getsysinfo_up(PM_PROC_NR, SIU_SYSTEMHZ, sizeof(system_hz), &system_hz); +#else + system_hz = HZ; +#endif + digit_seen = 0; + for (i = 0; i < 8; i++) a[i] = ' '; + hours = (int) (t / ((clock_t) 3600 * system_hz)); + t -= (clock_t) hours * 3600 * system_hz; + minutes = (int) (t / ((clock_t) 60 * system_hz)); + t -= (clock_t) minutes * 60 * system_hz; + seconds = (int) (t / system_hz); + t -= (clock_t) seconds * system_hz; + hundredths = (int) (t * 100 / system_hz); + + if (hours) { + twin(hours, &a[0]); + a[2] = ':'; + } + if (minutes || digit_seen) { + twin(minutes, &a[3]); + a[5] = ':'; + } + if (seconds || digit_seen) + twin(seconds, &a[6]); + else + a[7] = '0'; + a[9] = hundredths / 10 + '0'; +#ifdef HUNDREDTHS /* tenths used to be enough */ + a[10] = hundredths % 10 + '0'; +#endif + std_err(a); +} + +void twin(n, p) +int n; +char *p; +{ + char c1, c2; + c1 = (n / 10) + '0'; + c2 = (n % 10) + '0'; + if (digit_seen == 0 && c1 == '0') c1 = ' '; + *p++ = c1; + *p++ = c2; + if (n > 0) digit_seen = 1; +} + +void execute() +{ + execvp(name, args); + std_err("Cannot execute "); + std_err(name); + std_err("\n"); + exit(-1); +} diff --git a/pool/shard006/C/0118200_sorting.c b/pool/shard006/C/0118200_sorting.c new file mode 100644 index 0000000000000000000000000000000000000000..fe764dfbbea29f8bacacbf7faae3da72fd8b624e --- /dev/null +++ b/pool/shard006/C/0118200_sorting.c @@ -0,0 +1,186 @@ +#include + +/* + * + * sorting + * ------- + * S.No. | name | O(n) + * ------------------------ + * 1. | bubble | n*n + * 2. | selection | n*n + * 3. | insertion | n*n + * 4. | merge | n*lg n + * 5. | quck | n*lg n + */ + + + +/* + * pattern + * 0 1 2 3 4 5 ..x + * 0 01 12 23 34 45 56 + * 1 01 12 23 34 45 + * 2 01 12 23 34 + * 4 01 12 23 + * 5 01 12 + * 6 01 + * + * x + * + */ + + +int DL = 0; + +// 1. swap | swapping two index values in an array +void _swap(int A[], int i, int j){ + + if(A[i] > A[j]){ + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + } +} + +// 2. bubble sort +void bubble_sort(int A[], int start, int end) +{ + int x = start, y = start; + + for(y = start;y <= end; y++){ + for(x = start; x <= end - y; x++){ + printf("%d %d \t", x, x + 1); + _swap(A, x, x + 1); + } + printf("\n"); + } +} + +/* + * + * 1 12 13 14 15 16 + * 2 23 24 25 26 + * 3 34 35 36 + * 4 45 46 + * 5 56 + */ + +// 3. selection sort +void selection_sort(int A[], int start, int end) +{ + int x = start, y = start; + + for(y = start; y < end; y++){ + for(x = y + 1; x <= end; x++){ + printf("%d %d \t", y, x); + _swap(A, y, x); + } + printf("\n"); + } + +} + +/* + * + */ +// 4. insertion sort +void insertion_sort(int A[], int start, int end); + + +// 5. copy | copies from one array to another with specified start indices and end (from) +int copy(int from[], int to[], int f_start, int t_start, int f_end) +{ + printf("\n %d DEBUG ( copy) , f_start : %d, f_end : %d, t_start : %d", DL++, + f_start, f_end, t_start); + + for(; (to[t_start] = from[f_start]) && f_start <= f_end; t_start++,f_start++); +} + + +// merge | merge two sorted arrays +void merge(int A[], int start, int mid, int end) +{ + // 0, 1, 3 + // left [start - mid] + // right [ mid+1, right] + // left = 0, 1, = mid + 1 - start + // right = 1, 3 = end - mid + + // debug message + printf("\n %d DEBUG ( merg) , start : %d, end : %d, mid : %d", DL++, start, end, + mid); + + // getting left and right size + int l_size = mid + 1 - start, r_size = end - mid; + + printf("\n %d DEBUG ( merg) , l_size : %d, r_size : %d ", DL++, l_size, r_size); + + // copying the elements in left and right array + int left[l_size]; copy(A, left, start, 0, mid); + int right[r_size]; copy(A, right, mid + 1, 0, end); + + // + printf("\n array \n"); + display_array(A, start, end); + + printf("\n left \n"); + display_array(left, 0, l_size); + + printf("\n right \n"); + display_array(right, 0, r_size); + + int pos_l = 0, pos_r = 0, pos_a = 0; + // if both contain elements + + // choose lesser + // else + // fill with A + // else + // fill with B +} + +void merge_sort(int A[], int start, int end) +{ + if (end > start){ + int mid = (int)((start + end) / 2); + printf("\n %d DEBUG (me_so) start : %d, end : %d, mid : %d", DL++, start, + end, mid); + merge_sort(A, start, mid); + merge_sort(A, mid + 1, end); + merge(A, start, mid, end); + + // 0 4 = 0 1 2 | 3 4 = 0, 2, 4 + } +} + +void quick_sort(int A[], int start, int end); + + +void display_array(int A[], int start, int end){ + start--; + while(start < end) + printf("%d %d \n", start, A[++start]); +} + + +int main(){ + printf("-------------------------------------- \n"); + int space[10] = {2, 5, 1, 6, 2, 9, 1, 3, 8, 4}; + display_array(space, 0, 9); + + bubble_sort(space, 0, 9); + // selection_sort(space, 0, 9); + // insertion_sort(space, 0, 9); + // merge_sort(space, 0, 9); + // quick_sort(space, 0, 9); + + //int t_space[10]; + //copy(space, t_space, 0, 9); + display_array(space, 0, 9); + // + + // merge(space, 0, 4, 9); + + return 0; +} + diff --git a/pool/shard006/C/0118201_filerw.c b/pool/shard006/C/0118201_filerw.c new file mode 100644 index 0000000000000000000000000000000000000000..f074e67547e232951be7a37ad149362a6647d237 --- /dev/null +++ b/pool/shard006/C/0118201_filerw.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include + +int main (int argc, char *argv[]) { + char f1[1024], f2[1024]; + char * filename1 = NULL; + char * filename2 = NULL; + FILE * fp1 = NULL; + FILE * fp2 = NULL; + int bytes; + char c, d; + + if (argc < 3) { + printf("Usage: %s \n", argv[0]); + return argc; + } + + filename1 = argv[1]; + filename2 = argv[2]; + printf("Reading file %s\n", filename1); + printf("Writing file %s\n", filename2); + + fp1 = fopen(filename1, "r"); + fp2 = fopen(filename2, "w"); + + if (!fp1) { + printf("cannot open %s for read\n", filename1); + return -1; + } + if (!fp2) { + printf("cannot open %s for write\n", filename2); + return -2; + } + + + while ((c = fgetc(fp1)) != EOF) { + bytes++; + printf("%c", c); + + if ((d = fputc(c, fp2)) == EOF) { + printf("write error to file %s\n", filename2); + return -3; + } + } + + c = EOF; + printf("\nsup: EOF is %d, %u, %x\n", c, c, c); + + fclose(fp1); + fclose(fp2); + printf("Copied %d bytes from %s to %s\n", bytes, filename1, filename2); + + + // Check md5sum + sprintf(f1, "shasum %s", filename1); + sprintf(f2, "shasum %s", filename2); + system(f1); + system(f2); + + return 0; +} + + diff --git a/pool/shard006/C/0118202_tef6862.c b/pool/shard006/C/0118202_tef6862.c new file mode 100644 index 0000000000000000000000000000000000000000..d5c1e620dd29ffda725d8b06f6c14dff186ead1f --- /dev/null +++ b/pool/shard006/C/0118202_tef6862.c @@ -0,0 +1,222 @@ +/* + * tef6862.c Philips TEF6862 Car Radio Enhanced Selectivity Tuner + * Copyright (c) 2009 Intel Corporation + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DRIVER_NAME "tef6862" + +#define FREQ_MUL 16000 + +#define TEF6862_LO_FREQ (875 * FREQ_MUL / 10) +#define TEF6862_HI_FREQ (108 * FREQ_MUL) + +/* Write mode sub addresses */ +#define WM_SUB_BANDWIDTH 0x0 +#define WM_SUB_PLLM 0x1 +#define WM_SUB_PLLL 0x2 +#define WM_SUB_DAA 0x3 +#define WM_SUB_AGC 0x4 +#define WM_SUB_BAND 0x5 +#define WM_SUB_CONTROL 0x6 +#define WM_SUB_LEVEL 0x7 +#define WM_SUB_IFCF 0x8 +#define WM_SUB_IFCAP 0x9 +#define WM_SUB_ACD 0xA +#define WM_SUB_TEST 0xF + +/* Different modes of the MSA register */ +#define MODE_BUFFER 0x0 +#define MODE_PRESET 0x1 +#define MODE_SEARCH 0x2 +#define MODE_AF_UPDATE 0x3 +#define MODE_JUMP 0x4 +#define MODE_CHECK 0x5 +#define MODE_LOAD 0x6 +#define MODE_END 0x7 +#define MODE_SHIFT 5 + +struct tef6862_state { + struct v4l2_subdev sd; + unsigned long freq; +}; + +static inline struct tef6862_state *to_state(struct v4l2_subdev *sd) +{ + return container_of(sd, struct tef6862_state, sd); +} + +static u16 tef6862_sigstr(struct i2c_client *client) +{ + u8 buf[4]; + int err = i2c_master_recv(client, buf, sizeof(buf)); + if (err == sizeof(buf)) + return buf[3] << 8; + return 0; +} + +static int tef6862_g_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v) +{ + if (v->index > 0) + return -EINVAL; + + /* only support FM for now */ + strlcpy(v->name, "FM", sizeof(v->name)); + v->type = V4L2_TUNER_RADIO; + v->rangelow = TEF6862_LO_FREQ; + v->rangehigh = TEF6862_HI_FREQ; + v->rxsubchans = V4L2_TUNER_SUB_MONO; + v->capability = V4L2_TUNER_CAP_LOW; + v->audmode = V4L2_TUNER_MODE_STEREO; + v->signal = tef6862_sigstr(v4l2_get_subdevdata(sd)); + + return 0; +} + +static int tef6862_s_tuner(struct v4l2_subdev *sd, struct v4l2_tuner *v) +{ + return v->index ? -EINVAL : 0; +} + +static int tef6862_s_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f) +{ + struct tef6862_state *state = to_state(sd); + struct i2c_client *client = v4l2_get_subdevdata(sd); + u16 pll; + u8 i2cmsg[3]; + int err; + + if (f->tuner != 0) + return -EINVAL; + + pll = 1964 + ((f->frequency - TEF6862_LO_FREQ) * 20) / FREQ_MUL; + i2cmsg[0] = (MODE_PRESET << MODE_SHIFT) | WM_SUB_PLLM; + i2cmsg[1] = (pll >> 8) & 0xff; + i2cmsg[2] = pll & 0xff; + + err = i2c_master_send(client, i2cmsg, sizeof(i2cmsg)); + if (err != sizeof(i2cmsg)) + return err < 0 ? err : -EIO; + + state->freq = f->frequency; + return 0; +} + +static int tef6862_g_frequency(struct v4l2_subdev *sd, struct v4l2_frequency *f) +{ + struct tef6862_state *state = to_state(sd); + + if (f->tuner != 0) + return -EINVAL; + f->type = V4L2_TUNER_RADIO; + f->frequency = state->freq; + return 0; +} + +static int tef6862_g_chip_ident(struct v4l2_subdev *sd, + struct v4l2_dbg_chip_ident *chip) +{ + struct i2c_client *client = v4l2_get_subdevdata(sd); + + return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_TEF6862, 0); +} + +static const struct v4l2_subdev_tuner_ops tef6862_tuner_ops = { + .g_tuner = tef6862_g_tuner, + .s_tuner = tef6862_s_tuner, + .s_frequency = tef6862_s_frequency, + .g_frequency = tef6862_g_frequency, +}; + +static const struct v4l2_subdev_core_ops tef6862_core_ops = { + .g_chip_ident = tef6862_g_chip_ident, +}; + +static const struct v4l2_subdev_ops tef6862_ops = { + .core = &tef6862_core_ops, + .tuner = &tef6862_tuner_ops, +}; + +/* + * Generic i2c probe + * concerning the addresses: i2c wants 7 bit (without the r/w bit), so '>>1' + */ + +static int __devinit tef6862_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct tef6862_state *state; + struct v4l2_subdev *sd; + + /* Check if the adapter supports the needed features */ + if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) + return -EIO; + + v4l_info(client, "chip found @ 0x%02x (%s)\n", + client->addr << 1, client->adapter->name); + + state = kzalloc(sizeof(struct tef6862_state), GFP_KERNEL); + if (state == NULL) + return -ENOMEM; + state->freq = TEF6862_LO_FREQ; + + sd = &state->sd; + v4l2_i2c_subdev_init(sd, client, &tef6862_ops); + + return 0; +} + +static int __devexit tef6862_remove(struct i2c_client *client) +{ + struct v4l2_subdev *sd = i2c_get_clientdata(client); + + v4l2_device_unregister_subdev(sd); + kfree(to_state(sd)); + return 0; +} + +static const struct i2c_device_id tef6862_id[] = { + {DRIVER_NAME, 0}, + {}, +}; + +MODULE_DEVICE_TABLE(i2c, tef6862_id); + +static struct i2c_driver tef6862_driver = { + .driver = { + .owner = THIS_MODULE, + .name = DRIVER_NAME, + }, + .probe = tef6862_probe, + .remove = tef6862_remove, + .id_table = tef6862_id, +}; + +module_i2c_driver(tef6862_driver); + +MODULE_DESCRIPTION("TEF6862 Car Radio Enhanced Selectivity Tuner"); +MODULE_AUTHOR("Mocean Laboratories"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard006/C/0118204_syscall.c b/pool/shard006/C/0118204_syscall.c new file mode 100644 index 0000000000000000000000000000000000000000..4195681bb513c250807112bfab902baa686a760d --- /dev/null +++ b/pool/shard006/C/0118204_syscall.c @@ -0,0 +1,95 @@ +/* + * Distributed Shared NVM. + * + * Copyright (c) 2016-2017 Wuklab, Purdue University. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + */ + +#include +#include +#include +#include + +#include "dsnvm.h" + +static int (*dist_lock_hook)(void *); +static int (*dist_unlock_hook)(void *); +static int (*dist_create_lock_hook)(unsigned int, void *, unsigned int, void *); +static void (*dist_sync_barrier_hook)(void); + +static void (*dist_mmap_consensus_hook)(struct file *file, unsigned long *addr, unsigned long len); + +int register_dist_lock_hooks(const struct dist_hooks *hooks) +{ + if (unlikely(!hooks)) + return -EINVAL; + + if (unlikely(!hooks->dist_lock_hook || !hooks->dist_unlock_hook || + !hooks->dist_create_lock_hook || !hooks->dist_sync_barrier_hook || + !hooks->dist_mmap_consensus_hook)) + return -EINVAL; + + dist_lock_hook = hooks->dist_lock_hook; + dist_unlock_hook = hooks->dist_unlock_hook; + dist_create_lock_hook = hooks->dist_create_lock_hook; + dist_sync_barrier_hook = hooks->dist_sync_barrier_hook; + + dist_mmap_consensus_hook = hooks->dist_mmap_consensus_hook; + + return 0; +} +EXPORT_SYMBOL(register_dist_lock_hooks); + +void unregister_dist_lock_hooks(void) +{ + dist_lock_hook = NULL; + dist_unlock_hook = NULL; + dist_create_lock_hook = NULL; + dist_sync_barrier_hook = NULL; + + dist_mmap_consensus_hook = NULL; +} +EXPORT_SYMBOL(unregister_dist_lock_hooks); + +void dist_mmap_consensus(struct file *file, unsigned long *addr, unsigned long len) +{ + if (likely(dist_mmap_consensus_hook)) + dist_mmap_consensus_hook(file, addr, len); + else + pr_info("WARNING: Install DSNVM before call dist_mmap_consensus"); +} + +SYSCALL_DEFINE1(dist_lock, void __user *, key) +{ + if (likely(dist_lock_hook)) + return dist_lock_hook(key); + return -EFAULT; +} + +SYSCALL_DEFINE1(dist_unlock, void __user *, key) +{ + if (likely(dist_unlock_hook)) + return dist_unlock_hook(key); + return -EFAULT; +} + +SYSCALL_DEFINE4(dist_create_lock, unsigned int, target_node, void __user *, msg, + unsigned int, size, void __user *, output_mr) +{ + if (likely(dist_create_lock_hook)) + return dist_create_lock_hook(target_node, msg, size, output_mr); + return -EFAULT; +} + +SYSCALL_DEFINE0(dist_sync_barrier) +{ + if (likely(dist_sync_barrier_hook)) { + dist_sync_barrier_hook(); + return 0; + } + return -EFAULT; +} diff --git a/pool/shard006/C/0118205_pps_parport.c b/pool/shard006/C/0118205_pps_parport.c new file mode 100644 index 0000000000000000000000000000000000000000..83797d89c30fe88665c5d7214c391a0a571cfe88 --- /dev/null +++ b/pool/shard006/C/0118205_pps_parport.c @@ -0,0 +1,250 @@ +/* + * pps_parport.c -- kernel parallel port PPS client + * + * + * Copyright (C) 2009 Alexander Gordeev + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + + +/* + * TODO: + * implement echo over SEL pin + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DRVDESC "parallel port PPS client" + +/* module parameters */ + +#define CLEAR_WAIT_MAX 100 +#define CLEAR_WAIT_MAX_ERRORS 5 + +static unsigned int clear_wait = 100; +MODULE_PARM_DESC(clear_wait, + "Maximum number of port reads when polling for signal clear," + " zero turns clear edge capture off entirely"); +module_param(clear_wait, uint, 0); + + +/* internal per port structure */ +struct pps_client_pp { + struct pardevice *pardev; /* parport device */ + struct pps_device *pps; /* PPS device */ + unsigned int cw; /* port clear timeout */ + unsigned int cw_err; /* number of timeouts */ +}; + +static inline int signal_is_set(struct parport *port) +{ + return (port->ops->read_status(port) & PARPORT_STATUS_ACK) != 0; +} + +/* parport interrupt handler */ +static void parport_irq(void *handle) +{ + struct pps_event_time ts_assert, ts_clear; + struct pps_client_pp *dev = handle; + struct parport *port = dev->pardev->port; + unsigned int i; + unsigned long flags; + + /* first of all we get the time stamp... */ + pps_get_ts(&ts_assert); + + if (dev->cw == 0) + /* clear edge capture disabled */ + goto out_assert; + + /* try capture the clear edge */ + + /* We have to disable interrupts here. The idea is to prevent + * other interrupts on the same processor to introduce random + * lags while polling the port. Reading from IO port is known + * to take approximately 1us while other interrupt handlers can + * take much more potentially. + * + * Interrupts won't be disabled for a long time because the + * number of polls is limited by clear_wait parameter which is + * kept rather low. So it should never be an issue. + */ + local_irq_save(flags); + /* check the signal (no signal means the pulse is lost this time) */ + if (!signal_is_set(port)) { + local_irq_restore(flags); + dev_err(dev->pps->dev, "lost the signal\n"); + goto out_assert; + } + + /* poll the port until the signal is unset */ + for (i = dev->cw; i; i--) + if (!signal_is_set(port)) { + pps_get_ts(&ts_clear); + local_irq_restore(flags); + dev->cw_err = 0; + goto out_both; + } + local_irq_restore(flags); + + /* timeout */ + dev->cw_err++; + if (dev->cw_err >= CLEAR_WAIT_MAX_ERRORS) { + dev_err(dev->pps->dev, "disabled clear edge capture after %d" + " timeouts\n", dev->cw_err); + dev->cw = 0; + dev->cw_err = 0; + } + +out_assert: + /* fire assert event */ + pps_event(dev->pps, &ts_assert, + PPS_CAPTUREASSERT, NULL); + return; + +out_both: + /* fire assert event */ + pps_event(dev->pps, &ts_assert, + PPS_CAPTUREASSERT, NULL); + /* fire clear event */ + pps_event(dev->pps, &ts_clear, + PPS_CAPTURECLEAR, NULL); + return; +} + +static void parport_attach(struct parport *port) +{ + struct pps_client_pp *device; + struct pps_source_info info = { + .name = KBUILD_MODNAME, + .path = "", + .mode = PPS_CAPTUREBOTH | \ + PPS_OFFSETASSERT | PPS_OFFSETCLEAR | \ + PPS_ECHOASSERT | PPS_ECHOCLEAR | \ + PPS_CANWAIT | PPS_TSFMT_TSPEC, + .owner = THIS_MODULE, + .dev = NULL + }; + + device = kzalloc(sizeof(struct pps_client_pp), GFP_KERNEL); + if (!device) { + pr_err("memory allocation failed, not attaching\n"); + return; + } + + device->pardev = parport_register_device(port, KBUILD_MODNAME, + NULL, NULL, parport_irq, PARPORT_FLAG_EXCL, device); + if (!device->pardev) { + pr_err("couldn't register with %s\n", port->name); + goto err_free; + } + + if (parport_claim_or_block(device->pardev) < 0) { + pr_err("couldn't claim %s\n", port->name); + goto err_unregister_dev; + } + + device->pps = pps_register_source(&info, + PPS_CAPTUREBOTH | PPS_OFFSETASSERT | PPS_OFFSETCLEAR); + if (device->pps == NULL) { + pr_err("couldn't register PPS source\n"); + goto err_release_dev; + } + + device->cw = clear_wait; + + port->ops->enable_irq(port); + + pr_info("attached to %s\n", port->name); + + return; + +err_release_dev: + parport_release(device->pardev); +err_unregister_dev: + parport_unregister_device(device->pardev); +err_free: + kfree(device); +} + +static void parport_detach(struct parport *port) +{ + struct pardevice *pardev = port->cad; + struct pps_client_pp *device; + + /* FIXME: oooh, this is ugly! */ + if (!pardev || strcmp(pardev->name, KBUILD_MODNAME)) + /* not our port */ + return; + + device = pardev->private; + + port->ops->disable_irq(port); + pps_unregister_source(device->pps); + parport_release(pardev); + parport_unregister_device(pardev); + kfree(device); +} + +static struct parport_driver pps_parport_driver = { + .name = KBUILD_MODNAME, + .attach = parport_attach, + .detach = parport_detach, +}; + +/* module staff */ + +static int __init pps_parport_init(void) +{ + int ret; + + pr_info(DRVDESC "\n"); + + if (clear_wait > CLEAR_WAIT_MAX) { + pr_err("clear_wait value should be not greater" + " then %d\n", CLEAR_WAIT_MAX); + return -EINVAL; + } + + ret = parport_register_driver(&pps_parport_driver); + if (ret) { + pr_err("unable to register with parport\n"); + return ret; + } + + return 0; +} + +static void __exit pps_parport_exit(void) +{ + parport_unregister_driver(&pps_parport_driver); +} + +module_init(pps_parport_init); +module_exit(pps_parport_exit); + +MODULE_AUTHOR("Alexander Gordeev "); +MODULE_DESCRIPTION(DRVDESC); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0118211_category.c b/pool/shard006/C/0118211_category.c new file mode 100644 index 0000000000000000000000000000000000000000..866955e666f90702037b684c02c6c609f1e7b23a --- /dev/null +++ b/pool/shard006/C/0118211_category.c @@ -0,0 +1,159 @@ +/* -*- Mode: c; c-basic-offset: 2 -*- + * + * category.c - Flickcurl category functions + * + * Copyright (C) 2007-2008, David Beckett http://www.dajobe.org/ + * + * This file is licensed under the following three licenses as alternatives: + * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version + * 2. GNU General Public License (GPL) V2 or any newer version + * 3. Apache License, V2.0 or any newer version + * + * You may not use this file except in compliance with at least one of + * the above three licenses. + * + * See LICENSE.html or LICENSE.txt at the top of this package for the + * complete terms and further detail along with the license texts for + * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. + * + */ + +#include +#include +#include + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifdef WIN32 +#include +#endif + +#include +#include + + +/** + * flickcurl_free_category: + * @category: category object + * + * Destructor for category object + */ +void +flickcurl_free_category(flickcurl_category *category) +{ + FLICKCURL_ASSERT_OBJECT_POINTER_RETURN(category, flickcurl_category); + + if(category->id) + free(category->id); + + if(category->name) + free(category->name); + + if(category->categories) + flickcurl_free_categories(category->categories); + + if(category->groups) + flickcurl_free_groups(category->groups); + + free(category); +} + + +/** + * flickcurl_free_categories: + * @categories_object: category object array + * + * Destructor for array of category object + */ +void +flickcurl_free_categories(flickcurl_category **categories_object) +{ + int i; + + FLICKCURL_ASSERT_OBJECT_POINTER_RETURN(categories_object, flickcurl_category); + + for(i = 0; categories_object[i]; i++) + flickcurl_free_category(categories_object[i]); + + free(categories_object); +} + + +flickcurl_category** +flickcurl_build_categories(flickcurl* fc, xmlXPathContextPtr xpathCtx, + const xmlChar* xpathExpr, int* category_count_p) +{ + flickcurl_category** categories = NULL; + int nodes_count; + int category_count; + int i; + xmlXPathObjectPtr xpathObj = NULL; + xmlNodeSetPtr nodes; + + xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx); + if(!xpathObj) { + flickcurl_error(fc, "Unable to evaluate XPath expression \"%s\"", + xpathExpr); + fc->failed = 1; + goto tidy; + } + + nodes = xpathObj->nodesetval; + /* This is a max size - it can include nodes that are CDATA */ + nodes_count = xmlXPathNodeSetGetLength(nodes); + categories = (flickcurl_category**)calloc(sizeof(flickcurl_category*), nodes_count+1); + + for(i = 0, category_count = 0; i < nodes_count; i++) { + xmlNodePtr node = nodes->nodeTab[i]; + xmlAttr* attr; + flickcurl_category* c; + + if(node->type != XML_ELEMENT_NODE) { + flickcurl_error(fc, "Got unexpected node type %d", node->type); + fc->failed = 1; + break; + } + + c = (flickcurl_category*)calloc(sizeof(flickcurl_category), 1); + + for(attr = node->properties; attr; attr = attr->next) { + size_t attr_len = strlen((const char*)attr->children->content); + const char *attr_name = (const char*)attr->name; + char *attr_value; + + attr_value = (char*)malloc(attr_len + 1); + memcpy(attr_value, attr->children->content, attr_len + 1); + + if(!strcmp(attr_name, "id")) + c->id = attr_value; + else if(!strcmp(attr_name, "name")) + c->name = attr_value; + else if(!strcmp(attr_name, "path")) + c->path = attr_value; + else if(!strcmp(attr_name, "count")) { + c->count = atoi(attr_value); + free(attr_value); + } else + free(attr_value); + } + +#if FLICKCURL_DEBUG > 1 + fprintf(stderr, + "category: id %s name '%s' path '%s' count %d\n", + c->id, c->name, c->path, c->count); +#endif + + categories[category_count++] = c; + } /* for nodes */ + + if(category_count_p) + *category_count_p = category_count; + + tidy: + if(xpathObj) + xmlXPathFreeObject(xpathObj); + + return categories; +} diff --git a/pool/shard006/C/0118212_guava.c b/pool/shard006/C/0118212_guava.c new file mode 100644 index 0000000000000000000000000000000000000000..86081b206e42b91bce40c2b486492989d4a3436f --- /dev/null +++ b/pool/shard006/C/0118212_guava.c @@ -0,0 +1,61 @@ +/* + * 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 ``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 + * 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 "lib/salad/guava.h" + +#include + +/** + * This is implements a consistent hashing algorithm + * A Fast, Minimal Memory, Consistent Hash Algorithm + * John Lamping, Eric Veach + */ + +static const int64_t K = 2862933555777941757; +static const double D = 0x1.0p31; + +static inline double lcg(int64_t *state) +{ + return (double )((int32_t)(((uint64_t )*state >> 33) + 1)) / D; +} + +int32_t +guava(int64_t state, int32_t buckets) +{ + int32_t candidate = 0; + int32_t next; + while (1) { + state = K * state + 1; + next = (int32_t)((candidate + 1) / lcg(&state)); + if (next >= 0 && next < buckets) + candidate = next; + else + return candidate; + } +} diff --git a/pool/shard006/C/0118213_sse2-mulpd-1.c b/pool/shard006/C/0118213_sse2-mulpd-1.c new file mode 100644 index 0000000000000000000000000000000000000000..c87e9e20de6e75ad77ec88e351e909452d4213f4 --- /dev/null +++ b/pool/shard006/C/0118213_sse2-mulpd-1.c @@ -0,0 +1,38 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -msse2" } */ + +#ifndef CHECK_H +#define CHECK_H "sse2-check.h" +#endif + +#ifndef TEST +#define TEST sse2_test +#endif + +#include CHECK_H + +#include + +static __m128d +__attribute__((noinline, unused)) +test (__m128d s1, __m128d s2) +{ + return _mm_mul_pd (s1, s2); +} + +static void +TEST (void) +{ + union128d u, s1, s2; + double e[2]; + + s1.x = _mm_set_pd (2134.3343,1234.635654); + s2.x = _mm_set_pd (41124.234,2344.2354); + u.x = test (s1.x, s2.x); + + e[0] = s1.a[0] * s2.a[0]; + e[1] = s1.a[1] * s2.a[1]; + + if (check_union128d (u, e)) + abort (); +} diff --git a/pool/shard006/C/0118217_matmul_si2.c b/pool/shard006/C/0118217_matmul_si2.c new file mode 100644 index 0000000000000000000000000000000000000000..8538d14294e7a380adc97abf223f86b791a2f734 --- /dev/null +++ b/pool/shard006/C/0118217_matmul_si2.c @@ -0,0 +1,87 @@ +/* + * Copyright 2004 PathScale, Inc. All Rights Reserved. + */ + +/* + + Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. + + This program is free software; you can redistribute it and/or modify it + under the terms of version 2.1 of the GNU Lesser General Public License + as published by the Free Software Foundation. + + This program is distributed in the hope that it would be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + Further, this software is distributed without any warranty that it is + free of the rightful claim of any third person regarding infringement + or the like. Any license provided herein, whether implied or + otherwise, applies only to this software file. Patent licenses, if + any, provided herein do not apply to combinations of this program with + other software, or any other product whatsoever. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, + USA. + + Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, + Mountain View, CA 94043, or: + + http://www.sgi.com + + For further information regarding this notice, see: + + http://oss.sgi.com/projects/GenInfo/NoticeExplan + +*/ + + +#pragma ident "@(#) libfi/matrix/matmul_si2.c 92.1 07/09/99 15:18:08" +#include "matmul.h" + +/* + * Name of this entry point + */ +#define NAME _MATMUL_SI2 +/* + * Name of routine called do computation (if any) + */ +#if defined(BUILD_COMPILER_GNU) && defined(BUILD_OS_DARWIN) +#define SUBNAME underscore_i2sgemmx__ +#else /* defined(BUILD_COMPILER_GNU) && defined(BUILD_OS_DARWIN) */ +#define SUBNAME _i2sgemmx__ +#endif /* defined(BUILD_COMPILER_GNU) && defined(BUILD_OS_DARWIN) */ +/* + * Type of constants alpha and beta + */ +#define RESULTTYPE _f_real8 + +void +NAME(DopeVectorType *RESULT, DopeVectorType *MATRIX_A, + DopeVectorType *MATRIX_B) +{ + void SUBNAME(); + MatrixDimenType matdimdata, *MATDIM; + + const RESULTTYPE one = (RESULTTYPE) 1.0; + const RESULTTYPE zero = (RESULTTYPE) 0.0; + + MATDIM = (MatrixDimenType *) &matdimdata; + + /* + * Parse dope vectors, and perform error checking. + */ + + _premult(RESULT, MATRIX_A, MATRIX_B, MATDIM); + + /* + * Do the transposed matrix multiplication C' = B'*A' + */ + + SUBNAME(&MATDIM->n, &MATDIM->m, &MATDIM->k, &one, MATDIM->B, &MATDIM->inc2b, + &MATDIM->inc1b, MATDIM->A, &MATDIM->inc2a, &MATDIM->inc1a, + &zero, MATDIM->C, &MATDIM->inc2c, &MATDIM->inc1c); + return; +} diff --git a/pool/shard006/C/0118222_Utilities.c b/pool/shard006/C/0118222_Utilities.c new file mode 100644 index 0000000000000000000000000000000000000000..1bdf6706ad0f6b038939f8bc12c3bc0ac3bc2f34 --- /dev/null +++ b/pool/shard006/C/0118222_Utilities.c @@ -0,0 +1,555 @@ +/*++ + + The MIT License (MIT) + + Copyright (c) 2015 Aleksey Kabanov + + 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. + +Module Name: + + Utilities.c + +Abstract: + + Contains common helper functions. + +Environment: + + Kernel mode. + +--*/ + +//------------------------------------------------------------------------ +// Includes. +//------------------------------------------------------------------------ + +#include "Utilities.h" + +//------------------------------------------------------------------------ +// Text sections. +//------------------------------------------------------------------------ + +#ifdef ALLOC_PRAGMA + #pragma alloc_text(PAGE, LcAllocateBuffer) + #pragma alloc_text(PAGE, LcAllocateNonPagedBuffer) + #pragma alloc_text(PAGE, LcAllocateNonPagedAlignedBuffer) + #pragma alloc_text(PAGE, LcFreeBuffer) + #pragma alloc_text(PAGE, LcFreeNonPagedBuffer) + #pragma alloc_text(PAGE, LcFreeNonPagedAlignedBuffer) + #pragma alloc_text(PAGE, LcAllocateResource) + #pragma alloc_text(PAGE, LcFreeResource) + #pragma alloc_text(PAGE, LcAllocateUnicodeString) + #pragma alloc_text(PAGE, LcCopyUnicodeString) + #pragma alloc_text(PAGE, LcFreeUnicodeString) +#endif // ALLOC_PRAGMA + +//------------------------------------------------------------------------ +// Memory allocation/freeing functions. +//------------------------------------------------------------------------ + +_Check_return_ +NTSTATUS +LcAllocateBuffer( + _Outptr_result_buffer_(Size) PVOID* Buffer, + _In_ POOL_TYPE PoolType, + _In_ SIZE_T Size, + _In_ ULONG Tag + ) +/*++ + +Summary: + + This function allocates a buffer of a given size from a pool specified. + +Arguments: + + Buffer - A pointer to a variable that receives the buffer allocated. + + PoolType - Type of the pool to allocate memory from. + Must be 'PagedPool' or 'NonPagedPoolNx'. + + Size - Supplies the size of the buffer to be allocated. + + Tag - Pool tag for the allocated memory. + +Return value: + + STATUS_SUCCESS - Success. + STATUS_INSUFFICIENT_RESOURCES - Failure. Unable to allocate memory. + STATUS_INVALID_PARAMETER_1 - Failure. The 'Buffer' parameter is NULL. + STATUS_INVALID_PARAMETER_2 - Failure. The 'PoolType' parameter is not 'PagedPool' or 'NonPagedPoolNx'. + STATUS_INVALID_PARAMETER_3 - Failure. The 'Size' parameter is equal to zero. + +--*/ +{ + PVOID allocatedBuffer = NULL; + + PAGED_CODE(); + + IF_FALSE_RETURN_RESULT(Buffer != NULL, STATUS_INVALID_PARAMETER_1); + IF_FALSE_RETURN_RESULT(PoolType == PagedPool || PoolType == NonPagedPoolNx, STATUS_INVALID_PARAMETER_2); + IF_FALSE_RETURN_RESULT(Size != 0, STATUS_INVALID_PARAMETER_3); + + allocatedBuffer = ExAllocatePoolWithTag(PoolType, Size, Tag); + IF_FALSE_RETURN_RESULT(allocatedBuffer != NULL, STATUS_INSUFFICIENT_RESOURCES); + + // Zero buffer and set the result value. + RtlZeroMemory(allocatedBuffer, Size); + *Buffer = allocatedBuffer; + + return STATUS_SUCCESS; +} + +//------------------------------------------------------------------------ + +_Check_return_ +NTSTATUS +LcAllocateNonPagedBuffer( + _Outptr_result_buffer_(Size) PVOID* Buffer, + _In_ SIZE_T Size + ) +/*++ + +Summary: + + This function allocates a buffer from the non-paged pool. + +Arguments: + + Buffer - A pointer to a variable that receives the buffer allocated. + + Size - Supplies the size of the buffer to be allocated. + +Return value: + + STATUS_SUCCESS - Success. + STATUS_INSUFFICIENT_RESOURCES - Failure. Unable to allocate memory. + STATUS_INVALID_PARAMETER_1 - Failure. The 'Buffer' parameter is NULL. + STATUS_INVALID_PARAMETER_2 - Failure. The 'Size' parameter is equal to zero. + +--*/ +{ + PVOID allocatedBuffer = NULL; + + PAGED_CODE(); + + IF_FALSE_RETURN_RESULT(Buffer != NULL, STATUS_INVALID_PARAMETER_1); + IF_FALSE_RETURN_RESULT(Size != 0, STATUS_INVALID_PARAMETER_2); + + allocatedBuffer = ExAllocatePoolWithTag(NonPagedPoolNx, Size, LC_BUFFER_NON_PAGED_POOL_TAG); + IF_FALSE_RETURN_RESULT(allocatedBuffer != NULL, STATUS_INSUFFICIENT_RESOURCES); + + // Zero buffer and set the result value. + RtlZeroMemory(allocatedBuffer, Size); + *Buffer = allocatedBuffer; + + return STATUS_SUCCESS; +} + +//------------------------------------------------------------------------ + +_Check_return_ +NTSTATUS +LcAllocateNonPagedAlignedBuffer( + _In_ PFLT_INSTANCE Instance, + _Outptr_result_buffer_(Size) PVOID* Buffer, + _In_ SIZE_T Size + ) +/*++ + +Summary: + + This function allocates a device-aligned buffer from non-paged pool + for use in a noncached I/O operations. + +Arguments: + + Instance - Opaque instance pointer for a caller-owned minifilter driver + instance that is attached to the volume. + + Buffer - A pointer to a variable that receives the buffer allocated. + + Size - Supplies the size of the buffer to be allocated. + +Return value: + + STATUS_SUCCESS - Success. + STATUS_INSUFFICIENT_RESOURCES - Failure. Unable to allocate memory. + STATUS_INVALID_PARAMETER_1 - Failure. The 'Instance' parameter is NULL. + STATUS_INVALID_PARAMETER_2 - Failure. The 'Buffer' parameter is NULL. + STATUS_INVALID_PARAMETER_3 - Failure. The 'Size' parameter is equal to zero. + +--*/ +{ + PVOID allocatedBuffer = NULL; + + PAGED_CODE(); + + IF_FALSE_RETURN_RESULT(Instance != NULL, STATUS_INVALID_PARAMETER_1); + IF_FALSE_RETURN_RESULT(Buffer != NULL, STATUS_INVALID_PARAMETER_2); + IF_FALSE_RETURN_RESULT(Size != 0, STATUS_INVALID_PARAMETER_3); + + allocatedBuffer = FltAllocatePoolAlignedWithTag(Instance, NonPagedPoolNx, Size, LC_BUFFER_NON_PAGED_POOL_TAG); + IF_FALSE_RETURN_RESULT(allocatedBuffer != NULL, STATUS_INSUFFICIENT_RESOURCES); + + // Zero buffer and set the result value. + RtlZeroMemory(allocatedBuffer, Size); + *Buffer = allocatedBuffer; + + return STATUS_SUCCESS; +} + +//------------------------------------------------------------------------ + +VOID +LcFreeBuffer( + _Inout_ PVOID Buffer, + _In_ ULONG Tag + ) +/*++ + +Summary: + + This function frees the buffer previously allocated using the 'LcAllocateBuffer' function. + +Arguments: + + Buffer - Supplies the buffer to be freed. If it's NULL, this function will do nothing. + + Tag - Pool tag. + +Return value: + + None. + +--*/ +{ + PAGED_CODE(); + + IF_FALSE_RETURN(Buffer != NULL); + + ExFreePoolWithTag(Buffer, Tag); +} + +//------------------------------------------------------------------------ + +VOID +LcFreeNonPagedBuffer( + _Inout_ PVOID Buffer + ) +/*++ + +Summary: + + This function frees the buffer in the non-paged pool that previously allocated using + 'LcAllocateNonPagedBuffer' function. + +Arguments: + + Buffer - Supplies the buffer to be freed. If it's NULL, this function will do nothing. + NOTE: In order for this function to work properly, the buffer given must be + allocated using the 'LcAllocateNonPagedBuffer' function. + +Return value: + + None. + +--*/ +{ + PAGED_CODE(); + + IF_FALSE_RETURN(Buffer != NULL); + + ExFreePoolWithTag(Buffer, LC_BUFFER_NON_PAGED_POOL_TAG); +} + +//------------------------------------------------------------------------ + +VOID +LcFreeNonPagedAlignedBuffer( + _In_ PFLT_INSTANCE Instance, + _Inout_ PVOID Buffer + ) +/*++ + +Summary: + + This function frees the cache-aligned buffer in the non-paged pool that previously allocated using + 'LcAllocateNonPagedAlignedBuffer' function. + +Arguments: + + Instance - Opaque instance pointer for a caller-owned minifilter driver instance that + is attached to the volume. + + Buffer - Supplies the buffer to be freed. If it's NULL, this function will do nothing. + NOTE: In order for this function to work properly, the buffer given must be + allocated using the 'LcAllocateNonPagedAlignedBuffer' function. + +Return value: + + None. + +--*/ +{ + PAGED_CODE(); + + IF_FALSE_RETURN(Instance != NULL); + IF_FALSE_RETURN(Buffer != NULL); + + FltFreePoolAlignedWithTag(Instance, Buffer, LC_BUFFER_NON_PAGED_POOL_TAG); +} + +//------------------------------------------------------------------------ + +_Check_return_ +NTSTATUS +LcAllocateResource( + _Outptr_ PERESOURCE* Resource + ) +/*++ + +Summary: + + This function allocates a new ERESOURCE from the non-paged pool and initializes it. + +Arguments: + + Resource - Supplies pointer to the PERESOURCE to be created. + +Return value: + + The return value is the status of the operation. + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + PERESOURCE resource = NULL; + BOOLEAN deleteResource = FALSE; + BOOLEAN freeBuffer = FALSE; + + PAGED_CODE(); + + IF_FALSE_RETURN_RESULT(Resource != NULL, STATUS_INVALID_PARAMETER_1); + + __try + { + status = LcAllocateBuffer((PVOID*)&resource, NonPagedPoolNx, sizeof(ERESOURCE), LC_ERESOURCE_NON_PAGED_POOL_TAG); + if (!NT_SUCCESS(status)) + { + freeBuffer = TRUE; + __leave; + } + + status = ExInitializeResourceLite(resource); + if (!NT_SUCCESS(status)) + { + deleteResource = TRUE; + __leave; + } + + *Resource = resource; + } + __finally + { + if (!NT_SUCCESS(status)) + { + if (deleteResource) + { + ExDeleteResourceLite(resource); + } + + if (freeBuffer) + { + LcFreeBuffer(resource, LC_ERESOURCE_NON_PAGED_POOL_TAG); + } + } + } + + return status; +} + +//------------------------------------------------------------------------ + +VOID +LcFreeResource( + _In_ PERESOURCE Resource + ) +/*++ + +Summary: + + This function frees the PERESOURCE previously allocated using the 'LcAllocateResource' function. + +Arguments: + + Resource - Supplies pointer to the ERESOURCE to be freed. + If it's NULL, this function will do nothing. + NOTE: In order for this function to work properly, the resource given must be + allocated using the 'LcAllocateResource' function. + +Return value: + + None. + +--*/ +{ + PAGED_CODE(); + + IF_FALSE_RETURN(Resource != NULL); + + ExDeleteResourceLite(Resource); + LcFreeBuffer(Resource, LC_ERESOURCE_NON_PAGED_POOL_TAG); +} + +//------------------------------------------------------------------------ + +_Check_return_ +NTSTATUS +LcAllocateUnicodeString( + _Inout_ PUNICODE_STRING String, + _In_ USHORT Size + ) +/*++ + +Summary: + + This function allocates a unicode string from the non-paged pool. + + The allocated memory is zeroed and assigned to the 'String->Buffer', 'String->Length' is set to zero, + and the 'String->MaximumLength' is set to 'Size' given. + +Arguments: + + String - Pointer to unicode string to allocate buffer for. + + Size - Size, in bytes, of the buffer to be allocated. + +Return value: + + STATUS_SUCCESS - Success. + STATUS_INSUFFICIENT_RESOURCES - Failure. Unable to allocate memory. + STATUS_INVALID_PARAMETER_1 - Failure. If the 'String' parameter is NULL or the 'String->Buffer' is NOT NULL. + STATUS_INVALID_PARAMETER_2 - Failure. If the 'Size' value is equal to zero or the 'Size % sizeof(WCHAR)' is not equal to zero. + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + + PAGED_CODE(); + + IF_FALSE_RETURN_RESULT(String != NULL, STATUS_INVALID_PARAMETER_1); + IF_FALSE_RETURN_RESULT(String->Buffer == NULL, STATUS_INVALID_PARAMETER_1); + IF_FALSE_RETURN_RESULT(Size != 0, STATUS_INVALID_PARAMETER_2); + IF_FALSE_RETURN_RESULT(Size % sizeof(WCHAR) == 0, STATUS_INVALID_PARAMETER_2); + + NT_IF_FAIL_RETURN(LcAllocateBuffer((PVOID*)&String->Buffer, NonPagedPoolNx, Size, LC_STRING_NON_PAGED_POOL_TAG)); + + String->Length = 0; + String->MaximumLength = Size; + + // The buffer allocated should be freed by the caller. + + return status; +} + +//------------------------------------------------------------------------ + +_Check_return_ +NTSTATUS +LcCopyUnicodeString( + _Inout_ PUNICODE_STRING DestinationString, + _In_ PCUNICODE_STRING SourceString + ) +/*++ + +Summary: + + This function copies a source string to a destination string. + Before copying, buffer is allocated for the 'DestinationString' to store + the source string data. + +Arguments: + + DestinationString - Pointer to unicode string to copy source string into. + It must NOT have the allocated buffer, because this + function allocates a new buffer for it. + + SourceString - Source string, which contents should be copied. + +Return value: + + The return value is the status of the operation. + +--*/ +{ + NTSTATUS status = STATUS_SUCCESS; + + PAGED_CODE(); + + IF_FALSE_RETURN_RESULT(DestinationString != NULL, STATUS_INVALID_PARAMETER_1); + IF_FALSE_RETURN_RESULT(DestinationString->Buffer == NULL, STATUS_INVALID_PARAMETER_1); + + IF_FALSE_RETURN_RESULT(SourceString->Buffer != NULL, STATUS_INVALID_PARAMETER_2); + IF_FALSE_RETURN_RESULT(NT_SUCCESS(RtlUnicodeStringValidate(SourceString)), STATUS_INVALID_PARAMETER_2); + + NT_IF_FAIL_RETURN(LcAllocateUnicodeString(DestinationString, min(SourceString->Length, SourceString->MaximumLength) + sizeof(WCHAR))); + + #pragma warning(suppress: __WARNING_INVALID_PARAM_VALUE_1) // '_Param_(1)->Buffer' could be '0'. + RtlCopyUnicodeString(DestinationString, SourceString); + + return status; +} + +//------------------------------------------------------------------------ + +VOID +LcFreeUnicodeString( + _Inout_ PUNICODE_STRING UniString + ) +/*++ + +Summary: + + This function frees the unicode string previously allocated using the 'LcAllocateUnicodeString' function. + +Arguments: + + UniString - Supplies the string to be freed. + If it's NULL, this function will do nothing. + NOTE: In order for this function to work properly, the string given must be + allocated using the 'LcAllocateUnicodeString' function. + +Return value: + + None. + +--*/ +{ + PAGED_CODE(); + + IF_FALSE_RETURN(UniString != NULL); + + LcFreeBuffer(UniString->Buffer, LC_STRING_NON_PAGED_POOL_TAG); + + UniString->Buffer = NULL; + UniString->Length = 0; + UniString->MaximumLength = 0; +} diff --git a/pool/shard006/C/0118223_woodburn.c b/pool/shard006/C/0118223_woodburn.c new file mode 100644 index 0000000000000000000000000000000000000000..286749f3c910e2f409fd741220d7c0b5c885fcf0 --- /dev/null +++ b/pool/shard006/C/0118223_woodburn.c @@ -0,0 +1,261 @@ +/* + * Copyright (C) 2012, Stefano Babic + * + * Based on flea3.c and mx35pdk.c + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CCM_CCMR_CONFIG 0x003F4208 + +#define ESDCTL_DDR2_CONFIG 0x007FFC3F + +/* For MMC */ +#define GPIO_MMC_CD 7 +#define GPIO_MMC_WP 8 + +DECLARE_GLOBAL_DATA_PTR; + +int dram_init(void) +{ + gd->ram_size = get_ram_size((long *)PHYS_SDRAM_1, + PHYS_SDRAM_1_SIZE); + + return 0; +} + +static void board_setup_sdram(void) +{ + struct esdc_regs *esdc = (struct esdc_regs *)ESDCTL_BASE_ADDR; + + /* Initialize with default values both CSD0/1 */ + writel(0x2000, &esdc->esdctl0); + writel(0x2000, &esdc->esdctl1); + + mx3_setup_sdram_bank(CSD0_BASE_ADDR, ESDCTL_DDR2_CONFIG, + 13, 10, 2, 0x8080); +} + +static void setup_iomux_fec(void) +{ + /* setup pins for FEC */ + mxc_request_iomux(MX35_PIN_FEC_TX_CLK, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RX_CLK, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RX_DV, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_COL, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RDATA0, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_TDATA0, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_TX_EN, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_MDC, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_MDIO, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_TX_ERR, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RX_ERR, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_CRS, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RDATA1, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_TDATA1, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RDATA2, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_TDATA2, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_RDATA3, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_FEC_TDATA3, MUX_CONFIG_FUNC); +} + +int woodburn_init(void) +{ + struct ccm_regs *ccm = + (struct ccm_regs *)IMX_CCM_BASE; + + /* initialize PLL and clock configuration */ + writel(CCM_CCMR_CONFIG, &ccm->ccmr); + + /* Set-up RAM */ + board_setup_sdram(); + + /* enable clocks */ + writel(readl(&ccm->cgr0) | + MXC_CCM_CGR0_EMI_MASK | + MXC_CCM_CGR0_EDIO_MASK | + MXC_CCM_CGR0_EPIT1_MASK, + &ccm->cgr0); + + writel(readl(&ccm->cgr1) | + MXC_CCM_CGR1_FEC_MASK | + MXC_CCM_CGR1_GPIO1_MASK | + MXC_CCM_CGR1_GPIO2_MASK | + MXC_CCM_CGR1_GPIO3_MASK | + MXC_CCM_CGR1_I2C1_MASK | + MXC_CCM_CGR1_I2C2_MASK | + MXC_CCM_CGR1_I2C3_MASK, + &ccm->cgr1); + + /* Set-up NAND */ + __raw_writel(readl(&ccm->rcsr) | MXC_CCM_RCSR_NFC_FMS, &ccm->rcsr); + + /* Set pinmux for the required peripherals */ + setup_iomux_fec(); + + /* setup GPIO1_4 FEC_ENABLE signal */ + mxc_request_iomux(MX35_PIN_SCKR, MUX_CONFIG_ALT5); + gpio_direction_output(4, 1); + mxc_request_iomux(MX35_PIN_HCKT, MUX_CONFIG_ALT5); + gpio_direction_output(9, 0); + gpio_set_value(9, 1); + + return 0; +} + +#if defined(CONFIG_SPL_BUILD) +void board_init_f(ulong dummy) +{ + /* Set the stack pointer. */ + asm volatile("mov sp, %0\n" : : "r"(CONFIG_SPL_STACK)); + + /* Initialize MUX and SDRAM */ + woodburn_init(); + + /* Clear the BSS. */ + memset(__bss_start, 0, __bss_end__ - __bss_start); + + /* Set global data pointer. */ + gd = &gdata; + + preloader_console_init(); + timer_init(); + + board_init_r(NULL, 0); +} + +void spl_board_init(void) +{ +} + +#endif + + +/* Booting from NOR in external mode */ +int board_early_init_f(void) +{ + return woodburn_init(); +} + + +int board_init(void) +{ + struct pmic *p; + u32 val; + + /* address of boot parameters */ + gd->bd->bi_boot_params = PHYS_SDRAM_1 + 0x100; + + pmic_init(); + p = get_pmic(); + + /* + * Set switchers in Auto in NORMAL mode & STANDBY mode + * Setup the switcher mode for SW1 & SW2 + */ + pmic_reg_read(p, REG_SW_4, &val); + val = (val & ~((SWMODE_MASK << SWMODE1_SHIFT) | + (SWMODE_MASK << SWMODE2_SHIFT))); + val |= (SWMODE_AUTO_AUTO << SWMODE1_SHIFT) | + (SWMODE_AUTO_AUTO << SWMODE2_SHIFT); + /* Set SWILIMB */ + val |= (1 << 22); + pmic_reg_write(p, REG_SW_4, val); + + /* Setup the switcher mode for SW3 & SW4 */ + pmic_reg_read(p, REG_SW_5, &val); + val &= ~((SWMODE_MASK << SWMODE4_SHIFT) | + (SWMODE_MASK << SWMODE3_SHIFT)); + val |= (SWMODE_AUTO_AUTO << SWMODE4_SHIFT) | + (SWMODE_AUTO_AUTO << SWMODE3_SHIFT); + pmic_reg_write(p, REG_SW_5, val); + + /* Set VGEN1 to 3.15V */ + pmic_reg_read(p, REG_SETTING_0, &val); + val &= ~(VGEN1_MASK); + val |= VGEN1_3_15; + pmic_reg_write(p, REG_SETTING_0, val); + + pmic_reg_read(p, REG_MODE_0, &val); + val |= VGEN1EN; + pmic_reg_write(p, REG_MODE_0, val); + udelay(2000); + + return 0; +} + +#if defined(CONFIG_FSL_ESDHC) +struct fsl_esdhc_cfg esdhc_cfg = {MMC_SDHC1_BASE_ADDR}; + +int board_mmc_init(bd_t *bis) +{ + /* configure pins for SDHC1 only */ + mxc_request_iomux(MX35_PIN_SD1_CMD, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_SD1_CLK, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_SD1_DATA0, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_SD1_DATA1, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_SD1_DATA2, MUX_CONFIG_FUNC); + mxc_request_iomux(MX35_PIN_SD1_DATA3, MUX_CONFIG_FUNC); + + /* MMC Card Detect on GPIO1_7 */ + mxc_request_iomux(MX35_PIN_SCKT, MUX_CONFIG_ALT5); + mxc_iomux_set_input(MUX_IN_GPIO1_IN_7, 0x1); + gpio_direction_input(GPIO_MMC_CD); + + mxc_request_iomux(MX35_PIN_FST, MUX_CONFIG_ALT5); + mxc_iomux_set_input(MUX_IN_GPIO1_IN_8, 0x1); + gpio_direction_output(GPIO_MMC_WP, 0); + + esdhc_cfg.sdhc_clk = mxc_get_clock(MXC_ESDHC1_CLK); + + return fsl_esdhc_initialize(bis, &esdhc_cfg); +} + +int board_mmc_getcd(struct mmc *mmc) +{ + return !gpio_get_value(GPIO_MMC_CD); +} +#endif + +u32 get_board_rev(void) +{ + int rev = 0; + + return (get_cpu_rev() & ~(0xF << 8)) | (rev & 0xF) << 8; +} diff --git a/pool/shard006/C/0118224_pyglue.c b/pool/shard006/C/0118224_pyglue.c new file mode 100644 index 0000000000000000000000000000000000000000..735f03a1e16339cb4da3129d8fe1319963cea0ba --- /dev/null +++ b/pool/shard006/C/0118224_pyglue.c @@ -0,0 +1,250 @@ +/* + Unix SMB/CIFS implementation. + Copyright (C) Jelmer Vernooij 2007 + Copyright (C) Matthias Dieter Wallnöfer 2009 + + 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 . +*/ + +#include +#include "includes.h" +#include "version.h" +#include "param/pyparam.h" +#include "lib/socket/netif.h" + +void init_glue(void); + +#ifndef Py_RETURN_NONE +#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None +#endif + +static PyObject *py_generate_random_str(PyObject *self, PyObject *args) +{ + int len; + PyObject *ret; + char *retstr; + if (!PyArg_ParseTuple(args, "i", &len)) + return NULL; + + retstr = generate_random_str(NULL, len); + ret = PyString_FromString(retstr); + talloc_free(retstr); + return ret; +} + +static PyObject *py_generate_random_password(PyObject *self, PyObject *args) +{ + int min, max; + PyObject *ret; + char *retstr; + if (!PyArg_ParseTuple(args, "ii", &min, &max)) + return NULL; + + retstr = generate_random_password(NULL, min, max); + if (retstr == NULL) { + return NULL; + } + ret = PyString_FromString(retstr); + talloc_free(retstr); + return ret; +} + +static PyObject *py_unix2nttime(PyObject *self, PyObject *args) +{ + time_t t; + unsigned int _t; + NTTIME nt; + + if (!PyArg_ParseTuple(args, "I", &_t)) { + return NULL; + } + t = _t; + + unix_to_nt_time(&nt, t); + + return PyLong_FromLongLong((uint64_t)nt); +} + +static PyObject *py_nttime2unix(PyObject *self, PyObject *args) +{ + time_t t; + NTTIME nt; + if (!PyArg_ParseTuple(args, "K", &nt)) + return NULL; + + t = nt_time_to_unix(nt); + + return PyInt_FromLong((uint64_t)t); +} + +static PyObject *py_nttime2string(PyObject *self, PyObject *args) +{ + PyObject *ret; + NTTIME nt; + TALLOC_CTX *tmp_ctx; + const char *string; + if (!PyArg_ParseTuple(args, "K", &nt)) + return NULL; + + tmp_ctx = talloc_new(NULL); + if (tmp_ctx == NULL) { + PyErr_NoMemory(); + return NULL; + } + + string = nt_time_string(tmp_ctx, nt); + ret = PyString_FromString(string); + + talloc_free(tmp_ctx); + + return ret; +} + +static PyObject *py_set_debug_level(PyObject *self, PyObject *args) +{ + unsigned level; + if (!PyArg_ParseTuple(args, "I", &level)) + return NULL; + (DEBUGLEVEL) = level; + Py_RETURN_NONE; +} + +static PyObject *py_get_debug_level(PyObject *self) +{ + return PyInt_FromLong(DEBUGLEVEL); +} + +/* + return the list of interface IPs we have configured + takes an loadparm context, returns a list of IPs in string form + + Does not return addresses on 127.0.0.0/8 + */ +static PyObject *py_interface_ips(PyObject *self, PyObject *args) +{ + PyObject *pylist; + int count; + TALLOC_CTX *tmp_ctx; + PyObject *py_lp_ctx; + struct loadparm_context *lp_ctx; + struct interface *ifaces; + int i, ifcount; + int all_interfaces = 1; + + if (!PyArg_ParseTuple(args, "O|i", &py_lp_ctx, &all_interfaces)) + return NULL; + + tmp_ctx = talloc_new(NULL); + if (tmp_ctx == NULL) { + PyErr_NoMemory(); + return NULL; + } + + lp_ctx = lpcfg_from_py_object(tmp_ctx, py_lp_ctx); + if (lp_ctx == NULL) { + talloc_free(tmp_ctx); + return NULL; + } + + load_interface_list(tmp_ctx, lp_ctx, &ifaces); + + count = iface_list_count(ifaces); + + /* first count how many are not loopback addresses */ + for (ifcount = i = 0; i string\n" + "Generate random string with specified length." }, + { "generate_random_password", (PyCFunction)py_generate_random_password, + METH_VARARGS, "generate_random_password(min, max) -> string\n" + "Generate random password with a length >= min and <= max." }, + { "unix2nttime", (PyCFunction)py_unix2nttime, METH_VARARGS, + "unix2nttime(timestamp) -> nttime" }, + { "nttime2unix", (PyCFunction)py_nttime2unix, METH_VARARGS, + "nttime2unix(nttime) -> timestamp" }, + { "nttime2string", (PyCFunction)py_nttime2string, METH_VARARGS, + "nttime2string(nttime) -> string" }, + { "set_debug_level", (PyCFunction)py_set_debug_level, METH_VARARGS, + "set debug level" }, + { "get_debug_level", (PyCFunction)py_get_debug_level, METH_NOARGS, + "get debug level" }, + { "interface_ips", (PyCFunction)py_interface_ips, METH_VARARGS, + "interface_ips(lp_ctx[, all_interfaces) -> list_of_ifaces\n" + "\n" + "get interface IP address list"}, + { "strcasecmp_m", (PyCFunction)py_strcasecmp_m, METH_VARARGS, + "(for testing) compare two strings using Samba's strcasecmp_m()"}, + { "strstr_m", (PyCFunction)py_strstr_m, METH_VARARGS, + "(for testing) find one string in another with Samba's strstr_m()"}, + { NULL } +}; + +void init_glue(void) +{ + PyObject *m; + + debug_setup_talloc_log(); + + m = Py_InitModule3("_glue", py_misc_methods, + "Python bindings for miscellaneous Samba functions."); + if (m == NULL) + return; + + PyModule_AddObject(m, "version", + PyString_FromString(SAMBA_VERSION_STRING)); +} + diff --git a/pool/shard006/C/0118225_regedit_samba3.c b/pool/shard006/C/0118225_regedit_samba3.c new file mode 100644 index 0000000000000000000000000000000000000000..a1f8b39a47d0c10900bf64dc24f149c4ba2bb6e4 --- /dev/null +++ b/pool/shard006/C/0118225_regedit_samba3.c @@ -0,0 +1,244 @@ +/* + * Samba Unix/Linux SMB client library + * Registry Editor + * Copyright (C) Christopher Davis 2012 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 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 . + */ + +/* s3 registry backend, adapted from rpc backend */ + +#include "includes.h" +#include "lib/registry/registry.h" +#include "regedit.h" + +struct samba3_key { + struct registry_key key; + struct samba3_registry_key s3key; +}; + +struct samba3_registry_context { + struct registry_context context; +}; + +static struct registry_operations reg_backend_s3; + +static struct { + uint32_t hkey; + const char *name; +} known_hives[] = { + { HKEY_LOCAL_MACHINE, "HKLM" }, + { HKEY_CURRENT_USER, "HKCU" }, + { HKEY_CLASSES_ROOT, "HKCR" }, + { HKEY_PERFORMANCE_DATA, "HKPD" }, + { HKEY_USERS, "HKU" }, + { HKEY_DYN_DATA, "HKDD" }, + { HKEY_CURRENT_CONFIG, "HKCC" }, + { 0, NULL } +}; + +static WERROR samba3_get_predefined_key(struct registry_context *ctx, + uint32_t hkey_type, + struct registry_key **k) +{ + int n; + const char *name; + struct samba3_key *mykeydata; + + *k = NULL; + name = NULL; + + for(n = 0; known_hives[n].hkey; n++) { + if(known_hives[n].hkey == hkey_type) { + name = known_hives[n].name; + break; + } + } + + if (name == NULL) { + DEBUG(1, ("No such hive %d\n", hkey_type)); + return WERR_NO_MORE_ITEMS; + } + + mykeydata = talloc_zero(ctx, struct samba3_key); + W_ERROR_HAVE_NO_MEMORY(mykeydata); + mykeydata->key.context = ctx; + *k = (struct registry_key *)mykeydata; + + return reg_openhive_wrap(ctx, name, &mykeydata->s3key); +} + +static WERROR samba3_open_key(TALLOC_CTX *mem_ctx, struct registry_key *h, + const char *name, struct registry_key **key) +{ + struct samba3_key *parentkeydata, *mykeydata; + + parentkeydata = talloc_get_type(h, struct samba3_key); + + mykeydata = talloc_zero(mem_ctx, struct samba3_key); + W_ERROR_HAVE_NO_MEMORY(mykeydata); + mykeydata->key.context = h->context; + *key = (struct registry_key *)mykeydata; + + return reg_openkey_wrap(mem_ctx, &parentkeydata->s3key, + name, &mykeydata->s3key); +} + +static WERROR samba3_get_value_by_index(TALLOC_CTX *mem_ctx, + const struct registry_key *parent, + uint32_t n, + const char **value_name, + uint32_t *type, + DATA_BLOB *data) +{ + struct samba3_key *mykeydata; + + mykeydata = talloc_get_type(parent, struct samba3_key); + + return reg_enumvalue_wrap(mem_ctx, &mykeydata->s3key, n, + discard_const(value_name), type, data); +} + +static WERROR samba3_get_value_by_name(TALLOC_CTX *mem_ctx, + const struct registry_key *parent, + const char *value_name, + uint32_t *type, + DATA_BLOB *data) +{ + struct samba3_key *mykeydata; + + mykeydata = talloc_get_type(parent, struct samba3_key); + + return reg_queryvalue_wrap(mem_ctx, &mykeydata->s3key, + value_name, type, data); +} + +static WERROR samba3_get_subkey_by_index(TALLOC_CTX *mem_ctx, + const struct registry_key *parent, + uint32_t n, + const char **name, + const char **keyclass, + NTTIME *last_changed_time) +{ + struct samba3_key *mykeydata; + + mykeydata = talloc_get_type(parent, struct samba3_key); + + *keyclass = NULL; + + return reg_enumkey_wrap(mem_ctx, &mykeydata->s3key, n, + discard_const(name), last_changed_time); +} + +static WERROR samba3_add_key(TALLOC_CTX *mem_ctx, + struct registry_key *parent, const char *path, + const char *key_class, + struct security_descriptor *sec, + struct registry_key **key) +{ + struct samba3_key *parentkd; + struct samba3_key *newkd; + + parentkd = talloc_get_type(parent, struct samba3_key); + newkd = talloc_zero(mem_ctx, struct samba3_key); + + W_ERROR_HAVE_NO_MEMORY(newkd); + newkd->key.context = parent->context; + *key = (struct registry_key *)newkd; + + return reg_createkey_wrap(mem_ctx, &parentkd->s3key, path, + &newkd->s3key); +} + +static WERROR samba3_del_key(TALLOC_CTX *mem_ctx, struct registry_key *parent, + const char *name) +{ + struct samba3_key *mykeydata; + + mykeydata = talloc_get_type(parent, struct samba3_key); + + return reg_deletekey_wrap(&mykeydata->s3key, name); +} + +static WERROR samba3_del_value(TALLOC_CTX *mem_ctx, struct registry_key *key, + const char *name) +{ + struct samba3_key *mykeydata = talloc_get_type(key, struct samba3_key); + + return reg_deletevalue_wrap(&mykeydata->s3key, name); +} + +static WERROR samba3_set_value(struct registry_key *key, const char *name, + uint32_t type, const DATA_BLOB data) +{ + struct samba3_key *mykeydata = talloc_get_type(key, struct samba3_key); + + return reg_setvalue_wrap(&mykeydata->s3key, name, type, data); +} + +static WERROR samba3_get_info(TALLOC_CTX *mem_ctx, + const struct registry_key *key, + const char **classname, + uint32_t *num_subkeys, + uint32_t *num_values, + NTTIME *last_changed_time, + uint32_t *max_subkeylen, + uint32_t *max_valnamelen, + uint32_t *max_valbufsize) +{ + struct samba3_key *mykeydata = talloc_get_type(key, struct samba3_key); + uint32_t max_subkeysize, secdescsize; + + return reg_queryinfokey_wrap(&mykeydata->s3key, num_subkeys, + max_subkeylen, &max_subkeysize, + num_values, max_valnamelen, + max_valbufsize, &secdescsize, + last_changed_time); +} + +static struct registry_operations reg_backend_s3 = { + .name = "samba3", + .open_key = samba3_open_key, + .get_predefined_key = samba3_get_predefined_key, + .enum_key = samba3_get_subkey_by_index, + .enum_value = samba3_get_value_by_index, + .get_value = samba3_get_value_by_name, + .set_value = samba3_set_value, + .delete_value = samba3_del_value, + .create_key = samba3_add_key, + .delete_key = samba3_del_key, + .get_key_info = samba3_get_info, +}; + +WERROR reg_open_samba3(TALLOC_CTX *mem_ctx, struct registry_context **ctx) +{ + WERROR rv; + struct samba3_registry_context *rctx; + + /* initialize s3 registry */ + rv = reg_init_wrap(); + if (!W_ERROR_IS_OK(rv)) { + return rv; + } + + rctx = talloc_zero(mem_ctx, struct samba3_registry_context); + if (rctx == NULL) { + return WERR_NOT_ENOUGH_MEMORY; + } + + *ctx = (struct registry_context *)rctx; + (*ctx)->ops = ®_backend_s3; + + return WERR_OK; +} diff --git a/pool/shard006/C/0118227_sram.c b/pool/shard006/C/0118227_sram.c new file mode 100644 index 0000000000000000000000000000000000000000..4175f2cea9999f4ff3ef8de95d4c4ed6aa0118cf --- /dev/null +++ b/pool/shard006/C/0118227_sram.c @@ -0,0 +1,235 @@ +/* $OpenBSD: sram.c,v 1.5 1997/11/20 17:02:31 etheisen Exp $ */ + +/* + * Copyright (c) 1995 Theo de Raadt + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed under OpenBSD by + * Theo de Raadt for Willowglen Singapore. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "mc.h" + +#if NMC > 0 +#include +#endif + +#include + +struct sramsoftc { + struct device sc_dev; + void * sc_paddr; + void * sc_vaddr; + int sc_len; +}; + +void sramattach __P((struct device *, struct device *, void *)); +int srammatch __P((struct device *, void *, void *)); + +struct cfattach sram_ca = { + sizeof(struct sramsoftc), srammatch, sramattach +}; + +struct cfdriver sram_cd = { + NULL, "sram", DV_DULL, 0 +}; + +int +srammatch(parent, vcf, args) + struct device *parent; + void *vcf, *args; +{ + struct cfdata *cf = vcf; + struct confargs *ca = args; + + if (cputyp == CPU_147) + return (0); + if (ca->ca_vaddr == (void *)-1) + return (!badpaddr(ca->ca_paddr, 1)); + return (!badvaddr(ca->ca_vaddr, 1)); +} + +void +sramattach(parent, self, args) + struct device *parent, *self; + void *args; +{ + struct confargs *ca = args; + struct sramsoftc *sc = (struct sramsoftc *)self; + struct mcreg *mc; + int i; + + switch (cputyp) { +#ifdef MVME162 + case CPU_162: + /* XXX this code will almost never be used. just in case. */ + mc = sys_mc; + if (!mc) + mc = (struct mcreg *)(IIOV(0xfff00000) + MC_MCCHIP_OFF); + + switch (mc->mc_memoptions & MC_MEMOPTIONS_SRAMMASK) { + case MC_MEMOPTIONS_SRAM128K: + sc->sc_len = 128*1024; + break; + case MC_MEMOPTIONS_SRAM512K: + sc->sc_len = 512*1024; + break; + case MC_MEMOPTIONS_SRAM1M: + sc->sc_len = 1024*1024; + break; + case MC_MEMOPTIONS_SRAM2M: + sc->sc_len = 2048*1024; + break; + } + break; +#endif +#ifdef MVME167 + case CPU_167: + case CPU_166: + sc->sc_len = 128*1024; /* always 128K */ + break; +#endif +#ifdef MVME177 + case CPU_177: + sc->sc_len = 128*1024; /* always 128K */ + break; +#endif + default: + sc->sc_len = 0; + break; + } + + printf(": len %d", sc->sc_len); + + sc->sc_paddr = ca->ca_paddr; + sc->sc_vaddr = mapiodev((void *)sc->sc_paddr, sc->sc_len); + if (sc->sc_vaddr == NULL) { + sc->sc_len = 0; + printf(" -- failed to map"); + } + printf("\n"); +} + +/*ARGSUSED*/ +int +sramopen(dev, flag, mode) + dev_t dev; + int flag, mode; +{ + if (minor(dev) >= sram_cd.cd_ndevs || + sram_cd.cd_devs[minor(dev)] == NULL) + return (ENODEV); + return (0); +} + +/*ARGSUSED*/ +int +sramclose(dev, flag, mode) + dev_t dev; + int flag, mode; +{ + + return (0); +} + +/*ARGSUSED*/ +int +sramioctl(dev, cmd, data, flag, p) + dev_t dev; + caddr_t data; + int cmd, flag; + struct proc *p; +{ + int unit = minor(dev); + struct sramsoftc *sc = (struct sramsoftc *) sram_cd.cd_devs[unit]; + int error = 0; + + switch (cmd) { + case MIOCGSIZ: + *(int *)data = sc->sc_len; + break; + default: + error = ENOTTY; + break; + } + return (error); +} + +/*ARGSUSED*/ +int +sramread(dev, uio, flags) + dev_t dev; + struct uio *uio; + int flags; +{ + int unit = minor(dev); + struct sramsoftc *sc = (struct sramsoftc *) sram_cd.cd_devs[unit]; + + return (memdevrw(sc->sc_vaddr, sc->sc_len, uio, flags)); +} + +/*ARGSUSED*/ +int +sramwrite(dev, uio, flags) + dev_t dev; + struct uio *uio; + int flags; +{ + int unit = minor(dev); + struct sramsoftc *sc = (struct sramsoftc *) sram_cd.cd_devs[unit]; + + return (memdevrw(sc->sc_vaddr, sc->sc_len, uio, flags)); +} + +int +srammmap(dev, off, prot) + dev_t dev; + int off, prot; +{ + int unit = minor(dev); + struct sramsoftc *sc = (struct sramsoftc *) sram_cd.cd_devs[unit]; + + if (minor(dev) != 0) + return (-1); + + /* allow access only in RAM */ + if (off > sc->sc_len) + return (-1); + return (m68k_btop(sc->sc_paddr + off)); +} diff --git a/pool/shard006/C/0118228_uart_cmd.c b/pool/shard006/C/0118228_uart_cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..e5d6da76b3950d9375ba973aea4bb8a6c60d62f3 --- /dev/null +++ b/pool/shard006/C/0118228_uart_cmd.c @@ -0,0 +1,153 @@ +/** + * @file + * @brief UART command handler. + * @copyright 2015 [DeviceHive](http://devicehive.com) + * @author Nikolay Khabarov + */ +#include "commands/uart_cmd.h" +#include "DH/uart.h" +#include "DH/adc.h" + +#ifdef DH_COMMANDS_UART // UART command handlers +#include "dhcommand_parser.h" +#include "dhterminal.h" +#include + +/** + * @brief UART initialization helper. + * @return Non-zero if UART was initialized. Zero otherwise. + */ +static int ICACHE_FLASH_ATTR uart_init(COMMAND_RESULT *cmd_res, ALLOWED_FIELDS fields, + const gpio_command_params *params, int is_int) +{ + if (fields & AF_UARTMODE) { + if (params->uart_speed == 0 && is_int) { + dh_uart_enable_buf_interrupt(false); + dh_command_done(cmd_res, ""); + return 1; + } else if(!!dh_uart_init(params->uart_speed, params->uart_bits, + params->uart_partity, params->uart_stopbits)) { + dh_command_fail(cmd_res, "Wrong UART mode"); + return 1; + } + } + + return 0; +} + +/* + * dh_handle_uart_write() implementation. + */ +void ICACHE_FLASH_ATTR dh_handle_uart_write(COMMAND_RESULT *cmd_res, const char *command, + const char *params, unsigned int params_len) +{ + gpio_command_params info; + ALLOWED_FIELDS fields = 0; + const char *err_msg = parse_params_pins_set(params, params_len, + &info, DH_ADC_SUITABLE_PINS, 0, + AF_UARTMODE | AF_DATA, &fields); + if (err_msg != 0) { + dh_command_fail(cmd_res, err_msg); + } else if (!uart_init(cmd_res, fields, &info, false)) { + dh_uart_set_mode(DH_UART_MODE_PER_BUF); + dh_uart_send_buf(info.data, info.data_len); + dh_command_done(cmd_res, ""); + } +} + + +/** + * dh_handle_uart_read() implementation. + */ +void ICACHE_FLASH_ATTR dh_handle_uart_read(COMMAND_RESULT *cmd_res, const char *command, + const char *params, unsigned int params_len) +{ + gpio_command_params info; + ALLOWED_FIELDS fields = 0; + if (params_len) { + const char *err_msg = parse_params_pins_set(params, params_len, + &info, DH_ADC_SUITABLE_PINS, 0, + AF_UARTMODE | AF_DATA | AF_TIMEOUT, &fields); + if (err_msg != 0) { + dh_command_fail(cmd_res, err_msg); + return; + } + if (uart_init(cmd_res, fields, &info, false)) + return; + if (fields & AF_TIMEOUT) { + if (info.timeout > 1000) { // TODO: MAX timeout constant + dh_command_fail(cmd_res, "Timeout out of range"); + return; + } + if (!(fields & AF_DATA)) { + dh_command_fail(cmd_res, "Timeout can be specified only with data"); + return; + } + } + } + + if (fields & AF_DATA) { + dh_uart_set_mode(DH_UART_MODE_PER_BUF); + dh_uart_send_buf(info.data, info.data_len); + system_soft_wdt_feed(); + delay_ms((fields & AF_TIMEOUT) ? info.timeout : 250); + system_soft_wdt_feed(); + } + + void *buf = 0; + size_t len = dh_uart_get_buf(&buf); + if (len > INTERFACES_BUF_SIZE) + len = INTERFACES_BUF_SIZE; + dh_command_done_buf(cmd_res, buf, len); + dh_uart_set_mode(DH_UART_MODE_PER_BUF); +} + + +/** + * dh_handle_uart_int() implementation. + */ +void ICACHE_FLASH_ATTR dh_handle_uart_int(COMMAND_RESULT *cmd_res, const char *command, + const char *params, unsigned int params_len) +{ + if (params_len) { + gpio_command_params info; + ALLOWED_FIELDS fields = 0; + const char *err_msg = parse_params_pins_set(params, params_len, + &info, DH_ADC_SUITABLE_PINS, dh_uart_get_callback_timeout(), + AF_UARTMODE | AF_TIMEOUT, &fields); + if (err_msg != 0) { + dh_command_fail(cmd_res, err_msg); + return; + } + if ((fields & AF_TIMEOUT) && info.timeout > 5000) { // TODO: MAX timeout constant + dh_command_fail(cmd_res, "Timeout out of range"); + return; + } + if (uart_init(cmd_res, fields, &info, true)) + return; + if (fields & AF_TIMEOUT) + dh_uart_set_callback_timeout(info.timeout); + } + + dh_uart_set_mode(DH_UART_MODE_PER_BUF); + dh_uart_enable_buf_interrupt(true); + dh_command_done(cmd_res, ""); +} + + +/** + * dh_handle_uart_terminal() implementation. + */ +void ICACHE_FLASH_ATTR dh_handle_uart_terminal(COMMAND_RESULT *cmd_res, const char *command, + const char *params, unsigned int params_len) +{ + if (params_len) { + dh_command_fail(cmd_res, "No parameters expected"); + return; + } + + dhterminal_init(); + dh_command_done(cmd_res, ""); +} + +#endif /* DH_COMMANDS_UART */ diff --git a/pool/shard006/C/0118229_wdns-test-downcase-rrset.c b/pool/shard006/C/0118229_wdns-test-downcase-rrset.c new file mode 100644 index 0000000000000000000000000000000000000000..7146c9afddbe0f7ce5f4b372529d062c29d90a48 --- /dev/null +++ b/pool/shard006/C/0118229_wdns-test-downcase-rrset.c @@ -0,0 +1,36 @@ +#include "private.h" + +#include + +bool loadfunc(uint8_t *, size_t); +void freefunc(void); +bool testfunc(void); + +wdns_rrset_t rrset; + +bool +loadfunc(uint8_t *data, size_t len) +{ + wdns_res res; + res = wdns_deserialize_rrset(&rrset, data, len); + if (res != wdns_res_success) + return (false); + return (true); +} + +void +freefunc(void) +{ + wdns_clear_rrset(&rrset); +} + +bool +testfunc(void) +{ + wdns_res res; + res = wdns_downcase_rrset(&rrset); + if (res != wdns_res_success) + return (false); + wdns_print_rrset(stdout, &rrset, WDNS_MSG_SEC_ANSWER); + return (true); +} diff --git a/pool/shard006/C/0118230_mq_send.c b/pool/shard006/C/0118230_mq_send.c new file mode 100644 index 0000000000000000000000000000000000000000..7b317a4557eaf7d62fcf39f5d97f2946a59f63cc --- /dev/null +++ b/pool/shard006/C/0118230_mq_send.c @@ -0,0 +1,108 @@ +#include "mqueue.h" +#include +#include +#include +#include + +int mq_send (mqd_t mqd,const char *ptr,size_t len,unsigned int prio) +{ + int n = 0; + long index = 0; + long freeindex = 0; + int8_t *mptr; + struct sigevent *sigev; + struct mq_hdr *mqhdr; + struct msg_hdr *msghdr; + struct msg_hdr *nmsghdr; + struct msg_hdr *pmsghdr; + struct mq_info *mqinfo; + struct mq_attr *attr; + + mqinfo = mqd; + if (mqinfo->mqi_magic != MQI_MAGIC) { + errno = EBADF; + return -1; + } + + mqhdr = mqinfo->mqi_hdr; + mptr = (int8_t *) mqhdr; + attr = &mqhdr->mqh_attr; + + if ((n = pthread_mutex_lock (&mqhdr->mqh_lock)) != 0) { + errno = n; + return -1; + } + + if (len > attr->mq_msgsize) { + errno = EMSGSIZE; + goto err; + } + + if (attr->mq_curmsgs == 0) { + if (mqhdr->mqh_pid != 0 && mqhdr->mqh_nwait == 0) { + sigev = &mqhdr->mqh_event; + + if (sigev->sigev_notify == SIGEV_SIGNAL) { + sigqueue (mqhdr->mqh_pid,sigev->sigev_signo,sigev->sigev_value); + } + + mqhdr->mqh_pid = 0; + } + } else if (attr->mq_curmsgs >= attr->mq_maxmsg) { + if (mqinfo->mqi_flags & O_NONBLOCK) { + errno = EAGAIN; + goto err; + } + + while (attr->mq_curmsgs >= attr->mq_maxmsg) { + pthread_cond_wait (&mqhdr->mqh_wait,&mqhdr->mqh_lock); + } + } + + if ((freeindex = mqhdr->mqh_free) == 0) { + printf ("mq_send:wrong state\n"); + return -1; + } + + nmsghdr = (struct msg_hdr *) &mptr[freeindex]; + nmsghdr->msg_prio = prio; + nmsghdr->msg_len = len; + + memcpy (nmsghdr + 1,ptr,len); + mqhdr->mqh_free = nmsghdr->msg_next; + + index = mqhdr->mqh_head; + pmsghdr = (struct msg_hdr *) & (mqhdr->mqh_head); + while (index != 0) { + msghdr = (struct msg_hdr *) &mptr[index]; + + if (prio > msghdr->msg_prio) { + nmsghdr->msg_next = index; + pmsghdr->msg_next = freeindex; + + break; + } + + index = msghdr->msg_next; + pmsghdr = msghdr; + } + + if (index == 0) { + pmsghdr->msg_next = freeindex; + nmsghdr->msg_next = 0; + } + + if (attr->mq_curmsgs == 0) + pthread_cond_signal (&mqhdr->mqh_wait); + + attr->mq_curmsgs ++; + + pthread_mutex_unlock (&mqhdr->mqh_lock); + return 0; + +err: + pthread_mutex_unlock (&mqhdr->mqh_lock); + return -1; +} + + diff --git a/pool/shard006/C/0118231_FreeSpaceAtom.c b/pool/shard006/C/0118231_FreeSpaceAtom.c new file mode 100644 index 0000000000000000000000000000000000000000..aa53b8ea85be8a9c0eec5e6ce0f1daf595c3b51c --- /dev/null +++ b/pool/shard006/C/0118231_FreeSpaceAtom.c @@ -0,0 +1,127 @@ +/* +This software module was originally developed by Apple Computer, Inc. +in the course of development of MPEG-4. +This software module is an implementation of a part of one or +more MPEG-4 tools as specified by MPEG-4. +ISO/IEC gives users of MPEG-4 free license to this +software module or modifications thereof for use in hardware +or software products claiming conformance to MPEG-4. +Those intending to use this software module in hardware or software +products are advised that its use may infringe existing patents. +The original developer of this software module and his/her company, +the subsequent editors and their companies, and ISO/IEC have no +liability for use of this software module or modifications thereof +in an implementation. +Copyright is not released for non MPEG-4 conforming +products. Apple Computer, Inc. retains full right to use the code for its own +purpose, assign or donate the code to a third party and to +inhibit third parties from using the code for non +MPEG-4 conforming products. +This copyright notice must be included in all copies or +derivative works. Copyright (c) 1999. +*/ +/* + $Id: FreeSpaceAtom.c,v 1.1.1.1 2002/09/20 08:53:34 julien Exp $ +*/ + +#include "MP4Atoms.h" +#include +#include + +static void destroy( MP4AtomPtr s ) +{ + MP4FreeSpaceAtomPtr self; + self = (MP4FreeSpaceAtomPtr) s; + if ( self->data ) + { + free( self->data ); + self->data = NULL; + } + if ( self->super ) + self->super->destroy( s ); +} + +static MP4Err serialize( struct MP4Atom* s, char* buffer ) +{ + MP4Err err; + MP4FreeSpaceAtomPtr self = (MP4FreeSpaceAtomPtr) s; + err = MP4NoErr; + + err = MP4SerializeCommonBaseAtomFields( s, buffer ); if (err) goto bail; + buffer += self->bytesWritten; + PUTBYTES( self->data, self->dataSize ); + assert( self->bytesWritten == self->size ); +bail: + TEST_RETURN( err ); + + return err; +} + +static MP4Err calculateSize( struct MP4Atom* s ) +{ + MP4Err err; + MP4FreeSpaceAtomPtr self = (MP4FreeSpaceAtomPtr) s; + err = MP4NoErr; + + err = MP4CalculateBaseAtomFieldSize( s ); if (err) goto bail; + self->size += self->dataSize; +bail: + TEST_RETURN( err ); + + return err; +} + + +static MP4Err createFromInputStream( MP4AtomPtr s, MP4AtomPtr proto, MP4InputStreamPtr inputStream ) +{ + MP4Err err; + long bytesToRead; + MP4FreeSpaceAtomPtr self = (MP4FreeSpaceAtomPtr) s; + + err = MP4NoErr; + if ( self == NULL ) + BAILWITHERROR( MP4BadParamErr ) + err = self->super->createFromInputStream( s, proto, (char*) inputStream ); + + bytesToRead = s->size - s->bytesRead; + if (bytesToRead > 0) { + self->data = (char*) calloc( 1, bytesToRead ); + TESTMALLOC( self->data ); + GETBYTES( bytesToRead, data ); + } + else self->data = 0; + self->dataSize = bytesToRead; + +bail: + TEST_RETURN( err ); + + if ( err && self->data ) + { + free( self->data ); + } + return err; +} + +MP4Err MP4CreateFreeSpaceAtom( MP4FreeSpaceAtomPtr *outAtom ) +{ + MP4Err err; + MP4FreeSpaceAtomPtr self; + + self = (MP4FreeSpaceAtomPtr) calloc( 1, sizeof(MP4FreeSpaceAtom) ); + TESTMALLOC( self ); + + err = MP4CreateBaseAtom( (MP4AtomPtr) self ); + if ( err ) goto bail; + self->type = MP4FreeSpaceAtomType; + self->name = "free space"; + self->destroy = destroy; + self->createFromInputStream = (cisfunc) createFromInputStream; + self->data = NULL; + self->calculateSize = calculateSize; + self->serialize = serialize; + *outAtom = self; +bail: + TEST_RETURN( err ); + + return err; +} diff --git a/pool/shard006/C/0118232_sse2-cvtsd2si-2.c b/pool/shard006/C/0118232_sse2-cvtsd2si-2.c new file mode 100644 index 0000000000000000000000000000000000000000..df1008eeb3808ae00b45ddb4640d3e9ceba0fb99 --- /dev/null +++ b/pool/shard006/C/0118232_sse2-cvtsd2si-2.c @@ -0,0 +1,39 @@ +/* { dg-do run { target { ! ia32 } } } */ +/* { dg-require-effective-target sse2 } */ +/* { dg-options "-O2 -msse2" } */ + +#ifndef CHECK_H +#define CHECK_H "sse2-check.h" +#endif + +#ifndef TEST +#define TEST sse2_test +#endif + +#include CHECK_H + +#include + +static long long +__attribute__((noinline, unused)) +test (__m128d p) +{ + return _mm_cvtsd_si64 (p); +} + +static void +TEST (void) +{ + union128d s; + long long e; + long long d; + + s.x = _mm_set_pd (829496729501.4, 429496729501.4); + + d = test (s.x); + + e = (long long)(s.a[0] + 0.5); + + if (d != e) + abort (); +} diff --git a/pool/shard006/C/0118233_iqs128_cap_sensor.c b/pool/shard006/C/0118233_iqs128_cap_sensor.c new file mode 100644 index 0000000000000000000000000000000000000000..55e09634d7eaecfa12de069e2a911ca5b79ab499 --- /dev/null +++ b/pool/shard006/C/0118233_iqs128_cap_sensor.c @@ -0,0 +1,181 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct tegra_cap_dev { + struct switch_dev sdev; + unsigned gpio; + int irq; + int value; + struct work_struct work; + struct regulator *cap_3v3_reg; +}; + +static void tegra_cap_work(struct work_struct *work) +{ + int state; + struct tegra_cap_dev *dev = + container_of(work, struct tegra_cap_dev, work); + + state = gpio_get_value(dev->gpio); + if (dev->value != state) { + //printk("%s: cap sensor value changed from %d to %d\n", __func__, dev->value, state); + dev->value = state; + switch_set_state(&dev->sdev, state); + } +} + +static irqreturn_t tegra_cap_irq_handler(int irq, void *dev_id) +{ + struct tegra_cap_dev *dev = + (struct tegra_cap_dev *)dev_id; + + schedule_work(&dev->work); + return IRQ_HANDLED; +} + +static ssize_t tegra_cap_print_state(struct switch_dev *sdev, char *buf) +{ + struct tegra_cap_dev *dev = + container_of(sdev, struct tegra_cap_dev, sdev); + return sprintf(buf, "%d", dev->value); +} + +static int tegra_cap_regulator_enabled(int enable, struct tegra_cap_dev *dev) +{ + if (!dev->cap_3v3_reg && enable) { + dev->cap_3v3_reg = regulator_get(NULL, "vdd_3v3_cap"); + if (IS_ERR_OR_NULL(dev->cap_3v3_reg)) { + printk("%s: get regulator failed\n", __func__); + dev->cap_3v3_reg = NULL; + return -1; + } + regulator_enable(dev->cap_3v3_reg); + printk("%s: setting enabled\n", __func__); + } else if (dev->cap_3v3_reg && !enable) { + regulator_disable(dev->cap_3v3_reg); + regulator_put(dev->cap_3v3_reg); + dev->cap_3v3_reg = NULL; + printk("%s: setting disabled\n", __func__); + } else + return -1; + + return 0; +} + +static int tegra_cap_probe(struct platform_device *pdev) +{ + struct cap_sensor_platform_data *pdata = pdev->dev.platform_data; + struct tegra_cap_dev *dev = NULL; + int ret = 0; + + dev = kzalloc(sizeof(struct tegra_cap_dev), GFP_KERNEL); + if (!dev) + return -ENOMEM; + + /* Turning on device power */ + tegra_cap_regulator_enabled(1, dev); + + /* Register switch device */ + dev->sdev.name = "iqs128_cap"; + dev->sdev.print_state = tegra_cap_print_state; + + ret = switch_dev_register(&dev->sdev); + if (ret < 0) + goto err_switch_dev_register; + + /* Setting out gpio pin status */ + dev->gpio = pdata->gpio_num; + + ret = gpio_request(dev->gpio, pdev->name); + if (ret < 0) + goto err_request_gpio; + + ret = gpio_direction_input(dev->gpio); + if (ret < 0) + goto err_set_gpio_input; + + gpio_export(dev->gpio, 0); + + dev->irq = pdata->irq; + if (dev->irq < 0) { + ret = dev->irq; + goto err_detect_irq_num_failed; + } + + tegra_gpio_enable(dev->gpio); + + /* Init work queue and irq handler */ + INIT_WORK(&dev->work, tegra_cap_work); + + ret = request_irq(dev->irq, tegra_cap_irq_handler, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, pdev->name, dev); + if (ret < 0) + goto err_request_irq; + + /* Reading current value */ + tegra_cap_work(&dev->work); + + return 0; + +err_request_irq: +err_detect_irq_num_failed: +err_gpio_set_active_low: +err_gpio_enable: +err_set_gpio_input: + gpio_free(dev->gpio); +err_request_gpio: + switch_dev_unregister(&dev->sdev); +err_switch_dev_register: + kfree(dev); + + return ret; +} + +static int __devexit tegra_cap_remove(struct platform_device *pdev) +{ + struct tegra_cap_dev *dev = platform_get_drvdata(pdev); + + cancel_work_sync(&dev->work); + tegra_cap_regulator_enabled(0, dev); + gpio_free(dev->gpio); + switch_dev_unregister(&dev->sdev); + kfree(dev); + + return 0; +} + +static struct platform_driver tegra_cap_driver = { + .probe = tegra_cap_probe, + .remove = __devexit_p(tegra_cap_remove), + .driver = { + .name = "tegra_cap", + .owner = THIS_MODULE, + }, +}; + +static int __init tegra_cap_init(void) +{ + return platform_driver_register(&tegra_cap_driver); +} + +static void __exit tegra_cap_exit(void) +{ + platform_driver_unregister(&tegra_cap_driver); +} + +module_init(tegra_cap_init); +module_exit(tegra_cap_exit); + +MODULE_AUTHOR("Jeff Yu "); +MODULE_DESCRIPTION("IQS128 cap Sensor driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0118234_usbh_control.c b/pool/shard006/C/0118234_usbh_control.c new file mode 100644 index 0000000000000000000000000000000000000000..d034eec7f524bbb49fd89b5e46f16456b2af132e --- /dev/null +++ b/pool/shard006/C/0118234_usbh_control.c @@ -0,0 +1,138 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2020, Ha Thach (tinyusb.org) + * + * 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. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if CFG_TUH_ENABLED + +#include "tusb.h" +#include "usbh_classdriver.h" + +enum +{ + STAGE_SETUP, + STAGE_DATA, + STAGE_ACK +}; + +typedef struct +{ + tusb_control_request_t request TU_ATTR_ALIGNED(4); + + uint8_t stage; + uint8_t* buffer; + tuh_control_complete_cb_t complete_cb; +} usbh_control_xfer_t; + +static usbh_control_xfer_t _ctrl_xfer; + +//CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN +//static uint8_t _tuh_ctrl_buf[CFG_TUH_ENUMERATION_BUFSIZE]; + +//--------------------------------------------------------------------+ +// MACRO TYPEDEF CONSTANT ENUM DECLARATION +//--------------------------------------------------------------------+ + +bool tuh_control_xfer (uint8_t dev_addr, tusb_control_request_t const* request, void* buffer, tuh_control_complete_cb_t complete_cb) +{ + // TODO need to claim the endpoint first + const uint8_t rhport = usbh_get_rhport(dev_addr); + + _ctrl_xfer.request = (*request); + _ctrl_xfer.buffer = buffer; + _ctrl_xfer.stage = STAGE_SETUP; + _ctrl_xfer.complete_cb = complete_cb; + + TU_LOG2("Control Setup (addr = %u): ", dev_addr); + TU_LOG2_VAR(request); + TU_LOG2("\r\n"); + + // Send setup packet + TU_ASSERT( hcd_setup_send(rhport, dev_addr, (uint8_t const*) &_ctrl_xfer.request) ); + + return true; +} + +static void _xfer_complete(uint8_t dev_addr, xfer_result_t result) +{ + TU_LOG2("\r\n"); + if (_ctrl_xfer.complete_cb) _ctrl_xfer.complete_cb(dev_addr, &_ctrl_xfer.request, result); +} + +bool usbh_control_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) +{ + (void) ep_addr; + (void) xferred_bytes; + + const uint8_t rhport = usbh_get_rhport(dev_addr); + + tusb_control_request_t const * request = &_ctrl_xfer.request; + + if (XFER_RESULT_SUCCESS != result) + { + TU_LOG2("Control failed: result = %d\r\n", result); + + // terminate transfer if any stage failed + _xfer_complete(dev_addr, result); + }else + { + switch(_ctrl_xfer.stage) + { + case STAGE_SETUP: + _ctrl_xfer.stage = STAGE_DATA; + if (request->wLength) + { + // DATA stage: initial data toggle is always 1 + hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, request->bmRequestType_bit.direction), _ctrl_xfer.buffer, request->wLength); + return true; + } + __attribute__((fallthrough)); + + case STAGE_DATA: + _ctrl_xfer.stage = STAGE_ACK; + + if (request->wLength) + { + TU_LOG2("Control data (addr = %u):\r\n", dev_addr); + TU_LOG2_MEM(_ctrl_xfer.buffer, request->wLength, 2); + } + + // ACK stage: toggle is always 1 + hcd_edpt_xfer(rhport, dev_addr, tu_edpt_addr(0, 1-request->bmRequestType_bit.direction), NULL, 0); + break; + + case STAGE_ACK: + _xfer_complete(dev_addr, result); + break; + + default: return false; + } + } + + return true; +} + +#endif diff --git a/pool/shard006/C/0118236_stack.c b/pool/shard006/C/0118236_stack.c new file mode 100644 index 0000000000000000000000000000000000000000..bdc8daae9b032089bac594fe26cde15c4b455b97 --- /dev/null +++ b/pool/shard006/C/0118236_stack.c @@ -0,0 +1,112 @@ +#include +#include "../stack.h" + +void spec_push_pop_equality(void) +{ + int values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + struct stack *stack = NULL; + + for (int i = 0; i < 10; i++) { + stack_push(&stack, values + i); + } + + sp_assert(stack != NULL); + + for (int i = 9; i > 2; i--) { + int *val = (int *)stack_pop(&stack); + sp_assert(val == values + i); + } + + stack_free(&stack, NULL); +} + +void spec_free_empty_stack(void) +{ + struct stack *stack = NULL; + stack_free(&stack, NULL); + + sp_assert(stack == NULL); +} + +void spec_pop_from_empty_stack(void) +{ + struct stack *stack = NULL; + + sp_assert(stack_pop(&stack) == NULL); +} + +void spec_stack_remove_middle(void) +{ + struct stack *stack = NULL; + int a = 1; + int b = 2; + int c = 3; + + stack_push(&stack, &a); + stack_push(&stack, &b); + stack_push(&stack, &c); + + sp_assert(*((int *)stack_remove(&stack, &b)) == 2); + sp_assert(*((int *)stack_pop(&stack)) == 3); + sp_assert(*((int *)stack_pop(&stack)) == 1); +} + +void spec_stack_remove_first(void) +{ + struct stack *stack = NULL; + int a = 1; + int b = 2; + int c = 3; + + stack_push(&stack, &a); + stack_push(&stack, &b); + stack_push(&stack, &c); + + sp_assert(*((int *)stack_remove(&stack, &a)) == 1); + sp_assert(*((int *)stack_pop(&stack)) == 3); + sp_assert(*((int *)stack_pop(&stack)) == 2); +} + +void spec_stack_remove_last(void) +{ + struct stack *stack = NULL; + int a = 1; + int b = 2; + int c = 3; + + stack_push(&stack, &a); + stack_push(&stack, &b); + stack_push(&stack, &c); + + sp_assert(*((int *)stack_remove(&stack, &c)) == 3); + sp_assert(*((int *)stack_pop(&stack)) == 2); + sp_assert(*((int *)stack_pop(&stack)) == 1); +} + +void spec_stack_size(void) +{ + int values[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + struct stack *stack = NULL; + + for (int i = 0; i < 10; i++) { + stack_push(&stack, values + i); + } + + sp_assert(stack_size(&stack) == 10); + + stack_free(&stack, NULL); +} + +void spec_stack_peek(void) +{ + struct stack *stack = NULL; + int value = 42; + + stack_push(&stack, &value); + + int *result = stack_peek(&stack); + + sp_assert_equal_i(*result, value); + + stack_free(&stack, NULL); +} diff --git a/pool/shard006/C/0118237_rtl8195a_pwm.c b/pool/shard006/C/0118237_rtl8195a_pwm.c new file mode 100644 index 0000000000000000000000000000000000000000..d74a579554d14884825bda5651967be2b775a4b3 --- /dev/null +++ b/pool/shard006/C/0118237_rtl8195a_pwm.c @@ -0,0 +1,219 @@ +/* + * Routines to access hardware + * + * Copyright (c) 2013 Realtek Semiconductor Corp. + * + * This module is a confidential and proprietary property of RealTek and + * possession or use of this module requires written permission of RealTek. + */ + + +#include "rtl8195a.h" +#include "hal_peri_on.h" + +#ifdef CONFIG_PWM_EN +#include "rtl8195a_pwm.h" +#include "hal_pwm.h" + +extern HAL_PWM_ADAPTER PWMPin[]; + +extern HAL_TIMER_OP HalTimerOp; + +/** + * @brief Configure a G-Timer to generate a tick with certain time. + * + * @param pwm_id: the PWM pin index + * @param tick_time: the time (micro-second) of a tick + * + * @retval None + */ +void +Pwm_SetTimerTick_8195a( + HAL_PWM_ADAPTER *pPwmAdapt, + u32 tick_time +) +{ + TIMER_ADAPTER TimerAdapter; + + + if (tick_time <= MIN_GTIMER_TIMEOUT) { + tick_time = MIN_GTIMER_TIMEOUT; + } + else { + tick_time = (((tick_time-1)/TIMER_TICK_US)+1) * TIMER_TICK_US; + } + + // Initial a G-Timer for the PWM pin + if (pPwmAdapt->tick_time != tick_time) { + TimerAdapter.IrqDis = 1; // Disable Irq + TimerAdapter.IrqHandle.IrqFun = (IRQ_FUN) NULL; + TimerAdapter.IrqHandle.IrqNum = TIMER2_7_IRQ; + TimerAdapter.IrqHandle.Priority = 10; + TimerAdapter.IrqHandle.Data = (u32)NULL; + TimerAdapter.TimerId = pPwmAdapt->gtimer_id; + TimerAdapter.TimerIrqPriority = 0; + TimerAdapter.TimerLoadValueUs = tick_time-1; + TimerAdapter.TimerMode = 1; // auto-reload with user defined value + + HalTimerOp.HalTimerInit((VOID*) &TimerAdapter); + pPwmAdapt->tick_time = tick_time; + DBG_PWM_INFO("%s: Timer_Id=%d Count=%d\n", __FUNCTION__, pPwmAdapt->gtimer_id, tick_time); + } + +} + + +/** + * @brief Set the duty ratio of the PWM pin. + * + * @param pwm_id: the PWM pin index + * @param period: the period time, in micro-second. + * @param pulse_width: the pulse width time, in micro-second. + * + * @retval None + */ +void +HAL_Pwm_SetDuty_8195a( + HAL_PWM_ADAPTER *pPwmAdapt, + u32 period, + u32 pulse_width +) +{ + u32 RegAddr; + u32 RegValue; + u32 period_tick; + u32 pulsewidth_tick; + u32 tick_time; + u8 timer_id; + u8 pwm_id; + + pwm_id = pPwmAdapt->pwm_id; + // Adjust the tick time to a proper value + if (period < (MIN_GTIMER_TIMEOUT*2)) { + DBG_PWM_ERR ("HAL_Pwm_SetDuty_8195a: Invalid PWM period(%d), too short!!\n", period); + tick_time = MIN_GTIMER_TIMEOUT; + period = MIN_GTIMER_TIMEOUT*2; + } + else { + tick_time = period / 0x3fc; // a duty cycle be devided into 1020 ticks + if (tick_time < MIN_GTIMER_TIMEOUT) { + tick_time = MIN_GTIMER_TIMEOUT; + } + } + + Pwm_SetTimerTick_8195a(pPwmAdapt, tick_time); + tick_time = pPwmAdapt->tick_time; +#if 0 + // Check if current tick time needs adjustment + if ((pPwmAdapt->tick_time << 12) <= period) { + // need a longger tick time + } + else if ((pPwmAdapt->tick_time >> 2) >= period) { + // need a shorter tick time + } +#endif + period_tick = period/tick_time; + if (period_tick == 0) { + period_tick = 1; + } + + if (pulse_width >= period) { +// pulse_width = period-1; + pulse_width = period; + } + pulsewidth_tick = pulse_width/tick_time; + if (pulsewidth_tick == 0) { +// pulsewidth_tick = 1; + } + + timer_id = pPwmAdapt->gtimer_id; + + pPwmAdapt->period = period_tick & 0x3ff; + pPwmAdapt->pulsewidth = pulsewidth_tick & 0x3ff; + + RegAddr = REG_PERI_PWM0_CTRL + (pwm_id*4); + RegValue = BIT31 | (timer_id<<24) | (pulsewidth_tick<<12) | period_tick; + + HAL_WRITE32(PERI_ON_BASE, RegAddr, RegValue); +} + +/** + * @brief Initializes and enable a PWM control pin. + * + * @param pwm_id: the PWM pin index + * @param sel: pin mux selection + * @param timer_id: the G-timer index assigned to this PWM + * + * @retval HAL_Status + */ +HAL_Status +HAL_Pwm_Init_8195a( + HAL_PWM_ADAPTER *pPwmAdapt +) +{ + u32 pwm_id; + u32 pin_sel; + + pwm_id = pPwmAdapt->pwm_id; + pin_sel = pPwmAdapt->sel; + // Initial a G-Timer for the PWM pin + Pwm_SetTimerTick_8195a(pPwmAdapt, MIN_GTIMER_TIMEOUT); + + // Set default duty ration + HAL_Pwm_SetDuty_8195a(pPwmAdapt, 20000, 10000); + + // Configure the Pin Mux + PinCtrl((PWM0+pwm_id), pin_sel, 1); + + return HAL_OK; +} + + +/** + * @brief Enable a PWM control pin. + * + * @param pwm_id: the PWM pin index + * + * @retval None + */ +void +HAL_Pwm_Enable_8195a( + HAL_PWM_ADAPTER *pPwmAdapt +) +{ + u32 pwm_id; + + pwm_id = pPwmAdapt->pwm_id; + // Configure the Pin Mux + if (!pPwmAdapt->enable) { + PinCtrl((PWM0+pwm_id), pPwmAdapt->sel, 1); + HalTimerOp.HalTimerEn(pPwmAdapt->gtimer_id); + pPwmAdapt->enable = 1; + } +} + + +/** + * @brief Disable a PWM control pin. + * + * @param pwm_id: the PWM pin index + * + * @retval None + */ +void +HAL_Pwm_Disable_8195a( + HAL_PWM_ADAPTER *pPwmAdapt +) +{ + u32 pwm_id; + + pwm_id = pPwmAdapt->pwm_id; + // Configure the Pin Mux + if (pPwmAdapt->enable) { + PinCtrl((PWM0+pwm_id), pPwmAdapt->sel, 0); + HalTimerOp.HalTimerDis(pPwmAdapt->gtimer_id); + pPwmAdapt->enable = 0; + } +} + +#endif //CONFIG_PWM_EN diff --git a/pool/shard006/C/0118238_banshee-player-equalizer.c b/pool/shard006/C/0118238_banshee-player-equalizer.c new file mode 100644 index 0000000000000000000000000000000000000000..9e28d6d4c429b1247b08425f95fe99cf850d47a9 --- /dev/null +++ b/pool/shard006/C/0118238_banshee-player-equalizer.c @@ -0,0 +1,196 @@ +// +// banshee-player-equalizer.c +// +// Authors: +// Alexander Hixon +// Aaron Bockover +// Sebastian Dröge +// +// Copyright (C) 2005-2008 Novell, Inc. +// +// 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 "banshee-player-private.h" + +enum _BpEqStatus { + BP_EQ_STATUS_UNCHECKED, + BP_EQ_STATUS_DISABLED, + BP_EQ_STATUS_USE_BUILTIN, + BP_EQ_STATUS_USE_SYSTEM +}; + +// --------------------------------------------------------------------------- +// Internal Functions +// --------------------------------------------------------------------------- + +GstElement * +_bp_equalizer_new (BansheePlayer *player) +{ + GstElement *equalizer; + + if (player->equalizer_status == BP_EQ_STATUS_DISABLED) { + return NULL; + } + + if (player->equalizer_status == BP_EQ_STATUS_UNCHECKED || + player->equalizer_status == BP_EQ_STATUS_USE_BUILTIN) { + equalizer = gst_element_factory_make ("banshee-equalizer", "banshee-equalizer"); + if (equalizer != NULL) { + if (player->equalizer_status == BP_EQ_STATUS_UNCHECKED) { + player->equalizer_status = BP_EQ_STATUS_USE_BUILTIN; + bp_debug ("Using built-in equalizer element"); + } + + return equalizer; + } + } + + if (player->equalizer_status == BP_EQ_STATUS_UNCHECKED || + player->equalizer_status == BP_EQ_STATUS_USE_SYSTEM) { + equalizer = gst_element_factory_make ("equalizer-10bands", "equalizer-10bands"); + if (equalizer != NULL) { + if (player->equalizer_status == BP_EQ_STATUS_USE_SYSTEM) { + return equalizer; + } + +// TODO Windows compiler doesn't like this, I'm unsure why +#ifndef WIN32 + GstElementFactory *efactory = gst_element_get_factory (equalizer); + if (gst_plugin_feature_check_version (GST_PLUGIN_FEATURE (efactory), 0, 10, 9)) { + bp_debug ("Using system (gst-plugins-good) equalizer element"); + player->equalizer_status = BP_EQ_STATUS_USE_SYSTEM; + return equalizer; + } +#endif + + bp_debug ("Buggy system equalizer found. gst-plugins-good 0.10.9 or better " + "required, or build Banshee with the built-in equalizer."); + gst_object_unref (equalizer); + } else { + bp_debug ("No system equalizer found"); + } + } + + bp_debug ("No suitable equalizer element could be found, disabling EQ for this session"); + player->equalizer_status = BP_EQ_STATUS_DISABLED; + return NULL; +} + + +// --------------------------------------------------------------------------- +// Public Functions +// --------------------------------------------------------------------------- + +P_INVOKE gboolean +bp_equalizer_is_supported (BansheePlayer *player) +{ + return player != NULL && player->equalizer != NULL && player->preamp != NULL; +} + +P_INVOKE void +bp_equalizer_set_preamp_level (BansheePlayer *player, gdouble level) +{ + g_return_if_fail (IS_BANSHEE_PLAYER (player)); + + if (player->equalizer != NULL && player->preamp != NULL) { + g_object_set (player->preamp, "volume", level, NULL); + } +} + +P_INVOKE void +bp_equalizer_set_gain (BansheePlayer *player, guint bandnum, gdouble gain) +{ + g_return_if_fail (IS_BANSHEE_PLAYER (player)); + + if (player->equalizer != NULL) { + GstObject *band; + + g_return_if_fail (bandnum < gst_child_proxy_get_children_count (GST_CHILD_PROXY (player->equalizer))); + + band = gst_child_proxy_get_child_by_index (GST_CHILD_PROXY (player->equalizer), bandnum); + g_object_set (band, "gain", gain, NULL); + g_object_unref (band); + } +} + +P_INVOKE void +bp_equalizer_get_bandrange (BansheePlayer *player, gint *min, gint *max) +{ + GParamSpec *pspec; + GParamSpecDouble *dpspec; + + g_return_if_fail (IS_BANSHEE_PLAYER (player)); + + if (player->equalizer == NULL) { + return; + } + + // Fetch gain range of first band (since it should be the same for the rest) + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (player->equalizer), "band0::gain"); + if (pspec == NULL) + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (player->equalizer), "band0"); + + if (pspec != NULL && G_IS_PARAM_SPEC_DOUBLE (pspec)) { + dpspec = (GParamSpecDouble *) pspec; + *min = dpspec->minimum; + *max = dpspec->maximum; + return; + } else { + g_warning ("Could not find valid gain range for equalizer element"); + } +} + +P_INVOKE guint +bp_equalizer_get_nbands (BansheePlayer *player) +{ + guint count; + + g_return_val_if_fail (IS_BANSHEE_PLAYER (player), 0); + + if (player->equalizer == NULL) { + return 0; + } + + count = gst_child_proxy_get_children_count (GST_CHILD_PROXY (player->equalizer)); + return count; +} + +P_INVOKE void +bp_equalizer_get_frequencies (BansheePlayer *player, gdouble **freq) +{ + gint i, count; + + g_return_if_fail (IS_BANSHEE_PLAYER (player)); + + if (player->equalizer == NULL) { + return; + } + + count = gst_child_proxy_get_children_count (GST_CHILD_PROXY (player->equalizer)); + + for (i = 0; i < count; i++) { + GstObject *band; + + band = gst_child_proxy_get_child_by_index (GST_CHILD_PROXY (player->equalizer), i); + g_object_get (G_OBJECT (band), "freq", &(*freq)[i], NULL); + g_object_unref (band); + } +} diff --git a/pool/shard006/C/0118239_go-data-slicer.c b/pool/shard006/C/0118239_go-data-slicer.c new file mode 100644 index 0000000000000000000000000000000000000000..39ea4c7fb75a17332395849aef9e4ba595309f20 --- /dev/null +++ b/pool/shard006/C/0118239_go-data-slicer.c @@ -0,0 +1,185 @@ +/* vim: set sw=8: -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ +/* + * go-data-slicer.h : The definition of a content for a data slicer + * + * Copyright (C) 2008 Jody Goldberg (jody@gnome.org) + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 + * USA + */ + +#include +#include "go-data-slicer-impl.h" +#include "go-data-slicer-field-impl.h" +#include "go-data-cache.h" + +#include +#include +#include + +#define GO_DATA_SLICER_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GO_DATA_SLICER_TYPE, GODataSlicerClass)) +#define IS_GO_DATA_SLICER_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GO_DATA_SLICER_TYPE)) +#define GO_DATA_SLICER_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GO_DATA_SLICER_TYPE, GODataSlicerClass)) + +enum { + PROP_0, + PROP_CACHE, /* GODataCache * */ + PROP_NAME, /* GOString */ +}; +static void +go_data_slicer_init (GODataSlicer *ds) +{ + int i; + + ds->cache = NULL; + ds->name = NULL; + ds->all_fields = g_ptr_array_new (); + for (i = GDS_FIELD_TYPE_MAX ; --i > GDS_FIELD_TYPE_UNSET ; ) + ds->fields[i] = g_array_new (FALSE, FALSE, sizeof (int)); +} + +static GObjectClass *parent_klass; +static void +go_data_slicer_finalize (GObject *obj) +{ + GODataSlicer *ds = (GODataSlicer *)obj; + int i; + + for (i = GDS_FIELD_TYPE_MAX ; --i > GDS_FIELD_TYPE_UNSET ; ) { + g_array_free (ds->fields[i], TRUE); + ds->fields[i] = NULL; + } + + for (i = (int)ds->all_fields->len ; i-- > 0 ; ) + g_object_unref (g_ptr_array_index (ds->all_fields, i)); + g_ptr_array_free (ds->all_fields, TRUE); + ds->all_fields = NULL; + + go_data_slicer_set_cache (ds, NULL); + go_string_unref (ds->name); ds->name = NULL; + + (parent_klass->finalize) (obj); +} + +static void +go_data_slicer_set_property (GObject *obj, guint property_id, + GValue const *value, GParamSpec *pspec) +{ + GODataSlicer *ds = (GODataSlicer *)obj; + + switch (property_id) { + case PROP_CACHE : go_data_slicer_set_cache (ds, g_value_get_object (value)); break; + case PROP_NAME : go_string_unref (ds->name); ds->name = g_value_dup_boxed (value); break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, property_id, pspec); + } +} + +static void +go_data_slicer_get_property (GObject *obj, guint property_id, + GValue *value, GParamSpec *pspec) +{ + GODataSlicer const *ds = (GODataSlicer const *)obj; + switch (property_id) { + case PROP_CACHE : g_value_set_object (value, ds->cache); break; + case PROP_NAME : g_value_set_boxed (value, ds->name); break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, property_id, pspec); + } +} + +static void +go_data_slicer_class_init (GODataSlicerClass *klass) +{ + GObjectClass *gobject_class = (GObjectClass *)klass; + gobject_class->set_property = go_data_slicer_set_property; + gobject_class->get_property = go_data_slicer_get_property; + gobject_class->finalize = go_data_slicer_finalize; + + g_object_class_install_property (gobject_class, PROP_CACHE, + g_param_spec_object ("cache", NULL, NULL, + GO_DATA_CACHE_TYPE, GSF_PARAM_STATIC | G_PARAM_READWRITE)); + g_object_class_install_property (gobject_class, PROP_NAME, + g_param_spec_boxed ("name", NULL, NULL, go_string_get_type (), + GSF_PARAM_STATIC | G_PARAM_READWRITE)); + + parent_klass = g_type_class_peek_parent (klass); +} + +GSF_CLASS (GODataSlicer, go_data_slicer, + go_data_slicer_class_init, go_data_slicer_init, + G_TYPE_OBJECT) + +/** + * go_data_slicer_get_cache : + * @ds : #GODataSlicer + * + * Does not add a reference. + * + * Returns : the #GODataCache associated with @ds + **/ +GODataCache * +go_data_slicer_get_cache (GODataSlicer const *ds) +{ + g_return_val_if_fail (IS_GO_DATA_SLICER (ds), NULL); + return ds->cache; +} + +/** + * go_data_slicer_set_cache: + * @ds : #GODataSlicer + * @cache : #GODataCache + * + * Assign @cache to @ds, and adds a reference to @cache + **/ +void +go_data_slicer_set_cache (GODataSlicer *ds, GODataCache *cache) +{ + g_return_if_fail (IS_GO_DATA_SLICER (ds)); + + if (NULL != cache) + g_object_ref (G_OBJECT (cache)); + if (NULL != ds->cache) + g_object_unref (ds->cache); + ds->cache = cache; +} + +void +go_data_slicer_add_field (GODataSlicer *ds, GODataSlicerField *field) +{ + g_return_if_fail (IS_GO_DATA_SLICER (ds)); + g_return_if_fail (IS_GO_DATA_SLICER_FIELD (field)); + g_return_if_fail (field->indx < 0); + g_return_if_fail (field->ds == NULL); + + field->indx = ds->all_fields->len; + field->ds = ds; + g_ptr_array_add (ds->all_fields, field); +} + +unsigned int +go_data_slicer_num_fields (GODataSlicer const *ds) +{ + g_return_val_if_fail (IS_GO_DATA_SLICER (ds), 0); + return ds->all_fields->len; +} + +GODataSlicerField * +go_data_slicer_get_field (GODataSlicer const *ds, unsigned int field_index) +{ + g_return_val_if_fail (IS_GO_DATA_SLICER (ds), NULL); + g_return_val_if_fail (field_index < ds->all_fields->len, NULL); + return g_ptr_array_index (ds->all_fields, field_index); +} + diff --git a/pool/shard006/C/0118242_analogout_device.c b/pool/shard006/C/0118242_analogout_device.c new file mode 100644 index 0000000000000000000000000000000000000000..2220b7d592eaeafabe5e42ce0239e6afd6db113a --- /dev/null +++ b/pool/shard006/C/0118242_analogout_device.c @@ -0,0 +1,111 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "mbed_assert.h" +#include "analogout_api.h" + +#if DEVICE_ANALOGOUT + +#include "cmsis.h" +#include "pinmap.h" +#include "mbed_error.h" +#include "PeripheralPins.h" + +// These variables are used for the "free" function +static int pa4_used = 0; +static int pa5_used = 0; + +void analogout_init(dac_t *obj, PinName pin) { + DAC_ChannelConfTypeDef sConfig = {0}; + + // Get the peripheral name (DAC_1, ...) from the pin and assign it to the object + obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC); + MBED_ASSERT(obj->dac != (DACName)NC); + // Get the pin function and assign the used channel to the object + uint32_t function = pinmap_function(pin, PinMap_DAC); + switch (STM_PIN_CHANNEL(function)) { + case 1: + obj->channel = DAC_CHANNEL_1; + break; +#if defined(DAC_CHANNEL_2) + case 2: + obj->channel = DAC_CHANNEL_2; + break; +#endif + default: + error("Unknown DAC channel"); + break; + } + + // Configure GPIO + pinmap_pinout(pin, PinMap_DAC); + + // Save the channel for future use + obj->pin = pin; + + obj->handle.Instance = DAC; + obj->handle.State = HAL_DAC_STATE_RESET; + + if (HAL_DAC_Init(&obj->handle) != HAL_OK ) { + error("HAL_DAC_Init failed"); + } + + // Enable DAC clock + __DAC_CLK_ENABLE(); + + // Configure DAC + sConfig.DAC_Trigger = DAC_TRIGGER_NONE; + sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + + if (pin == PA_4) { + pa4_used = 1; + } else { // PA_5 + pa5_used = 1; + } + + if (HAL_DAC_ConfigChannel(&obj->handle, &sConfig, obj->channel) != HAL_OK) { + error("Cannot configure DAC channel\n"); + } + + analogout_write_u16(obj, 0); +} + +void analogout_free(dac_t *obj) { + // Reset DAC and disable clock + if (obj->pin == PA_4) pa4_used = 0; + if (obj->pin == PA_5) pa5_used = 0; + if ((pa4_used == 0) && (pa5_used == 0)) { + __DAC_FORCE_RESET(); + __DAC_RELEASE_RESET(); + __DAC_CLK_DISABLE(); + } + + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +#endif // DEVICE_ANALOGOUT diff --git a/pool/shard006/C/0118244_sockex2_user.c b/pool/shard006/C/0118244_sockex2_user.c new file mode 100644 index 0000000000000000000000000000000000000000..0e0207c9084130c362b600f6b8cd453d2541c4dc --- /dev/null +++ b/pool/shard006/C/0118244_sockex2_user.c @@ -0,0 +1,53 @@ +#include +#include +#include +#include "libbpf.h" +#include "bpf_load.h" +#include "sock_example.h" +#include +#include +#include + +struct pair { + __u64 packets; + __u64 bytes; +}; + +int main(int ac, char **argv) +{ + struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY}; + char filename[256]; + FILE *f; + int i, sock; + + snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); + setrlimit(RLIMIT_MEMLOCK, &r); + + if (load_bpf_file(filename)) { + printf("%s", bpf_log_buf); + return 1; + } + + sock = open_raw_sock("lo"); + + assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, prog_fd, + sizeof(prog_fd[0])) == 0); + + f = popen("ping -c5 localhost", "r"); + (void) f; + + for (i = 0; i < 5; i++) { + int key = 0, next_key; + struct pair value; + + while (bpf_map_get_next_key(map_fd[0], &key, &next_key) == 0) { + bpf_map_lookup_elem(map_fd[0], &next_key, &value); + printf("ip %s bytes %lld packets %lld\n", + inet_ntoa((struct in_addr){htonl(next_key)}), + value.bytes, value.packets); + key = next_key; + } + sleep(1); + } + return 0; +} diff --git a/pool/shard006/C/0118247_tlog10.c b/pool/shard006/C/0118247_tlog10.c new file mode 100644 index 0000000000000000000000000000000000000000..be95dbbeb0032b65f0a98d5ef00d84736d78844a --- /dev/null +++ b/pool/shard006/C/0118247_tlog10.c @@ -0,0 +1,119 @@ +/* Test file for mpfr_log10. + +Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc. +Contributed by the AriC and Caramel projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR 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 3 of the License, or (at your +option) any later version. + +The GNU MPFR 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 MPFR Library; see the file COPYING.LESSER. If not, see +http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#include "mpfr-test.h" + +#ifdef CHECK_EXTERNAL +static int +test_log10 (mpfr_ptr a, mpfr_srcptr b, mpfr_rnd_t rnd_mode) +{ + int res; + int ok = rnd_mode == MPFR_RNDN && mpfr_number_p (b) && mpfr_get_prec (a)>=53; + if (ok) + { + mpfr_print_raw (b); + } + res = mpfr_log10 (a, b, rnd_mode); + if (ok) + { + printf (" "); + mpfr_print_raw (a); + printf ("\n"); + } + return res; +} +#else +#define test_log10 mpfr_log10 +#endif + +#define TEST_FUNCTION test_log10 +#define TEST_RANDOM_POS 8 +#include "tgeneric.c" + +int +main (int argc, char *argv[]) +{ + mpfr_t x, y; + unsigned int n; + int inex; + + tests_start_mpfr (); + + test_generic (2, 100, 20); + + mpfr_init2 (x, 53); + mpfr_init2 (y, 53); + + /* check NaN */ + mpfr_set_nan (x); + inex = test_log10 (y, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_nan_p (y) && inex == 0); + + /* check Inf */ + mpfr_set_inf (x, -1); + inex = test_log10 (y, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_nan_p (y) && inex == 0); + + mpfr_set_inf (x, 1); + inex = test_log10 (y, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_inf_p (y) && mpfr_sgn (y) > 0 && inex == 0); + + mpfr_set_ui (x, 0, MPFR_RNDN); + inex = test_log10 (x, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_inf_p (x) && mpfr_sgn (x) < 0 && inex == 0); + mpfr_set_ui (x, 0, MPFR_RNDN); + mpfr_neg (x, x, MPFR_RNDN); + inex = test_log10 (x, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_inf_p (x) && mpfr_sgn (x) < 0 && inex == 0); + + /* check negative argument */ + mpfr_set_si (x, -1, MPFR_RNDN); + inex = test_log10 (y, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_nan_p (y) && inex == 0); + + /* check log10(1) = 0 */ + mpfr_set_ui (x, 1, MPFR_RNDN); + inex = test_log10 (y, x, MPFR_RNDN); + MPFR_ASSERTN (mpfr_cmp_ui (y, 0) == 0 && MPFR_IS_POS (y) && inex == 0); + + /* check log10(10^n)=n */ + mpfr_set_ui (x, 1, MPFR_RNDN); + for (n = 1; n <= 15; n++) + { + mpfr_mul_ui (x, x, 10, MPFR_RNDN); /* x = 10^n */ + inex = test_log10 (y, x, MPFR_RNDN); + if (mpfr_cmp_ui (y, n)) + { + printf ("log10(10^n) <> n for n=%u\n", n); + exit (1); + } + MPFR_ASSERTN (inex == 0); + } + + mpfr_clear (x); + mpfr_clear (y); + + data_check ("data/log10", mpfr_log10, "mpfr_log10"); + + tests_end_mpfr (); + return 0; +} diff --git a/pool/shard006/C/0118248_raspicam.c b/pool/shard006/C/0118248_raspicam.c new file mode 100644 index 0000000000000000000000000000000000000000..d93609a1fa489e79f40cd42a6c9ec1009b1973a6 --- /dev/null +++ b/pool/shard006/C/0118248_raspicam.c @@ -0,0 +1,235 @@ +/***************************************************************************/ +/* */ +/* raspicam.c - mruby testing */ +/* Copyright (C) 2015 Paolo Bosetti, */ +/* paolo[dot]bosetti[at]unitn.it */ +/* Department of Industrial Engineering, University of Trento */ +/* */ +/* This library is free software. You can redistribute it and/or */ +/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */ +/* */ +/* 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 */ +/* Artistic License 2.0 for more details. */ +/* */ +/* See the file LICENSE */ +/* */ +/***************************************************************************/ + +#include +#include +#include +#include +#include + +#include "mruby.h" +#include "mruby/variable.h" +#include "mruby/string.h" +#include "mruby/data.h" +#include "mruby/class.h" +#include "mruby/value.h" +#include "mruby/array.h" +#include "mruby/numeric.h" + +#include "laserCam.h" + +//#define MARK_LINE printf("*** FILE: %s - LINE: %d\n", __FILE__, __LINE__) +#define MARK_LINE +#define E_RASPICAM_ERROR (mrb_class_get(mrb, "RaspicamError")) + +// Struct holding data: +typedef struct { CRaspicamLaser camera; } raspicam_data_s; + +// Garbage collector handler, for raspicam_data struct +// if raspicam_data contains other dynamic data, free it too! +// Check it with GC.start +static void raspicam_data_destructor(mrb_state *mrb, void *p_) { + raspicam_data_s *pd = (raspicam_data_s *)p_; + delCRaspicamLaser(pd->camera); + free(pd); + // or simply: + // mrb_free(mrb, pd); +}; + +// Creating data type and reference for GC, in a const struct +const struct mrb_data_type raspicam_data_type = {"raspicam_data", + raspicam_data_destructor}; + +// Utility function for getting the struct out of the wrapping IV @data +static void mrb_raspicam_get_data(mrb_state *mrb, mrb_value self, + raspicam_data_s **data) { + mrb_value data_value; + data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data")); + + // Loading data from data_value into p_data: + Data_Get_Struct(mrb, data_value, &raspicam_data_type, *data); + if (!*data) + mrb_raise(mrb, E_RUNTIME_ERROR, "Could not access @data"); +} + +// Data Initializer C function (not exposed!) +static void mrb_raspicam_init(mrb_state *mrb, mrb_value self, mrb_int w, + mrb_int h) { + mrb_value data_value; // this IV holds the data + raspicam_data_s *p_data; // pointer to the C struct + data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, "@data")); + + // if @data already exists, free its content: + if (!mrb_nil_p(data_value)) { + Data_Get_Struct(mrb, data_value, &raspicam_data_type, p_data); + free(p_data); + } + // Allocate and zero-out the data struct: + p_data = (raspicam_data_s *)malloc(sizeof(raspicam_data_s)); + + // memset(p_data, 0, sizeof(raspicam_data_s)); + if (!p_data) + mrb_raise(mrb, E_RUNTIME_ERROR, "Could not allocate @data"); + + // Wrap struct into @data: + mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@data"), // set @data + mrb_obj_value( // with value hold in struct + Data_Wrap_Struct(mrb, mrb->object_class, &raspicam_data_type, + p_data))); + + // Now set values into struct: + p_data->camera = newCRaspicamLaser(w, h); +} + +static mrb_value mrb_raspicam_initialize(mrb_state *mrb, mrb_value self) { + mrb_int width, height; + mrb_int nargs = mrb_get_args(mrb, "|ii", &width, &height); + if (nargs == 0) { + width = 640; + height = 480; + } else if (nargs == 1) { + height = (mrb_int)((width / 640.0) * 480.0); + } + mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@width"), mrb_fixnum_value(width)); + mrb_iv_set(mrb, self, mrb_intern_lit(mrb, "@height"), mrb_fixnum_value(height)); + // Call strcut initializer: + mrb_raspicam_init(mrb, self, width, height); + return mrb_nil_value(); +} + +static mrb_value mrb_raspicam_open(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + if (0 != CRaspicamLaserOpenCamera(p_data->camera)) + mrb_raise(mrb, E_RUNTIME_ERROR, "Could not open camera!"); + return self; +} + +static mrb_value mrb_raspicam_close(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + CRaspicamLaserCloseCamera(p_data->camera); + return mrb_nil_value(); +} + +static mrb_value mrb_raspicam_red_thr(mrb_state *mrb, mrb_value self) { + unsigned int thr; + raspicam_data_s *p_data = NULL; + mrb_raspicam_get_data(mrb, self, &p_data); + + // raspicam with p_data content: + thr = CRaspicamLaserRedThreshold(p_data->camera); + return mrb_fixnum_value((mrb_int)thr); +} + +static mrb_value mrb_raspicam_set_red_thr(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + mrb_int val; + mrb_get_args(mrb, "i", &val); + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + + // raspicam with p_data content: + CRaspicamLaserSetRedThreshold(p_data->camera, val); + return mrb_fixnum_value(val); +} + +static mrb_value mrb_raspicam_set_rect(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + mrb_int x0, y0, x1, y1; + mrb_get_args(mrb, "iiii", &x0, &y0, &x1, &y1); + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + + // raspicam with p_data content: + CRaspicamLaserSetRect(p_data->camera, x0, y0, x1, y1); + return self; +} + +static mrb_value mrb_raspicam_reset_rect(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + + // raspicam with p_data content: + CRaspicamLaserResetRect(p_data->camera); + return self; +} + +static mrb_value mrb_raspicam_pos(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + mrb_value ary; + int x = 0, y = 0, res; + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + + // raspicam with p_data content: + ary = mrb_ary_new_capa(mrb, 2); + res = CRaspicamLaserPosition(p_data->camera, &x, &y); + if (0 != res) + mrb_raise(mrb, E_RASPICAM_ERROR, "Could not get position (device closed?)"); + mrb_ary_set(mrb, ary, 0, mrb_fixnum_value(x)); + mrb_ary_set(mrb, ary, 1, mrb_fixnum_value(y)); + return ary; +} + +static mrb_value mrb_raspicam_save(mrb_state *mrb, mrb_value self) { + raspicam_data_s *p_data = NULL; + mrb_value name; + mrb_int slp = 0, nargs; + nargs = mrb_get_args(mrb, "S|i", &name, &slp); + if (nargs == 1) + slp = 0; + // call utility for unwrapping @data into p_data: + mrb_raspicam_get_data(mrb, self, &p_data); + + // raspicam with p_data content: + if (0 != CRaspicamLaserSaveFrame(p_data->camera, + mrb_string_value_cstr(mrb, &name), slp)) + mrb_raise(mrb, E_RASPICAM_ERROR, "Could not save image (device closed?"); + return name; +} + +void mrb_mruby_raspicam_gem_init(mrb_state *mrb) { + struct RClass *raspicam; + mrb_define_class(mrb, "RaspicamError", mrb_class_get(mrb, "Exception")); + raspicam = mrb_define_class(mrb, "RaspiCam", mrb->object_class); + + mrb_define_method(mrb, raspicam, "initialize", mrb_raspicam_initialize, + MRB_ARGS_OPT(2)); + mrb_define_method(mrb, raspicam, "open", mrb_raspicam_open, MRB_ARGS_NONE()); + mrb_define_method(mrb, raspicam, "close", mrb_raspicam_close, + MRB_ARGS_NONE()); + mrb_define_method(mrb, raspicam, "red_threshold", mrb_raspicam_red_thr, + MRB_ARGS_NONE()); + mrb_define_method(mrb, raspicam, "red_threshold=", mrb_raspicam_set_red_thr, + MRB_ARGS_REQ(1)); + mrb_define_method(mrb, raspicam, "set_rect", mrb_raspicam_set_rect, + MRB_ARGS_REQ(4)); + mrb_define_method(mrb, raspicam, "reset_rect", mrb_raspicam_reset_rect, + MRB_ARGS_NONE()); + mrb_define_method(mrb, raspicam, "position", mrb_raspicam_pos, + MRB_ARGS_NONE()); + mrb_define_method(mrb, raspicam, "save_image", mrb_raspicam_save, + MRB_ARGS_REQ(1) & MRB_ARGS_OPT(1)); +} + +void mrb_mruby_raspicam_gem_final(mrb_state *mrb) {} diff --git a/pool/shard006/C/0118259_ex1.c b/pool/shard006/C/0118259_ex1.c new file mode 100644 index 0000000000000000000000000000000000000000..3eb70c8da5d5b5ee5135ae1b82af4b03a845c281 --- /dev/null +++ b/pool/shard006/C/0118259_ex1.c @@ -0,0 +1,76 @@ +/* + C socket server example +*/ + +#include +#include //strlen +#include +#include //inet_addr +#include //write +int main(int argc , char *argv[]) +{ + int socket_desc , client_sock , c , read_size; + struct sockaddr_in server , client; + char client_message[4]; + + //Create socket + socket_desc = socket(AF_INET , SOCK_STREAM , 0); + if (socket_desc == -1) + { + printf("Could not create socket"); + } + puts("Socket created"); + + //Prepare the sockaddr_in structure + server.sin_family = AF_INET; + server.sin_addr.s_addr = INADDR_ANY; + server.sin_port = htons( 8888 ); + + //Bind + if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) + { + //print the error message + perror("bind failed. Error"); + return 1; + } + puts("bind done"); + + //Listen + listen(socket_desc , 3); + + //Accept and incoming connection + puts("Waiting for incoming connections..."); + c = sizeof(struct sockaddr_in); + + //accept connection from an incoming client + client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); + if (client_sock < 0) + { + perror("accept failed"); + return 1; + } + puts("Connection accepted"); + + //Receive a message from client + while( (read_size = recv(client_sock , client_message , 4 , 0)) > 0 ) + { + //Send the message back to client + int number = atoi(client_message); + number += 1; + sprintf(client_message,"%d", number); + + write(client_sock , client_message, 4); + } + + if(read_size == 0) + { + puts("Client disconnected"); + fflush(stdout); + } + else if(read_size == -1) + { + perror("recv failed"); + } + + return 0; +} diff --git a/pool/shard006/C/0118260_apm.c b/pool/shard006/C/0118260_apm.c new file mode 100644 index 0000000000000000000000000000000000000000..f800580db7f49e37b71fc9bced18aa5d3c68b3dc --- /dev/null +++ b/pool/shard006/C/0118260_apm.c @@ -0,0 +1,93 @@ +/* + KSysGuard, the KDE System Guard + + Copyright (c) 2001 Tobias Koenig + + This program is free software; you can redistribute it and/or + modify it under the terms of version 2 of the GNU General Public + License as published by the Free Software Foundation. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +*/ + +#ifdef __i386__ + +#include +#include +#include +#include + +#include "Command.h" +#include "apm.h" +#include "ksysguardd.h" + +static int ApmFD, BattFill, BattTime; + +#define APMDEV "/dev/apm" + +/* +================================ public part ================================= +*/ + +void initApm(struct SensorModul *sm) +{ + if((ApmFD = open(APMDEV, O_RDONLY)) < 0) + return; + + if(updateApm() < 0) + return; + + registerMonitor("apm/batterycharge", "integer", printApmBatFill, printApmBatFillInfo, sm); + registerMonitor("apm/remainingtime", "integer", printApmBatTime, printApmBatTimeInfo, sm); +} + +void exitApm(void) +{ + removeMonitor("apm/batterycharge"); + removeMonitor("apm/remainingtime"); + + close(ApmFD); +} + +int updateApm(void) +{ + struct apm_info info; + int retval; + + retval = ioctl(ApmFD, APMIO_GETINFO, &info); + + BattFill = info.ai_batt_life; + BattTime = info.ai_batt_time; + + return retval; +} + +void printApmBatFill(const char *c) +{ + fprintf(CurrentClient, "%d\n", BattFill); +} + +void printApmBatFillInfo(const char *c) +{ + fprintf(CurrentClient, "Battery charge\t0\t100\t%%\n"); +} + +void printApmBatTime(const char *c) +{ + fprintf(CurrentClient, "%d\n", BattTime); +} + +void printApmBatTimeInfo(const char *c) +{ + fprintf(CurrentClient, "Remaining battery time\t0\t0\tmin\n"); +} + +#endif diff --git a/pool/shard006/C/0118262_active_window_win.c b/pool/shard006/C/0118262_active_window_win.c new file mode 100644 index 0000000000000000000000000000000000000000..17a148646c415e6e269bb018f2e1609f662d48d8 --- /dev/null +++ b/pool/shard006/C/0118262_active_window_win.c @@ -0,0 +1,15 @@ +#include +#include "region_picker/errors.h" +#include "region_picker/active_window.h" + +int update_region_from_active_window(ShotRegion *region) +{ + RECT rect; + HWND hwnd = GetForegroundWindow(); + GetWindowRect(hwnd, &rect); + region->x = rect.left; + region->y = rect.top; + region->width = rect.right - rect.left; + region->height = rect.bottom - rect.top; + return 0; +} diff --git a/pool/shard006/C/0118263_plugin_idlejitter.c b/pool/shard006/C/0118263_plugin_idlejitter.c new file mode 100644 index 0000000000000000000000000000000000000000..c59541ecba4b71206b607352b1281515e12d613e --- /dev/null +++ b/pool/shard006/C/0118263_plugin_idlejitter.c @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "plugin_idlejitter.h" + +#define CPU_IDLEJITTER_SLEEP_TIME_MS 20 + +static void cpuidlejitter_main_cleanup(void *ptr) { + struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr; + static_thread->enabled = NETDATA_MAIN_THREAD_EXITING; + + info("cleaning up..."); + + static_thread->enabled = NETDATA_MAIN_THREAD_EXITED; +} + +void *cpuidlejitter_main(void *ptr) { + netdata_thread_cleanup_push(cpuidlejitter_main_cleanup, ptr); + + usec_t sleep_ut = config_get_number("plugin:idlejitter", "loop time in ms", CPU_IDLEJITTER_SLEEP_TIME_MS) * USEC_PER_MS; + if(sleep_ut <= 0) { + config_set_number("plugin:idlejitter", "loop time in ms", CPU_IDLEJITTER_SLEEP_TIME_MS); + sleep_ut = CPU_IDLEJITTER_SLEEP_TIME_MS * USEC_PER_MS; + } + + RRDSET *st = rrdset_create_localhost( + "system" + , "idlejitter" + , NULL + , "idlejitter" + , NULL + , "CPU Idle Jitter" + , "microseconds lost/s" + , "idlejitter.plugin" + , NULL + , NETDATA_CHART_PRIO_SYSTEM_IDLEJITTER + , localhost->rrd_update_every + , RRDSET_TYPE_AREA + ); + RRDDIM *rd_min = rrddim_add(st, "min", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE); + RRDDIM *rd_max = rrddim_add(st, "max", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE); + RRDDIM *rd_avg = rrddim_add(st, "average", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE); + + usec_t update_every_ut = localhost->rrd_update_every * USEC_PER_SEC; + struct timeval before, after; + unsigned long long counter; + + for(counter = 0; 1 ;counter++) { + int iterations = 0; + usec_t error_total = 0, + error_min = 0, + error_max = 0, + elapsed = 0; + + if(netdata_exit) break; + + while(elapsed < update_every_ut) { + now_monotonic_high_precision_timeval(&before); + sleep_usec(sleep_ut); + now_monotonic_high_precision_timeval(&after); + + usec_t dt = dt_usec(&after, &before); + elapsed += dt; + + usec_t error = dt - sleep_ut; + error_total += error; + + if(unlikely(!iterations)) + error_min = error; + else if(error < error_min) + error_min = error; + + if(error > error_max) + error_max = error; + + iterations++; + } + + if(netdata_exit) break; + + if(iterations) { + if (likely(counter)) rrdset_next(st); + rrddim_set_by_pointer(st, rd_min, error_min); + rrddim_set_by_pointer(st, rd_max, error_max); + rrddim_set_by_pointer(st, rd_avg, error_total / iterations); + rrdset_done(st); + } + } + + netdata_thread_cleanup_pop(1); + return NULL; +} + diff --git a/pool/shard006/C/0118266_mail-copy.c b/pool/shard006/C/0118266_mail-copy.c new file mode 100644 index 0000000000000000000000000000000000000000..aea30e15923dc41cdfb5be4530bf0f57ca5fa2ac --- /dev/null +++ b/pool/shard006/C/0118266_mail-copy.c @@ -0,0 +1,127 @@ +/* Copyright (c) 2004-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "istream.h" +#include "mail-storage-private.h" +#include "mail-copy.h" + +static void +mail_copy_set_failed(struct mail_save_context *ctx, struct mail *mail, + const char *func) +{ + const char *errstr; + enum mail_error error; + + if (ctx->transaction->box->storage == mail->box->storage) + return; + + errstr = mail_storage_get_last_error(mail->box->storage, &error); + mail_storage_set_error(ctx->transaction->box->storage, error, + t_strdup_printf("%s (%s)", errstr, func)); +} + +int mail_save_copy_default_metadata(struct mail_save_context *ctx, + struct mail *mail) +{ + const char *from_envelope, *guid; + time_t received_date; + + if (ctx->data.received_date == (time_t)-1) { + if (mail_get_received_date(mail, &received_date) < 0) { + mail_copy_set_failed(ctx, mail, "received-date"); + return -1; + } + mailbox_save_set_received_date(ctx, received_date, 0); + } + if (ctx->data.from_envelope == NULL) { + if (mail_get_special(mail, MAIL_FETCH_FROM_ENVELOPE, + &from_envelope) < 0) { + mail_copy_set_failed(ctx, mail, "from-envelope"); + return -1; + } + if (*from_envelope != '\0') + mailbox_save_set_from_envelope(ctx, from_envelope); + } + if (ctx->data.guid == NULL) { + if (mail_get_special(mail, MAIL_FETCH_GUID, &guid) < 0) { + mail_copy_set_failed(ctx, mail, "guid"); + return -1; + } + if (*guid != '\0') + mailbox_save_set_guid(ctx, guid); + } + return 0; +} + +static int +mail_storage_try_copy(struct mail_save_context **_ctx, struct mail *mail) +{ + struct mail_save_context *ctx = *_ctx; + struct mail_private *pmail = (struct mail_private *)mail; + struct istream *input; + + ctx->copying_via_save = TRUE; + + /* we need to open the file in any case. caching metadata is unlikely + to help anything. */ + pmail->v.set_uid_cache_updates(mail, TRUE); + + if (mail_get_stream(mail, NULL, NULL, &input) < 0) { + mail_copy_set_failed(ctx, mail, "stream"); + return -1; + } + if (mail_save_copy_default_metadata(ctx, mail) < 0) + return -1; + + if (mailbox_save_begin(_ctx, input) < 0) + return -1; + + do { + if (mailbox_save_continue(ctx) < 0) + break; + } while (i_stream_read(input) != -1); + + if (input->stream_errno != 0) { + mail_storage_set_critical(ctx->transaction->box->storage, + "copy: i_stream_read() failed: %m"); + return -1; + } + return 0; +} + +int mail_storage_copy(struct mail_save_context *ctx, struct mail *mail) +{ + if (ctx->data.keywords != NULL) { + /* keywords gets unreferenced twice: first in + mailbox_save_cancel()/_finish() and second time in + mailbox_copy(). */ + mailbox_keywords_ref(ctx->data.keywords); + } + + if (mail_storage_try_copy(&ctx, mail) < 0) { + if (ctx != NULL) + mailbox_save_cancel(&ctx); + return -1; + } + return mailbox_save_finish(&ctx); +} + +bool mail_storage_copy_can_use_hardlink(struct mailbox *src, + struct mailbox *dest) +{ + const struct mailbox_permissions *src_perm = + mailbox_get_permissions(src); + const struct mailbox_permissions *dest_perm = + mailbox_get_permissions(dest); + + if (src_perm->file_uid != dest_perm->file_uid) { + /* if we don't have read permissions, we can't hard link + (basically we'll catch 0600 files here) */ + if ((src_perm->file_create_mode & 0022) == 0) + return FALSE; + } + + return src_perm->file_create_mode == dest_perm->file_create_mode && + src_perm->file_create_gid == dest_perm->file_create_gid && + !dest->disable_reflink_copy_to; +} diff --git a/pool/shard006/C/0118269_synotify.c b/pool/shard006/C/0118269_synotify.c new file mode 100644 index 0000000000000000000000000000000000000000..a776b616005d0a7d49596b38c5560727271a1dac --- /dev/null +++ b/pool/shard006/C/0118269_synotify.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include +#include +#include /* UINT_MAX */ +#include +#include +#include +#include + +static bool should_merge(struct fsnotify_event *old, struct fsnotify_event *new) +{ + pr_debug("%s: old=%p, mask=%x, new=%p, mask=%x\n", __func__, old, old->mask, new, new->mask); + if (old->data_type == FSNOTIFY_EVENT_NONE && new->data_type ==FSNOTIFY_EVENT_NONE) { + return (old->mask & FS_Q_OVERFLOW) && (new->mask & FS_Q_OVERFLOW); + } + if (old->mask != new->mask) return false; + + if ( (new->mask & (FS_ATTRIB | FS_ACCESS | FS_MODIFY)) + && (old->path.mnt == new->path.mnt) + && (old->path.dentry == new->path.dentry)) + return true; + return false; +} + +/* and the list better be locked by something too! */ +static struct fsnotify_event *synotify_merge(struct list_head *list, + struct fsnotify_event *event) +{ + struct fsnotify_event_holder *last_holder; + struct fsnotify_event *last_event; + pr_debug("%s: list=%p event=%p, mask=%x\n", __func__, list, event, event->mask); + + spin_lock(&event->lock); + + last_holder = list_entry(list->prev, struct fsnotify_event_holder, event_list); + last_event = last_holder->event; + + if (should_merge(last_event, event)) { + fsnotify_get_event(last_event); + } else { + last_event = NULL; + } + spin_unlock(&event->lock); + + return last_event; +} + +static int synotify_handle_event(struct fsnotify_group *group, + struct fsnotify_mark *inode_mark, + struct fsnotify_mark *synotify_mark, + struct fsnotify_event *event) +{ + int ret = 0; + struct fsnotify_event *notify_event = NULL; + + pr_debug("%s: group=%p event=%p, mnt=%p, mask=%x\n", __func__, group, event, event->path.mnt, event->mask); + // to prevent event dependecy, we should have much clever way to do merge + notify_event = fsnotify_add_notify_event(group, event, NULL, synotify_merge); + if (IS_ERR(notify_event)) + return PTR_ERR(notify_event); + + if (notify_event) + fsnotify_put_event(notify_event); + + return ret; +} + +static bool synotify_should_send_event(struct fsnotify_group *group, + struct inode *to_tell, + struct fsnotify_mark *inode_mark, + struct fsnotify_mark *vfsmnt_mark, + __u32 event_mask, void *data, int data_type) +{ + __u32 marks_mask; + + pr_debug("%s: group=%p to_tell=%p inode_mark=%p vfsmnt_mark=%p " + "mask=%x data=%p data_type=%d\n", __func__, group, to_tell, + inode_mark, vfsmnt_mark, event_mask, data, data_type); + + /* if we don't have enough info to send an event to userspace say no */ + if (data_type != FSNOTIFY_EVENT_SYNO && data_type != FSNOTIFY_EVENT_PATH) + return false; + + if (vfsmnt_mark) { + marks_mask = vfsmnt_mark->mask; + } else { + BUG(); + } + + if (event_mask & marks_mask) + return true; + + return false; +} + +static void synotify_free_group_priv(struct fsnotify_group *group) +{ + struct user_struct *user; + + user = group->synotify_data.user; + atomic_dec(&user->synotify_instances); + free_uid(user); +} + +const struct fsnotify_ops synotify_fsnotify_ops = { + .handle_event = synotify_handle_event, + .should_send_event = synotify_should_send_event, + .free_group_priv = synotify_free_group_priv, + .free_event_priv = NULL, + .freeing_mark = NULL, +}; diff --git a/pool/shard006/C/0118272_read_v5d_i.c b/pool/shard006/C/0118272_read_v5d_i.c new file mode 100644 index 0000000000000000000000000000000000000000..123390c07460f4204fa8dc803af18a1deba48d0c --- /dev/null +++ b/pool/shard006/C/0118272_read_v5d_i.c @@ -0,0 +1,163 @@ +/* v5d_file.c */ + +/* + * Vis5D system for visualizing five dimensional gridded data sets. + * Copyright (C) 1990 - 2000 Bill Hibbard, Johan Kellum, Brian Paul, + * Dave Santek, and Andre Battaiola. + * + * 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. + * + * As a special exception to the terms of the GNU General Public + * License, you are permitted to link Vis5D with (and distribute the + * resulting source and executables) the LUI library (copyright by + * Stellar Computer Inc. and licensed for distribution with Vis5D), + * the McIDAS library, and/or the NetCDF library, where those + * libraries are governed by the terms of their own licenses. + * + * 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 "../config.h" + + +/* + * Functions for reading Vis5D .v5d files + */ + + +#include +#include +#include +#include "file_i.h" +#include "grid_i.h" +#include "misc_i.h" +#include "proj_i.h" +#include "projlist_i.h" +#include "v5d.h" +/* 01Feb06 Phil McDonald */ +#include "memory.h" +/* end PM */ + + + +/* + * Scan the named file, createing a grid_info struct for each grid. Store + * the grid_info structs in the grid data base. + * Input: name - name of v5d file. + * db - the grid data base + * Return: number of grids found in the file + */ +int get_v5d_info( char *name, struct grid_db *db ) +{ + struct grid_info *info; + struct projection *proj; + int time, var; + int grids = 0; + v5dstruct *v; + int lowlev[MAXVARS]; + + /* Open the file */ + v = v5dOpenFile( name, NULL ); + if (!v) { + return 0; + } + + /* All grids use the same map projection */ + proj = new_projection( db, v->Projection, v->Nr, v->Nc, v->ProjArgs ); + + for (var=0;varNumVars;var++) { +#if V5D_VERSION >= 42 + lowlev[var] = v->LowLev[var]; +#else + lowlev[var] = 0; +#endif + } + + /* Read the description of each 3-D grid */ + for (time=0; timeNumTimes; time++) { + for (var=0; varNumVars; var++) { + + info = alloc_grid_info(); +/* 01Feb06 Phil McDonald */ + info->FileName = TMP_STRDUP (name); +/* end PM */ + info->Format = FILE_V5D; + info->TimeStep = time; + info->VarNum = var; + + info->Nr = v->Nr; + info->Nc = v->Nc; + info->Nl = v->Nl[var]; + + info->DateStamp = v->DateStamp[time]; + info->TimeStamp = v->TimeStamp[time]; +/* 01Feb06 Phil McDonald */ + info->VarName = TMP_STRDUP (v->VarName[var]); + if (v->Units[var][0]) { + info->Units = TMP_STRDUP (v->Units[var]); + } +/* end PM */ + + info->Proj = proj; + info->Vcs = new_vcs( db, v->VerticalSystem, v->Nl[var], + lowlev[var], v->VertArgs ); + + append_grid( info, db ); + grids++; + } + } + + return grids; +} + + + + +/* + * Get the grid data described by g. + * Input: g - pointer to a grid_info structure. It tells us which grid + * in which file is needed. + * Return: pointer to grid data (can be free()'d when finished) + * OR return NULL if there's an error. + */ +float *get_v5d_data( struct grid_info *g ) +{ + v5dstruct *v; + float *data; + int count; + + v = v5dOpenFile( g->FileName, NULL ); + if (!v) { + printf("error in get_v5d_data\n"); + return NULL; + } + + /* allocate buffer */ + count = g->Nr * g->Nc * g->Nl; +/* 01Feb06 Phil McDonald */ + data = (float *) TMP_MALLOC (count * sizeof (float)); +/* end PM */ + if (!data) { + printf("Error: out of memory in get_v5d_data\n"); + return NULL; + } + + if (!v5dReadGrid( v, g->TimeStep, g->VarNum, data )) { + return NULL; + } + + v5dCloseFile( v ); + return data; +} + diff --git a/pool/shard006/C/0118274_mali_kbase_security.c b/pool/shard006/C/0118274_mali_kbase_security.c new file mode 100644 index 0000000000000000000000000000000000000000..178fc413ebda0a2483d8006ce356a18c15714be8 --- /dev/null +++ b/pool/shard006/C/0118274_mali_kbase_security.c @@ -0,0 +1,76 @@ +/* + * + * (C) COPYRIGHT 2011 ARM Limited. All rights reserved. + * + * This program is free software and is provided to you under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. + * + * A copy of the licence is included with the program, and can also be obtained from Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + + + +/** + * @file mali_kbase_security.c + * Base kernel security capability API + */ + +#include +#include + +/** + * kbase_security_has_capability - see mali_kbase_caps.h for description. + */ + +mali_bool kbase_security_has_capability(kbase_context *kctx, kbase_security_capability cap, u32 flags) +{ + /* Assume failure */ + mali_bool access_allowed = MALI_FALSE; + mali_bool audit = (KBASE_SEC_FLAG_AUDIT & flags)? MALI_TRUE : MALI_FALSE; + + OSK_ASSERT(NULL != kctx); + CSTD_UNUSED(kctx); + + /* Detect unsupported flags */ + OSK_ASSERT(((~KBASE_SEC_FLAG_MASK) & flags) == 0); + + /* Determine if access is allowed for the given cap */ + switch(cap) + { + case KBASE_SEC_MODIFY_PRIORITY: +#if KBASE_HWCNT_DUMP_BYPASS_ROOT + access_allowed = TRUE; +#else + if (osk_is_privileged() == MALI_TRUE) + { + access_allowed = TRUE; + } +#endif + break; + case KBASE_SEC_INSTR_HW_COUNTERS_COLLECT: + /* Access is granted only if the caller is privileged */ +#if KBASE_HWCNT_DUMP_BYPASS_ROOT + access_allowed = TRUE; +#else + if (osk_is_privileged() == MALI_TRUE) + { + access_allowed = TRUE; + } +#endif + break; + } + + /* Report problem if requested */ + if(MALI_FALSE == access_allowed) + { + if(MALI_FALSE != audit) + { + OSK_PRINT_WARN(OSK_BASE_CORE, "Security capability failure: %d, %p", cap, (void *)kctx); + } + } + + return access_allowed; +} + diff --git a/pool/shard006/C/0118280_suite.c b/pool/shard006/C/0118280_suite.c new file mode 100644 index 0000000000000000000000000000000000000000..b843b96e7e032a30aeb5c969d30aa6dd71e01743 --- /dev/null +++ b/pool/shard006/C/0118280_suite.c @@ -0,0 +1,59 @@ +#include + +#include /* free() */ +#include /* strdup() */ + +#include "../../src/cfg/config.h" +#include "../../src/undo.h" + +static int exec_func(OPS op, void *data, const char *src, const char *dst); +static void init_undo_list_for_tests(perform_func exec_func, + const int *max_levels); +static int op_avail(OPS op); + +DEFINE_SUITE(); + +SETUP() +{ + static int undo_levels = 10; + + init_undo_list_for_tests(&exec_func, &undo_levels); + + cfg.use_system_calls = 1; + cfg.slow_fs_list = strdup(""); + cfg.delete_prg = strdup(""); + + lwin.list_rows = 0; + lwin.dir_entry = NULL; + rwin.list_rows = 0; + rwin.dir_entry = NULL; +} + +TEARDOWN() +{ + free(cfg.slow_fs_list); + free(cfg.delete_prg); + + reset_undo_list(); +} + +static int +exec_func(OPS op, void *data, const char *src, const char *dst) +{ + return 0; +} + +static void +init_undo_list_for_tests(perform_func exec_func, const int *max_levels) +{ + init_undo_list(exec_func, &op_avail, NULL, max_levels); +} + +static int +op_avail(OPS op) +{ + return op == OP_MOVE; +} + +/* vim: set tabstop=2 softtabstop=2 shiftwidth=2 noexpandtab cinoptions-=(0 : */ +/* vim: set cinoptions+=t0 filetype=c : */ diff --git a/pool/shard006/C/0118281_libcelt_dec.c b/pool/shard006/C/0118281_libcelt_dec.c new file mode 100644 index 0000000000000000000000000000000000000000..878e4cc673cb46b2a4fbcfcd8f5841a26973dc3e --- /dev/null +++ b/pool/shard006/C/0118281_libcelt_dec.c @@ -0,0 +1,140 @@ +/* + * Xiph CELT decoder using libcelt + * Copyright (c) 2011 Nicolas George + * + * 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 +#include +#include "avcodec.h" +#include "internal.h" +#include "libavutil/intreadwrite.h" + +struct libcelt_context { + CELTMode *mode; + CELTDecoder *dec; + int discard; +}; + +static int ff_celt_error_to_averror(int err) +{ + switch (err) { + case CELT_BAD_ARG: return AVERROR(EINVAL); +#ifdef CELT_BUFFER_TOO_SMALL + case CELT_BUFFER_TOO_SMALL: return AVERROR(ENOBUFS); +#endif + case CELT_INTERNAL_ERROR: return AVERROR(EFAULT); + case CELT_CORRUPTED_DATA: return AVERROR_INVALIDDATA; + case CELT_UNIMPLEMENTED: return AVERROR(ENOSYS); +#ifdef ENOTRECOVERABLE + case CELT_INVALID_STATE: return AVERROR(ENOTRECOVERABLE); +#endif + case CELT_ALLOC_FAIL: return AVERROR(ENOMEM); + default: return AVERROR(EINVAL); + } +} + +static int ff_celt_bitstream_version_hack(CELTMode *mode) +{ + CELTHeader header = { .version_id = 0 }; + celt_header_init(&header, mode, 960, 2); + return header.version_id; +} + +static av_cold int libcelt_dec_init(AVCodecContext *c) +{ + struct libcelt_context *celt = c->priv_data; + int err; + + if (!c->channels || !c->frame_size || + c->frame_size > INT_MAX / sizeof(int16_t) / c->channels) + return AVERROR(EINVAL); + celt->mode = celt_mode_create(c->sample_rate, c->frame_size, &err); + if (!celt->mode) + return ff_celt_error_to_averror(err); + celt->dec = celt_decoder_create_custom(celt->mode, c->channels, &err); + if (!celt->dec) { + celt_mode_destroy(celt->mode); + return ff_celt_error_to_averror(err); + } + if (c->extradata_size >= 4) { + celt->discard = AV_RL32(c->extradata); + if (celt->discard < 0 || celt->discard >= c->frame_size) { + av_log(c, AV_LOG_WARNING, + "Invalid overlap (%d), ignored.\n", celt->discard); + celt->discard = 0; + } + } + if (c->extradata_size >= 8) { + unsigned version = AV_RL32(c->extradata + 4); + unsigned lib_version = ff_celt_bitstream_version_hack(celt->mode); + if (version != lib_version) + av_log(c, AV_LOG_WARNING, + "CELT bitstream version 0x%x may be " + "improperly decoded by libcelt for version 0x%x.\n", + version, lib_version); + } + c->sample_fmt = AV_SAMPLE_FMT_S16; + return 0; +} + +static av_cold int libcelt_dec_close(AVCodecContext *c) +{ + struct libcelt_context *celt = c->priv_data; + + celt_decoder_destroy(celt->dec); + celt_mode_destroy(celt->mode); + return 0; +} + +static int libcelt_dec_decode(AVCodecContext *c, void *data, + int *got_frame_ptr, AVPacket *pkt) +{ + struct libcelt_context *celt = c->priv_data; + AVFrame *frame = data; + int err; + int16_t *pcm; + + frame->nb_samples = c->frame_size; + if ((err = ff_get_buffer(c, frame, 0)) < 0) + return err; + pcm = (int16_t *)frame->data[0]; + err = celt_decode(celt->dec, pkt->data, pkt->size, pcm, c->frame_size); + if (err < 0) + return ff_celt_error_to_averror(err); + if (celt->discard) { + frame->nb_samples -= celt->discard; + memmove(pcm, pcm + celt->discard * c->channels, + frame->nb_samples * c->channels * sizeof(int16_t)); + celt->discard = 0; + } + *got_frame_ptr = 1; + return pkt->size; +} + +AVCodec ff_libcelt_decoder = { + .name = "libcelt", + .long_name = NULL_IF_CONFIG_SMALL("Xiph CELT decoder using libcelt"), + .type = AVMEDIA_TYPE_AUDIO, + .id = AV_CODEC_ID_CELT, + .priv_data_size = sizeof(struct libcelt_context), + .init = libcelt_dec_init, + .close = libcelt_dec_close, + .decode = libcelt_dec_decode, + .capabilities = AV_CODEC_CAP_DR1, +}; diff --git a/pool/shard006/C/0118286_compose.c b/pool/shard006/C/0118286_compose.c new file mode 100644 index 0000000000000000000000000000000000000000..f703a2d3958ead7376c85a3f6f58a518402bb121 --- /dev/null +++ b/pool/shard006/C/0118286_compose.c @@ -0,0 +1,68 @@ +/* + Copyright (C) 2010 William Hart + Copyright (C) 2010, 2012 Sebastian Pancratz + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "nmod_poly.h" + +void +_nmod_poly_compose(mp_ptr res, mp_srcptr poly1, slong len1, + mp_srcptr poly2, slong len2, nmod_t mod) +{ + if (len1 == 1) + res[0] = poly1[0]; + else if (len2 == 1) + res[0] = _nmod_poly_evaluate_nmod(poly1, len1, poly2[0], mod); + else if (len1 <= 7) + _nmod_poly_compose_horner(res, poly1, len1, poly2, len2, mod); + else + _nmod_poly_compose_divconquer(res, poly1, len1, poly2, len2, mod); +} + +void nmod_poly_compose(nmod_poly_t res, + const nmod_poly_t poly1, const nmod_poly_t poly2) +{ + const slong len1 = poly1->length; + const slong len2 = poly2->length; + + if (len1 == 0) + { + nmod_poly_zero(res); + } + else if (len1 == 1 || len2 == 0) + { + nmod_poly_fit_length(res, 1); + res->coeffs[0] = poly1->coeffs[0]; + res->length = (res->coeffs[0] != 0); + } + else + { + const slong lenr = (len1 - 1) * (len2 - 1) + 1; + + if (res != poly1 && res != poly2) + { + nmod_poly_fit_length(res, lenr); + _nmod_poly_compose_horner(res->coeffs, poly1->coeffs, len1, + poly2->coeffs, len2, poly1->mod); + } + else + { + nmod_poly_t t; + nmod_poly_init2(t, poly1->mod.n, lenr); + _nmod_poly_compose_horner(t->coeffs, poly1->coeffs, len1, + poly2->coeffs, len2, poly1->mod); + nmod_poly_swap(res, t); + nmod_poly_clear(t); + } + + res->length = lenr; + _nmod_poly_normalise(res); + } +} diff --git a/pool/shard006/C/0118287_cancel3.c b/pool/shard006/C/0118287_cancel3.c new file mode 100644 index 0000000000000000000000000000000000000000..5020648a60c5fdc98e6961e56220bd849459e6ad --- /dev/null +++ b/pool/shard006/C/0118287_cancel3.c @@ -0,0 +1,201 @@ +/* + * File: cancel3.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * 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 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 in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test asynchronous cancelation (alertable or non-alertable). + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - Async cancel if thread is not blocked (i.e. voluntarily resumes if blocked). + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join. + * - quserex.dll and alertdrv.sys are not available. + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum +{ + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ +{ + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread (void *arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t *bag = (bag_t *) arg; + + assert (bag == &threadbag[bag->threadnum]); + assert (bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert (pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert (pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancelation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + Sleep (100); + + return result; +} + +int +main () +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + assert ((t[0] = pthread_self ()).p != NULL); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert (pthread_create (&t[i], NULL, mythread, (void *) &threadbag[i]) + == 0); + } + + /* + * Code to control or munipulate child threads should probably go here. + */ + Sleep (NUMTHREADS * 100); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert (pthread_cancel (t[i]) == 0); + } + + /* + * Give threads time to complete. + */ + Sleep (NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf (stderr, "Thread %d: started %d\n", i, + threadbag[i].started); + } + } + + assert (!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)0; + + /* + * The thread does not contain any cancelation points, so + * a return value of PTHREAD_CANCELED confirms that async + * cancelation succeeded. + */ + assert (pthread_join (t[i], &result) == 0); + + fail = (result != PTHREAD_CANCELED); + + if (fail) + { + fprintf (stderr, "Thread %d: started %d: count %d\n", + i, threadbag[i].started, threadbag[i].count); + } + failed = (failed || fail); + } + + assert (!failed); + + /* + * Success. + */ + return 0; +} diff --git a/pool/shard006/C/0118291_setrelease.c b/pool/shard006/C/0118291_setrelease.c new file mode 100644 index 0000000000000000000000000000000000000000..ae846bd863fc34f65315daebd83c0687ac28507f --- /dev/null +++ b/pool/shard006/C/0118291_setrelease.c @@ -0,0 +1,106 @@ +/* + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + * Copyright 1999-2004 Michael Klein + * Copyright 2001-2004 Spiro Trikaliotis + * + */ + +/*! ************************************************************** +** \file sys/libiec/setrelease.c \n +** \author Spiro Trikaliotis \n +** \version $Id: setrelease.c,v 1.5 2006/02/24 12:21:43 strik Exp $ \n +** \authors Based on code from +** Michael Klein +** \n +** \brief Set a specific line on the IEC bus +** +****************************************************************/ + +#include +#include "cbm_driver.h" +#include "i_iec.h" + +/*! \brief Activate and deactive a line on the IEC serial bus + + This function activates (sets to 0V, L) and deactivates + (set to 5V, H) lines on the IEC serial bus. + + \param Pdx + Pointer to the device extension. + + \param Set + The mask of which lines should be set. This has to be a bitwise OR + between the constants IEC_DATA, IEC_CLOCK, IEC_ATN, and IEC_RESET + + \param Release + The mask of which lines should be released. This has to be a bitwise + OR between the constants IEC_DATA, IEC_CLOCK, IEC_ATN, and IEC_RESET + + \return + If the routine succeeds, it returns STATUS_SUCCESS. Otherwise, it + returns one of the error status values. + + \remark + If a bit is specified in the Set as well as in the Release mask, the + effect is undefined. +*/ +NTSTATUS +cbmiec_iec_setrelease(IN PDEVICE_EXTENSION Pdx, IN USHORT Set, IN USHORT Release) +{ + NTSTATUS ntStatus; + + FUNC_ENTER(); + + FUNC_PARAM((DBG_PREFIX "set = 0x%02x, release = 0x%02x", Set, Release)); + + ntStatus = STATUS_SUCCESS; + + DBG_ASSERT((Set & Release) == 0); + + // Set the correct line as given by the call + + if ( (Set & ~(IEC_LINE_DATA | IEC_LINE_CLOCK | IEC_LINE_ATN | IEC_LINE_RESET)) + || (Release & ~(IEC_LINE_DATA | IEC_LINE_CLOCK | IEC_LINE_ATN | IEC_LINE_RESET))) + { + // there was some bit set that is not recognized, return + // with an error + ntStatus = STATUS_INVALID_PARAMETER; + } + else + { + ULONG set_mask = 0; + ULONG release_mask = 0; + +#define SET_RELEASE_LINE(_LineName, _PPName) \ + if (Set & IEC_LINE_##_LineName) { set_mask |= PP_##_PPName##_OUT; } \ + if (Release & IEC_LINE_##_LineName) { release_mask |= PP_##_PPName##_OUT; } + + SET_RELEASE_LINE(DATA, DATA); + SET_RELEASE_LINE(CLOCK, CLK); + SET_RELEASE_LINE(ATN, ATN); + SET_RELEASE_LINE(RESET, RESET); + +#ifdef TEST_BIDIR + + #define PP_BIDIR_OUT PP_LP_BIDIR + #define IEC_LINE_BIDIR PP_BIDIR_OUT + + SET_RELEASE_LINE(BIDIR, BIDIR); + + #undef PP_BIDIR_OUT + #undef IEC_LINE_BIDIR + +#endif // #ifdef TEST_BIDIR + +#undef SET_RELEASE_LINE + + CBMIEC_SET_RELEASE(set_mask, release_mask); + + } + + FUNC_LEAVE_NTSTATUS(ntStatus ); +} diff --git a/pool/shard006/C/0118292_spitz_pm.c b/pool/shard006/C/0118292_spitz_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..ea9f9034cb5427c67dc38ea69d7c2d18e6e7e63d --- /dev/null +++ b/pool/shard006/C/0118292_spitz_pm.c @@ -0,0 +1,262 @@ +/* + * Battery and Power Management code for the Sharp SL-Cxx00 + * + * Copyright (c) 2005 Richard Purdie + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include "pxa27x.h" +#include "sharpsl_pm.h" + +#include "generic.h" + +#define SHARPSL_CHARGE_ON_VOLT 0x99 /* 2.9V */ +#define SHARPSL_CHARGE_ON_TEMP 0xe0 /* 2.9V */ +#define SHARPSL_CHARGE_ON_ACIN_HIGH 0x9b /* 6V */ +#define SHARPSL_CHARGE_ON_ACIN_LOW 0x34 /* 2V */ +#define SHARPSL_FATAL_ACIN_VOLT 182 /* 3.45V */ +#define SHARPSL_FATAL_NOACIN_VOLT 170 /* 3.40V */ + +static int spitz_last_ac_status; + +static struct gpio spitz_charger_gpios[] = { + { SPITZ_GPIO_KEY_INT, GPIOF_IN, "Keyboard Interrupt" }, + { SPITZ_GPIO_SYNC, GPIOF_IN, "Sync" }, + { SPITZ_GPIO_AC_IN, GPIOF_IN, "Charger Detection" }, + { SPITZ_GPIO_ADC_TEMP_ON, GPIOF_OUT_INIT_LOW, "ADC Temp On" }, + { SPITZ_GPIO_JK_B, GPIOF_OUT_INIT_LOW, "JK B" }, + { SPITZ_GPIO_CHRG_ON, GPIOF_OUT_INIT_LOW, "Charger On" }, +}; + +static void spitz_charger_init(void) +{ + gpio_request_array(ARRAY_AND_SIZE(spitz_charger_gpios)); +} + +static void spitz_measure_temp(int on) +{ + gpio_set_value(SPITZ_GPIO_ADC_TEMP_ON, on); +} + +static void spitz_charge(int on) +{ + if (on) { + if (sharpsl_pm.flags & SHARPSL_SUSPENDED) { + gpio_set_value(SPITZ_GPIO_JK_B, 1); + gpio_set_value(SPITZ_GPIO_CHRG_ON, 0); + } else { + gpio_set_value(SPITZ_GPIO_JK_B, 0); + gpio_set_value(SPITZ_GPIO_CHRG_ON, 0); + } + } else { + gpio_set_value(SPITZ_GPIO_JK_B, 0); + gpio_set_value(SPITZ_GPIO_CHRG_ON, 1); + } +} + +static void spitz_discharge(int on) +{ + gpio_set_value(SPITZ_GPIO_JK_A, on); +} + +/* HACK - For unknown reasons, accurate voltage readings are only made with a load + on the power bus which the green led on spitz provides */ +static void spitz_discharge1(int on) +{ + gpio_set_value(SPITZ_GPIO_LED_GREEN, on); +} + +static unsigned long gpio18_config = GPIO18_GPIO; + +static void spitz_presuspend(void) +{ + spitz_last_ac_status = sharpsl_pm.machinfo->read_devdata(SHARPSL_STATUS_ACIN); + + /* GPIO Sleep Register */ + PGSR0 = 0x00144018; + PGSR1 = 0x00EF0000; + if (machine_is_akita()) { + PGSR2 = 0x2121C000; + PGSR3 = 0x00600400; + } else { + PGSR2 = 0x0121C000; + PGSR3 = 0x00600000; + } + + PGSR0 &= ~SPITZ_GPIO_G0_STROBE_BIT; + PGSR1 &= ~SPITZ_GPIO_G1_STROBE_BIT; + PGSR2 &= ~SPITZ_GPIO_G2_STROBE_BIT; + PGSR3 &= ~SPITZ_GPIO_G3_STROBE_BIT; + PGSR2 |= GPIO_bit(SPITZ_GPIO_KEY_STROBE0); + + pxa2xx_mfp_config(&gpio18_config, 1); + gpio_request_one(18, GPIOF_OUT_INIT_HIGH, "Unknown"); + gpio_free(18); + + PRER = GPIO_bit(SPITZ_GPIO_KEY_INT); + PFER = GPIO_bit(SPITZ_GPIO_KEY_INT) | GPIO_bit(SPITZ_GPIO_RESET); + PWER = GPIO_bit(SPITZ_GPIO_KEY_INT) | GPIO_bit(SPITZ_GPIO_RESET) | PWER_RTC; + PKWR = GPIO_bit(SPITZ_GPIO_SYNC) | GPIO_bit(SPITZ_GPIO_KEY_INT) | GPIO_bit(SPITZ_GPIO_RESET); + PKSR = 0xffffffff; /* clear */ + + /* nRESET_OUT Disable */ + PSLR |= PSLR_SL_ROD; + + /* Stop 3.6MHz and drive HIGH to PCMCIA and CS */ + PCFR = PCFR_GPR_EN | PCFR_OPDE; +} + +static void spitz_postsuspend(void) +{ +} + +static int spitz_should_wakeup(unsigned int resume_on_alarm) +{ + int is_resume = 0; + int acin = sharpsl_pm.machinfo->read_devdata(SHARPSL_STATUS_ACIN); + + if (spitz_last_ac_status != acin) { + if (acin) { + /* charge on */ + sharpsl_pm.flags |= SHARPSL_DO_OFFLINE_CHRG; + dev_dbg(sharpsl_pm.dev, "AC Inserted\n"); + } else { + /* charge off */ + dev_dbg(sharpsl_pm.dev, "AC Removed\n"); + sharpsl_pm_led(SHARPSL_LED_OFF); + sharpsl_pm.machinfo->charge(0); + sharpsl_pm.charge_mode = CHRG_OFF; + } + spitz_last_ac_status = acin; + /* Return to suspend as this must be what we were woken for */ + return 0; + } + + if (PEDR & GPIO_bit(SPITZ_GPIO_KEY_INT)) + is_resume |= GPIO_bit(SPITZ_GPIO_KEY_INT); + + if (PKSR & GPIO_bit(SPITZ_GPIO_SYNC)) + is_resume |= GPIO_bit(SPITZ_GPIO_SYNC); + + if (resume_on_alarm && (PEDR & PWER_RTC)) + is_resume |= PWER_RTC; + + dev_dbg(sharpsl_pm.dev, "is_resume: %x\n", is_resume); + return is_resume; +} + +static unsigned long spitz_charger_wakeup(void) +{ + unsigned long ret; + ret = ((!gpio_get_value(SPITZ_GPIO_KEY_INT) + << GPIO_bit(SPITZ_GPIO_KEY_INT)) + | gpio_get_value(SPITZ_GPIO_SYNC)); + return ret; +} + +unsigned long spitzpm_read_devdata(int type) +{ + switch (type) { + case SHARPSL_STATUS_ACIN: + return !gpio_get_value(SPITZ_GPIO_AC_IN); + case SHARPSL_STATUS_LOCK: + return gpio_get_value(sharpsl_pm.machinfo->gpio_batlock); + case SHARPSL_STATUS_CHRGFULL: + return gpio_get_value(sharpsl_pm.machinfo->gpio_batfull); + case SHARPSL_STATUS_FATAL: + return gpio_get_value(sharpsl_pm.machinfo->gpio_fatal); + case SHARPSL_ACIN_VOLT: + return sharpsl_pm_pxa_read_max1111(MAX1111_ACIN_VOLT); + case SHARPSL_BATT_TEMP: + return sharpsl_pm_pxa_read_max1111(MAX1111_BATT_TEMP); + case SHARPSL_BATT_VOLT: + default: + return sharpsl_pm_pxa_read_max1111(MAX1111_BATT_VOLT); + } +} + +struct sharpsl_charger_machinfo spitz_pm_machinfo = { + .init = spitz_charger_init, + .exit = NULL, + .gpio_batlock = SPITZ_GPIO_BAT_COVER, + .gpio_acin = SPITZ_GPIO_AC_IN, + .gpio_batfull = SPITZ_GPIO_CHRG_FULL, + .batfull_irq = 1, + .gpio_fatal = SPITZ_GPIO_FATAL_BAT, + .discharge = spitz_discharge, + .discharge1 = spitz_discharge1, + .charge = spitz_charge, + .measure_temp = spitz_measure_temp, + .presuspend = spitz_presuspend, + .postsuspend = spitz_postsuspend, + .read_devdata = spitzpm_read_devdata, + .charger_wakeup = spitz_charger_wakeup, + .should_wakeup = spitz_should_wakeup, +#if defined(CONFIG_LCD_CORGI) + .backlight_limit = corgi_lcd_limit_intensity, +#endif + .charge_on_volt = SHARPSL_CHARGE_ON_VOLT, + .charge_on_temp = SHARPSL_CHARGE_ON_TEMP, + .charge_acin_high = SHARPSL_CHARGE_ON_ACIN_HIGH, + .charge_acin_low = SHARPSL_CHARGE_ON_ACIN_LOW, + .fatal_acin_volt = SHARPSL_FATAL_ACIN_VOLT, + .fatal_noacin_volt= SHARPSL_FATAL_NOACIN_VOLT, + .bat_levels = 40, + .bat_levels_noac = sharpsl_battery_levels_noac, + .bat_levels_acin = sharpsl_battery_levels_acin, + .status_high_acin = 188, + .status_low_acin = 178, + .status_high_noac = 185, + .status_low_noac = 175, +}; + +static struct platform_device *spitzpm_device; + +static int spitzpm_init(void) +{ + int ret; + + if (!machine_is_spitz() && !machine_is_akita() + && !machine_is_borzoi()) + return -ENODEV; + + spitzpm_device = platform_device_alloc("sharpsl-pm", -1); + if (!spitzpm_device) + return -ENOMEM; + + spitzpm_device->dev.platform_data = &spitz_pm_machinfo; + ret = platform_device_add(spitzpm_device); + + if (ret) + platform_device_put(spitzpm_device); + + return ret; +} + +static void spitzpm_exit(void) +{ + platform_device_unregister(spitzpm_device); +} + +module_init(spitzpm_init); +module_exit(spitzpm_exit); diff --git a/pool/shard006/C/0118295_rb-audiocd-info.c b/pool/shard006/C/0118295_rb-audiocd-info.c new file mode 100644 index 0000000000000000000000000000000000000000..46c5203ef89e06cdd27c16e9b4d863a2aa873ad8 --- /dev/null +++ b/pool/shard006/C/0118295_rb-audiocd-info.c @@ -0,0 +1,281 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2012 Jonathan Matthew + * + * 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. + * + * The Rhythmbox authors hereby grant permission for non-GPL compatible + * GStreamer plugins to be used and distributed together with GStreamer + * and Rhythmbox. This permission is above and beyond the permissions granted + * by the GPL license by which Rhythmbox is covered. If you modify this code + * you may extend this exception to your version of the code, but you are not + * obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include +#include +#include + +#include "rb-audiocd-info.h" + +static gboolean +read_gst_disc_info (RBAudioCDInfo *info, GError **error) +{ + GstElement *source; + GstElement *sink; + GstElement *pipeline; + GstFormat format; + GstFormat out_format; + GstBus *bus; + gint64 num_tracks; + gboolean done; + int i; + + source = gst_element_make_from_uri (GST_URI_SRC, "cdda://", NULL); + if (source == NULL) { + /* if cdparanoiasrc wasn't in base and installed by default + * everywhere, plugin install might be worth trying here. + */ + g_set_error_literal (error, + GST_CORE_ERROR, + GST_CORE_ERROR_MISSING_PLUGIN, + _("Could not find a GStreamer CD source plugin")); + return FALSE; + } + + g_object_set (source, "device", info->device, NULL); + pipeline = gst_pipeline_new (NULL); + sink = gst_element_factory_make ("fakesink", NULL); + gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL); + gst_element_link (source, sink); + + if (g_object_class_find_property (G_OBJECT_GET_CLASS (source), "paranoia-mode")) + g_object_set (source, "paranoia-mode", 0, NULL); + + gst_element_set_state (pipeline, GST_STATE_PAUSED); + + bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); + done = FALSE; + while (done == FALSE) { + GstMessage *msg; + GstTagList *tags; + + msg = gst_bus_timed_pop (bus, 3 * GST_SECOND); + if (msg == NULL) + break; + + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_TAG: + gst_message_parse_tag (msg, &tags); + + gst_tag_list_get_string (tags, + GST_TAG_CDDA_MUSICBRAINZ_DISCID, + &info->musicbrainz_disc_id); + gst_tag_list_get_string (tags, + GST_TAG_CDDA_MUSICBRAINZ_DISCID_FULL, + &info->musicbrainz_full_disc_id); + + gst_tag_list_free (tags); + break; + + case GST_MESSAGE_STATE_CHANGED: + if (GST_MESSAGE_SRC (msg) == GST_OBJECT (pipeline)) { + GstState oldstate; + GstState newstate; + GstState pending; + + gst_message_parse_state_changed (msg, &oldstate, &newstate, &pending); + if (newstate == GST_STATE_PAUSED && pending == GST_STATE_VOID_PENDING) + done = TRUE; + } + break; + case GST_MESSAGE_ERROR: + gst_message_parse_error (msg, error, NULL); + done = TRUE; + break; + default: + break; + } + + gst_message_unref (msg); + } + + if (*error == NULL) { + format = gst_format_get_by_nick ("track"); + out_format = format; + gst_element_query_duration (source, &out_format, &num_tracks); + info->num_tracks = num_tracks; + + info->tracks = g_new0 (RBAudioCDTrack, num_tracks); + for (i = 0; i < num_tracks; i++) { + RBAudioCDTrack *track = &info->tracks[i]; + GstCddaBaseSrcTrack *gst_track = &GST_CDDA_BASE_SRC (source)->tracks[i]; + guint64 duration = 0; + + track->is_audio = gst_track->is_audio; + track->track_num = gst_track->num; + + gst_tag_list_get_uint64 (gst_track->tags, GST_TAG_DURATION, &duration); + track->duration = (duration / GST_MSECOND); + } + } + + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (bus); + gst_object_unref (pipeline); + return (*error == NULL); +} + +static void +read_gvfs_disc_info (RBAudioCDInfo *info) +{ + GFile *cdda; + GFileInfo *fileinfo; + GFileEnumerator *tracks; + const char *attr; + char *uri; + char *dev; + + dev = g_path_get_basename (info->device); + uri = g_strdup_printf ("cdda://%s", dev); + g_free (dev); + + cdda = g_file_new_for_uri (uri); + g_free (uri); + + fileinfo = g_file_query_info (cdda, "xattr::*", G_FILE_QUERY_INFO_NONE, NULL, NULL); + if (fileinfo == NULL) { + g_object_unref (cdda); + return; + } + + attr = g_file_info_get_attribute_string (fileinfo, "xattr::org.gnome.audio.title"); + if (attr != NULL) { + info->album = g_strdup (attr); + } + attr = g_file_info_get_attribute_string (fileinfo, "xattr::org.gnome.audio.artist"); + if (attr != NULL) { + info->album_artist = g_strdup (attr); + } + attr = g_file_info_get_attribute_string (fileinfo, "xattr::org.gnome.audio.genre"); + if (attr != NULL) { + info->genre = g_strdup (attr); + } + + tracks = g_file_enumerate_children (cdda, G_FILE_ATTRIBUTE_STANDARD_NAME ",xattr::*", G_FILE_QUERY_INFO_NONE, NULL, NULL); + if (tracks != NULL) { + for (fileinfo = g_file_enumerator_next_file (tracks, NULL, NULL); + fileinfo != NULL; + fileinfo = g_file_enumerator_next_file (tracks, NULL, NULL)) { + const char *name; + const char *attr; + int track_num; + + name = g_file_info_get_name (fileinfo); + if (name == NULL || sscanf (name, "Track %d.wav", &track_num) != 1) { + continue; + } + + if (track_num < 1 || track_num > info->num_tracks) { + continue; + } + g_assert (track_num == info->tracks[track_num-1].track_num); + + attr = g_file_info_get_attribute_string (fileinfo, "xattr::org.gnome.audio.title"); + if (attr != NULL) { + info->tracks[track_num - 1].title = g_strdup (attr); + } + attr = g_file_info_get_attribute_string (fileinfo, "xattr::org.gnome.audio.artist"); + if (attr != NULL) { + info->tracks[track_num - 1].artist = g_strdup (attr); + } + } + } + g_object_unref (tracks); + + g_object_unref (cdda); +} + +static void +audiocd_info_thread (GSimpleAsyncResult *result, GObject *object, GCancellable *cancellable) +{ + RBAudioCDInfo *info; + GError *error = NULL; + + info = g_simple_async_result_get_op_res_gpointer (result); + + if (read_gst_disc_info (info, &error)) { + read_gvfs_disc_info (info); + } else { + rb_audiocd_info_free (info); + g_simple_async_result_set_op_res_gpointer (result, NULL, NULL); + g_simple_async_result_take_error (result, error); + } +} + +void +rb_audiocd_info_free (RBAudioCDInfo *info) +{ + int i; + + g_free (info->device); + g_free (info->musicbrainz_disc_id); + g_free (info->musicbrainz_full_disc_id); + g_free (info->album); + g_free (info->genre); + g_free (info->album_artist); + + for (i = 0; i < info->num_tracks; i++) { + g_free (info->tracks[i].artist); + g_free (info->tracks[i].title); + } + g_free (info->tracks); + g_free (info); +} + +void +rb_audiocd_info_get (const char *device, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + GSimpleAsyncResult *result; + RBAudioCDInfo *info; + + result = g_simple_async_result_new (NULL, callback, user_data, rb_audiocd_info_get); + g_simple_async_result_set_check_cancellable (result, cancellable); + + info = g_new0 (RBAudioCDInfo, 1); + info->device = g_strdup (device); + g_simple_async_result_set_op_res_gpointer (result, info, NULL); + + g_simple_async_result_run_in_thread (result, audiocd_info_thread, G_PRIORITY_DEFAULT, cancellable); +} + +RBAudioCDInfo * +rb_audiocd_info_finish (GAsyncResult *result, + GError **error) +{ + g_return_val_if_fail (g_simple_async_result_is_valid (result, NULL, rb_audiocd_info_get), + NULL); + if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result), error)) + return NULL; + + return g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result)); +} diff --git a/pool/shard006/C/0118298_program.c b/pool/shard006/C/0118298_program.c new file mode 100644 index 0000000000000000000000000000000000000000..79b2414159bbf0c232fbb8fa7bee93fbbf620c4a --- /dev/null +++ b/pool/shard006/C/0118298_program.c @@ -0,0 +1,31 @@ +#include "../../lib/libduck.h" +#include "../../lib/string.h" +int main(int argc, char **argv); + +int main(int argc, char **argv) +{ + char *path; + if (argc > 1) + { + path = malloc(sizeof(char) * 100); + strcpy(path, "/man/"); + strcat(path, argv[1]); + strcat(path, ".man"); + int inode_num = path_to_inode(path); + EXT2_INODE_t *inode = malloc(sizeof(EXT2_INODE_t)); + load_inode(inode_num, inode); + char *file_buff = (char *)malloc(inode->size_low); + load_file(inode, 0, 0, file_buff); + for (int i = 0; i < inode->size_low; i++) + { + if (file_buff[i] > 0x1F || file_buff[i] == 0x0A) + { + putc(file_buff[i]); + } + else + { + putc('.'); + } + } + } +} \ No newline at end of file diff --git a/pool/shard006/C/0118299_StatusNullFolder.c b/pool/shard006/C/0118299_StatusNullFolder.c new file mode 100644 index 0000000000000000000000000000000000000000..1fa91b10d02eaf948e5d948e46988109164e2762 --- /dev/null +++ b/pool/shard006/C/0118299_StatusNullFolder.c @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2007-2009 Daniel Prevost + * + * This file is part of Photon (photonsoftware.org). + * + * This file may be distributed and/or modified under the terms of the + * GNU General Public License version 2 or version 3 as published by the + * Free Software Foundation and appearing in the file COPYING.GPL2 and + * COPYING.GPL3 included in the packaging of this software. + * + * Licensees holding a valid Photon Commercial license can use this file + * in accordance with the terms of their license. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +#include "folderTest.h" + +const bool expectedToPass = false; + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +int main() +{ +#if defined(USE_DBC) + psonFolder* pFolder; + psonSessionContext context; + bool ok; + psonTxStatus status; + psoObjStatus objStatus; + psoObjectDefinition def = { PSO_FOLDER, 0, 0, 0 }; + + pFolder = initFolderTest( expectedToPass, &context ); + + psonTxStatusInit( &status, SET_OFFSET( context.pTransaction ) ); + + ok = psonFolderInit( pFolder, 0, 1, 0, &status, 5, "Test1", 1234, &context ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); + } + + ok = psonFolderInsertObject( pFolder, + "test2", + "Test2", + 5, + &def, + NULL, + NULL, + 1, + 0, + &context ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, &context.errorHandler, ; ); + } + + psonAPIFolderStatus( NULL, &objStatus ); + + ERROR_EXIT( expectedToPass, NULL, ; ); +#else + return 1; +#endif +} + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + diff --git a/pool/shard006/C/0118302_global.c b/pool/shard006/C/0118302_global.c new file mode 100644 index 0000000000000000000000000000000000000000..382cffc9b7aa083cf2e7059f26293bc466bbae75 --- /dev/null +++ b/pool/shard006/C/0118302_global.c @@ -0,0 +1,213 @@ +/* + * global.c + * + * (c) 2009 donald@teamducktales + * + * 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 +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "global.h" + +#include "map.h" + +#define DEVICENAME "TDT RC event driver" +char eventPath[] = "/dev/input/event0"; + +//Checks with event device is created by simubutton.ko +int getEventDevice() +{ + int vFd = -1; + int vIterator = 0; + bool vDeviceFound = false; + char vName[256] = "Unknown"; + + while(vIterator < 10 && vDeviceFound == false) + { + eventPath[16] = vIterator + 48; + vIterator++; + vFd = open(eventPath, O_RDONLY); + if(vFd <= 0) + continue; + + ioctl(vFd, EVIOCGNAME(sizeof(vName)), vName); + printf("Input device name: \"%s\"\n", vName); + + if(!strcmp(DEVICENAME, vName)) + vDeviceFound = true; + + close(vFd); + } + + return vDeviceFound; +} + +// Translates internal remote control hex value to known linux input key value +int getInternalCode(tButton * cButtons, const char cCode[3]) { + int vLoop = 0; + + for (vLoop = 0; cButtons[vLoop].KeyCode != KEY_NULL; vLoop++) + { + //printf("%20s - %2s - %3d\n", cButtons[vLoop].KeyName, cButtons[vLoop].KeyWord, cButtons[vLoop].KeyCode); + if ( (cButtons[vLoop].KeyWord[0] == cCode[0] || cButtons[vLoop].KeyWord[0] == (cCode[0]-32) ) && + (cButtons[vLoop].KeyWord[1] == cCode[1] || cButtons[vLoop].KeyWord[1] == (cCode[1]-32) )) { + + printf("KEY: %02X - %s\n", cButtons[vLoop].KeyCode, cButtons[vLoop].KeyName); + return cButtons[vLoop].KeyCode; + } + } + return 0; +} + +int printKeyMap(tButton * cButtons) { + int vLoop = 0; + + for (vLoop = 0; cButtons[vLoop].KeyCode != KEY_NULL; vLoop++) + printf("%20s - %2s - %3d\n", cButtons[vLoop].KeyName, cButtons[vLoop].KeyWord, cButtons[vLoop].KeyCode); +} + +// Translates internal remote control hex value to known linux input key value +int getInternalCodeHex(tButton * cButtons, const unsigned char cCode) { + char vCode[3]; + + + sprintf(vCode, "%.2hhx", cCode); + vCode[2] = '\0'; + + return getInternalCode(cButtons, vCode); +} + + +static int tuxtxt_exit_count = 0; +static int sSockethandle = -1; +#define SocketName "/tmp/rc.socket" + +int checkTuxTxt(const int cCode) +{ + int vTmpO; + + if ( (vTmpO = open("/tmp/block.tmp", O_RDONLY)) >= 0) { + close(vTmpO); + + //workaround if tuxtxt hangs + if(cCode == KEY_HOME) //EXIT + { + tuxtxt_exit_count++; + if(tuxtxt_exit_count > 1) + { + tuxtxt_exit_count = 0; + system("killall tuxtxt; sleep 3; killall -9 tuxtxt; rm -f /tmp/block.tmp"); + } + } + + fprintf(stderr, "Forwarding to Socket-> %u\n", sSockethandle); + + if (sSockethandle <= 0) { + struct sockaddr_un vAddr; + vAddr.sun_family = AF_UNIX; + strcpy( vAddr.sun_path, SocketName ); + sSockethandle = socket( PF_UNIX, SOCK_STREAM, 0 ); + + if ( sSockethandle <= 0 ) { + fprintf(stderr, "No RemoteControlSocket attached!\n"); + return 0; + }; + + if(connect(sSockethandle,(struct sockaddr *)&vAddr,sizeof(vAddr))!=0) { + close (sSockethandle); + sSockethandle = -1; + fprintf(stderr, "connect failed!\n"); + return 0; + } + } + + if ( sSockethandle > 0 ) { + char * vTmpS = (char*) malloc(sizeof("00000000")); + sprintf(vTmpS, "%08d", cCode); + + if (write(sSockethandle, (void *) vTmpS, sizeof("00000000")) <= 0) + fprintf(stderr, "Error while forwarding!\n"); + } else + fprintf(stderr, "Error while forwarding!\n"); + return 1; + } + + tuxtxt_exit_count = 0; + if (sSockethandle != -1) { + close (sSockethandle); + sSockethandle = -1; + } + return 0; +} + +void sendInputEvent(const int cCode) +{ + sendInputEventT(INPUT_PRESS, cCode); + sendInputEventT(INPUT_RELEASE, cCode); +} + +void sendInputEventT(const unsigned int type, const int cCode) +{ + int vFd = -1; + struct input_event vInev; + int cSize = sizeof(struct input_event); + + gettimeofday(&vInev.time, NULL); + vInev.type = 1; + vInev.code = cCode; + + vFd = open(eventPath, O_WRONLY); + + vInev.value = type; + write(vFd, &vInev, cSize); + + close(vFd); +} + +void setInputEventRepeatRate(unsigned int delay, unsigned int period) +{ + int vFd = -1; + struct input_event vInev; + + vFd = open(eventPath, O_WRONLY); + + vInev.type = EV_REP; + vInev.code = REP_DELAY; + vInev.value = delay; + if (write(vFd, &vInev, sizeof(vInev)) == -1) + perror("REP_DELAY"); + vInev.code = REP_PERIOD; + vInev.value = period; + if (write(vFd, &vInev, sizeof(vInev)) == -1) + perror("REP_PERIOD"); + + close(vFd); +} + diff --git a/pool/shard006/C/0118306_value.c b/pool/shard006/C/0118306_value.c new file mode 100644 index 0000000000000000000000000000000000000000..fe7047f67ddee480659cf31858654ae0d4317428 --- /dev/null +++ b/pool/shard006/C/0118306_value.c @@ -0,0 +1,173 @@ +/* Copyright 2010 Erik Price */ + +/* TValue functions */ + +#include "bijou.h" +#include "internal.h" + +#include +#include + +const TValue *to_number(const TValue *obj, TValue *n) +{ + if (ttisnumber(obj)) + return obj; + /* TODO: fix this at some point to be less ugly */ + if (ttisstring(obj)) { + setnumvalue(n, strtod(obj->value.s.ptr, NULL)); + return n; + } else { + return NULL; + } +} + +/* create a TValue from a number */ +TValue create_bijou_Number(bijou_Number num) +{ + Value v; + v.n = num; + TValue ret; + ret.tt = BIJOU_TNUMBER; + ret.value = v; + return ret; +} + +/* create a boolean from val, 0 => false, not-0 => true */ +TValue create_boolean(bijou_Number val) +{ + Value v; + v.b = val; + TValue ret; + ret.tt = BIJOU_TBOOLEAN; + ret.value = v; + return ret; +} + +/* create a TValue with the value of null */ +TValue create_null(void) +{ + TValue ret; + ret.tt = BIJOU_TNULL; + return ret; +} + +/* return a TValue with the value BIJOU_TNONE */ +TValue create_none(void) +{ + TValue ret; + ret.tt = BIJOU_TNONE; + return ret; +} + +TValue create_function(BijouFunction *func) +{ + TValue ret; + Value v; + ret.tt = BIJOU_TFUNCTION; + v.func = func; + ret.value = v; + return ret; +} + +/* create a TValue from a BijouString */ +TValue create_TValue_string(BijouString s) +{ + TValue tv; + Value v; + + v.s = s; + tv.tt = BIJOU_TSTRING; + tv.value = v; + + return tv; + +} + +/* create a TValue containing a pointer to something */ +TValue create_pointer(void * p) +{ + TValue tv; + Value v; + v.pointer = p; + tv.tt = BIJOU_TPOINTER; + tv.value = v; + + return tv; +} +/* returns nonzero if the two parameters are equal, + * zero otherwise. + */ +int TValue_equal(TValue f, TValue s) +{ + /* lol, ternary */ + return f.tt == s.tt ? f.tt == BIJOU_TNULL ? 1 : \ + f.tt == BIJOU_TNUMBER || f.tt == BIJOU_TBOOLEAN \ + ? (f.value.n == s.value.n) : f.tt == BIJOU_TSTRING ? \ + BijouString_equal(f.value.s, s.value.s) : &f == &s : 0; +} + + +/* returns a string representation of t */ +char *TValue_to_string(TValue t) +{ + int type = t.tt; + switch (type) { + case BIJOU_TNONE: + return "NONE"; + case BIJOU_TNULL: + return "NULL"; + case BIJOU_TNUMBER: { + char *ca = B_MALLOC(sizeof(char) * 20); + memset(ca, '\0', 20); + sprintf(ca, "%f", (double) t.value.n ); + return ca; + } + case BIJOU_TSTRING: + return t.value.s.ptr; + case BIJOU_TBOOLEAN: + return t.value.b ? "true" : "false"; + case BIJOU_TPOINTER: { + char *ca = B_MALLOC(sizeof(char) * 20); + memset(ca, '\0', 20); + sprintf(ca, "%p", t.value.pointer ); + return ca; + } + case BIJOU_TFUNCTION: { + char *ca = B_MALLOC(sizeof(char) * 20); + memset(ca, '\0', 20); + sprintf(ca, "%p", (void *)&t.value ); + return ca; + } + default: + return "Don't know type"; + } +} + +/* return a BijouString representation of t */ +BijouString TValue_to_BijouString(TValue t) +{ + return BijouString_new(TValue_to_string(t)); +} + +/* return a string representation of TValue t */ +char *TValue_type_to_string(TValue t) +{ + switch (t.tt) { + case BIJOU_TNONE: + return "NONE"; + case BIJOU_TNULL: + return "null"; + case BIJOU_TNUMBER: + return "number"; + case BIJOU_TBOOLEAN: + return "bool"; + case BIJOU_TSTRING: + return "string"; + case BIJOU_TFUNCTION: + return "function"; + case BIJOU_TPOINTER: + return "pointer"; + default: + return "I haven't a damn clue."; + } +} diff --git a/pool/shard006/C/0118311_tst-mbsrtowcs.c b/pool/shard006/C/0118311_tst-mbsrtowcs.c new file mode 100644 index 0000000000000000000000000000000000000000..bed76bf4ef81fde7a15b052bb37b83dd9cb95e21 --- /dev/null +++ b/pool/shard006/C/0118311_tst-mbsrtowcs.c @@ -0,0 +1,67 @@ +/* Test NUL handling of mbsrtowcs. + Copyright (C) 2004-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 2004. + + 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 + . */ + +#include +#include +#include + +static int +do_test (void) +{ + const unsigned char buf[] = { 'a', 'b', '\0', 'c', 'd', '\0', 'e' }; + wchar_t out[sizeof (buf)]; + memset (out, '\xff', sizeof (out)); + + mbstate_t state; + memset (&state, '\0', sizeof (state)); + + const char *in = (const char *) buf; + size_t n = mbsrtowcs (out, &in, sizeof (out) / sizeof (wchar_t), &state); + + int result = 0; + if (n != 2) + { + printf ("n = %zu, expected 2\n", n); + result = 1; + } + if (in != NULL) + { + printf ("in = %p, expected NULL\n", in); + result = 1; + } + if (out[0] != L'a') + { + printf ("out[0] = L'%lc', expected L'a'\n", (wint_t) out[0]); + result = 1; + } + if (out[1] != L'b') + { + printf ("out[1] = L'%lc', expected L'b'\n", (wint_t) out[1]); + result = 1; + } + if (out[2] != L'\0') + { + printf ("out[2] = L'%lc', expected L'\\0'\n", (wint_t) out[2]); + result = 1; + } + return result; +} + +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard006/C/0118312_qmgr_defer.c b/pool/shard006/C/0118312_qmgr_defer.c new file mode 100644 index 0000000000000000000000000000000000000000..79615cc0f760c34cedb8aa856978391e2de6013b --- /dev/null +++ b/pool/shard006/C/0118312_qmgr_defer.c @@ -0,0 +1,163 @@ +/*++ +/* NAME +/* qmgr_defer +/* SUMMARY +/* deal with mail that must be delivered later +/* SYNOPSIS +/* #include "qmgr.h" +/* +/* void qmgr_defer_recipient(message, recipient, dsn) +/* QMGR_MESSAGE *message; +/* RECIPIENT *recipient; +/* DSN *dsn; +/* +/* void qmgr_defer_todo(queue, dsn) +/* QMGR_QUEUE *queue; +/* DSN *dsn; +/* +/* void qmgr_defer_transport(transport, dsn) +/* QMGR_TRANSPORT *transport; +/* DSN *dsn; +/* DESCRIPTION +/* qmgr_defer_recipient() defers delivery of the named message to +/* the named recipient. It updates the message structure and writes +/* a log entry. +/* +/* qmgr_defer_todo() iterates over all "todo" deliveries queued for +/* the named site, and calls qmgr_defer_recipient() for each recipient +/* found. Side effects caused by qmgr_entry_done(), qmgr_queue_done(), +/* and by qmgr_active_done(): in-core queue entries will disappear, +/* in-core queues may disappear, in-core and on-disk messages may +/* disappear, bounces may be sent, new in-core queues, queue entries +/* and recipients may appear. +/* +/* qmgr_defer_transport() calls qmgr_defer_todo() for each queue +/* that depends on the named transport. See there for side effects. +/* +/* Arguments: +/* .IP recipient +/* A recipient address; used for logging purposes, and for updating +/* the message-specific \fIdefer\fR log. +/* .IP queue +/* Specifies a queue with delivery requests for a specific next-hop +/* host (or local user). +/* .IP transport +/* Specifies a message delivery transport. +/* .IP dsn +/* See dsn(3). +/* BUGS +/* The side effects of calling this routine are quite dramatic. +/* DIAGNOSTICS +/* Panic: consistency check failure. Fatal: out of memory. +/* LICENSE +/* .ad +/* .fi +/* The Secure Mailer license must be distributed with this software. +/* AUTHOR(S) +/* Wietse Venema +/* IBM T.J. Watson Research +/* P.O. Box 704 +/* Yorktown Heights, NY 10598, USA +/* +/* Preemptive scheduler enhancements: +/* Patrik Rak +/* Modra 6 +/* 155 00, Prague, Czech Republic +/*--*/ + +/* System library. */ + +#include + +/* Utility library. */ + +#include +#include + +/* Global library. */ + +#include +#include + +/* Application-specific. */ + +#include "qmgr.h" + +/* qmgr_defer_transport - defer todo entries for named transport */ + +void qmgr_defer_transport(QMGR_TRANSPORT *transport, DSN *dsn) +{ + QMGR_QUEUE *queue; + QMGR_QUEUE *next; + + if (msg_verbose) + msg_info("defer transport %s: %s %s", + transport->name, dsn->status, dsn->reason); + + /* + * Proceed carefully. Queues may disappear as a side effect. + */ + for (queue = transport->queue_list.next; queue; queue = next) { + next = queue->peers.next; + qmgr_defer_todo(queue, dsn); + } +} + +/* qmgr_defer_todo - defer all todo queue entries for specific site */ + +void qmgr_defer_todo(QMGR_QUEUE *queue, DSN *dsn) +{ + QMGR_ENTRY *entry; + QMGR_ENTRY *next; + QMGR_MESSAGE *message; + RECIPIENT *recipient; + int nrcpt; + QMGR_QUEUE *retry_queue; + + /* + * Sanity checks. + */ + if (msg_verbose) + msg_info("defer site %s: %s %s", + queue->name, dsn->status, dsn->reason); + + /* + * See if we can redirect the deliveries to the retry(8) delivery agent, + * so that they can be handled asynchronously. If the retry(8) service is + * unavailable, use the synchronous defer(8) server. With a large todo + * queue, this blocks the queue manager for a significant time. + */ + retry_queue = qmgr_error_queue(MAIL_SERVICE_RETRY, dsn); + + /* + * Proceed carefully. Queue entries may disappear as a side effect. + */ + for (entry = queue->todo.next; entry != 0; entry = next) { + next = entry->queue_peers.next; + if (retry_queue != 0) { + qmgr_entry_move_todo(retry_queue, entry); + continue; + } + message = entry->message; + for (nrcpt = 0; nrcpt < entry->rcpt_list.len; nrcpt++) { + recipient = entry->rcpt_list.info + nrcpt; + qmgr_defer_recipient(message, recipient, dsn); + } + qmgr_entry_done(entry, QMGR_QUEUE_TODO); + } +} + +/* qmgr_defer_recipient - defer delivery of specific recipient */ + +void qmgr_defer_recipient(QMGR_MESSAGE *message, RECIPIENT *recipient, + DSN *dsn) +{ + MSG_STATS stats; + + /* + * Update the message structure and log the message disposition. + */ + message->flags |= defer_append(message->tflags, message->queue_id, + QMGR_MSG_STATS(&stats, message), recipient, + "none", dsn); +} diff --git a/pool/shard006/C/0118315_bbsmailmsg.c b/pool/shard006/C/0118315_bbsmailmsg.c new file mode 100644 index 0000000000000000000000000000000000000000..40edbd8b3d09ce3016d228e48cae95436fc66697 --- /dev/null +++ b/pool/shard006/C/0118315_bbsmailmsg.c @@ -0,0 +1,47 @@ +#include "bbslib.h" + +int +bbsmailmsg_main() +{ + html_header(1); + check_msg(); + if (!loginok || isguest) + http_fatal("´Ò´Ò¹ý¿Í²»ÄÜ´¦ÀíѶϢ£¬ÇëÏȵǼ"); + changemode(SMAIL); + mail_msg(¤tuser); + u_info->unreadmsg = 0; + printf("ѶϢ±¸·ÝÒѾ­¼Ä»ØÄúµÄÐÅÏä"); + printf("·µ»Ø"); + http_quit(); + return 0; +} + +void +mail_msg(struct userec *user) { + char fname[30]; + char buf[MAX_MSG_SIZE], showmsg[MAX_MSG_SIZE * 2]; + int i; + struct msghead head; + time_t now; + char title[STRLEN]; + FILE *fn; + int count; + + sprintf(fname, "tmp/%s.msg", user->userid); + fn = fopen(fname, "w"); + count = get_msgcount(0, user->userid); + for (i = 0; i < count; i++) { + load_msghead(0, user->userid, &head, i); + load_msgtext(user->userid, &head, buf); + translate_msg(buf, &head, showmsg, 0); + fprintf(fn, "%s", showmsg); + } + fclose(fn); + + now = time(0); + sprintf(title, "[%12.12s] ËùÓÐѶϢ±¸·Ý", ctime(&now) + 4); + mail_file(fname, user->userid, title, user->userid); + unlink(fname); + clear_msg(user->userid); +} + diff --git a/pool/shard006/C/0118317_CWE126_Buffer_Overread__malloc_char_memcpy_18.c b/pool/shard006/C/0118317_CWE126_Buffer_Overread__malloc_char_memcpy_18.c new file mode 100644 index 0000000000000000000000000000000000000000..13b8f2401b0ed6ca644026b53d9736aa6999dd50 --- /dev/null +++ b/pool/shard006/C/0118317_CWE126_Buffer_Overread__malloc_char_memcpy_18.c @@ -0,0 +1,106 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE126_Buffer_Overread__malloc_char_memcpy_18.c +Label Definition File: CWE126_Buffer_Overread__malloc.label.xml +Template File: sources-sink-18.tmpl.c +*/ +/* + * @description + * CWE: 126 Buffer Over-read + * BadSource: Use a small buffer + * GoodSource: Use a large buffer + * Sink: memcpy + * BadSink : Copy data to string using memcpy + * Flow Variant: 18 Control flow: goto statements + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE126_Buffer_Overread__malloc_char_memcpy_18_bad() +{ + char * data; + data = NULL; + goto source; +source: + /* FLAW: Use a small buffer */ + data = (char *)malloc(50*sizeof(char)); + memset(data, 'A', 50-1); /* fill with 'A's */ + data[50-1] = '\0'; /* null terminate */ + { + char dest[100]; + memset(dest, 'C', 100-1); + dest[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: using memcpy with the length of the dest where data + * could be smaller than dest causing buffer overread */ + memcpy(dest, data, strlen(dest)*sizeof(char)); + dest[100-1] = '\0'; + printLine(dest); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */ +static void goodG2B() +{ + char * data; + data = NULL; + goto source; +source: + /* FIX: Use a large buffer */ + data = (char *)malloc(100*sizeof(char)); + memset(data, 'A', 100-1); /* fill with 'A's */ + data[100-1] = '\0'; /* null terminate */ + { + char dest[100]; + memset(dest, 'C', 100-1); + dest[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: using memcpy with the length of the dest where data + * could be smaller than dest causing buffer overread */ + memcpy(dest, data, strlen(dest)*sizeof(char)); + dest[100-1] = '\0'; + printLine(dest); + free(data); + } +} + +void CWE126_Buffer_Overread__malloc_char_memcpy_18_good() +{ + goodG2B(); +} + +#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()..."); + CWE126_Buffer_Overread__malloc_char_memcpy_18_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE126_Buffer_Overread__malloc_char_memcpy_18_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0118321_mali_kbase_security.c b/pool/shard006/C/0118321_mali_kbase_security.c new file mode 100644 index 0000000000000000000000000000000000000000..80b48fb08c18f6a64b75e3e3f1d67ca85ade8dd8 --- /dev/null +++ b/pool/shard006/C/0118321_mali_kbase_security.c @@ -0,0 +1,78 @@ +/* + * + * (C) COPYRIGHT 2011-2015 ARM Limited. All rights reserved. + * + * This program is free software and is provided to you under the terms of the + * GNU General Public License version 2 as published by the Free Software + * Foundation, and any use by you of this program is subject to the terms + * of such GNU licence. + * + * A copy of the licence is included with the program, and can also be obtained + * from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + + + + + +/** + * @file mali_kbase_security.c + * Base kernel security capability API + */ + +#include + +static inline bool kbasep_am_i_root(void) +{ +#if KBASE_HWCNT_DUMP_BYPASS_ROOT + return true; +#else + /* Check if root */ +#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0) + if (uid_eq(current_euid(), GLOBAL_ROOT_UID)) + return true; +#else + if (current_euid() == 0) + return true; +#endif /*LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0)*/ + return false; +#endif /*KBASE_HWCNT_DUMP_BYPASS_ROOT*/ +} + +/** + * kbase_security_has_capability - see mali_kbase_caps.h for description. + */ + +bool kbase_security_has_capability(struct kbase_context *kctx, enum kbase_security_capability cap, u32 flags) +{ + /* Assume failure */ + bool access_allowed = false; + bool audit = KBASE_SEC_FLAG_AUDIT & flags; + + KBASE_DEBUG_ASSERT(NULL != kctx); + CSTD_UNUSED(kctx); + + /* Detect unsupported flags */ + KBASE_DEBUG_ASSERT(((~KBASE_SEC_FLAG_MASK) & flags) == 0); + + /* Determine if access is allowed for the given cap */ + switch (cap) { + case KBASE_SEC_MODIFY_PRIORITY: + case KBASE_SEC_INSTR_HW_COUNTERS_COLLECT: + /* Access is granted only if the caller is privileged */ + access_allowed = kbasep_am_i_root(); + break; + } + + /* Report problem if requested */ + if (!access_allowed && audit) { + dev_warn(kctx->kbdev->dev, "Security capability failure: %d, %p", cap, (void *)kctx); + HiLOGE("DISPLAY", "GPU", "Security capability failure: %d, %p", cap, (void *)kctx); + } + + return access_allowed; +} + +KBASE_EXPORT_TEST_API(kbase_security_has_capability); diff --git a/pool/shard006/C/0118322_test-u32-vasnprintf2.c b/pool/shard006/C/0118322_test-u32-vasnprintf2.c new file mode 100644 index 0000000000000000000000000000000000000000..0edc23bc2e869eeac01c362228ec9c1465dc8339 --- /dev/null +++ b/pool/shard006/C/0118322_test-u32-vasnprintf2.c @@ -0,0 +1,119 @@ +/* Test of u32_vasnprintf() function in an ISO-8859-1 locale. + Copyright (C) 2007-2014 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 . */ + +/* Written by Bruno Haible , 2007. */ + +#include + +#include "unistdio.h" + +#include +#include +#include +#include +#include + +#include "unistr.h" +#include "macros.h" + +static void +test_function (uint32_t * (*my_asnprintf) (uint32_t *, size_t *, const char *, ...)) +{ + /* Test the support of the 's' conversion specifier for strings. */ + + { + const char *locale_string = "\304rger"; /* Ärger */ + { + size_t length; + uint32_t *result = + my_asnprintf (NULL, &length, "%s %d", locale_string, 33, 44, 55); + static const uint32_t expected[] = + { 0x00c4, 'r', 'g', 'e', 'r', ' ', '3', '3', 0 }; + ASSERT (result != NULL); + ASSERT (u32_strcmp (result, expected) == 0); + ASSERT (length == u32_strlen (result)); + free (result); + } + { /* Width. */ + size_t length; + uint32_t *result = + my_asnprintf (NULL, &length, "%10s %d", locale_string, 33, 44, 55); + static const uint32_t expected[] = + { ' ', ' ', ' ', ' ', ' ', 0x00c4, 'r', 'g', 'e', 'r', + ' ', '3', '3', 0 + }; + ASSERT (result != NULL); + ASSERT (u32_strcmp (result, expected) == 0); + ASSERT (length == u32_strlen (result)); + free (result); + } + { /* FLAG_LEFT. */ + size_t length; + uint32_t *result = + my_asnprintf (NULL, &length, "%-10s %d", locale_string, 33, 44, 55); + static const uint32_t expected[] = + { 0x00c4, 'r', 'g', 'e', 'r', ' ', ' ', ' ', ' ', ' ', + ' ', '3', '3', 0 + }; + ASSERT (result != NULL); + ASSERT (u32_strcmp (result, expected) == 0); + ASSERT (length == u32_strlen (result)); + free (result); + } + { /* FLAG_ZERO: no effect. */ + size_t length; + uint32_t *result = + my_asnprintf (NULL, &length, "%010s %d", locale_string, 33, 44, 55); + static const uint32_t expected[] = + { ' ', ' ', ' ', ' ', ' ', 0x00c4, 'r', 'g', 'e', 'r', + ' ', '3', '3', 0 + }; + ASSERT (result != NULL); + ASSERT (u32_strcmp (result, expected) == 0); + ASSERT (length == u32_strlen (result)); + free (result); + } + } +} + +static uint32_t * +my_asnprintf (uint32_t *resultbuf, size_t *lengthp, const char *format, ...) +{ + va_list args; + uint32_t *ret; + + va_start (args, format); + ret = u32_vasnprintf (resultbuf, lengthp, format, args); + va_end (args); + return ret; +} + +static void +test_vasnprintf () +{ + test_function (my_asnprintf); +} + +int +main (int argc, char *argv[]) +{ + /* configure should already have checked that the locale is supported. */ + if (setlocale (LC_ALL, "") == NULL) + return 1; + + test_vasnprintf (); + return 0; +} diff --git a/pool/shard006/C/0118325_CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05.c b/pool/shard006/C/0118325_CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05.c new file mode 100644 index 0000000000000000000000000000000000000000..bccdae6ec53d6a88d4d88044364ee8208895aa00 --- /dev/null +++ b/pool/shard006/C/0118325_CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05.c @@ -0,0 +1,170 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-05.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: file Read input from a file + * GoodSource: Fixed string + * Sink: w32_spawnv + * BadSink : execute command with wspawnv + * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#include + +/* The two variables below are not defined as "const", but are never + * assigned any other value, so a tool should be able to identify that + * reads of these will always return their initialized values. + */ +static int staticTrue = 1; /* true */ +static int staticFalse = 0; /* false */ + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(staticTrue) + { + { + /* Read input from a file */ + size_t dataLen = wcslen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (100-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + fclose(pFile); + } + } + } + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wspawnv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnv(_P_WAIT, COMMAND_INT_PATH, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(staticFalse) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wspawnv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnv(_P_WAIT, COMMAND_INT_PATH, args); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(staticTrue) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wspawnv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnv(_P_WAIT, COMMAND_INT_PATH, args); + } +} + +void CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_file_w32_spawnv_05_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0118327_tutorial_5.c b/pool/shard006/C/0118327_tutorial_5.c new file mode 100644 index 0000000000000000000000000000000000000000..5e8bbbb624a35168d02f0c8ede938e3d38847afe --- /dev/null +++ b/pool/shard006/C/0118327_tutorial_5.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015, 2016, 2017, Intel Corporation + * + * 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 LOG OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include + +#include "imbalancer.h" +#include "tutorial_region.h" + + +int main(int argc, char **argv) +{ + int size = 0; + int rank = 0; + + int err = MPI_Init(&argc, &argv); + if (!err) { + err = MPI_Comm_size(MPI_COMM_WORLD, &size); + } + if (!err) { + err = MPI_Comm_rank(MPI_COMM_WORLD, &rank); + } + if (!err && !rank) { + printf("MPI_COMM_WORLD size: %d\n", size); + } + + int num_iter = 10; + double stream_big_o = 1.0; + + if (!rank) { + printf("Beginning loop of %d iterations.\n", num_iter); + fflush(stdout); + } + for (int i = 0; !err && i < num_iter; ++i) { + err = geopm_prof_epoch(); + if (!err) { + err = tutorial_stream_profiled(stream_big_o, 0); + } + if (!err) { + err = MPI_Barrier(MPI_COMM_WORLD); + } + if (!err && !rank) { + printf("Iteration=%.3d\r", i); + fflush(stdout); + } + } + if (!err && !rank) { + printf("Completed loop. \n"); + fflush(stdout); + } + if (!err) { + err = MPI_Finalize(); + } + + return err; +} diff --git a/pool/shard006/C/0118329_test-0226.c b/pool/shard006/C/0118329_test-0226.c new file mode 100644 index 0000000000000000000000000000000000000000..aa42024ba30f0a8724f10ce3864863a3e6bbcf11 --- /dev/null +++ b/pool/shard006/C/0118329_test-0226.c @@ -0,0 +1,55 @@ +#include +#include + +struct item { + struct item *next; + void *data; +}; + +static void append(struct item **plist, void *data) +{ + struct item *item = malloc(sizeof *item); + item->next = *plist; + item->data = data; + *plist = item; +} + +int main() +{ + // allocate shared data + void *data = malloc(113U); + + // create SLS 2+ + struct item *list = NULL; + append(&list, data); + append(&list, data); + while (___sl_get_nondet_int()) + append(&list, data); + + // var-killer does NOT kill 'data' at this point + + while (list) { + struct item *next = list->next; + // the following #if causes a memleak +#if 0 + if (!next) + free(list->data); +#endif + ___sl_plot(NULL); + + free(list); + list = next; + } + + return !!data; +} + +/** + * @file test-0226.c + * + * @brief tiny modification of test-0225 that worked even before the fix + * + * @attention + * This description is automatically imported from tests/predator-regre/README. + * Any changes made to this comment will be thrown away on the next import. + */ diff --git a/pool/shard006/C/0118335_song.c b/pool/shard006/C/0118335_song.c new file mode 100644 index 0000000000000000000000000000000000000000..eff2211ad9d604a1820ca538b156c3e989b39cd6 --- /dev/null +++ b/pool/shard006/C/0118335_song.c @@ -0,0 +1,104 @@ +#include +#include + +unsigned int *p_per; +code unsigned int quarterNote = TEMPO * 4, eighthNote = TEMPO*2, sixteenthNote = TEMPO, halfNote = TEMPO * 8, wholeNote = TEMPO*16; +code unsigned int period[] = {C2, Db2, D2, Eb2, E2, F2, Gb2, G2, Ab2, A2, Bb2, B2, + C3, Db3, D3, Eb3, E3, F3, Gb3, G3, Ab3, A3, Bb3, B3, + C4, Db4, D4, Eb4, E4, F4, Gb4, G4, Ab4, A4, Bb4, B4, + C5, Db5, D5, Eb5, E5, F5, Gb5, G5, Ab5, A5, Bb5, B5, + C6, Db6, D6, Eb6, E6, F6, Gb6, G6, Ab6, A6, Bb6, B6, + C7}; +void clk( void ) interrupt 3 using 1 +{ + TH1=-(*p_per)>>8; + TL1=-(*p_per)&0x0ff; + SPKR = ~SPKR; +} + +void playConstantSong(char notes[], char length, int numNotes) +{ + int i, j; + for(i = 0; i < numNotes; i++) + { + playNote(notes[i], length); + + if (SW7 == 0) { + length/=2; + delayms(40); + } + else if(SW9 == 0) + { + length*=2; + delayms(40); + } + else if (SW1 == 0) { + while(SW1==0); + delayms(10); + break; + } + + j = 0; + } +} + +void playSong(char notes[], char lengths[], int numNotes) +{ + int i; + for(i = 0; i < numNotes; i++) + { + playNote(notes[i], lengths[i]); + } +} + +void playNote(char note, int noteType) +{ + int i; + int length; + p_per = &period[note]; + switch (noteType) + { + case 1: + length = wholeNote; + break; + case 2: + length = halfNote; + break; + case 4: + length = quarterNote; + break; + case 8: + length = eighthNote; + break; + case 16: + length = sixteenthNote; + break; + } + TH1=-(*p_per)>>8; + TL1=-(*p_per)&0x0ff; + ET1=1; + TR1=1; + + delayms(length); + TR1 = 0; + delayms(4); +} + +void delayms(int numMS) +{ + int i; + for(i = 0; i < numMS; i++) + { + delay1ms(); + } +} + +void delay1ms() +{ + TH0=-0x0E; + TL0=-0x66; + TR0 = 1; + while(TF0 == 0); + TR0 = 0; + TF0 = 0; +} diff --git a/pool/shard006/C/0118339_ex_screen.c b/pool/shard006/C/0118339_ex_screen.c new file mode 100644 index 0000000000000000000000000000000000000000..7bec2bc9ab1219581633cd3c2a2bde3338713637 --- /dev/null +++ b/pool/shard006/C/0118339_ex_screen.c @@ -0,0 +1,131 @@ +/*- + * Copyright (c) 1993, 1994 + * The Regents of the University of California. All rights reserved. + * Copyright (c) 1993, 1994, 1995, 1996 + * Keith Bostic. All rights reserved. + * + * See the LICENSE file for redistribution information. + */ + +#include "config.h" + +#ifndef lint +static const char sccsid[] = "$Id: ex_screen.c,v 10.12 2001/06/25 15:19:19 skimo Exp $"; +#endif /* not lint */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../common/common.h" +#include "../vi/vi.h" + +/* + * ex_bg -- :bg + * Hide the screen. + * + * PUBLIC: int ex_bg(SCR *, EXCMD *); + */ +int +ex_bg(SCR *sp, EXCMD *cmdp) +{ + return (vs_bg(sp)); +} + +/* + * ex_fg -- :fg [file] + * Show the screen. + * + * PUBLIC: int ex_fg(SCR *, EXCMD *); + */ +int +ex_fg(SCR *sp, EXCMD *cmdp) +{ + SCR *nsp; + int newscreen; + + newscreen = F_ISSET(cmdp, E_NEWSCREEN); + if (vs_fg(sp, &nsp, cmdp->argc ? cmdp->argv[0]->bp : NULL, newscreen)) + return (1); + + /* Set up the switch. */ + if (newscreen) { + sp->nextdisp = nsp; + F_SET(sp, SC_SSWITCH); + } + return (0); +} + +/* + * ex_resize -- :resize [+-]rows + * Change the screen size. + * + * PUBLIC: int ex_resize(SCR *, EXCMD *); + */ +int +ex_resize(SCR *sp, EXCMD *cmdp) +{ + adj_t adj; + + switch (FL_ISSET(cmdp->iflags, + E_C_COUNT | E_C_COUNT_NEG | E_C_COUNT_POS)) { + case E_C_COUNT: + adj = A_SET; + break; + case E_C_COUNT | E_C_COUNT_NEG: + adj = A_DECREASE; + break; + case E_C_COUNT | E_C_COUNT_POS: + adj = A_INCREASE; + break; + default: + ex_emsg(sp, cmdp->cmd->usage, EXM_USAGE); + return (1); + } + return (vs_resize(sp, cmdp->count, adj)); +} + +/* + * ex_sdisplay -- + * Display the list of screens. + * + * PUBLIC: int ex_sdisplay(SCR *); + */ +int +ex_sdisplay(SCR *sp) +{ + GS *gp; + SCR *tsp; + int cnt, col, len, sep; + + gp = sp->gp; + if ((tsp = TAILQ_FIRST(gp->hq)) == NULL) { + msgq(sp, M_INFO, "149|No background screens to display"); + return (0); + } + + col = len = sep = 0; + for (cnt = 1; tsp != NULL && !INTERRUPTED(sp); + tsp = TAILQ_NEXT(tsp, q)) { + col += len = strlen(tsp->frp->name) + sep; + if (col >= sp->cols - 1) { + col = len; + sep = 0; + (void)ex_puts(sp, "\n"); + } else if (cnt != 1) { + sep = 1; + (void)ex_puts(sp, " "); + } + (void)ex_puts(sp, tsp->frp->name); + ++cnt; + } + if (!INTERRUPTED(sp)) + (void)ex_puts(sp, "\n"); + return (0); +} diff --git a/pool/shard006/C/0118342_nand_partitions.c b/pool/shard006/C/0118342_nand_partitions.c new file mode 100644 index 0000000000000000000000000000000000000000..58643cf5f9fb4fe63dc9e45f0737d7064c4e5cf6 --- /dev/null +++ b/pool/shard006/C/0118342_nand_partitions.c @@ -0,0 +1,232 @@ +/* arch/arm/mach-msm/nand_partitions.c + * + * Code to extract partition information from ATAG set up by the + * bootloader. + * + * Copyright (C) 2007 Google, Inc. + * Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved. + * Author: Brian Swetland + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include + +#include +#include "smd_private.h" + + +/* configuration tags specific to msm */ + +#define ATAG_MSM_PARTITION 0x4d534D70 /* MSMp */ + +struct msm_ptbl_entry { + char name[16]; + __u32 offset; + __u32 size; + __u32 flags; +}; + +#ifdef CONFIG_VIRTUAL_KPANIC_PARTITION +#define MSM_MAX_PARTITIONS 9 +#else +#define MSM_MAX_PARTITIONS 8 +#endif + +static struct mtd_partition msm_nand_partitions[MSM_MAX_PARTITIONS]; +static char msm_nand_names[MSM_MAX_PARTITIONS * 16]; + +extern struct flash_platform_data msm_nand_data; + +static int __init parse_tag_msm_partition(const struct tag *tag) +{ + struct mtd_partition *ptn = msm_nand_partitions; + char *name = msm_nand_names; + struct msm_ptbl_entry *entry = (void *) &tag->u; + unsigned count, n; + unsigned have_kpanic = 0; + + count = (tag->hdr.size - 2) / + (sizeof(struct msm_ptbl_entry) / sizeof(__u32)); + + if (count > MSM_MAX_PARTITIONS) + count = MSM_MAX_PARTITIONS; + + for (n = 0; n < count; n++) { + memcpy(name, entry->name, 15); + name[15] = 0; + + if (!strcmp(name, "kpanic")) + have_kpanic = 1; + + ptn->name = name; + ptn->offset = entry->offset; + ptn->size = entry->size; + + printk(KERN_INFO "Partition (from atag) %s " + "-- Offset:%llx Size:%llx\n", + ptn->name, ptn->offset, ptn->size); + + name += 16; + entry++; + ptn++; + } + +#ifdef CONFIG_VIRTUAL_KPANIC_PARTITION + if (!have_kpanic) { + int i; + uint64_t kpanic_off = 0; + + if (count == MSM_MAX_PARTITIONS) { + printk("Cannot create virtual 'kpanic' partition\n"); + goto out; + } + + for (i = 0; i < count; i++) { + ptn = &msm_nand_partitions[i]; + if (!strcmp(ptn->name, CONFIG_VIRTUAL_KPANIC_SRC)) { + ptn->size -= CONFIG_VIRTUAL_KPANIC_PSIZE; + kpanic_off = ptn->offset + ptn->size; + break; + } + } + if (i == count) { + printk(KERN_ERR "Partition %s not found\n", + CONFIG_VIRTUAL_KPANIC_SRC); + goto out; + } + + ptn = &msm_nand_partitions[count]; + ptn->name ="kpanic"; + ptn->offset = kpanic_off; + ptn->size = CONFIG_VIRTUAL_KPANIC_PSIZE; + + printk("Virtual mtd partition '%s' created @%llx (%llu)\n", + ptn->name, ptn->offset, ptn->size); + + count++; + } +out: +#endif /* CONFIG_VIRTUAL_KPANIC_SRC */ + msm_nand_data.nr_parts = count; + msm_nand_data.parts = msm_nand_partitions; + + return 0; +} + +__tagtable(ATAG_MSM_PARTITION, parse_tag_msm_partition); + +#define FLASH_PART_MAGIC1 0x55EE73AA +#define FLASH_PART_MAGIC2 0xE35EBDDB +#define FLASH_PARTITION_VERSION 0x3 + +#define LINUX_FS_PARTITION_NAME "0:EFS2APPS" + +struct flash_partition_entry { + char name[16]; + u32 offset; /* Offset in blocks from beginning of device */ + u32 length; /* Length of the partition in blocks */ + u8 attrib1; + u8 attrib2; + u8 attrib3; + u8 which_flash; /* Numeric ID (first = 0, second = 1) */ +}; +struct flash_partition_table { + u32 magic1; + u32 magic2; + u32 version; + u32 numparts; + struct flash_partition_entry part_entry[16]; +}; + +static int get_nand_partitions(void) +{ + struct flash_partition_table *partition_table; + struct flash_partition_entry *part_entry; + struct mtd_partition *ptn = msm_nand_partitions; + char *name = msm_nand_names; + int part; + + if (msm_nand_data.nr_parts) + return 0; + + partition_table = (struct flash_partition_table *) + smem_alloc(SMEM_AARM_PARTITION_TABLE, + sizeof(struct flash_partition_table)); + + if (!partition_table) { + printk(KERN_WARNING "%s: no flash partition table in shared " + "memory\n", __func__); + return -ENOENT; + } + + if ((partition_table->magic1 != (u32) FLASH_PART_MAGIC1) || + (partition_table->magic2 != (u32) FLASH_PART_MAGIC2) || + (partition_table->version != (u32) FLASH_PARTITION_VERSION)) { + printk(KERN_WARNING "%s: version mismatch -- magic1=%#x, " + "magic2=%#x, version=%#x\n", __func__, + partition_table->magic1, + partition_table->magic2, + partition_table->version); + return -EFAULT; + } + + msm_nand_data.nr_parts = 0; + + /* Get the LINUX FS partition info */ + for (part = 0; part < partition_table->numparts; part++) { + part_entry = &partition_table->part_entry[part]; + + /* Find a match for the Linux file system partition */ + if (strcmp(part_entry->name, LINUX_FS_PARTITION_NAME) == 0) { + strcpy(name, part_entry->name); + ptn->name = name; + + /*TODO: Get block count and size info */ + ptn->offset = part_entry->offset; + + /* For SMEM, -1 indicates remaining space in flash, + * but for MTD it is 0 + */ + if (part_entry->length == (u32)-1) + ptn->size = 0; + else + ptn->size = part_entry->length; + + msm_nand_data.nr_parts = 1; + msm_nand_data.parts = msm_nand_partitions; + + printk(KERN_INFO "Partition(from smem) %s " + "-- Offset:%llx Size:%llx\n", + ptn->name, ptn->offset, ptn->size); + + return 0; + } + } + + printk(KERN_WARNING "%s: no partition table found!", __func__); + + return -ENODEV; +} + +device_initcall(get_nand_partitions); diff --git a/pool/shard006/C/0118347_ShortURL.c b/pool/shard006/C/0118347_ShortURL.c new file mode 100644 index 0000000000000000000000000000000000000000..2a63d77df71587a8faa06d594cf6f95adfc6c733 --- /dev/null +++ b/pool/shard006/C/0118347_ShortURL.c @@ -0,0 +1,76 @@ +/* + * ShortURL (https://github.com/delight-im/ShortURL) + * Copyright (c) delight.im (https://www.delight.im/) + * Licensed under the MIT License (https://opensource.org/licenses/MIT) + */ + +/* + * ShortURL: Bijective conversion between natural numbers (IDs) and short strings + * + * url_encode() takes an ID and turns it into a short string and writes it into a buffer + * url_decode() takes a short string and turns it into an ID + * + * Features: + * + large alphabet (51 chars) and thus very short resulting strings + * + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u') + * + unambiguous (removed 'I', 'l', '1', 'O' and '0') + * + * Example output: + * 123456789 <=> pgK8p + */ + +#include +#include +#include + +const char alphabet[] = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"; +const size_t base = sizeof(alphabet) / sizeof(alphabet[0]) - 1; + +// buff is a pre-allocated buffer provided by the caller, e.g. char[100] +// buffsize is the pre-allocated buffer's size, e.g. 100 +size_t url_encode(char *buff, size_t buffsize, int num) { + size_t idx = 0; + size_t i; + + while (num > 0 && idx < buffsize) { + buff[idx++] = alphabet[num % base]; + num /= base; + } + + // if the buffer is not large enough + if (idx == buffsize) { + // fail + return -1; + } + + // add a null terminator + buff[idx] = '\0'; + + // reverse the encoded string + for (i = 0; i < idx / 2; ++i) { + char t = buff[i]; + buff[i] = buff[idx - i - 1]; + buff[idx - i - 1] = t; + } + + // return the length of the encoded string + return idx; +} + +int url_decode(const char *url) { + int num = 0; + size_t idx, i, j, len; + + len = strlen(url); + + for (i = 0; i < len; ++i) { + // locate the char in the alphabet + for (j = 0; j <= base && alphabet[j] != url[i]; ++j); + + if (j > base) return INT_MAX; + + num = num * base + j; + } + + return num; +} diff --git a/pool/shard006/C/0118350_fsync02.c b/pool/shard006/C/0118350_fsync02.c new file mode 100644 index 0000000000000000000000000000000000000000..1e5f9ee0099b5354c53db96078f48eb2c8f82be4 --- /dev/null +++ b/pool/shard006/C/0118350_fsync02.c @@ -0,0 +1,195 @@ +/* + * + * Copyright (c) International Business Machines Corp., 2001 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* + * NAME + * fsync02.c + * + * DESCRIPTION + * Create a sparse file, fsync it, and time the fsync + * + * ALGORITHM + * 1. Create a file. + * 2. Write to the file at equally spaced intervals up to a max block + * 3. Check if the time limit was exceeded. + * + * USAGE: + * fsync02 [-c n] [-f] [-i n] [-I x] [-P x] [-t] + * where, -c n : Run n copies concurrently. + * -f : Turn off functionality Testing. + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + * + * HISTORY + * 07/2001 Ported by Wayne Boyer + * + * RESTRICTIONS + * None + */ + +#include +#include +#include +#include +#include +#include +#include +#include "test.h" +#include "safe_macros.h" +#include + +#define BLOCKSIZE 8192 +#define MAXBLKS 262144 +#define TIME_LIMIT 120 + +char *TCID = "fsync02"; +int TST_TOTAL = 1; + +void setup(void); +void cleanup(void); + +char tempfile[40] = ""; +int fd, pid; +off_t max_blks = MAXBLKS; + +struct statvfs stat_buf; + +int main(int ac, char **av) +{ + int lc; + + off_t offsetret, offset; + char pbuf[BUFSIZ]; + int ret, max_block = 0; + int i; + time_t time_start, time_end; + double time_delta; + int data_blocks = 0; + long int random_number; + + tst_parse_opts(ac, av, NULL, NULL); + + setup(); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + tst_count = 0; + + while (max_block <= data_blocks) { + random_number = random(); + max_block = random_number % max_blks; + data_blocks = random_number % 1000 + 1; + } + + for (i = 1; i <= data_blocks; i++) { + offset = i * ((BLOCKSIZE * max_block) / data_blocks); + offset -= BUFSIZ; + if ((offsetret = lseek(fd, offset, SEEK_SET)) != offset) + tst_brkm(TBROK | TERRNO, cleanup, + "lseek failed: %ld, %ld", offsetret, + offset); + if ((ret = write(fd, pbuf, BUFSIZ)) != BUFSIZ) + tst_brkm(TBROK, cleanup, "write failed"); + } + if (time(&time_start) == -1) + tst_brkm(TBROK | TERRNO, cleanup, + "getting start time failed"); + + TEST(fsync(fd)); + + if (time(&time_end) == -1) + tst_brkm(TBROK | TERRNO, cleanup, + "getting end time failed"); + + if (TEST_RETURN == -1) { + tst_resm(TFAIL | TTERRNO, "fsync failed"); + continue; + } + + if (time_end < time_start) + tst_resm(TBROK, + "timer broken end %ld < start %ld", + time_end, time_start); + + if ((time_delta = + difftime(time_end, time_start)) > TIME_LIMIT) + tst_resm(TFAIL, + "fsync took too long: %lf seconds; " + "max_block: %d; data_blocks: %d", + time_delta, max_block, data_blocks); + else + tst_resm(TPASS, "fsync succeeded in an " + "acceptable amount of time"); + + SAFE_FTRUNCATE(cleanup, fd, 0); + } + + sync(); + cleanup(); + tst_exit(); +} + +/* + * setup() - performs all ONE TIME setup for this test. + */ +void setup(void) +{ + /* free blocks avail to non-superuser */ + unsigned long f_bavail; + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + + /* make a temporary directory and cd to it */ + tst_tmpdir(); + + sprintf(tempfile, "%s.%d", TCID, pid = getpid()); + srand48(pid); + + if ((fd = open(tempfile, O_RDWR | O_CREAT | O_TRUNC, 0777)) == -1) + tst_brkm(TBROK, cleanup, "open failed"); + + if (fstatvfs(fd, &stat_buf) != 0) + tst_brkm(TBROK, cleanup, "fstatvfs failed"); + + f_bavail = (stat_buf.f_bavail * stat_buf.f_frsize) / BLOCKSIZE; + if (f_bavail && (f_bavail < MAXBLKS)) + max_blks = f_bavail; + +#ifdef LARGEFILE + if ((fcntl(fd, F_SETFL, O_LARGEFILE)) == -1) + tst_brkm(TBROK | TERRNO, cleanup, + "fcntl(.., O_LARGEFILE) failed"); + + if (write(fd, pbuf, BUFSIZ) != BUFSIZ) + tst_brkm(TBROK | TERRNO, cleanup, "write(fd, pbuf, ..) failed"); +#endif +} + +void cleanup(void) +{ + if (close(fd) == -1) + tst_resm(TWARN | TERRNO, "close failed"); + + tst_rmdir(); + +} diff --git a/pool/shard006/C/0118357_initializers.c b/pool/shard006/C/0118357_initializers.c new file mode 100644 index 0000000000000000000000000000000000000000..ee920bcadf50b758ceed12762443d9ad23991d23 --- /dev/null +++ b/pool/shard006/C/0118357_initializers.c @@ -0,0 +1,69 @@ + + +#include + +#include "usb.h" +#include "initializers.h" +#include "debug.h" +#include "transport.h" + + +int usb_stor_euscsi_init(struct us_data *us) +{ + int result; + + US_DEBUGP("Attempting to init eUSCSI bridge...\n"); + us->iobuf[0] = 0x1; + result = usb_stor_control_msg(us, us->send_ctrl_pipe, + 0x0C, USB_RECIP_INTERFACE | USB_TYPE_VENDOR, + 0x01, 0x0, us->iobuf, 0x1, 5000); + US_DEBUGP("-- result is %d\n", result); + + return 0; +} + + +int usb_stor_ucr61s2b_init(struct us_data *us) +{ + struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap*) us->iobuf; + struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap*) us->iobuf; + int res; + unsigned int partial; + static char init_string[] = "\xec\x0a\x06\x00$PCCHIPS"; + + US_DEBUGP("Sending UCR-61S2B initialization packet...\n"); + + bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN); + bcb->Tag = 0; + bcb->DataTransferLength = cpu_to_le32(0); + bcb->Flags = bcb->Lun = 0; + bcb->Length = sizeof(init_string) - 1; + memset(bcb->CDB, 0, sizeof(bcb->CDB)); + memcpy(bcb->CDB, init_string, sizeof(init_string) - 1); + + res = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, bcb, + US_BULK_CB_WRAP_LEN, &partial); + if (res) + return -EIO; + + US_DEBUGP("Getting status packet...\n"); + res = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, bcs, + US_BULK_CS_WRAP_LEN, &partial); + if (res) + return -EIO; + + return 0; +} + + +int usb_stor_huawei_e220_init(struct us_data *us) +{ + int result; + + result = usb_stor_control_msg(us, us->send_ctrl_pipe, + USB_REQ_SET_FEATURE, + USB_TYPE_STANDARD | USB_RECIP_DEVICE, + 0x01, 0x0, NULL, 0x0, 1000); + US_DEBUGP("Huawei mode set result is %d\n", result); + return 0; +} diff --git a/pool/shard006/C/0118364_my_printf.c b/pool/shard006/C/0118364_my_printf.c new file mode 100644 index 0000000000000000000000000000000000000000..99013014ba919e83f89ce0d1cd6b24e8d1b82c77 --- /dev/null +++ b/pool/shard006/C/0118364_my_printf.c @@ -0,0 +1,40 @@ +/* +** my_printf.c for mysh in /home/pirou_g/minishell2/src +** +** Made by Guillaume Pirou +** Login +** +** Started on Sun Feb 1 08:30:40 2015 Guillaume Pirou +** Last update Fri May 15 21:00:55 2015 guigui +*/ + +#include +#include +#include "my_printf.h" +#include "my.h" + +int my_printf(const char *format, ...) +{ + int i; + va_list list; + int cp; + + if (format == NULL) + return (-1); + i = -1; + va_start(list, format); + while (format[++i] != '\0') + { + if (format[i] != '%') + my_putchar(format[i]); + else + { + cp = i; + i += my_parse_format(format + i, &list); + if (i < cp) + return (-1); + } + } + va_end(list); + return (0); +} diff --git a/pool/shard006/C/0118365_cpress.c b/pool/shard006/C/0118365_cpress.c new file mode 100644 index 0000000000000000000000000000000000000000..9a3782a0c3b2b06ce0a785565e8371c8a633fa2a --- /dev/null +++ b/pool/shard006/C/0118365_cpress.c @@ -0,0 +1,435 @@ +/* +cpress - C library for simulating keypress. + +Requirements: +- Linux +- running uinput (modprobe uinput) +- root privileges + +There are Python and Go bindings for this library. + +------------------------------------------------------------------------------- + +License: MIT (http://www.opensource.org/licenses/mit-license.php) +Repository: https://github.com/solusipse/cpress + +------------------------------------------------------------------------------- +*/ + +#include "cpress.h" + +void initialize() +{ + /* This function is used for initializing everything. */ + + check_permissions(); + + uinput = fd_initialize(); + if(uinput == -1) + error("initialization"); + + usleep(10000); /* That is required because /dev/input + needs some time for creating new input. */ +} + + +void finish() +{ + /* Use this function at the end to clean up. */ + ioctl(uinput, UI_DEV_DESTROY); + close(uinput); +} + + +void press_key(int key) +{ + /* This function is used for simulating single + press and release action. */ + ci_write(EV_KEY, key, 1); + ci_write(EV_KEY, key, 0); + ci_write(EV_SYN, SYN_REPORT, 0); +} + + +void hold_key(int key) +{ + /* Use this to add modifiers, for example KEY_LEFTSHIFT */ + ci_write(EV_KEY, key, 1); + ci_write(EV_SYN, SYN_REPORT, 0); +} + + +void release_key(int key) +{ + /* Used to release keys triggered by hold_key() */ + ci_write(EV_KEY, key, 0); + ci_write(EV_SYN, SYN_REPORT, 0); +} + + +void press_combination(int num_args, ...) +{ + /* This function is used for simulating multiple + keys pressed in one moment. */ + va_list keylist; + int i; + + va_start(keylist, num_args); + for(i = 0; i < num_args + 1; i++) + { + ci_write(EV_KEY, va_arg(keylist, int), 1); + } + va_end(keylist); + + ci_write(EV_SYN, SYN_REPORT, 0); + + va_start(keylist, num_args); + for(i = 0; i < num_args + 1; i++) + { + ci_write(EV_KEY, va_arg(keylist, int), 0); + } + va_end(keylist); + + ci_write(EV_SYN, SYN_REPORT, 0); +} + + +void ci_write(int type, int code, int value) +{ + struct input_event ie; + + memset(&ie, 0, sizeof(ie)); + ie.type = type; + ie.code = code; + ie.value = value; + + if(write(uinput, &ie, sizeof(ie)) != sizeof(ie)) + error("write"); +} + + +int open_uinput() +{ + int fd; + + if ((fd = open("/dev/input/uinput", O_WRONLY | O_NONBLOCK)) == -1) + if ((fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK)) == -1) + if ((fd = open("/dev/misc/uinput", O_WRONLY | O_NONBLOCK)) == -1) + { + printf("No enough permissions to write to uinput.\n"); + exit(1); + } + + return fd; +} + + +int fd_initialize() +{ + /* This function is used for initialization, it is called internally + by initialization() */ + int fd, key; + struct uinput_user_dev dev; + + fd = open_uinput(); + + memset(&dev, 0, sizeof(dev)); + strncpy(dev.name, "c2h2_spi_kbd", UINPUT_MAX_NAME_SIZE); + + + if(write(fd, &dev, sizeof(dev)) != sizeof(dev)) + return -1; + + for (key = 0; key < 256; key++) + if (ioctl(fd, UI_SET_KEYBIT, key) != 0) + return -1; + + if(ioctl(fd, UI_SET_EVBIT, EV_KEY) != 0) + return -1; + + if(ioctl(fd, UI_SET_EVBIT, EV_REP) != 0) + return -1; + + if (ioctl(fd, UI_DEV_CREATE) != 0) + return -1; + + return fd; +} + +void ask_for_password() +{ + /* This function asks for root password and changes + mode of uinput */ + if (access("/dev/input/uinput", F_OK) == 0) + system("su -c \"chmod +0666 /dev/input/uinput\""); + if (access("/dev/uinput", F_OK) == 0) + system("su -c \"chmod +0666 /dev/uinput\""); + if (access("/dev/misc/uinput", F_OK) == 0) + system("su -c \"chmod +0666 /dev/misc/uinput\""); +} + +void check_permissions() +{ + /* If there are not enough permissions to write to uinput, + this function calls ask_for_password() */ + if (access("/dev/input/uinput", W_OK) == -1) + if (access("/dev/uinput", W_OK) == -1) + if (access("/dev/misc/uinput", W_OK) == -1) + ask_for_password(); +} + + +void error(char *error_code) +{ + perror(error_code); + exit(1); +} + +/* keylist from linux/uinput.h + +#define KEY_RESERVED 0 +#define KEY_ESC 1 +#define KEY_1 2 +#define KEY_2 3 +#define KEY_3 4 +#define KEY_4 5 +#define KEY_5 6 +#define KEY_6 7 +#define KEY_7 8 +#define KEY_8 9 +#define KEY_9 10 +#define KEY_0 11 +#define KEY_MINUS 12 +#define KEY_EQUAL 13 +#define KEY_BACKSPACE 14 +#define KEY_TAB 15 +#define KEY_Q 16 +#define KEY_W 17 +#define KEY_E 18 +#define KEY_R 19 +#define KEY_T 20 +#define KEY_Y 21 +#define KEY_U 22 +#define KEY_I 23 +#define KEY_O 24 +#define KEY_P 25 +#define KEY_LEFTBRACE 26 +#define KEY_RIGHTBRACE 27 +#define KEY_ENTER 28 +#define KEY_LEFTCTRL 29 +#define KEY_A 30 +#define KEY_S 31 +#define KEY_D 32 +#define KEY_F 33 +#define KEY_G 34 +#define KEY_H 35 +#define KEY_J 36 +#define KEY_K 37 +#define KEY_L 38 +#define KEY_SEMICOLON 39 +#define KEY_APOSTROPHE 40 +#define KEY_GRAVE 41 +#define KEY_LEFTSHIFT 42 +#define KEY_BACKSLASH 43 +#define KEY_Z 44 +#define KEY_X 45 +#define KEY_C 46 +#define KEY_V 47 +#define KEY_B 48 +#define KEY_N 49 +#define KEY_M 50 +#define KEY_COMMA 51 +#define KEY_DOT 52 +#define KEY_SLASH 53 +#define KEY_RIGHTSHIFT 54 +#define KEY_KPASTERISK 55 +#define KEY_LEFTALT 56 +#define KEY_SPACE 57 +#define KEY_CAPSLOCK 58 +#define KEY_F1 59 +#define KEY_F2 60 +#define KEY_F3 61 +#define KEY_F4 62 +#define KEY_F5 63 +#define KEY_F6 64 +#define KEY_F7 65 +#define KEY_F8 66 +#define KEY_F9 67 +#define KEY_F10 68 +#define KEY_NUMLOCK 69 +#define KEY_SCROLLLOCK 70 +#define KEY_KP7 71 +#define KEY_KP8 72 +#define KEY_KP9 73 +#define KEY_KPMINUS 74 +#define KEY_KP4 75 +#define KEY_KP5 76 +#define KEY_KP6 77 +#define KEY_KPPLUS 78 +#define KEY_KP1 79 +#define KEY_KP2 80 +#define KEY_KP3 81 +#define KEY_KP0 82 +#define KEY_KPDOT 83 +#define KEY_ZENKAKUHANKAKU 85 +#define KEY_102ND 86 +#define KEY_F11 87 +#define KEY_F12 88 +#define KEY_RO 89 +#define KEY_KATAKANA 90 +#define KEY_HIRAGANA 91 +#define KEY_HENKAN 92 +#define KEY_KATAKANAHIRAGANA 93 +#define KEY_MUHENKAN 94 +#define KEY_KPJPCOMMA 95 +#define KEY_KPENTER 96 +#define KEY_RIGHTCTRL 97 +#define KEY_KPSLASH 98 +#define KEY_SYSRQ 99 +#define KEY_RIGHTALT 100 +#define KEY_LINEFEED 101 +#define KEY_HOME 102 +#define KEY_UP 103 +#define KEY_PAGEUP 104 +#define KEY_LEFT 105 +#define KEY_RIGHT 106 +#define KEY_END 107 +#define KEY_DOWN 108 +#define KEY_PAGEDOWN 109 +#define KEY_INSERT 110 +#define KEY_DELETE 111 +#define KEY_MACRO 112 +#define KEY_MUTE 113 +#define KEY_VOLUMEDOWN 114 +#define KEY_VOLUMEUP 115 +#define KEY_POWER 116 +#define KEY_KPEQUAL 117 +#define KEY_KPPLUSMINUS 118 +#define KEY_PAUSE 119 +#define KEY_SCALE 120 +#define KEY_KPCOMMA 121 +#define KEY_HANGEUL 122 +#define KEY_HANGUEL KEY_HANGEUL +#define KEY_HANJA 123 +#define KEY_YEN 124 +#define KEY_LEFTMETA 125 +#define KEY_RIGHTMETA 126 +#define KEY_COMPOSE 127 +#define KEY_STOP 128 +#define KEY_AGAIN 129 +#define KEY_PROPS 130 +#define KEY_UNDO 131 +#define KEY_FRONT 132 +#define KEY_COPY 133 +#define KEY_OPEN 134 +#define KEY_PASTE 135 +#define KEY_FIND 136 +#define KEY_CUT 137 +#define KEY_HELP 138 +#define KEY_MENU 139 +#define KEY_CALC 140 +#define KEY_SETUP 141 +#define KEY_SLEEP 142 +#define KEY_WAKEUP 143 +#define KEY_FILE 144 +#define KEY_SENDFILE 145 +#define KEY_DELETEFILE 146 +#define KEY_XFER 147 +#define KEY_PROG1 148 +#define KEY_PROG2 149 +#define KEY_WWW 150 +#define KEY_MSDOS 151 +#define KEY_COFFEE 152 +#define KEY_SCREENLOCK KEY_COFFEE +#define KEY_DIRECTION 153 +#define KEY_CYCLEWINDOWS 154 +#define KEY_MAIL 155 +#define KEY_BOOKMARKS 156 +#define KEY_COMPUTER 157 +#define KEY_BACK 158 +#define KEY_FORWARD 159 +#define KEY_CLOSECD 160 +#define KEY_EJECTCD 161 +#define KEY_EJECTCLOSECD 162 +#define KEY_NEXTSONG 163 +#define KEY_PLAYPAUSE 164 +#define KEY_PREVIOUSSONG 165 +#define KEY_STOPCD 166 +#define KEY_RECORD 167 +#define KEY_REWIND 168 +#define KEY_PHONE 169 +#define KEY_ISO 170 +#define KEY_CONFIG 171 +#define KEY_HOMEPAGE 172 +#define KEY_REFRESH 173 +#define KEY_EXIT 174 +#define KEY_MOVE 175 +#define KEY_EDIT 176 +#define KEY_SCROLLUP 177 +#define KEY_SCROLLDOWN 178 +#define KEY_KPLEFTPAREN 179 +#define KEY_KPRIGHTPAREN 180 +#define KEY_NEW 181 +#define KEY_REDO 182 +#define KEY_F13 183 +#define KEY_F14 184 +#define KEY_F15 185 +#define KEY_F16 186 +#define KEY_F17 187 +#define KEY_F18 188 +#define KEY_F19 189 +#define KEY_F20 190 +#define KEY_F21 191 +#define KEY_F22 192 +#define KEY_F23 193 +#define KEY_F24 194 +#define KEY_PLAYCD 200 +#define KEY_PAUSECD 201 +#define KEY_PROG3 202 +#define KEY_PROG4 203 +#define KEY_DASHBOARD 204 +#define KEY_SUSPEND 205 +#define KEY_CLOSE 206 +#define KEY_PLAY 207 +#define KEY_FASTFORWARD 208 +#define KEY_BASSBOOST 209 +#define KEY_PRINT 210 +#define KEY_HP 211 +#define KEY_CAMERA 212 +#define KEY_SOUND 213 +#define KEY_QUESTION 214 +#define KEY_EMAIL 215 +#define KEY_CHAT 216 +#define KEY_SEARCH 217 +#define KEY_CONNECT 218 +#define KEY_FINANCE 219 +#define KEY_SPORT 220 +#define KEY_SHOP 221 +#define KEY_ALTERASE 222 +#define KEY_CANCEL 223 +#define KEY_BRIGHTNESSDOWN 224 +#define KEY_BRIGHTNESSUP 225 +#define KEY_MEDIA 226 +#define KEY_SWITCHVIDEOMODE 227 +#define KEY_KBDILLUMTOGGLE 228 +#define KEY_KBDILLUMDOWN 229 +#define KEY_KBDILLUMUP 230 +#define KEY_SEND 231 +#define KEY_REPLY 232 +#define KEY_FORWARDMAIL 233 +#define KEY_SAVE 234 +#define KEY_DOCUMENTS 235 +#define KEY_BATTERY 236 +#define KEY_BLUETOOTH 237 +#define KEY_WLAN 238 +#define KEY_UWB 239 +#define KEY_UNKNOWN 240 +#define KEY_VIDEO_NEXT 241 +#define KEY_VIDEO_PREV 242 +#define KEY_BRIGHTNESS_CYCLE 243 +#define KEY_BRIGHTNESS_ZERO 244 +#define KEY_DISPLAY_OFF 245 +#define KEY_WIMAX 246 +#define KEY_RFKILL 247 +#define KEY_MICMUTE 248 +*/ diff --git a/pool/shard006/C/0118366_sam9g20_wm8731.c b/pool/shard006/C/0118366_sam9g20_wm8731.c new file mode 100644 index 0000000000000000000000000000000000000000..5cef225ef1a8cf32099d5054af407a11c1c45511 --- /dev/null +++ b/pool/shard006/C/0118366_sam9g20_wm8731.c @@ -0,0 +1,280 @@ +/* + * sam9g20_wm8731 -- SoC audio for AT91SAM9G20-based + * ATMEL AT91SAM9G20ek board. + * + * Copyright (C) 2005 SAN People + * Copyright (C) 2008 Atmel + * + * Authors: Sedji Gaouaou + * + * Based on ati_b1_wm8731.c by: + * Frank Mandarino + * Copyright 2006 Endrelia Technologies Inc. + * Based on corgi.c by: + * Copyright 2005 Wolfson Microelectronics PLC. + * Copyright 2005 Openedhand Ltd. + * + * 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 +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include "../codecs/wm8731.h" +#include "atmel-pcm.h" +#include "atmel_ssc_dai.h" + +#define MCLK_RATE 12000000 + +/* + * As shipped the board does not have inputs. However, it is relatively + * straightforward to modify the board to hook them up so support is left + * in the driver. + */ +#undef ENABLE_MIC_INPUT + +static struct clk *mclk; + +static int at91sam9g20ek_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; + int ret; + + /* set codec DAI configuration */ + ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); + if (ret < 0) + return ret; + + /* set cpu DAI configuration */ + ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); + if (ret < 0) + return ret; + + return 0; +} + +static struct snd_soc_ops at91sam9g20ek_ops = { + .hw_params = at91sam9g20ek_hw_params, +}; + +static int at91sam9g20ek_set_bias_level(struct snd_soc_card *card, + struct snd_soc_dapm_context *dapm, + enum snd_soc_bias_level level) +{ + static int mclk_on; + int ret = 0; + + switch (level) { + case SND_SOC_BIAS_ON: + case SND_SOC_BIAS_PREPARE: + if (!mclk_on) + ret = clk_enable(mclk); + if (ret == 0) + mclk_on = 1; + break; + + case SND_SOC_BIAS_OFF: + case SND_SOC_BIAS_STANDBY: + if (mclk_on) + clk_disable(mclk); + mclk_on = 0; + break; + } + + return ret; +} + +static const struct snd_soc_dapm_widget at91sam9g20ek_dapm_widgets[] = { + SND_SOC_DAPM_MIC("Int Mic", NULL), + SND_SOC_DAPM_SPK("Ext Spk", NULL), +}; + +static const struct snd_soc_dapm_route intercon[] = { + + /* speaker connected to LHPOUT */ + {"Ext Spk", NULL, "LHPOUT"}, + + /* mic is connected to Mic Jack, with WM8731 Mic Bias */ + {"MICIN", NULL, "Mic Bias"}, + {"Mic Bias", NULL, "Int Mic"}, +}; + +/* + * Logic for a wm8731 as connected on a at91sam9g20ek board. + */ +static int at91sam9g20ek_wm8731_init(struct snd_soc_pcm_runtime *rtd) +{ + struct snd_soc_codec *codec = rtd->codec; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + struct snd_soc_dapm_context *dapm = &codec->dapm; + int ret; + + printk(KERN_DEBUG + "at91sam9g20ek_wm8731 " + ": at91sam9g20ek_wm8731_init() called\n"); + + ret = snd_soc_dai_set_sysclk(codec_dai, WM8731_SYSCLK_MCLK, + MCLK_RATE, SND_SOC_CLOCK_IN); + if (ret < 0) { + printk(KERN_ERR "Failed to set WM8731 SYSCLK: %d\n", ret); + return ret; + } + + /* Add specific widgets */ + snd_soc_dapm_new_controls(dapm, at91sam9g20ek_dapm_widgets, + ARRAY_SIZE(at91sam9g20ek_dapm_widgets)); + /* Set up specific audio path interconnects */ + snd_soc_dapm_add_routes(dapm, intercon, ARRAY_SIZE(intercon)); + + /* not connected */ + snd_soc_dapm_nc_pin(dapm, "RLINEIN"); + snd_soc_dapm_nc_pin(dapm, "LLINEIN"); + +#ifdef ENABLE_MIC_INPUT + snd_soc_dapm_enable_pin(dapm, "Int Mic"); +#else + snd_soc_dapm_nc_pin(dapm, "Int Mic"); +#endif + + /* always connected */ + snd_soc_dapm_enable_pin(dapm, "Ext Spk"); + + return 0; +} + +static struct snd_soc_dai_link at91sam9g20ek_dai = { + .name = "WM8731", + .stream_name = "WM8731 PCM", + .cpu_dai_name = "atmel-ssc-dai.0", + .codec_dai_name = "wm8731-hifi", + .init = at91sam9g20ek_wm8731_init, + .platform_name = "atmel-pcm-audio", + .codec_name = "wm8731.0-001b", + .ops = &at91sam9g20ek_ops, +}; + +static struct snd_soc_card snd_soc_at91sam9g20ek = { + .name = "AT91SAMG20-EK", + .owner = THIS_MODULE, + .dai_link = &at91sam9g20ek_dai, + .num_links = 1, + .set_bias_level = at91sam9g20ek_set_bias_level, +}; + +static struct platform_device *at91sam9g20ek_snd_device; + +static int __init at91sam9g20ek_init(void) +{ + struct clk *pllb; + int ret; + + if (!(machine_is_at91sam9g20ek() || machine_is_at91sam9g20ek_2mmc())) + return -ENODEV; + + ret = atmel_ssc_set_audio(0); + if (ret != 0) { + pr_err("Failed to set SSC 0 for audio: %d\n", ret); + return ret; + } + + /* + * Codec MCLK is supplied by PCK0 - set it up. + */ + mclk = clk_get(NULL, "pck0"); + if (IS_ERR(mclk)) { + printk(KERN_ERR "ASoC: Failed to get MCLK\n"); + ret = PTR_ERR(mclk); + goto err; + } + + pllb = clk_get(NULL, "pllb"); + if (IS_ERR(pllb)) { + printk(KERN_ERR "ASoC: Failed to get PLLB\n"); + ret = PTR_ERR(pllb); + goto err_mclk; + } + ret = clk_set_parent(mclk, pllb); + clk_put(pllb); + if (ret != 0) { + printk(KERN_ERR "ASoC: Failed to set MCLK parent\n"); + goto err_mclk; + } + + clk_set_rate(mclk, MCLK_RATE); + + at91sam9g20ek_snd_device = platform_device_alloc("soc-audio", -1); + if (!at91sam9g20ek_snd_device) { + printk(KERN_ERR "ASoC: Platform device allocation failed\n"); + ret = -ENOMEM; + goto err_mclk; + } + + platform_set_drvdata(at91sam9g20ek_snd_device, + &snd_soc_at91sam9g20ek); + + ret = platform_device_add(at91sam9g20ek_snd_device); + if (ret) { + printk(KERN_ERR "ASoC: Platform device allocation failed\n"); + goto err_device_add; + } + + return ret; + +err_device_add: + platform_device_put(at91sam9g20ek_snd_device); +err_mclk: + clk_put(mclk); + mclk = NULL; +err: + return ret; +} + +static void __exit at91sam9g20ek_exit(void) +{ + platform_device_unregister(at91sam9g20ek_snd_device); + at91sam9g20ek_snd_device = NULL; + clk_put(mclk); + mclk = NULL; +} + +module_init(at91sam9g20ek_init); +module_exit(at91sam9g20ek_exit); + +/* Module information */ +MODULE_AUTHOR("Sedji Gaouaou "); +MODULE_DESCRIPTION("ALSA SoC AT91SAM9G20EK_WM8731"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0118371_playback.c b/pool/shard006/C/0118371_playback.c new file mode 100644 index 0000000000000000000000000000000000000000..1a72eb7780bc7d2a2d849e4cd5223d3c757d0ddf --- /dev/null +++ b/pool/shard006/C/0118371_playback.c @@ -0,0 +1,189 @@ +/* playback.c +*/ + +#include +#include +#include "led.h" +#include "notes.h" + +/* Global variables for the buffers */ +#define NOTE_BUFSIZE 24 +volatile uint8_t note_buffer[24] = {111}; +volatile uint8_t bytes_in_notebuffer = 0; +volatile uint8_t time_buffer[24]; + //time buffers count with 10ms groupings + +/* Global variables for playback */ +volatile uint8_t playback_counter = 0; + //counts time between notes +volatile uint8_t playback_noteSpace = 0; + //stores the current note's length +volatile uint8_t tuneWait = 255; + //0=play,1=waitForBeat,255=idle + +/* Global variables for note recording */ +volatile uint8_t rec_waveform = 0; +volatile uint16_t rec_timecounter = 0; +volatile uint16_t rec_beatset = 0; +volatile uint8_t recording = 0; +volatile uint8_t rec_octave = 0; +volatile uint8_t tmp_octave = 0; +volatile uint8_t tmp_waveform = 0; + +/* Playback */ +void playBuffer(void) { + + /* Set state */ + playback_counter = 0; + playback_noteSpace = time_buffer[0]; + tuneWait = 1; + + tmp_octave = octave; + octave = rec_octave; + + tmp_waveform = waveform; + waveform = rec_waveform; + +} + + +void buffer_note(uint8_t n, uint8_t t) { + /* Procedure to output a note/time (adding it to the outgoing buffers) + ** (The values will get consumed one at a time on the 1ms timer) + */ + + if(bytes_in_notebuffer < NOTE_BUFSIZE) { + /* We have room to add this byte */ + note_buffer[bytes_in_notebuffer] = n; + time_buffer[bytes_in_notebuffer] = t; + bytes_in_notebuffer++; + } +} + + +void buffer_song(uint8_t* note_array, uint8_t* time_array) { + /* Procedure to output a song (by adding it to the outgoing buffer + ** note by note). We iterate over all notes in the + ** array. IMPORTANT: (Terminates with 111) + */ + uint8_t i; + + /* Write to buffer */ + for(i=0; note_array[i] != 111; i++) { + buffer_note(note_array[i], time_array[i]); + } + + /* Playback */ + playBuffer(); + +} + + +void record_start(void) { + /* Procedure to refresh the recorded data + ** and activate recording of button presses + */ + notebuffer_clear(); + rec_waveform = waveform; + rec_beatset = beatCount; + rec_octave = octave; + recording = 1; +} + +void record_stop(void) { + /* Switch off note recording*/ + recording = 0; + //buffer_note(111,1); +} + +void record_note(uint8_t n, uint8_t t) { + /* Attempt to write the given values to the recording + ** buffer. End recording if buffer full. + */ + buffer_note(n,t); + if (bytes_in_notebuffer == NOTE_BUFSIZE) { + record_stop(); + } +} + + + +/* Play the demo tune (to be run on LED activation) + ** + ** Set a global variable to prevent other actions while the demo + ** tune plays. Loop through a series of notes, leaving a beat + ** between each and playing on the beat. + ** 2beats/sec, so 500ms delay + */ +void demoTuneStart(void) { + + if (recording==0) { + /* Note/time buffers */ + const uint8_t twinkleSong[17] = {0,0,4,4,5,5,4,255,3,3,2,2,1,1,0,255,111}; + const uint8_t twinkleTime[17] = {50}; + //C:0 D:1 E:2 F:3 G:4 A:5 B:6 C:7 xx:255 EoF:111 + + /* Settings */ + rec_beatset = 0; + rec_waveform = waveform; + rec_octave = 0; + + /* Buffer write */ + buffer_song(twinkleSong,twinkleTime); + } + +} + + + +/* Define the timer handler for playing notes from the buffer +*/ +void playbackStep(void) { + + /* 0. Check recording */ + if ((recording==1) && (tuneWait==255)) { + rec_timecounter++; + return; + } + + /* 1. Time start of playback to beat LED */ + if ((tuneWait==1) && (beatCount==rec_beatset)) { + tuneWait = 0; + } + + /* 2. Check if we have notes to play, + ** and aren't still waiting for the beat + */ + if ((bytes_in_notebuffer > 0) && (tuneWait==0)) { + + /* Check note timing match */ + if (playback_counter++ == playback_noteSpace) { + + uint8_t n, t; + + /* Read from buffers */ + n = note_buffer[bytes_in_notebuffer -1]; + t = time_buffer[bytes_in_notebuffer -1]; + bytes_in_notebuffer--; + + /* Play the note */ + note = n; + pressNote(); + + if (bytes_in_notebuffer > 0) { + /* Prepare for the next note */ + playback_noteSpace = t*10; + playback_counter = 0; + } else { + /* Turn off playback */ + tuneWait = 255; + octave = tmp_octave; + waveform = tmp_waveform; + } + + } + + } + +} + diff --git a/pool/shard006/C/0118375_array.c b/pool/shard006/C/0118375_array.c new file mode 100644 index 0000000000000000000000000000000000000000..89da877c094cf1d02e40bfdc67d9c90635b743b4 --- /dev/null +++ b/pool/shard006/C/0118375_array.c @@ -0,0 +1,117 @@ +/* Copyright (c) 2011, onitake + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE 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 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 +#include +#include +#include "array.h" + +struct Array { + size_t elemsize; + size_t allocated; + size_t length; + void *data; +}; + +ArrayPtr array_new(size_t elemsize) { + struct Array *ret = malloc(sizeof(struct Array)); + if (ret) { + ret->elemsize = elemsize; + ret->allocated = 0; + ret->length = 0; + ret->data = NULL; + } + return ret; +} + +void array_free(ArrayPtr array) { + if (array) { + if (array->data) { + free(array->data); + } + free(array); + } +} + +ssize_t array_length(ArrayPtr array) { + if (array) { + return array->length; + } + return -1; +} + +void *array_get(ArrayPtr array, size_t index) { + if (array && index < array->length) { + uint8_t *ptr = (uint8_t *) array->data; + return &ptr[array->elemsize * index]; + } + return NULL; +} + +ssize_t array_append(ArrayPtr array, void *data) { + if (array && data) { + if (!array->data) { + array->allocated = 1; + array->data = malloc(array->elemsize * array->allocated); + } + if (array->length + 1 > array->allocated) { + array->allocated <<= 1; + array->data = realloc(array->data, array->elemsize * array->allocated); + } + if (array->data) { + uint8_t *ptr = (uint8_t *) array->data; + memcpy(&ptr[array->elemsize * array->length], data, array->elemsize); + return array->length++; + } + } + return -1; +} + +void array_remove(ArrayPtr array, size_t index) { + if (array && index < array->length) { + uint8_t *ptr = (uint8_t *) array->data; + memcpy(&ptr[array->elemsize * index], &ptr[array->elemsize * (index + 1)], array->elemsize * (array->length - index)); + if (--array->length < 1) { + free(array->data); + array->allocated = 0; + array->data = NULL; + } + } +} + +ssize_t array_memsize(ArrayPtr array) { + if (array) { + return array->length * array->elemsize; + } + return -1; +} + +void *const array_storage(ArrayPtr array) { + if (array) { + return array->data; + } + return NULL; +} + diff --git a/pool/shard006/C/0118376_pthread_detach.c b/pool/shard006/C/0118376_pthread_detach.c new file mode 100644 index 0000000000000000000000000000000000000000..634c48cd6ae52c708de8963cc3d797e3911a3a73 --- /dev/null +++ b/pool/shard006/C/0118376_pthread_detach.c @@ -0,0 +1,22 @@ +#include + +#include +#include "thread_internal.h" + +int pthread_detach(pthread_t th) { + int ret=ESRCH; + _pthread_descr td,this=__thread_self(); + __NO_ASYNC_CANCEL_BEGIN_(this); + if ((td=__thread_find(th))) { + if (td->detached) { + ret=EINVAL; + } + else if (td->joined.__spinlock==PTHREAD_SPIN_UNLOCKED) { + td->detached=1; + ret^=ret; /* short ret=0; */ + } + UNLOCK(td); + } + __NO_ASYNC_CANCEL_END_(this); + return ret; +} diff --git a/pool/shard006/C/0118381_gtkmenutray.c b/pool/shard006/C/0118381_gtkmenutray.c new file mode 100644 index 0000000000000000000000000000000000000000..bd3c12a97982d239f439f0744d52ca6eecadde5c --- /dev/null +++ b/pool/shard006/C/0118381_gtkmenutray.c @@ -0,0 +1,253 @@ +/* + * Pidgin is the legal property of its developers, whose names are too numerous + * to list here. Please refer to the COPYRIGHT file distributed with this + * source distribution. + * + * This program is free software; you can redistribute it and/or modify + * under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA + */ +#include "internal.h" + +#include "debug.h" + +#include "gtkmenutray.h" + +#include "glibcompat.h" +#include "gtk3compat.h" + +/****************************************************************************** + * Enums + *****************************************************************************/ +enum { + PROP_ZERO = 0, + PROP_BOX +}; + +/****************************************************************************** + * Globals + *****************************************************************************/ +static GObjectClass *parent_class = NULL; +/****************************************************************************** + * Internal Stuff + *****************************************************************************/ + +/****************************************************************************** + * Item Stuff + *****************************************************************************/ +static void +pidgin_menu_tray_select(GtkMenuItem *widget) { + /* this may look like nothing, but it's really overriding the + * GtkMenuItem's select function so that it doesn't get highlighted like + * a normal menu item would. + */ +} + +static void +pidgin_menu_tray_deselect(GtkMenuItem *widget) { + /* Probably not necessary, but I'd rather be safe than sorry. We're + * overridding the select, so it makes sense to override deselect as well. + */ +} + +/****************************************************************************** + * Object Stuff + *****************************************************************************/ +static void +pidgin_menu_tray_get_property(GObject *obj, guint param_id, GValue *value, + GParamSpec *pspec) +{ + PidginMenuTray *menu_tray = PIDGIN_MENU_TRAY(obj); + + switch(param_id) { + case PROP_BOX: + g_value_set_object(value, pidgin_menu_tray_get_box(menu_tray)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(obj, param_id, pspec); + break; + } +} + +static void +pidgin_menu_tray_map(GtkWidget *widget) +{ + GTK_WIDGET_CLASS(parent_class)->map(widget); + gtk_container_add(GTK_CONTAINER(widget), + PIDGIN_MENU_TRAY(widget)->tray); +} + +static void +pidgin_menu_tray_finalize(GObject *obj) +{ +#if 0 + PidginMenuTray *tray = PIDGIN_MENU_TRAY(obj); + + /* This _might_ be leaking, but I have a sneaking suspicion that the widget is + * getting destroyed in GtkContainer's finalize function. But if were are + * leaking here, be sure to figure out why this causes a crash. + * -- Gary + */ + + if(GTK_IS_WIDGET(tray->tray)) + gtk_widget_destroy(GTK_WIDGET(tray->tray)); +#endif + + G_OBJECT_CLASS(parent_class)->finalize(obj); +} + +static void +pidgin_menu_tray_class_init(PidginMenuTrayClass *klass) { + GObjectClass *object_class = G_OBJECT_CLASS(klass); + GtkMenuItemClass *menu_item_class = GTK_MENU_ITEM_CLASS(klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass); + GParamSpec *pspec; + + parent_class = g_type_class_peek_parent(klass); + + object_class->finalize = pidgin_menu_tray_finalize; + object_class->get_property = pidgin_menu_tray_get_property; + + menu_item_class->select = pidgin_menu_tray_select; + menu_item_class->deselect = pidgin_menu_tray_deselect; + + widget_class->map = pidgin_menu_tray_map; + + pspec = g_param_spec_object("box", "The box", + "The box", + GTK_TYPE_BOX, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS); + g_object_class_install_property(object_class, PROP_BOX, pspec); +} + +static void +pidgin_menu_tray_init(PidginMenuTray *menu_tray) { + GtkWidget *widget = GTK_WIDGET(menu_tray); + GtkSettings *settings; + gint height = -1; + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS + /* Gtk3 docs says, it should be replaced with gtk_widget_set_hexpand and + * gtk_widget_set_halign. But it doesn't seems to work. */ + gtk_menu_item_set_right_justified(GTK_MENU_ITEM(menu_tray), TRUE); +G_GNUC_END_IGNORE_DEPRECATIONS + + if(!GTK_IS_WIDGET(menu_tray->tray)) + menu_tray->tray = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + + settings = + gtk_settings_get_for_screen(gtk_widget_get_screen(widget)); + + if(gtk_icon_size_lookup_for_settings(settings, GTK_ICON_SIZE_MENU, + NULL, &height)) + { + gtk_widget_set_size_request(widget, -1, height); + } + + gtk_widget_show(menu_tray->tray); +} + +/****************************************************************************** + * API + *****************************************************************************/ +GType +pidgin_menu_tray_get_type(void) { + static GType type = 0; + + if(type == 0) { + static const GTypeInfo info = { + sizeof(PidginMenuTrayClass), + NULL, + NULL, + (GClassInitFunc)pidgin_menu_tray_class_init, + NULL, + NULL, + sizeof(PidginMenuTray), + 0, + (GInstanceInitFunc)pidgin_menu_tray_init, + NULL + }; + + type = g_type_register_static(GTK_TYPE_MENU_ITEM, + "PidginMenuTray", + &info, 0); + } + + return type; +} + +GtkWidget * +pidgin_menu_tray_new() { + return g_object_new(PIDGIN_TYPE_MENU_TRAY, NULL); +} + +GtkWidget * +pidgin_menu_tray_get_box(PidginMenuTray *menu_tray) { + g_return_val_if_fail(PIDGIN_IS_MENU_TRAY(menu_tray), NULL); + return menu_tray->tray; +} + +static void +pidgin_menu_tray_add(PidginMenuTray *menu_tray, GtkWidget *widget, + const char *tooltip, gboolean prepend) +{ + g_return_if_fail(PIDGIN_IS_MENU_TRAY(menu_tray)); + g_return_if_fail(GTK_IS_WIDGET(widget)); + + if (!gtk_widget_get_has_window(widget)) + { + GtkWidget *event; + + event = gtk_event_box_new(); + gtk_container_add(GTK_CONTAINER(event), widget); + gtk_widget_show(event); + widget = event; + } + + pidgin_menu_tray_set_tooltip(menu_tray, widget, tooltip); + + if (prepend) + gtk_box_pack_start(GTK_BOX(menu_tray->tray), widget, FALSE, FALSE, 0); + else + gtk_box_pack_end(GTK_BOX(menu_tray->tray), widget, FALSE, FALSE, 0); +} + +void +pidgin_menu_tray_append(PidginMenuTray *menu_tray, GtkWidget *widget, const char *tooltip) +{ + pidgin_menu_tray_add(menu_tray, widget, tooltip, FALSE); +} + +void +pidgin_menu_tray_prepend(PidginMenuTray *menu_tray, GtkWidget *widget, const char *tooltip) +{ + pidgin_menu_tray_add(menu_tray, widget, tooltip, TRUE); +} + +void +pidgin_menu_tray_set_tooltip(PidginMenuTray *menu_tray, GtkWidget *widget, const char *tooltip) +{ + /* Should we check whether widget is a child of menu_tray? */ + + /* + * If the widget does not have its own window, then it + * must have automatically been added to an event box + * when it was added to the menu tray. If this is the + * case, we want to set the tooltip on the widget's parent, + * not on the widget itself. + */ + if (!gtk_widget_get_has_window(widget)) + widget = gtk_widget_get_parent(widget); + + gtk_widget_set_tooltip_text(widget, tooltip); +} diff --git a/pool/shard006/C/0118387_array.c b/pool/shard006/C/0118387_array.c new file mode 100644 index 0000000000000000000000000000000000000000..9af0eb6b535d0e676c156d2f103720f9128a68db --- /dev/null +++ b/pool/shard006/C/0118387_array.c @@ -0,0 +1,123 @@ +/*- + * Copyright (c) 2009 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by David A. Holland. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#define ARRAYINLINE + +#include +#include +#include +#include + +struct array * +array_create(void) +{ + struct array *a; + + a = kmalloc(sizeof(*a)); + if (a != NULL) { + array_init(a); + } + return a; +} + +void +array_destroy(struct array *a) +{ + array_cleanup(a); + kfree(a); +} + +void +array_init(struct array *a) +{ + a->num = a->max = 0; + a->v = NULL; +} + +void +array_cleanup(struct array *a) +{ + /* + * Require array to be empty - helps avoid memory leaks since + * we don't/can't free anything any contents may be pointing + * to. + */ + ARRAYASSERT(a->num == 0); + kfree(a->v); +#ifdef ARRAYS_CHECKED + a->v = NULL; +#endif +} + +int +array_setsize(struct array *a, unsigned num) +{ + void **newptr; + unsigned newmax; + + if (num > a->max) { + /* Don't touch A until the allocation succeeds. */ + newmax = a->max; + while (num > newmax) { + newmax = newmax ? newmax*2 : 4; + } + + /* + * We don't have krealloc, and it wouldn't be + * worthwhile to implement just for this. So just + * allocate a new block and copy. (Exercise: what + * about this and/or kmalloc makes it not worthwhile?) + */ + + newptr = kmalloc(newmax*sizeof(*a->v)); + if (newptr == NULL) { + return ENOMEM; + } + memcpy(newptr, a->v, a->num*sizeof(*a->v)); + kfree(a->v); + a->v = newptr; + a->max = newmax; + } + a->num = num; + + return 0; +} + +void +array_remove(struct array *a, unsigned index) +{ + unsigned num_to_move; + + ARRAYASSERT(a->num <= a->max); + ARRAYASSERT(index < a->num); + + num_to_move = a->num - (index + 1); + memmove(a->v + index, a->v + index+1, num_to_move*sizeof(void *)); + a->num--; +} diff --git a/pool/shard006/C/0118388_factorial.c b/pool/shard006/C/0118388_factorial.c new file mode 100644 index 0000000000000000000000000000000000000000..b7e1a1e7492560dbeaa50a1a049d1fb5f6f5df97 --- /dev/null +++ b/pool/shard006/C/0118388_factorial.c @@ -0,0 +1,186 @@ +/* +# Pablo Castro Valiño (pablo.castro1@udc.es) +# Deseño de Sistemas Operativos + +Programa que crea 3 hilos y realiza el factorial de un número introducido. + +*/ +#include +#include +#include +#include +#include +#include +#include + + +//Array de control para las primeras llamadas a los threads +int start[3]; + +//Array de control para los threads terminados +int fin[3]; + +//Variables para guardar los números para los diferentes threads +int numero_t0 = 5; +int numero_t1 = 6; +int numero_t2 = 7; +//8192 + +//Variables para guardar los factoriales para los diferentes threads +int fact_t0 = 1; +int fact_t1 = 1; +int fact_t2 = 1; + +int ct = 0; //Current Thread +int t_frame[4]; //Almacena las direcciones de los frames +int t_return[4]; //Almacena las direcciones de retorno + +//Variable para imprimir textos +char mensaje[1024]; + +//Función que cambia entre threads +void yield(){ + int a[10]; + int i = 0; + //Guarda las direcciones + t_frame[ct] = a[13];//frame + t_return[ct] = a[14];//return + + //1º ACCESO A T0 + if(start[0]){ + start[0]= 0; + fact_t0 = t0(numero_t0); + fin[0] = 1; + }else{ + //1º ACCESO A T1 + if(start[1]){ + start[1] = 0; + fact_t1 = t1(numero_t1); + fin[1] = 1; + }else{ + //1º ACCESO A T2 + if(start[2]){ + start[2] = 0; + fact_t2 = t2(numero_t2); + fin[2] = 1; + } + } + } + + //Cambia el thread actual + for(i=0;i<=2;i++){ + ct = (ct+1) % 3; + + if(!fin[ct]) + break; + } + + //Si es el final se carga el frame de la funcion "frame" + if((fin[0]) && (fin[1]) && (fin[2])) + ct = 3; + + a[13] = t_frame[ct]; + a[14] = t_return[ct]; +} + +//Función que coloca el SP en el lugar adecuado +void adjust_frame(){ + yield(); + return; +} + +int t0(int numero_t0){ + int a[10]; + int temp = 1; + if (numero_t0){ + + temp = t0(numero_t0-1); + + //printf("Thread-0\n"); + + //sprintf(mensaje,"Thread-0\n"); + //write(1,mensaje,strlen(mensaje)); + + adjust_frame(); + return numero_t0 * temp; + }else{ + ct=0; + adjust_frame(); + return 1; + } +} + + +int t1(int numero_t1){ + int a[10]; + int temp = 1; + if (numero_t1){ + + temp = t1(numero_t1-1); + //printf("Thread-1\n"); + //sprintf(mensaje,"Thread-1\n"); + //write(1,mensaje,strlen(mensaje)); + + adjust_frame(); + return numero_t1 * temp; + }else{ + ct=1; + adjust_frame(); + return 1; + } +} + +int t2(int numero_t2){ + int a[10]; + int temp = 1; + if (numero_t2){ + + temp = t2(numero_t2-1); + //printf("Thread-2\n"); + //sprintf(mensaje,"Thread-2\n"); + //write(1,mensaje,strlen(mensaje)); + + adjust_frame(); + return numero_t2 * temp; + }else{ + ct=2; + adjust_frame(); + return 1; + } +} + + +int main(int argc, char *argv[]){ + int i; + //Inicialización de variables + for(i=0;i<=2;i++){ + fin[i] = 0; + start[i] = 1; + } + + ct=3; + adjust_frame(); + + int salidat0 = fact_t0; + int salidat1 = fact_t1; + int salidat2 = fact_t2; + + printf("Thread 0 - Resultado:%i\nThread 1 - Resultado:%i\nThread 2 - Resultado:%i\n",salidat0,salidat1,salidat2); +} + + + + + + + + + + + + + + + + + diff --git a/pool/shard006/C/0118394_graphml.c b/pool/shard006/C/0118394_graphml.c new file mode 100644 index 0000000000000000000000000000000000000000..8e7fa56429b6461f960c63c19ef8add6ed20be74 --- /dev/null +++ b/pool/shard006/C/0118394_graphml.c @@ -0,0 +1,98 @@ +/* -*- mode: C -*- */ +/* + IGraph library. + Copyright (C) 2006-2012 Gabor Csardi + 334 Harvard street, Cambridge, MA 02139 USA + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA + +*/ +#include +#include +#include /* unlink */ + +void custom_warning_handler (const char *reason, const char *file, + int line, int igraph_errno) { + printf("Warning: %s\n", reason); +} + +int main(int argc, char **argv) { + igraph_t g; + igraph_error_handler_t* oldhandler; + igraph_warning_handler_t* oldwarnhandler; + int result; + FILE *ifile, *ofile; + + /* GraphML */ + ifile=fopen("test.gxl", "r"); + if (ifile==0) { + return 10; + } + + oldhandler=igraph_set_error_handler(igraph_error_handler_ignore); + oldwarnhandler=igraph_set_warning_handler(custom_warning_handler); + if (result=igraph_read_graph_graphml(&g, ifile, 0)) { + // maybe it is simply disabled at compile-time + if (result == IGRAPH_UNIMPLEMENTED) return 77; + return 1; + } + igraph_set_error_handler(oldhandler); + + fclose(ifile); + + /* Write it back */ + ofile=fopen("test2.gxl", "w"); + /* If we can't create the test file, just skip the test */ + if (ofile) { + if (result=igraph_write_graph_graphml(&g, ofile)) { + return 1; + } + fclose(ofile); + unlink("test2.gxl"); + } + + printf("The directed graph:\n"); + printf("Vertices: %li\n", (long int) igraph_vcount(&g)); + printf("Edges: %li\n", (long int) igraph_ecount(&g)); + printf("Directed: %i\n", (int) igraph_is_directed(&g)); + igraph_write_graph_edgelist(&g, stdout); + igraph_destroy(&g); + + /* The same with undirected graph */ + ifile=fopen("test.gxl", "r"); + if (result=igraph_read_graph_graphml(&g, ifile, 0)) { + return 1; + } + fclose(ifile); + printf("The undirected graph:\n"); + printf("Vertices: %li\n", (long int) igraph_vcount(&g)); + printf("Edges: %li\n", (long int) igraph_ecount(&g)); + printf("Directed: %i\n", (int) igraph_is_directed(&g)); + igraph_write_graph_edgelist(&g, stdout); + igraph_destroy(&g); + igraph_set_warning_handler(oldwarnhandler); + + /* There were sometimes problems with this file */ + /* Only if called from R though, and only on random occasions, once in every + ten reads. Do testing here doesn't make much sense, but if we have the file + then let's do it anyway. */ + ifile=fopen("graphml-hsa05010.xml", "r"); + igraph_read_graph_graphml(&g, ifile, 0); + fclose(ifile); + igraph_destroy(&g); + + return 0; +} diff --git a/pool/shard006/C/0118400_netrt_rtnetlink.c b/pool/shard006/C/0118400_netrt_rtnetlink.c new file mode 100644 index 0000000000000000000000000000000000000000..025d3d6c8c8d6a5a39bc7b41d8697d8ad63424dd --- /dev/null +++ b/pool/shard006/C/0118400_netrt_rtnetlink.c @@ -0,0 +1,250 @@ +#if defined(HAVE_CONFIG_H) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +char * +find_egress_interface(struct sockaddr *source, struct sockaddr *dest) { + + struct sockaddr_nl me,them; + struct sockaddr_in *in4; + struct sockaddr_in6 *in6; + + int interface_index = -1; + char interface_name[IF_NAMESIZE]; + + int s; + + /* so, in our msghdr we will put the address and an iovec pointing + to our request. that request will consist of a netlink message + header, a routing message header and some routing attributes. + the chalice with the palace holds the pellet with the poison, the + vessel with the pestle holds the brew which is true. i guess it + would have been "too easy" to just have a plain old ioctl that + one calls to get the route for a given destination and + source... raj 2008-02-11 */ + + struct msghdr msg; + + struct iovec iov; + + struct { + struct nlmsghdr nl; + struct rtmsg rt; + char buf[1024]; + } request; + + char reply[1024]; + + struct nlmsghdr *nlp; + struct rtmsg *rtp; + struct rtattr *rtap; + int nll,rtl; + + int ret; + + /* create and bind the netlink socket */ + s = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + + memset(&me, 0, sizeof(me)); + me.nl_family = AF_NETLINK; + me.nl_pid = getpid(); + + /* probably should be checking a return value... */ + bind(s, (struct sockaddr *)&me, sizeof(me)); + + /* create the message we are going to send */ + + memset(&request, 0, sizeof(request)); + request.nl.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); + request.nl.nlmsg_flags = NLM_F_REQUEST; + request.nl.nlmsg_type = RTM_GETROUTE; + + /* time to add the destination attribute to the request */ + if (dest) { + in4 = (struct sockaddr_in *)dest; + in6 = (struct sockaddr_in6 *)dest; + request.rt.rtm_family = in4->sin_family; + rtap = (struct rtattr *)request.buf; + rtap->rta_type = RTA_DST; + if (AF_INET == in4->sin_family) { + /* while a sin_addr is a multiple of 4 bytes in length, we + should still use RTA_SPACE rather than RTA_LENGTH. kudos to + Thomas Graf for pointing that out */ + rtap->rta_len = RTA_SPACE(sizeof(in4->sin_addr)); + memcpy(RTA_DATA(rtap), &(in4->sin_addr), sizeof(in4->sin_addr)); + } + else if (AF_INET6 == in6->sin6_family) { + rtap->rta_len = RTA_SPACE(sizeof(in6->sin6_addr)); + memcpy(RTA_DATA(rtap), &(in6->sin6_addr), sizeof(in6->sin6_addr)); + } + else { + return strdup("UnknownAddressFamily"); + } + } + else { + /* there must always be a destination */ + printf("No destination specified.\n"); + return strdup("NoDestination"); + } + + /* add the length of our request to our overall message length. it + should already be suitably padded by the previous RTA_SPACE */ + request.nl.nlmsg_len += rtap->rta_len; + + /* now the src */ + if (source) { + /* the source goes after the dest, so we can just increment by the + current value of rta_len */ + in4 = (struct sockaddr_in *)source; + in6 = (struct sockaddr_in6 *)source; + + /* pointer math is fun. silly me initially tried to to rtap += + rtap->rta_len but since rtap isn't pointing at bytes... again + kudos to Thomas Graf for finding that mistake */ + rtap = (struct rtattr *)((char *)rtap + (rtap->rta_len)); + rtap->rta_type = RTA_SRC; + if (AF_INET == in4->sin_family) { + rtap->rta_len = RTA_SPACE(sizeof(in4->sin_addr)); + memcpy(RTA_DATA(rtap), &(in4->sin_addr), sizeof(in4->sin_addr)); + } + else if (AF_INET6 == in6->sin6_family) { + rtap->rta_len = RTA_SPACE(sizeof(in6->sin6_addr)); + memcpy(RTA_DATA(rtap), &(in6->sin6_addr), sizeof(in6->sin6_addr)); + } + else { + return strdup("UnknownAddressFamily"); + } + + + /* add the length of the just added attribute to the overall + message length. it should already be suitably padded by the + previous RTA_SPACE */ + request.nl.nlmsg_len += rtap->rta_len; + } + + /* address it */ + memset(&them, 0, sizeof(them)); + them.nl_family = AF_NETLINK; + + memset(&msg, 0, sizeof(msg)); + msg.msg_name = (void *)&them; + msg.msg_namelen = sizeof(them); + + iov.iov_base = (void *) &request.nl; + iov.iov_len = request.nl.nlmsg_len; + + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + + /* send it */ + ret = sendmsg(s, &msg, 0); + + if (ret < 0) { + return strdup("SendmsgFailure"); + } + + memset(reply,0,sizeof(reply)); + ret = recv(s, reply, sizeof(reply), 0); + + if (ret < 0) { + return strdup("RecvmsgFailure"); + } + + nll = ret; + + /* Since we are looking for a single route, one has to wonder if + this is really necessary, but since all the examples I could find + seemed to be doing it, I'll simply follow along. raj + 2008-02-11 */ + + for (nlp = (struct nlmsghdr *)reply; + NLMSG_OK(nlp,nll); + nlp = NLMSG_NEXT(nlp, nll)) { + /* where oh where might the route header be? */ + rtp = (struct rtmsg *) NLMSG_DATA(nlp); + +#if 0 + /* we will ass-u-me we are only interested in results for the main + routing table */ + if (RT_TABLE_MAIN != rtp->rtm_table) { + printf("skipping table %d\n",rtp->rtm_table); + continue; + } +#endif + + for (rtap = (struct rtattr *) RTM_RTA(rtp), rtl = RTM_PAYLOAD(nlp); + RTA_OK(rtap, rtl); + rtap = RTA_NEXT(rtap,rtl)) { + if (RTA_OIF == rtap->rta_type) { + if (-1 == interface_index){ + interface_index = *((int *) RTA_DATA(rtap)); + } + else { + printf("Found a second interface index, which was not expected!\n"); + return strdup("MultipleInterfacesFound"); + } + } + } + } + + if (interface_index == -1) { + /* we didn't find it */ + return strdup("InterfaceNotFound"); + } + else { + if (NULL == if_indextoname(interface_index,interface_name)) { + return strdup("IfIndexToNameFailure"); + } + else { + return strdup(interface_name); + } + } +} +#if defined(NETPERF_STANDALONE_DEBUG) +int +main(int argc, char *argv[]) { + + struct sockaddr_storage source,destination; + struct sockaddr_in *sin; + int ret; + char *egress_if; + + if ((argc < 2) || (argc > 3)) { + fprintf(stderr,"%s [srcip]\n",argv[0]); + return -1; + } + + sin = (struct sockaddr_in *)&destination; + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = inet_addr(argv[1]); + + printf("destination address is %s\n",inet_ntoa(sin->sin_addr)); + + sin = NULL; + + if (argc == 3) { + sin = (struct sockaddr_in *)&source; + sin->sin_family = AF_INET; + sin->sin_addr.s_addr = inet_addr(argv[2]); + } + + egress_if = find_egress_interface((struct sockaddr *)sin,(struct sockaddr *)&destination); + + printf("egress interface %p %s\n",egress_if,egress_if); + +} +#endif diff --git a/pool/shard006/C/0118401_toeplitz.c b/pool/shard006/C/0118401_toeplitz.c new file mode 100644 index 0000000000000000000000000000000000000000..fcc4b64ad1906b8f312a58a44fa8d7d2c17a9faa --- /dev/null +++ b/pool/shard006/C/0118401_toeplitz.c @@ -0,0 +1,122 @@ +/* SPDX-License-Identifier: Apache-2.0 + * Copyright(c) 2021 Cisco Systems, Inc. + */ + +#include +#include +#include + +static u8 default_key[40] = { + 0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2, 0x41, 0x67, + 0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0, 0xd0, 0xca, 0x2b, 0xcb, + 0xae, 0x7b, 0x30, 0xb4, 0x77, 0xcb, 0x2d, 0xa3, 0x80, 0x30, + 0xf2, 0x0c, 0x6a, 0x42, 0xb7, 0x3b, 0xbe, 0xac, 0x01, 0xfa, +}; + +#ifdef __x86_64__ +static_always_inline void +clib_toeplitz_hash_key_expand_8 (u64x2 kv, u64x8u *m) +{ + u64x8 kv4, a, b, shift = { 0, 1, 2, 3, 4, 5, 6, 7 }; + + kv4 = (u64x8){ kv[0], kv[1], kv[0], kv[1], kv[0], kv[1], kv[0], kv[1] }; + + /* clang-format off */ + /* create 8 byte-swapped copies of the bytes 0 - 7 */ + a = (u64x8) u8x64_shuffle (kv4, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0, + 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1, 0x0); + /* create 8 byte-swapped copies of the bytes 4 - 11 */ + b = (u64x8) u8x64_shuffle (kv4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, + 0xb, 0xa, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4); + /* clang-format on */ + + /* shift each 64-bit element for 0 - 7 bits */ + a <<= shift; + b <<= shift; + + /* clang-format off */ + /* construct eight 8x8 bit matrix used by gf2p8affine */ + * m = (u64x8) u8x64_shuffle2 (a, b, + 0x07, 0x0f, 0x17, 0x1f, 0x27, 0x2f, 0x37, 0x3f, + 0x06, 0x0e, 0x16, 0x1e, 0x26, 0x2e, 0x36, 0x3e, + 0x05, 0x0d, 0x15, 0x1d, 0x25, 0x2d, 0x35, 0x3d, + 0x04, 0x0c, 0x14, 0x1c, 0x24, 0x2c, 0x34, 0x3c, + 0x47, 0x4f, 0x57, 0x5f, 0x67, 0x6f, 0x77, 0x7f, + 0x46, 0x4e, 0x56, 0x5e, 0x66, 0x6e, 0x76, 0x7e, + 0x45, 0x4d, 0x55, 0x5d, 0x65, 0x6d, 0x75, 0x7d, + 0x44, 0x4c, 0x54, 0x5c, 0x64, 0x6c, 0x74, 0x7c); + /* clang-format on */ +} + +void +clib_toeplitz_hash_key_expand (u64 *matrixes, u8 *key, int size) +{ + u64x8u *m = (u64x8u *) matrixes; + u64x2 kv = {}, zero = {}; + + while (size >= 8) + { + kv = *(u64x2u *) key; + clib_toeplitz_hash_key_expand_8 (kv, m); + key += 8; + m++; + size -= 8; + } + + kv = u64x2_shuffle2 (kv, zero, 1, 2); + clib_toeplitz_hash_key_expand_8 (kv, m); +} +#endif + +__clib_export clib_toeplitz_hash_key_t * +clib_toeplitz_hash_key_init (u8 *key, u32 keylen) +{ + clib_toeplitz_hash_key_t *k; + u32 size, gfni_size = 0; + + if (key == 0) + { + key = default_key; + keylen = sizeof (default_key); + } + + size = + round_pow2 (sizeof (clib_toeplitz_hash_key_t) + round_pow2 (keylen, 16), + CLIB_CACHE_LINE_BYTES); +#ifdef __x86_64__ + gfni_size = round_pow2 ((keylen + 1) * 8, CLIB_CACHE_LINE_BYTES); +#endif + + k = clib_mem_alloc_aligned (size + gfni_size, CLIB_CACHE_LINE_BYTES); + clib_memset_u8 (k, 0, size + gfni_size); + k->key_length = keylen; + k->gfni_offset = size; + clib_memcpy_fast (k->data, key, keylen); + +#ifdef __x86_64__ + clib_toeplitz_hash_key_expand ((u64 *) ((u8 *) k + k->gfni_offset), k->data, + k->key_length); +#endif + + return k; +} + +__clib_export void +clib_toeplitz_hash_key_free (clib_toeplitz_hash_key_t *k) +{ + clib_mem_free (k); +} diff --git a/pool/shard006/C/0118404_memory.c b/pool/shard006/C/0118404_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..92f4ff4fcbfe9c7d9b9dc2b1b9b83819f1e20996 --- /dev/null +++ b/pool/shard006/C/0118404_memory.c @@ -0,0 +1,152 @@ +/* $Id: memory.c,v 1.5 1999/08/31 06:55:04 davem Exp $ + * memory.c: Prom routine for acquiring various bits of information + * about RAM on the machine, both virtual and physical. + * + * Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu) + * Copyright (C) 1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz) + */ + +#include +#include + +#include +#include + +/* This routine, for consistency, returns the ram parameters in the + * V0 prom memory descriptor format. I choose this format because I + * think it was the easiest to work with. I feel the religious + * arguments now... ;) Also, I return the linked lists sorted to + * prevent paging_init() upset stomach as I have not yet written + * the pepto-bismol kernel module yet. + */ + +struct linux_prom64_registers prom_reg_memlist[64]; +struct linux_prom64_registers prom_reg_tmp[64]; + +struct linux_mlist_p1275 prom_phys_total[64]; +struct linux_mlist_p1275 prom_prom_taken[64]; +struct linux_mlist_p1275 prom_phys_avail[64]; + +struct linux_mlist_p1275 *prom_ptot_ptr = prom_phys_total; +struct linux_mlist_p1275 *prom_ptak_ptr = prom_prom_taken; +struct linux_mlist_p1275 *prom_pavl_ptr = prom_phys_avail; + +struct linux_mem_p1275 prom_memlist; + + +/* Internal Prom library routine to sort a linux_mlist_p1275 memory + * list. Used below in initialization. + */ +static void __init +prom_sortmemlist(struct linux_mlist_p1275 *thislist) +{ + int swapi = 0; + int i, mitr; + unsigned long tmpaddr, tmpsize; + unsigned long lowest; + + for(i=0; thislist[i].theres_more != 0; i++) { + lowest = thislist[i].start_adr; + for(mitr = i+1; thislist[mitr-1].theres_more != 0; mitr++) + if(thislist[mitr].start_adr < lowest) { + lowest = thislist[mitr].start_adr; + swapi = mitr; + } + if(lowest == thislist[i].start_adr) continue; + tmpaddr = thislist[swapi].start_adr; + tmpsize = thislist[swapi].num_bytes; + for(mitr = swapi; mitr > i; mitr--) { + thislist[mitr].start_adr = thislist[mitr-1].start_adr; + thislist[mitr].num_bytes = thislist[mitr-1].num_bytes; + } + thislist[i].start_adr = tmpaddr; + thislist[i].num_bytes = tmpsize; + } +} + +/* Initialize the memory lists based upon the prom version. */ +void __init prom_meminit(void) +{ + int node = 0; + unsigned int iter, num_regs; + + node = prom_finddevice("/memory"); + num_regs = prom_getproperty(node, "available", + (char *) prom_reg_memlist, + sizeof(prom_reg_memlist)); + num_regs = (num_regs/sizeof(struct linux_prom64_registers)); + for(iter=0; iter. + * + * + * File: i2cHwBus.c + * Created on: 24 Sep 2010 + * Author: Clive Webster + * + * Place a thin wrapper around the i2c_master calls so that they can be used + * from an abstract i2c bus + */ +#include "i2cBus.h" +#include "_i2c_common.h" + +// TWS4:3 set - ACK has been received back +// Acknowledgement in Write mode +#define TW_MT_SLA_ACK 0x18 + +// TWS6 set +// Acknowledgement in Read mode +#define TW_MR_SLA_ACK 0x40 + +// The sent data has been acknowledged +#define TW_MT_DATA_ACK 0x28 + +// Include the device definitions +#include + +static void speed(const I2C_ABSTRACT_BUS* bus,uint16_t bitrateKHz){ + // TWBR x 4pow(TWPS) = ((cpudiv1000/ bitrateKHz) - 16) /2 + uint16_t bitrate_div; + + // calculate bitrate division + bitrate_div = cpu_speed_div_1000 / bitrateKHz; + + if(bitrate_div >= 16){ + bitrate_div = (bitrate_div-16)/2; + }else{ + bitrate_div=0; + } + + // Turn prescaler off by default + #ifdef TWPS0 + cbi(TWSR, TWPS0); + #endif + #ifdef TWPS1 + cbi(TWSR, TWPS1); + #endif + + // Check if need to use the prescaler + #ifdef TWPS0 + if(bitrate_div > 255){ + sbi(TWSR, TWPS0); + bitrate_div /= 4; + } + #endif + #ifdef TWPS1 + if(bitrate_div > 255){ + sbi(TWSR, TWPS1); + bitrate_div /= 16; + } + #endif + + // Cannot prescale it on some devices - so just go as slow as possible + if(bitrate_div > 255){ + bitrate_div = 255; + } + + outb(TWBR, (uint8_t)(bitrate_div) ); +} + + +// Initialiase I2C hardware +void __attribute__ ((constructor)) _private_i2cMasterInit(void){ + + // Make the 2 wires into inputs + cbi(SCL_DDR,SCL_PIN); + cbi(SDA_DDR,SDA_PIN); + // and turn on the pullups + sbi(SCL_PORT,SCL_PIN); + sbi(SDA_PORT,SDA_PIN); + + + // enable TWI (two-wire interface) + sbi(TWCR, TWEN); + + // set state + i2cState = I2C_IDLE; + + // enable TWI interrupt and slave address ACK +// sbi(TWCR, TWIE); +// sbi(TWCR, TWEA); + + // enable interrupts +// sei(); +} + +static void init(I2C_ABSTRACT_BUS* bus){ + // set i2c bit rate to 100KHz + speed(bus,100); +} + +static inline void i2cWaitForComplete(void){ + // wait for i2c interface to complete operation + while( !(inb(TWCR) & BV(TWINT)) ); +} + +static uint8_t getByte(const I2C_ABSTRACT_BUS* bus, boolean isLastByte){ + // begin receive over i2c + if( isLastByte ){ + // ackFlag = FALSE: NACK the received data + outb(TWCR, (inb(TWCR)&TWCR_CMD_MASK)|BV(TWINT)); + }else{ + // ackFlag = TRUE: ACK the recevied data + outb(TWCR, (inb(TWCR)&TWCR_CMD_MASK)|BV(TWINT)|BV(TWEA)); + } + i2cWaitForComplete(); + return inb(TWDR); +} + + +static boolean putByte(const I2C_ABSTRACT_BUS* bus, uint8_t data){ + // save data to the TWDR + outb(TWDR, data); + // begin send + outb(TWCR, (inb(TWCR)&TWCR_CMD_MASK)|BV(TWINT)); + + i2cWaitForComplete(); + + uint8_t got = inb(TWSR) & TWSR_STATUS_MASK; // get the status + + return( (got == TW_MT_DATA_ACK) ? TRUE : FALSE ); + +} + +static boolean start(const I2C_DEVICE* device, boolean writeMode){ + uint8_t expect; + if(writeMode){ + i2cState = I2C_MASTER_TX; + expect = TW_MT_SLA_ACK; + }else{ + i2cState = I2C_MASTER_RX; + expect = TW_MR_SLA_ACK; + } + + // send start condition + outb(TWCR, (inb(TWCR)&TWCR_CMD_MASK)|BV(TWINT)|BV(TWSTA)); + i2cWaitForComplete(); + + // Send the device addr and direction + uint8_t addr = device->addr; + if(writeMode==FALSE){ + addr |= 1; + }else{ + addr &= 0xfe; + } + outb(TWDR, addr); + // begin send + outb(TWCR, (inb(TWCR)&TWCR_CMD_MASK)|BV(TWINT)); + i2cWaitForComplete(); + + uint8_t got = inb(TWSR) & TWSR_STATUS_MASK; // get the status + return( (got == expect) ? TRUE : FALSE ); + +} + +static void stop(const I2C_ABSTRACT_BUS* bus){ + // transmit stop condition + // leave with TWEA on for slave receiving + outb(TWCR, (inb(TWCR)&TWCR_CMD_MASK)|BV(TWINT)|BV(TWEA)|BV(TWSTO)); + i2cState = I2C_IDLE; +} + + +// Expose this implementation to the linker +I2C_CLASS const c_hw_i2c = MAKE_I2C_CLASS(&init, &start,&stop, &getByte, &putByte, &speed); diff --git a/pool/shard006/C/0118411_intel_pixel_copy.c b/pool/shard006/C/0118411_intel_pixel_copy.c new file mode 100644 index 0000000000000000000000000000000000000000..56faf076c7e9d26d83cd9bf15486699657f713a6 --- /dev/null +++ b/pool/shard006/C/0118411_intel_pixel_copy.c @@ -0,0 +1,214 @@ +/************************************************************************** + * + * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas. + * 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, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 "main/glheader.h" +#include "main/image.h" +#include "main/state.h" +#include "main/mtypes.h" +#include "drivers/common/meta.h" + +#include "intel_context.h" +#include "intel_buffers.h" +#include "intel_regions.h" +#include "intel_pixel.h" +#include "intel_fbo.h" + +#define FILE_DEBUG_FLAG DEBUG_PIXEL + +static struct intel_region * +copypix_src_region(struct intel_context *intel, GLenum type) +{ + struct intel_renderbuffer *depth; + + depth = (struct intel_renderbuffer *) + &intel->ctx.DrawBuffer->Attachment[BUFFER_DEPTH].Renderbuffer; + + switch (type) { + case GL_COLOR: + return intel_readbuf_region(intel); + case GL_DEPTH: + /* Don't think this is really possible execpt at 16bpp, when we + * have no stencil. */ + if (depth && depth->region->cpp == 2) + return depth->region; + case GL_STENCIL: + /* Don't think this is really possible. */ + break; + case GL_DEPTH_STENCIL_EXT: + /* Does it matter whether it is stencil/depth or depth/stencil? + */ + return depth->region; + default: + break; + } + + return NULL; +} + + +/** + * Check if any fragment operations are in effect which might effect + * glCopyPixels. Differs from intel_check_blit_fragment_ops in that + * we allow Scissor. + */ +static GLboolean +intel_check_copypixel_blit_fragment_ops(GLcontext * ctx) +{ + if (ctx->NewState) + _mesa_update_state(ctx); + + /* Could do logicop with the blitter: + */ + return !(ctx->_ImageTransferState || + ctx->Color.AlphaEnabled || + ctx->Depth.Test || + ctx->Fog.Enabled || + ctx->Stencil._Enabled || + !ctx->Color.ColorMask[0][0] || + !ctx->Color.ColorMask[0][1] || + !ctx->Color.ColorMask[0][2] || + !ctx->Color.ColorMask[0][3] || + ctx->Texture._EnabledUnits || + ctx->FragmentProgram._Enabled || + ctx->Color.BlendEnabled); +} + + +/** + * CopyPixels with the blitter. Don't support zooming, pixel transfer, etc. + */ +static GLboolean +do_blit_copypixels(GLcontext * ctx, + GLint srcx, GLint srcy, + GLsizei width, GLsizei height, + GLint dstx, GLint dsty, GLenum type) +{ + struct intel_context *intel = intel_context(ctx); + struct intel_region *dst; + struct intel_region *src; + struct gl_framebuffer *fb = ctx->DrawBuffer; + struct gl_framebuffer *read_fb = ctx->ReadBuffer; + GLint orig_dstx; + GLint orig_dsty; + GLint orig_srcx; + GLint orig_srcy; + GLboolean flip = GL_FALSE; + + if (type == GL_DEPTH || type == GL_STENCIL) { + if (INTEL_DEBUG & DEBUG_FALLBACKS) + fprintf(stderr, "glCopyPixels() fallback: GL_DEPTH || GL_STENCIL\n"); + return GL_FALSE; + } + + /* Update draw buffer bounds */ + _mesa_update_state(ctx); + + /* Copypixels can be more than a straight copy. Ensure all the + * extra operations are disabled: + */ + if (!intel_check_copypixel_blit_fragment_ops(ctx) || + ctx->Pixel.ZoomX != 1.0F || ctx->Pixel.ZoomY != 1.0F) + return GL_FALSE; + + intel_prepare_render(intel); + + dst = intel_drawbuf_region(intel); + src = copypix_src_region(intel, type); + + if (!src || !dst) + return GL_FALSE; + + intelFlush(&intel->ctx); + + /* Clip to destination buffer. */ + orig_dstx = dstx; + orig_dsty = dsty; + if (!_mesa_clip_to_region(fb->_Xmin, fb->_Ymin, + fb->_Xmax, fb->_Ymax, + &dstx, &dsty, &width, &height)) + goto out; + /* Adjust src coords for our post-clipped destination origin */ + srcx += dstx - orig_dstx; + srcy += dsty - orig_dsty; + + /* Clip to source buffer. */ + orig_srcx = srcx; + orig_srcy = srcy; + if (!_mesa_clip_to_region(0, 0, + read_fb->Width, read_fb->Height, + &srcx, &srcy, &width, &height)) + goto out; + /* Adjust dst coords for our post-clipped source origin */ + dstx += srcx - orig_srcx; + dsty += srcy - orig_srcy; + + /* Flip dest Y if it's a window system framebuffer. */ + if (fb->Name == 0) { + /* copypixels to a window system framebuffer */ + dsty = fb->Height - dsty - height; + flip = !flip; + } + + /* Flip source Y if it's a window system framebuffer. */ + if (read_fb->Name == 0) { + srcy = read_fb->Height - srcy - height; + flip = !flip; + } + + if (!intel_region_copy(intel, + dst, 0, dstx, dsty, + src, 0, srcx, srcy, + width, height, flip, + ctx->Color.ColorLogicOpEnabled ? + ctx->Color.LogicOp : GL_COPY)) { + DBG("%s: blit failure\n", __FUNCTION__); + return GL_FALSE; + } + +out: + intel_check_front_buffer_rendering(intel); + + DBG("%s: success\n", __FUNCTION__); + return GL_TRUE; +} + + +void +intelCopyPixels(GLcontext * ctx, + GLint srcx, GLint srcy, + GLsizei width, GLsizei height, + GLint destx, GLint desty, GLenum type) +{ + if (INTEL_DEBUG & DEBUG_PIXEL) + fprintf(stderr, "%s\n", __FUNCTION__); + + if (do_blit_copypixels(ctx, srcx, srcy, width, height, destx, desty, type)) + return; + + /* this will use swrast if needed */ + _mesa_meta_CopyPixels(ctx, srcx, srcy, width, height, destx, desty, type); +} diff --git a/pool/shard006/C/0118417_sse2-paddw-1.c b/pool/shard006/C/0118417_sse2-paddw-1.c new file mode 100644 index 0000000000000000000000000000000000000000..3ed73299be9789fdf10322e5f3e2303315d33f83 --- /dev/null +++ b/pool/shard006/C/0118417_sse2-paddw-1.c @@ -0,0 +1,40 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -msse2" } */ +/* { dg-require-effective-target sse2 } */ + +#ifndef CHECK_H +#define CHECK_H "sse2-check.h" +#endif + +#ifndef TEST +#define TEST sse2_test +#endif + +#include CHECK_H + +#include + +static __m128i +__attribute__((noinline, unused)) +test (__m128i s1, __m128i s2) +{ + return _mm_add_epi16 (s1, s2); +} + +static void +TEST (void) +{ + union128i_w u, s1, s2; + short e[8]; + int i; + + s1.x = _mm_set_epi16 (10,20,30,90,-80,-40,-100,-15); + s2.x = _mm_set_epi16 (11, 98, 76, -100, -34, -78, -39, 14); + u.x = test (s1.x, s2.x); + + for (i = 0; i < 8; i++) + e[i] = s1.a[i] + s2.a[i]; + + if (check_union128i_w (u, e)) + abort (); +} diff --git a/pool/shard006/C/0118418_encoders.c b/pool/shard006/C/0118418_encoders.c new file mode 100644 index 0000000000000000000000000000000000000000..478b3885cb1183b700c0b03627412e89692fd998 --- /dev/null +++ b/pool/shard006/C/0118418_encoders.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2014-2017 Pavel Kalvoda + * + * libcbor is free software; you can redistribute it and/or modify + * it under the terms of the MIT license. See LICENSE for details. + */ + +#include "encoders.h" + +#if HAVE_ENDIAN_H +#include +#endif + +size_t _cbor_encode_uint8(uint8_t value, unsigned char *buffer, size_t buffer_size, uint8_t offset) +{ + if (value <= 23) { + if (buffer_size >= 1) { + buffer[0] = value + offset; + return 1; + } + } else { + if (buffer_size >= 2) { + buffer[0] = 0x18 + offset; + buffer[1] = value; + return 2; + } + } + return 0; +} + +size_t _cbor_encode_uint16(uint16_t value, unsigned char *buffer, size_t buffer_size, uint8_t offset) +{ + if (buffer_size >= 3) { + buffer[0] = 0x19 + offset; + +#ifdef HAVE_ENDIAN_H + *(uint16_t *) &buffer[1] = htobe16(value); +#else + #ifdef IS_BIG_ENDIAN + *(uint16_t *) &buffer[1] = value; + #else + buffer[1] = value >> 8; + buffer[2] = value; + #endif +#endif + + return 3; + } else + return 0; +} + +size_t _cbor_encode_uint32(uint32_t value, unsigned char *buffer, size_t buffer_size, uint8_t offset) +{ + if (buffer_size >= 5) { + buffer[0] = 0x1A + offset; + +#ifdef HAVE_ENDIAN_H + *(uint32_t *) &buffer[1] = htobe32(value); +#else + #ifdef IS_BIG_ENDIAN + *(uint32_t *) &buffer[1] = value; + #else + buffer[1] = value >> 24; + buffer[2] = value >> 16; + buffer[3] = value >> 8; + buffer[4] = value; + #endif +#endif + + return 5; + } else + return 0; +} + +size_t _cbor_encode_uint64(uint64_t value, unsigned char *buffer, size_t buffer_size, uint8_t offset) +{ + if (buffer_size >= 9) { + buffer[0] = 0x1B + offset; + +#ifdef HAVE_ENDIAN_H + *(uint64_t *) &buffer[1] = htobe64(value); +#else + #ifdef IS_BIG_ENDIAN + *(uint64_t *) &buffer[1] = value; + #else + buffer[1] = value >> 56; + buffer[2] = value >> 48; + buffer[3] = value >> 40; + buffer[4] = value >> 32; + buffer[5] = value >> 24; + buffer[6] = value >> 16; + buffer[7] = value >> 8; + buffer[8] = value; + #endif +#endif + + return 9; + } else + return 0; +} + +size_t _cbor_encode_uint(uint64_t value, unsigned char *buffer, size_t buffer_size, uint8_t offset) +{ + if (value <= UINT16_MAX) if (value <= UINT8_MAX) + return _cbor_encode_uint8((uint8_t) value, buffer, buffer_size, offset); + else + return _cbor_encode_uint16((uint16_t) value, buffer, buffer_size, offset); + else if (value <= UINT32_MAX) + return _cbor_encode_uint32((uint32_t) value, buffer, buffer_size, offset); + else + return _cbor_encode_uint64((uint64_t) value, buffer, buffer_size, offset); +} diff --git a/pool/shard006/C/0118427_tsl_user.c b/pool/shard006/C/0118427_tsl_user.c new file mode 100644 index 0000000000000000000000000000000000000000..a31913e698f74bdfddcd00466dc4ee8ba19db71c --- /dev/null +++ b/pool/shard006/C/0118427_tsl_user.c @@ -0,0 +1,329 @@ +/** + ****************************************************************************** + * @file TouchSensing\TouchSensing_Linear\Src\tsl_user.c + * @author MCD Application Team + * @brief Touch-Sensing user configuration file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +#include "tsl_user.h" + +/*============================================================================*/ +/* Channels */ +/*============================================================================*/ + +/* Source and Configuration (ROM) */ +CONST TSL_ChannelSrc_T MyChannels_Src[TSLPRM_TOTAL_CHANNELS] = +{ + { CHANNEL_0_SRC, CHANNEL_0_IO_MSK, CHANNEL_0_GRP_MSK }, + { CHANNEL_1_SRC, CHANNEL_1_IO_MSK, CHANNEL_1_GRP_MSK }, + { CHANNEL_2_SRC, CHANNEL_2_IO_MSK, CHANNEL_2_GRP_MSK } +}; + +/* Destination (ROM) */ +CONST TSL_ChannelDest_T MyChannels_Dest[TSLPRM_TOTAL_CHANNELS] = +{ + { CHANNEL_0_DEST }, + { CHANNEL_1_DEST }, + { CHANNEL_2_DEST } +}; + +/* Data (RAM) */ +TSL_ChannelData_T MyChannels_Data[TSLPRM_TOTAL_CHANNELS]; + +/*============================================================================*/ +/* Banks */ +/*============================================================================*/ + +/* List (ROM) */ +CONST TSL_Bank_T MyBanks[TSLPRM_TOTAL_BANKS] = { + {&MyChannels_Src[0], &MyChannels_Dest[0], MyChannels_Data, BANK_0_NBCHANNELS, BANK_0_MSK_CHANNELS, BANK_0_MSK_GROUPS}, +}; + +/*============================================================================*/ +/* Linear and Rotary sensors */ +/*============================================================================*/ + +/* Data (RAM) */ +TSL_LinRotData_T MyLinRots_Data[TSLPRM_TOTAL_LINROTS]; + +/* Parameters (RAM) */ +TSL_LinRotParam_T MyLinRots_Param[TSLPRM_TOTAL_LINROTS]; + +/* State Machine (ROM) */ + +void MyLinRots_ErrorStateProcess(void); +void MyLinRots_OffStateProcess(void); + +CONST TSL_State_T MyLinRots_StateMachine[] = +{ + /* Calibration states */ + /* 0 */ { TSL_STATEMASK_CALIB, TSL_linrot_CalibrationStateProcess }, + /* 1 */ { TSL_STATEMASK_DEB_CALIB, TSL_linrot_DebCalibrationStateProcess }, + /* Release states */ + /* 2 */ { TSL_STATEMASK_RELEASE, TSL_linrot_ReleaseStateProcess }, +#if TSLPRM_USE_PROX > 0 + /* 3 */ { TSL_STATEMASK_DEB_RELEASE_PROX, TSL_linrot_DebReleaseProxStateProcess }, +#else + /* 3 */ { TSL_STATEMASK_DEB_RELEASE_PROX, 0 }, +#endif + /* 4 */ { TSL_STATEMASK_DEB_RELEASE_DETECT, TSL_linrot_DebReleaseDetectStateProcess }, + /* 5 */ { TSL_STATEMASK_DEB_RELEASE_TOUCH, TSL_linrot_DebReleaseTouchStateProcess }, +#if TSLPRM_USE_PROX > 0 + /* Proximity states */ + /* 6 */ { TSL_STATEMASK_PROX, TSL_linrot_ProxStateProcess }, + /* 7 */ { TSL_STATEMASK_DEB_PROX, TSL_linrot_DebProxStateProcess }, + /* 8 */ { TSL_STATEMASK_DEB_PROX_DETECT, TSL_linrot_DebProxDetectStateProcess }, + /* 9 */ { TSL_STATEMASK_DEB_PROX_TOUCH, TSL_linrot_DebProxTouchStateProcess }, +#else + /* 6 */ { TSL_STATEMASK_PROX, 0 }, + /* 7 */ { TSL_STATEMASK_DEB_PROX, 0 }, + /* 8 */ { TSL_STATEMASK_DEB_PROX_DETECT, 0 }, + /* 9 */ { TSL_STATEMASK_DEB_PROX_TOUCH, 0 }, +#endif + /* Detect states */ + /* 10 */ { TSL_STATEMASK_DETECT, TSL_linrot_DetectStateProcess }, + /* 11 */ { TSL_STATEMASK_DEB_DETECT, TSL_linrot_DebDetectStateProcess }, + /* Touch state */ + /* 12 */ { TSL_STATEMASK_TOUCH, TSL_linrot_TouchStateProcess }, + /* Error states */ + /* 13 */ { TSL_STATEMASK_ERROR, MyLinRots_ErrorStateProcess }, + /* 14 */ { TSL_STATEMASK_DEB_ERROR_CALIB, TSL_linrot_DebErrorStateProcess }, + /* 15 */ { TSL_STATEMASK_DEB_ERROR_RELEASE, TSL_linrot_DebErrorStateProcess }, + /* 16 */ { TSL_STATEMASK_DEB_ERROR_PROX, TSL_linrot_DebErrorStateProcess }, + /* 17 */ { TSL_STATEMASK_DEB_ERROR_DETECT, TSL_linrot_DebErrorStateProcess }, + /* 18 */ { TSL_STATEMASK_DEB_ERROR_TOUCH, TSL_linrot_DebErrorStateProcess }, + /* Other states */ + /* 19 */ { TSL_STATEMASK_OFF, MyLinRots_OffStateProcess } +}; + +/* Methods for "extended" type (ROM) */ +CONST TSL_LinRotMethods_T MyLinRots_Methods = +{ + TSL_linrot_Init, + TSL_linrot_Process, + TSL_linrot_CalcPos +}; + +/* Delta Normalization Process + The MSB is the integer part, the LSB is the real part + Examples: + - To apply a factor 1.10: + 0x01 to the MSB + 0x1A to the LSB (0.10 x 256 = 25.6 -> rounded to 26 = 0x1A) + - To apply a factor 0.90: + 0x00 to the MSB + 0xE6 to the LSB (0.90 x 256 = 230.4 -> rounded to 230 = 0xE6) +*/ +CONST uint16_t MyLinRot0_DeltaCoeff[3] = {0x0100, 0x0100, 0x0100}; + +/* LinRots list (ROM)*/ +CONST TSL_LinRot_T MyLinRots[TSLPRM_TOTAL_LINROTS] = +{ + { + /* LinRot sensor 0 = S1 */ + &MyLinRots_Data[0], + &MyLinRots_Param[0], + &MyChannels_Data[CHANNEL_0_DEST], + 3, /* Number of channels */ + MyLinRot0_DeltaCoeff, + (TSL_tsignPosition_T *)TSL_POSOFF_3CH_LIN_H, + TSL_SCTCOMP_3CH_LIN_H, + TSL_POSCORR_3CH_LIN_H, + MyLinRots_StateMachine, + &MyLinRots_Methods + } +}; + +/*============================================================================*/ +/* Generic Objects */ +/*============================================================================*/ + +/* List (ROM) */ +CONST TSL_Object_T MyObjects[TSLPRM_TOTAL_OBJECTS] = +{ + { TSL_OBJ_LINEAR, (TSL_LinRot_T *)&MyLinRots[0] } +}; + +/* Group (RAM) */ +TSL_ObjectGroup_T MyObjGroup = +{ + &MyObjects[0], /* First object */ + TSLPRM_TOTAL_OBJECTS, /* Number of objects */ + 0x00, /* State mask reset value */ + TSL_STATE_NOT_CHANGED /* Current state */ +}; + +/*============================================================================*/ +/* TSL Common Parameters placed in RAM or ROM */ +/* --> external declaration in tsl_conf.h */ +/*============================================================================*/ + +TSL_Params_T TSL_Params = +{ + TSLPRM_ACQ_MIN, + TSLPRM_ACQ_MAX, + TSLPRM_CALIB_SAMPLES, + TSLPRM_DTO, +#if TSLPRM_TOTAL_TKEYS > 0 + MyTKeys_StateMachine, /* Default state machine for TKeys */ + &MyTKeys_Methods, /* Default methods for TKeys */ +#endif +#if TSLPRM_TOTAL_LNRTS > 0 + MyLinRots_StateMachine, /* Default state machine for LinRots */ + &MyLinRots_Methods /* Default methods for LinRots */ +#endif +}; + +/* Private functions prototype -----------------------------------------------*/ + +/* Global variables ----------------------------------------------------------*/ + +__IO TSL_tTick_ms_T ECSLastTick; /* Hold the last time value for ECS */ + +/** + * @brief Initialize the STMTouch Driver + * @param None + * @retval None + */ +void tsl_user_Init(void) +{ + TSL_obj_GroupInit(&MyObjGroup); /* Init Objects */ + + TSL_Init(MyBanks); /* Init acquisition module */ + + tsl_user_SetThresholds(); /* Init thresholds for each object individually (optional) */ +} + + +/** + * @brief Execute STMTouch Driver main State machine + * @param None + * @retval status Return TSL_STATUS_OK if the acquisition is done + */ +tsl_user_status_t tsl_user_Exec(void) +{ + static uint32_t idx_bank = 0; + static uint32_t config_done = 0; + tsl_user_status_t status = TSL_USER_STATUS_BUSY; + + /* Configure and start bank acquisition */ + if (!config_done) + { + TSL_acq_BankConfig(idx_bank); + TSL_acq_BankStartAcq(); + config_done = 1; + } + + /* Check end of acquisition (polling mode) and read result */ + if (TSL_acq_BankWaitEOC() == TSL_STATUS_OK) + { + STMSTUDIO_LOCK; + TSL_acq_BankGetResult(idx_bank, 0, 0); + STMSTUDIO_UNLOCK; + idx_bank++; /* Next bank */ + config_done = 0; + } + + /* Process objects, DxS and ECS + Check if all banks have been acquired + */ + if (idx_bank > TSLPRM_TOTAL_BANKS-1) + { + /* Reset flags for next banks acquisition */ + idx_bank = 0; + config_done = 0; + + /* Process Objects */ + TSL_obj_GroupProcess(&MyObjGroup); + + /* DxS processing (if TSLPRM_USE_DXS option is set) */ + TSL_dxs_FirstObj(&MyObjGroup); + + /* ECS every 100ms */ + if (TSL_tim_CheckDelay_ms(100, &ECSLastTick) == TSL_STATUS_OK) + { + if (TSL_ecs_Process(&MyObjGroup) == TSL_STATUS_OK) + { + status = TSL_USER_STATUS_OK_ECS_ON; + } + else + { + status = TSL_USER_STATUS_OK_ECS_OFF; + } + } + else + { + status = TSL_USER_STATUS_OK_NO_ECS; + } + } + else + { + status = TSL_USER_STATUS_BUSY; + } + + return status; +} + +/** + * @brief Set thresholds for each object (optional). + * @param None + * @retval None + */ +void tsl_user_SetThresholds(void) +{ + /* Example: Decrease the Detect thresholds for the TKEY 0 + MyTKeys_Param[0].DetectInTh -= 10; + MyTKeys_Param[0].DetectOutTh -= 10; + */ +} + +/** + * @brief Executed when a sensor is in Error state + * @param None + * @retval None + */ +void MyLinRots_ErrorStateProcess(void) +{ + /* Add here your own processing when a sensor is in Error state */ +} + + +/** + * @brief Executed when a sensor is in Off state + * @param None + * @retval None + */ +void MyLinRots_OffStateProcess(void) +{ + /* Add here your own processing when a sensor is in Off state */ +} + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0118435_mpls_pkt_gen.c b/pool/shard006/C/0118435_mpls_pkt_gen.c new file mode 100644 index 0000000000000000000000000000000000000000..9ff71a0a7e6e91886117b4105d0f26d31c3822c8 --- /dev/null +++ b/pool/shard006/C/0118435_mpls_pkt_gen.c @@ -0,0 +1,301 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include"csum.h" + +#define PACKET_LENGTH 1024 + +#define ETH_TYPE_IP 0x0800 +#define ETH_TYPE_MPLS_UNICAST 0x8847 + +typedef unsigned char uint8_t; +typedef unsigned int uint32_t; + +typedef union +{ + struct + { + #if BYTE_ORDER == BIG_ENDIAN + uint32_t label:20; + uint8_t exp:3; + uint8_t s:1; + uint8_t ttl:8; + #else + uint8_t ttl:8; + uint8_t s:1; + uint8_t exp:3; + uint32_t label:20; + #endif + }; + uint32_t value; +} mpls_header; + +int CreateRawSocket(int protocol_to_sniff) +{ + int rawsock; + + if((rawsock = socket(PF_PACKET, SOCK_RAW, htons(protocol_to_sniff)))== -1) + { + perror("Error creating raw socket: "); + exit(-1); + } + + return rawsock; +} + +int BindRawSocketToInterface(char *device, int rawsock, int protocol) +{ + + struct sockaddr_ll sll; + struct ifreq ifr; + + bzero(&sll, sizeof(sll)); + bzero(&ifr, sizeof(ifr)); + + /* First Get the Interface Index */ + + + strncpy((char *)ifr.ifr_name, device, IFNAMSIZ); + if((ioctl(rawsock, SIOCGIFINDEX, &ifr)) == -1) + { + printf("Error getting Interface index !\n"); + exit(-1); + } + + /* Bind our raw socket to this interface */ + + sll.sll_family = AF_PACKET; + sll.sll_ifindex = ifr.ifr_ifindex; + sll.sll_protocol = htons(protocol); + + + if((bind(rawsock, (struct sockaddr *)&sll, sizeof(sll)))== -1) + { + perror("Error binding raw socket to interface\n"); + exit(-1); + } + + return 1; + +} + + +int SendRawPacket(int rawsock, unsigned char *pkt, int pkt_len) +{ + int sent= 0; + + /* A simple write on the socket ..thats all it takes ! */ + + if((sent = write(rawsock, pkt, pkt_len)) != pkt_len) + { + return 0; + } + + return 1; + + +} + + #define ETH_DST_ADDR 0 + #define ETH_SRC_ADDR ETH_DST_ADDR+ETH_ALEN + #define ETH_TYPE_ADDR ETH_SRC_ADDR+ETH_ALEN + #define MPLS_HDR_ADDR ETH_TYPE_ADDR+2 + #define IP_HDR_ADDR MPLS_HDR_ADDR+4 + +void write_ethernet_header(unsigned char *packet, unsigned short eth_type) +{ + /*our MAC address*/ + unsigned char src_mac[6] = {0x00, 0x1a, 0x4b, 0x53, 0xf7, 0x2c}; + + /*other host MAC address*/ + //unsigned char dest_mac[6] = {0x00, 0x1a, 0x4b, 0x53, 0xf7, 0x2d}; + unsigned char dest_mac[6] = {0x00, 0x1a, 0x4b, 0x53, 0xf7, 0x2c}; + + + //unsigned char eth_type[2] = {0x88, 0x47}; + eth_type = htons(eth_type); + + memcpy((void*)(packet+ETH_DST_ADDR), (void*)dest_mac, ETH_ALEN); + memcpy((void*)(packet+ETH_SRC_ADDR), (void*)src_mac, ETH_ALEN); + memcpy((void*)(packet+ETH_TYPE_ADDR), (void*)ð_type, 2); + + + +} + + +void write_mpls_header(unsigned char *packet, unsigned int label, unsigned int exp, unsigned int s, unsigned int ttl) +{ + mpls_header mpls_header1; + + mpls_header1.ttl = ttl; + mpls_header1.exp = exp; + mpls_header1.s = s; + mpls_header1.label = label; + + + //printf("mpls_header1 = %x\n", mpls_header1.value); + //printf("mpls_header1.label = %u\n" + // "mpls_header1.CoS = %u\n" + // "mpls_header1.s = %u\n" + // "mpls_header1.TTL = %u\n", + //mpls_header1.label, mpls_header1.exp, mpls_header1.s, mpls_header1.ttl); + + uint32_t mpls_wire = htonl(mpls_header1.value); + + memcpy((void*)(packet), (void *) &mpls_wire, 4); +} + +void write_ip_header(unsigned char *packet, unsigned short ip_pkt_len) +{ + +// unsigned short ip_pkt_len = PACKET_LENGTH - (IP_HDR_ADDR); + unsigned char ip_hdr[20] = { 0x45, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0xFF, 0x11, 0xa3, 0xfc, + 0x0a, 0x00, 0x00, 0x02, + 0x0a, 0x00, 0x00, 0x01}; + + ip_hdr[2] = (0xFF00 & ip_pkt_len) >> 8; + ip_hdr[3] = 0x00FF & ip_pkt_len; + + memcpy((void *)(packet), (void *) &ip_hdr, 20); + +} + +void write_udp_header(unsigned char *packet, unsigned short udp_len) +{ +// unsigned short udp_len = PACKET_LENGTH - (IP_HDR_ADDR) - 20; + unsigned char udp_hdr[8] = {0x0F, 0x00, 0x0F, 0x00, + 0x00, 0x00, 0x00, 0x00}; + + udp_hdr[4] = (0xFF00 & udp_len) >> 8; + udp_hdr[5] = (0x00FF & udp_len); + + + //printf("udp_len = %u udp_hdr[4]=%02x udp_hdr[5]=%02x\n", udp_len +/// ,udp_hdr[4], udp_hdr[5]); + + + memcpy((void *)(packet), (void *) &udp_hdr, 8); + +} + +void write_ip_csum(unsigned char *packet, unsigned short len) +{ + // len should be just the length of the header + unsigned short ip_csum = 0; + // initialize the ip checksum field to 0 for + // purposes of calculating the header + memcpy(packet + 10, &ip_csum, 2); + + // appears to return in network byte order somehow + ip_csum = csum(packet, len); + memcpy(packet + 10, &ip_csum, 2); +} + + +/* argv[1] is the device e.g. eth0 + argv[2] is the number of packets to send +*/ + +main(int argc, char **argv) +{ + + int raw; + unsigned char packet[PACKET_LENGTH]; + unsigned char *packet_pos = packet; + unsigned char *ip_pos; + char scanfstr[1024]; + unsigned int label, exp, ttl; + int num_of_pkts; + int i = 0; + + if (argc != 4) { + printf("usage: %s <# packets> <#labels>\ndevice = device to send on e.g. eth0\nnumber of arguments = %u\n", argv[0], argc); + return -1; + } + + num_of_pkts = atoi(argv[2]); + + /* Set the packet to all A's */ + + memset(packet, 'A', PACKET_LENGTH); + + unsigned int num_labels = atoi(argv[argc-1]); + + + + if (!num_labels) { + write_ethernet_header(packet_pos, ETH_TYPE_IP); + } else { + write_ethernet_header(packet_pos, ETH_TYPE_MPLS_UNICAST); + } + packet_pos += MPLS_HDR_ADDR; + + + printf("Enter labels starting from top of stack:\n" + "------------------------------------------\n"); + for (i = 0; i < num_labels; i++) + { + printf("Enter label value for label %u: ", i); + scanf("%s",scanfstr); + label = atoi(scanfstr); + printf("Enter exp value for label %u: ", i); + scanf("%s",scanfstr); + exp = atoi(scanfstr); + printf("Enter ttl value for label %u: ", i); + scanf("%s",scanfstr); + ttl = atoi(scanfstr); + printf("i = %u num_labels = %u\n", i, num_labels); + if (i == num_labels -1) { + write_mpls_header(packet_pos, label, exp, 1, ttl); + } else { + write_mpls_header(packet_pos, label, exp, 0, ttl); + } + packet_pos += 4; + } + + ip_pos = packet_pos; + write_ip_header(packet_pos, PACKET_LENGTH - (ip_pos - packet)); + packet_pos += 20; + + write_udp_header(packet_pos, PACKET_LENGTH -(packet_pos - packet)); + packet_pos += 8; + + write_ip_csum(ip_pos, 20); + + /* Create the raw socket */ + + raw = CreateRawSocket(ETH_P_ALL); + + /* Bind raw socket to interface */ + + BindRawSocketToInterface(argv[1], raw, ETH_P_ALL); + + + while((num_of_pkts--)>0) + { + + if(!SendRawPacket(raw, packet, PACKET_LENGTH)) + { + perror("Error sending packet"); + } + else + { + printf("Packet sent successfully\n"); + } + } + + close(raw); + + return 0; +} + diff --git a/pool/shard006/C/0118436_system.c b/pool/shard006/C/0118436_system.c new file mode 100644 index 0000000000000000000000000000000000000000..9da1ef7b6af1fef8eb122bb2674dcab83cdc07c6 --- /dev/null +++ b/pool/shard006/C/0118436_system.c @@ -0,0 +1,107 @@ +/* + * system.c - a driver for reserving pnp system resources + * + * Some code is based on pnpbios_core.c + * Copyright 2002 Adam Belay + * + */ + +#include +#include +#include +#include +#include +#include + +static const struct pnp_device_id pnp_dev_table[] = { + /* General ID for reserving resources */ + { "PNP0c02", 0 }, + /* memory controller */ + { "PNP0c01", 0 }, + { "", 0 } +}; + +static void __init reserve_ioport_range(char *pnpid, int start, int end) +{ + struct resource *res; + char *regionid; + + regionid = kmalloc(16, GFP_KERNEL); + if ( regionid == NULL ) + return; + snprintf(regionid, 16, "pnp %s", pnpid); + res = request_region(start,end-start+1,regionid); + if ( res == NULL ) + kfree( regionid ); + else + res->flags &= ~IORESOURCE_BUSY; + /* + * Failures at this point are usually harmless. pci quirks for + * example do reserve stuff they know about too, so we may well + * have double reservations. + */ + printk(KERN_INFO + "pnp: %s: ioport range 0x%x-0x%x %s reserved\n", + pnpid, start, end, + NULL != res ? "has been" : "could not be" + ); + + return; +} + +static void __init reserve_resources_of_dev( struct pnp_dev *dev ) +{ + int i; + + for (i=0;idev.bus_id, + pnp_port_start(dev, i), + pnp_port_end(dev, i) + ); + } + + return; +} + +static int system_pnp_probe(struct pnp_dev * dev, const struct pnp_device_id *dev_id) +{ + reserve_resources_of_dev(dev); + return 0; +} + +static struct pnp_driver system_pnp_driver = { + .name = "system", + .id_table = pnp_dev_table, + .flags = PNP_DRIVER_RES_DO_NOT_CHANGE, + .probe = system_pnp_probe, + .remove = NULL, +}; + +static int __init pnp_system_init(void) +{ + return pnp_register_driver(&system_pnp_driver); +} + +subsys_initcall(pnp_system_init); diff --git a/pool/shard006/C/0118438_gstalsadeviceprobe.c b/pool/shard006/C/0118438_gstalsadeviceprobe.c new file mode 100644 index 0000000000000000000000000000000000000000..337c21bcea822d8cfab0356d0e52f89f4144733a --- /dev/null +++ b/pool/shard006/C/0118438_gstalsadeviceprobe.c @@ -0,0 +1,216 @@ +/* Copyright (C) 2001 CodeFactory AB + * Copyright (C) 2001 Thomas Nyberg + * Copyright (C) 2001-2002 Andy Wingo + * Copyright (C) 2003 Benjamin Otte + * Copyright (C) 2005 Tim-Philipp Müller + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +/* FIXME 0.11: suppress warnings for deprecated API such as GValueArray + * with newer GLib versions (>= 2.31.0) */ +#define GLIB_DISABLE_DEPRECATION_WARNINGS + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstalsadeviceprobe.h" +#include "gst/interfaces/propertyprobe.h" + +G_LOCK_DEFINE_STATIC (probe_lock); + +static const GList * +gst_alsa_device_property_probe_get_properties (GstPropertyProbe * probe) +{ + GObjectClass *klass = G_OBJECT_GET_CLASS (probe); + static GList *list = NULL; + + /* well, not perfect, but better than no locking at all. + * In the worst case we leak a list node, so who cares? */ + G_LOCK (probe_lock); + + if (!list) { + GParamSpec *pspec; + + pspec = g_object_class_find_property (klass, "device"); + list = g_list_append (NULL, pspec); + } + + G_UNLOCK (probe_lock); + + return list; +} + +static GList * +gst_alsa_get_device_list (snd_pcm_stream_t stream) +{ + snd_ctl_t *handle; + int card, dev; + snd_ctl_card_info_t *info; + snd_pcm_info_t *pcminfo; + gboolean mixer = (stream == -1); + GList *list = NULL; + + if (stream == -1) + stream = 0; + + snd_ctl_card_info_malloc (&info); + snd_pcm_info_malloc (&pcminfo); + card = -1; + + if (snd_card_next (&card) < 0 || card < 0) { + /* no soundcard found */ + GST_WARNING ("No soundcard found"); + goto beach; + } + + while (card >= 0) { + gchar name[32]; + + g_snprintf (name, sizeof (name), "hw:%d", card); + if (snd_ctl_open (&handle, name, 0) < 0) { + goto next_card; + } + if (snd_ctl_card_info (handle, info) < 0) { + snd_ctl_close (handle); + goto next_card; + } + + if (mixer) { + list = g_list_append (list, g_strdup (name)); + } else { + dev = -1; + while (1) { + gchar *gst_device; + + snd_ctl_pcm_next_device (handle, &dev); + + if (dev < 0) + break; + snd_pcm_info_set_device (pcminfo, dev); + snd_pcm_info_set_subdevice (pcminfo, 0); + snd_pcm_info_set_stream (pcminfo, stream); + if (snd_ctl_pcm_info (handle, pcminfo) < 0) { + continue; + } + + gst_device = g_strdup_printf ("hw:%d,%d", card, dev); + list = g_list_append (list, gst_device); + } + } + snd_ctl_close (handle); + next_card: + if (snd_card_next (&card) < 0) { + break; + } + } + +beach: + snd_ctl_card_info_free (info); + snd_pcm_info_free (pcminfo); + + return list; +} + +static void +gst_alsa_device_property_probe_probe_property (GstPropertyProbe * probe, + guint prop_id, const GParamSpec * pspec) +{ + if (!g_str_equal (pspec->name, "device")) { + G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec); + } +} + +static gboolean +gst_alsa_device_property_probe_needs_probe (GstPropertyProbe * probe, + guint prop_id, const GParamSpec * pspec) +{ + /* don't cache probed data */ + return TRUE; +} + +static GValueArray * +gst_alsa_device_property_probe_get_values (GstPropertyProbe * probe, + guint prop_id, const GParamSpec * pspec) +{ + GstElementClass *klass; + const GList *templates; + snd_pcm_stream_t mode = -1; + GValueArray *array; + GValue value = { 0, }; + GList *l, *list; + + if (!g_str_equal (pspec->name, "device")) { + G_OBJECT_WARN_INVALID_PROPERTY_ID (probe, prop_id, pspec); + return NULL; + } + + klass = GST_ELEMENT_GET_CLASS (GST_ELEMENT (probe)); + + /* I'm pretty sure ALSA has a good way to do this. However, their cool + * auto-generated documentation is pretty much useless if you try to + * do function-wise look-ups. */ + /* we assume one pad template at max [zero=mixer] */ + templates = gst_element_class_get_pad_template_list (klass); + if (templates) { + if (GST_PAD_TEMPLATE_DIRECTION (templates->data) == GST_PAD_SRC) + mode = SND_PCM_STREAM_CAPTURE; + else + mode = SND_PCM_STREAM_PLAYBACK; + } + + list = gst_alsa_get_device_list (mode); + + if (list == NULL) { + GST_LOG_OBJECT (probe, "No devices found"); + return NULL; + } + + array = g_value_array_new (g_list_length (list)); + g_value_init (&value, G_TYPE_STRING); + for (l = list; l != NULL; l = l->next) { + GST_LOG_OBJECT (probe, "Found device: %s", (gchar *) l->data); + g_value_take_string (&value, (gchar *) l->data); + l->data = NULL; + g_value_array_append (array, &value); + } + g_value_unset (&value); + g_list_free (list); + + return array; +} + +static void +gst_alsa_property_probe_interface_init (GstPropertyProbeInterface * iface) +{ + iface->get_properties = gst_alsa_device_property_probe_get_properties; + iface->probe_property = gst_alsa_device_property_probe_probe_property; + iface->needs_probe = gst_alsa_device_property_probe_needs_probe; + iface->get_values = gst_alsa_device_property_probe_get_values; +} + +void +gst_alsa_type_add_device_property_probe_interface (GType type) +{ + static const GInterfaceInfo probe_iface_info = { + (GInterfaceInitFunc) gst_alsa_property_probe_interface_init, + NULL, + NULL, + }; + + g_type_add_interface_static (type, GST_TYPE_PROPERTY_PROBE, + &probe_iface_info); +} diff --git a/pool/shard006/C/0118439_rmnt.c b/pool/shard006/C/0118439_rmnt.c new file mode 100644 index 0000000000000000000000000000000000000000..15c56a9954b1d248b70a7e7660870d74c63b8db4 --- /dev/null +++ b/pool/shard006/C/0118439_rmnt.c @@ -0,0 +1,243 @@ +/* + * rmnt.c -- readmnt() function for lsof library + */ + + +/* + * Copyright 1997 Purdue Research Foundation, West Lafayette, Indiana + * 47907. All rights reserved. + * + * Written by Victor A. Abell + * + * This software is not subject to any license of the American Telephone + * and Telegraph Company or the Regents of the University of California. + * + * Permission is granted to anyone to use this software for any purpose on + * any computer system, and to alter it and redistribute it freely, subject + * to the following restrictions: + * + * 1. Neither the authors nor Purdue University are responsible for any + * consequences of the use of this software. + * + * 2. The origin of this software must not be misrepresented, either by + * explicit claim or by omission. Credit to the authors and Purdue + * University must appear in documentation and sources. + * + * 3. Altered versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * + * 4. This notice may not be removed or altered. + */ + + +#include "../machine.h" + +#if defined(USE_LIB_READMNT) + +# if !defined(lint) +static char copyright[] = +"@(#) Copyright 1997 Purdue Research Foundation.\nAll rights reserved.\n"; +static char *rcsid = "$Id: rmnt.c,v 1.11 2006/03/27 22:56:06 abe Exp $"; +# endif /* !defined(lint) */ + +#include "../lsof.h" + + + +/* + * The caller may define: + * + * 1. An RMNT_EXPDEV macro to expand (ala EP/IX) device numbers; + * + * EP/IX, for example, uses: + * + * #define RMNT_EXPDEV(n) expdev(n) + * + * 2. A custom macro, MNTSKIP, for making decisions to skip entries + * -- e.g., ones whose mnt_type is MNTTYPE_IGNORE. + * + * 3. RMNT_FSTYPE to specify the member name of the character string of the + * mntent structure containing the file system type, and MOUNTS_FSTYPE to + * specify the member name of the character string pointer of the local + * mounts structure where RMNT_FSTYPE is to be copied. + * + * 4. RMNT_STAT_FSTYPE to specify the member name of the stat structure + * containing an integer file system type, and MOUNTS_STAT_FSTYPE to + * specify the member name of the integer in the local mounts structure + * where RMNT_STAT_FSTYPE is to be copied. + * + */ + +#if !defined(RMNT_EXPDEV) +#define RMNT_EXPDEV(n) n +#endif /* !defined(RMNT_EXPDEV) */ + + +/* + * Local static definitions + */ + +static struct mounts *Lmi = (struct mounts *)NULL; /* local mount info */ +static int Lmist = 0; /* Lmi status */ + + +/* + * readmnt() - read mount table + */ + +struct mounts * +readmnt() +{ + char *dn = (char *)NULL; + char *ln; + FILE *mfp; + struct mntent *mp; + struct mounts *mtp; + char *opt, *opte; + struct stat sb; + + if (Lmi || Lmist) + return(Lmi); +/* + * Open access to the mount table. + */ + if (!(mfp = setmntent(MOUNTED, "r"))) { + (void) fprintf(stderr, "%s: can't access %s\n", Pn, MOUNTED); + Exit(1); + } +/* + * Read mount table entries. + */ + while ((mp = getmntent(mfp))) { + +#if defined(MNTSKIP) + /* + * Specfy in the MNTSKIP macro the decisions needed to determine + * that this entry should be skipped. + * + * Typically entries whose mnt_type is MNTTYPE_IGNORE are skipped. + * + * The MNTSKIP macro allows the caller to use other tests. + */ + MNTSKIP +#endif /* MNTSKIP */ + + /* + * Interpolate a possible symbolic directory link. + */ + if (dn) + (void) free((FREE_P *)dn); + if (!(dn = mkstrcpy(mp->mnt_dir, (MALLOC_S *)NULL))) + goto no_space_for_mount; + if (!(ln = Readlink(dn))) { + if (!Fwarn) + (void) fprintf(stderr, + " Output information may be incomplete.\n"); + continue; + } + if (ln != dn) { + (void) free((FREE_P *)dn); + dn = ln; + } + if (*dn != '/') + continue; + /* + * Stat() the directory. + */ + if (statsafely(dn, &sb)) { + if (!Fwarn) { + (void) fprintf(stderr, "%s: WARNING: can't stat() ", Pn); + safestrprt(mp->mnt_type, stderr, 0); + (void) fprintf(stderr, " file system "); + safestrprt(mp->mnt_dir, stderr, 1); + (void) fprintf(stderr, + " Output information may be incomplete.\n"); + } + if ((opt = strstr(mp->mnt_opts, "dev="))) { + (void) zeromem(&sb, sizeof(sb)); + if ((opte = x2dev(opt + 4, (dev_t *)&sb.st_dev))) { + sb.st_mode = S_IFDIR | 0777; + if (!Fwarn) + (void) fprintf(stderr, + " assuming \"%.*s\" from %s\n", + (int)(opte - opt), opt, MOUNTED); + } else + opt = (char *)NULL; + } + if (!opt) + continue; + } + /* + * Allocate and fill a local mounts structure with the directory + * (mounted) information. + */ + if (!(mtp = (struct mounts *)malloc(sizeof(struct mounts)))) { + +no_space_for_mount: + + (void) fprintf(stderr, "%s: no space for mount at ", Pn); + safestrprt(mp->mnt_fsname, stderr, 0); + (void) fprintf(stderr, " ("); + safestrprt(mp->mnt_dir, stderr, 0); + (void) fprintf(stderr, ")\n"); + Exit(1); + } + mtp->dir = dn; + dn = (char *)NULL; + mtp->next = Lmi; + mtp->dev = RMNT_EXPDEV(sb.st_dev); + mtp->rdev = RMNT_EXPDEV(sb.st_rdev); + mtp->inode = (INODETYPE)sb.st_ino; + mtp->mode = sb.st_mode; + +# if defined(RMNT_FSTYPE) && defined(MOUNTS_FSTYPE) + /* + * Make a copy of RMNT_FSTYPE in MOUNTS_FSTYPE. + */ + if (!(mtp->MOUNTS_FSTYPE = mkstrcpy(mp->RMNT_FSTYPE, + (MALLOC_S *)NULL))) + { + (void) fprintf(stderr, "%s: no space for fstype (%s): %s\n", + Pn, mtp->dir, mp->RMNT_FSTYPE); + Exit(1); + } + (void) strcpy(mtp->MOUNTS_FSTYPE, mp->RMNT_FSTYPE); +# endif /* defined(RMNT_FSTYP) && defined(MOUNTS_FSTYP) */ + +# if defined(RMNT_STAT_FSTYPE) && defined(MOUNTS_STAT_FSTYPE) + /* + * Make a copy of RMNT_STAT_FSTYPE in MOUNTS_STAT_FSTYPE. + */ + mtp->MOUNTS_STAT_FSTYPE = (int)sb.RMNT_STAT_FSTYPE; +# endif /* defined(RMNT_STAT_FSTYP) && defined(MOUNTS_STAT_FSTYP) */ + + /* + * Interpolate a possible file system (mounted-on device) name link. + */ + if (!(dn = mkstrcpy(mp->mnt_fsname, (MALLOC_S *)NULL))) + goto no_space_for_mount; + mtp->fsname = dn; + ln = Readlink(dn); + dn = (char *)NULL; + /* + * Stat() the file system (mounted-on) name and add file system + * information to the local mounts structure. + */ + if (!ln || statsafely(ln, &sb)) + sb.st_mode = 0; + mtp->fsnmres = ln; + mtp->fs_mode = sb.st_mode; + Lmi = mtp; + } + (void) endmntent(mfp); +/* + * Clean up and return the local nount info table address. + */ + if (dn) + (void) free((FREE_P *)dn); + Lmist = 1; + return(Lmi); +} +#else /* !defined(USE_LIB_READMNT) */ +static char d1[] = "d"; static char *d2 = d1; +#endif /* defined(USE_LIB_READMNT) */ diff --git a/pool/shard006/C/0118452_basic.c b/pool/shard006/C/0118452_basic.c new file mode 100644 index 0000000000000000000000000000000000000000..201a2ca49ed4f4aada7d1c355a8e93f3f6973741 --- /dev/null +++ b/pool/shard006/C/0118452_basic.c @@ -0,0 +1,68 @@ +#include "shared.h" + +void testDecodeVideo() { + checkpointNext("testDecodeVideo:"); + + const int PACKETS_PER_RUN = 24; + const int MAX_FRAMES = 180; + + void *vbuffer = memalign(64, 512 * 272 * 4); + void *abuffer; + + SceInt32 atracParamNotTestedYet = 1; + SceInt32 avcParamNotSureYet = 6; + // TODO: Possible a struct? Or wrong? + SceInt32 decodeParamNotSureYet = 512; + + int j; + for (j = 0; j < MAX_FRAMES; ++j) { + checkpointNext("Next frame"); + + int freePackets = sceMpegRingbufferAvailableSize((SceMpegRingbuffer *) &g_ringbuffer); + checkpoint(" sceMpegRingbufferAvailableSize: %d", freePackets); + int result = sceMpegRingbufferPut((SceMpegRingbuffer *) &g_ringbuffer, PACKETS_PER_RUN, freePackets); + checkpoint(" sceMpegRingbufferPut: %08x", result); + freePackets = sceMpegRingbufferAvailableSize((SceMpegRingbuffer *) &g_ringbuffer); + checkpoint(" sceMpegRingbufferAvailableSize: %d", freePackets); + + result = sceMpegGetAtracAu(&g_mpeg, g_atrac_stream, &g_atrac_au, &abuffer); + checkpoint(" sceMpegGetAtracAu: %08x (at %08x from %08x)", result, abuffer, g_atracData); + schedfAu(&g_atrac_au); + + result = sceMpegAtracDecode(&g_mpeg, &g_atrac_au, abuffer, atracParamNotTestedYet); + checkpoint(" sceMpegAtracDecode: %08x", result); + schedfAu(&g_atrac_au); + + result = sceMpegGetAvcAu(&g_mpeg, g_avc_stream, &g_avc_au, &avcParamNotSureYet); + checkpoint(" sceMpegGetAvcAu: %08x (%08x)", result, avcParamNotSureYet); + schedfAu(&g_avc_au); + + SceInt32 *decodeParamNotSureYetp = &decodeParamNotSureYet; + result = sceMpegAvcDecode(&g_mpeg, &g_avc_au, 512, &vbuffer, (SceInt32 *) &decodeParamNotSureYetp); + checkpoint(" sceMpegAvcDecode: %08x (%08x, %08x)", result, decodeParamNotSureYet, decodeParamNotSureYetp); + schedfAu(&g_avc_au); + + checkpoint(" *** Frame: %d ***", j); + } + + checkpoint(" sceMpegAvcDecodeFlush: %08x", sceMpegAvcDecodeFlush(&g_mpeg)); + + free(vbuffer); +} + +int main(int argc, char *argv[]) { + if (loadVideoModules() < 0) { + return 1; + } + + sceMpegInit(); + if (createTestMpeg(512) >= 0) { + registMpegStreams(0, 0); + loadMpegFile("test.pmf"); + testDecodeVideo(); + deleteTestMpeg(); + } + + unloadVideoModules(); + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C/0118455_parser.c b/pool/shard006/C/0118455_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..3b4fa8e380a284bb39ef54365ab25e9d03282116 --- /dev/null +++ b/pool/shard006/C/0118455_parser.c @@ -0,0 +1,245 @@ +/* + * lib/parser.c - simple parser for mount, etc. options. + * + * This source code is licensed under the GNU General Public License, + * Version 2. See the file COPYING for more details. + */ + +#include +#include +#include +#include +#include + +/** + * match_one: - Determines if a string matches a simple pattern +<<<<<<< HEAD + * @s: the string to examine for presence of the pattern +======= + * @s: the string to examine for presense of the pattern +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + * @p: the string containing the pattern + * @args: array of %MAX_OPT_ARGS &substring_t elements. Used to return match + * locations. + * + * Description: Determines if the pattern @p is present in string @s. Can only + * match extremely simple token=arg style patterns. If the pattern is found, + * the location(s) of the arguments will be returned in the @args array. + */ +static int match_one(char *s, const char *p, substring_t args[]) +{ + char *meta; + int argc = 0; + + if (!p) + return 1; + + while(1) { + int len = -1; + meta = strchr(p, '%'); + if (!meta) + return strcmp(p, s) == 0; + + if (strncmp(p, s, meta-p)) + return 0; + + s += meta - p; + p = meta + 1; + + if (isdigit(*p)) + len = simple_strtoul(p, (char **) &p, 10); + else if (*p == '%') { + if (*s++ != '%') + return 0; + p++; + continue; + } + + if (argc >= MAX_OPT_ARGS) + return 0; + + args[argc].from = s; + switch (*p++) { + case 's': { + size_t str_len = strlen(s); + + if (str_len == 0) + return 0; + if (len == -1 || len > str_len) + len = str_len; + args[argc].to = s + len; + break; + } + case 'd': + simple_strtol(s, &args[argc].to, 0); + goto num; + case 'u': + simple_strtoul(s, &args[argc].to, 0); + goto num; + case 'o': + simple_strtoul(s, &args[argc].to, 8); + goto num; + case 'x': + simple_strtoul(s, &args[argc].to, 16); + num: + if (args[argc].to == args[argc].from) + return 0; + break; + default: + return 0; + } + s = args[argc].to; + argc++; + } +} + +/** + * match_token: - Find a token (and optional args) in a string + * @s: the string to examine for token/argument pairs + * @table: match_table_t describing the set of allowed option tokens and the + * arguments that may be associated with them. Must be terminated with a + * &struct match_token whose pattern is set to the NULL pointer. + * @args: array of %MAX_OPT_ARGS &substring_t elements. Used to return match + * locations. + * + * Description: Detects which if any of a set of token strings has been passed + * to it. Tokens can include up to MAX_OPT_ARGS instances of basic c-style + * format identifiers which will be taken into account when matching the + * tokens, and whose locations will be returned in the @args array. + */ +int match_token(char *s, const match_table_t table, substring_t args[]) +{ + const struct match_token *p; + + for (p = table; !match_one(s, p->pattern, args) ; p++) + ; + + return p->token; +} + +/** + * match_number: scan a number in the given base from a substring_t + * @s: substring to be scanned + * @result: resulting integer on success + * @base: base to use when converting string + * + * Description: Given a &substring_t and a base, attempts to parse the substring + * as a number in that base. On success, sets @result to the integer represented + * by the string and returns 0. Returns either -ENOMEM or -EINVAL on failure. + */ +static int match_number(substring_t *s, int *result, int base) +{ + char *endp; + char *buf; + int ret; +<<<<<<< HEAD + size_t len = s->to - s->from; + + buf = kmalloc(len + 1, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy(buf, s->from, len); + buf[len] = '\0'; +======= + + buf = kmalloc(s->to - s->from + 1, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy(buf, s->from, s->to - s->from); + buf[s->to - s->from] = '\0'; +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + *result = simple_strtol(buf, &endp, base); + ret = 0; + if (endp == buf) + ret = -EINVAL; + kfree(buf); + return ret; +} + +/** + * match_int: - scan a decimal representation of an integer from a substring_t + * @s: substring_t to be scanned + * @result: resulting integer on success + * + * Description: Attempts to parse the &substring_t @s as a decimal integer. On + * success, sets @result to the integer represented by the string and returns 0. + * Returns either -ENOMEM or -EINVAL on failure. + */ +int match_int(substring_t *s, int *result) +{ + return match_number(s, result, 0); +} + +/** + * match_octal: - scan an octal representation of an integer from a substring_t + * @s: substring_t to be scanned + * @result: resulting integer on success + * + * Description: Attempts to parse the &substring_t @s as an octal integer. On + * success, sets @result to the integer represented by the string and returns + * 0. Returns either -ENOMEM or -EINVAL on failure. + */ +int match_octal(substring_t *s, int *result) +{ + return match_number(s, result, 8); +} + +/** + * match_hex: - scan a hex representation of an integer from a substring_t + * @s: substring_t to be scanned + * @result: resulting integer on success + * + * Description: Attempts to parse the &substring_t @s as a hexadecimal integer. + * On success, sets @result to the integer represented by the string and + * returns 0. Returns either -ENOMEM or -EINVAL on failure. + */ +int match_hex(substring_t *s, int *result) +{ + return match_number(s, result, 16); +} + +/** + * match_strlcpy: - Copy the characters from a substring_t to a sized buffer + * @dest: where to copy to + * @src: &substring_t to copy + * @size: size of destination buffer + * + * Description: Copy the characters in &substring_t @src to the + * c-style string @dest. Copy no more than @size - 1 characters, plus + * the terminating NUL. Return length of @src. + */ +size_t match_strlcpy(char *dest, const substring_t *src, size_t size) +{ + size_t ret = src->to - src->from; + + if (size) { + size_t len = ret >= size ? size - 1 : ret; + memcpy(dest, src->from, len); + dest[len] = '\0'; + } + return ret; +} + +/** + * match_strdup: - allocate a new string with the contents of a substring_t + * @s: &substring_t to copy + * + * Description: Allocates and returns a string filled with the contents of + * the &substring_t @s. The caller is responsible for freeing the returned + * string with kfree(). + */ +char *match_strdup(const substring_t *s) +{ + size_t sz = s->to - s->from + 1; + char *p = kmalloc(sz, GFP_KERNEL); + if (p) + match_strlcpy(p, s, sz); + return p; +} + +EXPORT_SYMBOL(match_token); +EXPORT_SYMBOL(match_int); +EXPORT_SYMBOL(match_octal); +EXPORT_SYMBOL(match_hex); +EXPORT_SYMBOL(match_strlcpy); +EXPORT_SYMBOL(match_strdup); diff --git a/pool/shard006/C/0118461_hlfs_write.c b/pool/shard006/C/0118461_hlfs_write.c new file mode 100644 index 0000000000000000000000000000000000000000..fb282987b75c28742b6c725f543173ebdebc9e5d --- /dev/null +++ b/pool/shard006/C/0118461_hlfs_write.c @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2012 KangHua + * + * 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. + */ + +/* + * @author kanghua(kanghua151@msn.com) + */ +#include +#include +#include +#include +#include +#include +#include "hlfs_ctrl.h" +#include "hlfs_log.h" +#include "comm_define.h" +#include "misc.h" +#include "logger.h" + +int hlfs_write(struct hlfs_ctrl *ctrl, char *write_buf, \ + uint32_t write_len, uint64_t pos) +{ + //HLOG_DEBUG("enter func %s", __func__); + if ((NULL == ctrl) || (NULL == write_buf) || \ + (0 == write_len) || (ctrl->sb.seg_size < write_len)) { + HLOG_ERROR("Params Error"); + return -1; + } + HLOG_INFO("Hlfs Write Req pos:%llu, read_len:%d, \ + last_segno:%d, last_offset:%d, cur_file_len:%llu", + pos, + write_len, + ctrl->last_segno, + ctrl->last_offset, + ctrl->inode.length); + //g_mutex_lock (ctrl->hlfs_access_mutex); + if (ctrl->rw_inode_flag == 0) { + HLOG_ERROR("your config only allow read request!"); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + return -1; + } + + if (ctrl->sb.max_fs_size * 1024 * 1024 < pos+write_len) { + HLOG_ERROR("your config only allow write beyond :%llu", \ + ctrl->sb.max_fs_size); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + return -1; + } + int ret = 0; + guint32 BLOCKSIZE = ctrl->sb.block_size; + uint64_t cur_time; + uint32_t db_start = pos / BLOCKSIZE; + uint32_t db_end = (pos + write_len - 1) / BLOCKSIZE; + int write_blocks_size = (db_end - db_start + 1 ) * BLOCKSIZE; + char *datablocks = NULL; + //(char*)g_malloc0(write_blocks_size); + //if (!datablocks) { + // HLOG_ERROR("allocate error!"); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + // return -1; + // } + + //HLOG_DEBUG("write offset:%llu, write len:%d", pos, write_len); + if (db_start == db_end && (db_start % BLOCKSIZE != 0 || \ + db_end % BLOCKSIZE != 0) ) { + HLOG_DEBUG("only need to write part in one block:%llu", \ + pos / BLOCKSIZE); + char *block= (char *)alloca(BLOCKSIZE); + g_assert(block != NULL); + //g_mutex_lock (ctrl->hlfs_access_mutex); + ret = load_block_by_addr_fast(ctrl, pos, block); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + if ( 1==ret ) { + //HLOG_DEBUG("fail to load block for addr!\ + %llu for not write yet", pos); + memset(block, 0, BLOCKSIZE); + } else if (-1 == ret) { + HLOG_ERROR("can not read logic block: %llu", pos / BLOCKSIZE); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + return -1; + } + datablocks = (char*)g_malloc0(write_blocks_size); + g_assert(datablocks != NULL); + memcpy(datablocks, block, pos % BLOCKSIZE); + memcpy(datablocks + pos % BLOCKSIZE, write_buf, write_len); + memcpy(datablocks + pos % BLOCKSIZE + write_len, + block + pos % BLOCKSIZE + write_len, + BLOCKSIZE - (pos % BLOCKSIZE + write_len)); + //g_free(block); + goto write_log; + } + + if (pos % BLOCKSIZE != 0 ) { + //HLOG_DEBUG("to load first block!"); + char *first_block = (char *)alloca(BLOCKSIZE); + g_assert(first_block != NULL); + //g_mutex_lock (ctrl->hlfs_access_mutex); + ret = load_block_by_addr_fast(ctrl, pos, first_block); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + if (1 == ret) { + //HLOG_DEBUG("fail to load first block for not write yet"); + memset(first_block, 0, BLOCKSIZE); + } else if (ret == -1) { + HLOG_ERROR("can not read logic block: %llu", pos / BLOCKSIZE); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + return -1; + } + datablocks = (char *)g_malloc0(write_blocks_size); + g_assert(datablocks != NULL); + memcpy(datablocks, first_block, BLOCKSIZE); + memcpy(datablocks + pos % BLOCKSIZE, write_buf, write_len); + //g_free(first_block); + } else { + //HLOG_DEBUG("do not need load first block"); + if ((pos + write_len) % BLOCKSIZE != 0) { + datablocks = (char *)g_malloc0(write_blocks_size); + g_assert(datablocks != NULL); + memcpy(datablocks, write_buf, write_len); + } else { + HLOG_DEBUG("Do not need alloc any buffer"); + datablocks = write_buf; + goto write_log; + } + } + if ((pos + write_len) % BLOCKSIZE !=0) { + //HLOG_DEBUG("to load last block"); + char *last_block = (char *)alloca(BLOCKSIZE); + //g_mutex_lock (ctrl->hlfs_access_mutex); + ret = load_block_by_addr_fast(ctrl, pos + write_len, last_block); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + if (1 == ret) { + //HLOG_DEBUG("fail to load last block for not write yet"); + memset(last_block,0,BLOCKSIZE); + } else if (-1 == ret) { + //g_mutex_unlock (ctrl->hlfs_access_mutex); + HLOG_ERROR("can not read logic block: %llu", pos / BLOCKSIZE); + ret = -1; + goto out; + } + memcpy(datablocks + pos % BLOCKSIZE + write_len, + last_block + (write_len + pos) % BLOCKSIZE, + BLOCKSIZE - (write_len + pos) % BLOCKSIZE); + //g_free(last_block); + } +write_log:; + //HLOG_DEBUG("db_start: %u db_end: %u", db_start, db_end); + + cur_time = get_current_time(); + ctrl->inode.mtime = cur_time; + //ctrl->inode.ctime = cur_time; + //ctrl->inode.atime = cur_time; + //HLOG_DEBUG("get_current_time is %llu", ctrl->inode.mtime); + //HLOG_DEBUG("length is %llu", ctrl->inode.length); + ctrl->last_write_timestamp = get_current_time(); + if (ctrl->cctrl != NULL) { + HLOG_DEBUG("we use write back mode !"); + int ret = dbcache_insert_blocks(ctrl->cctrl, db_start, \ + (db_end - db_start + 1), datablocks); + g_assert(ret == 0); + } else { + HLOG_DEBUG("we use write through mode !"); + g_mutex_lock (ctrl->hlfs_access_mutex); + //ctrl->last_write_timestamp = get_current_time(); + int size = append_log(ctrl, datablocks, db_start, db_end, 1); + g_mutex_unlock (ctrl->hlfs_access_mutex); + if (size < 0) { + HLOG_ERROR("Append Log Error"); + //g_free(datablocks); + ret = -1; + goto out; + } + HLOG_INFO("Append Log Exec Succ . filesize:%llu, last_segno:%u, last_offset:%u, log size:%u, start_dbno:%u, end_dbno:%u", + ctrl->inode.length, + ctrl->last_segno, + ctrl->last_offset, + size, + db_start, + db_end) + } + +#if 0 +#if 0 /* use async way */ + int size = append_log(ctrl, datablocks, db_start, db_end); + if (size < 0) { + g_message("fail to append log\n"); + return -1; + } +#else + memset(&(ctrl->write_req), 0, sizeof(struct write_req)); + struct write_req *w_req = &ctrl->write_req; + //struct write_rsp *w_rsp = &ctrl->write_rsp; + //struct write_req * w_req = (struct write_req *)g_malloc0 \ + (sizeof(struct write_req)); + w_req->req_buf = datablocks; + w_req->db_start = db_start; + w_req->db_end = db_end; + g_async_queue_push(ctrl->write_req_aqueue, (gpointer)w_req); + if (NULL == w_req) { + HLOG_DEBUG("g_async_queue_push pushed null data"); + } + HLOG_DEBUG("ctrl->write_task_run is %d", ctrl->write_task_run); + HLOG_DEBUG("request pushed to aysn"); + struct write_rsp * w_rsp = (struct write_rsp*)g_async_queue_pop \ + (ctrl->write_rsp_aqueue); + ret = w_rsp->res; + int size = w_rsp->size; + //g_free(w_rsp); + if (ret != 0) { + HLOG_ERROR("fail to append log"); + //g_mutex_unlock (ctrl->hlfs_access_mutex); + return -1; + } +#endif /*use async queue*/ +#endif +out: + if (datablocks != NULL && datablocks != write_buf) { + g_free(datablocks); + } + //ctrl->last_access_timestamp = get_current_time(); + //HLOG_DEBUG("leave func %s", __func__); + if (ctrl->inode.length < (pos + write_len)) { + ctrl->inode.length = pos + write_len; + } + return write_len; +} diff --git a/pool/shard006/C/0118466_rtc.c b/pool/shard006/C/0118466_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..8d23e867621b4abe31a0a1c1798bd41df3d6e590 --- /dev/null +++ b/pool/shard006/C/0118466_rtc.c @@ -0,0 +1,99 @@ +/* + * RTEMS for Nintendo DS realtime clock driver. + * + * Copyright (c) 2008 by Cedric Gestes + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * + * http://www.rtems.com/license/LICENSE + * + * $Id$ + */ + +#include +#include +#include +#include + +rtems_device_minor_number RTC_Minor; +size_t RTC_Count = 1; + +/* + * probe for a rtc. we always claim to have one. + */ + +bool +nds_rtc_probe (int minor) +{ + return true; +} + +/* + * initialize the nds rtc. + */ + +void +nds_rtc_init (int minor) +{ + /* nothing to do here (already done in the arm7 main) */ + printk ("[+] rtc started\n"); +} + +/* + * read current time from nds real-time clock chip and convert it + * to the rtems_time_of_day structure. + */ + +int +nds_rtc_get_time (int minor, rtems_time_of_day * time) +{ + time->year = 2000 + IPC->time.rtc.year; + time->month = IPC->time.rtc.month; + time->day = IPC->time.rtc.day; + time->hour = IPC->time.rtc.hours; + time->minute = IPC->time.rtc.minutes; + time->second = IPC->time.rtc.seconds; + time->ticks = 0; + + return 0; +} + +/* + * set time to the arm7 nds rtc. + * NOTE: this is not supported. + */ + +int +nds_rtc_set_time (int minor, const rtems_time_of_day * time) +{ + return -1; +} + +/* + * driver function table. + */ + +rtc_fns nds_rtc_fns = { + nds_rtc_init, + nds_rtc_get_time, + nds_rtc_set_time +}; + +/* + * the following table configures the RTC drivers used in this BSP + */ + +rtc_tbl RTC_Table[] = { + { + "/dev/rtc", /* sDeviceName */ + RTC_CUSTOM, /* deviceType */ + &nds_rtc_fns, /* pDeviceFns */ + nds_rtc_probe, /* deviceProbe */ + NULL, /* pDeviceParams */ + 0, /* ulCtrlPort1 */ + 0, /* ulDataPort */ + NULL, /* getRegister */ + NULL /* setRegister */ + } +}; diff --git a/pool/shard006/C/0118467_char.c b/pool/shard006/C/0118467_char.c new file mode 100644 index 0000000000000000000000000000000000000000..4e03c09d21389ea7eeede21f093cce130a2ccdeb --- /dev/null +++ b/pool/shard006/C/0118467_char.c @@ -0,0 +1,39 @@ +/* + * Draw a single character glyph. + * + * Copyright (C) 2015 Serge Vakulenko, + * + * Permission to use, copy, modify, and distribute this software + * and its documentation for any purpose and without fee is hereby + * granted, provided that the above copyright notice appear in all + * copies and that both that the copyright notice and this + * permission notice and warranty disclaimer appear in supporting + * documentation, and that the name of the author not be used in + * advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. + * + * The author disclaim all warranties with regard to this + * software, including all implied warranties of merchantability + * and fitness. In no event shall the author be liable for any + * special, indirect or consequential damages or any damages + * whatsoever resulting from loss of use, data or profits, whether + * in an action of contract, negligence or other tortious action, + * arising out of or in connection with the use or performance of + * this software. + */ +#include +#include + +void gpanel_char(const struct gpanel_font_t *font, int color, int background, + int x, int y, int sym) +{ + struct gpanel_char_t param; + + param.font = font; + param.color = color; + param.background = background; + param.x = x; + param.y = y; + param.sym = sym; + ioctl(_gpanel_fd, GPANEL_CHAR, ¶m); +} diff --git a/pool/shard006/C/0118468_f128M_to_extF80M.c b/pool/shard006/C/0118468_f128M_to_extF80M.c new file mode 100644 index 0000000000000000000000000000000000000000..ff2ae39e588e95c5e8efd1b0203d5e172ee5dcb9 --- /dev/null +++ b/pool/shard006/C/0118468_f128M_to_extF80M.c @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: BSD-3-Clause + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3a, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that 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 University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 +#include +#include "platform.h" +#include "internals.h" +#include "specialize.h" +#include "softfloat.h" + +#ifdef SOFTFLOAT_FAST_INT64 + +void f128M_to_extF80M( const float128_t *aPtr, extFloat80_t *zPtr ) +{ + + *zPtr = f128_to_extF80( *aPtr ); + +} + +#else + +void f128M_to_extF80M( const float128_t *aPtr, extFloat80_t *zPtr ) +{ + const uint32_t *aWPtr; + struct extFloat80M *zSPtr; + uint32_t uiA96; + bool sign; + int32_t exp; + struct commonNaN commonNaN; + uint32_t sig[4]; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + aWPtr = (const uint32_t *) aPtr; + zSPtr = (struct extFloat80M *) zPtr; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiA96 = aWPtr[indexWordHi( 4 )]; + sign = signF128UI96( uiA96 ); + exp = expF128UI96( uiA96 ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x7FFF ) { + if ( softfloat_isNaNF128M( aWPtr ) ) { + softfloat_f128MToCommonNaN( aWPtr, &commonNaN ); + softfloat_commonNaNToExtF80M( &commonNaN, zSPtr ); + return; + } + zSPtr->signExp = packToExtF80UI64( sign, 0x7FFF ); + zSPtr->signif = UINT64_C( 0x8000000000000000 ); + return; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + exp = softfloat_shiftNormSigF128M( aWPtr, 15, sig ); + if ( exp == -128 ) { + zSPtr->signExp = packToExtF80UI64( sign, 0 ); + zSPtr->signif = 0; + return; + } + if ( sig[indexWord( 4, 0 )] ) sig[indexWord( 4, 1 )] |= 1; + softfloat_roundPackMToExtF80M( + sign, exp, &sig[indexMultiwordHi( 4, 3 )], 80, zSPtr ); + +} + +#endif + diff --git a/pool/shard006/C/0118469_istat.c b/pool/shard006/C/0118469_istat.c new file mode 100644 index 0000000000000000000000000000000000000000..421b365c6203e8a59b840a35c6522d5929f81ca6 --- /dev/null +++ b/pool/shard006/C/0118469_istat.c @@ -0,0 +1,47 @@ +/* + * istat : a workstation statistics display for InterViews + */ + +#include "stats.h" +#include +#include +#include +#include +#include +#include +#include + +static PropertyData props[] = { + { "*host", "" }, + { "*delay", "5" }, + { "*font", "6x10" }, + { "*geometry", "100x60" }, + { nil } +}; + +static OptionDesc options[] = { + { "-delay", "*delay", OptionValueNext }, + { "-host", "*host", OptionValueNext }, + { nil } +}; + +static char hostname[64]; + +int main (int argc, char* argv[]) { + World* world = new World("IStat", props, options, argc, argv); + if (argc > 1) { + fprintf(stderr, "usage: %s [-delay sec] [-host name]\n", argv[0]); + exit(1); + } + + int delay = atoi(world->GetAttribute("delay")); + strcpy(hostname, world->GetAttribute("host")); + if (hostname[0] == '\0') { + gethostname(hostname, sizeof(hostname)); + } + + IStat* istat = new IStat(hostname, delay); + world->InsertApplication(istat); + istat->Run(); + return 0; +} diff --git a/pool/shard006/C/0118471_getpass.c b/pool/shard006/C/0118471_getpass.c new file mode 100644 index 0000000000000000000000000000000000000000..7367349cf39fe4535dc0a7602edb0253fec66c4f --- /dev/null +++ b/pool/shard006/C/0118471_getpass.c @@ -0,0 +1,75 @@ +/** + * @file + * @brief + * + * @date 19.03.13 + * @author Ilia Vaprol + */ + +#include +#include +#include +#include +#include + +/** + * @brief Non posix extension of deprecated @a getpass that not use static buffers and + * therefore thread-safe. + * + * @param prompt Prompt to be printed to user + * @param buf Buffer to store user's input + * @param buflen @a buf length + * + * @return + * NULL on error + * pointer to user entered password + */ +char *getpass_r(const char *prompt, char *buf, size_t buflen) { + size_t pass_len; + struct termios t; + /* print prompt */ + if (0 > fprintf(stdout, "%s", prompt)) { + return NULL; + } + fflush(stdout); + + /* read password from stdin (with disabling ECHO-mode) */ + if (-1 == tcgetattr(STDIN_FILENO, &t)) { + return NULL; + } + + t.c_lflag &= ~ECHO; + + if (-1 == tcsetattr(STDIN_FILENO, TCSANOW, &t)) { + return NULL; + } + + t.c_lflag |= ECHO; + + if (NULL == fgets(buf, buflen, stdin)) { + tcsetattr(STDIN_FILENO, TCSANOW, &t); + return NULL; + } + + if (-1 == tcsetattr(STDIN_FILENO, TCSANOW, &t)) { + return NULL; + } + + /* remove newline character */ + pass_len = strlen(buf); + + if (buf[pass_len - 1] != '\n') { + return NULL; /* error: no newline at the end of line. + password is too long or EOF is encountered */ + } + + buf[pass_len - 1] = '\0'; + + /* done */ + return buf; +} + +char * getpass(const char *prompt) { + static char pass[PASS_MAX + 2]; /* for \n\0 */ + return getpass_r(prompt, pass, sizeof(pass)); +} diff --git a/pool/shard006/C/0118473_test_menu_tb.c b/pool/shard006/C/0118473_test_menu_tb.c new file mode 100644 index 0000000000000000000000000000000000000000..e3934970d0d697d9928b4b6e475127343f3948d5 --- /dev/null +++ b/pool/shard006/C/0118473_test_menu_tb.c @@ -0,0 +1,31 @@ +#include +#include +#include + +#include "menu.h" +#include "ui_menu.h" +#include "menu_test.h" +#include "graphics_tb.h" + +static void test_menu_tb() { + graphics_tb_t *graphics = graphics_tb_init(); + char err_msg[MENU_TEST_ERR_MSG_SIZE] = ""; + + if (graphics == NULL) { + fprintf(stderr, "Could not initialize termbox"); + return; + } + + bool success = test_menu(graphics, graphics_tb_callbacks, err_msg); + graphics_tb_quit(graphics); + + if (!success) { + puts(err_msg); + } +} + + +int main(int argc, char **argv) { + test_menu_tb(); + return 0; +} diff --git a/pool/shard006/C/0118479_cvector.c b/pool/shard006/C/0118479_cvector.c new file mode 100644 index 0000000000000000000000000000000000000000..9cb8626aea59664b95079cd551260b25735106d0 --- /dev/null +++ b/pool/shard006/C/0118479_cvector.c @@ -0,0 +1,99 @@ +/* + * Copyright 2014, NICTA + * + * This software may be distributed and modified according to the terms of + * the BSD 2-Clause license. Note that NO WARRANTY is provided. + * See "LICENSE_BSD2.txt" for details. + * + * @TAG(NICTA_BSD) + */ + +#include +#include + +static void +cvector_delete_resize(cvector_t *v) { + if (v->nextResize-- > 0) { + return; + } + // Condition to decrease v->data size: size > (c * 2) + k + if ((v->count + 2) * 2 < v->size) { + v->size = (v->count + 2); + v->data = krealloc(v->data, sizeof(cvector_item_t) * v->size); + v->nextResize = CVECTOR_RESIZE_CHECK_FREQ; + } +} + +void +cvector_init(cvector_t *v) +{ + assert(v); + v->data = NULL; + v->size = 0; + v->count = 0; + v->nextResize = CVECTOR_RESIZE_CHECK_FREQ; +} + +int +cvector_add(cvector_t *v, cvector_item_t e) +{ + assert(v); + if (v->size == 0) { + v->size = CVECTOR_INIT_SIZE; + v->data = kmalloc(sizeof(cvector_item_t) * v->size); + assert(v->data); + } + + // Condition to increase v->data: last slot exhausted + if (v->size <= v->count) { + v->size *= 2; + v->data = krealloc(v->data, sizeof(cvector_item_t) * v->size); + assert(v->data); + } + + v->data[v->count] = e; + return v->count++; +} + +void +cvector_set(cvector_t *v, uint32_t index, cvector_item_t e) +{ + assert(v); + assert(index < v->count); + v->data[index] = e; +} + +cvector_item_t +cvector_get(cvector_t *v, int index) +{ + assert(v); + assert(index < v->count); + return v->data[index]; +} + +void +cvector_delete(cvector_t *v, int index) +{ + assert(v); + assert(index < v->count); + for(int i = index; i < (v->count - 1); i++) { + v->data[i] = v->data[i + 1]; + } + v->count--; + cvector_delete_resize(v); +} + +void +cvector_free(cvector_t *v) +{ + assert(v); + if (v->data) kfree(v->data); + cvector_init(v); +} + +void +cvector_reset(cvector_t *v) +{ + assert(v); + v->count = 0; +} diff --git a/pool/shard006/C/0118484_checkbox.c b/pool/shard006/C/0118484_checkbox.c new file mode 100644 index 0000000000000000000000000000000000000000..7ed97e0b2ebfa88c0aa337ea0ad3eca9d206a7c1 --- /dev/null +++ b/pool/shard006/C/0118484_checkbox.c @@ -0,0 +1,174 @@ +/* Checkbox widget handlers. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "elinks.h" + +#include "bfu/button.h" +#include "bfu/checkbox.h" +#include "bfu/dialog.h" +#include "bfu/text.h" +#include "intl/gettext/libintl.h" +#include "terminal/draw.h" +#include "terminal/mouse.h" +#include "terminal/terminal.h" + +#define CHECKBOX_HEIGHT 1 +#define CHECKBOX_LEN 3 /* "[X]" or "(X)" */ +#define CHECKBOX_SPACING 1 /* "[X]" + " " + "Label" */ +#define CHECKBOX_LS (CHECKBOX_LEN + CHECKBOX_SPACING) /* "[X] " */ + +void +add_dlg_radio_do(struct dialog *dlg, unsigned char *text, + int groupid, int groupnum, int *data) +{ + struct widget *widget = &dlg->widgets[dlg->number_of_widgets++]; + + widget->type = WIDGET_CHECKBOX; + widget->text = text; + widget->datalen = sizeof(*data); + widget->data = (void *) data; + + widget->info.checkbox.gid = groupid; + widget->info.checkbox.gnum = groupnum; +} + +void +dlg_format_checkbox(struct terminal *term, + struct widget_data *widget_data, + int x, int *y, int w, int *rw, + enum format_align align, int format_only) +{ + unsigned char *text = widget_data->widget->text; + + set_box(&widget_data->box, x, *y, CHECKBOX_LEN, CHECKBOX_HEIGHT); + + if (w <= CHECKBOX_LS) return; + + if (text && *text) { + if (rw) *rw -= CHECKBOX_LS; + dlg_format_text_do(term, text, x + CHECKBOX_LS, y, + w - CHECKBOX_LS, rw, + get_bfu_color(term, "dialog.checkbox-label"), + align, format_only); + if (rw) *rw += CHECKBOX_LS; + } +} + +static widget_handler_status_T +display_checkbox(struct dialog_data *dlg_data, struct widget_data *widget_data) +{ + struct terminal *term = dlg_data->win->term; + struct color_pair *color; + unsigned char *text; + struct box *pos = &widget_data->box; + int selected = is_selected_widget(dlg_data, widget_data); + + if (selected) { + color = get_bfu_color(term, "dialog.checkbox-selected"); + } else { + color = get_bfu_color(term, "dialog.checkbox"); + } + if (!color) return EVENT_PROCESSED; + + if (widget_data->info.checkbox.checked) + text = widget_data->widget->info.checkbox.gid ? "(X)" : "[X]"; + else + text = widget_data->widget->info.checkbox.gid ? "( )" : "[ ]"; + + draw_text(term, pos->x, pos->y, text, CHECKBOX_LEN, 0, color); + + if (selected) { + set_cursor(term, pos->x + 1, pos->y, 1); + set_window_ptr(dlg_data->win, pos->x, pos->y); + } + + return EVENT_PROCESSED; +} + +static widget_handler_status_T +init_checkbox(struct dialog_data *dlg_data, struct widget_data *widget_data) +{ + int *cdata = (int *) widget_data->cdata; + + assert(cdata); + + if (widget_data->widget->info.checkbox.gid) { + if (*cdata == widget_data->widget->info.checkbox.gnum) + widget_data->info.checkbox.checked = 1; + } else { + if (*cdata) + widget_data->info.checkbox.checked = 1; + } + return EVENT_PROCESSED; +} + +static widget_handler_status_T +mouse_checkbox(struct dialog_data *dlg_data, struct widget_data *widget_data) +{ + struct terminal *term = dlg_data->win->term; + struct term_event *ev = dlg_data->term_event; + + if (check_mouse_wheel(ev) + || !check_mouse_position(ev, &widget_data->box)) + return EVENT_NOT_PROCESSED; + + select_widget(dlg_data, widget_data); + + do_not_ignore_next_mouse_event(term); + + if (check_mouse_action(ev, B_UP) && widget_data->widget->ops->select) + widget_data->widget->ops->select(dlg_data, widget_data); + + return EVENT_PROCESSED; +} + +static widget_handler_status_T +select_checkbox(struct dialog_data *dlg_data, struct widget_data *widget_data) +{ + + if (!widget_data->widget->info.checkbox.gid) { + /* Checkbox. */ + int *cdata = (int *) widget_data->cdata; + + assert(cdata); + + widget_data->info.checkbox.checked = *cdata = !*cdata; + + } else { + /* Group of radio buttons. */ + struct widget_data *wdata; + + foreach_widget(dlg_data, wdata) { + int *cdata = (int *) wdata->cdata; + + if (wdata->widget->type != WIDGET_CHECKBOX) + continue; + + if (wdata->widget->info.checkbox.gid + != widget_data->widget->info.checkbox.gid) + continue; + + assert(cdata); + + *cdata = widget_data->widget->info.checkbox.gnum; + wdata->info.checkbox.checked = 0; + display_widget(dlg_data, wdata); + } + widget_data->info.checkbox.checked = 1; + } + + display_widget(dlg_data, widget_data); + return EVENT_PROCESSED; +} + +const struct widget_ops checkbox_ops = { + display_checkbox, + init_checkbox, + mouse_checkbox, + NULL, + select_checkbox, + NULL, +}; diff --git a/pool/shard006/C/0118486_vcd_util.c b/pool/shard006/C/0118486_vcd_util.c new file mode 100644 index 0000000000000000000000000000000000000000..82f671df4bfdb04da11e0a8cab1b7fcdc65a3f80 --- /dev/null +++ b/pool/shard006/C/0118486_vcd_util.c @@ -0,0 +1,111 @@ +/* Copyright (c) 2010, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + */ + +#include "vidc_type.h" +#include "vcd_util.h" + +u32 vcd_critical_section_create(u32 **p_cs) +{ + struct mutex *lock; + if (!p_cs) { + VCD_MSG_ERROR("Bad critical section ptr"); + return VCD_ERR_BAD_POINTER; + } else { + lock = kmalloc(sizeof(struct mutex), GFP_KERNEL); + if (!lock) { + VCD_MSG_ERROR("Failed: vcd_critical_section_create"); + return VCD_ERR_ALLOC_FAIL; + } + mutex_init(lock); + *p_cs = (u32 *) lock; + return VCD_S_SUCCESS; + } +} + +u32 vcd_critical_section_release(u32 *cs) +{ + struct mutex *lock = (struct mutex *)cs; + if (!lock) { + VCD_MSG_ERROR("Bad critical section object"); + return VCD_ERR_BAD_POINTER; + } + + mutex_destroy(lock); + kfree(cs); + return VCD_S_SUCCESS; +} + +u32 vcd_critical_section_enter(u32 *cs) +{ + struct mutex *lock = (struct mutex *)cs; + if (!lock) { + VCD_MSG_ERROR("Bad critical section object"); + return VCD_ERR_BAD_POINTER; + } else + mutex_lock(lock); + + return VCD_S_SUCCESS; +} + +u32 vcd_critical_section_leave(u32 *cs) +{ + struct mutex *lock = (struct mutex *)cs; + + if (!lock) { + VCD_MSG_ERROR("Bad critical section object"); + + return VCD_ERR_BAD_POINTER; + } else + mutex_unlock(lock); + + return VCD_S_SUCCESS; +} + +int vcd_pmem_alloc(u32 size, u8 **kernel_vaddr, u8 **phy_addr) +{ + *phy_addr = + (u8 *) pmem_kalloc(size, PMEM_MEMTYPE_EBI1 | PMEM_ALIGNMENT_4K); + + if (!IS_ERR((void *)*phy_addr)) { + + *kernel_vaddr = ioremap((unsigned long)*phy_addr, size); + + if (!*kernel_vaddr) { + pr_err("%s: could not ioremap in kernel pmem buffers\n", + __func__); + pmem_kfree((s32) *phy_addr); + return -ENOMEM; + } + pr_debug("write buf: phy addr 0x%08x kernel addr 0x%08x\n", + (u32) *phy_addr, (u32) *kernel_vaddr); + return 0; + } else { + pr_err("%s: could not allocte in kernel pmem buffers\n", + __func__); + return -ENOMEM; + } + +} + +int vcd_pmem_free(u8 *kernel_vaddr, u8 *phy_addr) +{ + iounmap((void *)kernel_vaddr); + pmem_kfree((s32) phy_addr); + + return 0; +} diff --git a/pool/shard006/C/0118487_a12611.c b/pool/shard006/C/0118487_a12611.c new file mode 100644 index 0000000000000000000000000000000000000000..b9662cf142ac551f31374a860c39b1ab0c23a7c7 --- /dev/null +++ b/pool/shard006/C/0118487_a12611.c @@ -0,0 +1,29 @@ +#include +#include + +int main(int argc, char *argv[]) +{ + //t¬°´ú¸ê¼Æ¶q¡Ar¬°¶êªº¥b®|¡Alength¬°ªø¤è§Îªºªø¡Awidth¬°ªø¤è§Îªº¼e¡Aright¬°¥k½u¬q¡Aleft¬°¥ª½u¬q + int i, t, r, length, width, right, left; + + fflush(stdin); + scanf("%d", &t); + + for(i = 1; i <= t; i++) { + scanf("%d", &r); + + length = r * 5; + width = length * 60 / 100; + right = length * 55 / 100; + left = length * 45 / 100; + + //¦L¥X¥ª¤W¡B¥k¤W¡B¥k¤U¡B¥ª¤U®y¼Ð + printf("Case%d¡G\n", i); + printf("%d %d\n", width / 2, -left); + printf("%d %d\n", right, width / 2); + printf("%d %d\n", right, -width / 2); + printf("%d %d\n", -left, -width / 2); + } + + return 0; +} diff --git a/pool/shard006/C/0118491_pci.c b/pool/shard006/C/0118491_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..52db183797f34d35ae1449b6f96ed24a13d2e029 --- /dev/null +++ b/pool/shard006/C/0118491_pci.c @@ -0,0 +1,232 @@ +/* + * arch/sh/drivers/pci/pci.c + * + * Copyright (c) 2002 M. R. Brown + * Copyright (c) 2004 - 2006 Paul Mundt + * + * These functions are collected here to reduce duplication of common + * code amongst the many platform-specific PCI support code files. + * + * These routines require the following board-specific routines: + * void pcibios_fixup_irqs(); + * + * See include/asm-sh/pci.h for more information. + * + * 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. + */ +#include +#include +#include +#include + +static inline u8 bridge_swizzle(u8 pin, u8 slot) +{ + return (((pin - 1) + slot) % 4) + 1; +} + +static u8 __init simple_swizzle(struct pci_dev *dev, u8 *pinp) +{ + u8 pin = *pinp; + + while (dev->bus->parent) { + pin = bridge_swizzle(pin, PCI_SLOT(dev->devfn)); + /* Move up the chain of bridges. */ + dev = dev->bus->self; + } + *pinp = pin; + + /* The slot is the slot of the last bridge. */ + return PCI_SLOT(dev->devfn); +} + +static int __init pcibios_init(void) +{ + struct pci_channel *p; + struct pci_bus *bus; + int busno; + +#ifdef CONFIG_PCI_AUTO + /* assign resources */ + busno = 0; + for (p = board_pci_channels; p->pci_ops != NULL; p++) + busno = pciauto_assign_resources(busno, p) + 1; +#endif + + /* scan the buses */ + busno = 0; + for (p = board_pci_channels; p->pci_ops != NULL; p++) { + bus = pci_scan_bus(busno, p->pci_ops, p); + busno = bus->subordinate + 1; + } + + pci_fixup_irqs(simple_swizzle, pcibios_map_platform_irq); + + return 0; +} +subsys_initcall(pcibios_init); + +/* + * Called after each bus is probed, but before its children + * are examined. + */ +void __devinit pcibios_fixup_bus(struct pci_bus *bus) +{ + pci_read_bridge_bases(bus); +} + +void +pcibios_update_resource(struct pci_dev *dev, struct resource *root, + struct resource *res, int resource) +{ + u32 new, check; + int reg; + + new = res->start | (res->flags & PCI_REGION_FLAG_MASK); + if (resource < 6) { + reg = PCI_BASE_ADDRESS_0 + 4*resource; + } else if (resource == PCI_ROM_RESOURCE) { + res->flags |= IORESOURCE_ROM_ENABLE; + new |= PCI_ROM_ADDRESS_ENABLE; + reg = dev->rom_base_reg; + } else { + /* + * Somebody might have asked allocation of a non-standard + * resource + */ + return; + } + + pci_write_config_dword(dev, reg, new); + pci_read_config_dword(dev, reg, &check); + if ((new ^ check) & ((new & PCI_BASE_ADDRESS_SPACE_IO) ? + PCI_BASE_ADDRESS_IO_MASK : PCI_BASE_ADDRESS_MEM_MASK)) { + printk(KERN_ERR "PCI: Error while updating region " + "%s/%d (%08x != %08x)\n", pci_name(dev), resource, + new, check); + } +} + +void pcibios_align_resource(void *data, struct resource *res, + resource_size_t size, resource_size_t align) + __attribute__ ((weak)); + +/* + * We need to avoid collisions with `mirrored' VGA ports + * and other strange ISA hardware, so we always want the + * addresses to be allocated in the 0x000-0x0ff region + * modulo 0x400. + */ +void pcibios_align_resource(void *data, struct resource *res, + resource_size_t size, resource_size_t align) +{ + if (res->flags & IORESOURCE_IO) { + resource_size_t start = res->start; + + if (start & 0x300) { + start = (start + 0x3ff) & ~0x3ff; + res->start = start; + } + } +} + +int pcibios_enable_device(struct pci_dev *dev, int mask) +{ + u16 cmd, old_cmd; + int idx; + struct resource *r; + + pci_read_config_word(dev, PCI_COMMAND, &cmd); + old_cmd = cmd; + for(idx=0; idx<6; idx++) { + if (!(mask & (1 << idx))) + continue; + r = &dev->resource[idx]; + if (!r->start && r->end) { + printk(KERN_ERR "PCI: Device %s not available because " + "of resource collisions\n", pci_name(dev)); + return -EINVAL; + } + if (r->flags & IORESOURCE_IO) + cmd |= PCI_COMMAND_IO; + if (r->flags & IORESOURCE_MEM) + cmd |= PCI_COMMAND_MEMORY; + } + if (dev->resource[PCI_ROM_RESOURCE].start) + cmd |= PCI_COMMAND_MEMORY; + if (cmd != old_cmd) { + printk(KERN_INFO "PCI: Enabling device %s (%04x -> %04x)\n", + pci_name(dev), old_cmd, cmd); + pci_write_config_word(dev, PCI_COMMAND, cmd); + } + return 0; +} + +/* + * If we set up a device for bus mastering, we need to check and set + * the latency timer as it may not be properly set. + */ +unsigned int pcibios_max_latency = 255; + +void pcibios_set_master(struct pci_dev *dev) +{ + u8 lat; + pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat); + if (lat < 16) + lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency; + else if (lat > pcibios_max_latency) + lat = pcibios_max_latency; + else + return; + printk(KERN_INFO "PCI: Setting latency timer of device %s to %d\n", + pci_name(dev), lat); + pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat); +} + +void __init pcibios_update_irq(struct pci_dev *dev, int irq) +{ + pci_write_config_byte(dev, PCI_INTERRUPT_LINE, irq); +} + + +#ifndef CONFIG_GENERIC_IOMAP + +void __iomem *pci_iomap(struct pci_dev *dev, int bar, unsigned long maxlen) +{ + unsigned long start = pci_resource_start(dev, bar); + unsigned long len = pci_resource_len(dev, bar); + unsigned long flags = pci_resource_flags(dev, bar); + + if (unlikely(!len || !start)) + return NULL; + if (maxlen && len > maxlen) + len = maxlen; + + /* + * Presently the IORESOURCE_MEM case is a bit special, most + * SH7751 style PCI controllers have PCI memory at a fixed + * location in the address space where no remapping is desired + * (typically at 0xfd000000, but is_pci_memaddr() will know + * best). With the IORESOURCE_MEM case more care has to be taken + * to inhibit page table mapping for legacy cores, but this is + * punted off to __ioremap(). + * -- PFM. + */ + if (flags & IORESOURCE_IO) + return ioport_map(start, len); + if (flags & IORESOURCE_MEM) + return ioremap(start, len); + + return NULL; +} +EXPORT_SYMBOL(pci_iomap); + +void pci_iounmap(struct pci_dev *dev, void __iomem *addr) +{ + iounmap(addr); +} +EXPORT_SYMBOL(pci_iounmap); + +#endif + diff --git a/pool/shard006/C/0118492_VBoxCAPIGlue.c b/pool/shard006/C/0118492_VBoxCAPIGlue.c new file mode 100644 index 0000000000000000000000000000000000000000..3981fb58b1ce400b8cf9df062438f5d38f2d9c7b --- /dev/null +++ b/pool/shard006/C/0118492_VBoxCAPIGlue.c @@ -0,0 +1,330 @@ +/* $Revision$ */ +/** @file + * Glue code for dynamically linking to VBoxCAPI. + */ + +/* + * Copyright (C) 2008-2014 Oracle Corporation + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + */ + +/******************************************************************************* +* Header Files * +*******************************************************************************/ +#include "VBoxCAPIGlue.h" + +#include +#include +#include +#include +#include +#ifndef WIN32 +# include +# include +#else /* WIN32 */ +# include +#endif /* WIN32 */ + + +/******************************************************************************* +* Defined Constants And Macros * +*******************************************************************************/ +#if defined(__linux__) || defined(__linux_gnu__) || defined(__sun__) || defined(__FreeBSD__) +# define DYNLIB_NAME "VBoxXPCOMC.so" +#elif defined(__APPLE__) +# define DYNLIB_NAME "VBoxXPCOMC.dylib" +#elif defined(__OS2__) +# define DYNLIB_NAME "VBoxXPCOMC.dll" +#elif defined(WIN32) +# define DYNLIB_NAME "VBoxCAPI.dll" +#else +# error "Port me" +#endif + + +/******************************************************************************* +* Global Variables * +*******************************************************************************/ +/** The so/dynsym/dll handle for VBoxCAPI. */ +#ifndef WIN32 +void *g_hVBoxCAPI = NULL; +#else /* WIN32 */ +HMODULE g_hVBoxCAPI = NULL; +#endif /* WIN32 */ +/** The last load error. */ +char g_szVBoxErrMsg[256] = ""; +/** Pointer to the VBOXCAPI function table. */ +PCVBOXCAPI g_pVBoxFuncs = NULL; +/** Pointer to VBoxGetCAPIFunctions for the loaded VBoxCAPI so/dylib/dll. */ +PFNVBOXGETCAPIFUNCTIONS g_pfnGetFunctions = NULL; + +typedef void FNDUMMY(void); +typedef FNDUMMY *PFNDUMMY; +/** Just a dummy global structure containing a bunch of + * function pointers to code which is wanted in the link. */ +PFNDUMMY g_apfnVBoxCAPIGlue[] = +{ +#ifndef WIN32 + /* The following link dependency is for helping gdb as it gets hideously + * confused if the application doesn't drag in pthreads, but uses it. */ + (PFNDUMMY)pthread_create, +#endif /* !WIN32 */ + NULL +}; + + +/** + * Wrapper for setting g_szVBoxErrMsg. Can be an empty stub. + * + * @param fAlways When 0 the g_szVBoxErrMsg is only set if empty. + * @param pszFormat The format string. + * @param ... The arguments. + */ +static void setErrMsg(int fAlways, const char *pszFormat, ...) +{ + if ( fAlways + || !g_szVBoxErrMsg[0]) + { + va_list va; + va_start(va, pszFormat); + vsnprintf(g_szVBoxErrMsg, sizeof(g_szVBoxErrMsg), pszFormat, va); + va_end(va); + } +} + + +/** + * Try load C API .so/dylib/dll from the specified location and resolve all + * the symbols we need. Tries both the new style and legacy name. + * + * @returns 0 on success, -1 on failure. + * @param pszHome The directory where to try load VBoxCAPI/VBoxXPCOMC + * from. Can be NULL. + * @param fSetAppHome Whether to set the VBOX_APP_HOME env.var. or not + * (boolean). + */ +static int tryLoadLibrary(const char *pszHome, int fSetAppHome) +{ + size_t cchHome = pszHome ? strlen(pszHome) : 0; + size_t cbBufNeeded; + char szName[4096]; + + /* + * Construct the full name. + */ + cbBufNeeded = cchHome + sizeof("/" DYNLIB_NAME); + if (cbBufNeeded > sizeof(szName)) + { + setErrMsg(1, "path buffer too small: %u bytes needed", + (unsigned)cbBufNeeded); + return -1; + } + if (cchHome) + { + memcpy(szName, pszHome, cchHome); + szName[cchHome] = '/'; + cchHome++; + } + memcpy(&szName[cchHome], DYNLIB_NAME, sizeof(DYNLIB_NAME)); + + /* + * Try load it by that name, setting the VBOX_APP_HOME first (for now). + * Then resolve and call the function table getter. + */ + if (fSetAppHome) + { +#ifndef WIN32 + if (pszHome) + setenv("VBOX_APP_HOME", pszHome, 1 /* always override */); + else + unsetenv("VBOX_APP_HOME"); +#endif /* !WIN32 */ + } + +#ifndef WIN32 + g_hVBoxCAPI = dlopen(szName, RTLD_NOW | RTLD_LOCAL); + if (g_hVBoxCAPI) + { + PFNVBOXGETCAPIFUNCTIONS pfnGetFunctions; + pfnGetFunctions = (PFNVBOXGETCAPIFUNCTIONS)(uintptr_t) + dlsym(g_hVBoxCAPI, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME); +#ifdef VBOX_GET_XPCOM_FUNCTIONS_SYMBOL_NAME + if (!pfnGetFunctions) + pfnGetFunctions = (PFNVBOXGETCAPIFUNCTIONS)(uintptr_t) + dlsym(g_hVBoxCAPI, VBOX_GET_XPCOM_FUNCTIONS_SYMBOL_NAME); +#endif /* VBOX_GET_XPCOM_FUNCTIONS_SYMBOL_NAME */ + if (pfnGetFunctions) + { + g_pVBoxFuncs = pfnGetFunctions(VBOX_CAPI_VERSION); + if (g_pVBoxFuncs) + { + g_pfnGetFunctions = pfnGetFunctions; + return 0; + } + + /* bail out */ + setErrMsg(1, "%.80s: pfnGetFunctions(%#x) failed", + szName, VBOX_CAPI_VERSION); + } + else + setErrMsg(1, "dlsym(%.80s/%.32s): %.128s", + szName, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME, dlerror()); + dlclose(g_hVBoxCAPI); + g_hVBoxCAPI = NULL; + } + else + setErrMsg(0, "dlopen(%.80s): %.160s", szName, dlerror()); +#else /* !WIN32 */ + g_hVBoxCAPI = LoadLibraryExA(szName, NULL /* hFile */, 0 /* dwFlags */); + if (g_hVBoxCAPI) + { + PFNVBOXGETCAPIFUNCTIONS pfnGetFunctions; + pfnGetFunctions = (PFNVBOXGETCAPIFUNCTIONS) + GetProcAddress(g_hVBoxCAPI, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME); + if (pfnGetFunctions) + { + g_pVBoxFuncs = pfnGetFunctions(VBOX_CAPI_VERSION); + if (g_pVBoxFuncs) + { + g_pfnGetFunctions = pfnGetFunctions; + return 0; + } + + /* bail out */ + setErrMsg(1, "%.80s: pfnGetFunctions(%#x) failed", + szName, VBOX_CAPI_VERSION); + } + else + setErrMsg(1, "GetProcAddress(%.80s/%.32s): %d", + szName, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME, GetLastError()); + FreeLibrary(g_hVBoxCAPI); + g_hVBoxCAPI = NULL; + } + else + setErrMsg(0, "LoadLibraryEx(%.80s): %d", szName, GetLastError()); +#endif /* !WIN32 */ + + return -1; +} + + +/** + * Tries to locate and load VBoxCAPI.so/dylib/dll, resolving all the related + * function pointers. + * + * @returns 0 on success, -1 on failure. + * + * @remark This should be considered moved into a separate glue library since + * its its going to be pretty much the same for any user of VBoxCAPI + * and it will just cause trouble to have duplicate versions of this + * source code all around the place. + */ +int VBoxCGlueInit(void) +{ + const char *pszHome; + + memset(g_szVBoxErrMsg, 0, sizeof(g_szVBoxErrMsg)); + + /* + * If the user specifies the location, try only that. + */ + pszHome = getenv("VBOX_APP_HOME"); + if (pszHome) + return tryLoadLibrary(pszHome, 0); + + /* + * Try the known standard locations. + */ +#if defined(__gnu__linux__) || defined(__linux__) + if (tryLoadLibrary("/opt/VirtualBox", 1) == 0) + return 0; + if (tryLoadLibrary("/usr/lib/virtualbox", 1) == 0) + return 0; +#elif defined(__sun__) + if (tryLoadLibrary("/opt/VirtualBox/amd64", 1) == 0) + return 0; + if (tryLoadLibrary("/opt/VirtualBox/i386", 1) == 0) + return 0; +#elif defined(__APPLE__) + if (tryLoadLibrary("/Application/VirtualBox.app/Contents/MacOS", 1) == 0) + return 0; +#elif defined(__FreeBSD__) + if (tryLoadLibrary("/usr/local/lib/virtualbox", 1) == 0) + return 0; +#elif defined(__OS2__) + if (tryLoadLibrary("C:/Apps/VirtualBox", 1) == 0) + return 0; +#elif defined(WIN32) + pszHome = getenv("ProgramFiles"); + if (pszHome) + { + char szPath[4096]; + size_t cb = sizeof(szPath); + char *tmp = szPath; + strncpy(tmp, pszHome, cb); + tmp[cb - 1] = '\0'; + cb -= strlen(tmp); + tmp += strlen(tmp); + strncpy(tmp, "/Oracle/VirtualBox", cb); + tmp[cb - 1] = '\0'; + if (tryLoadLibrary(szPath, 1) == 0) + return 0; + } + if (tryLoadLibrary("C:/Program Files/Oracle/VirtualBox", 1) == 0) + return 0; +#else +# error "port me" +#endif + + /* + * Finally try the dynamic linker search path. + */ + if (tryLoadLibrary(NULL, 1) == 0) + return 0; + + /* No luck, return failure. */ + return -1; +} + + +/** + * Terminate the C glue library. + */ +void VBoxCGlueTerm(void) +{ + if (g_hVBoxCAPI) + { +#if 0 /* VBoxRT.so doesn't like being reloaded. See @bugref{3725}. */ +#ifndef WIN32 + dlclose(g_hVBoxCAPI); +#else + FreeLibrary(g_hVBoxCAPI); +#endif +#endif + g_hVBoxCAPI = NULL; + } + g_pVBoxFuncs = NULL; + g_pfnGetFunctions = NULL; + memset(g_szVBoxErrMsg, 0, sizeof(g_szVBoxErrMsg)); +} + diff --git a/pool/shard006/C/0118495_hello.c b/pool/shard006/C/0118495_hello.c new file mode 100644 index 0000000000000000000000000000000000000000..52a727f5059d4db5cb0b6caef0951c459063ac25 --- /dev/null +++ b/pool/shard006/C/0118495_hello.c @@ -0,0 +1,50 @@ +#include "hello.h" +#include "SDL.h" +#include "PDL.h" + +PDL_bool hello(PDL_JSParameters *params) +{ + const char *name = NULL; + if (PDL_GetNumJSParams(params) < 1 || !(name = PDL_GetJSParamString(params, 0))) { + PDL_JSException(params, "You must send a name string"); + return PDL_TRUE; + } + + char reply[MAXLINLEN]; + snprintf(reply, MAXLINLEN, "Hello %s!", name); + PDL_JSReply(params, reply); + + return PDL_TRUE; +} + +int main(int argc, char** argv) +{ + // Initialize the SDL library + int result = SDL_Init(SDL_INIT_VIDEO); + + if ( result != 0 ) { + printf("Could not init SDL: %s\n", SDL_GetError()); + exit(1); + } + + PDL_Init(0); + + // register the js callback + PDL_RegisterJSHandler("hello", hello); + PDL_JSRegistrationComplete(); + PDL_CallJS("ready", NULL, 0); + + // Event descriptor + SDL_Event Event; + + do { + SDL_WaitEvent(&Event); + } while (Event.type != SDL_QUIT); + // We exit anytime we get a request to quit the app + + // Cleanup + PDL_Quit(); + SDL_Quit(); + + return 0; +} diff --git a/pool/shard006/C/0118503_bluetooth.c b/pool/shard006/C/0118503_bluetooth.c new file mode 100644 index 0000000000000000000000000000000000000000..eda577505e9a2f61e7ce12edd4293b966034e93c --- /dev/null +++ b/pool/shard006/C/0118503_bluetooth.c @@ -0,0 +1,198 @@ +/* Copyright (C) 2007 L. Donnie Smith + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * ChangeLog: + * 2007-04-24 L. Donnie Smith (cwiid@abstrakraft.org> + * * revised error messages + * + * 2007-04-12 L. Donnie Smith + * * streamlined wiimote filter + * + * 2007-04-09 L. Donnie Smith + * * renamed wiimote to libcwiid, renamed structures accordingly + * + * 2007-04-07 L. Donnie Smith + * * changed cwiid_info.class to btclass + * + * 2007-04-03 L. Donnie Smith + * * fixed cwiid_find_wiimote seg fault + * + * 2007-04-02 L. Donnie Smith + * * exception handling bugs + * + * 2007-04-01 L. Donnie Smith + * * created file + */ + +#include +#include +#include +#include +#include +#include "cwiid_internal.h" + +/* When filtering wiimotes, in order to avoid having to store the + * remote names before the blue_dev array is malloced (because we don't + * yet know how many wiimotes there are, we'll assume there are no more + * than dev_count, and realloc to the actual number afterwards, since + * reallocing to a smaller chunk should be fast. */ +#define BT_MAX_INQUIRY 256 +/* timeout in 2 second units */ +int cwiid_get_bdinfo_array(int dev_id, unsigned int timeout, int max_bdinfo, + struct cwiid_bdinfo **bdinfo, uint8_t flags) +{ + inquiry_info *dev_list = NULL; + int max_inquiry; + int dev_count; + int sock = -1; + int bdinfo_count; + int i, j; + int err = 0; + int ret; + + /* NULLify for the benefit of error handling */ + *bdinfo = NULL; + + /* If not given (=-1), get the first available Bluetooth interface */ + if (dev_id == -1) { + if ((dev_id = hci_get_route(NULL)) == -1) { + cwiid_err(NULL, "No Bluetooth interface found"); + return -1; + } + } + + /* Get Bluetooth Device List */ + if ((flags & BT_NO_WIIMOTE_FILTER) && (max_bdinfo != -1)) { + max_inquiry = max_bdinfo; + } + else { + max_inquiry = BT_MAX_INQUIRY; + } + if ((dev_count = hci_inquiry(dev_id, timeout, max_inquiry, NULL, + &dev_list, IREQ_CACHE_FLUSH)) == -1) { + cwiid_err(NULL, "Bluetooth device inquiry error"); + err = 1; + goto CODA; + } + + if (dev_count == 0) { + bdinfo_count = 0; + goto CODA; + } + + /* Open connection to Bluetooth Interface */ + if ((sock = hci_open_dev(dev_id)) == -1) { + cwiid_err(NULL, "Bluetooth interface open error"); + err = 1; + goto CODA; + } + + /* Allocate info list */ + if (max_bdinfo == -1) { + max_bdinfo = dev_count; + } + if ((*bdinfo = malloc(max_bdinfo * sizeof **bdinfo)) == NULL) { + cwiid_err(NULL, "Memory allocation error (bdinfo array)"); + err = 1; + goto CODA; + } + + /* Copy dev_list to bdinfo */ + for (bdinfo_count=i=0; (i < dev_count) && (bdinfo_count < max_bdinfo); + i++) { + /* Filter by class */ + if (!(flags & BT_NO_WIIMOTE_FILTER) && + ((dev_list[i].dev_class[0] != WIIMOTE_CLASS_0) || + (dev_list[i].dev_class[1] != WIIMOTE_CLASS_1) || + (dev_list[i].dev_class[2] != WIIMOTE_CLASS_2))) { + continue; + } + + /* timeout (10000) in milliseconds */ + if (hci_read_remote_name(sock, &dev_list[i].bdaddr, BT_NAME_LEN, + (*bdinfo)[bdinfo_count].name, 10000)) { + cwiid_err(NULL, "Bluetooth name read error"); + err = 1; + goto CODA; + } + + /* Filter by name */ + if (!(flags & BT_NO_WIIMOTE_FILTER) && + strncmp((*bdinfo)[bdinfo_count].name, WIIMOTE_NAME, BT_NAME_LEN)) { + continue; + } + + /* Passed filter, add to bdinfo */ + bacpy(&(*bdinfo)[bdinfo_count].bdaddr, &dev_list[i].bdaddr); + for (j=0; j<3; j++) { + (*bdinfo)[bdinfo_count].btclass[j] = + dev_list[i].dev_class[j]; + } + bdinfo_count++; + } + + if (bdinfo_count == 0) { + free(*bdinfo); + } + else if (bdinfo_count < max_bdinfo) { + if ((*bdinfo = realloc(*bdinfo, bdinfo_count * sizeof **bdinfo)) + == NULL) { + cwiid_err(NULL, "Memory reallocation error (bdinfo array)"); + err = 1; + goto CODA; + } + } + +CODA: + if (dev_list) free(dev_list); + if (sock != -1) hci_close_dev(sock); + if (err) { + if (*bdinfo) free(*bdinfo); + ret = -1; + } + else { + ret = bdinfo_count; + } + return ret; +} + +int cwiid_find_wiimote(bdaddr_t *bdaddr, int timeout) +{ + struct cwiid_bdinfo *bdinfo; + int bdinfo_count; + + if (timeout == -1) { + while ((bdinfo_count = cwiid_get_bdinfo_array(-1, 2, 1, &bdinfo, 0)) + == 0); + if (bdinfo_count == -1) { + return -1; + } + } + else { + bdinfo_count = cwiid_get_bdinfo_array(-1, timeout, 1, &bdinfo, 0); + if (bdinfo_count == -1) { + return -1; + } + else if (bdinfo_count == 0) { + cwiid_err(NULL, "No wiimotes found"); + return -1; + } + } + + bacpy(bdaddr, &bdinfo[0].bdaddr); + free(bdinfo); + return 0; +} diff --git a/pool/shard006/C/0118504_imap_cmd_select_prev.c b/pool/shard006/C/0118504_imap_cmd_select_prev.c new file mode 100644 index 0000000000000000000000000000000000000000..3d7b6f1446c23c2d9c0eeb06315fe9b1fa81f813 --- /dev/null +++ b/pool/shard006/C/0118504_imap_cmd_select_prev.c @@ -0,0 +1,77 @@ +/* + * This is a plug-in for GIMP. + * + * Generates clickable image maps. + * + * Copyright (C) 1998-2003 Maurits Rijk lpeek.mrijk@consunet.nl + * + * 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 "config.h" + +#include + +#include "imap_commands.h" + +#include "libgimp/stdplugins-intl.h" + +static CmdExecuteValue_t select_prev_command_execute(Command_t *parent); + +static CommandClass_t select_prev_command_class = { + NULL, /* select_prev_command_destruct */ + select_prev_command_execute, + NULL, /* select_prev_command_undo */ + NULL /* select_prev_command_redo */ +}; + +typedef struct { + Command_t parent; + ObjectList_t *list; +} SelectPrevCommand_t; + +Command_t* +select_prev_command_new(ObjectList_t *list) +{ + SelectPrevCommand_t *command = g_new(SelectPrevCommand_t, 1); + command->list = list; + return command_init(&command->parent, _("Select Previous"), + &select_prev_command_class); +} + +static void +select_one_object(Object_t *obj, gpointer data) +{ + SelectPrevCommand_t *command = (SelectPrevCommand_t*) data; + Command_t *sub_command; + + sub_command = (obj->selected) + ? select_command_new(obj) : unselect_command_new(obj); + command_add_subcommand(&command->parent, sub_command); +} + +static CmdExecuteValue_t +select_prev_command_execute(Command_t *parent) +{ + SelectPrevCommand_t *command = (SelectPrevCommand_t*) parent; + ObjectList_t *list = command->list; + gpointer id; + + id = object_list_add_select_cb(list, select_one_object, command); + object_list_select_prev(list); + object_list_remove_select_cb(list, id); + return CMD_APPEND; +} diff --git a/pool/shard006/C/0118505_main.c b/pool/shard006/C/0118505_main.c new file mode 100644 index 0000000000000000000000000000000000000000..02f0bd4a8245fdddcd7cc7b5714158bb1879e8b9 --- /dev/null +++ b/pool/shard006/C/0118505_main.c @@ -0,0 +1,26 @@ +#include +#include +int getMaxElement(int array[], int size) { + int max = array[0]; + for (int i = 1; i < size; i++) { + if (array[i] > max) { + max = array[i]; + } + } + return max; +} +int main(int argc, char **argv) { + printf("= Aufgabe 13 =\n"); + + int a[3] = { 0, 2, 1 }; + int b[5] = { 0, 1, 4, 3, 2 }; + int c[9] = { 0, 7, 2, 3, 8, 5, 6, 1, 4 }; + int d[4] = { 3, 1, 2, 0 }; + + printf("Größtes Element des Arrays a => %d\n", getMaxElement(a, sizeof(a) / 4)); + printf("Größtes Element des Arrays b => %d\n", getMaxElement(b, sizeof(b) / 4)); + printf("Größtes Element des Arrays c => %d\n", getMaxElement(c, sizeof(c) / 4)); + printf("Größtes Element des Arrays d => %d\n", getMaxElement(d, sizeof(d) / 4)); + + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C/0118506_gstrtpg726depay.c b/pool/shard006/C/0118506_gstrtpg726depay.c new file mode 100644 index 0000000000000000000000000000000000000000..cedcd7da1970243785bb324f4f20124da3a538b8 --- /dev/null +++ b/pool/shard006/C/0118506_gstrtpg726depay.c @@ -0,0 +1,207 @@ +/* GStreamer + * Copyright (C) 1999 Erik Walthinsen + * Copyright (C) 2005 Edgard Lima + * Copyright (C) 2005 Zeeshan Ali + * Copyright (C) 2008 Axis Communications + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include + +#include "gstrtpg726depay.h" + +#define DEFAULT_BIT_RATE 32000 +#define SAMPLE_RATE 8000 +#define LAYOUT_G726 "g726" + +/* elementfactory information */ +static const GstElementDetails gst_rtp_g726depay_details = +GST_ELEMENT_DETAILS ("RTP packet depayloader", + "Codec/Depayloader/Network", + "Extracts G.726 audio from RTP packets", + "Axis Communications "); + +/* RtpG726Depay signals and args */ +enum +{ + /* FILL ME */ + LAST_SIGNAL +}; + +enum +{ + ARG_0 +}; + +static GstStaticPadTemplate gst_rtp_g726_depay_sink_template = + GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("application/x-rtp, " + "media = (string) \"audio\", " + "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", " + "encoding-name = (string) { \"G726\", \"G726-16\", \"G726-24\", \"G726-32\", \"G726-40\"}, " + "clock-rate = (int) 8000;") + ); + +static GstStaticPadTemplate gst_rtp_g726_depay_src_template = +GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("audio/x-adpcm, " + "channels = (int) 1, " + "rate = (int) 8000, " + "bitrate = (int) { 16000, 24000, 32000, 40000 }, " + "layout = (string) \"g726\"") + ); + +static GstBuffer *gst_rtp_g726_depay_process (GstBaseRTPDepayload * depayload, + GstBuffer * buf); +static gboolean gst_rtp_g726_depay_setcaps (GstBaseRTPDepayload * depayload, + GstCaps * caps); + +GST_BOILERPLATE (GstRtpG726Depay, gst_rtp_g726_depay, GstBaseRTPDepayload, + GST_TYPE_BASE_RTP_DEPAYLOAD); + +static void +gst_rtp_g726_depay_base_init (gpointer klass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (klass); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gst_rtp_g726_depay_src_template)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gst_rtp_g726_depay_sink_template)); + gst_element_class_set_details (element_class, &gst_rtp_g726depay_details); +} + +static void +gst_rtp_g726_depay_class_init (GstRtpG726DepayClass * klass) +{ + GObjectClass *gobject_class; + GstElementClass *gstelement_class; + GstBaseRTPDepayloadClass *gstbasertpdepayload_class; + + gobject_class = (GObjectClass *) klass; + gstelement_class = (GstElementClass *) klass; + gstbasertpdepayload_class = (GstBaseRTPDepayloadClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gstbasertpdepayload_class->process = gst_rtp_g726_depay_process; + gstbasertpdepayload_class->set_caps = gst_rtp_g726_depay_setcaps; +} + +static void +gst_rtp_g726_depay_init (GstRtpG726Depay * rtpG726depay, + GstRtpG726DepayClass * klass) +{ + GstBaseRTPDepayload *depayload; + + depayload = GST_BASE_RTP_DEPAYLOAD (rtpG726depay); + + gst_pad_use_fixed_caps (GST_BASE_RTP_DEPAYLOAD_SRCPAD (depayload)); +} + +static gboolean +gst_rtp_g726_depay_setcaps (GstBaseRTPDepayload * depayload, GstCaps * caps) +{ + GstCaps *srccaps; + GstStructure *structure; + gboolean ret; + gint clock_rate = 8000; /* default */ + const gchar *encoding_name; + gint bitrate; + + structure = gst_caps_get_structure (caps, 0); + + gst_structure_get_int (structure, "clock-rate", &clock_rate); + depayload->clock_rate = clock_rate; + + encoding_name = gst_structure_get_string (structure, "encoding-name"); + if (encoding_name == NULL || g_ascii_strcasecmp (encoding_name, "G726") == 0) { + bitrate = DEFAULT_BIT_RATE; + } else if (g_ascii_strcasecmp (encoding_name, "G726-16") == 0) { + bitrate = 16000; + } else if (g_ascii_strcasecmp (encoding_name, "G726-24") == 0) { + bitrate = 24000; + } else if (g_ascii_strcasecmp (encoding_name, "G726-32") == 0) { + bitrate = 32000; + } else if (g_ascii_strcasecmp (encoding_name, "G726-40") == 0) { + bitrate = 40000; + } else { + GST_WARNING ("Could not determine bitrate from encoding-name (%s)", + encoding_name); + ret = FALSE; + goto done; + } + GST_DEBUG ("RTP G.726 depayloader, bitrate set to %d\n", bitrate); + + srccaps = gst_caps_new_simple ("audio/x-adpcm", + "channels", G_TYPE_INT, 1, + "rate", G_TYPE_INT, clock_rate, + "bitrate", G_TYPE_INT, bitrate, + "layout", G_TYPE_STRING, LAYOUT_G726, NULL); + + ret = gst_pad_set_caps (GST_BASE_RTP_DEPAYLOAD_SRCPAD (depayload), srccaps); + gst_caps_unref (srccaps); + +done: + return ret; +} + + +static GstBuffer * +gst_rtp_g726_depay_process (GstBaseRTPDepayload * depayload, GstBuffer * buf) +{ + GstCaps *srccaps; + GstBuffer *outbuf = NULL; + + GST_DEBUG ("process : got %d bytes, mark %d ts %u seqn %d", + GST_BUFFER_SIZE (buf), + gst_rtp_buffer_get_marker (buf), + gst_rtp_buffer_get_timestamp (buf), gst_rtp_buffer_get_seq (buf)); + + srccaps = GST_PAD_CAPS (GST_BASE_RTP_DEPAYLOAD_SRCPAD (depayload)); + if (!srccaps) { + /* Set the default caps */ + srccaps = gst_caps_new_simple ("audio/x-adpcm", + "channels", G_TYPE_INT, 1, + "rate", G_TYPE_INT, SAMPLE_RATE, + "bitrate", G_TYPE_INT, DEFAULT_BIT_RATE, + "layout", G_TYPE_STRING, LAYOUT_G726, NULL); + gst_pad_set_caps (GST_BASE_RTP_DEPAYLOAD_SRCPAD (depayload), srccaps); + gst_caps_unref (srccaps); + } + outbuf = gst_rtp_buffer_get_payload_buffer (buf); + + return outbuf; +} + +gboolean +gst_rtp_g726_depay_plugin_init (GstPlugin * plugin) +{ + return gst_element_register (plugin, "rtpg726depay", + GST_RANK_MARGINAL, GST_TYPE_RTP_G726_DEPAY); +} diff --git a/pool/shard006/C/0118511_m_whowas.c b/pool/shard006/C/0118511_m_whowas.c new file mode 100644 index 0000000000000000000000000000000000000000..a5038cce88694112b5924d9c6e12d9b62901e7d6 --- /dev/null +++ b/pool/shard006/C/0118511_m_whowas.c @@ -0,0 +1,151 @@ +/* + * ircd-ratbox: A slightly useful ircd. + * m_whois.c: Shows who a user was. + * + * Copyright (C) 1990 Jarkko Oikarinen and University of Oulu, Co Center + * Copyright (C) 1996-2002 Hybrid Development Team + * Copyright (C) 2002-2005 ircd-ratbox development team + * + * 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 "stdinc.h" +#include "whowas.h" +#include "client.h" +#include "hash.h" +#include "match.h" +#include "ircd.h" +#include "ircd_defs.h" +#include "numeric.h" +#include "s_serv.h" +#include "s_user.h" +#include "send.h" +#include "s_conf.h" +#include "msg.h" +#include "parse.h" +#include "modules.h" + +static const char whowas_desc[] = + "Provides the WHOWAS command to display information on a disconnected user"; + +static void m_whowas(struct MsgBuf *, struct Client *, struct Client *, int, const char **); + +struct Message whowas_msgtab = { + "WHOWAS", 0, 0, 0, 0, + {mg_unreg, {m_whowas, 2}, {m_whowas, 4}, mg_ignore, mg_ignore, {m_whowas, 2}} +}; + +mapi_clist_av1 whowas_clist[] = { &whowas_msgtab, NULL }; + +DECLARE_MODULE_AV2(whowas, NULL, NULL, whowas_clist, NULL, NULL, NULL, NULL, whowas_desc); + +/* +** m_whowas +** parv[1] = nickname queried +*/ +static void +m_whowas(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) +{ + rb_dlink_list *whowas_list; + rb_dlink_node *ptr; + int cur = 0; + int max = -1; + char *p; + const char *nick; + char tbuf[26]; + long sendq_limit; + + static time_t last_used = 0L; + + if(MyClient(source_p) && !IsOper(source_p)) + { + if(last_used + (parc > 3 ? ConfigFileEntry.pace_wait : + ConfigFileEntry.pace_wait_simple + ) > rb_current_time()) + { + sendto_one(source_p, form_str(RPL_LOAD2HI), + me.name, source_p->name, "WHOWAS"); + sendto_one_numeric(source_p, RPL_ENDOFWHOWAS, form_str(RPL_ENDOFWHOWAS), + parv[1]); + return; + } + else + last_used = rb_current_time(); + } + + + if(parc > 2) + max = atoi(parv[2]); + + if(parc > 3) + if(hunt_server(client_p, source_p, ":%s WHOWAS %s %s :%s", 3, parc, parv)) + return; + + if(!MyClient(source_p) && (max <= 0 || max > 20)) + max = 20; + + if((p = strchr(parv[1], ','))) + *p = '\0'; + + nick = parv[1]; + + sendq_limit = get_sendq(client_p) * 9 / 10; + whowas_list = whowas_get_list(nick); + + if(whowas_list == NULL) + { + sendto_one_numeric(source_p, ERR_WASNOSUCHNICK, form_str(ERR_WASNOSUCHNICK), nick); + sendto_one_numeric(source_p, RPL_ENDOFWHOWAS, form_str(RPL_ENDOFWHOWAS), parv[1]); + return; + } + + RB_DLINK_FOREACH(ptr, whowas_list->head) + { + struct Whowas *temp = ptr->data; + if(cur > 0 && rb_linebuf_len(&client_p->localClient->buf_sendq) > sendq_limit) + { + sendto_one(source_p, form_str(ERR_TOOMANYMATCHES), + me.name, source_p->name, "WHOWAS"); + break; + } + + sendto_one(source_p, form_str(RPL_WHOWASUSER), + me.name, source_p->name, temp->name, + temp->username, temp->hostname, temp->realname); + if (!EmptyString(temp->sockhost) && + strcmp(temp->sockhost, "0") && + show_ip_whowas(temp, source_p)) + sendto_one_numeric(source_p, RPL_WHOISACTUALLY, + form_str(RPL_WHOISACTUALLY), + temp->name, temp->sockhost); + + if (!EmptyString(temp->suser)) + sendto_one_numeric(source_p, RPL_WHOISLOGGEDIN, + "%s %s :was logged in as", + temp->name, temp->suser); + + sendto_one_numeric(source_p, RPL_WHOISSERVER, + form_str(RPL_WHOISSERVER), + temp->name, temp->servername, + rb_ctime(temp->logoff, tbuf, sizeof(tbuf))); + + cur++; + if(max > 0 && cur >= max) + break; + } + + sendto_one_numeric(source_p, RPL_ENDOFWHOWAS, form_str(RPL_ENDOFWHOWAS), parv[1]); +} diff --git a/pool/shard006/C/0118517_c_ctgetc.c b/pool/shard006/C/0118517_c_ctgetc.c new file mode 100644 index 0000000000000000000000000000000000000000..f25e05938a3c15dfbbd6621d84f2f59c9a183d65 --- /dev/null +++ b/pool/shard006/C/0118517_c_ctgetc.c @@ -0,0 +1,64 @@ +/* + * $Id: c_ctgetc.c,v 1.2 2008-07-23 16:16:44 haley Exp $ + */ +/************************************************************************ +* * +* Copyright (C) 2000 * +* University Corporation for Atmospheric Research * +* All Rights Reserved * +* * +* The use of this Software is governed by a License Agreement. * +* * +************************************************************************/ + +#include + +extern void NGCALLF(ctgetc,CTGETC)(NGstring,NGstring,int,int); + +void c_ctgetc +#ifdef NeedFuncProto +( + char *whch, + char *cval, + int len +) +#else +(whch,cval,len) + char *whch; + char *cval; + int len; +#endif +{ + int i, len1; + char error_msg[256]; + NGstring whch2; + NGstring cval2; +/* + * Make sure return string is valid + */ + if( chk_ret_str( cval, len, error_msg ) ) { + fprintf( stderr, "c_ctgetc: %s\n", error_msg ); + return; + } +/* + * Make sure parameter name is not NULL + */ + if( !whch ) { + fprintf( stderr, "c_ctgetc: illegal parameter name (NULL)\n" ); + return; + } + + len1 = NGSTRLEN(whch); + cval2 = NGCstrToFstr(cval,len); + whch2 = NGCstrToFstr(whch,len1); + NGCALLF(ctgetc,CTGETC)(whch2,cval2,len1,len-1); + + cval = NGFstrToCstr(cval2); + cval[len-1] = '\0'; + for( i = len-2; i >= 0; i-- ) { + if( cval[i] != ' ' && cval[i] != '\0' ) { + cval[i+1] = '\0'; + break; + } + } +} diff --git a/pool/shard006/C/0118520_test.c b/pool/shard006/C/0118520_test.c new file mode 100644 index 0000000000000000000000000000000000000000..371a18feef74a05f82e0f269dc3049877ee3643f --- /dev/null +++ b/pool/shard006/C/0118520_test.c @@ -0,0 +1,60 @@ +// 'Heap allocated VLA' (variable length-array) - actually only pointer +// with function for performing the allocation. +// This is a C99 standard! + +// Reference + +// note that returning the pointer will not work, since this is a VLA! +// they are automatic objects and are deallocated if they go out of scope +// hence the need to use the input parameter + +// Alexandre Lopes + +#include +#include + +int arrayAlloc2D (int dim1, int dim2, double(**array)[dim1][dim2]) +{ + + /* allocate VLA on the heap */ + (*array) = malloc(sizeof( **array )); + if ((*array) == NULL ) + { + return -1; + } + + return 0; +} + +int main() +{ + int dim1 = 5; + int dim2 = 5; + int i, j; + + double (*array)[dim1][dim2] = NULL; + int ret = arrayAlloc2D(dim1, dim2, &array); // return value should be checked + if (ret == -1) + { + return -1; + } + + for (i = 0; i < dim1; i++) + { + for (j = 0; j < dim2; j++) + { + (*array)[i][j] = i+j; + } + } + + for (i = 0; i < dim1; i++) + { + for (j = 0; j < dim2; j++) + { + printf("%f \n", (*array)[i][j]); + } + } + + free(*array); + return 0; +} diff --git a/pool/shard006/C/0118521_CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04.c b/pool/shard006/C/0118521_CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04.c new file mode 100644 index 0000000000000000000000000000000000000000..9b60e64114d6097d09d769fc3b6e89eb803421e6 --- /dev/null +++ b/pool/shard006/C/0118521_CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04.c @@ -0,0 +1,244 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04.c +Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml +Template File: sources-sink-04.tmpl.c +*/ +/* + * @description + * CWE: 194 Unexpected Sign Extension + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Positive integer + * Sink: malloc + * BadSink : Allocate memory using malloc() with the size of data + * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE) + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 +/* Must be at least 8 for atoi() to work properly */ +#define CHAR_ARRAY_SIZE 8 + +/* The two variables below are declared "const", so a tool should + * be able to identify that reads of these will always return their + * initialized values. + */ +static const int STATIC_CONST_TRUE = 1; /* true */ +static const int STATIC_CONST_FALSE = 0; /* false */ + +#ifndef OMITBAD + +void CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04_bad() +{ + short data; + /* Initialize data */ + data = 0; + if(STATIC_CONST_TRUE) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + int tempInt; + struct sockaddr_in service; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + char inputBuffer[CHAR_ARRAY_SIZE]; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); + /* FLAW: Use a value input from the network */ + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* NUL-terminate string */ + inputBuffer[recvResult] = '\0'; + /* Convert to short - ensure int to short conversion will be successful and if + * not ensure that data will be negative */ + tempInt = atoi(inputBuffer); + if (tempInt > SHRT_MAX || tempInt < SHRT_MIN) + { + data = -1; + } + else + { + data = tempInt; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the STATIC_CONST_TRUE to STATIC_CONST_FALSE */ +static void goodG2B1() +{ + short data; + /* Initialize data */ + data = 0; + if(STATIC_CONST_FALSE) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + short data; + /* Initialize data */ + data = 0; + if(STATIC_CONST_TRUE) + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +void CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE194_Unexpected_Sign_Extension__listen_socket_malloc_04_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0118522_archos-flash.c b/pool/shard006/C/0118522_archos-flash.c new file mode 100644 index 0000000000000000000000000000000000000000..d8c740132eb91ca6071924d279f40be98cee62d8 --- /dev/null +++ b/pool/shard006/C/0118522_archos-flash.c @@ -0,0 +1,205 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define GPMC_CS_SIZE 0x30 + +#define NOR_BOOT_BLOCK_SIZE SZ_8K +#define NOR_BLOCK_SIZE SZ_64K +#define NAND_BLOCK_SIZE SZ_128K + +#define FLASH_PART_NAME_STAGE1 "stage1" +#define FLASH_PART_NAME_STAGE2 "stage2" +#define FLASH_PART_NAME_STORE5 "store5" +#define FLASH_PART_NAME_STOREX "storex" +#define FLASH_PART_NAME_STOREXFLAT "storexflat" +#define FLASH_PART_NAME_LOGO "logo" +#define FLASH_PART_NAME_INIT "init" +#define FLASH_PART_NAME_ENV "env" +#define FLASH_PART_NAME_RECOVERY "recovery" +#define FLASH_PART_NAME_SYSTEM "system" +#define FLASH_PART_NAME_DATA "data" + +#ifdef CONFIG_MACH_ARCHOS_PRODTEST_MTD + #define MTD0_MASK_FLAGS 0 +#else + #define MTD0_MASK_FLAGS MTD_WRITEABLE /* force read-only */ +#endif + +static struct mtd_partition archos_nor_partitions[] = { + /* All the partition sizes are listed in terms of Nor block size */ + { + .name = FLASH_PART_NAME_STAGE1, + .offset = 0, + .size = 1 * NOR_BLOCK_SIZE, + .mask_flags = MTD_WRITEABLE, /* force read-only */ + }, + { + .name = FLASH_PART_NAME_STORE5, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x010000 */ + .size = 2 * NOR_BLOCK_SIZE, + .mask_flags = MTD_WRITEABLE, /* force read-only */ + }, + { + .name = FLASH_PART_NAME_STAGE2, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x030000 */ + .size = 3 * NOR_BLOCK_SIZE, + }, + { + .name = FLASH_PART_NAME_LOGO, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x060000 */ + .size = 2 * NOR_BLOCK_SIZE, + }, + { + .name = FLASH_PART_NAME_RECOVERY, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x080000 */ + .size = 25 * NOR_BLOCK_SIZE, + }, + { + .name = FLASH_PART_NAME_INIT, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x210000 */ + .size = 30 * NOR_BLOCK_SIZE, + }, +/* + { + .name = FLASH_PART_NAME_ENV, + .offset = MTDPART_OFS_APPEND, // Offset = 0x3F0000 + .size = 1 * NOR_BOOT_BLOCK_SIZE, + }, +*/ + { + .name = FLASH_PART_NAME_STOREXFLAT, /* + AVBoot Evironment */ + .offset = MTDPART_OFS_APPEND, /* Offset = 0x3F2000 */ + .size = MTDPART_SIZ_FULL, + }, +}; + +static struct flash_platform_data archos_nor_data = { + .map_name = "cfi_probe", + .width = 2, + .parts = archos_nor_partitions, + .nr_parts = ARRAY_SIZE(archos_nor_partitions), +}; + +static struct resource archos_nor_resource = { + .start = 0, + .end = 0, + .flags = IORESOURCE_MEM, +}; + +static struct mtd_partition archos_nand_partitions[] = { + /* All the partition sizes are listed in terms of NAND block size */ + { + .name = FLASH_PART_NAME_STAGE1, + .offset = 0, + .size = 4 * NAND_BLOCK_SIZE, + .mask_flags = MTD0_MASK_FLAGS, + }, + { + .name = FLASH_PART_NAME_STAGE2, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x80000 */ + .size = 4 * NAND_BLOCK_SIZE, + .mask_flags = MTD_WRITEABLE, /* force read-only */ + }, + { + .name = FLASH_PART_NAME_RECOVERY, + .offset = 8 * NAND_BLOCK_SIZE, /* Offset = 0x100000 */ + .size = 24 * NAND_BLOCK_SIZE, + .mask_flags = MTD_WRITEABLE, /* force read-only */ + }, + { + .name = FLASH_PART_NAME_INIT, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x400000 */ + .size = 20 * NAND_BLOCK_SIZE, + }, + { + .name = FLASH_PART_NAME_STOREX, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x680000 */ + .size = 5 * NAND_BLOCK_SIZE, + }, + { + .name = FLASH_PART_NAME_SYSTEM, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x720000 */ + .size = 720 * NAND_BLOCK_SIZE, + }, + { + .name = FLASH_PART_NAME_DATA, + .offset = MTDPART_OFS_APPEND, /* Offset = 0x6120000 */ + .size = MTDPART_SIZ_FULL, + }, +}; + +static struct omap_nand_platform_data archos_nand_data = { + .options = NAND_BUSWIDTH_16, + .parts = archos_nand_partitions, + .nr_parts = ARRAY_SIZE(archos_nand_partitions), + .dma_channel = -1, /* disable DMA in OMAP NAND driver */ + .nand_setup = NULL, + .dev_ready = NULL, +}; + +static struct resource archos_nand_resource = { + .flags = IORESOURCE_MEM, +}; + +static struct platform_device archos_nor_device = { + .name = "omapflash", + .id = -1, + .dev = { + .platform_data = &archos_nor_data, + }, + .num_resources = 1, + .resource = &archos_nor_resource, +}; + +static struct platform_device archos_nand_device = { + .name = "omap2-nand", + .id = -1, + .dev = { + .platform_data = &archos_nand_data, + }, + .num_resources = 1, + .resource = &archos_nand_resource, +}; + +void __init archos_flash_init(void) +{ + u8 cs = 0; + + u32 gpmc_base_add = OMAP34XX_GPMC_VIRT; + + u32 ret = gpmc_cs_read_reg(cs, GPMC_CS_CONFIG1); + if ((ret & 0xC00) == GPMC_CONFIG1_DEVICETYPE_NOR) { + printk(KERN_INFO "Found NOR on CS%d\n", cs); + + archos_nor_resource.start = FLASH_BASE_NOR_ARCHOS; + archos_nor_resource.end = FLASH_BASE_NOR_ARCHOS + + FLASH_SIZE_NOR_ARCHOS - 1; + printk(KERN_INFO "Registering NOR on CS%d\n", cs); + if (platform_device_register(&archos_nor_device) < 0) + printk(KERN_ERR "Unable to register NOR device\n"); + } + else if ((ret & 0xC00) == GPMC_CONFIG1_DEVICETYPE_NAND) { + printk(KERN_INFO "Found NAND on CS%d\n", cs); + + archos_nand_data.cs = cs; + archos_nand_data.gpmc_cs_baseaddr = (void *) + (gpmc_base_add + GPMC_CS0_BASE + cs * GPMC_CS_SIZE); + archos_nand_data.gpmc_baseaddr = (void *) (gpmc_base_add); + + printk(KERN_INFO "Registering NAND on CS%d\n", cs); + if (platform_device_register(&archos_nand_device) < 0) + printk(KERN_ERR "Unable to register NAND device\n"); + + } else { + printk(KERN_ERR "No FLASH device found on CS%d\n", cs); + return; + } + +} diff --git a/pool/shard006/C/0118523_png.c b/pool/shard006/C/0118523_png.c new file mode 100644 index 0000000000000000000000000000000000000000..ef52b51bd43eebb7323846024dfa3223dd9d0e69 --- /dev/null +++ b/pool/shard006/C/0118523_png.c @@ -0,0 +1,72 @@ +/* + * PNG image format + * Copyright (c) 2003 Fabrice Bellard + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include "avcodec.h" +#include "png.h" + +/* Mask to determine which y pixels are valid in a pass */ +const uint8_t ff_png_pass_ymask[NB_PASSES] = { + 0x80, 0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, +}; + +/* minimum x value */ +static const uint8_t ff_png_pass_xmin[NB_PASSES] = { + 0, 4, 0, 2, 0, 1, 0 +}; + +/* x shift to get row width */ +static const uint8_t ff_png_pass_xshift[NB_PASSES] = { + 3, 3, 2, 2, 1, 1, 0 +}; + +void *ff_png_zalloc(void *opaque, unsigned int items, unsigned int size) +{ + return av_mallocz_array(items, size); +} + +void ff_png_zfree(void *opaque, void *ptr) +{ + av_free(ptr); +} + +int ff_png_get_nb_channels(int color_type) +{ + int channels; + channels = 1; + if ((color_type & (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)) == + PNG_COLOR_MASK_COLOR) + channels = 3; + if (color_type & PNG_COLOR_MASK_ALPHA) + channels++; + return channels; +} + +/* compute the row size of an interleaved pass */ +int ff_png_pass_row_size(int pass, int bits_per_pixel, int width) +{ + int shift, xmin, pass_width; + + xmin = ff_png_pass_xmin[pass]; + if (width <= xmin) + return 0; + shift = ff_png_pass_xshift[pass]; + pass_width = (width - xmin + (1 << shift) - 1) >> shift; + return (pass_width * bits_per_pixel + 7) >> 3; +} diff --git a/pool/shard006/C/0118525_error.c b/pool/shard006/C/0118525_error.c new file mode 100644 index 0000000000000000000000000000000000000000..5d4ce08234338a636a03ee6fdee52392e28575d9 --- /dev/null +++ b/pool/shard006/C/0118525_error.c @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2016 Canonical Ltd + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 3 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +#include "error.h" + +// To get vasprintf +#define _GNU_SOURCE + +#include "utils.h" + +#include +#include +#include +#include + +static sc_error *sc_error_initv(const char *domain, int code, + const char *msgfmt, va_list ap) +{ + // Set errno in case we die. + errno = 0; + sc_error *err = calloc(1, sizeof *err); + if (err == NULL) { + die("cannot allocate memory for error object"); + } + err->domain = domain; + err->code = code; + if (vasprintf(&err->msg, msgfmt, ap) == -1) { + die("cannot format error message"); + } + return err; +} + +sc_error *sc_error_init(const char *domain, int code, const char *msgfmt, ...) +{ + va_list ap; + va_start(ap, msgfmt); + sc_error *err = sc_error_initv(domain, code, msgfmt, ap); + va_end(ap); + return err; +} + +sc_error *sc_error_init_from_errno(int errno_copy, const char *msgfmt, ...) +{ + va_list ap; + va_start(ap, msgfmt); + sc_error *err = sc_error_initv(SC_ERRNO_DOMAIN, errno_copy, msgfmt, ap); + va_end(ap); + return err; +} + +sc_error *sc_error_init_simple(const char *msgfmt, ...) +{ + va_list ap; + va_start(ap, msgfmt); + sc_error *err = sc_error_initv(SC_LIBSNAP_DOMAIN, + SC_UNSPECIFIED_ERROR, msgfmt, ap); + va_end(ap); + return err; +} + +sc_error *sc_error_init_api_misuse(const char *msgfmt, ...) +{ + va_list ap; + va_start(ap, msgfmt); + sc_error *err = sc_error_initv(SC_LIBSNAP_DOMAIN, + SC_API_MISUSE, msgfmt, ap); + va_end(ap); + return err; +} + +const char *sc_error_domain(sc_error * err) +{ + // Set errno in case we die. + errno = 0; + if (err == NULL) { + die("cannot obtain error domain from NULL error"); + } + return err->domain; +} + +int sc_error_code(sc_error * err) +{ + // Set errno in case we die. + errno = 0; + if (err == NULL) { + die("cannot obtain error code from NULL error"); + } + return err->code; +} + +const char *sc_error_msg(sc_error * err) +{ + // Set errno in case we die. + errno = 0; + if (err == NULL) { + die("cannot obtain error message from NULL error"); + } + return err->msg; +} + +void sc_error_free(sc_error * err) +{ + if (err != NULL) { + free(err->msg); + err->msg = NULL; + free(err); + } +} + +void sc_cleanup_error(sc_error ** ptr) +{ + sc_error_free(*ptr); + *ptr = NULL; +} + +void sc_die_on_error(sc_error * error) +{ + if (error != NULL) { + if (strcmp(sc_error_domain(error), SC_ERRNO_DOMAIN) == 0) { + fprintf(stderr, "%s: %s\n", sc_error_msg(error), strerror(sc_error_code(error))); + } else { + fprintf(stderr, "%s\n", sc_error_msg(error)); + } + sc_error_free(error); + exit(1); + } +} + +int sc_error_forward(sc_error ** recipient, sc_error * error) +{ + if (recipient != NULL) { + *recipient = error; + } else { + sc_die_on_error(error); + } + return error != NULL ? -1 : 0; +} + +bool sc_error_match(sc_error * error, const char *domain, int code) +{ + // Set errno in case we die. + errno = 0; + if (domain == NULL) { + die("cannot match error to a NULL domain"); + } + if (error == NULL) { + return false; + } + return strcmp(sc_error_domain(error), domain) == 0 + && sc_error_code(error) == code; +} diff --git a/pool/shard006/C/0118529_pragha-song-info-thread-pane.c b/pool/shard006/C/0118529_pragha-song-info-thread-pane.c new file mode 100644 index 0000000000000000000000000000000000000000..34b61645876203303d170457e9b840ca3e4f987f --- /dev/null +++ b/pool/shard006/C/0118529_pragha-song-info-thread-pane.c @@ -0,0 +1,223 @@ +/*************************************************************************/ +/* Copyright (C) 2011-2014 matias */ +/* */ +/* 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 . */ +/*************************************************************************/ + +#if defined(GETTEXT_PACKAGE) +#include +#else +#include +#endif + +#include + +#include "pragha-song-info-plugin.h" +#include "pragha-song-info-pane.h" + +#include "src/pragha-simple-async.h" + +typedef struct { + PraghaSongInfoPlugin *plugin; + GCancellable *cancellable; + gulong cancel_id; + gchar *filename; + GlyrQuery query; + GlyrMemCache *head; +} glyr_struct; + + +/* + * Function to check if has the last + */ + +static gboolean +glyr_finished_thread_is_current_song (PraghaSongInfoPlugin *plugin, const gchar *filename) +{ + PraghaApplication *pragha; + PraghaBackend *backend; + PraghaMusicobject *mobj; + const gchar *current_filename = NULL; + + pragha = pragha_songinfo_plugin_get_application (plugin); + + backend = pragha_application_get_backend (pragha); + if (pragha_backend_get_state (backend) == ST_STOPPED) + return FALSE; + + mobj = pragha_backend_get_musicobject (backend); + current_filename = pragha_musicobject_get_file (mobj); + + if (g_ascii_strcasecmp(filename, current_filename)) + return FALSE; + + return TRUE; +} + +/* + * Threads + */ + +static void +glyr_finished_successfully_pane (glyr_struct *glyr_info) +{ + PraghaSonginfoPane *pane; + + switch (glyr_info->head->type) { + case GLYR_TYPE_LYRICS: + pane = pragha_songinfo_plugin_get_pane (glyr_info->plugin); + pragha_songinfo_pane_set_text (pane, glyr_info->query.title, glyr_info->head->data, glyr_info->head->prov); + break; + case GLYR_TYPE_ARTIST_BIO: + pane = pragha_songinfo_plugin_get_pane (glyr_info->plugin); + pragha_songinfo_pane_set_text (pane,glyr_info->query.artist, glyr_info->head->data, glyr_info->head->prov); + break; + case GLYR_TYPE_COVERART: + default: + break; + } +} + +static void +glyr_finished_incorrectly_pane (glyr_struct *glyr_info) +{ + PraghaSonginfoPane *pane; + + switch (glyr_info->query.type) { + case GLYR_GET_LYRICS: + pane = pragha_songinfo_plugin_get_pane (glyr_info->plugin); + pragha_songinfo_pane_set_text (pane, glyr_info->query.title, _("Lyrics not found."), ""); + break; + case GLYR_GET_ARTIST_BIO: + pane = pragha_songinfo_plugin_get_pane (glyr_info->plugin); + pragha_songinfo_pane_set_text (pane, glyr_info->query.artist, _("Artist information not found."), ""); + break; + case GLYR_GET_COVERART: + default: + break; + } +} + +static gboolean +glyr_finished_thread_update_pane (gpointer data) +{ + glyr_struct *glyr_info = data; + + if (g_cancellable_is_cancelled (glyr_info->cancellable)) + goto old_thread; + + if (!glyr_finished_thread_is_current_song(glyr_info->plugin, glyr_info->filename)) + goto old_thread; + + if (glyr_info->head != NULL) + glyr_finished_successfully_pane (glyr_info); + else + glyr_finished_incorrectly_pane (glyr_info); + +old_thread: + g_cancellable_disconnect (glyr_info->cancellable, glyr_info->cancel_id); + g_object_unref (glyr_info->cancellable); + + if (glyr_info->head != NULL) + glyr_free_list (glyr_info->head); + + glyr_query_destroy (&glyr_info->query); + g_free (glyr_info->filename); + + g_slice_free (glyr_struct, glyr_info); + + return FALSE; +} + +static gpointer +get_related_info_idle_func (gpointer data) +{ + GlyrMemCache *head; + GLYR_ERROR error; + + glyr_struct *glyr_info = data; + + head = glyr_get (&glyr_info->query, &error, NULL); + + glyr_info->head = head; + + return glyr_info; +} + +static void +search_cancelled (GCancellable *cancellable, gpointer user_data) +{ + GlyrQuery *query = user_data; + glyr_signal_exit (query); +} + +GCancellable * +pragha_songinfo_plugin_get_info_to_pane (PraghaSongInfoPlugin *plugin, + GLYR_GET_TYPE type, + const gchar *artist, + const gchar *title, + const gchar *filename) +{ + PraghaSonginfoPane *pane; + GlyrDatabase *cache_db; + glyr_struct *glyr_info; + + glyr_info = g_slice_new0 (glyr_struct); + + glyr_query_init (&glyr_info->query); + glyr_opt_type (&glyr_info->query, type); + + pane = pragha_songinfo_plugin_get_pane (plugin); + + switch (type) { + case GLYR_GET_ARTIST_BIO: + pragha_songinfo_pane_set_text (pane, artist, _("Searching..."), ""); + + glyr_opt_artist(&glyr_info->query, artist); + + glyr_opt_lang (&glyr_info->query, "auto"); + glyr_opt_lang_aware_only (&glyr_info->query, TRUE); + break; + case GLYR_GET_LYRICS: + pragha_songinfo_pane_set_text (pane, title, _("Searching..."), ""); + + glyr_opt_artist(&glyr_info->query, artist); + glyr_opt_title(&glyr_info->query, title); + break; + default: + break; + } + + cache_db = pragha_songinfo_plugin_get_cache (plugin); + + glyr_opt_lookup_db (&glyr_info->query, cache_db); + glyr_opt_db_autowrite (&glyr_info->query, TRUE); + + glyr_info->filename = g_strdup(filename); + glyr_info->plugin = plugin; + + GCancellable *cancellable = g_cancellable_new (); + glyr_info->cancellable = g_object_ref (cancellable); + glyr_info->cancel_id = g_cancellable_connect (glyr_info->cancellable, + G_CALLBACK (search_cancelled), + &glyr_info->query, + NULL); + + pragha_async_launch (get_related_info_idle_func, + glyr_finished_thread_update_pane, + glyr_info); + + return cancellable; +} + diff --git a/pool/shard006/C/0118531_stm32f0xx_hal_timebase_TIM.c b/pool/shard006/C/0118531_stm32f0xx_hal_timebase_TIM.c new file mode 100644 index 0000000000000000000000000000000000000000..ff2f8f3bab17b5b066b5fb597ab2c0c24576a231 --- /dev/null +++ b/pool/shard006/C/0118531_stm32f0xx_hal_timebase_TIM.c @@ -0,0 +1,143 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_timebase_TIM.c + * @brief HAL time base based on the hardware TIM. + ****************************************************************************** + * + * COPYRIGHT(c) 2016 STMicroelectronics + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" +#include "stm32f0xx_hal_tim.h" +/** @addtogroup STM32F7xx_HAL_Examples + * @{ + */ + +/** @addtogroup HAL_TimeBase + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +TIM_HandleTypeDef htim1; +uint32_t uwIncrementState = 0; +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief This function configures the TIM1 as a time base source. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). + * @param TickPriority: Tick interrupt priorty. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) +{ + RCC_ClkInitTypeDef clkconfig; + uint32_t uwTimclock = 0; + uint32_t uwPrescalerValue = 0; + uint32_t pFLatency; + + /*Configure the TIM1 IRQ priority */ + HAL_NVIC_SetPriority(TIM1_BRK_UP_TRG_COM_IRQn, TickPriority ,0); + + /* Enable the TIM1 global Interrupt */ + HAL_NVIC_EnableIRQ(TIM1_BRK_UP_TRG_COM_IRQn); + + /* Enable TIM1 clock */ + __HAL_RCC_TIM1_CLK_ENABLE(); + + /* Get clock configuration */ + HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); + + /* Compute TIM1 clock */ + uwTimclock = HAL_RCC_GetPCLK1Freq(); + + /* Compute the prescaler value to have TIM1 counter clock equal to 1MHz */ + uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1); + + /* Initialize TIM1 */ + htim1.Instance = TIM1; + + /* Initialize TIMx peripheral as follow: + + Period = [(TIM1CLK/1000) - 1]. to have a (1/1000) s time base. + + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + + ClockDivision = 0 + + Counter direction = Up + */ + htim1.Init.Period = (1000000 / 1000) - 1; + htim1.Init.Prescaler = uwPrescalerValue; + htim1.Init.ClockDivision = 0; + htim1.Init.CounterMode = TIM_COUNTERMODE_UP; + if(HAL_TIM_Base_Init(&htim1) == HAL_OK) + { + /* Start the TIM time Base generation in interrupt mode */ + return HAL_TIM_Base_Start_IT(&htim1); + } + + /* Return function status */ + return HAL_ERROR; +} + +/** + * @brief Suspend Tick increment. + * @note Disable the tick increment by disabling TIM1 update interrupt. + * @param None + * @retval None + */ +void HAL_SuspendTick(void) +{ + /* Disable TIM1 update Interrupt */ + __HAL_TIM_DISABLE_IT(&htim1, TIM_IT_UPDATE); +} + +/** + * @brief Resume Tick increment. + * @note Enable the tick increment by Enabling TIM1 update interrupt. + * @param None + * @retval None + */ +void HAL_ResumeTick(void) +{ + /* Enable TIM1 Update interrupt */ + __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE); +} + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0118532_ssa-dse-15.c b/pool/shard006/C/0118532_ssa-dse-15.c new file mode 100644 index 0000000000000000000000000000000000000000..cfddb30e4fa3398c262273f3ca5733a6413834fa --- /dev/null +++ b/pool/shard006/C/0118532_ssa-dse-15.c @@ -0,0 +1,24 @@ +/* { dg-do compile } */ +/* { dg-options "-O2 -fdump-tree-dse1-details" } */ + +void *foo (int *p) +{ + void *q; + /* We should be able to DSE this store (p may point to errno). */ + *p = 0; + q = __builtin_malloc (4); + *p = 0; + return q; +} + +int j; +void bar (int *i) +{ + /* This store is dead as well. */ + j = 1; + *i = 0; + j = 2; +} + +/* { dg-final { scan-tree-dump-times "Deleted dead store" 2 "dse1" } } */ +/* { dg-final { cleanup-tree-dump "dse1" } } */ diff --git a/pool/shard006/C/0118535_vorec.c b/pool/shard006/C/0118535_vorec.c new file mode 100644 index 0000000000000000000000000000000000000000..f1a0ef70d2c1a7f69873a5b1b33deb24e89aa2b4 --- /dev/null +++ b/pool/shard006/C/0118535_vorec.c @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "msm_audio.h" +#include "msm_audio_voicememo.h" + +#define VODEV "/dev/msm_voicememo" + + +int sw = 0; + +static void *vorec_main() +{ + int vfd, status, rfd; + unsigned char *buf; + struct msm_audio_voicememo_config cfg; + char amrname[64]; + char dirname[64]; + char filename[64]; + char wavefile[256]; + time_t ltime; + struct tm *tm; + char hdr[] = { 0x23, 0x21, 0x41, 0x4d, 0x52, 0x0a}; + + memset( &cfg, 0, sizeof(cfg)); + memset( amrname, 0, sizeof(amrname)); + memset( dirname, 0, sizeof(dirname)); + + vfd = open( VODEV, O_RDWR); + + ltime = time(NULL); + tm = localtime(<ime); + + sprintf( amrname, "/tmp/%u.amr", ltime); + + rfd = open(amrname, O_RDWR|O_CREAT); + + buf = (unsigned char *)calloc( 1, 32); + + cfg.rec_type = RPC_VOC_REC_BOTH; + cfg.rec_interval_ms = 00; + cfg.auto_stop_ms = 0; + cfg.capability = RPC_VOC_CAP_AMR; + cfg.max_rate = RPC_VOC_AMR_RATE_1220; + cfg.min_rate = RPC_VOC_AMR_RATE_1220; + cfg.frame_format = RPC_VOC_PB_AMR; + cfg.dtx_enable = 0; + cfg.data_req_ms = 20; + + status = ioctl( vfd, AUDIO_SET_VOICEMEMO_CONFIG, &cfg); + + status = ioctl( vfd, AUDIO_GET_VOICEMEMO_CONFIG, &cfg); + + status = ioctl( vfd, AUDIO_START, 0); + + status = 0; + write(rfd, hdr, sizeof(hdr)); + + while(sw) + { + memset(buf, 0, 32); + read( vfd, buf, 32); + write( rfd, buf, 32); + } + sprintf( dirname, "/media/internal/record/%4d-%02d-%02d", + tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday); + mkdir(dirname, 0); + snprintf( wavefile, sizeof(wavefile), "%s/%02d-%02d-%02d.wav", + dirname, tm->tm_hour, tm->tm_min, tm->tm_sec); + + free(buf); + close(rfd); + close(vfd); + + decodec(amrname, wavefile); + unlink(amrname); + + pthread_exit(NULL); +} + + +int rec_begin(void) +{ + pthread_t rec_pid; + fprintf( stdout, "record startd...\n"); + mkdir("/media/internal/record", 0); + + if(sw) + return 1; + + if( pthread_create( &rec_pid, NULL, vorec_main, NULL)) + { + fprintf( stderr, "create recorder threads fail...\n"); + return 0; + } + sw = 1; + return 1; +} + +int rec_stop(void) +{ + sw = 0; + fprintf( stdout, "recoder stoped..\n"); + + return 1; +} + +int rec_status(void) +{ + if(sw) + return 1; + return 0; +} diff --git a/pool/shard006/C/0118536_fs_rwops.c b/pool/shard006/C/0118536_fs_rwops.c new file mode 100644 index 0000000000000000000000000000000000000000..c3d49d7d167d7a46800f800d67fc3b611810ffda --- /dev/null +++ b/pool/shard006/C/0118536_fs_rwops.c @@ -0,0 +1,55 @@ +#include "fs_rwops.h" + +static int rwops_seek(SDL_RWops *ctx, int offset, int whence) +{ + fs_file fh = ctx->hidden.unknown.data1; + return fs_seek(fh, offset, whence) ? fs_tell(fh) : -1; +} + +static int rwops_read(SDL_RWops *ctx, void *ptr, int size, int maxnum) +{ + return fs_read(ptr, size, maxnum, ctx->hidden.unknown.data1); +} + +static int rwops_write(SDL_RWops *ctx, const void *ptr, int size, int num) +{ + return fs_write(ptr, size, num, ctx->hidden.unknown.data1); +} + +static int rwops_close(SDL_RWops *ctx) +{ + fs_file fh = ctx->hidden.unknown.data1; + + if (!fs_close(fh)) + return -1; + + SDL_FreeRW(ctx); + return 0; +} + +SDL_RWops *fs_rwops_make(fs_file fh) +{ + SDL_RWops *ctx; + + if ((ctx = SDL_AllocRW())) + { + ctx->seek = rwops_seek; + ctx->read = rwops_read; + ctx->write = rwops_write; + ctx->close = rwops_close; + + ctx->hidden.unknown.data1 = fh; + } + + return ctx; +} + +SDL_RWops *fs_rwops_open(const char *path, const char *mode) +{ + fs_file fh; + + if ((fh = fs_open(path, mode))) + return fs_rwops_make(fh); + + return NULL; +} diff --git a/pool/shard006/C/0118537_menu.c b/pool/shard006/C/0118537_menu.c new file mode 100644 index 0000000000000000000000000000000000000000..71b7dc91ccb3ac40e07ca92b356442693b41484d --- /dev/null +++ b/pool/shard006/C/0118537_menu.c @@ -0,0 +1,259 @@ +/*************************************************************************** + * Copyright (C) 2016 + * by Dimok + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any + * damages arising from the use of this software. + * + * Permission is granted to anyone to use this software for any + * purpose, including commercial applications, and to alter it and + * redistribute it freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you + * must not claim that you wrote the original software. If you use + * this software in a product, an acknowledgment in the product + * documentation would be appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and + * must not be misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source + * distribution. + ***************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include "dynamic_libs/os_functions.h" +#include "dynamic_libs/fs_functions.h" +#include "dynamic_libs/gx2_functions.h" +#include "dynamic_libs/sys_functions.h" +#include "dynamic_libs/vpad_functions.h" +#include "dynamic_libs/socket_functions.h" +#include "menu.h" + +#define MAX_CONFIG_SETTINGS_EXPERT 9 +#define MAX_CONFIG_SETTINGS_DEFAULT (MAX_CONFIG_SETTINGS_EXPERT - 3) + +#define TEXT_SEL(x, text1, text2) ((x) ? (text1) : (text2)) + +struct { + const char *option; + const char *enabled; + const char *disabled; +} selection_options[] = +{ + { "Config view mode", "expert", "default" }, + { "Skip this menu on launch", "on", "off" }, + { "Show launch image", "on", "off" }, + { "Don't relaunch OS", "on", "off" }, + { "Launch System Menu", "on", "off" }, + { "redNAND", "on", "off" }, + { "SEEPROM redirection", "on", "off" }, + { "OTP redirection", "on", "off" }, + { "Use syshax.xml (coldboothax)", "on", "off" }, +}; + +static void console_print_pos(int x, int y, const char *format, ...) +{ + char * tmp = NULL; + + va_list va; + va_start(va, format); + if((vasprintf(&tmp, format, va) >= 0) && tmp) + { + if(strlen(tmp) > 79) + tmp[79] = 0; + + OSScreenPutFontEx(0, x, y, tmp); + OSScreenPutFontEx(1, x, y, tmp); + + } + va_end(va); + + if(tmp) + free(tmp); +} + +int ShowMenu(cfw_config_t * currentConfig) +{ + // Init screen and screen buffers + OSScreenInit(); + u32 screen_buf0_size = OSScreenGetBufferSizeEx(0); + u32 screen_buf1_size = OSScreenGetBufferSizeEx(1); + u8 * screenBuffer = (u8*) memalign(0x100, screen_buf0_size + screen_buf1_size); + OSScreenSetBufferEx(0, (void *)screenBuffer); + OSScreenSetBufferEx(1, (void *)(screenBuffer + screen_buf0_size)); + + OSScreenEnableEx(0, 1); + OSScreenEnableEx(1, 1); + + // Clear screens + OSScreenClearBufferEx(0, 0); + OSScreenClearBufferEx(1, 0); + + // Flip buffers + OSScreenFlipBuffersEx(0); + OSScreenFlipBuffersEx(1); + + VPADData vpad; + int vpadError; + int x_offset = -2; + int initScreen = 1; + int selected = 0; + int launch = 0; + cfw_config_t config; + memcpy(&config, currentConfig, sizeof(cfw_config_t)); + + int max_config_item = config.viewMode ? MAX_CONFIG_SETTINGS_EXPERT : MAX_CONFIG_SETTINGS_DEFAULT; + + while(1) + { + //! update only at 50 Hz, thats more than enough + vpadError = -1; + VPADRead(0, &vpad, 1, &vpadError); + + if(vpadError == 0) + { + if(vpad.btns_d & VPAD_BUTTON_HOME) + { + break; + } + else if(vpad.btns_d & VPAD_BUTTON_A) + { + launch = 1; + break; + } + else if(vpad.btns_d & VPAD_BUTTON_DOWN) + { + selected++; + if(selected >= max_config_item) + selected = 0; + + initScreen = 1; + } + else if(vpad.btns_d & VPAD_BUTTON_UP) + { + selected--; + if(selected < 0) + selected = max_config_item - 1; + + initScreen = 1; + } + else if(vpad.btns_d & (VPAD_BUTTON_LEFT | VPAD_BUTTON_RIGHT)) + { + switch(selected) + { + case 0: + config.viewMode = !config.viewMode; + max_config_item = config.viewMode ? MAX_CONFIG_SETTINGS_EXPERT : MAX_CONFIG_SETTINGS_DEFAULT; + break; + case 1: + config.directLaunch = !config.directLaunch; + break; + case 2: + config.launchImage = !config.launchImage; + break; + case 3: + config.noIosReload = !config.noIosReload; + break; + case 4: + config.launchSysMenu = !config.launchSysMenu; + break; + case 5: + config.redNAND = !config.redNAND; + break; + case 6: + config.seeprom_red = !config.seeprom_red; + break; + case 7: + config.otp_red = !config.otp_red; + break; + case 8: + config.syshaxXml = !config.syshaxXml; + break; + default: + break; + } + + if(!config.viewMode) + { + config.syshaxXml = 0; + + if(config.redNAND) + { + config.seeprom_red = 1; + config.otp_red = 1; + } + } + if(config.noIosReload) + { + config.launchImage = 0; + config.redNAND = 0; + } + else + { + config.launchSysMenu = 1; + } + + if(config.redNAND == 0) + { + config.seeprom_red = 0; + config.otp_red = 0; + } + + initScreen = 1; + } + } + + if(initScreen) + { + OSScreenClearBufferEx(0, 0); + OSScreenClearBufferEx(1, 0); + + console_print_pos(x_offset, 1, " -- MOCHA CFW %s by Dimok --", APP_VERSION); + + console_print_pos(x_offset, 3, "Select your options and press A to launch."); + console_print_pos(x_offset, 4, "Press HOME to exit back to HBL."); + console_print_pos(x_offset, 5, "Hold B on start to force enter this menu"); + + int y_offset = 6; + int option_count = sizeof(selection_options) / sizeof(selection_options[0]); + int idx; + int * configPtr = &config.viewMode; + + for(idx = 0; idx < option_count && idx < max_config_item; idx++) + { + console_print_pos(x_offset, y_offset++, "%s %-29s : %s%s%s %s%s%s", TEXT_SEL((selected == idx), "--->", " "), selection_options[idx].option, + TEXT_SEL(configPtr[idx], "<", " "), selection_options[idx].enabled, TEXT_SEL(configPtr[idx], ">", " "), + TEXT_SEL(configPtr[idx], " ", "<"), selection_options[idx].disabled, TEXT_SEL(configPtr[idx], " ", ">")); + } + + console_print_pos(x_offset, 16, "Credits go to everyone who contributed to Wii U scene publicly."); + console_print_pos(x_offset, 17, "Special thanks to smealum, plutoo, yellows8, naehrwert and derrek."); + + // Flip buffers + OSScreenFlipBuffersEx(0); + OSScreenFlipBuffersEx(1); + + initScreen = 0; + } + + usleep(20000); + } + + OSScreenShutdown(); + free(screenBuffer); + + if(memcmp(currentConfig, &config, sizeof(cfw_config_t)) != 0) + { + memcpy(currentConfig, &config, sizeof(cfw_config_t)); + write_config(currentConfig); + } + + return launch; +} diff --git a/pool/shard006/C/0118538_ilatcurve.c b/pool/shard006/C/0118538_ilatcurve.c new file mode 100644 index 0000000000000000000000000000000000000000..52ccd0f88e80e7a6861e471c5db7349eed68e66e --- /dev/null +++ b/pool/shard006/C/0118538_ilatcurve.c @@ -0,0 +1,182 @@ +/* + * FILE NAME kernel/ilatcurve.c + * + * BRIEF MODULE DESCRIPTION + * This file implements a sample based interrupt latency curve for Linux. + * + * Author: David Singleton + * MontaVista Software, Inc. + * support@mvista.com + * + * Copyright 2001 MontaVista Software Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * 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., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_SMP +#include +#endif + +unsigned long bucketlog[BUCKETS]; +unsigned long maximum_off; +unsigned int ilatency_start; +unsigned int ilatency_stop; + +void __noinstrument inline interrupt_overhead_start() +{ + + readclock(ilatency_start); +} + +void __noinstrument inline interrupt_overhead_stop() +{ + readclock(ilatency_stop); +} + + +unsigned long total_ilat_samples; /* total number of samples collected */ + +asmlinkage void __noinstrument inthoff_logentry(unsigned diff) +{ + unsigned sampletime = diff; + sampletime /= BUCKET_SIZE; + if (maximum_off < diff) { + maximum_off = diff; + } + + if (sampletime < 0) { + bucketlog[0]++; + } else if (sampletime > LAST_BUCKET) { + bucketlog[LAST_BUCKET]++; + } else { + bucketlog[sampletime]++; + } + total_ilat_samples++; + return; +} + +/* + * Writing to /proc/maxoff resets the counters + */ +static ssize_t __noinstrument +ilatcurve_write_proc(struct file * file, const char * buf, size_t count, +loff_t *ppos) +{ + extern interrupt_latency_log_t latency; + + total_ilat_samples = 0; + memset(&bucketlog, 0, sizeof(unsigned long) * BUCKETS); + memset(&latency, 0, sizeof(interrupt_latency_log_t)); + latency.logging = ON; + return count; +} + +static int g_read_completed = 0; + +static int __noinstrument ilatcurve_read_proc( + char *page_buffer, + char **my_first_byte, + off_t virtual_start, + int length, + int *eof, + void *data) +{ + int my_buffer_offset = 0; + char * const my_base = page_buffer; + int i; + if (virtual_start == 0) { + /* + * Just been opened so display the header information + * also stop logging BUGBUG: stop logging while we are + * reading, initialize the index numbers in the log array + */ + unsigned int usecs; + g_read_completed = 0; + + usecs = clock_to_usecs(clock_diff(ilatency_start, ilatency_stop));; + + my_buffer_offset += sprintf(my_base+my_buffer_offset, + "#%lu samples logged\n#timer measured %u ticks per usec.\n" + "#interrupt overhead %u microseconds\n" + "#maximum interrupt off time %u microseconds\n" + "#usecs samples\n", total_ilat_samples, + (unsigned)ticks_per_usec, usecs, maximum_off); + } else if (g_read_completed == BUCKETS) { + *eof = 1; + /* BUGBUG: start logging again */ + return 0; + } + + /* dump the sample log on the screen */ + for (i = 0; i < (BUCKETS-1); i++) { + my_buffer_offset += sprintf(my_base + my_buffer_offset, + "%5u\t%8lu\n", (i + 1) * BUCKET_SIZE, bucketlog[i]); + g_read_completed++; + } + my_buffer_offset += sprintf(my_base + my_buffer_offset, + "%5u\t%8lu(greater than this time)\n", i * BUCKET_SIZE, + bucketlog[LAST_BUCKET]); + g_read_completed++; + + *my_first_byte = page_buffer; + return my_buffer_offset; +} + +int __noinstrument __init +ilatcurve_init(void) +{ + struct proc_dir_entry *entry; + + readclock_init(); +#ifndef CONFIG_PPC + ticks_per_usec = TICKS_PER_USEC; +#endif +#ifdef CONFIG_SMP + printk("Interrupt holdoff times are not supported on SMP systems.\n"); +#else + printk("Interrupt holdoff times measurement enabled at %u ticks per usec.\n", ticks_per_usec); + /* + * this is where each platform must turn the + * delta 'ticks' into microseconds. Each architecture + * does it differently. + */ +#ifdef CONFIG_PROC_FS + entry = create_proc_read_entry("ilatcurve", S_IWUSR | S_IRUGO, NULL, + ilatcurve_read_proc, 0); + if (entry) { + entry->write_proc = (write_proc_t *)ilatcurve_write_proc; + } + +#endif +#endif + return 0; +} + +__initcall(ilatcurve_init); + + diff --git a/pool/shard006/C/0118540_ev1527.c b/pool/shard006/C/0118540_ev1527.c new file mode 100644 index 0000000000000000000000000000000000000000..86cc9bfb06c497aa862ef1c431c116e5e4e66334 --- /dev/null +++ b/pool/shard006/C/0118540_ev1527.c @@ -0,0 +1,110 @@ +/* + Copyright (C) 2015 CurlyMo and Meloen + + This file is part of pilight. + + pilight 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. + + pilight 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 pilight. If not, see +*/ + +#include +#include +#include +#include + +#include "../../core/pilight.h" +#include "../../core/common.h" +#include "../../core/dso.h" +#include "../../core/log.h" +#include "../protocol.h" +#include "../../core/binary.h" +#include "../../core/gc.h" +#include "ev1527.h" + +#define PULSE_MULTIPLIER 5 +#define MIN_PULSE_LENGTH 251 +#define MAX_PULSE_LENGTH 311 +#define AVG_PULSE_LENGTH 256 +#define RAW_LENGTH 50 + +static int validate(void) { + if(ev1527->rawlen == RAW_LENGTH) { + if(ev1527->raw[ev1527->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && + ev1527->raw[ev1527->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { + return 0; + } + } + + return -1; +} + +static void createMessage(int unitcode, int state) { + ev1527->message = json_mkobject(); + json_append_member(ev1527->message, "unitcode", json_mknumber(unitcode, 0)); + if(state == 0) { + json_append_member(ev1527->message, "state", json_mkstring("opened")); + } else { + json_append_member(ev1527->message, "state", json_mkstring("closed")); + } +} + +static void parseCode(void) { + int binary[RAW_LENGTH/2], x = 0, i = 0; + + for(x=0;xrawlen-2;x+=2) { + if(ev1527->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { + binary[i++] = 1; + } else { + binary[i++] = 0; + } + } + + int unitcode = binToDec(binary, 0, 19); + int state = binary[20]; + createMessage(unitcode, state); +} + +#if !defined(MODULE) && !defined(_WIN32) +__attribute__((weak)) +#endif +void ev1527Init(void) { + + protocol_register(&ev1527); + protocol_set_id(ev1527, "ev1527"); + protocol_device_add(ev1527, "ev1527", "ev1527 contact sensor"); + ev1527->devtype = CONTACT; + ev1527->hwtype = RF433; + ev1527->minrawlen = RAW_LENGTH; + ev1527->maxrawlen = RAW_LENGTH; + ev1527->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; + ev1527->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; + + options_add(&ev1527->options, 'u', "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); + options_add(&ev1527->options, 't', "opened", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); + options_add(&ev1527->options, 'f', "closed", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); + + ev1527->parseCode=&parseCode; + ev1527->validate=&validate; +} + +#if !defined(MODULE) && !defined(_WIN32) +void compatibility(struct module_t *module) { + module->name = "ev1527"; + module->version = "1.0"; + module->reqversion = "6.0"; + module->reqcommit = "84"; +} + +void init(void) { + ev1527Init(); +} +#endif diff --git a/pool/shard006/C/0118541_audio.c b/pool/shard006/C/0118541_audio.c new file mode 100644 index 0000000000000000000000000000000000000000..1eddf552ce247944de99d1a89ff1faa46b752cdf --- /dev/null +++ b/pool/shard006/C/0118541_audio.c @@ -0,0 +1,15 @@ +#include + +#include "audio.h" + +int audio_init() { + int ret = Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 4096); + return ret; +} + +void audio_play(uint8_t *data) { + Mix_Chunk *chunk = Mix_QuickLoad_WAV(data); + int channel = Mix_PlayChannel(-1, chunk, 0); + Mix_FreeChunk(chunk); + chunk = NULL; +} \ No newline at end of file diff --git a/pool/shard006/C/0118542_erl_tracer_nif.c b/pool/shard006/C/0118542_erl_tracer_nif.c new file mode 100644 index 0000000000000000000000000000000000000000..65b54a3582fefe7fc7ee7b27567ef7e6d4fa6399 --- /dev/null +++ b/pool/shard006/C/0118542_erl_tracer_nif.c @@ -0,0 +1,257 @@ +/* + * %CopyrightBegin% + * + * Copyright Ericsson 2015-2016. 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% + */ + +/* + * Purpose: NIF library for process/port tracer + * + */ + + +#define STATIC_ERLANG_NIF 1 + +#include "erl_nif.h" +#include "config.h" +#include "sys.h" + +#ifdef VALGRIND +# include +#endif + +/* NIF interface declarations */ +static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info); +static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info); +static void unload(ErlNifEnv* env, void* priv_data); + +/* The NIFs: */ +static ERL_NIF_TERM enabled(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); +static ERL_NIF_TERM trace(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); + +static ErlNifFunc nif_funcs[] = { + {"enabled", 3, enabled}, + {"trace", 5, trace} +}; + + +ERL_NIF_INIT(erl_tracer, nif_funcs, load, NULL, upgrade, unload) + +#define ATOMS \ + ATOM_DECL(call); \ + ATOM_DECL(command); \ + ATOM_DECL(cpu_timestamp); \ + ATOM_DECL(discard); \ + ATOM_DECL(exception_from); \ + ATOM_DECL(extra); \ + ATOM_DECL(match_spec_result); \ + ATOM_DECL(monotonic); \ + ATOM_DECL(ok); \ + ATOM_DECL(remove); \ + ATOM_DECL(return_from); \ + ATOM_DECL(scheduler_id); \ + ATOM_DECL(send); \ + ATOM_DECL(send_to_non_existing_process); \ + ATOM_DECL(seq_trace); \ + ATOM_DECL(spawn); \ + ATOM_DECL(strict_monotonic); \ + ATOM_DECL(timestamp); \ + ATOM_DECL(trace); \ + ATOM_DECL(trace_status); \ + ATOM_DECL(trace_ts); \ + ATOM_DECL(true); \ + ATOM_DECL(gc_minor_start); \ + ATOM_DECL(gc_minor_end); \ + ATOM_DECL(gc_major_start); \ + ATOM_DECL(gc_major_end); + +#define ATOM_DECL(A) static ERL_NIF_TERM atom_##A +ATOMS +#undef ATOM_DECL + +static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) +{ + +#define ATOM_DECL(A) atom_##A = enif_make_atom(env, #A) +ATOMS +#undef ATOM_DECL + + *priv_data = NULL; + + return 0; +} + +static void unload(ErlNifEnv* env, void* priv_data) +{ + +} + +static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, + ERL_NIF_TERM load_info) +{ + if (*old_priv_data != NULL) { + return -1; /* Don't know how to do that */ + } + if (*priv_data != NULL) { + return -1; /* Don't know how to do that */ + } + if (load(env, priv_data, load_info)) { + return -1; + } + return 0; +} + +static ERL_NIF_TERM enabled(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) +{ + ErlNifPid to_pid; + ErlNifPort to_port; + ERL_NIF_TERM ret = enif_is_identical(argv[0], atom_trace_status) ? + atom_remove : atom_discard; + + ASSERT(argc == 3); + + if (enif_get_local_pid(env, argv[1], &to_pid)) { + if (!enif_is_process_alive(env, &to_pid)) + /* tracer is dead so we should remove this trace point */ + return ret; + } else if (enif_get_local_port(env, argv[1], &to_port)) { + if (!enif_is_port_alive(env, &to_port)) + /* tracer is dead so we should remove this trace point */ + return ret; + } else { + /* The state was not a pid or a port */ + return ret; + } + + /* Only generate trace for when tracer != tracee */ + if (enif_is_identical(argv[1], argv[2])) { + return atom_discard; + } + + return atom_trace; +} + +/* + -spec trace(seq_trace, TracerState :: pid() | port(), + Label :: non_neg_integer(), + Msg :: term(), + Opts :: map()) -> ignored(); + trace(Tag :: atom(), TracerState :: pid() | port(), + Tracee :: pid() || port() || undefined, + Msg :: term(), + Opts :: map()) -> ignored(). +*/ +static ERL_NIF_TERM trace(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) +{ + ERL_NIF_TERM value, msg, tt[8], opts; + ErlNifPid to_pid; + ErlNifPort to_port; + size_t tt_sz = 0; + int is_port = 0; + size_t opts_sz = 0; + ASSERT(argc == 5); + + if (!enif_get_local_pid(env, argv[1], &to_pid)) { + if (!enif_get_local_port(env, argv[1], &to_port)) { + /* This only fails if argv[1] is a not a local port/pid + which should not happen as it is checked in enabled */ + ASSERT(0); + return atom_ok; + } + is_port = 1; + } + + opts = argv[4]; + + if (!enif_get_map_size(env, opts, &opts_sz)) + opts_sz = 0; + + if (opts_sz && enif_get_map_value(env, opts, atom_extra, &value)) { + tt[tt_sz++] = atom_trace; + tt[tt_sz++] = argv[2]; + tt[tt_sz++] = argv[0]; + tt[tt_sz++] = argv[3]; + tt[tt_sz++] = value; + } else { + if (enif_is_identical(argv[0], atom_seq_trace)) { + tt[tt_sz++] = atom_seq_trace; + tt[tt_sz++] = argv[2]; + tt[tt_sz++] = argv[3]; + } else { + tt[tt_sz++] = atom_trace; + tt[tt_sz++] = argv[2]; + tt[tt_sz++] = argv[0]; + tt[tt_sz++] = argv[3]; + } + } + + + if (opts_sz && enif_get_map_value(env, opts, atom_match_spec_result, &value)) { + tt[tt_sz++] = value; + } + + if (opts_sz && enif_get_map_value(env, opts, atom_scheduler_id, &value)) { + tt[tt_sz++] = value; + } + + if (opts_sz && enif_get_map_value(env, opts, atom_timestamp, &value)) { + ERL_NIF_TERM ts; + if (enif_is_identical(value, atom_monotonic)) { + ErlNifTime mon = enif_monotonic_time(ERL_NIF_NSEC); + ts = enif_make_int64(env, mon); + } else if (enif_is_identical(value, atom_strict_monotonic)) { + ErlNifTime mon = enif_monotonic_time(ERL_NIF_NSEC); + ERL_NIF_TERM unique = enif_make_unique_integer( + env, ERL_NIF_UNIQUE_MONOTONIC); + ts = enif_make_tuple2(env, enif_make_int64(env, mon), unique); + } else if (enif_is_identical(value, atom_timestamp)) { + ts = enif_now_time(env); + } else if (enif_is_identical(value, atom_cpu_timestamp)) { + ts = enif_cpu_time(env); + } else { + ASSERT(0); + goto error; + } + tt[tt_sz++] = ts; + if (tt[0] == atom_trace) + tt[0] = atom_trace_ts; + } + + msg = enif_make_tuple_from_array(env, tt, tt_sz); + + if (is_port) { + ErlNifBinary bin; + + if (!enif_term_to_binary(env, msg, &bin)) + goto error; + + msg = enif_make_binary(env, &bin); + + (void) enif_port_command(env, &to_port, NULL, msg); + /* if failure: port has probably died, enabled will clean up */ + + enif_release_binary(&bin); + } else { + + (void) enif_send(env, &to_pid, NULL, msg); + /* if failure: process has probably died, enabled will clean up */ + } + +error: + + return atom_ok; +} diff --git a/pool/shard006/C/0118554_sxs_usrmem.c b/pool/shard006/C/0118554_sxs_usrmem.c new file mode 100644 index 0000000000000000000000000000000000000000..4f09d2663bd2dfbdf16116e78b268172c981c367 --- /dev/null +++ b/pool/shard006/C/0118554_sxs_usrmem.c @@ -0,0 +1,133 @@ +#include "sxr_ops.h" +#include "sxr_mem.hp" +#include "sxs_type.h" +#include "sxs_io.h" +#include "sxs_lib.h" +#include "sxs_rmt.h" +#include "sxr_cnf.h" +#include "sxp_debug.h" +#define __SXR_USRMEM_VAR__ +#include "sxr_usrmem.h" +#undef __SXR_USRMEM_VAR__ + +/* +=============================================================================== + Function : sxr_checkInUsrCluster + ---------------------------------------------------------------------------- + Scope : Check user cluster scope + Parameters : paddress, malloc address + Return : TRUE if address found in cluster +=============================================================================== +*/ +bool sxr_checkInUsrCluster (void *paddress) +{ + int32 vi=0; + for(vi=0;vi=sxr_UsrCluster [vi].Add && + paddress<(sxr_UsrCluster [vi].Add+(sxr_UsrCluster [vi].AlignSize*sxr_UsrCluster [vi].NbCluster)/sizeof(void) ) ) + { + return TRUE; + } + } + + return FALSE; +} + + + +/* +=============================================================================== + Function : sxr_NewUsrCluster + ---------------------------------------------------------------------------- + Scope : Cluster creation from a dedicated heap. + Parameters : Size, Cluster size + NbCluster, number of cluster + Idx, heap index + Return : none +=============================================================================== +*/ +void sxr_NewUsrCluster (u16 Size, u16 NbCluster, u8 Idx) +{ + + u32 i; + sxr_HMemHead_t *HBlock = NIL; + u16 AlignSize = ( (Size + 3 + 1 + 4 + sizeof (sxr_HMemHead_t)) & ~3 ); + + u32 Status = sxr_EnterSc (); + + if (sxr_NbUsrCluster >= SXR_NB_USER_CLUSTER) + SXS_RAISE ((_SXR|TABORT|TDB,TSTR("Too many clusters.\n",0x06bc0001))); + + u8 usrClusterIdx = sxr_NbUsrCluster; + sxr_NbUsrCluster++; + + sxr_ExitSc (Status); + +// FIXME The malloc getting memory for the cluster +// cast the size on 16 bits (We don't know why). +// Thus a cluster cannot be bigger than 64kB, taking +// headers into account. + if ((AlignSize * NbCluster) >= (1 << 16)) + SXS_RAISE ((_SXR|TABORT|TNB_ARG(2)|TDB,TSTR("Total cluster > 64 k Size %i Nb %i.\n",0x06bc0002), Size, NbCluster)); + + sxr_UsrCluster [usrClusterIdx].Size = Size; + sxr_UsrCluster [usrClusterIdx].AlignSize = AlignSize; + sxr_UsrCluster [usrClusterIdx].NbCluster = NbCluster; + sxr_UsrCluster [usrClusterIdx].Add = _sxr_HMalloc((u16) ( AlignSize * NbCluster), Idx); //sxr_HMalloc ((u16) ( AlignSize * NbCluster)); + sxr_UsrCluster [usrClusterIdx].FirstCluster = 0; + sxr_UsrCluster [usrClusterIdx].NbAllocation = 0; + + if ( sxr_UsrCluster [usrClusterIdx].Add == NIL ) + SXS_RAISE ((_SXR|TABORT|TDB,TSTR("Out of memory for cluster creation.\n",0x06bc0003))); + + memset ( (u8 *)sxr_UsrCluster [usrClusterIdx].Add, 0, ( AlignSize * NbCluster)); + + for ( i=0; iH. CallerAdd = SXR_POOL_FREE; + HBlock ->H. DSize = 0; + HBlock ->H. Link = 0; + HBlock ->H. Index = i; + HBlock ->H. Next = (i+1); + HBlock ->H. PIdx = usrClusterIdx; + sxr_SetCheckSum (&HBlock ->H. CheckSum); + + HBlock -> Size = 0; + + ((u8 *)sxr_UsrCluster [usrClusterIdx].Add) [(i+1)*AlignSize - 1] = SXR_MEM_PATTERN; + +#ifdef __SXR_DEBUG__ + memset (((u8 *)HBlock) + sizeof (sxr_HMemHead_t), SXR_MEM_PATTERN, Size); +#endif + } + + HBlock ->H. Next = NIL_IDX; + sxr_SetCheckSum (&HBlock ->H. CheckSum); +} + + +#ifdef __USER_CLUSTER_TEST_FUNC__ +U16 user_cluster_size[SXR_NB_USER_CLUSTER] = {0,}; +U16 user_cluster_firstcluster_max[SXR_NB_USER_CLUSTER] = {0,}; +U8 user_cluster_used_total =0; +void sxr_userCluster_check(void) +{ + U8 i = 0; + user_cluster_used_total = sxr_NbUsrCluster; + + for(;i +#include +#include + + +/* + * FreeBSD file AIO features and quirks: + * + * if an asked data are already in VM cache, then aio_error() returns 0, + * and the data are already copied in buffer; + * + * aio_read() preread in VM cache as minimum 16K (probably BKVASIZE); + * the first AIO preload may be up to 128K; + * + * aio_read/aio_error() may return EINPROGRESS for just written data; + * + * kqueue EVFILT_AIO filter is level triggered only: an event repeats + * until aio_return() will be called; + * + * aio_cancel() cannot cancel file AIO: it returns AIO_NOTCANCELED always. + */ + + +extern int ngx_kqueue; + + +static ssize_t ngx_file_aio_result(ngx_file_t *file, ngx_event_aio_t *aio, + ngx_event_t *ev); +static void ngx_file_aio_event_handler(ngx_event_t *ev); + + +ngx_int_t +ngx_file_aio_init(ngx_file_t *file, ngx_pool_t *pool) +{ + ngx_event_aio_t *aio; + + aio = ngx_pcalloc(pool, sizeof(ngx_event_aio_t)); + if (aio == NULL) { + return NGX_ERROR; + } + + aio->file = file; + aio->fd = file->fd; + aio->event.data = aio; + aio->event.ready = 1; + aio->event.log = file->log; + + file->aio = aio; + + return NGX_OK; +} + +/* + Õû¸öÍøÂçʼþµÄÇý¶¯»úÖÆ¾ÍÊÇÕâÑùͨ¹ýngx_eventfd֪ͨÃèÊö·ûºÍngx_epoll_eventfd +handler»Øµ÷·½·¨£¬²¢ÓëÎļþÒì²½I/Oʼþ½áºÏÆðÀ´µÄ¡£ + ÄÇô£¬ÔõÑùÏòÒì²½I/OÉÏÏÂÎÄÖÐÌá½»Òì²½I/O²Ù×÷ÄØ£¿¿´¿´ngx_linux_aio read.cÎļþÖÐ +µÄngx_file_aio_read·½·¨£¬ÔÚ´ò¿ªÎļþÒì²½I/Oºó£¬Õâ¸ö·½·¨½«»á¸ºÔð´ÅÅÌÎļþµÄ¶ÁÈ¡ +*/ + +/* +ngx_epoll_aio_init³õʼ»¯aioʼþÁÐ±í£¬ ngx_file_aio_readÌí¼Ó¶ÁÎļþʼþ£¬µ±¶ÁÈ¡Íê±Ïºóepoll»á´¥·¢ +ngx_epoll_eventfd_handler->ngx_file_aio_event_handler +nginx file aioÖ»ÌṩÁËread½Ó¿Ú£¬²»Ìṩwrite½Ó¿Ú£¬ÒòΪÒì²½aioÖ»´Ó´ÅÅ̶ÁºÍд£¬¶ø·Çaio·½Ê½Ò»°ãд»áÂäµ½ +´ÅÅÌ»º´æ£¬ËùÒÔ²»Ìṩ¸Ã½Ó¿Ú£¬Èç¹ûÒì²½ioд¿ÉÄÜ»á¸üÂý +*/ +ssize_t +ngx_file_aio_read(ngx_file_t *file, u_char *buf, size_t size, off_t offset, + ngx_pool_t *pool) +{ + int n; + ngx_event_t *ev; + ngx_event_aio_t *aio; + + if (!ngx_file_aio) { + return ngx_read_file(file, buf, size, offset); + } + + if (file->aio == NULL && ngx_file_aio_init(file, pool) != NGX_OK) { + return NGX_ERROR; + } + + aio = file->aio; + ev = &aio->event; + + if (!ev->ready) { + ngx_log_error(NGX_LOG_ALERT, file->log, 0, + "second aio post for \"%V\"", &file->name); + return NGX_AGAIN; + } + + ngx_log_debug4(NGX_LOG_DEBUG_CORE, file->log, 0, + "aio complete:%d @%O:%z %V", + ev->complete, offset, size, &file->name); + + if (ev->complete) { + ev->complete = 0; + ngx_set_errno(aio->err); + + if (aio->err == 0) { + return aio->nbytes; + } + + ngx_log_error(NGX_LOG_CRIT, file->log, ngx_errno, + "aio read \"%s\" failed", file->name.data); + + return NGX_ERROR; + } + + ngx_memzero(&aio->aiocb, sizeof(struct aiocb)); + + aio->aiocb.aio_fildes = file->fd; + aio->aiocb.aio_offset = offset; + aio->aiocb.aio_buf = buf; + aio->aiocb.aio_nbytes = size; +#if (NGX_HAVE_KQUEUE) + aio->aiocb.aio_sigevent.sigev_notify_kqueue = ngx_kqueue; + aio->aiocb.aio_sigevent.sigev_notify = SIGEV_KEVENT; + aio->aiocb.aio_sigevent.sigev_value.sigval_ptr = ev; +#endif + ev->handler = ngx_file_aio_event_handler; + + n = aio_read(&aio->aiocb); + + if (n == -1) { + n = ngx_errno; + + if (n == NGX_EAGAIN) { + return ngx_read_file(file, buf, size, offset); + } + + ngx_log_error(NGX_LOG_CRIT, file->log, n, + "aio_read(\"%V\") failed", &file->name); + + if (n == NGX_ENOSYS) { + ngx_file_aio = 0; + return ngx_read_file(file, buf, size, offset); + } + + return NGX_ERROR; + } + + ngx_log_debug2(NGX_LOG_DEBUG_CORE, file->log, 0, + "aio_read: fd:%d %d", file->fd, n); + + ev->active = 1; + ev->ready = 0; + ev->complete = 0; + + return ngx_file_aio_result(aio->file, aio, ev); +} + +static ssize_t +ngx_file_aio_result(ngx_file_t *file, ngx_event_aio_t *aio, ngx_event_t *ev) +{ + int n; + ngx_err_t err; + + n = aio_error(&aio->aiocb); + + ngx_log_debug2(NGX_LOG_DEBUG_CORE, file->log, 0, + "aio_error: fd:%d %d", file->fd, n); + + if (n == -1) { + err = ngx_errno; + aio->err = err; + + ngx_log_error(NGX_LOG_ALERT, file->log, err, + "aio_error(\"%V\") failed", &file->name); + return NGX_ERROR; + } + + if (n == NGX_EINPROGRESS) { + if (ev->ready) { + ev->ready = 0; + ngx_log_error(NGX_LOG_ALERT, file->log, n, + "aio_read(\"%V\") still in progress", + &file->name); + } + + return NGX_AGAIN; + } + + n = aio_return(&aio->aiocb); + + if (n == -1) { + err = ngx_errno; + aio->err = err; + ev->ready = 1; + + ngx_log_error(NGX_LOG_CRIT, file->log, err, + "aio_return(\"%V\") failed", &file->name); + return NGX_ERROR; + } + + aio->err = 0; + aio->nbytes = n; + ev->ready = 1; + ev->active = 0; + + ngx_log_debug2(NGX_LOG_DEBUG_CORE, file->log, 0, + "aio_return: fd:%d %d", file->fd, n); + + return n; +} + + +/* +ngx_epoll_aio_init³õʼ»¯aioʼþÁÐ±í£¬ ngx_file_aio_readÌí¼Ó¶ÁÎļþʼþ£¬µ±¶ÁÈ¡Íê±Ïºóepoll»á´¥·¢ +ngx_epoll_eventfd_handler->ngx_file_aio_event_handler +nginx file aioÖ»ÌṩÁËread½Ó¿Ú£¬²»Ìṩwrite½Ó¿Ú£¬ÒòΪÒì²½aioÖ»´Ó´ÅÅ̶ÁºÍд£¬¶ø·Çaio·½Ê½Ò»°ãд»áÂäµ½ +´ÅÅÌ»º´æ£¬ËùÒÔ²»Ìṩ¸Ã½Ó¿Ú£¬Èç¹ûÒì²½ioд¿ÉÄÜ»á¸üÂý +*/ +static void +ngx_file_aio_event_handler(ngx_event_t *ev) +{ + ngx_event_aio_t *aio; + + aio = ev->data; + + ngx_log_debug2(NGX_LOG_DEBUG_CORE, ev->log, 0, + "aio event handler fd:%d %V", aio->fd, &aio->file->name); + + if (ngx_file_aio_result(aio->file, aio, ev) != NGX_AGAIN) { + aio->handler(ev); + } +} diff --git a/pool/shard006/C/0118564_str_tempdescf.c b/pool/shard006/C/0118564_str_tempdescf.c new file mode 100644 index 0000000000000000000000000000000000000000..a17a607b3d4d857ea589b86693d18f444ec589a5 --- /dev/null +++ b/pool/shard006/C/0118564_str_tempdescf.c @@ -0,0 +1,36 @@ +/* temp string descriptor allocation for fixed-len strings */ + +#include "fb.h" + +/*:::::*/ +FBCALL FBSTRING *fb_StrAllocTempDescF( char *str, int str_size ) +{ + FBSTRING *dsc; + + FB_STRLOCK(); + + /* alloc a temporary descriptor */ + dsc = fb_hStrAllocTmpDesc( ); + + FB_STRUNLOCK(); + + if( dsc == NULL ) + return &__fb_ctx.null_desc; + + dsc->data = str; + + /* can't use strlen() if the size is known */ + if( str_size != 0 ) + dsc->len = str_size - 1; /* less the null-term */ + else + { + if( str != NULL ) + dsc->len = strlen( str ); + else + dsc->len = 0; + } + + dsc->size = dsc->len; + + return dsc; +} diff --git a/pool/shard006/C/0118569_atlas_int.c b/pool/shard006/C/0118569_atlas_int.c new file mode 100644 index 0000000000000000000000000000000000000000..79c2aa33d15940230a45692120a4f4dfa66f4509 --- /dev/null +++ b/pool/shard006/C/0118569_atlas_int.c @@ -0,0 +1,151 @@ +/* + * Carsten Langgaard, carstenl@mips.com + * Copyright (C) 1999,2000 MIPS Technologies, Inc. All rights reserved. + * + * ######################################################################## + * + * This program is free software; you can distribute it and/or modify it + * under the terms of the GNU General Public License (Version 2) as + * published by the Free Software Foundation. + * + * This program is distributed in the hope 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. + * + * ######################################################################## + * + * Routines for generic manipulation of the interrupts found on the MIPS + * Atlas board. + * + */ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +struct atlas_ictrl_regs *atlas_hw0_icregs + = (struct atlas_ictrl_regs *)ATLAS_ICTRL_REGS_BASE; + +extern asmlinkage void mipsIRQ(void); + +#if 0 +#define DEBUG_INT(x...) printk(x) +#else +#define DEBUG_INT(x...) +#endif + +void disable_atlas_irq(unsigned int irq_nr) +{ + atlas_hw0_icregs->intrsten = (1 << irq_nr); +} + +void enable_atlas_irq(unsigned int irq_nr) +{ + atlas_hw0_icregs->intseten = (1 << irq_nr); +} + +static unsigned int startup_atlas_irq(unsigned int irq) +{ + enable_atlas_irq(irq); + return 0; /* never anything pending */ +} + +#define shutdown_atlas_irq disable_atlas_irq + +#define mask_and_ack_atlas_irq disable_atlas_irq + +static void end_atlas_irq(unsigned int irq) +{ + if (!(irq_desc[irq].status & (IRQ_DISABLED|IRQ_INPROGRESS))) + enable_atlas_irq(irq); +} + +static struct hw_interrupt_type atlas_irq_type = { + "Atlas", + startup_atlas_irq, + shutdown_atlas_irq, + enable_atlas_irq, + disable_atlas_irq, + mask_and_ack_atlas_irq, + end_atlas_irq, + NULL +}; + +static inline int ls1bit32(unsigned int x) +{ + int b = 31, s; + + s = 16; if (x << 16 == 0) s = 0; b -= s; x <<= s; + s = 8; if (x << 8 == 0) s = 0; b -= s; x <<= s; + s = 4; if (x << 4 == 0) s = 0; b -= s; x <<= s; + s = 2; if (x << 2 == 0) s = 0; b -= s; x <<= s; + s = 1; if (x << 1 == 0) s = 0; b -= s; + + return b; +} + +void atlas_hw0_irqdispatch(struct pt_regs *regs) +{ + unsigned long int_status; + int irq; + + int_status = atlas_hw0_icregs->intstatus; + + /* if int_status == 0, then the interrupt has already been cleared */ + if (unlikely(int_status == 0)) + return; + + irq = ls1bit32(int_status); + + DEBUG_INT("atlas_hw0_irqdispatch: irq=%d\n", irq); + + do_IRQ(irq, regs); +} + +#ifdef CONFIG_KGDB +extern void breakpoint(void); +extern int remote_debug; +#endif + +void __init init_IRQ(void) +{ + int i; + + /* + * Mask out all interrupt by writing "1" to all bit position in + * the interrupt reset reg. + */ + atlas_hw0_icregs->intrsten = 0xffffffff; + + /* Now safe to set the exception vector. */ + set_except_vector(0, mipsIRQ); + + for (i = 0; i <= ATLASINT_END; i++) { + irq_desc[i].status = IRQ_DISABLED; + irq_desc[i].action = 0; + irq_desc[i].depth = 1; + irq_desc[i].handler = &atlas_irq_type; + spin_lock_init(&irq_desc[i].lock); + } + +#ifdef CONFIG_KGDB + if (remote_debug) { + set_debug_traps(); + breakpoint(); + } +#endif +} diff --git a/pool/shard006/C/0118571_lsmod.c b/pool/shard006/C/0118571_lsmod.c new file mode 100644 index 0000000000000000000000000000000000000000..a8b70cafa50f0dea7b589310fe6b36fc4b5437f1 --- /dev/null +++ b/pool/shard006/C/0118571_lsmod.c @@ -0,0 +1,116 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini lsmod implementation for busybox + * + * Copyright (C) 1999-2004 by Erik Andersen + * Copyright (C) 2008 by Vladimir Dronnikov + * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ + +//applet:IF_LSMOD(APPLET(lsmod, BB_DIR_SBIN, BB_SUID_DROP)) + +//usage:#if !ENABLE_MODPROBE_SMALL +//usage:#define lsmod_trivial_usage +//usage: "" +//usage:#define lsmod_full_usage "\n\n" +//usage: "List the currently loaded kernel modules" +//usage:#endif + +#include "libbb.h" +#include "unicode.h" + +#if ENABLE_FEATURE_CHECK_TAINTED_MODULE +//enum { +// TAINT_PROPRIETORY_MODULE = (1 << 0), +// TAINT_FORCED_MODULE = (1 << 1), +// TAINT_UNSAFE_SMP = (1 << 2), +//}; + +#define TAINT_PROPRIETORY_MODULE (1 << 0) +#define TAINT_FORCED_MODULE (1 << 1) +#define TAINT_UNSAFE_SMP (1 << 2) + +static void check_tainted(void) +{ + int tainted = 0; + char *buf = xmalloc_open_read_close("/proc/sys/kernel/tainted", NULL); + if (buf) { + tainted = atoi(buf); + if (ENABLE_FEATURE_CLEAN_UP) + free(buf); + } + + if (tainted) { + printf(" Tainted: %c%c%c\n", + tainted & TAINT_PROPRIETORY_MODULE ? 'P' : 'G', + tainted & TAINT_FORCED_MODULE ? 'F' : ' ', + tainted & TAINT_UNSAFE_SMP ? 'S' : ' '); + } else { + puts(" Not tainted"); + } +} +#else +static void check_tainted(void) { putchar('\n'); } +#endif + +int lsmod_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int lsmod_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM) +{ +#if ENABLE_FEATURE_LSMOD_PRETTY_2_6_OUTPUT + char *token[4]; + parser_t *parser = config_open("/proc/modules"); + init_unicode(); + + printf("%-24sSize Used by", "Module"); + check_tainted(); + + if (ENABLE_FEATURE_2_4_MODULES + && get_linux_version_code() < KERNEL_VERSION(2,6,0) + ) { + while (config_read(parser, token, 4, 3, "# \t", PARSE_NORMAL)) { + if (token[3] != NULL && token[3][0] == '[') { + token[3]++; + token[3][strlen(token[3])-1] = '\0'; + } else + token[3] = (char *) ""; +# if ENABLE_UNICODE_SUPPORT + { + uni_stat_t uni_stat; + char *uni_name = unicode_conv_to_printable(&uni_stat, token[0]); + unsigned pad_len = (uni_stat.unicode_width > 19) ? 0 : 19 - uni_stat.unicode_width; + printf("%s%*s %8s %2s %s\n", uni_name, pad_len, "", token[1], token[2], token[3]); + free(uni_name); + } +# else + printf("%-19s %8s %2s %s\n", token[0], token[1], token[2], token[3]); +# endif + } + } else { + while (config_read(parser, token, 4, 4, "# \t", PARSE_NORMAL & ~PARSE_GREEDY)) { + // N.B. token[3] is either '-' (module is not used by others) + // or comma-separated list ended by comma + // so trimming the trailing char is just what we need! + if (token[3][0]) + token[3][strlen(token[3]) - 1] = '\0'; +# if ENABLE_UNICODE_SUPPORT + { + uni_stat_t uni_stat; + char *uni_name = unicode_conv_to_printable(&uni_stat, token[0]); + unsigned pad_len = (uni_stat.unicode_width > 19) ? 0 : 19 - uni_stat.unicode_width; + printf("%s%*s %8s %2s %s\n", uni_name, pad_len, "", token[1], token[2], token[3]); + free(uni_name); + } +# else + printf("%-19s %8s %2s %s\n", token[0], token[1], token[2], token[3]); +# endif + } + } + if (ENABLE_FEATURE_CLEAN_UP) + config_close(parser); +#else + check_tainted(); + xprint_and_close_file(xfopen_for_read("/proc/modules")); +#endif + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C/0118575_layer3.c b/pool/shard006/C/0118575_layer3.c new file mode 100644 index 0000000000000000000000000000000000000000..8b0d5070d939696eafdb0d5559a9fe68d23ffcef --- /dev/null +++ b/pool/shard006/C/0118575_layer3.c @@ -0,0 +1,75 @@ +/* + * layer3.c + * + * Created on: Jan 31, 2014 + * Author: nathan + * + * PROTOCOL: [DATA CHUNKS]... [SHORT DATA CHUNK] + * Writes data as a series of length 16 chunks followed by a length 0-15 chunk + * + */ + +#include +#include "layers.h" + +static inline int min(int a, int b) { return a < b ? a : b; } + +int layer3_write(char* msg, int len) +{ + INIT_ERROR(); + + //Total number on unwritten bytes + int bytes_remaining = len; + + //ptr to the next chunk + char* msg_seek = msg; + + //Keep sending chunks until a short one is sent + int bytes_to_write; + do + { + //How many bytes in this chunk + bytes_to_write = min(MAX_CHUNK_SIZE, bytes_remaining); + + //Write the chunk + CHECK_LAYER_ERROR(layer2_write(msg_seek, bytes_to_write)); + + //Update counters + msg_seek += bytes_to_write; + bytes_remaining -= bytes_to_write; + } while(bytes_to_write == MAX_CHUNK_SIZE); + + return len; +} + +int layer3_read(char* msg, int max) +{ + INIT_ERROR(); + + //Total number of bytes before we go over max + int bytes_remaining = max; + + //ptr to where the next chunk will be written + char* msg_seek = msg; + + /* + * Note: an old implementation of layer3_read used buffering to read the + * whole message, even if max was too small. Decided to not bother. + */ + + //Keep reading until a short chunk is read + int bytes_read; + do + { + //Read the chunk into the client array + //If the size of the chunk is < bytes_remaining, permafail. + CHECK_LAYER_ERROR(bytes_read = layer2_read(msg_seek, bytes_remaining)); + + //Update counters + msg_seek += bytes_read; + bytes_remaining -= bytes_read; + } while(bytes_read == MAX_CHUNK_SIZE); + + //Compute length based on how far msg_seek moved + return msg_seek - msg; +} diff --git a/pool/shard006/C/0118578_function.c b/pool/shard006/C/0118578_function.c new file mode 100644 index 0000000000000000000000000000000000000000..92fe37aa51593dae07a3064bd9ddfc8fc964a732 --- /dev/null +++ b/pool/shard006/C/0118578_function.c @@ -0,0 +1,79 @@ +/* + ============================================================================ + Name : Assignmet4.c + Author : Luca Zelioli and Minna + Description : Program that print out information about the student + ============================================================================ + */ + +#include + +/*simple print array */ +void printArray(int * array, int arraySize) +{ + + printf("I will print the array elements its index and its memory position\n\n"); + + for(int i=0; i< arraySize; i++) + { + printf("The value of\t [%d] position\t is %d\t and the memory location is %p\n",i, array[i], &array[i]); + } + + +} + +void secondTask() +{ + printf("\nThis is the second task:\n"); + + char *pointer = NULL; + + + char name[] = "luca&Minna"; + + + + int size = sizeof(name)/sizeof(name[0]); + + char *pointerArray[size]; + + for(int i=0; i + +#include +#include +#include +#include +#include +#include +#include + +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/support/spinlock.h" + +#define MAX_DEPTH 2 + +typedef struct { + gpr_mu mu; + gpr_cv cv; + grpc_closure_list elems; + size_t depth; + bool shutdown; + gpr_thd_id id; +} thread_state; + +static thread_state *g_thread_state; +static size_t g_max_threads; +static gpr_atm g_cur_threads; +static gpr_spinlock g_adding_thread_lock = GPR_SPINLOCK_STATIC_INITIALIZER; + +GPR_TLS_DECL(g_this_thread_state); + +static void executor_thread(void *arg); + +static size_t run_closures(grpc_exec_ctx *exec_ctx, grpc_closure_list list) { + size_t n = 0; + + grpc_closure *c = list.head; + while (c != NULL) { + grpc_closure *next = c->next_data.next; + grpc_error *error = c->error_data.error; +#ifdef GRPC_CLOSURE_RICH_DEBUG + c->scheduled = false; +#endif + c->cb(exec_ctx, c->cb_arg, error); + GRPC_ERROR_UNREF(error); + c = next; + n++; + } + + return n; +} + +bool grpc_executor_is_threaded() { + return gpr_atm_no_barrier_load(&g_cur_threads) > 0; +} + +void grpc_executor_set_threading(grpc_exec_ctx *exec_ctx, bool threading) { + gpr_atm cur_threads = gpr_atm_no_barrier_load(&g_cur_threads); + if (threading) { + if (cur_threads > 0) return; + g_max_threads = GPR_MAX(1, 2 * gpr_cpu_num_cores()); + gpr_atm_no_barrier_store(&g_cur_threads, 1); + gpr_tls_init(&g_this_thread_state); + g_thread_state = gpr_zalloc(sizeof(thread_state) * g_max_threads); + for (size_t i = 0; i < g_max_threads; i++) { + gpr_mu_init(&g_thread_state[i].mu); + gpr_cv_init(&g_thread_state[i].cv); + g_thread_state[i].elems = (grpc_closure_list)GRPC_CLOSURE_LIST_INIT; + } + + gpr_thd_options opt = gpr_thd_options_default(); + gpr_thd_options_set_joinable(&opt); + gpr_thd_new(&g_thread_state[0].id, executor_thread, &g_thread_state[0], + &opt); + } else { + if (cur_threads == 0) return; + for (size_t i = 0; i < g_max_threads; i++) { + gpr_mu_lock(&g_thread_state[i].mu); + g_thread_state[i].shutdown = true; + gpr_cv_signal(&g_thread_state[i].cv); + gpr_mu_unlock(&g_thread_state[i].mu); + } + /* ensure no thread is adding a new thread... once this is past, then + no thread will try to add a new one either (since shutdown is true) */ + gpr_spinlock_lock(&g_adding_thread_lock); + gpr_spinlock_unlock(&g_adding_thread_lock); + for (gpr_atm i = 0; i < g_cur_threads; i++) { + gpr_thd_join(g_thread_state[i].id); + } + gpr_atm_no_barrier_store(&g_cur_threads, 0); + for (size_t i = 0; i < g_max_threads; i++) { + gpr_mu_destroy(&g_thread_state[i].mu); + gpr_cv_destroy(&g_thread_state[i].cv); + run_closures(exec_ctx, g_thread_state[i].elems); + } + gpr_free(g_thread_state); + gpr_tls_destroy(&g_this_thread_state); + } +} + +void grpc_executor_init(grpc_exec_ctx *exec_ctx) { + gpr_atm_no_barrier_store(&g_cur_threads, 0); + grpc_executor_set_threading(exec_ctx, true); +} + +void grpc_executor_shutdown(grpc_exec_ctx *exec_ctx) { + grpc_executor_set_threading(exec_ctx, false); +} + +static void executor_thread(void *arg) { + thread_state *ts = arg; + gpr_tls_set(&g_this_thread_state, (intptr_t)ts); + + grpc_exec_ctx exec_ctx = + GRPC_EXEC_CTX_INITIALIZER(0, grpc_never_ready_to_finish, NULL); + + size_t subtract_depth = 0; + for (;;) { + gpr_mu_lock(&ts->mu); + ts->depth -= subtract_depth; + while (grpc_closure_list_empty(ts->elems) && !ts->shutdown) { + gpr_cv_wait(&ts->cv, &ts->mu, gpr_inf_future(GPR_CLOCK_REALTIME)); + } + if (ts->shutdown) { + gpr_mu_unlock(&ts->mu); + break; + } + grpc_closure_list exec = ts->elems; + ts->elems = (grpc_closure_list)GRPC_CLOSURE_LIST_INIT; + gpr_mu_unlock(&ts->mu); + + subtract_depth = run_closures(&exec_ctx, exec); + grpc_exec_ctx_flush(&exec_ctx); + } + grpc_exec_ctx_finish(&exec_ctx); +} + +static void executor_push(grpc_exec_ctx *exec_ctx, grpc_closure *closure, + grpc_error *error) { + size_t cur_thread_count = (size_t)gpr_atm_no_barrier_load(&g_cur_threads); + if (cur_thread_count == 0) { + grpc_closure_list_append(&exec_ctx->closure_list, closure, error); + return; + } + thread_state *ts = (thread_state *)gpr_tls_get(&g_this_thread_state); + if (ts == NULL) { + ts = &g_thread_state[GPR_HASH_POINTER(exec_ctx, cur_thread_count)]; + } + gpr_mu_lock(&ts->mu); + if (grpc_closure_list_empty(ts->elems)) { + gpr_cv_signal(&ts->cv); + } + grpc_closure_list_append(&ts->elems, closure, error); + ts->depth++; + bool try_new_thread = ts->depth > MAX_DEPTH && + cur_thread_count < g_max_threads && !ts->shutdown; + gpr_mu_unlock(&ts->mu); + if (try_new_thread && gpr_spinlock_trylock(&g_adding_thread_lock)) { + cur_thread_count = (size_t)gpr_atm_no_barrier_load(&g_cur_threads); + if (cur_thread_count < g_max_threads) { + gpr_atm_no_barrier_store(&g_cur_threads, cur_thread_count + 1); + + gpr_thd_options opt = gpr_thd_options_default(); + gpr_thd_options_set_joinable(&opt); + gpr_thd_new(&g_thread_state[cur_thread_count].id, executor_thread, + &g_thread_state[cur_thread_count], &opt); + } + gpr_spinlock_unlock(&g_adding_thread_lock); + } +} + +static const grpc_closure_scheduler_vtable executor_vtable = { + executor_push, executor_push, "executor"}; +static grpc_closure_scheduler executor_scheduler = {&executor_vtable}; +grpc_closure_scheduler *grpc_executor_scheduler = &executor_scheduler; diff --git a/pool/shard006/C/0118582_mkfifo.c b/pool/shard006/C/0118582_mkfifo.c new file mode 100644 index 0000000000000000000000000000000000000000..45d16cd4cc47fba13f3b49c8ecb614876ffa6b7c --- /dev/null +++ b/pool/shard006/C/0118582_mkfifo.c @@ -0,0 +1,58 @@ +/* Create a named fifo. + Copyright (C) 2009-2013 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* written by Eric Blake */ + +#include + +#include + +#include +#include + +#if !HAVE_MKFIFO +/* Mingw lacks mkfifo; always fail with ENOSYS. */ + +int +mkfifo (char const *name _GL_UNUSED, mode_t mode _GL_UNUSED) +{ + errno = ENOSYS; + return -1; +} + +#else /* HAVE_MKFIFO */ + +# undef mkfifo + +/* Create a named fifo FILE, with access permissions in MODE. Work +around trailing slash bugs. */ + +int +rpl_mkfifo (char const *name, mode_t mode) +{ +# if MKFIFO_TRAILING_SLASH_BUG + size_t len = strlen (name); + if (len && name[len - 1] == '/') + { + struct stat st; + if (stat (name, &st) == 0) + errno = EEXIST; + return -1; + } +# endif + return mkfifo (name, mode); +} +#endif /* HAVE_MKFIFO */ diff --git a/pool/shard006/C/0118584_auth_none.c b/pool/shard006/C/0118584_auth_none.c new file mode 100644 index 0000000000000000000000000000000000000000..f2d72fd3d0d56c26042d93cbf720e86727b44a06 --- /dev/null +++ b/pool/shard006/C/0118584_auth_none.c @@ -0,0 +1,134 @@ +/* @(#)auth_none.c 1.1 87/11/04 3.9 RPCSRC */ +/* + * Sun RPC is a product of Sun Microsystems, Inc. and is provided for + * unrestricted use provided that this legend is included on all tape + * media and as a part of the software program in whole or part. Users + * may copy or modify Sun RPC without charge, but are not authorized + * to license or distribute it to anyone else except as part of a product or + * program developed by the user. + * + * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE + * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR + * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. + * + * Sun RPC is provided with no support and without any obligation on the + * part of Sun Microsystems, Inc. to assist in its use, correction, + * modification or enhancement. + * + * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE + * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC + * OR ANY PART THEREOF. + * + * In no event will Sun Microsystems, Inc. be liable for any lost revenue + * or profits or other special, indirect and consequential damages, even if + * Sun has been advised of the possibility of such damages. + * + * Sun Microsystems, Inc. + * 2550 Garcia Avenue + * Mountain View, California 94043 + */ +#if !defined(lint) && defined(SCCSIDS) +static char sccsid[] = "@(#)auth_none.c 1.19 87/08/11 Copyr 1984 Sun Micro"; +#endif + +/* + * auth_none.c + * Creates a client authentication handle for passing "null" + * credentials and verifiers to remote systems. + * + * Copyright (C) 1984, Sun Microsystems, Inc. + */ + +#include +#include +#include +#define MAX_MARSHEL_SIZE 20 + +/* + * Authenticator operations routines + */ +static void authnone_verf(); +static void authnone_destroy(); +static bool_t authnone_marshal(); +static bool_t authnone_validate(); +static bool_t authnone_refresh(); +extern bool_t xdr_opaque_auth( XDR * xdrs, struct opaque_auth * ap ); + +static struct auth_ops ops = { + authnone_verf, + authnone_marshal, + authnone_validate, + authnone_refresh, + authnone_destroy +}; + +static struct authnone_private { + AUTH no_client; + char marshalled_client[MAX_MARSHEL_SIZE]; + u_int mcnt; +} *authnone_private; + +AUTH * +authnone_create() +{ + register struct authnone_private *ap = authnone_private; + XDR xdr_stream; + register XDR *xdrs; + + if (ap == 0) { + ap = (struct authnone_private *)calloc(1, sizeof (*ap)); + if (ap == 0) + return (0); + authnone_private = ap; + } + if (!ap->mcnt) { + ap->no_client.ah_cred = ap->no_client.ah_verf = _null_auth; + ap->no_client.ah_ops = &ops; + xdrs = &xdr_stream; + xdrmem_create(xdrs, ap->marshalled_client, (u_int)MAX_MARSHEL_SIZE, + XDR_ENCODE); + (void)xdr_opaque_auth(xdrs, &ap->no_client.ah_cred); + (void)xdr_opaque_auth(xdrs, &ap->no_client.ah_verf); + ap->mcnt = XDR_GETPOS(xdrs); + XDR_DESTROY(xdrs); + } + return (&ap->no_client); +} + +/*ARGSUSED*/ +static bool_t +authnone_marshal(client, xdrs) + AUTH *client; + XDR *xdrs; +{ + register struct authnone_private *ap = authnone_private; + + if (ap == 0) + return (0); + return ((*xdrs->x_ops->x_putbytes)(xdrs, + ap->marshalled_client, ap->mcnt)); +} + +static void +authnone_verf() +{ +} + +static bool_t +authnone_validate() +{ + + return (TRUE); +} + +static bool_t +authnone_refresh() +{ + + return (FALSE); +} + +static void +authnone_destroy() +{ +} diff --git a/pool/shard006/C/0118585_debug_console.c b/pool/shard006/C/0118585_debug_console.c new file mode 100644 index 0000000000000000000000000000000000000000..a5a715228c4d4a9b720d3aeaac54211ac2068081 --- /dev/null +++ b/pool/shard006/C/0118585_debug_console.c @@ -0,0 +1,125 @@ +/* + * ===================================================================================== + * + * Filename: console.c + * + * Description: + * + * Version: 1.0 + * Created: 06/24/2015 03:49:44 AM + * Revision: none + * Compiler: gcc + * + * Author: alan lin (), a1an1in@sina.com + * Organization: + * + * ===================================================================================== + */ +/* + * Copyright (c) 2015-2020 alan lin + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ +#include +#include +#include +#include "libdbg/debug.h" +#include "cutils_re.h" + +int console_print_print_str_vl(debugger_t *debugger, + size_t level,const char *fmt,va_list vl) +{ +#define MAX_STR_LEN 1024 + char dest[MAX_STR_LEN]; + size_t offset=0 , ret = 0; + + memset(dest,'\0',MAX_STR_LEN); + offset = vsnprintf(dest,MAX_STR_LEN,fmt,vl); + +#ifdef UNIX_LIKE_USER_MODE + int reverse_color_flag,background_color,front_color,high_light_flag; + char high_light_value[MAX_STR_LEN]; + char reverse_color_value[MAX_STR_LEN]; + size_t color_value; + + color_value = debugger_get_level_color(debugger,level); + reverse_color_flag = color_value&0x1; + background_color = ((color_value&0x70)>>4); + front_color = ((color_value&0xe)>>1); + high_light_flag = ((color_value>>7)&1); + + if(high_light_flag == 1){ + strcpy(high_light_value,"\33[1m"); + }else{ + strcpy(high_light_value,""); + } + if(reverse_color_flag == 1){ + strcpy(reverse_color_value,"\33[7m"); + }else{ + strcpy(reverse_color_value,""); + } + if((color_value & 0xfe) == 0xe & high_light_flag == 0){ + printf("\33[0m\33[%dm\33[%dm",49,30); + printf("%s",dest); + printf("\33[0m\033[K"); + }else{ + printf("\33[0m%s%s\33[%dm\33[%dm",high_light_value,reverse_color_value,background_color+40,front_color+30); + printf("%s",dest); + printf("\33[0m\033[K"); + } + printf("\n"); + return strlen(dest); +#endif + +#ifdef WINDOWS_USER_MODE + printf("%s\n",dest); +#endif + +#undef MAX_STR_LEN + return ret; +} +int console_print_print(debugger_t *debugger,size_t level,const char *fmt,...) +{ + int ret; + va_list ap; + + va_start(ap,fmt); + ret = console_print_print_str_vl(debugger,level,fmt,ap); + va_end(ap); + + return ret; +} +void console_print_regester() +{ + debugger_module_t dm={ + .dbg_ops ={ + .dbg_string_vl = console_print_print_str_vl, + .dbg_string = console_print_print, + .init = NULL, + .destroy = NULL, + } + }; + memcpy(&debugger_modules[DEBUGGER_TYPE_CONSOLE],&dm,sizeof(debugger_module_t)); +} diff --git a/pool/shard006/C/0118590_my_bitmap.c b/pool/shard006/C/0118590_my_bitmap.c new file mode 100644 index 0000000000000000000000000000000000000000..a18fcba0b6006a3fa07a3fc2c142fecd99d71a78 --- /dev/null +++ b/pool/shard006/C/0118590_my_bitmap.c @@ -0,0 +1,145 @@ +/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library 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 */ + +/* + Handling of uchar arrays as large bitmaps. + We assume that the size of the used bitmap is less than ~(uint) 0 + + TODO: + Make assembler THREAD safe versions of these using test-and-set instructions +*/ + +#include "mysys_priv.h" +#include +#include +#include +#include + +inline void bitmap_lock(MY_BITMAP* map) +{ +#ifdef THREAD + if (map->thread_safe) + pthread_mutex_lock(&map->mutex); +#endif +} + +inline void bitmap_unlock(MY_BITMAP* map) +{ +#ifdef THREAD + if (map->thread_safe) + pthread_mutex_unlock(&map->mutex); +#endif +} + +my_bool bitmap_init(MY_BITMAP *map, uint bitmap_size, my_bool thread_safe) +{ + if (!(map->bitmap=(uchar*) my_malloc((bitmap_size+7)/8, + MYF(MY_WME | MY_ZEROFILL)))) + return 1; + dbug_assert(bitmap_size != ~(uint) 0); +#ifdef THREAD + if ((map->thread_safe = thread_safe)) + pthread_mutex_init(&map->mutex, MY_MUTEX_INIT_FAST); +#endif + map->bitmap_size=bitmap_size; + return 0; +} + +void bitmap_free(MY_BITMAP *map) +{ + if (map->bitmap) + { + my_free((char*) map->bitmap, MYF(0)); + map->bitmap=0; +#ifdef THREAD + if (map->thread_safe) + pthread_mutex_destroy(&map->mutex); +#endif + } +} + +void bitmap_set_bit(MY_BITMAP *map, uint bitmap_bit) +{ + if (bitmap_bit < map->bitmap_size) + { + bitmap_lock(map); + map->bitmap[bitmap_bit / 8] |= (1 << (bitmap_bit & 7)); + bitmap_unlock(map); + } +} + + +uint bitmap_set_next(MY_BITMAP *map) +{ + uchar *bitmap=map->bitmap; + uint bit_found = MY_BIT_NONE; + uint bitmap_size=map->bitmap_size; + uint i; + + bitmap_lock(map); + for (i=0; i < bitmap_size ; i++, bitmap++) + { + if (*bitmap != 0xff) + { /* Found slot with free bit */ + uint b; + for (b=0; ; b++) + { + if (!(*bitmap & (1 << b))) + { + *bitmap |= 1<bitmap_size) + { + bitmap_lock(map); + map->bitmap[bitmap_bit / 8] &= ~ (1 << (bitmap_bit & 7)); + bitmap_unlock(map); + } +} + +void bitmap_set_all(MY_BITMAP* map) +{ + bitmap_lock(map); + memset(map->bitmap, 0xff, (map->bitmap_size+7)/8); + bitmap_unlock(map); +} + +my_bool bitmap_is_set(MY_BITMAP* map, uint bitmap_bit) +{ + return (bitmap_bit < map->bitmap_size) ? + (map->bitmap[bitmap_bit / 8] & (1 << (bitmap_bit & 7))) : + 0; +} + +void bitmap_clear_all(MY_BITMAP* map) +{ + bitmap_lock(map); + bzero(map->bitmap,(map->bitmap_size+7)/8); + bitmap_unlock(map); +} diff --git a/pool/shard006/C/0118592_pkcs5v2.c b/pool/shard006/C/0118592_pkcs5v2.c new file mode 100644 index 0000000000000000000000000000000000000000..05677c1b76f139581a7d49651a3bbcad2153e639 --- /dev/null +++ b/pool/shard006/C/0118592_pkcs5v2.c @@ -0,0 +1,123 @@ +/*- + * Copyright (c) 2005 Pawel Jakub Dawidek + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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 +__FBSDID("$FreeBSD$"); + +#include +#ifdef _KERNEL +#include +#include +#else +#include +#include +#include +#endif + +#include +#include + +static __inline void +xor(uint8_t *dst, const uint8_t *src, size_t size) +{ + + for (; size > 0; size--) + *dst++ ^= *src++; +} + +void +pkcs5v2_genkey(uint8_t *key, unsigned keylen, const uint8_t *salt, + size_t saltsize, const char *passphrase, u_int iterations) +{ + uint8_t md[SHA512_MDLEN], saltcount[saltsize + sizeof(uint32_t)]; + uint8_t *counter, *keyp; + u_int i, bsize, passlen; + uint32_t count; + + passlen = strlen(passphrase); + bzero(key, keylen); + bcopy(salt, saltcount, saltsize); + counter = saltcount + saltsize; + + keyp = key; + for (count = 1; keylen > 0; count++, keylen -= bsize, keyp += bsize) { + bsize = MIN(keylen, sizeof(md)); + + counter[0] = (count >> 24) & 0xff; + counter[1] = (count >> 16) & 0xff; + counter[2] = (count >> 8) & 0xff; + counter[3] = count & 0xff; + g_eli_crypto_hmac(passphrase, passlen, saltcount, + sizeof(saltcount), md, 0); + xor(keyp, md, bsize); + + for(i = 1; i < iterations; i++) { + g_eli_crypto_hmac(passphrase, passlen, md, sizeof(md), + md, 0); + xor(keyp, md, bsize); + } + } +} + +#ifndef _KERNEL +/* + * Return the number of microseconds needed for 'interations' iterations. + */ +static int +pkcs5v2_probe(int iterations) +{ + uint8_t key[G_ELI_USERKEYLEN], salt[G_ELI_SALTLEN]; + uint8_t passphrase[] = "passphrase"; + struct rusage start, end; + int usecs; + + getrusage(RUSAGE_SELF, &start); + pkcs5v2_genkey(key, sizeof(key), salt, sizeof(salt), passphrase, + iterations); + getrusage(RUSAGE_SELF, &end); + + usecs = end.ru_utime.tv_sec - start.ru_utime.tv_sec; + usecs *= 1000000; + usecs += end.ru_utime.tv_usec - start.ru_utime.tv_usec; + return (usecs); +} + +/* + * Return the number of iterations which takes 'usecs' microseconds. + */ +int +pkcs5v2_calculate(int usecs) +{ + int iterations, v; + + for (iterations = 1; ; iterations <<= 1) { + v = pkcs5v2_probe(iterations); + if (v > 2000000) + break; + } + return (((intmax_t)iterations * (intmax_t)usecs) / v); +} +#endif /* !_KERNEL */ diff --git a/pool/shard006/C/0118593_main.c b/pool/shard006/C/0118593_main.c new file mode 100644 index 0000000000000000000000000000000000000000..95ebaca35e8533868e880f43980f413111ff295f --- /dev/null +++ b/pool/shard006/C/0118593_main.c @@ -0,0 +1,96 @@ +# include +# include +# include +# include +# include + +/* valeur maximal dans le tableau */ +# define MAX_VAL (1000) + +/* nombre d'entier dans le tableau */ +# define N_INTEGERS (20) + +/* seed pour l'aléatoire */ +# define SEED (time(NULL)) + +/* nombre total de threads */ +int nb_threads; + +/* tableau d'entiers aléatoires */ +int integers[N_INTEGERS]; + +/* maximum global */ +volatile int m_global; + +/* mutex sur la variable "m_global" */ +pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +/** + * calcul le maximum local pour le thread numéro 'i' + * @param i l'id du thread + * @return le maximum + */ +static long localMax(long i) { + int integers_per_thread = N_INTEGERS / nb_threads; /* taille du tableau local */ + int bgn = i * integers_per_thread; /* debut local */ + int end = (i == nb_threads - 1) ? N_INTEGERS : (i + 1) * integers_per_thread; /* fin local */ + /* printf("%d to %d\n", bgn, end); */ + int m_local = integers[bgn]; + int j; + for (j = bgn + 1 ; j < end ; j++) { + if (m_local < integers[j] ) { + m_local = integers[j]; + } + } + + pthread_mutex_lock(&mutex); + if (m_global < m_local) { + m_global = m_local; + } + pthread_mutex_unlock(&mutex); + + return (long)m_local; +} + +int main(int argc, char ** argv) { + /* lecture paramètres */ + if (argc != 2) { + fprintf(stderr, "usage: %s [N_THREADS]\n", argv[0]); + return 1; + } + nb_threads = atoi(argv[1]); + + /* création du tableau pseudo-aléatoire */ + srand(SEED); + long i; + for (i = 0 ; i < N_INTEGERS ; i++) { + integers[i] = rand() % MAX_VAL; + } + /* initialise la valeur max */ + m_global = integers[0]; + + /* création des threads */ + pthread_t * thrds = (pthread_t *) malloc(nb_threads * sizeof(pthread_t)); + for (i = 0 ; i < nb_threads ; i++) { + if (pthread_create(thrds + i, NULL, (void * (*)(void *))localMax, (void *)i)) { + fprintf(stderr, "Couldn't create thread %ld\n", i); + memset(thrds + i, 0, sizeof(pthread_t)); + } + } + + /* join sur les threads */ + for (i = 0 ; i < nb_threads ; i++) { + pthread_t * thrd = thrds + i; + if (!thrd) { + continue ; + } + void * unused; + pthread_join(*thrd, &unused); + } + + free(thrds); + pthread_mutex_destroy(&mutex); + printf("Maximum global: %d\n", m_global); + + return 0; +} diff --git a/pool/shard006/C/0118594_reverseTests.c b/pool/shard006/C/0118594_reverseTests.c new file mode 100644 index 0000000000000000000000000000000000000000..51cbc4d13ac8a2e3848d3df9af7a548d598ba9ec --- /dev/null +++ b/pool/shard006/C/0118594_reverseTests.c @@ -0,0 +1,47 @@ +#include "cgreen/cgreen.h" +#include "cgreen/mocks.h" + +#include "reverse.c" + +Describe(Reverse); +BeforeEach(Reverse){}; +AfterEach(Reverse){}; + +Ensure(Reverse, canSeeIfReversalIsAlreadyDone) { + addressesDone = NULL; + doneSize = 0; + numberDone = 0; + + assert_that(alreadyDone(0)); + assert_that(doneSize, is_equal_to(0)); + + assert_that(alreadyDone(1), is_false); + assert_that(doneSize, is_equal_to(100)); + assert_that(numberDone, is_equal_to(1)); + + assert_that(alreadyDone(2), is_false); + assert_that(doneSize, is_equal_to(100)); + assert_that(numberDone, is_equal_to(2)); + + assert_that(alreadyDone(1)); + assert_that(doneSize, is_equal_to(100)); + assert_that(numberDone, is_equal_to(2)); +} + +static void mySyserr(char *string) { + mock(string); +} + +Ensure(Reverse, reverseTableProhibitsTableElementsSmallerThanAword) { + setSyserrHandler(mySyserr); + expect(mySyserr); + + reverseTable(0, sizeof(Aword)-1); +} + +Ensure(Reverse, reverseTableProhibitsTableElementsNotMultipleOfAword) { + setSyserrHandler(mySyserr); + expect(mySyserr); + + reverseTable(0, 4*sizeof(Aword)+1); +} diff --git a/pool/shard006/C/0118596_drm_debugfs.c b/pool/shard006/C/0118596_drm_debugfs.c new file mode 100644 index 0000000000000000000000000000000000000000..895621ec7618e83de8e5d15a8210c14ad52c8603 --- /dev/null +++ b/pool/shard006/C/0118596_drm_debugfs.c @@ -0,0 +1,241 @@ +/** + * \file drm_debugfs.c + * debugfs support for DRM + * + * \author Ben Gamari + */ + +/* + * Created: Sun Dec 21 13:08:50 2008 by bgamari@gmail.com + * + * Copyright 2008 Ben Gamari + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS 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 +#include +#include +#include "drmP.h" + +#if defined(CONFIG_DEBUG_FS) + +/*************************************************** + * Initialization, etc. + **************************************************/ + +static struct drm_info_list drm_debugfs_list[] = { + {"name", drm_name_info, 0}, + {"vm", drm_vm_info, 0}, + {"clients", drm_clients_info, 0}, + {"queues", drm_queues_info, 0}, + {"bufs", drm_bufs_info, 0}, + {"gem_names", drm_gem_name_info, DRIVER_GEM}, +#if DRM_DEBUG_CODE + {"vma", drm_vma_info, 0}, +#endif +}; +#define DRM_DEBUGFS_ENTRIES ARRAY_SIZE(drm_debugfs_list) + + +static int drm_debugfs_open(struct inode *inode, struct file *file) +{ + struct drm_info_node *node = inode->i_private; + + return single_open(file, node->info_ent->show, node); +} + + +static const struct file_operations drm_debugfs_fops = { + .owner = THIS_MODULE, + .open = drm_debugfs_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + + +/** + * Initialize a given set of debugfs files for a device + * + * \param files The array of files to create + * \param count The number of files given + * \param root DRI debugfs dir entry. + * \param minor device minor number + * \return Zero on success, non-zero on failure + * + * Create a given set of debugfs files represented by an array of + * gdm_debugfs_lists in the given root directory. + */ +int drm_debugfs_create_files(struct drm_info_list *files, int count, + struct dentry *root, struct drm_minor *minor) +{ + struct drm_device *dev = minor->dev; + struct dentry *ent; + struct drm_info_node *tmp; + int i, ret; + + for (i = 0; i < count; i++) { + u32 features = files[i].driver_features; + + if (features != 0 && + (dev->driver->driver_features & features) != features) + continue; + + tmp = kmalloc(sizeof(struct drm_info_node), GFP_KERNEL); + if (tmp == NULL) { + ret = -1; + goto fail; + } + ent = debugfs_create_file(files[i].name, S_IFREG | S_IRUGO, + root, tmp, &drm_debugfs_fops); + if (!ent) { + DRM_ERROR("Cannot create /sys/kernel/debug/dri/%s/%s\n", + root->d_name.name, files[i].name); + kfree(tmp); + ret = -1; + goto fail; + } + + tmp->minor = minor; + tmp->dent = ent; + tmp->info_ent = &files[i]; + + mutex_lock(&minor->debugfs_lock); + list_add(&tmp->list, &minor->debugfs_list); + mutex_unlock(&minor->debugfs_lock); + } + return 0; + +fail: + drm_debugfs_remove_files(files, count, minor); + return ret; +} +EXPORT_SYMBOL(drm_debugfs_create_files); + +/** + * Initialize the DRI debugfs filesystem for a device + * + * \param dev DRM device + * \param minor device minor number + * \param root DRI debugfs dir entry. + * + * Create the DRI debugfs root entry "/sys/kernel/debug/dri", the device debugfs root entry + * "/sys/kernel/debug/dri/%minor%/", and each entry in debugfs_list as + * "/sys/kernel/debug/dri/%minor%/%name%". + */ +int drm_debugfs_init(struct drm_minor *minor, int minor_id, + struct dentry *root) +{ + struct drm_device *dev = minor->dev; + char name[64]; + int ret; + + INIT_LIST_HEAD(&minor->debugfs_list); + mutex_init(&minor->debugfs_lock); + sprintf(name, "%d", minor_id); + minor->debugfs_root = debugfs_create_dir(name, root); + if (!minor->debugfs_root) { + DRM_ERROR("Cannot create /sys/kernel/debug/dri/%s\n", name); + return -1; + } + + ret = drm_debugfs_create_files(drm_debugfs_list, DRM_DEBUGFS_ENTRIES, + minor->debugfs_root, minor); + if (ret) { + debugfs_remove(minor->debugfs_root); + minor->debugfs_root = NULL; + DRM_ERROR("Failed to create core drm debugfs files\n"); + return ret; + } + + if (dev->driver->debugfs_init) { + ret = dev->driver->debugfs_init(minor); + if (ret) { + DRM_ERROR("DRM: Driver failed to initialize " + "/sys/kernel/debug/dri.\n"); + return ret; + } + } + return 0; +} + + +/** + * Remove a list of debugfs files + * + * \param files The list of files + * \param count The number of files + * \param minor The minor of which we should remove the files + * \return always zero. + * + * Remove all debugfs entries created by debugfs_init(). + */ +int drm_debugfs_remove_files(struct drm_info_list *files, int count, + struct drm_minor *minor) +{ + struct list_head *pos, *q; + struct drm_info_node *tmp; + int i; + + mutex_lock(&minor->debugfs_lock); + for (i = 0; i < count; i++) { + list_for_each_safe(pos, q, &minor->debugfs_list) { + tmp = list_entry(pos, struct drm_info_node, list); + if (tmp->info_ent == &files[i]) { + debugfs_remove(tmp->dent); + list_del(pos); + kfree(tmp); + } + } + } + mutex_unlock(&minor->debugfs_lock); + return 0; +} +EXPORT_SYMBOL(drm_debugfs_remove_files); + +/** + * Cleanup the debugfs filesystem resources. + * + * \param minor device minor number. + * \return always zero. + * + * Remove all debugfs entries created by debugfs_init(). + */ +int drm_debugfs_cleanup(struct drm_minor *minor) +{ + struct drm_device *dev = minor->dev; + + if (!minor->debugfs_root) + return 0; + + if (dev->driver->debugfs_cleanup) + dev->driver->debugfs_cleanup(minor); + + drm_debugfs_remove_files(drm_debugfs_list, DRM_DEBUGFS_ENTRIES, minor); + + debugfs_remove(minor->debugfs_root); + minor->debugfs_root = NULL; + + return 0; +} + +#endif /* CONFIG_DEBUG_FS */ + diff --git a/pool/shard006/C/0118601_dw_apb_timer_of.c b/pool/shard006/C/0118601_dw_apb_timer_of.c new file mode 100644 index 0000000000000000000000000000000000000000..929e7ce16fae23ba5e97587d8f9dee143bc6a7d7 --- /dev/null +++ b/pool/shard006/C/0118601_dw_apb_timer_of.c @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2012 Altera Corporation + * Copyright (c) 2011 Picochip Ltd., Jamie Iles + * + * Modified from mach-picoxcell/time.c + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include +#include +#include +#include + +#include +#include + +static void timer_get_base_and_rate(struct device_node *np, + void __iomem **base, u32 *rate) +{ + *base = of_iomap(np, 0); + + if (!*base) + panic("Unable to map regs for %s", np->name); + + if (of_property_read_u32(np, "clock-freq", rate) && + of_property_read_u32(np, "clock-frequency", rate)) + panic("No clock-frequency property for %s", np->name); +} + +static void add_clockevent(struct device_node *event_timer) +{ + void __iomem *iobase; + struct dw_apb_clock_event_device *ced; + u32 irq, rate; + + irq = irq_of_parse_and_map(event_timer, 0); + if (irq == 0) + panic("No IRQ for clock event timer"); + + timer_get_base_and_rate(event_timer, &iobase, &rate); + + ced = dw_apb_clockevent_init(0, event_timer->name, 300, iobase, irq, + rate); + if (!ced) + panic("Unable to initialise clockevent device"); + + dw_apb_clockevent_register(ced); +} + +static void add_clocksource(struct device_node *source_timer) +{ + void __iomem *iobase; + struct dw_apb_clocksource *cs; + u32 rate; + + timer_get_base_and_rate(source_timer, &iobase, &rate); + + cs = dw_apb_clocksource_init(300, source_timer->name, iobase, rate); + if (!cs) + panic("Unable to initialise clocksource device"); + + dw_apb_clocksource_start(cs); + dw_apb_clocksource_register(cs); +} + +static void __iomem *sched_io_base; + +static u32 read_sched_clock(void) +{ + return __raw_readl(sched_io_base); +} + +static const struct of_device_id sptimer_ids[] __initconst = { + { .compatible = "picochip,pc3x2-rtc" }, + { .compatible = "snps,dw-apb-timer-sp" }, + { /* Sentinel */ }, +}; + +static void init_sched_clock(void) +{ + struct device_node *sched_timer; + u32 rate; + + sched_timer = of_find_matching_node(NULL, sptimer_ids); + if (!sched_timer) + panic("No RTC for sched clock to use"); + + timer_get_base_and_rate(sched_timer, &sched_io_base, &rate); + of_node_put(sched_timer); + + setup_sched_clock(read_sched_clock, 32, rate); +} + +static const struct of_device_id osctimer_ids[] __initconst = { + { .compatible = "picochip,pc3x2-timer" }, + { .compatible = "snps,dw-apb-timer-osc" }, + {}, +}; + +static void __init timer_init(void) +{ + struct device_node *event_timer, *source_timer; + + event_timer = of_find_matching_node(NULL, osctimer_ids); + if (!event_timer) + panic("No timer for clockevent"); + add_clockevent(event_timer); + + source_timer = of_find_matching_node(event_timer, osctimer_ids); + if (!source_timer) + panic("No timer for clocksource"); + add_clocksource(source_timer); + + of_node_put(source_timer); + + init_sched_clock(); +} + +struct sys_timer dw_apb_timer = { + .init = timer_init, +}; diff --git a/pool/shard006/C/0118609_SCSI_Parity_Error.c b/pool/shard006/C/0118609_SCSI_Parity_Error.c new file mode 100644 index 0000000000000000000000000000000000000000..de05e37769baa7a7c927bcdcae2fa18af945131b --- /dev/null +++ b/pool/shard006/C/0118609_SCSI_Parity_Error.c @@ -0,0 +1,134 @@ +/******************************************************************************* +* File Name: SCSI_Parity_Error.c +* Version 1.90 +* +* Description: +* This file contains API to enable firmware to read the value of a Status +* Register. +* +* Note: +* +******************************************************************************** +* Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved. +* You may use this file only in accordance with the license, terms, conditions, +* disclaimers, and limitations in the end user license agreement accompanying +* the software package with which this file was provided. +*******************************************************************************/ + +#include "SCSI_Parity_Error.h" + +#if !defined(SCSI_Parity_Error_sts_sts_reg__REMOVED) /* Check for removal by optimization */ + + +/******************************************************************************* +* Function Name: SCSI_Parity_Error_Read +******************************************************************************** +* +* Summary: +* Reads the current value assigned to the Status Register. +* +* Parameters: +* None. +* +* Return: +* The current value in the Status Register. +* +*******************************************************************************/ +uint8 SCSI_Parity_Error_Read(void) +{ + return SCSI_Parity_Error_Status; +} + + +/******************************************************************************* +* Function Name: SCSI_Parity_Error_InterruptEnable +******************************************************************************** +* +* Summary: +* Enables the Status Register interrupt. +* +* Parameters: +* None. +* +* Return: +* None. +* +*******************************************************************************/ +void SCSI_Parity_Error_InterruptEnable(void) +{ + uint8 interruptState; + interruptState = CyEnterCriticalSection(); + SCSI_Parity_Error_Status_Aux_Ctrl |= SCSI_Parity_Error_STATUS_INTR_ENBL; + CyExitCriticalSection(interruptState); +} + + +/******************************************************************************* +* Function Name: SCSI_Parity_Error_InterruptDisable +******************************************************************************** +* +* Summary: +* Disables the Status Register interrupt. +* +* Parameters: +* None. +* +* Return: +* None. +* +*******************************************************************************/ +void SCSI_Parity_Error_InterruptDisable(void) +{ + uint8 interruptState; + interruptState = CyEnterCriticalSection(); + SCSI_Parity_Error_Status_Aux_Ctrl &= (uint8)(~SCSI_Parity_Error_STATUS_INTR_ENBL); + CyExitCriticalSection(interruptState); +} + + +/******************************************************************************* +* Function Name: SCSI_Parity_Error_WriteMask +******************************************************************************** +* +* Summary: +* Writes the current mask value assigned to the Status Register. +* +* Parameters: +* mask: Value to write into the mask register. +* +* Return: +* None. +* +*******************************************************************************/ +void SCSI_Parity_Error_WriteMask(uint8 mask) +{ + #if(SCSI_Parity_Error_INPUTS < 8u) + mask &= ((uint8)(1u << SCSI_Parity_Error_INPUTS) - 1u); + #endif /* End SCSI_Parity_Error_INPUTS < 8u */ + SCSI_Parity_Error_Status_Mask = mask; +} + + +/******************************************************************************* +* Function Name: SCSI_Parity_Error_ReadMask +******************************************************************************** +* +* Summary: +* Reads the current interrupt mask assigned to the Status Register. +* +* Parameters: +* None. +* +* Return: +* The value of the interrupt mask of the Status Register. +* +*******************************************************************************/ +uint8 SCSI_Parity_Error_ReadMask(void) +{ + return SCSI_Parity_Error_Status_Mask; +} + +#endif /* End check for removal by optimization */ + + +/* [] END OF FILE */ diff --git a/pool/shard006/C/0118611_simpleserver.c b/pool/shard006/C/0118611_simpleserver.c new file mode 100644 index 0000000000000000000000000000000000000000..a579c3db36c1307b67191ac4ec58d533e5758b9b --- /dev/null +++ b/pool/shard006/C/0118611_simpleserver.c @@ -0,0 +1,169 @@ +/* SPDX license identifier: MPL-2.0 + * Copyright (C) 2015, Visteon Corp. + * Author: Pavel Konopelko, pkonopel@visteon.com + * + * This file is part of Common API C + * + * This Source Code Form is subject to the terms of the + * Mozilla Public License (MPL), version 2.0. + * If a copy of the MPL was not distributed with this file, + * you can obtain one at http://mozilla.org/MPL/2.0/. + * For further information see http://www.genivi.org/. + */ + +#include +#include +#include + +#include +#include +#include +#include "src-gen/server-Calculator.h" + + +static int Calculator_impl1_split( + struct cc_server_Calculator *instance, double value, int32_t *whole, int32_t *fraction) +{ + CC_LOG_DEBUG("invoked method Calculator_impl1_split()\n"); + CC_LOG_DEBUG("with value=%g\n", value); + assert(instance); + assert(whole); + assert(fraction); + *whole = (int32_t)value; + *fraction = (int32_t)((value - (double)*whole) * 1.0e+9); + CC_LOG_DEBUG("returning whole=%d, fraction=%d\n", *whole, *fraction); + return 0; +} + +static int Calculator_impl2_split( + struct cc_server_Calculator *instance, double value, int32_t *whole, int32_t *fraction) +{ + CC_LOG_DEBUG("invoked method Calculator_impl1_split()\n"); + CC_LOG_DEBUG("with value=%g\n", value); + assert(instance); + assert(whole); + assert(fraction); + *whole = -1; + *fraction = -2; + CC_LOG_DEBUG("returning whole=%d, fraction=%d\n", *whole, *fraction); + return 0; +} + +static struct cc_server_Calculator_impl impl1 = { + .split = &Calculator_impl1_split +}; + +static struct cc_server_Calculator_impl impl2 = { + .split = &Calculator_impl2_split +}; + +static int signal_handler( + sd_event_source *source, const struct signalfd_siginfo *signal_info, void *user_data) +{ + sd_event *event = (sd_event *) user_data; + int result; + + CC_LOG_DEBUG("invoked signal_handler() with signal %d\n", signal_info->ssi_signo); + assert(event); + assert(signal_info->ssi_signo == SIGTERM || signal_info->ssi_signo == SIGINT); + + result = sd_event_exit(event, 0); + if (result < 0) + CC_LOG_ERROR("unable to exit event loop: %s\n", strerror(-result)); + + return result; +} + +static int setup_signals(sd_event *event) +{ + sigset_t signals; + int result; + + CC_LOG_DEBUG("invoked setup_signals()\n"); + assert(event); + sigemptyset(&signals); + sigaddset(&signals, SIGTERM); + sigaddset(&signals, SIGINT); + result = sigprocmask(SIG_BLOCK, &signals, NULL); + if (result != 0) { + CC_LOG_ERROR("unable to block signals: %s\n", strerror(result)); + return -result; + } + result = sd_event_add_signal(event, NULL, SIGTERM, &signal_handler, event); + if (result < 0) { + CC_LOG_ERROR("unable to setup SIGTERM handler: %s\n", strerror(-result)); + return result; + } + result = sd_event_add_signal(event, NULL, SIGINT, &signal_handler, event); + if (result < 0) { + CC_LOG_ERROR("unable to setup SIGINT handler: %s\n", strerror(-result)); + return result; + } + + return 0; +} + + +int main(int argc, char *argv[]) +{ + int result = 0; + struct cc_event_context *context = NULL; + sd_event *event = NULL; + struct cc_server_Calculator *instance1 = NULL, *instance2 = NULL; + + CC_LOG_OPEN("simpleserver"); + printf("Started simpleserver\n"); + + result = cc_backend_startup(); + if (result < 0) { + printf("unable to startup backend: %s\n", strerror(-result)); + goto fail; + } + result = cc_server_Calculator_new( + "org.genivi.capic.Server:/instance1:org.genivi.capic.Calculator", + &impl1, NULL, &instance1); + if (result < 0) { + printf("unable to create server instance '/instance1': %s\n", strerror(-result)); + goto fail; + } + result = cc_server_Calculator_new( + "org.genivi.capic.Server:/instance2:org.genivi.capic.Calculator", + &impl2, NULL, &instance2); + if (result < 0) { + printf("unable to create server instance '/instance2': %s\n", strerror(-result)); + goto fail; + } + + result = cc_backend_get_event_context(&context); + if (result < 0) { + printf("unable to get backend event context: %s\n", strerror(-result)); + goto fail; + } + event = (sd_event *) cc_event_get_native(context); + assert(event); + sd_event_ref(event); + result = setup_signals(event); + if (result < 0) { + printf("unable to setup signal sources: %s\n", strerror(-result)); + goto fail; + } + + printf("entering main loop...\n"); + result = sd_event_loop(event); + if (result < 0) { + printf("unable to run event loop: %s\n", strerror(-result)); + goto fail; + } + +fail: + if (event) + sd_event_unref(event); + instance2 = cc_server_Calculator_free(instance2); + instance1 = cc_server_Calculator_free(instance1); + cc_backend_shutdown(); + + CC_LOG_CLOSE(); + printf("exiting simpleserver\n"); + + return result; +} diff --git a/pool/shard006/C/0118619_app_controlplayback.c b/pool/shard006/C/0118619_app_controlplayback.c new file mode 100644 index 0000000000000000000000000000000000000000..b44eafba96babf1d5c98dd378e8b9b7e30a93acb --- /dev/null +++ b/pool/shard006/C/0118619_app_controlplayback.c @@ -0,0 +1,143 @@ +/* + * Asterisk -- A telephony toolkit for Linux. + * + * Trivial application to control playback a sound file + * + * Copyright (C) 1999, Mark Spencer + * + * Mark Spencer + * + * This program is free software, distributed under the terms of + * the GNU General Public License + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static char *tdesc = "Control Playback Application"; + +static char *app = "ControlPlayback"; + +static char *synopsis = "Play a file with fast forward and rewind"; + +static char *descrip = +"ControlPlayback(filename[|skipms[|ffchar[|rewchar[|stopchar[|pausechr]]]]]):\n" +" Plays back a given filename (do not put extension). Options may also\n" +" be included following a pipe symbol. You can use * and # to rewind and\n" +" fast forward the playback specified. If 'stopchar' is added the file will\n" +" terminate playback when 'stopchar' is pressed. Returns -1 if the channel\n" +" was hung up, or if the file does not exist. Returns 0 otherwise.\n\n" +" Example: exten => 1234,1,ControlPlayback(file|4000|*|#|1|0)\n\n"; + +STANDARD_LOCAL_USER; + +LOCAL_USER_DECL; + +static int is_on_phonepad(char key) +{ + return (key == 35 || key == 42 || (key >= 48 && key <= 57)) ? 1 : 0; +} + +static int controlplayback_exec(struct ast_channel *chan, void *data) +{ + int res = 0; + int skipms = 0; + struct localuser *u; + char tmp[256]; + char *skip = NULL, *fwd = NULL, *rev = NULL, *stop = NULL, *pause = NULL, *file = NULL; + + if (!data || ast_strlen_zero((char *)data)) { + ast_log(LOG_WARNING, "ControlPlayback requires an argument (filename)\n"); + return -1; + } + + strncpy(tmp, (char *)data, sizeof(tmp)-1); + file = tmp; + + if ((skip=strchr(tmp,'|'))) { + *skip = '\0'; + *skip++; + fwd=strchr(skip,'|'); + if (fwd) { + *fwd = '\0'; + *fwd++; + rev = strchr(fwd,'|'); + if (rev) { + *rev = '\0'; + *rev++; + stop = strchr(rev,'|'); + if (stop) { + *stop = '\0'; + *stop++; + pause = strchr(stop,'|'); + if (pause) { + *pause = '\0'; + *pause++; + } + } + } + } + } + + skipms = skip ? atoi(skip) : 3000; + if (!skipms) + skipms = 3000; + + if (!fwd || !is_on_phonepad(*fwd)) + fwd = "#"; + if (!rev || !is_on_phonepad(*rev)) + rev = "*"; + if (stop && !is_on_phonepad(*stop)) + stop = NULL; + if (pause && !is_on_phonepad(*pause)) + pause = NULL; + + LOCAL_USER_ADD(u); + + res = ast_control_streamfile(chan, file, fwd, rev, stop, pause, skipms); + + LOCAL_USER_REMOVE(u); + + /* If we stopped on one of our stop keys, return 0 */ + if(stop && strchr(stop, res)) + res = 0; + + return res; +} + +int unload_module(void) +{ + STANDARD_HANGUP_LOCALUSERS; + return ast_unregister_application(app); +} + +int load_module(void) +{ + return ast_register_application(app, controlplayback_exec, synopsis, descrip); +} + +char *description(void) +{ + return tdesc; +} + +int usecount(void) +{ + int res; + STANDARD_USECOUNT(res); + return res; +} + +char *key() +{ + return ASTERISK_GPL_KEY; +} diff --git a/pool/shard006/C/0118625_bookmark.c b/pool/shard006/C/0118625_bookmark.c new file mode 100644 index 0000000000000000000000000000000000000000..9a594789ccd2729e6ac1d05382057968e457cf50 --- /dev/null +++ b/pool/shard006/C/0118625_bookmark.c @@ -0,0 +1,86 @@ +/* + * File: bookmark.c + * + * Copyright 2002-2007 Jorge Arellano Cid + * + * 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. + */ + +#include + +#include "msg.h" +#include "history.h" +#include "capi.h" +#include "bookmark.h" /* for prototypes */ +#include "../dpip/dpip.h" + + + +/* + * Have a short chat with the bookmarks server, + * and finally ask it to add a new bookmark. + * (this is an example of dpi chat) + */ +void a_Bookmarks_chat_add(BrowserWindow *Bw, char *Cmd, char *answer) +{ + static char *cmd1 = NULL, *cmd2 = NULL, *cmd3 = NULL, *cmd4 = NULL; + static BrowserWindow *bw = NULL; + + if (!cmd1) { + cmd1 = a_Dpip_build_cmd("cmd=%s msg=%s", "chat", "Hi server"); + cmd2 = a_Dpip_build_cmd("cmd=%s msg=%s", "chat", + "I want to set a bookmark"); + cmd3 = a_Dpip_build_cmd("cmd=%s msg=%s", "chat", "Sure it is!"); + } + + _MSG("a_Bookmarks_chat_add\n answer=%s\n", answer ? answer : "(null)"); + + if (Bw) + bw = Bw; + if (!cmd4 && Cmd) + cmd4 = dStrdup(Cmd); + + if (!answer) { + a_Capi_dpi_send_cmd(NULL, bw, cmd1, "bookmarks", 1); + + } else { + /* we have an answer */ + if (answer) { + if (*answer == 'H') { + /* "Hi browser" */ + a_Capi_dpi_send_cmd(NULL, bw, cmd2, "bookmarks", 0); + } else if (*answer == 'I') { + /* "Is it worth?" */ + a_Capi_dpi_send_cmd(NULL, bw, cmd3, "bookmarks", 0); + } else if (*answer == 'O') { + /* "OK, send it!" */ + a_Capi_dpi_send_cmd(NULL, bw, cmd4, "bookmarks", 0); + dFree(cmd4); + cmd4 = NULL; + } + } + } +} + +/* + * Add the new bookmark through the bookmarks server + */ +void a_Bookmarks_add(BrowserWindow *bw, const DilloUrl *url) +{ + const char *title; + char *cmd; + + dReturn_if_fail(url != NULL); + + /* if the page has no title, we'll use the url string */ + title = a_History_get_title_by_url(url, 1); + + cmd = a_Dpip_build_cmd("cmd=%s url=%s title=%s", + "add_bookmark", URL_STR(url), title); + a_Bookmarks_chat_add(bw, cmd, NULL); + dFree(cmd); +} + diff --git a/pool/shard006/C/0118626_modem.c b/pool/shard006/C/0118626_modem.c new file mode 100644 index 0000000000000000000000000000000000000000..bba64b2f78a79517f783aeb77a84fd343abca904 --- /dev/null +++ b/pool/shard006/C/0118626_modem.c @@ -0,0 +1,227 @@ +/* + * This file is GPLv2 + * Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies) + * Copyright (C) 2010 Sebastian Reichel + */ +#include +#include +#include +#include +#include + +#include "gisi/modem.h" +#include "opcodes/mtc.h" + +#include "debug.h" +#include "modem.h" +#include "gisi/netlink.h" +#include "helper.h" + +void mtc_state_cb(GIsiClient *client, const void *restrict data, size_t len, uint16_t object, void *opaque) { + const unsigned char *msg = data; + struct isi_modem *isi = opaque; + + if(!msg) { + g_print("ISI client error: %d", g_isi_client_error(client)); + return; + } + + if(len < 3 || msg[0] != MTC_STATE_INFO_IND) + return; + + g_debug("current modem state: %s (0x%02X)", mtc_modem_state_name(msg[1]), msg[1]); + g_debug("target modem state: %s (0x%02X)", mtc_modem_state_name(msg[2]), msg[2]); + + isi->power = (msg[1] != MTC_POWER_OFF); + if(isi->powerstatus) + isi->powerstatus(msg[1] != MTC_POWER_OFF, isi->user_data); +} + +gboolean mtc_query_cb(GIsiClient *client, const void *restrict data, size_t len, uint16_t object, void *opaque) { + const unsigned char *msg = data; + struct isi_modem *isi = opaque; + + if(!msg) { + g_debug("ISI client error: %d", g_isi_client_error(client)); + return TRUE; + } + + if(len < 3 || msg[0] != MTC_STATE_QUERY_RESP) + return FALSE; + + g_debug("current modem state: %s (0x%02X)", mtc_modem_state_name(msg[1]), msg[1]); + g_debug("target modem state: %s (0x%02X)", mtc_modem_state_name(msg[2]), msg[2]); + + isi->power = (msg[1] != MTC_POWER_OFF); + return TRUE; +} + +void modem_reachable_cb(GIsiClient *client, gboolean alive, uint16_t object, void *opaque) { + struct isi_cb_data *cbd = opaque; + isi_subsystem_reachable_cb cb = cbd->callback; + struct isi_modem *modem = cbd->subsystem; + void * user_data = cbd->data; + isi_cb_data_free(opaque); + + const unsigned char msg[] = { + MTC_STATE_QUERY_REQ, + 0x00, 0x00 /* Filler */ + }; + + if(!alive) { + g_warning("Unable to bootstrap mtc driver"); + cb(TRUE, user_data); + return; + } + + g_debug("%s (v.%03d.%03d) reachable", + pn_resource_name(g_isi_client_resource(client)), + g_isi_version_major(client), + g_isi_version_minor(client)); + + cb(FALSE, user_data); + + g_isi_subscribe(client, MTC_STATE_INFO_IND, mtc_state_cb, modem); + g_isi_request_make(client, msg, sizeof(msg), MTC_TIMEOUT, mtc_query_cb, modem); +} + +gboolean mtc_power_on_cb(GIsiClient *client, const void *restrict data, size_t len, uint16_t object, void *opaque) { + const unsigned char *msg = data; + struct isi_modem *isi = opaque; + + if(!msg) { + g_debug("ISI client error: %d", g_isi_client_error(client)); + return TRUE; + } + + if(len < 2 || msg[0] != MTC_POWER_ON_RESP) + return FALSE; + + if(msg[1] == MTC_OK) { + isi->power = TRUE; + if(isi->powerstatus) + isi->powerstatus(TRUE, isi->user_data); + } + + return TRUE; +} + +gboolean mtc_power_off_cb(GIsiClient *client, const void *restrict data, size_t len, uint16_t object, void *opaque) { + const unsigned char *msg = data; + struct isi_modem *isi = opaque; + + if(!msg) { + g_debug("ISI client error: %d", g_isi_client_error(client)); + return TRUE; + } + + if(len < 2 || msg[0] != MTC_POWER_OFF_RESP) + return FALSE; + + if(msg[1] == MTC_OK) { + isi->power = FALSE; + if(isi->powerstatus) + isi->powerstatus(FALSE, isi->user_data); + } + + return TRUE; +} + +static void netlink_status_cb(GIsiModem *idx, GPhonetLinkState state, char const *iface, void *data) { + struct isi_cb_data *cbd = data; + isi_subsystem_reachable_cb cb = cbd->callback; + struct isi_modem *modem = cbd->subsystem; + void * user_data = cbd->data; + + g_debug("Phonet: %s is %s, idx=%p", iface, state == PN_LINK_UP ? "up" : "down", idx); + + if(state == PN_LINK_UP) { + modem->idx = idx; + modem->client = g_isi_client_create(idx, PN_MTC); + + if(!modem->client) { + cb(TRUE, user_data); + isi_cb_data_free(cbd); + return; + } + + g_isi_verify(modem->client, modem_reachable_cb, cbd); + } else { + g_isi_client_destroy(modem->client); + modem->client = NULL; + modem->idx = NULL; + modem->status = FALSE; + cb(TRUE, user_data); + } +} + +struct isi_modem* isi_modem_create(char *interface, isi_subsystem_reachable_cb cb, void *user_data) { + struct isi_modem *modem = malloc(sizeof(struct isi_modem)); + struct isi_cb_data *cbd = isi_cb_data_new(modem, cb, user_data); + int error; + + if(!modem || !cbd) + goto error; + + modem->idx = g_isi_modem_by_name(interface); + modem->link = g_pn_netlink_start(modem->idx, netlink_status_cb, cbd); + modem->client = NULL; + + if(!modem->link) + goto error; + + error = g_pn_netlink_set_address(modem->idx, PN_DEV_SOS); + if(error && error != -EEXIST) + g_debug("g_pn_netlink_set_address: %s\n", strerror(-error)); + + error = g_pn_netlink_add_route(modem->idx, PN_DEV_HOST); + if(error && error != -ENOTSUP) + g_debug("g_pn_netlink_add_route: %s\n", strerror(-error)); + + return modem; + + error: + if(modem) + free(modem); + isi_cb_data_free(cbd); + cb(TRUE, user_data); + return NULL; +} + +void isi_modem_destroy(struct isi_modem *modem) { + g_isi_client_destroy(modem->client); + free(modem); +} + +void isi_modem_set_powerstatus_notification(struct isi_modem *modem, isi_powerstatus_cb cb, void *user_data) { + modem->powerstatus = cb; + modem->user_data = user_data; +} + +gboolean isi_modem_get_powerstatus(struct isi_modem *modem) { + return modem->power; +} + +int isi_modem_enable(struct isi_modem *modem) { + const unsigned char msg[] = { + MTC_POWER_ON_REQ, + 0x00, 0x00 /* Filler */ + }; + + if (!g_isi_request_make(modem->client, msg, sizeof(msg), MTC_TIMEOUT, mtc_power_on_cb, modem)) + return -EINVAL; + + return -EINPROGRESS; +} + +int isi_modem_disable(struct isi_modem *modem) { + const unsigned char msg[] = { + MTC_POWER_OFF_REQ, + 0x00, 0x00 /* Filler */ + }; + + if (!g_isi_request_make(modem->client, msg, sizeof(msg), MTC_TIMEOUT, mtc_power_off_cb, modem)) + return -EINVAL; + + return -EINPROGRESS; +} diff --git a/pool/shard006/C/0118629_fcblanks.c b/pool/shard006/C/0118629_fcblanks.c new file mode 100644 index 0000000000000000000000000000000000000000..30f44069fc9abb3484c3c35ac1d24e8eef5b2f4a --- /dev/null +++ b/pool/shard006/C/0118629_fcblanks.c @@ -0,0 +1,92 @@ +/* + * $XFree86: xc/lib/fontconfig/src/fcblanks.c,v 1.2 2002/08/31 22:17:31 keithp Exp $ + * + * Copyright © 2002 Keith Packard, member of The XFree86 Project, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of Keith Packard not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Keith Packard makes no + * representations about the suitability of this software for any purpose. It + * is provided "as is" without express or implied warranty. + * + * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +#include "fcint.h" + +FcBlanks * +FcBlanksCreate (void) +{ + FcBlanks *b; + + b = malloc (sizeof (FcBlanks)); + if (!b) + return 0; + FcMemAlloc (FC_MEM_BLANKS, sizeof (FcBlanks)); + b->nblank = 0; + b->sblank = 0; + b->blanks = 0; + return b; +} + +void +FcBlanksDestroy (FcBlanks *b) +{ + if (b->blanks) + { + FcMemFree (FC_MEM_BLANKS, b->sblank * sizeof (FcChar32)); + free (b->blanks); + } + FcMemFree (FC_MEM_BLANKS, sizeof (FcBlanks)); + free (b); +} + +FcBool +FcBlanksAdd (FcBlanks *b, FcChar32 ucs4) +{ + FcChar32 *c; + int sblank; + + for (sblank = 0; sblank < b->nblank; sblank++) + if (b->blanks[sblank] == ucs4) + return FcTrue; + + if (b->nblank == b->sblank) + { + sblank = b->sblank + 32; + if (b->blanks) + c = (FcChar32 *) realloc (b->blanks, sblank * sizeof (FcChar32)); + else + c = (FcChar32 *) malloc (sblank * sizeof (FcChar32)); + if (!c) + return FcFalse; + if (b->sblank) + FcMemFree (FC_MEM_BLANKS, b->sblank * sizeof (FcChar32)); + FcMemAlloc (FC_MEM_BLANKS, sblank * sizeof (FcChar32)); + b->sblank = sblank; + b->blanks = c; + } + b->blanks[b->nblank++] = ucs4; + return FcTrue; +} + +FcBool +FcBlanksIsMember (FcBlanks *b, FcChar32 ucs4) +{ + int i; + + for (i = 0; i < b->nblank; i++) + if (b->blanks[i] == ucs4) + return FcTrue; + return FcFalse; +} diff --git a/pool/shard006/C/0118630_intel_qrk_imr_test.c b/pool/shard006/C/0118630_intel_qrk_imr_test.c new file mode 100644 index 0000000000000000000000000000000000000000..549bb61d8adf40a7720964fc8dda74abdf1a7a77 --- /dev/null +++ b/pool/shard006/C/0118630_intel_qrk_imr_test.c @@ -0,0 +1,350 @@ +/* + * Copyright(c) 2013 Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ +/* + * Intel Quark IMR Test module + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "intel_qrk_imr.h" + +#define DRIVER_NAME "intel_qrk_imr_test" + +/** + * XXX intel_qrk_sb.h needs to be updated with SB_ID_PUNIT and change + * propagated. This is a workaround to make it look less ugly. */ +#define SB_ID_PUNIT SB_ID_THERMAL + +/* Memory-mapped SPI Flash address */ +#define ILB_SPIFLASH_BASEADDR 0xFF800000 +/* PUnit DMA block transfer size, in bytes */ +#define SPI_DMA_BLOCK_SIZE 512 + +/**************************** Exported to LISA *******************************/ + +/* + * Internally-used ioctl code. At the moment it is not reserved by any mainline + * driver. + */ +#define IMR_TEST_IOCTL_CODE 0xE1 + +/* + * Integers for ioctl operation. + */ +#define IOCTL_QRK_SANITY_CHECK_PUNIT_DMA _IO(IMR_TEST_IOCTL_CODE, 0x00) +#define IOCTL_QRK_IMR_1 _IO(IMR_TEST_IOCTL_CODE, 0x01) + +/*****************************************************************************/ + +/** + * struct intel_qrk_imr_dev + * + * Structure to represent module state/data/etc + */ +struct intel_qrk_imr_test_dev { + unsigned int opened; + struct platform_device *pldev; /* Platform device */ + struct cdev cdev; + struct mutex open_lock; +}; + +static struct intel_qrk_imr_test_dev imr_test_dev; +static struct class *imr_test_class; +static DEFINE_MUTEX(imr_test_mutex); +static int imr_test_major; + +/* PUnit DMA registers over side-band */ +#define PUNIT_SPI_DMA_COUNT_REG 0x60 +#define PUNIT_SPI_DMA_DEST_REG 0x61 +#define PUNIT_SPI_DMA_SRC_REG 0x62 + +/** + * ilb_spi_dma_read + * + * @param src: physical address in Legacy SPI Flash + * @param dst: physical address of destination + * @param dma_block_count: number of 512B SPI Flash blocks to be transferred + * + * Read-access iLB SPI via PUnit DMA engine. + * + */ +static void ilb_spi_dma_read(u32 *src, u32 *dst, u32 dma_block_count) +{ + pr_info("%s: src=%p, dst=%p, count=%u\n", __func__, src, dst, + dma_block_count); + + /* Setup source and destination addresses. */ + intel_qrk_sb_write_reg(SB_ID_PUNIT, CFG_WRITE_OPCODE, + PUNIT_SPI_DMA_SRC_REG, (u32) src, 0); + intel_qrk_sb_write_reg(SB_ID_PUNIT, CFG_WRITE_OPCODE, + PUNIT_SPI_DMA_DEST_REG, (u32) dst, 0); + + pr_info("%s: starting transaction\n", __func__); + + /* + * Setup the number of block to be copied over. Transaction will start + * as soon as the register is filled with value. + */ + intel_qrk_sb_write_reg(SB_ID_PUNIT, CFG_WRITE_OPCODE, + PUNIT_SPI_DMA_COUNT_REG, dma_block_count, 0); + + /* Poll for completion. */ + while (dma_block_count > 0) { + intel_qrk_sb_read_reg(SB_ID_PUNIT, CFG_READ_OPCODE, + PUNIT_SPI_DMA_COUNT_REG, &dma_block_count, 0); + } + + pr_info("%s: transaction completed\n", __func__); +} + +/** + * punit_dma_sanity_check + * + * @return 0 if success, 1 if failure + * + * Perform a basic sanity check for PUnit DMA engine. Copy over a 512B SPI + * Flash block. + */ +static int punit_dma_sanity_check(void) +{ + int err = 0; + u32 *buffer = NULL; + u32 buf_ph_addr = 0; + + /* Allocate 512B buffer for 1 SPI Flash block */ + buffer = kzalloc(SPI_DMA_BLOCK_SIZE, GFP_KERNEL); + if (!buffer) { + err = -ENOMEM; + goto end; + } + + /* DMA first SPI Flash block into buffer */ + buf_ph_addr = (u32)virt_to_phys(buffer); + ilb_spi_dma_read((u32 *)ILB_SPIFLASH_BASEADDR, (u32 *)buf_ph_addr, 1); + + kfree(buffer); +end: + return err; +} + +/** + * imr_violate_kernel_punit_dma + * + * @return always 0 + * + * PUnit-DMA access to the Uncompressed Kernel IMR. + * This is based on set_imr_kernel_data() in intel_qrk_imr.c. Find the physical + * address of .text section and copy a 512B chunk of legacy SPI via PuUnit DMA. + * + */ +static int imr_violate_kernel_punit_dma(void) +{ + extern unsigned long _text; + u32 kernel_text = (u32)virt_to_phys(&_text); + + /* We expect this to trigger an IMR violation reset */ + ilb_spi_dma_read((u32 *)ILB_SPIFLASH_BASEADDR, (u32 *)kernel_text, 1); + + /* + * If we're still alive, we have a serious bug: + * - we didn't appropriately target the IMR? + * - if we have, weren't we prevented from accessing? + * - if we weren't prevented, it's unlikely we're alive with a dirty + * text section + */ + pr_err("%s: BUG: still running after DMAing into kernel text!?\n", + __func__); + + return 0; +} + +/* + * File ops + */ +static long imr_test_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + int ret = -EINVAL; + + switch (cmd) { + case IOCTL_QRK_SANITY_CHECK_PUNIT_DMA: + /* Check PUnit DMA actually works */ + ret = punit_dma_sanity_check(); + break; + case IOCTL_QRK_IMR_1: + /* Kernel IMR violation: PUnit DMA access */ + ret = imr_violate_kernel_punit_dma(); + break; + default: + break; + } + + return ret; +} + +static int imr_test_open(struct inode *inode, struct file *file) +{ + mutex_lock(&imr_test_mutex); + nonseekable_open(inode, file); + + if (mutex_lock_interruptible(&imr_test_dev.open_lock)) { + mutex_unlock(&imr_test_mutex); + return -ERESTARTSYS; + } + + if (imr_test_dev.opened) { + mutex_unlock(&imr_test_dev.open_lock); + mutex_unlock(&imr_test_mutex); + return -EINVAL; + } + + imr_test_dev.opened++; + mutex_unlock(&imr_test_dev.open_lock); + mutex_unlock(&imr_test_mutex); + return 0; +} + +static int imr_test_release(struct inode *inode, struct file *file) +{ + mutex_lock(&imr_test_dev.open_lock); + imr_test_dev.opened = 0; + mutex_unlock(&imr_test_dev.open_lock); + + return 0; +} + +static const struct file_operations imr_test_file_ops = { + .open = imr_test_open, + .release = imr_test_release, + .unlocked_ioctl = imr_test_ioctl, + .llseek = no_llseek, +}; + +/** + * intel_qrk_imr_test_probe + * + * @param pdev: Platform device + * @return 0 success < 0 failure + * + * Callback from platform sub-system to probe + */ +static int intel_qrk_imr_test_probe(struct platform_device * pdev) +{ + int retval = 0; + unsigned int minor = 0; + + mutex_init(&imr_test_dev.open_lock); + cdev_init(&imr_test_dev.cdev, &imr_test_file_ops); + imr_test_dev.cdev.owner = THIS_MODULE; + + retval = cdev_add(&imr_test_dev.cdev, MKDEV(imr_test_major, minor), 1); + if (retval) { + printk(KERN_ERR "chardev registration failed\n"); + return -EINVAL; + } + if (IS_ERR(device_create(imr_test_class, NULL, + MKDEV(imr_test_major, minor), NULL, + "imrtest%u", minor))){ + dev_err(&pdev->dev, "can't create device\n"); + return -EINVAL; + } + + return 0; + +} + +static int intel_qrk_imr_test_remove(struct platform_device * pdev) +{ + unsigned int minor = MINOR(imr_test_dev.cdev.dev); + + device_destroy(imr_test_class, MKDEV(imr_test_major, minor)); + cdev_del(&imr_test_dev.cdev); + + class_destroy(imr_test_class); + + return 0; +} + +/* + * Platform structures useful for interface to PM subsystem + */ +static struct platform_driver intel_qrk_imr_test_driver = { + .driver = { + .name = DRIVER_NAME, + .owner = THIS_MODULE, + }, + .remove = intel_qrk_imr_test_remove, +}; + +/** + * intel_qrk_imr_test_init + * + * Load module. + */ +static int __init intel_qrk_imr_test_init(void) +{ + int retval = 0; + dev_t dev; + + imr_test_class = class_create(THIS_MODULE,"qrk_imr_test"); + if (IS_ERR(imr_test_class)) { + retval = PTR_ERR(imr_test_class); + printk(KERN_ERR "imr_test: can't register imr_test class\n"); + goto err; + } + + retval = alloc_chrdev_region(&dev, 0, 1, "imr_test"); + if (retval) { + printk(KERN_ERR "earam_test: can't register character device\n"); + goto err_class; + } + imr_test_major = MAJOR(dev); + + memset(&imr_test_dev, 0x00, sizeof(imr_test_dev)); + imr_test_dev.pldev = platform_create_bundle( + &intel_qrk_imr_test_driver, intel_qrk_imr_test_probe, NULL, 0, NULL, 0); + + if(IS_ERR(imr_test_dev.pldev)){ + printk(KERN_ERR "platform_create_bundle fail!\n"); + retval = PTR_ERR(imr_test_dev.pldev); + goto err_class; + } + + return 0; + +err_class: + class_destroy(imr_test_class); +err: + return retval; +} + +static void __exit intel_qrk_imr_test_exit(void) +{ + platform_device_unregister(imr_test_dev.pldev); + platform_driver_unregister(&intel_qrk_imr_test_driver); +} + +module_init(intel_qrk_imr_test_init); +module_exit(intel_qrk_imr_test_exit); + +MODULE_AUTHOR("Josef Ahmad "); +MODULE_DESCRIPTION("Quark IMR test module"); +MODULE_LICENSE("Dual BSD/GPL"); + diff --git a/pool/shard006/C/0118635_chcon.c b/pool/shard006/C/0118635_chcon.c new file mode 100644 index 0000000000000000000000000000000000000000..c743013cec394d30d45ea907adcf6991ba793eb8 --- /dev/null +++ b/pool/shard006/C/0118635_chcon.c @@ -0,0 +1,228 @@ +/* + * chcon -- change security context, based on coreutils-5.97-13 + * + * Port to busybox: KaiGai Kohei + * + * Copyright (C) 2006 - 2007 KaiGai Kohei + * + * Licensed under GPLv2, see file LICENSE in this source tree. + */ +//config:config CHCON +//config: bool "chcon" +//config: default n +//config: depends on SELINUX +//config: help +//config: Enable support to change the security context of file. +//config: +//config:config FEATURE_CHCON_LONG_OPTIONS +//config: bool "Enable long options" +//config: default y +//config: depends on CHCON && LONG_OPTS +//config: help +//config: Support long options for the chcon applet. + +//applet:IF_CHCON(APPLET(chcon, BB_DIR_USR_BIN, BB_SUID_DROP)) + +//kbuild:lib-$(CONFIG_CHCON) += chcon.o + +//usage:#define chcon_trivial_usage +//usage: "[OPTIONS] CONTEXT FILE..." +//usage: "\n chcon [OPTIONS] [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE..." +//usage: IF_FEATURE_CHCON_LONG_OPTIONS( +//usage: "\n chcon [OPTIONS] --reference=RFILE FILE..." +//usage: ) +//usage:#define chcon_full_usage "\n\n" +//usage: "Change the security context of each FILE to CONTEXT\n" +//usage: IF_FEATURE_CHCON_LONG_OPTIONS( +//usage: "\n -v,--verbose Verbose" +//usage: "\n -c,--changes Report changes made" +//usage: "\n -h,--no-dereference Affect symlinks instead of their targets" +//usage: "\n -f,--silent,--quiet Suppress most error messages" +//usage: "\n --reference=RFILE Use RFILE's group instead of using a CONTEXT value" +//usage: "\n -u,--user=USER Set user/role/type/range in the target" +//usage: "\n -r,--role=ROLE security context" +//usage: "\n -t,--type=TYPE" +//usage: "\n -l,--range=RANGE" +//usage: "\n -R,--recursive Recurse" +//usage: ) +//usage: IF_NOT_FEATURE_CHCON_LONG_OPTIONS( +//usage: "\n -v Verbose" +//usage: "\n -c Report changes made" +//usage: "\n -h Affect symlinks instead of their targets" +//usage: "\n -f Suppress most error messages" +//usage: "\n -u USER Set user/role/type/range in the target security context" +//usage: "\n -r ROLE" +//usage: "\n -t TYPE" +//usage: "\n -l RNG" +//usage: "\n -R Recurse" +//usage: ) + +#include + +#include "libbb.h" + +#define OPT_RECURSIVE (1<<0) /* 'R' */ +#define OPT_CHANHES (1<<1) /* 'c' */ +#define OPT_NODEREFERENCE (1<<2) /* 'h' */ +#define OPT_QUIET (1<<3) /* 'f' */ +#define OPT_USER (1<<4) /* 'u' */ +#define OPT_ROLE (1<<5) /* 'r' */ +#define OPT_TYPE (1<<6) /* 't' */ +#define OPT_RANGE (1<<7) /* 'l' */ +#define OPT_VERBOSE (1<<8) /* 'v' */ +#define OPT_REFERENCE ((1<<9) * ENABLE_FEATURE_CHCON_LONG_OPTIONS) +#define OPT_COMPONENT_SPECIFIED (OPT_USER | OPT_ROLE | OPT_TYPE | OPT_RANGE) + +static char *user = NULL; +static char *role = NULL; +static char *type = NULL; +static char *range = NULL; +static char *specified_context = NULL; + +static int FAST_FUNC change_filedir_context( + const char *fname, + struct stat *stbuf UNUSED_PARAM, + void *userData UNUSED_PARAM, + int depth UNUSED_PARAM) +{ + context_t context = NULL; + security_context_t file_context = NULL; + security_context_t context_string; + int rc = FALSE; + int status = 0; + + if (option_mask32 & OPT_NODEREFERENCE) { + status = lgetfilecon(fname, &file_context); + } else { + status = getfilecon(fname, &file_context); + } + if (status < 0 && errno != ENODATA) { + if ((option_mask32 & OPT_QUIET) == 0) + bb_error_msg("can't obtain security context: %s", fname); + goto skip; + } + + if (file_context == NULL && specified_context == NULL) { + bb_error_msg("can't apply partial context to unlabeled file %s", fname); + goto skip; + } + + if (specified_context == NULL) { + context = set_security_context_component(file_context, + user, role, type, range); + if (!context) { + bb_error_msg("can't compute security context from %s", file_context); + goto skip; + } + } else { + context = context_new(specified_context); + if (!context) { + bb_error_msg("invalid context: %s", specified_context); + goto skip; + } + } + + context_string = context_str(context); + if (!context_string) { + bb_error_msg("can't obtain security context in text expression"); + goto skip; + } + + if (file_context == NULL || strcmp(context_string, file_context) != 0) { + int fail; + + if (option_mask32 & OPT_NODEREFERENCE) { + fail = lsetfilecon(fname, context_string); + } else { + fail = setfilecon(fname, context_string); + } + if ((option_mask32 & OPT_VERBOSE) || ((option_mask32 & OPT_CHANHES) && !fail)) { + printf(!fail + ? "context of %s changed to %s\n" + : "can't change context of %s to %s\n", + fname, context_string); + } + if (!fail) { + rc = TRUE; + } else if ((option_mask32 & OPT_QUIET) == 0) { + bb_error_msg("can't change context of %s to %s", + fname, context_string); + } + } else if (option_mask32 & OPT_VERBOSE) { + printf("context of %s retained as %s\n", fname, context_string); + rc = TRUE; + } +skip: + context_free(context); + freecon(file_context); + + return rc; +} + +#if ENABLE_FEATURE_CHCON_LONG_OPTIONS +static const char chcon_longopts[] ALIGN1 = + "recursive\0" No_argument "R" + "changes\0" No_argument "c" + "no-dereference\0" No_argument "h" + "silent\0" No_argument "f" + "quiet\0" No_argument "f" + "user\0" Required_argument "u" + "role\0" Required_argument "r" + "type\0" Required_argument "t" + "range\0" Required_argument "l" + "verbose\0" No_argument "v" + "reference\0" Required_argument "\xff" /* no short option */ + ; +#endif + +int chcon_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int chcon_main(int argc UNUSED_PARAM, char **argv) +{ + char *reference_file; + char *fname; + int i, errors = 0; + +#if ENABLE_FEATURE_CHCON_LONG_OPTIONS + applet_long_options = chcon_longopts; +#endif + opt_complementary = "-1" /* at least 1 param */ + ":?" /* error if exclusivity constraints are violated */ +#if ENABLE_FEATURE_CHCON_LONG_OPTIONS + ":\xff--urtl:u--\xff:r--\xff:t--\xff:l--\xff" +#endif + ":f--v:v--f"; /* 'verbose' and 'quiet' are exclusive */ + getopt32(argv, "Rchfu:r:t:l:v", + &user, &role, &type, &range, &reference_file); + argv += optind; + +#if ENABLE_FEATURE_CHCON_LONG_OPTIONS + if (option_mask32 & OPT_REFERENCE) { + /* FIXME: lgetfilecon() should be used when '-h' is specified. + * But current implementation follows the original one. */ + if (getfilecon(reference_file, &specified_context) < 0) + bb_perror_msg_and_die("getfilecon('%s') failed", reference_file); + } else +#endif + if ((option_mask32 & OPT_COMPONENT_SPECIFIED) == 0) { + specified_context = *argv++; + /* specified_context is never NULL - + * "-1" in opt_complementary prevents this. */ + if (!argv[0]) + bb_error_msg_and_die("too few arguments"); + } + + for (i = 0; (fname = argv[i]) != NULL; i++) { + int fname_len = strlen(fname); + while (fname_len > 1 && fname[fname_len - 1] == '/') + fname_len--; + fname[fname_len] = '\0'; + + if (recursive_action(fname, + 1< +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif +#include +#include "h.h" +#ifdef _WIN32 +#include "version.h" +#endif + + +ModuleHeader MOD_HEADER(nokick) + = { + "chanmodes/nokick", + "$Id$", + "Channel Mode +Q", + "3.2-b8-1", + NULL + }; + +Cmode_t EXTCMODE_NOKICK; +static char errMsg[2048]; + +#define IsNoKick(chptr) (chptr->mode.extmode & EXTCMODE_NOKICK) + +DLLFUNC char * nokick_check (aClient* sptr, aClient* who, aChannel *chptr, char* comment, long sptr_flags, long who_flags); + +DLLFUNC int MOD_TEST(nokick)(ModuleInfo *modinfo) +{ + return MOD_SUCCESS; +} + +DLLFUNC int MOD_INIT(nokick)(ModuleInfo *modinfo) +{ + CmodeInfo req; + + memset(&req, 0, sizeof(req)); + req.paracount = 0; + req.flag = 'Q'; + req.is_ok = extcmode_default_requirechop; + CmodeAdd(modinfo->handle, req, &EXTCMODE_NOKICK); + + HookAddPCharEx(modinfo->handle, HOOKTYPE_CAN_KICK, nokick_check); + + + MARK_AS_OFFICIAL_MODULE(modinfo); + return MOD_SUCCESS; +} + +DLLFUNC int MOD_LOAD(nokick)(int module_load) +{ + return MOD_SUCCESS; +} + +DLLFUNC int MOD_UNLOAD(nokick)(int module_unload) +{ + return MOD_SUCCESS; +} + +DLLFUNC char * nokick_check (aClient* sptr, aClient* who, aChannel *chptr, char* comment, long sptr_flags, long who_flags) +{ + + if (MyClient(sptr) && IsNoKick(chptr)) + { + /* As a warning, this is not thread safe... */ + ircsnprintf(errMsg,sizeof(errMsg),err_str(ERR_CANNOTDOCOMMAND), + me.name, sptr->name, "KICK", + "channel is +Q"); + return errMsg; + } + + return 0; +} + diff --git a/pool/shard006/C/0118638_io_passfd.c b/pool/shard006/C/0118638_io_passfd.c new file mode 100644 index 0000000000000000000000000000000000000000..b29d2078641c37a3e0a65a2cb5cbd0bd23bff8af --- /dev/null +++ b/pool/shard006/C/0118638_io_passfd.c @@ -0,0 +1,68 @@ +#ifdef __MINGW32__ +#include "io_internal.h" +#include +int io_passfd(int64 sock,int64 fd) { + errno=EINVAL; + return -1; +} +#else + +#ifdef __NetBSD__ +#define _NETBSD_SOURCE +#endif + +#define _XOPEN_SOURCE +#define _XOPEN_SOURCE_EXTENDED 1 +#include +#include +#include +#include +#include +#include +#include +#include "io_internal.h" + +union fdmsg { + struct cmsghdr h; + /* on NetBSD, CMSG_SPACE is not constant */ +/* char buf[CMSG_SPACE(sizeof(int))]; */ + char buf[1000]; +}; + +int io_passfd(int64 sock,int64 fd) { + struct msghdr msg; + struct iovec iov; +#ifdef CMSG_FIRSTHDR + struct cmsghdr *cmsg; +#ifndef CMSG_SPACE +#define CMSG_SPACE(x) x+100 +#endif + char buf[CMSG_SPACE(sizeof(int))]; + memset(buf,0,sizeof(buf)); +#endif + memset(&msg,0,sizeof(msg)); + iov.iov_len=1; + iov.iov_base="x"; + msg.msg_iov=&iov; + msg.msg_iovlen=1; + msg.msg_name=0; + msg.msg_namelen=0; +#ifdef CMSG_FIRSTHDR + msg.msg_control = buf; + msg.msg_controllen = sizeof(buf); + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; +#ifndef CMSG_LEN +#define CMSG_LEN(x) x +#endif + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + msg.msg_controllen = cmsg->cmsg_len; + *((int*)CMSG_DATA(cmsg))=fd; +#else + msg.msg_accrights = (char*)&fd; + msg.msg_accrightslen = sizeof(fd); +#endif + return sendmsg(sock,&msg,0)>=0?0:-1; +} +#endif diff --git a/pool/shard006/C/0118640_random_seed.c b/pool/shard006/C/0118640_random_seed.c new file mode 100644 index 0000000000000000000000000000000000000000..f7f4f938a234ba0c420bdc8102a9b9ea53fa6b50 --- /dev/null +++ b/pool/shard006/C/0118640_random_seed.c @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2009 Baptiste Coudurier + * + * 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 "config.h" + +#if HAVE_IO_H +#include +#endif +#if HAVE_CRYPTGENRANDOM +#include +#include +#endif + +#if HAVE_UNISTD_H +#include +#endif + +#include +#include +#include +#include +#include "avassert.h" +#include "internal.h" +#include "intreadwrite.h" +#include "timer.h" +#include "random_seed.h" +#include "sha.h" + +#ifndef TEST +#define TEST 0 +#endif + +static int read_random(uint32_t *dst, const char *file) +{ +#if HAVE_UNISTD_H + int fd = avpriv_open(file, O_RDONLY); + int err = -1; + + if (fd == -1) + return -1; + err = read(fd, dst, sizeof(*dst)); + close(fd); + + return err; +#else + return -1; +#endif +} + +static uint32_t get_generic_seed(void) +{ + uint8_t tmp[120]; + struct AVSHA *sha = (void*)tmp; + clock_t last_t = 0; + static uint64_t i = 0; + static uint32_t buffer[512] = { 0 }; + unsigned char digest[20]; + uint64_t last_i = i; + + av_assert0(sizeof(tmp) >= av_sha_size); + + if(TEST){ + memset(buffer, 0, sizeof(buffer)); + last_i = i = 0; + }else{ +#ifdef AV_READ_TIME + buffer[13] ^= AV_READ_TIME(); + buffer[41] ^= AV_READ_TIME()>>32; +#endif + } + + for (;;) { + clock_t t = clock(); + + if (last_t == t) { + buffer[i & 511]++; + } else { + buffer[++i & 511] += (t - last_t) % 3294638521U; + if (last_i && i - last_i > 4 || i - last_i > 64 || TEST && i - last_i > 8) + break; + } + last_t = t; + } + + if(TEST) + buffer[0] = buffer[1] = 0; + + av_sha_init(sha, 160); + av_sha_update(sha, (const uint8_t *)buffer, sizeof(buffer)); + av_sha_final(sha, digest); + return AV_RB32(digest) + AV_RB32(digest + 16); +} + +uint32_t av_get_random_seed(void) +{ + uint32_t seed; + +#if HAVE_CRYPTGENRANDOM + HCRYPTPROV provider; + if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { + BOOL ret = CryptGenRandom(provider, sizeof(seed), (PBYTE) &seed); + CryptReleaseContext(provider, 0); + if (ret) + return seed; + } +#endif + +#ifdef __amigaos4__ + if (read_random(&seed, "RANDOM:") == sizeof(seed)) + return seed; +#else + if (read_random(&seed, "/dev/urandom") == sizeof(seed)) + return seed; + if (read_random(&seed, "/dev/random") == sizeof(seed)) + return seed; +#endif + return get_generic_seed(); +} + +#if TEST +#undef printf +#define N 256 +#include + +int main(void) +{ + int i, j, retry; + uint32_t seeds[N]; + + for (retry=0; retry<3; retry++){ + for (i=0; i + * + * 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 +#include +#include +#include +#include + +#include "internal.h" + +static struct dentry *regmap_debugfs_root; + +/* Calculate the length of a fixed format */ +static size_t regmap_calc_reg_len(int max_val, char *buf, size_t buf_size) +{ + snprintf(buf, buf_size, "%x", max_val); + return strlen(buf); +} + +static ssize_t regmap_name_read_file(struct file *file, + char __user *user_buf, size_t count, + loff_t *ppos) +{ + struct regmap *map = file->private_data; + int ret; + char *buf; + + buf = kmalloc(PAGE_SIZE, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + ret = snprintf(buf, PAGE_SIZE, "%s\n", map->dev->driver->name); + if (ret < 0) { + kfree(buf); + return ret; + } + + ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret); + kfree(buf); + return ret; +} + +static const struct file_operations regmap_name_fops = { + .open = simple_open, + .read = regmap_name_read_file, + .llseek = default_llseek, +}; + +static ssize_t regmap_map_read_file(struct file *file, char __user *user_buf, + size_t count, loff_t *ppos) +{ + int reg_len, val_len, tot_len; + size_t buf_pos = 0; + loff_t p = 0; + ssize_t ret; + int i; + struct regmap *map = file->private_data; + char *buf; + unsigned int val; + + if (*ppos < 0 || !count) + return -EINVAL; + + buf = kmalloc(count, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + /* Calculate the length of a fixed format */ + reg_len = regmap_calc_reg_len(map->max_register, buf, count); + val_len = 2 * map->format.val_bytes; + tot_len = reg_len + val_len + 3; /* : \n */ + + for (i = 0; i < map->max_register + 1; i++) { + if (!regmap_readable(map, i)) + continue; + + if (regmap_precious(map, i)) + continue; + + /* If we're in the region the user is trying to read */ + if (p >= *ppos) { + /* ...but not beyond it */ + if (buf_pos >= count - 1 - tot_len) + break; + + /* Format the register */ + snprintf(buf + buf_pos, count - buf_pos, "%.*x: ", + reg_len, i); + buf_pos += reg_len + 2; + + /* Format the value, write all X if we can't read */ + ret = regmap_read(map, i, &val); + if (ret == 0) + snprintf(buf + buf_pos, count - buf_pos, + "%.*x", val_len, val); + else + memset(buf + buf_pos, 'X', val_len); + buf_pos += 2 * map->format.val_bytes; + + buf[buf_pos++] = '\n'; + } + p += tot_len; + } + + ret = buf_pos; + + if (copy_to_user(user_buf, buf, buf_pos)) { + ret = -EFAULT; + goto out; + } + + *ppos += buf_pos; + +out: + kfree(buf); + return ret; +} + +#undef REGMAP_ALLOW_WRITE_DEBUGFS +#ifdef REGMAP_ALLOW_WRITE_DEBUGFS +/* + * This can be dangerous especially when we have clients such as + * PMICs, therefore don't provide any real compile time configuration option + * for this feature, people who want to use this will need to modify + * the source code directly. + */ +static ssize_t regmap_map_write_file(struct file *file, + const char __user *user_buf, + size_t count, loff_t *ppos) +{ + char buf[32]; + size_t buf_size; + char *start = buf; + unsigned long reg, value; + struct regmap *map = file->private_data; + + buf_size = min(count, (sizeof(buf)-1)); + if (copy_from_user(buf, user_buf, buf_size)) + return -EFAULT; + buf[buf_size] = 0; + + while (*start == ' ') + start++; + reg = simple_strtoul(start, &start, 16); + while (*start == ' ') + start++; + if (strict_strtoul(start, 16, &value)) + return -EINVAL; + + /* Userspace has been fiddling around behind the kernel's back */ + add_taint(TAINT_USER); + + regmap_write(map, reg, value); + return buf_size; +} +#else +#define regmap_map_write_file NULL +#endif + +static const struct file_operations regmap_map_fops = { + .open = simple_open, + .read = regmap_map_read_file, + .write = regmap_map_write_file, + .llseek = default_llseek, +}; + +static ssize_t regmap_access_read_file(struct file *file, + char __user *user_buf, size_t count, + loff_t *ppos) +{ + int reg_len, tot_len; + size_t buf_pos = 0; + loff_t p = 0; + ssize_t ret; + int i; + struct regmap *map = file->private_data; + char *buf; + + if (*ppos < 0 || !count) + return -EINVAL; + + buf = kmalloc(count, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + /* Calculate the length of a fixed format */ + reg_len = regmap_calc_reg_len(map->max_register, buf, count); + tot_len = reg_len + 10; /* ': R W V P\n' */ + + for (i = 0; i < map->max_register + 1; i++) { + /* Ignore registers which are neither readable nor writable */ + if (!regmap_readable(map, i) && !regmap_writeable(map, i)) + continue; + + /* If we're in the region the user is trying to read */ + if (p >= *ppos) { + /* ...but not beyond it */ + if (buf_pos >= count - 1 - tot_len) + break; + + /* Format the register */ + snprintf(buf + buf_pos, count - buf_pos, + "%.*x: %c %c %c %c\n", + reg_len, i, + regmap_readable(map, i) ? 'y' : 'n', + regmap_writeable(map, i) ? 'y' : 'n', + regmap_volatile(map, i) ? 'y' : 'n', + regmap_precious(map, i) ? 'y' : 'n'); + + buf_pos += tot_len; + } + p += tot_len; + } + + ret = buf_pos; + + if (copy_to_user(user_buf, buf, buf_pos)) { + ret = -EFAULT; + goto out; + } + + *ppos += buf_pos; + +out: + kfree(buf); + return ret; +} + +static const struct file_operations regmap_access_fops = { + .open = simple_open, + .read = regmap_access_read_file, + .llseek = default_llseek, +}; + +void regmap_debugfs_init(struct regmap *map) +{ + const char *devname = "dummy"; + + if (map->dev) + devname = dev_name(map->dev); + + map->debugfs = debugfs_create_dir(devname, + regmap_debugfs_root); + if (!map->debugfs) { + dev_warn(map->dev, "Failed to create debugfs directory\n"); + return; + } + + debugfs_create_file("name", 0400, map->debugfs, + map, ®map_name_fops); + + if (map->max_register) { + debugfs_create_file("registers", 0400, map->debugfs, + map, ®map_map_fops); + debugfs_create_file("access", 0400, map->debugfs, + map, ®map_access_fops); + } + + if (map->cache_type) { + debugfs_create_bool("cache_only", 0400, map->debugfs, + &map->cache_only); + debugfs_create_bool("cache_dirty", 0400, map->debugfs, + &map->cache_dirty); + debugfs_create_bool("cache_bypass", 0400, map->debugfs, + &map->cache_bypass); + } +} + +void regmap_debugfs_exit(struct regmap *map) +{ + debugfs_remove_recursive(map->debugfs); +} + +void regmap_debugfs_initcall(void) +{ + regmap_debugfs_root = debugfs_create_dir("regmap", NULL); + if (!regmap_debugfs_root) { + pr_warn("regmap: Failed to create debugfs root\n"); + return; + } +} diff --git a/pool/shard006/C/0118646_ls_hgl-setup.c b/pool/shard006/C/0118646_ls_hgl-setup.c new file mode 100644 index 0000000000000000000000000000000000000000..0a2eea064159ce06cdaa800f88d3c7d0c4a43c5c --- /dev/null +++ b/pool/shard006/C/0118646_ls_hgl-setup.c @@ -0,0 +1,274 @@ +/* + * arch/arm/mach-orion5x/ls_hgl-setup.c + * + * Maintainer: Zhu Qingsen + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "mpp.h" + +/***************************************************************************** + * Linkstation LS-HGL Info + ****************************************************************************/ + +/* + * 256K NOR flash Device bus boot chip select + */ + +#define LS_HGL_NOR_BOOT_BASE 0xf4000000 +#define LS_HGL_NOR_BOOT_SIZE SZ_256K + +/***************************************************************************** + * 256KB NOR Flash on BOOT Device + ****************************************************************************/ + +static struct physmap_flash_data ls_hgl_nor_flash_data = { + .width = 1, +}; + +static struct resource ls_hgl_nor_flash_resource = { + .flags = IORESOURCE_MEM, + .start = LS_HGL_NOR_BOOT_BASE, + .end = LS_HGL_NOR_BOOT_BASE + LS_HGL_NOR_BOOT_SIZE - 1, +}; + +static struct platform_device ls_hgl_nor_flash = { + .name = "physmap-flash", + .id = 0, + .dev = { + .platform_data = &ls_hgl_nor_flash_data, + }, + .num_resources = 1, + .resource = &ls_hgl_nor_flash_resource, +}; + +/***************************************************************************** + * Ethernet + ****************************************************************************/ + +static struct mv643xx_eth_platform_data ls_hgl_eth_data = { + .phy_addr = 8, +}; + +/***************************************************************************** + * RTC 5C372a on I2C bus + ****************************************************************************/ + +static struct i2c_board_info __initdata ls_hgl_i2c_rtc = { + I2C_BOARD_INFO("rs5c372a", 0x32), +}; + +/***************************************************************************** + * LEDs attached to GPIO + ****************************************************************************/ + +#define LS_HGL_GPIO_LED_ALARM 2 +#define LS_HGL_GPIO_LED_INFO 3 +#define LS_HGL_GPIO_LED_FUNC 17 +#define LS_HGL_GPIO_LED_PWR 0 + + +static struct gpio_led ls_hgl_led_pins[] = { + { + .name = "alarm:red", + .gpio = LS_HGL_GPIO_LED_ALARM, + .active_low = 1, + }, { + .name = "info:amber", + .gpio = LS_HGL_GPIO_LED_INFO, + .active_low = 1, + }, { + .name = "func:blue:top", + .gpio = LS_HGL_GPIO_LED_FUNC, + .active_low = 1, + }, { + .name = "power:blue:bottom", + .gpio = LS_HGL_GPIO_LED_PWR, + }, +}; + +static struct gpio_led_platform_data ls_hgl_led_data = { + .leds = ls_hgl_led_pins, + .num_leds = ARRAY_SIZE(ls_hgl_led_pins), +}; + +static struct platform_device ls_hgl_leds = { + .name = "leds-gpio", + .id = -1, + .dev = { + .platform_data = &ls_hgl_led_data, + }, +}; + +/**************************************************************************** + * GPIO Attached Keys + ****************************************************************************/ +#define LS_HGL_GPIO_KEY_FUNC 15 +#define LS_HGL_GPIO_KEY_POWER 8 +#define LS_HGL_GPIO_KEY_AUTOPOWER 10 + +#define LS_HGL_SW_POWER 0x00 +#define LS_HGL_SW_AUTOPOWER 0x01 + +static struct gpio_keys_button ls_hgl_buttons[] = { + { + .code = KEY_OPTION, + .gpio = LS_HGL_GPIO_KEY_FUNC, + .desc = "Function Button", + .active_low = 1, + }, { + .type = EV_SW, + .code = LS_HGL_SW_POWER, + .gpio = LS_HGL_GPIO_KEY_POWER, + .desc = "Power-on Switch", + .active_low = 1, + }, { + .type = EV_SW, + .code = LS_HGL_SW_AUTOPOWER, + .gpio = LS_HGL_GPIO_KEY_AUTOPOWER, + .desc = "Power-auto Switch", + .active_low = 1, + }, +}; + +static struct gpio_keys_platform_data ls_hgl_button_data = { + .buttons = ls_hgl_buttons, + .nbuttons = ARRAY_SIZE(ls_hgl_buttons), +}; + +static struct platform_device ls_hgl_button_device = { + .name = "gpio-keys", + .id = -1, + .num_resources = 0, + .dev = { + .platform_data = &ls_hgl_button_data, + }, +}; + + +/***************************************************************************** + * SATA + ****************************************************************************/ +static struct mv_sata_platform_data ls_hgl_sata_data = { + .n_ports = 2, +}; + + +/***************************************************************************** + * Linkstation LS-HGL specific power off method: reboot + ****************************************************************************/ +/* + * On the Linkstation LS-HGL, the shutdown process is following: + * - Userland monitors key events until the power switch goes to off position + * - The board reboots + * - U-boot starts and goes into an idle mode waiting for the user + * to move the switch to ON position + */ + +static void ls_hgl_power_off(void) +{ + arm_machine_restart('h', NULL); +} + + +/***************************************************************************** + * General Setup + ****************************************************************************/ + +#define LS_HGL_GPIO_USB_POWER 9 +#define LS_HGL_GPIO_AUTO_POWER 10 +#define LS_HGL_GPIO_POWER 8 + +#define LS_HGL_GPIO_HDD_POWER 1 + +static unsigned int ls_hgl_mpp_modes[] __initdata = { + MPP0_GPIO, /* LED_PWR */ + MPP1_GPIO, /* HDD_PWR */ + MPP2_GPIO, /* LED_ALARM */ + MPP3_GPIO, /* LED_INFO */ + MPP4_UNUSED, + MPP5_UNUSED, + MPP6_GPIO, /* FAN_LCK */ + MPP7_GPIO, /* INIT */ + MPP8_GPIO, /* POWER */ + MPP9_GPIO, /* USB_PWR */ + MPP10_GPIO, /* AUTO_POWER */ + MPP11_UNUSED, /* LED_ETH (dummy) */ + MPP12_UNUSED, + MPP13_UNUSED, + MPP14_UNUSED, + MPP15_GPIO, /* FUNC */ + MPP16_UNUSED, + MPP17_GPIO, /* LED_FUNC */ + MPP18_UNUSED, + MPP19_UNUSED, + 0, +}; + +static void __init ls_hgl_init(void) +{ + /* + * Setup basic Orion functions. Need to be called early. + */ + orion5x_init(); + + orion5x_mpp_conf(ls_hgl_mpp_modes); + + /* + * Configure peripherals. + */ + orion5x_ehci0_init(); + orion5x_ehci1_init(); + orion5x_eth_init(&ls_hgl_eth_data); + orion5x_i2c_init(); + orion5x_sata_init(&ls_hgl_sata_data); + orion5x_uart0_init(); + orion5x_xor_init(); + + orion5x_setup_dev_boot_win(LS_HGL_NOR_BOOT_BASE, + LS_HGL_NOR_BOOT_SIZE); + platform_device_register(&ls_hgl_nor_flash); + + platform_device_register(&ls_hgl_button_device); + + platform_device_register(&ls_hgl_leds); + + i2c_register_board_info(0, &ls_hgl_i2c_rtc, 1); + + /* enable USB power */ + gpio_set_value(LS_HGL_GPIO_USB_POWER, 1); + + /* register power-off method */ + pm_power_off = ls_hgl_power_off; + + pr_info("%s: finished\n", __func__); +} + +MACHINE_START(LINKSTATION_LS_HGL, "Buffalo Linkstation LS-HGL") + /* Maintainer: Zhu Qingsen */ + .boot_params = 0x00000100, + .init_machine = ls_hgl_init, + .map_io = orion5x_map_io, + .init_early = orion5x_init_early, + .init_irq = orion5x_init_irq, + .timer = &orion5x_timer, + .fixup = tag_fixup_mem32, +MACHINE_END diff --git a/pool/shard006/C/0118647_lister.c b/pool/shard006/C/0118647_lister.c new file mode 100644 index 0000000000000000000000000000000000000000..1f86e9ef4a01f533380c9a4ad1b4acb96d858c95 --- /dev/null +++ b/pool/shard006/C/0118647_lister.c @@ -0,0 +1,368 @@ +/*############################################################################## + +FUNNNELWEB COPYRIGHT +==================== +FunnelWeb is a literate-programming macro preprocessor. + +Copyright (C) 1992 Ross N. Williams. + + Ross N. Williams + ross@spam.adelaide.edu.au + 16 Lerwick Avenue, Hazelwood Park 5066, Australia. + +This program is free software; you can redistribute it and/or modify +it under the terms of Version 2 of the GNU General Public License as +published by the Free Software Foundation. + +This program is distributed WITHOUT ANY WARRANTY; without even the implied +warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +See Version 2 of the GNU General Public License for more details. + +You should have received a copy of Version 2 of the GNU General Public +License along with this program. If not, you can FTP the license from +prep.ai.mit.edu/pub/gnu/COPYING-2 or write to the Free Software +Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +Section 2a of the license requires that all changes to this file be +recorded prominently in this file. Please record all changes here. + +Programmers: + RNW Ross N. Williams ross@spam.adelaide.edu.au + +Changes: + 07-May-1992 RNW Program prepared for release under GNU GPL V2. + +##############################################################################*/ + + +/******************************************************************************/ +/* LISTER.C */ +/******************************************************************************/ + +#include "style.h" + +#include "as.h" +#include "data.h" +#include "list.h" +#include "lister.h" +#include "machin.h" +#include "misc.h" +#include "table.h" +#include "writfile.h" + +/******************************************************************************/ + +#define LISTWIDTH 80 /* Nominal width of listing file. Can be wider. */ +#define INDENTQ 3 /* Indentation quantum for include files. */ +#define MESSMAXCH 200 /* Maximum number of characters in a message. */ +#define CTXINF 100 /* Special value that signals infinite context. */ +#define MAXLINES 10000 /* Maximum number of lines in input file. */ + +/******************************************************************************/ + +/* The following #defines and typedef define an enumerated type for message */ +/* kinds. There are four kinds of message, and we need a type for storing */ +/* this information. mess_k_t stands for message_kind_type. */ +/* We use #defines instead of enums as enums are not portable enough. */ +#define MESS_MES 1 +#define MESS_WAR 2 +#define MESS_ERR 3 +#define MESS_SEV 4 +typedef ubyte mess_k_t; + +/* We wish to store messages in a table with message positions as keys. */ +/* However, the table package will not tolerate duplicate keys. To solve this */ +/* problem, we create a new type 'unqpos_t' (unique position type) which has */ +/* not only a position but a serial number as well. */ +typedef struct + { + ps_t up_pos; + ulong up_serial; + } unqpos_t; + +/* The following structure stores a single message. As we are storing COPIES */ +/* of the messages, we impose a maximum limit (MESSMAXCH) to their length. */ +typedef struct + { + mess_k_t ms_kind; + char ms_text[MESSMAXCH+1]; + } mess_t; + +/******************************************************************************/ + +LOCVAR p_tb_t p_msgtab; /* The message table storing diagnostics. */ +LOCVAR ulong serial_next; /* Serial number for numbering messages. */ + +/******************************************************************************/ + +LOCAL int cmpuqpos P_((unqpos_t *,unqpos_t *)); +LOCAL int cmpuqpos(p1,p2) +/* Compare two unique positions for the table package and returns [-1,0,1]. */ +unqpos_t *p1; +unqpos_t *p2; +{ + long diff; + ubyte i; + + for (i=1; i<=3; i++) + { + switch (i) + { + case 1: diff= p1->up_pos.ps_line - p2->up_pos.ps_line; break; + case 2: diff= p1->up_pos.ps_column - p2->up_pos.ps_column; break; + case 3: diff= p1->up_serial - p2->up_serial; break; + default: as_bomb("cmpuqpos: Case defaulted."); + } + if (diff<0) + return -1; + else + if (diff>0) + return 1; + } + return 0; +} + +/******************************************************************************/ + +/* Converts a value of message kind type into a representative string. */ +/* This routine unused at present. +LOCAL char *mess_let P_((mess_k_t)); +LOCAL char *mess_let (mess_k) +mess_k_t mess_k; +{ + switch (mess_k) + { + case MESS_MES : return "M"; + case MESS_WAR : return "W"; + case MESS_ERR : return "E"; + case MESS_SEV : return "S"; + default: as_bomb("mess_let: Case defaulted."); + } + as_bomb("mess_let: Switch dropped out."); + return "Failure"; +} +*/ + +/******************************************************************************/ + +#define DUPMAX 200 + +LOCAL char *dup P_((int,uword)); +LOCAL char *dup(ch,count) +/* Returns a pointer to a STAVAR string containing 'count' copies of 'ch'. */ +/* Count must be in the range [0,DUPMAX]. The pointer returned always points */ +/* to the same address which is a 'STAVAR' inside this function. */ +int ch; +uword count; +{ + STAVAR char buffer[DUPMAX+1]; + + as_cold(count=DUPMAX"); + /* The IF in the following is just in case 'memset' is brain damaged. */ + if (count>0) memset(&buffer[0],ch,(size_t) count); + buffer[count]=EOS; + return &buffer[0]; +} + +/******************************************************************************/ + +LOCAL void mess_wri P_((p_wf_t,mess_t *,uword,uword)); +LOCAL void mess_wri(p_wf,p_mess,indent,column) +/* Writes message p_mess to file p_wf indented by INDENTQ*indent+column. */ +p_wf_t p_wf; +mess_t *p_mess; +uword indent; +uword column; +{ + switch (p_mess->ms_kind) + { + case MESS_MES : wf_wr(p_wf," "); break; + case MESS_WAR : wf_wr(p_wf," Warning"); break; + case MESS_ERR : wf_wr(p_wf," Error"); break; + case MESS_SEV : wf_wr(p_wf," Severe"); break; + default: as_bomb("mess_let: Case defaulted."); + } + wf_wr(p_wf,"|."); + wf_wr(p_wf,dup('.',indent*INDENTQ)); + wf_wr(p_wf,dup('.',column-1)); + wf_wr(p_wf,"^"); + wf_wr(p_wf,&p_mess->ms_text[0]); + wf_wr(p_wf,"\n"); +} + +/******************************************************************************/ + +LOCAL void line_wri P_((p_wf_t,ln_t *)); +LOCAL void line_wri(p_wf,p_line) +/* Writes the given line to the given output stream. */ +p_wf_t p_wf; +ln_t *p_line; +{ + char buffer[100]; + + /* The last line of the line list is the EOF marker line and to indicate */ + /* that it is not really part of the input file, we omit it's line number. */ + if (p_line->ln_global==ls_len(line_list)) + /*" 12345 12345| "*/ + sprintf(buffer," | "); + else + sprintf(buffer," %5lu %5lu| ", + (unsigned long) p_line->ln_global, + (unsigned long) p_line->ln_local); + wf_wr(p_wf,buffer); + wf_blk(p_wf,p_line->ln_body.sc_first,(size_t) + (p_line->ln_body.sc_last-p_line->ln_body.sc_first+1)); +} + +/******************************************************************************/ + +LOCAL void add_mess P_((ps_t *,mess_k_t,char *)); +LOCAL void add_mess(p_pos,messkind,p_string) +/* Creates a message record and places the message information in the */ +/* argument into the record. Inserts the record into the message table. */ +ps_t *p_pos; +mess_k_t messkind; +char *p_string; +{ + mess_t tempmess; + unqpos_t unqpos; + + tempmess.ms_kind=messkind; + as_cold(strlen(p_string)<=MESSMAXCH, + "lister.add_mess: Parameter message is too long."); + strcpy(tempmess.ms_text,p_string); + ASSIGN(unqpos.up_pos,*p_pos); + unqpos.up_serial=serial_next++; + tb_ins(p_msgtab,PV &unqpos,PV &tempmess); +} + +/******************************************************************************/ + +EXPORT void lr_ini P_((void)) +{ + /* Create a brand new empty message table. */ + p_msgtab=tb_cre(sizeof(unqpos_t),sizeof(mess_t),(p_kycm_t) cmpuqpos); + + /* Start the serial numbers at zero again. */ + serial_next=0; +} + +/******************************************************************************/ + +EXPORT void lr_mes(p_pos,s) +ps_t *p_pos; +char *s; +{ + add_mess(p_pos,MESS_MES,s); +} + +/******************************************************************************/ + +EXPORT void lr_war(p_pos,s) +ps_t *p_pos; +char *s; +{ + add_mess(p_pos,MESS_WAR,s); + num_war++; +} + +/******************************************************************************/ + +EXPORT void lr_err(p_pos,s) +ps_t *p_pos; +char *s; +{ + add_mess(p_pos,MESS_ERR,s); + num_err++; +} + +/******************************************************************************/ + +EXPORT void lr_sev(p_pos,s) +ps_t *p_pos; +char *s; +{ + add_mess(p_pos,MESS_SEV,s); + num_sev++; +} + +/******************************************************************************/ + +EXPORT void lr_gen(p_wf,ctx) +p_wf_t p_wf; +uword ctx; +{ + unqpos_t next_pos; /* Position of next message. */ + mess_t next_mes; /* Content of next message. */ + long prev_no; /* Global line number of previous message. */ + long next_no; /* Global line number of next message. */ + bool ingap; /* Controls issuance of gap markers in the listing. */ + long context=ctx; /* Signed version of the parameter. */ + + /* A context of CTXINF signals an infinite context. */ + if (context==CTXINF) context=MAXLINES; + + /* Write listing header. */ + wf_wr(p_wf,"\nGlobal Local| Input File\n"); + wf_wr(p_wf,dup('-',12));wf_wr(p_wf,"+"); + wf_wr(p_wf,dup('-',LISTWIDTH-13));wf_wr(p_wf,"\n"); + + /* Reset the line list and message table for reading. */ + ls_fir(line_list); + tb_fir(p_msgtab); + + /* Prime the variables ingap, prev_no, next_no, next_pos, and next_mes. */ + ingap=FALSE; prev_no = -(context+1); + if (tb_rea(p_msgtab,PV &next_pos,PV &next_mes)) + next_no=next_pos.up_pos.ps_line; + else + next_no=MAXLINES+context+1; + + while (TRUE) + {/* Process a single line per iteration. */ + ln_t *p_line; + + /* Grab the next line from the line list. */ + ls_nxt(line_list,PPV &p_line); + if (p_line==NULL) break; + + /* List the line if it is within context range of prev or next message. */ + if ((((long) p_line->ln_global) <= prev_no+context) || + (((long) p_line->ln_global) >= next_no-context)) + {line_wri(p_wf,p_line);ingap=FALSE;} + else + if (!ingap) + {wf_wr(p_wf,".................\n");ingap=TRUE;} + + /* Issue any messages that are about this line. */ + while (next_no == p_line->ln_global) + { + /* Write the current message. */ + mess_wri(p_wf,&next_mes,(uword) 0, + (uword) next_pos.up_pos.ps_column); + + /* Read the next message from the table. */ + prev_no=next_no; + if (tb_rea(p_msgtab,PV &next_pos,PV &next_mes)) + next_no=next_pos.up_pos.ps_line; + else + next_no=MAXLINES+context+1; + } + } /* End while */ + + /* Make sure that we have read to the end of the message table. */ + {bool result; + result=tb_rea(p_msgtab,PV &next_pos,PV &next_mes); + as_cold(!result, + "lr_gen: Messages remaining in message table after listing."); + } + + /* Write listing trailer. */ + wf_wr(p_wf,dup('-',12));wf_wr(p_wf,"+"); + wf_wr(p_wf,dup('-',LISTWIDTH-13));wf_wr(p_wf,"\n"); + wf_wl(p_wf,""); +} + +/******************************************************************************/ +/* End of LISTER.C */ +/******************************************************************************/ diff --git a/pool/shard006/C/0118648_energymon-msr.c b/pool/shard006/C/0118648_energymon-msr.c new file mode 100644 index 0000000000000000000000000000000000000000..65749d82ead21a86047f6c216de358213e2b448b --- /dev/null +++ b/pool/shard006/C/0118648_energymon-msr.c @@ -0,0 +1,261 @@ +/** + * Read energy from X86 MSRs (Model-Specific Registers). + * + * By default, the MSR on cpu0 is read. To configure other MSRs, set the + * ENERGYMON_MSRS environment variable with a comma-delimited list of CPU IDs, + * e.g.: + * export ENERGYMON_MSRS=0,4,8,12 + * + * @author Connor Imes + * @author Hank Hoffmann + */ + +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include +#include "energymon.h" +#include "energymon-msr.h" +#include "energymon-util.h" + +#ifdef ENERGYMON_DEFAULT +#include "energymon-default.h" +int energymon_get_default(energymon* em) { + return energymon_get_msr(em); +} +#endif + +#define MSR_RAPL_POWER_UNIT 0x606 + +/* Package RAPL Domain */ +#define MSR_PKG_ENERGY_STATUS 0x611 + +/* PP0 RAPL Domain */ +#define MSR_PP0_ENERGY_STATUS 0x639 + +/* PP1 RAPL Domain, may reflect to uncore devices */ +#define MSR_PP1_ENERGY_STATUS 0x641 + +/* DRAM RAPL Domain */ +#define MSR_DRAM_ENERGY_STATUS 0x619 + +typedef struct msr_info { + int fd; + unsigned int n_overflow; + uint64_t energy_last; + double energy_units; +} msr_info; + +typedef struct energymon_msr { + unsigned int msr_count; + msr_info msrs[]; +} energymon_msr; + +/** + * env_cores is consumed by strtok_r, so cannot be reused after this function. + */ +static inline unsigned int count_msrs(char* env_cores) { + unsigned int ncores; + char* saveptr; + char* tok = strtok_r(env_cores, ENERGYMON_MSRS_DELIMS, &saveptr); + for (ncores = 0; tok; ncores++) { + tok = strtok_r(NULL, ENERGYMON_MSRS_DELIMS, &saveptr); + } + return ncores; +} + +/** + * env_cores is consumed by strtok_r, so cannot be reused after this function. + * Returns the errno (if any) + */ +static inline int msr_info_init(msr_info* m, unsigned int n, char* env_cores) { + uint64_t msr_val; + unsigned int i; + unsigned int energy_status_units; + char filename[32]; + char* saveptr; + const char* tok = env_cores == NULL ? "0" : + strtok_r(env_cores, ENERGYMON_MSRS_DELIMS, &saveptr); + for (i = 0; tok && i < n; i++) { + m[i].n_overflow = 0; + m[i].energy_last = 0; + // first try msr_safe file + snprintf(filename, sizeof(filename), "/dev/cpu/%s/msr_safe", tok); + if ((m[i].fd = open(filename, O_RDONLY)) <= 0) { + // fall back on regular msr file + snprintf(filename, sizeof(filename), "/dev/cpu/%s/msr", tok); + if ((m[i].fd = open(filename, O_RDONLY)) <= 0) { + perror(filename); + return errno; + } + } + if (pread(m[i].fd, &msr_val, sizeof(msr_val), MSR_RAPL_POWER_UNIT) < 0) { + perror(filename); + return errno; + } + + // Energy related information (in Joules) is based on the multiplier, + // 1/2^ESU; where ESU is an unsigned integer represented by bits 12:8. + energy_status_units = ((msr_val >> 8) & 0x1f); + // At 5 bits only, 0 <= energy_status_units < 32, so bit shift instead, + // no need to use "pow" and require linking to math library + // m[i].energy_units = pow(0.5, energy_status_units); + m[i].energy_units = 1.0 / (1 << energy_status_units); + tok = env_cores == NULL ? NULL : + strtok_r(NULL, ENERGYMON_MSRS_DELIMS, &saveptr); + } + return 0; +} + +int energymon_init_msr(energymon* em) { + if (em == NULL || em->state != NULL) { + errno = EINVAL; + return -1; + } + + unsigned int ncores = 1; + char* tmp = NULL; + // get a delimited list of cores with MSRs to read from + const char* env_cores = getenv(ENERGYMON_MSR_ENV_VAR); + if (env_cores != NULL) { + if ((tmp = strdup(env_cores)) == NULL) { + return -1; + } + ncores = count_msrs(tmp); + free(tmp); + if (ncores == 0) { + errno = EINVAL; + perror("Parsing number of cores from " ENERGYMON_MSR_ENV_VAR " env var"); + return -1; + } + if ((tmp = strdup(env_cores)) == NULL) { + return -1; + } + } + + size_t size = sizeof(energymon_msr) + ncores * sizeof(msr_info); + energymon_msr* state = calloc(1, size); + if (state == NULL) { + free(tmp); + return -1; + } + state->msr_count = ncores; + + // open the MSR files + em->state = state; + int save_err = msr_info_init(state->msrs, ncores, tmp); + free(tmp); + if (save_err) { + energymon_finish_msr(em); + errno = save_err; + return -1; + } + + return 0; +} + +uint64_t energymon_read_total_msr(const energymon* em) { + if (em == NULL || em->state == NULL) { + errno = EINVAL; + return 0; + } + + unsigned int i; + uint64_t msr_val; + uint64_t total = 0; + energymon_msr* state = (energymon_msr*) em->state; + for (errno = 0, i = 0; i < state->msr_count && !errno; i++) { + if (pread(state->msrs[i].fd, &msr_val, sizeof(uint64_t), + MSR_PKG_ENERGY_STATUS) == sizeof(uint64_t)) { + // bits 31:0 hold the energy consumption counter, ignore upper 32 bits + msr_val &= 0xFFFFFFFF; + // overflows at 32 bits + if (msr_val < state->msrs[i].energy_last) { + state->msrs[i].n_overflow++; + } + state->msrs[i].energy_last = msr_val; + total += (msr_val + state->msrs[i].n_overflow * (uint64_t) UINT32_MAX) + * state->msrs[i].energy_units * 1000000; + } + } + return errno ? 0 : total; +} + +int energymon_finish_msr(energymon* em) { + if (em == NULL || em->state == NULL) { + errno = EINVAL; + return -1; + } + + int err_save = 0; + unsigned int i; + energymon_msr* state = em->state; + for (i = 0; i < state->msr_count; i++) { + if (state->msrs[i].fd > 0 && close(state->msrs[i].fd)) { + err_save = errno; + } + } + free(em->state); + em->state = NULL; + errno = err_save; + return errno ? -1 : 0; +} + +char* energymon_get_source_msr(char* buffer, size_t n) { + return energymon_strencpy(buffer, "X86 MSR", n); +} + +uint64_t energymon_get_interval_msr(const energymon* em) { + if (em == NULL) { + // we don't need to access em, but it's still a programming error + errno = EINVAL; + return 0; + } + return 1000; +} + +uint64_t energymon_get_precision_msr(const energymon* em) { + if (em == NULL || em->state == NULL) { + errno = EINVAL; + return 0; + } + energymon_msr* state = (energymon_msr*) em->state; + uint64_t prec; + unsigned int i; + if (state->msr_count == 0) { + prec = 1; + } else { + prec = UINT64_MAX; + for (i = 0; i < state->msr_count; i++) { + if (state->msrs[i].energy_units < prec) { + // 61 uJ by default + prec = (uint64_t) (state->msrs[i].energy_units * 1000000); + } + } + } + return prec ? prec : 1; +} + +int energymon_is_exclusive_msr(void) { + return 0; +} + +int energymon_get_msr(energymon* em) { + if (em == NULL) { + errno = EINVAL; + return -1; + } + em->finit = &energymon_init_msr; + em->fread = &energymon_read_total_msr; + em->ffinish = &energymon_finish_msr; + em->fsource = &energymon_get_source_msr; + em->finterval = &energymon_get_interval_msr; + em->fprecision = &energymon_get_precision_msr; + em->fexclusive = &energymon_is_exclusive_msr; + em->state = NULL; + return 0; +} diff --git a/pool/shard006/C/0118652_7-performance.c b/pool/shard006/C/0118652_7-performance.c new file mode 100644 index 0000000000000000000000000000000000000000..3a01a253b2039b682fed98f35160f70714eb46ba --- /dev/null +++ b/pool/shard006/C/0118652_7-performance.c @@ -0,0 +1,176 @@ +/* +* Copyright (c) Bull S.A. 2007 All Rights Reserved. +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of version 2 of the GNU General Public License as +* published by the Free Software Foundation. +* +* This program is distributed in the hope that it would be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +* +* Further, this software is distributed without any warranty that it is +* free of the rightful claim of any third person regarding infringement +* or the like. Any license provided herein, whether implied or +* otherwise, applies only to this software file. Patent licenses, if +* any, provided herein do not apply to combinations of this program with +* other software, or any other product whatsoever. +* +* You should have received a copy of the GNU General Public License along +* with this program; if not, write the Free Software Foundation, Inc., 59 +* Temple Place - Suite 330, Boston MA 02111-1307, USA. +* +* History: +* Created by: Cyril Lacabanne (Cyril.Lacabanne@bull.net) +* +*/ + +#include +#include +#include +#include + +//Standard define +#define PROCNUM 1 +#define VERSNUM 1 + +//Set number of test call +int maxIter; + +double average(double *tbl) +{ + //Return average of values in tbl + int i; + double rslt = 0; + + for (i = 0; i < maxIter; i++) + { + rslt += tbl[i]; + } + rslt = rslt / maxIter; + return rslt; +} + +double mini(double *tbl) +{ + //Return minimal of values in tbl + int i; + double rslt = tbl[0]; + + for (i = 0; i < maxIter; i++) + { + if (rslt > tbl[i]) + rslt = tbl[i]; + } + return rslt; +} + +double maxi(double *tbl) +{ + //Return maximal of values in tbl + int i; + double rslt = tbl[0]; + + for (i = 0; i < maxIter; i++) + { + if (rslt < tbl[i]) + rslt = tbl[i]; + } + return rslt; +} + +int main(int argn, char *argc[]) +{ + //Program parameters : argc[1] : HostName or Host IP + // argc[2] : Server Program Number + // argc[3] : Number of test call + // other arguments depend on test case + + //run_mode can switch into stand alone program or program launch by shell script + //1 : stand alone, debug mode, more screen information + //0 : launch by shell script as test case, only one printf -> result status + int run_mode = 0; + int test_status = 0; //Default test result set to FAILED + int i; + double *resultTbl; + struct timeval tv1,tv2; + struct timezone tz; + long long diff; + double rslt; + int progNum = atoi(argc[2]); + int sndVar = 0; + int recVar = -1; + CLIENT *client = NULL; + struct netconfig *nconf = NULL; + struct timeval tv; + enum clnt_stat cs; + + //Test initialisation + maxIter = atoi(argc[3]); + resultTbl = (double *)malloc(maxIter * sizeof(double)); + + nconf = getnetconfigent("udp"); + + if ((struct netconfig *)nconf == NULL) + { + //Test failed + printf("5\n"); + return 5; + } + + tv.tv_sec = 1; + tv.tv_usec = 1; + + client = clnt_tp_create_timed(argc[1], progNum, + VERSNUM, (struct netconfig *)nconf, &tv); + + if (client == NULL) + { + printf("5\n"); + return 5; + } + + //Call tested function several times + for (i = 0; i < maxIter; i++) + { + //Tic + gettimeofday(&tv1, &tz); + + //Call function + cs = clnt_call(client, PROCNUM, + (xdrproc_t)xdr_int, (char *)&sndVar, // xdr_in + (xdrproc_t)xdr_int, (char *)&recVar, // xdr_out + tv); + + //Toc + gettimeofday(&tv2, &tz); + + //Add function execution time (toc-tic) + diff = (tv2.tv_sec-tv1.tv_sec) * 1000000L + (tv2.tv_usec-tv1.tv_usec); + rslt = (double)diff / 1000; + + if (cs == RPC_SUCCESS) + { + resultTbl[i] = rslt; + } + else + { + test_status = 1; + break; + } + + if (run_mode) + { + fprintf(stderr, "lf time = %lf usecn\n", resultTbl[i]); + } + } + + //This last printf gives the result status to the tests suite + //normally should be 0: test has passed or 1: test has failed + printf("%d\n", test_status); + printf("%lf %d\n", average(resultTbl), maxIter); + printf("%lf\n", mini(resultTbl)); + printf("%lf\n", maxi(resultTbl)); + + return test_status; +} \ No newline at end of file diff --git a/pool/shard006/C/0118654_testDrawCard.c b/pool/shard006/C/0118654_testDrawCard.c new file mode 100644 index 0000000000000000000000000000000000000000..ace1a66a898ba278c937b514d5191bbdb35df25b --- /dev/null +++ b/pool/shard006/C/0118654_testDrawCard.c @@ -0,0 +1,94 @@ +#include "dominion.h" +#include "dominion_helpers.h" +#include +#include +#include +#include +#include "rngs.h" + +#define DEBUG 0 +#define NOISY_TEST 1 + +int checkDrawCard(int p, struct gameState *post) { + struct gameState pre; + memcpy (&pre, post, sizeof(struct gameState)); + + int r; + // printf ("drawCard PRE: p %d HC %d DeC %d DiC %d\n", + // p, pre.handCount[p], pre.deckCount[p], pre.discardCount[p]); + + r = drawCard (p, post); + + //printf ("drawCard POST: p %d HC %d DeC %d DiC %d\n", + // p, post->handCount[p], post->deckCount[p], post->discardCount[p]); + + if (pre.deckCount[p] > 0) { + pre.handCount[p]++; + pre.hand[p][pre.handCount[p]-1] = pre.deck[p][pre.deckCount[p]-1]; + pre.deckCount[p]--; + } else if (pre.discardCount[p] > 0) { + memcpy(pre.deck[p], post->deck[p], sizeof(int) * pre.discardCount[p]); + memcpy(pre.discard[p], post->discard[p], sizeof(int)*pre.discardCount[p]); + pre.hand[p][post->handCount[p]-1] = post->hand[p][post->handCount[p]-1]; + pre.handCount[p]++; + pre.deckCount[p] = pre.discardCount[p]-1; + pre.discardCount[p] = 0; + } + + assert (r == 0); + + assert(memcmp(&pre, post, sizeof(struct gameState)) == 0); +} + +int main () { + + int i, n, r, p, deckCount, discardCount, handCount; + + int k[10] = {adventurer, council_room, feast, gardens, mine, + remodel, smithy, village, baron, great_hall}; + + struct gameState G; + + printf ("Testing drawCard.\n"); + + printf ("RANDOM TESTS.\n"); + + SelectStream(2); + PutSeed(3); + + for (n = 0; n < 2000; n++) { + for (i = 0; i < sizeof(struct gameState); i++) { + ((char*)&G)[i] = floor(Random() * 256); + } + p = floor(Random() * 2); + G.deckCount[p] = floor(Random() * MAX_DECK); + G.discardCount[p] = floor(Random() * MAX_DECK); + G.handCount[p] = floor(Random() * MAX_HAND); + checkDrawCard(p, &G); + } + + printf ("ALL TESTS OK\n"); + + exit(0); + + printf ("SIMPLE FIXED TESTS.\n"); + for (p = 0; p < 2; p++) { + for (deckCount = 0; deckCount < 5; deckCount++) { + for (discardCount = 0; discardCount < 5; discardCount++) { + for (handCount = 0; handCount < 5; handCount++) { + memset(&G, 23, sizeof(struct gameState)); + r = initializeGame(2, k, 1, &G); + G.deckCount[p] = deckCount; + memset(G.deck[p], 0, sizeof(int) * deckCount); + G.discardCount[p] = discardCount; + memset(G.discard[p], 0, sizeof(int) * discardCount); + G.handCount[p] = handCount; + memset(G.hand[p], 0, sizeof(int) * handCount); + checkDrawCard(p, &G); + } + } + } + } + + return 0; +} diff --git a/pool/shard006/C/0118657_dbztool.c b/pool/shard006/C/0118657_dbztool.c new file mode 100644 index 0000000000000000000000000000000000000000..b2edf474f38466bfb013c35d8b20ba9f6d52bc6f --- /dev/null +++ b/pool/shard006/C/0118657_dbztool.c @@ -0,0 +1,91 @@ +#include +#include "his.h" + +#define DEBUG 1 +#undef DEBUG + +static datum content, inputkey, inputvalue; +static char dboutput[1025]; +static char dbinput[1025]; +static char valueinput[100]; + +enum { + SUBJECT, FROM, NAME +}; +char * +DBfetch(key) +char *key; +{ + int i; + char *tail, *ptr; + if (key == NULL) + return NULL; + sprintf(dbinput, "%.510s", key); + inputkey.dptr = dbinput; + inputkey.dsize = strlen(dbinput); + content.dptr = dboutput; + ptr = (char *) HISfilesfor(&inputkey, &content); + if (ptr == NULL) { + return NULL; + } + return ptr; +} +DBstore(key, paths) +char *key; +char *paths; +{ + int i; + char *tail; + time_t now; + time(&now); + if (key == NULL) + return -1; + sprintf(dbinput, "%.510s", key); + inputkey.dptr = dbinput; + inputkey.dsize = strlen(dbinput); + if (HISwrite(&inputkey, now, paths) == FALSE) { + return -1; + } else { + return 0; + } +} + +int +storeDB(mid, paths) +char *mid; +char *paths; +{ + char *key, *ptr; + int rel; + ptr = DBfetch(mid); + if (ptr != NULL) { + return 0; + } else { + return DBstore(mid, paths); + } +} +my_mkdir(idir, mode) +char *idir; +int mode; +{ + char buffer[LEN]; + char *ptr, *dir = buffer; + struct stat st; + strncpy(dir, idir, LEN - 1); + for (; dir != NULL && *dir;) { + ptr = (char *) strchr(dir, '/'); + if (ptr != NULL) { + *ptr = '\0'; + } + if (stat(dir, &st) != 0) { + if (mkdir(dir, mode) != 0) + return -1; + } + chdir(dir); + if (ptr != NULL) + dir = ptr + 1; + else + dir = ptr; + } + return 0; +} diff --git a/pool/shard006/C/0118658_rtpdec_svq3.c b/pool/shard006/C/0118658_rtpdec_svq3.c new file mode 100644 index 0000000000000000000000000000000000000000..b532f86947c2ddb5824f858d501a57099fa32130 --- /dev/null +++ b/pool/shard006/C/0118658_rtpdec_svq3.c @@ -0,0 +1,133 @@ +/* + * Sorenson-3 (SVQ3/SV3V) payload for RTP + * Copyright (c) 2010 Ronald S. Bultje + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * @brief RTP support for the SV3V (SVQ3) payload + * @author Ronald S. Bultje + * @see http://wiki.multimedia.cx/index.php?title=Sorenson_Video_3#Packetization + */ + +#include +#include "libavutil/intreadwrite.h" +#include "internal.h" +#include "rtp.h" +#include "rtpdec.h" +#include "rtpdec_formats.h" + +struct PayloadContext { + AVIOContext *pktbuf; + int64_t timestamp; +}; + +/** return 0 on packet, <0 on partial packet or error... */ +static int svq3_parse_packet (AVFormatContext *s, PayloadContext *sv, + AVStream *st, AVPacket *pkt, + uint32_t *timestamp, + const uint8_t *buf, int len, uint16_t seq, + int flags) +{ + int config_packet, start_packet, end_packet; + + if (len < 2) + return AVERROR_INVALIDDATA; + + config_packet = buf[0] & 0x40; + start_packet = buf[0] & 0x20; + end_packet = buf[0] & 0x10; + buf += 2; // ignore buf[1] + len -= 2; + + if (config_packet) { + + av_freep(&st->codec->extradata); + st->codec->extradata_size = 0; + + if (len < 2 || ff_alloc_extradata(st->codec, len + 8)) + return AVERROR_INVALIDDATA; + + memcpy(st->codec->extradata, "SEQH", 4); + AV_WB32(st->codec->extradata + 4, len); + memcpy(st->codec->extradata + 8, buf, len); + + /* We set codec_id to AV_CODEC_ID_NONE initially to + * delay decoder initialization since extradata is + * carried within the RTP stream, not SDP. Here, + * by setting codec_id to AV_CODEC_ID_SVQ3, we are signalling + * to the decoder that it is OK to initialize. */ + st->codec->codec_id = AV_CODEC_ID_SVQ3; + + return AVERROR(EAGAIN); + } + + if (start_packet) { + int res; + + if (sv->pktbuf) { + uint8_t *tmp; + avio_close_dyn_buf(sv->pktbuf, &tmp); + av_free(tmp); + } + if ((res = avio_open_dyn_buf(&sv->pktbuf)) < 0) + return res; + sv->timestamp = *timestamp; + } + + if (!sv->pktbuf) + return AVERROR_INVALIDDATA; + + avio_write(sv->pktbuf, buf, len); + + if (end_packet) { + int ret = ff_rtp_finalize_packet(pkt, &sv->pktbuf, st->index); + if (ret < 0) + return ret; + + *timestamp = sv->timestamp; + return 0; + } + + return AVERROR(EAGAIN); +} + +static PayloadContext *svq3_extradata_new(void) +{ + return av_mallocz(sizeof(PayloadContext)); +} + +static void svq3_extradata_free(PayloadContext *sv) +{ + if (sv->pktbuf) { + uint8_t *buf; + avio_close_dyn_buf(sv->pktbuf, &buf); + av_free(buf); + } + av_free(sv); +} + +RTPDynamicProtocolHandler ff_svq3_dynamic_handler = { + .enc_name = "X-SV3V-ES", + .codec_type = AVMEDIA_TYPE_VIDEO, + .codec_id = AV_CODEC_ID_NONE, // see if (config_packet) above + .alloc = svq3_extradata_new, + .free = svq3_extradata_free, + .parse_packet = svq3_parse_packet, +}; diff --git a/pool/shard006/C/0118659_smp-mt.c b/pool/shard006/C/0118659_smp-mt.c new file mode 100644 index 0000000000000000000000000000000000000000..d160b536f2648dafb0f6fcbab7fd27fd36b91d87 --- /dev/null +++ b/pool/shard006/C/0118659_smp-mt.c @@ -0,0 +1,310 @@ +/* + * This program is free software; you can distribute it and/or modify it + * under the terms of the GNU General Public License (Version 2) as + * published by the Free Software Foundation. + * + * This program is distributed in the hope 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. + * + * Copyright (C) 2004, 05, 06 MIPS Technologies, Inc. + * Elizabeth Clarke (beth@mips.com) + * Ralf Baechle (ralf@linux-mips.org) + * Copyright (C) 2006 Ralf Baechle (ralf@linux-mips.org) + */ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void __init smvp_copy_vpe_config(void) +{ + write_vpe_c0_status( + (read_c0_status() & ~(ST0_IM | ST0_IE | ST0_KSU)) | ST0_CU0); + + /* set config to be the same as vpe0, particularly kseg0 coherency alg */ + write_vpe_c0_config( read_c0_config()); + + /* make sure there are no software interrupts pending */ + write_vpe_c0_cause(0); + + /* Propagate Config7 */ + write_vpe_c0_config7(read_c0_config7()); + + write_vpe_c0_count(read_c0_count()); +} + +static unsigned int __init smvp_vpe_init(unsigned int tc, unsigned int mvpconf0, + unsigned int ncpu) +{ + if (tc > ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT)) + return ncpu; + + /* Deactivate all but VPE 0 */ + if (tc != 0) { + unsigned long tmp = read_vpe_c0_vpeconf0(); + + tmp &= ~VPECONF0_VPA; + + /* master VPE */ + tmp |= VPECONF0_MVP; + write_vpe_c0_vpeconf0(tmp); + + /* Record this as available CPU */ + set_cpu_possible(tc, true); + set_cpu_present(tc, true); + __cpu_number_map[tc] = ++ncpu; + __cpu_logical_map[ncpu] = tc; + } + + /* Disable multi-threading with TC's */ + write_vpe_c0_vpecontrol(read_vpe_c0_vpecontrol() & ~VPECONTROL_TE); + + if (tc != 0) + smvp_copy_vpe_config(); + + return ncpu; +} + +static void __init smvp_tc_init(unsigned int tc, unsigned int mvpconf0) +{ + unsigned long tmp; + + if (!tc) + return; + + /* bind a TC to each VPE, May as well put all excess TC's + on the last VPE */ + if (tc >= (((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT)+1)) + write_tc_c0_tcbind(read_tc_c0_tcbind() | ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT)); + else { + write_tc_c0_tcbind(read_tc_c0_tcbind() | tc); + + /* and set XTC */ + write_vpe_c0_vpeconf0(read_vpe_c0_vpeconf0() | (tc << VPECONF0_XTC_SHIFT)); + } + + tmp = read_tc_c0_tcstatus(); + + /* mark not allocated and not dynamically allocatable */ + tmp &= ~(TCSTATUS_A | TCSTATUS_DA); + tmp |= TCSTATUS_IXMT; /* interrupt exempt */ + write_tc_c0_tcstatus(tmp); + + write_tc_c0_tchalt(TCHALT_H); +} + +static void vsmp_send_ipi_single(int cpu, unsigned int action) +{ + int i; + unsigned long flags; + int vpflags; + +#ifdef CONFIG_MIPS_GIC_IPI + if (gic_present) { + gic_send_ipi_single(cpu, action); + return; + } +#endif + local_irq_save(flags); + + vpflags = dvpe(); /* can't access the other CPU's registers whilst MVPE enabled */ + + switch (action) { + case SMP_CALL_FUNCTION: + i = C_SW1; + break; + + case SMP_RESCHEDULE_YOURSELF: + default: + i = C_SW0; + break; + } + + /* 1:1 mapping of vpe and tc... */ + settc(cpu); + write_vpe_c0_cause(read_vpe_c0_cause() | i); + evpe(vpflags); + + local_irq_restore(flags); +} + +static void vsmp_send_ipi_mask(const struct cpumask *mask, unsigned int action) +{ + unsigned int i; + + for_each_cpu(i, mask) + vsmp_send_ipi_single(i, action); +} + +static void __cpuinit vsmp_init_secondary(void) +{ + struct cpuinfo_mips *c = ¤t_cpu_data; + + c->core = (read_c0_ebase() & 0x3ff) >> (fls(smp_num_siblings)-1); +#if defined(CONFIG_MIPS_MT_SMP) || defined(CONFIG_MIPS_MT_SMTC) + if (cpu_has_mipsmt) + c->vpe_id = (read_c0_tcbind() >> TCBIND_CURVPE_SHIFT) & TCBIND_CURVPE; +#endif + +#ifdef CONFIG_IRQ_GIC + /* This is Malta specific: IPI,performance and timer interrupts */ + if (gic_present) + change_c0_status(ST0_IM, STATUSF_IP3 | STATUSF_IP4 | + STATUSF_IP6 | STATUSF_IP7); + else +#endif + change_c0_status(ST0_IM, STATUSF_IP0 | STATUSF_IP1 | + STATUSF_IP6 | STATUSF_IP7); +} + +static void __cpuinit vsmp_smp_finish(void) +{ + pr_debug("SMPMT: CPU%d: vsmp_smp_finish\n", smp_processor_id()); + + /* CDFIXME: remove this? */ + write_c0_compare(read_c0_count() + (8* mips_hpt_frequency/HZ)); + +#ifdef CONFIG_MIPS_MT_FPAFF + /* If we have an FPU, enroll ourselves in the FPU-full mask */ + if (cpu_has_fpu) + cpu_set(smp_processor_id(), mt_fpu_cpumask); +#endif /* CONFIG_MIPS_MT_FPAFF */ + + local_irq_enable(); +} + +static void vsmp_cpus_done(void) +{ + pr_debug("SMPMT: CPU%d: vsmp_cpus_done\n", smp_processor_id()); +} + +/* + * Setup the PC, SP, and GP of a secondary processor and start it + * running! + * smp_bootstrap is the place to resume from + * __KSTK_TOS(idle) is apparently the stack pointer + * (unsigned long)idle->thread_info the gp + * assumes a 1:1 mapping of TC => VPE + */ +static void __cpuinit vsmp_boot_secondary(int cpu, struct task_struct *idle) +{ + struct thread_info *gp = task_thread_info(idle); + pr_debug("SMPMT: CPU%d: vsmp_boot_secondary cpu %d\n", + smp_processor_id(), cpu); + dvpe(); + set_c0_mvpcontrol(MVPCONTROL_VPC); + + settc(cpu); + + /* restart */ + write_tc_c0_tcrestart((unsigned long)&smp_bootstrap); + + /* enable the tc this vpe/cpu will be running */ + write_tc_c0_tcstatus((read_tc_c0_tcstatus() & ~TCSTATUS_IXMT) | TCSTATUS_A); + + write_tc_c0_tchalt(0); + + /* enable the VPE */ + write_vpe_c0_vpeconf0(read_vpe_c0_vpeconf0() | VPECONF0_VPA); + + /* stack pointer */ + write_tc_gpr_sp( __KSTK_TOS(idle)); + + /* global pointer */ + write_tc_gpr_gp((unsigned long)gp); + + local_flush_icache_range((unsigned long)gp, + (unsigned long)(gp + sizeof(struct thread_info))); + + /* finally out of configuration and into chaos */ + clear_c0_mvpcontrol(MVPCONTROL_VPC); + + evpe(EVPE_ENABLE); +} + +/* + * Common setup before any secondaries are started + * Make sure all CPU's are in a sensible state before we boot any of the + * secondaries + */ +static void __init vsmp_smp_setup(void) +{ + unsigned int mvpconf0, ntc, tc, ncpu = 0; + unsigned int nvpe; + + pr_debug("SMPMT: CPU%d: vsmp_smp_setup\n", smp_processor_id()); +#ifdef CONFIG_MIPS_MT_FPAFF + /* If we have an FPU, enroll ourselves in the FPU-full mask */ + if (cpu_has_fpu) + cpu_set(0, mt_fpu_cpumask); +#endif /* CONFIG_MIPS_MT_FPAFF */ + if (!cpu_has_mipsmt) + return; + + /* disable MT so we can configure */ + dvpe(); + dmt(); + + /* Put MVPE's into 'configuration state' */ + set_c0_mvpcontrol(MVPCONTROL_VPC); + + mvpconf0 = read_c0_mvpconf0(); + ntc = (mvpconf0 & MVPCONF0_PTC) >> MVPCONF0_PTC_SHIFT; + + nvpe = ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT) + 1; + smp_num_siblings = nvpe; + + /* we'll always have more TC's than VPE's, so loop setting everything + to a sensible state */ + for (tc = 0; tc <= ntc; tc++) { + settc(tc); + + smvp_tc_init(tc, mvpconf0); + ncpu = smvp_vpe_init(tc, mvpconf0, ncpu); + } + + /* Release config state */ + clear_c0_mvpcontrol(MVPCONTROL_VPC); + + /* We'll wait until starting the secondaries before starting MVPE */ + + printk(KERN_INFO "Detected %i available secondary CPU(s)\n", ncpu); +} + +static void __init vsmp_prepare_cpus(unsigned int max_cpus) +{ + pr_debug("SMPMT: CPU%d: vsmp_prepare_cpus %d\n", + smp_processor_id(), max_cpus); + mips_mt_set_cpuoptions(); +} + +struct plat_smp_ops vsmp_smp_ops = { + .send_ipi_single = vsmp_send_ipi_single, + .send_ipi_mask = vsmp_send_ipi_mask, + .init_secondary = vsmp_init_secondary, + .smp_finish = vsmp_smp_finish, + .cpus_done = vsmp_cpus_done, + .boot_secondary = vsmp_boot_secondary, + .smp_setup = vsmp_smp_setup, + .prepare_cpus = vsmp_prepare_cpus, +}; diff --git a/pool/shard006/C/0118661_Elbow.c b/pool/shard006/C/0118661_Elbow.c new file mode 100644 index 0000000000000000000000000000000000000000..6454832b589ef1dc7daaaad7e47f01e32c231472 --- /dev/null +++ b/pool/shard006/C/0118661_Elbow.c @@ -0,0 +1,151 @@ +/******************************************************************************* +* File Name: Elbow.c +* Version 2.10 +* +* Description: +* This file contains API to enable firmware control of a Pins component. +* +* Note: +* +******************************************************************************** +* Copyright 2008-2014, Cypress Semiconductor Corporation. All rights reserved. +* You may use this file only in accordance with the license, terms, conditions, +* disclaimers, and limitations in the end user license agreement accompanying +* the software package with which this file was provided. +*******************************************************************************/ + +#include "cytypes.h" +#include "Elbow.h" + +#define SetP4PinDriveMode(shift, mode) \ + do { \ + Elbow_PC = (Elbow_PC & \ + (uint32)(~(uint32)(Elbow_DRIVE_MODE_IND_MASK << (Elbow_DRIVE_MODE_BITS * (shift))))) | \ + (uint32)((uint32)(mode) << (Elbow_DRIVE_MODE_BITS * (shift))); \ + } while (0) + + +/******************************************************************************* +* Function Name: Elbow_Write +******************************************************************************** +* +* Summary: +* Assign a new value to the digital port's data output register. +* +* Parameters: +* prtValue: The value to be assigned to the Digital Port. +* +* Return: +* None +* +*******************************************************************************/ +void Elbow_Write(uint8 value) +{ + uint8 drVal = (uint8)(Elbow_DR & (uint8)(~Elbow_MASK)); + drVal = (drVal | ((uint8)(value << Elbow_SHIFT) & Elbow_MASK)); + Elbow_DR = (uint32)drVal; +} + + +/******************************************************************************* +* Function Name: Elbow_SetDriveMode +******************************************************************************** +* +* Summary: +* Change the drive mode on the pins of the port. +* +* Parameters: +* mode: Change the pins to one of the following drive modes. +* +* Elbow_DM_STRONG Strong Drive +* Elbow_DM_OD_HI Open Drain, Drives High +* Elbow_DM_OD_LO Open Drain, Drives Low +* Elbow_DM_RES_UP Resistive Pull Up +* Elbow_DM_RES_DWN Resistive Pull Down +* Elbow_DM_RES_UPDWN Resistive Pull Up/Down +* Elbow_DM_DIG_HIZ High Impedance Digital +* Elbow_DM_ALG_HIZ High Impedance Analog +* +* Return: +* None +* +*******************************************************************************/ +void Elbow_SetDriveMode(uint8 mode) +{ + SetP4PinDriveMode(Elbow__0__SHIFT, mode); +} + + +/******************************************************************************* +* Function Name: Elbow_Read +******************************************************************************** +* +* Summary: +* Read the current value on the pins of the Digital Port in right justified +* form. +* +* Parameters: +* None +* +* Return: +* Returns the current value of the Digital Port as a right justified number +* +* Note: +* Macro Elbow_ReadPS calls this function. +* +*******************************************************************************/ +uint8 Elbow_Read(void) +{ + return (uint8)((Elbow_PS & Elbow_MASK) >> Elbow_SHIFT); +} + + +/******************************************************************************* +* Function Name: Elbow_ReadDataReg +******************************************************************************** +* +* Summary: +* Read the current value assigned to a Digital Port's data output register +* +* Parameters: +* None +* +* Return: +* Returns the current value assigned to the Digital Port's data output register +* +*******************************************************************************/ +uint8 Elbow_ReadDataReg(void) +{ + return (uint8)((Elbow_DR & Elbow_MASK) >> Elbow_SHIFT); +} + + +/* If Interrupts Are Enabled for this Pins component */ +#if defined(Elbow_INTSTAT) + + /******************************************************************************* + * Function Name: Elbow_ClearInterrupt + ******************************************************************************** + * + * Summary: + * Clears any active interrupts attached to port and returns the value of the + * interrupt status register. + * + * Parameters: + * None + * + * Return: + * Returns the value of the interrupt status register + * + *******************************************************************************/ + uint8 Elbow_ClearInterrupt(void) + { + uint8 maskedStatus = (uint8)(Elbow_INTSTAT & Elbow_MASK); + Elbow_INTSTAT = maskedStatus; + return maskedStatus >> Elbow_SHIFT; + } + +#endif /* If Interrupts Are Enabled for this Pins component */ + + +/* [] END OF FILE */ diff --git a/pool/shard006/C/0118667_misc_error.c b/pool/shard006/C/0118667_misc_error.c new file mode 100644 index 0000000000000000000000000000000000000000..63a5482979a2eaab90e801e20ad8e5e4f6b9dada --- /dev/null +++ b/pool/shard006/C/0118667_misc_error.c @@ -0,0 +1,91 @@ +#include "gale/misc.h" +#include "gale/compat.h" +#include "gale/globals.h" + +#include +#include +#include +#include +#include +#include + +struct gale_errors { + oop_source *source; + gale_call_error *call; + void *data; +}; + +struct error_message { + enum gale_error severity; + struct gale_text text; +}; + +static void output(struct error_message *message) { + gale_print(stderr,1,G_("! ")); + gale_print(stderr,0,message->text); + gale_print(stderr,0,G_("\n")); + fflush(stderr); +} + +static void *on_error(oop_source *source,struct timeval when,void *data) { + struct error_message *message = (struct error_message *) data; + if (NULL != gale_global->error->call) + return gale_global->error->call( + message->severity,message->text, + gale_global->error->data); + output(message); + return OOP_CONTINUE; +} + +/** Set a different error handler. + * The function \a func will be called when an error is reported. + * \param oop The liboop source used for dispatch. + * \param func The function to call when there's an error. + * \param user The user-defined parameter to pass the function. */ +void gale_on_error(oop_source *oop,gale_call_error *func,void *user) { + gale_create(gale_global->error); + gale_global->error->source = oop; + gale_global->error->call = func; + gale_global->error->data = user; +} + +/** Report an error; terminate if \a severity is GALE_ERROR. + * \param severity The severity of the error (from ::gale_error). + * \param msg The error message to report. + * \param err If nonzero, a system errno value to look up. */ +void gale_alert(int severity,struct gale_text msg,int err) { + struct error_message *message; + struct gale_text stamp,prefix,label; + + stamp = gale_time_format(gale_time_now()); + prefix = null_text; + if (gale_global && gale_global->error_prefix) + prefix = gale_text_concat(2,G_(" "), + gale_text_from(NULL,gale_global->error_prefix,-1)); + + switch (severity) { + case GALE_NOTICE: label = G_(" notice"); break; + case GALE_WARNING: label = G_(" warning"); break; + case GALE_ERROR: label = G_(" error"); break; + } + + gale_create(message); + message->severity = severity; + if (0 != err) + message->text = gale_text_concat(7, + stamp,prefix,label,G_(" ("),msg,G_("): "), + gale_text_from(gale_global->enc_sys,strerror(err),-1)); + else + message->text = gale_text_concat(5, + stamp,prefix,label,G_(": "),msg); + + if (NULL == gale_global || NULL == gale_global->error) + output(message); + else + gale_global->error->source->on_time( + gale_global->error->source, + OOP_TIME_NOW, + on_error,message); + + if (GALE_ERROR == severity) exit(1); +} diff --git a/pool/shard006/C/0118670_ogd-activity.c b/pool/shard006/C/0118670_ogd-activity.c new file mode 100644 index 0000000000000000000000000000000000000000..37efe30e0b68047b83421b85e0a4feb6c28c3096 --- /dev/null +++ b/pool/shard006/C/0118670_ogd-activity.c @@ -0,0 +1,199 @@ +/* libopengdesktop + * Copyright (C) 2009/2012 Roberto -MadBob- Guido + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This 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 . + */ + +#include "ogd.h" +#include "ogd-activity.h" +#include "ogd-private-utils.h" + +#define OGD_ACTIVITY_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), \ + OGD_ACTIVITY_TYPE, OGDActivityPrivate)) + +/** + * SECTION: ogd-activity + * @short_description: description of what happens + * + * You can use #OGDActivity to see what is going on in friends network. For example who visited + * you homepage, who has send you a message and who uploaded a new content to the website. + * + * You can also post a microblogging message which is visible on you profile page and in the + * activities of your friends. + */ + +struct _OGDActivityPrivate { + gchar *authorid; + GDate *date; + OGD_ACTIVITY_CATEGORY category; + gchar *message; + gchar *link; +}; + +G_DEFINE_TYPE (OGDActivity, ogd_activity, OGD_OBJECT_TYPE); + +static void ogd_activity_finalize (GObject *obj) +{ + OGDActivity *activity; + + activity = OGD_ACTIVITY (obj); + + PTR_CHECK_FREE_NULLIFY (activity->priv->authorid); + DATE_CHECK_FREE_NULLIFY (activity->priv->date); + PTR_CHECK_FREE_NULLIFY (activity->priv->message); + PTR_CHECK_FREE_NULLIFY (activity->priv->link); +} + +static gboolean ogd_activity_fill_by_xml (OGDObject *obj, const xmlNode *xml, GError **error) +{ + xmlNode *cursor; + OGDActivity *activity; + + activity = OGD_ACTIVITY (obj); + + if (MYSTRCMP (xml->name, "activity") != 0) { + g_set_error (error, OGD_PARSING_ERROR_DOMAIN, OGD_XML_ERROR, "Invalid XML for OGDActivity"); + return FALSE; + } + + ogd_activity_finalize (G_OBJECT (obj)); + + for (cursor = xml->children; cursor; cursor = cursor->next) { + if (MYSTRCMP (cursor->name, "personid") == 0) + activity->priv->authorid = MYGETCONTENT (cursor); + else if (MYSTRCMP (cursor->name, "timestamp") == 0) + activity->priv->date = node_to_date (cursor); + else if (MYSTRCMP (cursor->name, "type") == 0) + activity->priv->category = (guint) node_to_num (cursor); + else if (MYSTRCMP (cursor->name, "message") == 0) + activity->priv->message = MYGETCONTENT (cursor); + else if (MYSTRCMP (cursor->name, "link") == 0) + activity->priv->link = MYGETCONTENT (cursor); + } + + return TRUE; +} + +static void ogd_activity_class_init (OGDActivityClass *klass) +{ + GObjectClass *gobject_class; + OGDObjectClass *ogd_object_class; + + g_type_class_add_private (klass, sizeof (OGDActivityPrivate)); + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = ogd_activity_finalize; + + ogd_object_class = OGD_OBJECT_CLASS (klass); + ogd_object_class->fill_by_xml = ogd_activity_fill_by_xml; +} + +static void ogd_activity_init (OGDActivity *item) +{ + item->priv = OGD_ACTIVITY_GET_PRIVATE (item); + memset (item->priv, 0, sizeof (OGDActivityPrivate)); +} + +/** + * ogd_activity_get_authorid: + * @activity: an #OGDActivity to read + * + * To retrieve the author of the @activity + * + * Return value: identifiers of the #OGDPerson who created the activity. You can use + ogd_object_fill_by_id() to obtain all informations + */ +const gchar* ogd_activity_get_authorid (OGDActivity *activity) +{ + return (const gchar*) activity->priv->authorid; +} + +/** + * ogd_activity_get_date: + * @activity: an #OGDActivity to read + * + * To retrieve the date of creation of the activity + * + * Return value: a #GDate for the date of creation of the activity + */ +const GDate* ogd_activity_get_date (OGDActivity *activity) +{ + return (const GDate*) activity->priv->date; +} + +/** + * ogd_activity_get_category: + * @activity: an #OGDActivity to read + * + * To retrieve the category of the activity + * + * Return value: identifier of the provided activity + */ +OGD_ACTIVITY_CATEGORY ogd_activity_get_category (OGDActivity *activity) +{ + return activity->priv->category; +} + +/** + * ogd_activity_get_message: + * @activity: an #OGDActivity to read + * + * To retrieve the message attached to the activity + * + * Return value: a string containing a message, or NULL if no message has been assigned + */ +const gchar* ogd_activity_get_message (OGDActivity *activity) +{ + return (const gchar*) activity->priv->message; +} + +/** + * ogd_activity_get_link: + * @activity: an #OGDActivity to read + * + * To retrieve the web link attached to the activity + * + * Return value: a string containing a web link, or NULL if no link has been assigned + */ +const gchar* ogd_activity_get_link (OGDActivity *activity) +{ + return (const gchar*) activity->priv->link; +} + +/** + * ogd_activity_set: + * @myself: return value of ogd_person_get_myself() + * @status: text to set as current status + * + * To update the status of the current user. Valid only if authentication is performed with + * ogd_provider_auth_user_and_pwd() + * + * Return value: %TRUE if status is correctly set, %FALSE otherwise + */ +gboolean ogd_activity_set (OGDPerson *myself, gchar *status) +{ + gboolean ret; + GHashTable *params; + OGDProvider *provider; + + provider = ogd_object_get_provider (OGD_OBJECT (myself)); + + params = g_hash_table_new (g_str_hash, g_str_equal); + g_hash_table_insert (params, "message", status); + + ret = ogd_provider_put (provider, "activity", params); + + g_hash_table_unref (params); + return ret; +} diff --git a/pool/shard006/C/0118671_smtinit.c b/pool/shard006/C/0118671_smtinit.c new file mode 100644 index 0000000000000000000000000000000000000000..dce67baefd90cfdd7040f5fb5e598654bb5fef76 --- /dev/null +++ b/pool/shard006/C/0118671_smtinit.c @@ -0,0 +1,98 @@ + + + +#include "h/types.h" +#include "h/fddi.h" +#include "h/smc.h" + +#ifndef lint +static const char ID_sccs[] = "@(#)smtinit.c 1.15 97/05/06 (C) SK " ; +#endif + +void init_fddi_driver(struct s_smc *smc, u_char *mac_addr); + +/* define global debug variable */ +#if defined(DEBUG) && !defined(DEBUG_BRD) +struct smt_debug debug; +#endif + +#ifndef MULT_OEM +#define OEMID(smc,i) oem_id[i] + extern u_char oem_id[] ; +#else /* MULT_OEM */ +#define OEMID(smc,i) smc->hw.oem_id->oi_mark[i] + extern struct s_oem_ids oem_ids[] ; +#endif /* MULT_OEM */ + +static void set_oem_spec_val(struct s_smc *smc) +{ + struct fddi_mib *mib ; + + mib = &smc->mib ; + + /* + * set IBM specific values + */ + if (OEMID(smc,0) == 'I') { + mib->fddiSMTConnectionPolicy = POLICY_MM ; + } +} + +int init_smt(struct s_smc *smc, u_char *mac_addr) +/* u_char *mac_addr; canonical address or NULL */ +{ + int p ; + +#if defined(DEBUG) && !defined(DEBUG_BRD) + debug.d_smt = 0 ; + debug.d_smtf = 0 ; + debug.d_rmt = 0 ; + debug.d_ecm = 0 ; + debug.d_pcm = 0 ; + debug.d_cfm = 0 ; + + debug.d_plc = 0 ; +#ifdef ESS + debug.d_ess = 0 ; +#endif +#ifdef SBA + debug.d_sba = 0 ; +#endif +#endif /* DEBUG && !DEBUG_BRD */ + + /* First initialize the ports mib->pointers */ + for ( p = 0; p < NUMPHYS; p ++ ) { + smc->y[p].mib = & smc->mib.p[p] ; + } + + set_oem_spec_val(smc) ; + (void) smt_set_mac_opvalues(smc) ; + init_fddi_driver(smc,mac_addr) ; /* HW driver */ + smt_fixup_mib(smc) ; /* update values that depend on s.sas */ + + ev_init(smc) ; /* event queue */ +#ifndef SLIM_SMT + smt_init_evc(smc) ; /* evcs in MIB */ +#endif /* no SLIM_SMT */ + smt_timer_init(smc) ; /* timer package */ + smt_agent_init(smc) ; /* SMT frame manager */ + + pcm_init(smc) ; /* PCM state machine */ + ecm_init(smc) ; /* ECM state machine */ + cfm_init(smc) ; /* CFM state machine */ + rmt_init(smc) ; /* RMT state machine */ + + for (p = 0 ; p < NUMPHYS ; p++) { + pcm(smc,p,0) ; /* PCM A state machine */ + } + ecm(smc,0) ; /* ECM state machine */ + cfm(smc,0) ; /* CFM state machine */ + rmt(smc,0) ; /* RMT state machine */ + + smt_agent_task(smc) ; /* NIF FSM etc */ + + PNMI_INIT(smc) ; /* PNMI initialization */ + + return(0) ; +} + diff --git a/pool/shard006/C/0118673_route-hpux.c b/pool/shard006/C/0118673_route-hpux.c new file mode 100644 index 0000000000000000000000000000000000000000..a22efdf19e7b11692c2d812429baa2290e7d9857 --- /dev/null +++ b/pool/shard006/C/0118673_route-hpux.c @@ -0,0 +1,180 @@ +/* + * route-hpux.c + * + * Copyright (c) 2000 Dug Song + * + * $Id: route-hpux.c 483 2004-01-14 04:52:11Z dugsong $ + */ + +#include "config.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include "dnet.h" + +#define ADDR_ISHOST(a) (((a)->addr_type == ADDR_TYPE_IP && \ + (a)->addr_bits == IP_ADDR_BITS) || \ + ((a)->addr_type == ADDR_TYPE_IP6 && \ + (a)->addr_bits == IP6_ADDR_BITS)) + +struct route_handle { + int fd; +}; + +route_t * +route_open(void) +{ + route_t *r; + + if ((r = calloc(1, sizeof(*r))) != NULL) { + if ((r->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) + return (route_close(r)); + } + return (r); +} + +int +route_add(route_t *r, const struct route_entry *entry) +{ + struct rtentry rt; + struct addr dst; + + memset(&rt, 0, sizeof(rt)); + rt.rt_flags = RTF_UP | RTF_GATEWAY; + + if (ADDR_ISHOST(&entry->route_dst)) { + rt.rt_flags |= RTF_HOST; + memcpy(&dst, &entry->route_dst, sizeof(dst)); + } else + addr_net(&entry->route_dst, &dst); + + if (addr_ntos(&dst, &rt.rt_dst) < 0 || + addr_ntos(&entry->route_gw, &rt.rt_gateway) < 0 || + addr_btom(entry->route_dst.addr_bits, &rt.rt_subnetmask, + IP_ADDR_LEN) < 0) + return (-1); + + return (ioctl(r->fd, SIOCADDRT, &rt)); +} + +int +route_delete(route_t *r, const struct route_entry *entry) +{ + struct rtentry rt; + struct addr dst; + + memset(&rt, 0, sizeof(rt)); + rt.rt_flags = RTF_UP; + + if (ADDR_ISHOST(&entry->route_dst)) { + rt.rt_flags |= RTF_HOST; + memcpy(&dst, &entry->route_dst, sizeof(dst)); + } else + addr_net(&entry->route_dst, &dst); + + if (addr_ntos(&dst, &rt.rt_dst) < 0 || + addr_btom(entry->route_dst.addr_bits, &rt.rt_subnetmask, + IP_ADDR_LEN) < 0) + return (-1); + + return (ioctl(r->fd, SIOCDELRT, &rt)); +} + +int +route_get(route_t *r, struct route_entry *entry) +{ + struct rtreq rtr; + + memset(&rtr, 0, sizeof(rtr)); + + /* XXX - gross hack for default route */ + if (entry->route_dst.addr_ip == IP_ADDR_ANY) { + rtr.rtr_destaddr = htonl(0x60060606); + rtr.rtr_subnetmask = 0xffffffff; + } else { + memcpy(&rtr.rtr_destaddr, &entry->route_dst.addr_ip, + IP_ADDR_LEN); + if (entry->route_dst.addr_bits < IP_ADDR_BITS) + addr_btom(entry->route_dst.addr_bits, + &rtr.rtr_subnetmask, IP_ADDR_LEN); + } + if (ioctl(r->fd, SIOCGRTENTRY, &rtr) < 0) + return (-1); + + if (rtr.rtr_gwayaddr == 0) { + errno = ESRCH; + return (-1); + } + entry->route_gw.addr_type = ADDR_TYPE_IP; + entry->route_gw.addr_bits = IP_ADDR_BITS; + memcpy(&entry->route_gw.addr_ip, &rtr.rtr_gwayaddr, IP_ADDR_LEN); + + return (0); +} + +#define MAX_RTENTRIES 256 /* XXX */ + +int +route_loop(route_t *r, route_handler callback, void *arg) +{ + struct nmparms nm; + struct route_entry entry; + mib_ipRouteEnt rtentries[MAX_RTENTRIES]; + int fd, i, n, ret; + + if ((fd = open_mib("/dev/ip", O_RDWR, 0 /* XXX */, 0)) < 0) + return (-1); + + nm.objid = ID_ipRouteTable; + nm.buffer = rtentries; + n = sizeof(rtentries); + nm.len = &n; + + if (get_mib_info(fd, &nm) < 0) { + close_mib(fd); + return (-1); + } + close_mib(fd); + + entry.route_dst.addr_type = entry.route_gw.addr_type = ADDR_TYPE_IP; + entry.route_dst.addr_bits = entry.route_gw.addr_bits = IP_ADDR_BITS; + n /= sizeof(*rtentries); + ret = 0; + + for (i = 0; i < n; i++) { + if (rtentries[i].Type != NMDIRECT && + rtentries[i].Type != NMREMOTE) + continue; + + entry.route_dst.addr_ip = rtentries[i].Dest; + addr_mtob(&rtentries[i].Mask, IP_ADDR_LEN, + &entry.route_dst.addr_bits); + entry.route_gw.addr_ip = rtentries[i].NextHop; + + if ((ret = callback(&entry, arg)) != 0) + break; + } + return (ret); +} + +route_t * +route_close(route_t *r) +{ + if (r != NULL) { + if (r->fd >= 0) + close(r->fd); + free(r); + } + return (NULL); +} diff --git a/pool/shard006/C/0118674_esound.c b/pool/shard006/C/0118674_esound.c new file mode 100644 index 0000000000000000000000000000000000000000..63e5b6aa2f7a0cb902075b910de4a7295c602c85 --- /dev/null +++ b/pool/shard006/C/0118674_esound.c @@ -0,0 +1,45 @@ +// Auto-generated from: audio/wrappers/esound.entries +// With android/scripts/gen-dll-wrapper.py +// DO NOT EDIT THIS FILE + +#include +#include + +/// +/// W R A P P E R P O I N T E R S +/// + +static int (*__dll_esd_open_sound)(const char * host) = 0; +static int (*__dll_esd_play_stream)(esd_format_t format, int rate, const char * host, const char * name) = 0; +static int (*__dll_esd_record_stream)(esd_format_t format, int rate, const char * host, const char * name) = 0; + +/// +/// W R A P P E R F U N C T I O N S +/// + +int esd_open_sound(const char * host) { + return __dll_esd_open_sound(host); +} + +int esd_play_stream(esd_format_t format, int rate, const char * host, const char * name) { + return __dll_esd_play_stream(format, rate, host, name); +} + +int esd_record_stream(esd_format_t format, int rate, const char * host, const char * name) { + return __dll_esd_record_stream(format, rate, host, name); +} + + +/// +/// I N I T I A L I Z A T I O N F U N C T I O N +/// + +int esound_dynlink_init(void* lib) { + __dll_esd_open_sound = (int(*)(const char * host))dlsym(lib, "esd_open_sound"); + if (!__dll_esd_open_sound) return -1; + __dll_esd_play_stream = (int(*)(esd_format_t format, int rate, const char * host, const char * name))dlsym(lib, "esd_play_stream"); + if (!__dll_esd_play_stream) return -1; + __dll_esd_record_stream = (int(*)(esd_format_t format, int rate, const char * host, const char * name))dlsym(lib, "esd_record_stream"); + if (!__dll_esd_record_stream) return -1; + return 0; +} diff --git a/pool/shard006/C/0118676_ft_lstremoveif.c b/pool/shard006/C/0118676_ft_lstremoveif.c new file mode 100644 index 0000000000000000000000000000000000000000..5794c160a6012b1bcc485adc6f66847240047e0b --- /dev/null +++ b/pool/shard006/C/0118676_ft_lstremoveif.c @@ -0,0 +1,40 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_lstremoveif.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: mfilipch +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/08/23 15:25:47 by mfilipch #+# #+# */ +/* Updated: 2016/08/23 15:25:50 by mfilipch ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +void ft_lstremoveif(t_list **begin_list, void *data_ref, int (*cmp)()) +{ + t_list *tmp; + t_list *tmp0; + + tmp = *begin_list; + while (*begin_list && (*cmp)((*begin_list)->content, data_ref) == 0 && tmp) + { + *begin_list = tmp->next; + free(tmp); + tmp = *begin_list; + } + if (tmp) + while (tmp && tmp->next) + { + if ((*cmp)(tmp->next->content, data_ref) == 0) + { + tmp0 = tmp->next; + tmp->next = tmp->next->next; + free(tmp0); + } + tmp = tmp->next; + } + else + *begin_list = NULL; +} diff --git a/pool/shard006/C/0118678_e_gamma_r.c b/pool/shard006/C/0118678_e_gamma_r.c new file mode 100644 index 0000000000000000000000000000000000000000..d1acaa6a1281809f5935204ce21011836bb258f3 --- /dev/null +++ b/pool/shard006/C/0118678_e_gamma_r.c @@ -0,0 +1,230 @@ +/* Implementation of gamma function according to ISO C. + Copyright (C) 1997-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1997. + + 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 + . */ + +#include +#include +#include + +/* Coefficients B_2k / 2k(2k-1) of x^-(2k-1) inside exp in Stirling's + approximation to gamma function. */ + +static const double gamma_coeff[] = + { + 0x1.5555555555555p-4, + -0xb.60b60b60b60b8p-12, + 0x3.4034034034034p-12, + -0x2.7027027027028p-12, + 0x3.72a3c5631fe46p-12, + -0x7.daac36664f1f4p-12, + }; + +#define NCOEFF (sizeof (gamma_coeff) / sizeof (gamma_coeff[0])) + +/* Return gamma (X), for positive X less than 184, in the form R * + 2^(*EXP2_ADJ), where R is the return value and *EXP2_ADJ is set to + avoid overflow or underflow in intermediate calculations. */ + +static double +gamma_positive (double x, int *exp2_adj) +{ + int local_signgam; + if (x < 0.5) + { + *exp2_adj = 0; + return __ieee754_exp (__ieee754_lgamma_r (x + 1, &local_signgam)) / x; + } + else if (x <= 1.5) + { + *exp2_adj = 0; + return __ieee754_exp (__ieee754_lgamma_r (x, &local_signgam)); + } + else if (x < 6.5) + { + /* Adjust into the range for using exp (lgamma). */ + *exp2_adj = 0; + double n = __ceil (x - 1.5); + double x_adj = x - n; + double eps; + double prod = __gamma_product (x_adj, 0, n, &eps); + return (__ieee754_exp (__ieee754_lgamma_r (x_adj, &local_signgam)) + * prod * (1.0 + eps)); + } + else + { + double eps = 0; + double x_eps = 0; + double x_adj = x; + double prod = 1; + if (x < 12.0) + { + /* Adjust into the range for applying Stirling's + approximation. */ + double n = __ceil (12.0 - x); +#if FLT_EVAL_METHOD != 0 + volatile +#endif + double x_tmp = x + n; + x_adj = x_tmp; + x_eps = (x - (x_adj - n)); + prod = __gamma_product (x_adj - n, x_eps, n, &eps); + } + /* The result is now gamma (X_ADJ + X_EPS) / (PROD * (1 + EPS)). + Compute gamma (X_ADJ + X_EPS) using Stirling's approximation, + starting by computing pow (X_ADJ, X_ADJ) with a power of 2 + factored out. */ + double exp_adj = -eps; + double x_adj_int = __round (x_adj); + double x_adj_frac = x_adj - x_adj_int; + int x_adj_log2; + double x_adj_mant = __frexp (x_adj, &x_adj_log2); + if (x_adj_mant < M_SQRT1_2) + { + x_adj_log2--; + x_adj_mant *= 2.0; + } + *exp2_adj = x_adj_log2 * (int) x_adj_int; + double ret = (__ieee754_pow (x_adj_mant, x_adj) + * __ieee754_exp2 (x_adj_log2 * x_adj_frac) + * __ieee754_exp (-x_adj) + * __ieee754_sqrt (2 * M_PI / x_adj) + / prod); + exp_adj += x_eps * __ieee754_log (x_adj); + double bsum = gamma_coeff[NCOEFF - 1]; + double x_adj2 = x_adj * x_adj; + for (size_t i = 1; i <= NCOEFF - 1; i++) + bsum = bsum / x_adj2 + gamma_coeff[NCOEFF - 1 - i]; + exp_adj += bsum / x_adj; + return ret + ret * __expm1 (exp_adj); + } +} + +double +__ieee754_gamma_r (double x, int *signgamp) +{ + int32_t hx; + u_int32_t lx; +#if FLT_EVAL_METHOD != 0 + volatile +#endif + double ret; + + EXTRACT_WORDS (hx, lx, x); + + if (__glibc_unlikely (((hx & 0x7fffffff) | lx) == 0)) + { + /* Return value for x == 0 is Inf with divide by zero exception. */ + *signgamp = 0; + return 1.0 / x; + } + if (__builtin_expect (hx < 0, 0) + && (u_int32_t) hx < 0xfff00000 && __rint (x) == x) + { + /* Return value for integer x < 0 is NaN with invalid exception. */ + *signgamp = 0; + return (x - x) / (x - x); + } + if (__glibc_unlikely ((unsigned int) hx == 0xfff00000 && lx == 0)) + { + /* x == -Inf. According to ISO this is NaN. */ + *signgamp = 0; + return x - x; + } + if (__glibc_unlikely ((hx & 0x7ff00000) == 0x7ff00000)) + { + /* Positive infinity (return positive infinity) or NaN (return + NaN). */ + *signgamp = 0; + return x + x; + } + + if (x >= 172.0) + { + /* Overflow. */ + *signgamp = 0; + ret = DBL_MAX * DBL_MAX; + return ret; + } + else + { + SET_RESTORE_ROUND (FE_TONEAREST); + if (x > 0.0) + { + *signgamp = 0; + int exp2_adj; + double tret = gamma_positive (x, &exp2_adj); + ret = __scalbn (tret, exp2_adj); + } + else if (x >= -DBL_EPSILON / 4.0) + { + *signgamp = 0; + ret = 1.0 / x; + } + else + { + double tx = __trunc (x); + *signgamp = (tx == 2.0 * __trunc (tx / 2.0)) ? -1 : 1; + if (x <= -184.0) + /* Underflow. */ + ret = DBL_MIN * DBL_MIN; + else + { + double frac = tx - x; + if (frac > 0.5) + frac = 1.0 - frac; + double sinpix = (frac <= 0.25 + ? __sin (M_PI * frac) + : __cos (M_PI * (0.5 - frac))); + int exp2_adj; + double tret = M_PI / (-x * sinpix + * gamma_positive (-x, &exp2_adj)); + ret = __scalbn (tret, -exp2_adj); + if (ret < DBL_MIN) + { + double force_underflow = ret * ret; + math_force_eval (force_underflow); + } + } + } + } + if (isinf (ret) && x != 0) + { + if (*signgamp < 0) + { + ret = -__copysign (DBL_MAX, ret) * DBL_MAX; + ret = -ret; + } + else + ret = __copysign (DBL_MAX, ret) * DBL_MAX; + return ret; + } + else if (ret == 0) + { + if (*signgamp < 0) + { + ret = -__copysign (DBL_MIN, ret) * DBL_MIN; + ret = -ret; + } + else + ret = __copysign (DBL_MIN, ret) * DBL_MIN; + return ret; + } + else + return ret; +} +strong_alias (__ieee754_gamma_r, __gamma_r_finite) diff --git a/pool/shard006/C/0118681_test_time.c b/pool/shard006/C/0118681_test_time.c new file mode 100644 index 0000000000000000000000000000000000000000..c253ade44b92e9f5597d83266347cda628a6e29a --- /dev/null +++ b/pool/shard006/C/0118681_test_time.c @@ -0,0 +1,163 @@ +/**************************************************************************** + * px4/tests/test_time.c + * + * Copyright (C) 2012 PX4 Development Team. 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 PX4 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 +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "tests_main.h" + +#include +#include +#include + + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/* emulate hrt_absolute_time using the cycle counter */ +static hrt_abstime +cycletime(void) +{ + static uint64_t basetime; + static uint32_t lasttime; + uint32_t cycles; + + cycles = *(unsigned long *)0xe0001004; + + if (cycles < lasttime) { + basetime += 0x100000000ULL; + } + + lasttime = cycles; + + return (basetime + cycles) / 168; /* XXX magic number */ +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: test_time + ****************************************************************************/ + +int test_time(int argc, char *argv[]) +{ + hrt_abstime h, c; + int64_t lowdelta, maxdelta = 0; + int64_t delta, deltadelta; + + /* enable the cycle counter */ + (*(unsigned long *)0xe000edfc) |= (1 << 24); /* DEMCR |= DEMCR_TRCENA */ + (*(unsigned long *)0xe0001000) |= 1; /* DWT_CTRL |= DWT_CYCCNT_ENA */ + + /* get an average delta between the two clocks - this should stay roughly the same */ + delta = 0; + + for (unsigned i = 0; i < 100; i++) { + uint32_t flags = px4_enter_critical_section(); + + h = hrt_absolute_time(); + c = cycletime(); + + px4_leave_critical_section(flags); + + delta += h - c; + } + + lowdelta = abs(delta / 100); + + /* loop checking the time */ + for (unsigned i = 0; i < 100; i++) { + + usleep(rand()); + + uint32_t flags = px4_enter_critical_section(); + + c = cycletime(); + h = hrt_absolute_time(); + + px4_leave_critical_section(flags); + + delta = abs(h - c); + deltadelta = abs(delta - lowdelta); + + if (deltadelta > maxdelta) { + maxdelta = deltadelta; + } + + if (deltadelta > 1000) { + fprintf(stderr, "h %" PRIu64 " c %" PRIu64 " d %" PRId64 "\n", h, c, delta - lowdelta); + } + } + + printf("Maximum jitter %" PRId64 "us\n", maxdelta); + + return 0; +} diff --git a/pool/shard006/C/0118682_applesmc.c b/pool/shard006/C/0118682_applesmc.c new file mode 100644 index 0000000000000000000000000000000000000000..c29558bdd58b8e509ce60f7bc029fef1c33a2d81 --- /dev/null +++ b/pool/shard006/C/0118682_applesmc.c @@ -0,0 +1,251 @@ +/* + * Apple SMC controller + * + * Copyright (c) 2007 Alexander Graf + * + * Authors: Alexander Graf + * Susanne Graf + * + * 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 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + * ***************************************************************** + * + * In all Intel-based Apple hardware there is an SMC chip to control the + * backlight, fans and several other generic device parameters. It also + * contains the magic keys used to dongle Mac OS X to the device. + * + * This driver was mostly created by looking at the Linux AppleSMC driver + * implementation and does not support IRQ. + * + */ + +#include "hw/hw.h" +#include "hw/isa/isa.h" +#include "ui/console.h" +#include "qemu/timer.h" + +/* #define DEBUG_SMC */ + +#define APPLESMC_DEFAULT_IOBASE 0x300 +/* data port used by Apple SMC */ +#define APPLESMC_DATA_PORT 0x0 +/* command/status port used by Apple SMC */ +#define APPLESMC_CMD_PORT 0x4 +#define APPLESMC_NR_PORTS 32 +#define APPLESMC_MAX_DATA_LENGTH 32 + +#define APPLESMC_READ_CMD 0x10 +#define APPLESMC_WRITE_CMD 0x11 +#define APPLESMC_GET_KEY_BY_INDEX_CMD 0x12 +#define APPLESMC_GET_KEY_TYPE_CMD 0x13 + +#ifdef DEBUG_SMC +#define smc_debug(...) fprintf(stderr, "AppleSMC: " __VA_ARGS__) +#else +#define smc_debug(...) do { } while(0) +#endif + +static char default_osk[64] = "This is a dummy key. Enter the real key " + "using the -osk parameter"; + +struct AppleSMCData { + uint8_t len; + const char *key; + const char *data; + QLIST_ENTRY(AppleSMCData) node; +}; + +struct AppleSMCStatus { + ISADevice dev; + uint32_t iobase; + uint8_t cmd; + uint8_t status; + uint8_t key[4]; + uint8_t read_pos; + uint8_t data_len; + uint8_t data_pos; + uint8_t data[255]; + uint8_t charactic[4]; + char *osk; + QLIST_HEAD(, AppleSMCData) data_def; +}; + +static void applesmc_io_cmd_writeb(void *opaque, uint32_t addr, uint32_t val) +{ + struct AppleSMCStatus *s = opaque; + + smc_debug("CMD Write B: %#x = %#x\n", addr, val); + switch(val) { + case APPLESMC_READ_CMD: + s->status = 0x0c; + break; + } + s->cmd = val; + s->read_pos = 0; + s->data_pos = 0; +} + +static void applesmc_fill_data(struct AppleSMCStatus *s) +{ + struct AppleSMCData *d; + + QLIST_FOREACH(d, &s->data_def, node) { + if (!memcmp(d->key, s->key, 4)) { + smc_debug("Key matched (%s Len=%d Data=%s)\n", d->key, + d->len, d->data); + memcpy(s->data, d->data, d->len); + return; + } + } +} + +static void applesmc_io_data_writeb(void *opaque, uint32_t addr, uint32_t val) +{ + struct AppleSMCStatus *s = opaque; + + smc_debug("DATA Write B: %#x = %#x\n", addr, val); + switch(s->cmd) { + case APPLESMC_READ_CMD: + if(s->read_pos < 4) { + s->key[s->read_pos] = val; + s->status = 0x04; + } else if(s->read_pos == 4) { + s->data_len = val; + s->status = 0x05; + s->data_pos = 0; + smc_debug("Key = %c%c%c%c Len = %d\n", s->key[0], + s->key[1], s->key[2], s->key[3], val); + applesmc_fill_data(s); + } + s->read_pos++; + break; + } +} + +static uint32_t applesmc_io_data_readb(void *opaque, uint32_t addr1) +{ + struct AppleSMCStatus *s = opaque; + uint8_t retval = 0; + + switch(s->cmd) { + case APPLESMC_READ_CMD: + if(s->data_pos < s->data_len) { + retval = s->data[s->data_pos]; + smc_debug("READ_DATA[%d] = %#hhx\n", s->data_pos, + retval); + s->data_pos++; + if(s->data_pos == s->data_len) { + s->status = 0x00; + smc_debug("EOF\n"); + } else + s->status = 0x05; + } + } + smc_debug("DATA Read b: %#x = %#x\n", addr1, retval); + + return retval; +} + +static uint32_t applesmc_io_cmd_readb(void *opaque, uint32_t addr1) +{ + struct AppleSMCStatus *s = opaque; + + smc_debug("CMD Read B: %#x\n", addr1); + return s->status; +} + +static void applesmc_add_key(struct AppleSMCStatus *s, const char *key, + int len, const char *data) +{ + struct AppleSMCData *def; + + def = g_malloc0(sizeof(struct AppleSMCData)); + def->key = key; + def->len = len; + def->data = data; + + QLIST_INSERT_HEAD(&s->data_def, def, node); +} + +static void qdev_applesmc_isa_reset(DeviceState *dev) +{ + struct AppleSMCStatus *s = DO_UPCAST(struct AppleSMCStatus, dev.qdev, dev); + struct AppleSMCData *d, *next; + + /* Remove existing entries */ + QLIST_FOREACH_SAFE(d, &s->data_def, node, next) { + QLIST_REMOVE(d, node); + } + + applesmc_add_key(s, "REV ", 6, "\x01\x13\x0f\x00\x00\x03"); + applesmc_add_key(s, "OSK0", 32, s->osk); + applesmc_add_key(s, "OSK1", 32, s->osk + 32); + applesmc_add_key(s, "NATJ", 1, "\0"); + applesmc_add_key(s, "MSSP", 1, "\0"); + applesmc_add_key(s, "MSSD", 1, "\0x3"); +} + +static int applesmc_isa_init(ISADevice *dev) +{ + struct AppleSMCStatus *s = DO_UPCAST(struct AppleSMCStatus, dev, dev); + + register_ioport_read(s->iobase + APPLESMC_DATA_PORT, 4, 1, + applesmc_io_data_readb, s); + register_ioport_read(s->iobase + APPLESMC_CMD_PORT, 4, 1, + applesmc_io_cmd_readb, s); + register_ioport_write(s->iobase + APPLESMC_DATA_PORT, 4, 1, + applesmc_io_data_writeb, s); + register_ioport_write(s->iobase + APPLESMC_CMD_PORT, 4, 1, + applesmc_io_cmd_writeb, s); + + if (!s->osk || (strlen(s->osk) != 64)) { + fprintf(stderr, "WARNING: Using AppleSMC with invalid key\n"); + s->osk = default_osk; + } + + QLIST_INIT(&s->data_def); + qdev_applesmc_isa_reset(&dev->qdev); + + return 0; +} + +static Property applesmc_isa_properties[] = { + DEFINE_PROP_HEX32("iobase", struct AppleSMCStatus, iobase, + APPLESMC_DEFAULT_IOBASE), + DEFINE_PROP_STRING("osk", struct AppleSMCStatus, osk), + DEFINE_PROP_END_OF_LIST(), +}; + +static void qdev_applesmc_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + ISADeviceClass *ic = ISA_DEVICE_CLASS(klass); + ic->init = applesmc_isa_init; + dc->reset = qdev_applesmc_isa_reset; + dc->props = applesmc_isa_properties; +} + +static const TypeInfo applesmc_isa_info = { + .name = "isa-applesmc", + .parent = TYPE_ISA_DEVICE, + .instance_size = sizeof(struct AppleSMCStatus), + .class_init = qdev_applesmc_class_init, +}; + +static void applesmc_register_types(void) +{ + type_register_static(&applesmc_isa_info); +} + +type_init(applesmc_register_types) diff --git a/pool/shard006/C/0118683_mutex-reentrance.c b/pool/shard006/C/0118683_mutex-reentrance.c new file mode 100644 index 0000000000000000000000000000000000000000..a8cbc70ef3185542058e5c888a9bb889c7332e10 --- /dev/null +++ b/pool/shard006/C/0118683_mutex-reentrance.c @@ -0,0 +1,95 @@ +/* (C) IT Sky Consulting GmbH 2014 + * http://www.it-sky-consulting.com/ + * Author: Karl Brodowsky + * Date: 2014-02-27 + * License: GPL v2 (See https://de.wikipedia.org/wiki/GNU_General_Public_License ) + */ + +/* test reentrance of lock */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +pthread_mutex_t mutex1; + +void usage(const char *argv0, const char *msg) { + if (msg != NULL && strlen(msg) > 0) { + printf("%s\n\n", msg); + } + printf("Usage\n\n"); + printf("%s -d\n mutex_type=PTHREAD_MUTEX_DEFAULT\n\n", argv0); + printf("%s -n\n mutex_type=PTHREAD_MUTEX_NORMAL\n\n", argv0); + printf("%s -e\n mutex_type=PTHREAD_MUTEX_ERRORCHECK\n\n", argv0); + printf("%s -r\n mutex_type=PTHREAD_MUTEX_RECURSIVE\n\n", argv0); + printf("%s -x\n no attribute used\n\n", argv0); + exit(1); +} + +int main(int argc, char *argv[]) { + int retcode; + + if (is_help_requested(argc, argv)) { + usage(argv[0], ""); + } + + pthread_mutexattr_t mutex_attr; + pthread_mutexattr_init(&mutex_attr); + char mutex_type = 'x'; // default + if (argc >= 2 && strlen(argv[1]) == 2 && argv[1][0] == '-') { + mutex_type = argv[1][1]; + } + switch (mutex_type) { + case 'd': + pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_DEFAULT); + break; + case 'n': + pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_NORMAL); + break; + case 'e': + pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ERRORCHECK); + break; + case 'r': + pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE); + break; + case 'x': + // use NULL; + break; + default: + usage(argv[0], "unknown option, supported: -d -n -e -r -x"); + } + if (mutex_type == 'x') { + retcode = pthread_mutex_init(&mutex1, NULL); + } else { + retcode = pthread_mutex_init(&mutex1, &mutex_attr); + } + handle_thread_error(retcode, "pthread_mutex_init", PROCESS_EXIT); + + printf("in parent thread: getting mutex1\n"); + retcode = pthread_mutex_lock(&mutex1); + handle_thread_error(retcode, "lock (1)", PROCESS_EXIT); + printf("in parent thread: got mutex1\n"); + printf("in parent thread: getting mutex1\n"); + retcode = pthread_mutex_lock(&mutex1); + handle_thread_error(retcode, "lock (2)", PROCESS_EXIT); + printf("in parent thread: got mutex1\n"); + sleep(5); + printf("in parent thread: releasing (1)\n"); + retcode = pthread_mutex_unlock(&mutex1); + handle_thread_error(retcode, "unlock (1)", PROCESS_EXIT); + printf("in parent thread: releasing (2)\n"); + retcode = pthread_mutex_unlock(&mutex1); + handle_thread_error(retcode, "unlock (2)", PROCESS_EXIT); + printf("in parent thread: done\n"); + + retcode = pthread_mutex_destroy(&mutex1); + handle_thread_error(retcode, "pthread_mutex_destroy", PROCESS_EXIT); + printf("done\n"); + exit(0); +} diff --git a/pool/shard006/C/0118687_main.c b/pool/shard006/C/0118687_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ac530875640b51e9a6e5678fec61da0a1552aec0 --- /dev/null +++ b/pool/shard006/C/0118687_main.c @@ -0,0 +1,31 @@ +#include +#include + + +int main() +{ + int n; + int *vec; + long long sum; + + // read the size of the vector + scanf("%d", &n); + + vec = malloc(n * sizeof(int)); + + // read 'n' numbers + for (int i = 0; i < n; ++i) + scanf("%d", &vec[i]); + + // calculate the sum of the elements in the vector + sum = 0; + for (int j = 0; j < n; ++j) + sum += vec[j]; + + // prints the sum and free memory + printf("%lld\n", sum); + + free(vec); + return 0; +} + diff --git a/pool/shard006/C/0118689_polynomial_solver.c b/pool/shard006/C/0118689_polynomial_solver.c new file mode 100644 index 0000000000000000000000000000000000000000..31c4f8649b478fa1749102ff7a246bfa290261ae --- /dev/null +++ b/pool/shard006/C/0118689_polynomial_solver.c @@ -0,0 +1,41 @@ +/* + normal way of calculating polynomial equation; + + for more effient implementation see polynomial_square.c + + */ + +// Copyright 2017 Karthik + +#include +#include + +double polynomial(double x, int n); + +int main(void) { + clock_t tic = clock(); + int n; + double x, poly; + + printf("enter the x value: "); + scanf("%lf", &x); + + poly = 3 * polynomial(x, 5) + 2 * polynomial(x, 4) - 5 * polynomial(x, 3) + - polynomial(x, 2) + 7 * polynomial(x, 1) - 6 * polynomial(x, 0); + + printf("%.2lf\n", poly); + + clock_t toc = clock(); + + printf("elapsed: %f seconds\n", (double)(toc-tic) / CLOCKS_PER_SEC); + return 0; +} + + +double polynomial(double x, int n) { + if (n == 0) + return 1; + else + return x * polynomial(x, n - 1); + +} diff --git a/pool/shard006/C/0118690_cola.c b/pool/shard006/C/0118690_cola.c new file mode 100644 index 0000000000000000000000000000000000000000..645195183f7e9e0ec97aedf7f44000efd1f5ef23 --- /dev/null +++ b/pool/shard006/C/0118690_cola.c @@ -0,0 +1,209 @@ +// cola.c +// Planificador de procesos +// +// Created by Juan Ortiz & Andres Buelvas on 29/1/17. +// Copyright © 2017 Juan Ortiz & Andres Buelvas. All rights reserved. +// + +#include +#include "cola.h" + +/* + Funcion que se encarga de crear un nodo a partir de procesos de entrada + Entrada proceso: proceso de tipo Proceso + Salida: retorna un nodo de tipo NodoProceso que la identifica +*/ +NodoProceso* CrearNodo (Proceso* proceso) { + NodoProceso* nodo = (NodoProceso *) malloc (sizeof (NodoProceso)); + nodo->proceso = proceso; + nodo->anterior = nodo->siguiente = NULL; + return nodo; +} + +/* + Funcion que se encarga eliminar o destruir el proceso perteneciente al nodo + Entrada nodo: es rl nodo de tipo NodoProceso que queremos eliminar +*/ +void DestruirNodo (NodoProceso* nodo) { + nodo->proceso = NULL; + nodo->anterior = nodo->siguiente = NULL; + free (nodo); +} + +/* + Funcion que se encarga de contruir un cola de prioridad en memoria dinamica + Salida: retorna un apuntador a una cola de prioridad +*/ +Cola* CrearCola () { + Cola* cola = (Cola *) malloc (sizeof (Cola)); + cola->primero = cola->cabeza = cola->ultimo = NULL; + return cola; +} + +/* + Funcion que se encarga de eliminar una cola de prioridad de la memoria dinamica + Entrada cola: cola de prioridad del planificar de tipo Cola +*/ +void DestruirCola (Cola* cola) { + while (cola->primero) + Eliminar (cola); + free (cola); +} + +/* + Funcion que se encarga de consultar un proceso a traves del PID que lo identifica + Entrada cola: cola de prioridad del planificar de tipo Cola + Entrada PID: identificador del proceso. + Salida: un apuntador a proceso +*/ +Proceso* consultarPID (Cola* cola, long PID) { + cola->cabeza = cola->primero; + while (cola->cabeza) { + if (cola->cabeza->proceso->PID == PID) + return cola->cabeza->proceso; + cola->cabeza = cola->cabeza->siguiente; + } + return NULL; +} + +/* + Funcion que se encarga de insertar el proceso dentro de la cola de prioridad + asignada + Entrada cola + Entrada PID: identificador del proceso. + Salida: un apuntador a proceso +*/ +void Encolar (Cola* cola, Proceso* proceso){ + NodoProceso* nodo = CrearNodo (proceso); + if (!cola->primero) { + cola->primero = nodo; + cola->ultimo = nodo; + } else { + cola->ultimo->siguiente = nodo; + nodo->anterior = cola->ultimo; + cola->ultimo = nodo; + } +} + +/* + Funcion que permite consultar el primer proceso de la cola + Entrada cola: cola de prioridad del planificador + Salida: apuntador al primer proceso +*/ +Proceso* Consultar (Cola* cola) { + if (cola->primero) { + return cola->primero->proceso; + } else { + return NULL; + } +} + +/* + Funcion que permite eliminar al primer proceso de la cola + Entrada cola: cola de prioridad del planificador +*/ +void Eliminar (Cola* cola) { + if (cola->primero) { + NodoProceso* eliminado = cola->primero; + cola->primero = cola->primero->siguiente; + + DestruirNodo (eliminado); + if (!cola->primero) + cola->ultimo = NULL; + else { + cola->primero->anterior = NULL; + cola->ultimo->siguiente = NULL; + } + } +} + +/* + Funcion que permite eliminar al ultimo proceso de la cola + Entrada: cola de prioridad del planificador +*/ +void EliminarU (Cola* cola) { + if (cola->ultimo) { + NodoProceso* eliminado = cola->ultimo; + cola->ultimo = cola->ultimo->anterior; + + DestruirNodo (eliminado); + if (!cola->ultimo) + cola->primero = NULL; + else { + cola->ultimo->siguiente = NULL; + cola->primero->anterior = NULL; + } + } +} + +/* + Funcion que permite eliminar y retornar el primer proceso de la cola + Entrada cola: cola de prioridad del planificador + Salida: apuntador al primer proceso de la cola +*/ +Proceso* EliminarPrimero (Cola* cola) { + if (cola->primero) { + NodoProceso* eliminado = cola->primero; + Proceso* proceso = cola->primero->proceso; + cola->primero = cola->primero->siguiente; + DestruirNodo (eliminado); + if (!cola -> primero) + cola->ultimo = NULL; + else { + cola->ultimo->siguiente = NULL; + cola->primero->anterior = NULL; + } + return proceso; + } + return NULL; +} + +/* + Funcion que permite eliminar un proceso de la cola de acuerdo a su PID + Entrada cola: cola de prioridad del planificador + Entrada PID: identificador del proceso +*/ +void EliminarProceso (Cola* cola, long PID) { + cola->cabeza = cola->primero; + NodoProceso* eliminado; + while (cola->cabeza) { + if (cola->cabeza->proceso->PID == PID){ + eliminado = cola->cabeza; + if (cola->cabeza == cola->primero) { + cola->primero = cola->primero->siguiente; + } else if (cola->cabeza == cola->ultimo) { + cola->ultimo = cola->ultimo->anterior; + } else { + eliminado->anterior->siguiente = eliminado->siguiente; + eliminado->siguiente->anterior = eliminado->anterior; + } + DestruirNodo (eliminado); + if (!cola->primero) + cola->ultimo = NULL; + else { + cola->ultimo->siguiente = NULL; + cola->primero->anterior = NULL; + } + } + cola->cabeza = cola->cabeza->siguiente; + } +} + +/* + Funcion que permite colocar al primer nodo de la cola al final del mismo + y se le asigna del valor de 'E' a su estado + Entrada cola: cola de prioridad del planificador + Salida: apuntador al proceso desplazado +*/ +Proceso* DesplazarNodo (Cola* cola) { + cola->ultimo->siguiente = cola->primero; + cola->ultimo->siguiente->anterior = cola->ultimo; + cola->ultimo = cola->ultimo->siguiente; + cola->primero = cola->primero->siguiente; + cola->primero->anterior = NULL; + cola->ultimo->siguiente = NULL; + + cola->ultimo->proceso->estado = 'E'; + + return cola->ultimo->proceso; +} \ No newline at end of file diff --git a/pool/shard006/C/0118698_hypervisor_vendor.c b/pool/shard006/C/0118698_hypervisor_vendor.c new file mode 100644 index 0000000000000000000000000000000000000000..9bcef8baadb2cdee63caa5da43df73588d3abd0c --- /dev/null +++ b/pool/shard006/C/0118698_hypervisor_vendor.c @@ -0,0 +1,193 @@ +/* + * Identify hypervisor vendor + * + * This is based on code from lscpu and virt-what. Unfortunately, neither + * of those is sufficient. lscpu doesn't detect many VM's, + * and virt-what is a shell script that has to be run as root. + * + * **** License **** + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * # + * A copy of the GNU General Public License is available as + * `/usr/share/common-licenses/GPL' in the Debian GNU/Linux distribution + * or on the World Wide Web at `http://www.gnu.org/copyleft/gpl.html'. + * You can also obtain it by writing to the Free Software Foundation, + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * Portions created by Vyatta are Copyright (C) 2011 Vyatta, Inc. + * All Rights Reserved. + */ + +#include +#include +#include + +#define PROC_XEN "/proc/xen" +#define PROC_XENCAP PROC_XEN "/capabilities" +#define PROC_PCIDEVS "/proc/bus/pci/devices" +#define SYS_HYPERVISOR "/sys/hypervisor/type" +#define SYS_DMI_VENDOR "/sys/class/dmi/id/sys_vendor" + +/* + * This CPUID leaf returns the information about the hypervisor. + * EAX : maximum input value for CPUID supported by the hypervisor. + * EBX, ECX, EDX : Hypervisor vendor ID signature. E.g. VMwareVMware. + */ +#define HYPERVISOR_INFO_LEAF 0x40000000 + +#if 0 +static inline void +cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, + unsigned int *ecx, unsigned int *edx) +{ + __asm__( +#if defined(__PIC__) && defined(__i386__) + /* x86 PIC cannot clobber ebx -- gcc bitches */ + "pushl %%ebx;" + "cpuid;" + "movl %%ebx, %%esi;" + "popl %%ebx;" + : "=S" (*ebx), +#else + "cpuid;" + : "=b" (*ebx), +#endif + "=a" (*eax), + "=c" (*ecx), + "=d" (*edx) + : "1" (op), "c"(0)); +} +#endif + + +/* Use CPUID instruction to find hypervisor vendor. + * This is the preferred method, but doesn't work with older + * hypervisors. + */ +static const char *get_hypervisor_cpuid(void) +{ +#if 0 + unsigned int eax = 0, ebx = 0, ecx = 0, edx = 0; + char hyper_vendor_id[13]; + + memset(hyper_vendor_id, 0, sizeof(hyper_vendor_id)); + + cpuid(HYPERVISOR_INFO_LEAF, &eax, &ebx, &ecx, &edx); + memcpy(hyper_vendor_id + 0, &ebx, 4); + memcpy(hyper_vendor_id + 4, &ecx, 4); + memcpy(hyper_vendor_id + 8, &edx, 4); + hyper_vendor_id[12] = '\0'; + + if (!hyper_vendor_id[0]) + return NULL; + + else if (!strncmp("XenVMMXenVMM", hyper_vendor_id, 12)) + return "Xen hvm"; + else if (!strncmp("KVMKVMKVM", hyper_vendor_id, 9)) + return "KVM"; + else if (!strncmp("Microsoft Hv", hyper_vendor_id, 12)) + return "Microsoft HyperV"; + else if (!strncmp("VMwareVMware", hyper_vendor_id, 12)) + return "VMware"; + else +#endif + return NULL; +} + +/* Use DMI vendor information */ +static const char *get_hypervisor_dmi(void) +{ + FILE *f = fopen(SYS_DMI_VENDOR, "r"); + char vendor_id[128]; + + if (!f) + return NULL; + + if (fgets(vendor_id, sizeof(vendor_id), f) == NULL) { + fclose(f); + return NULL; + } + fclose(f); + + if (!strncmp(vendor_id, "VMware", 6)) + return "VMware"; + /* Note: Hyper-V has same DMI, but different CPUID */ + else if (!strncmp(vendor_id, "Microsoft Corporation", 21)) + return "VirtualPC"; + else if (!strncmp(vendor_id, "innotek GmbH", 12)) + return "VirtualBox"; + else if (!strncmp(vendor_id, "Parallels", 9)) + return "Parallels"; + else + return NULL; +} + +static int +has_pci_device(int vendor, int device) +{ + FILE *f; + int num, fn, ven, dev; + int res = 1; + + f = fopen(PROC_PCIDEVS, "r"); + if (!f) + return 0; + + /* for more details about bus/pci/devices format see + * drivers/pci/proc.c in linux kernel + */ + while(fscanf(f, "%02x%02x\t%04x%04x\t%*[^\n]", + &num, &fn, &ven, &dev) == 4) { + + if (ven == vendor && dev == device) + goto found; + } + + res = 0; +found: + fclose(f); + return res; +} + +int main(int argc, char **argv) +{ + FILE *f; + const char *hvm; + char buf[256]; + + if ((hvm = get_hypervisor_cpuid()) != NULL || + (hvm = get_hypervisor_dmi()) != NULL) + printf("%s\n", hvm); + + /* Grotty code to look for old Xen */ + else if ((f = fopen(PROC_XENCAP, "r")) != NULL) { + int dom0 = 0; + + if (fscanf(f, "%s", buf) == 1 && + !strcmp(buf, "control_d")) + dom0 = 1; + printf("Xen %s\n", dom0 ? "dom0" : "domU"); + fclose(f); + } + else if ((f = fopen(SYS_HYPERVISOR, "r")) != NULL) { + if (fgets(buf, sizeof(buf), f) != NULL + && !strncmp(buf, "xen", 3)) + printf("Xen\n"); + fclose(f); + } + else if (has_pci_device(0x5853, 0x0001)) { + /* Xen full-virt on non-x86_64 */ + printf("Xen full\n"); + } + + /* print nothing if in real mode */ + return 0; +} diff --git a/pool/shard006/C/0118700_Read1DChunk.c b/pool/shard006/C/0118700_Read1DChunk.c new file mode 100644 index 0000000000000000000000000000000000000000..8f41d8fb13b7970cf5ca957e03fcffab75faf2ac --- /dev/null +++ b/pool/shard006/C/0118700_Read1DChunk.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include + +char *ncFileName; + +void testChunk(void) { + NcDataSet1D *dset; + NcVar1D *v; + double ix, istart, iend, istep; + FILE *outf = fopen("data_1D_chunk.dat", "w"); + if (!outf) { + printf("error: could not open output file for writing\n"); + return; + } + fprintf(outf, "# you may plot this file with gnuplot\n"); + + dset = ncDataSet1DNew(ncFileName, "time", EpAuto, LtFull, -1); + + v = ncVar1DNew(dset, "big_var_0", IpAkima, LtAuto); + + istart = dset->min; + iend = dset->max - 0.1 * (dset->max - dset->min); + istep = (iend - istart) / 20; + for (ix = istart; ix < iend; ix += istep) { + double x, start, end, step; + start = ix; + end = start + istep / 300; + step = 0.0001 * (end-start); + for (x = start; x < end; x+= step) { + fprintf(outf, "%10f\t%10f\n", x, ncVar1DGet(v, x)); + } + fprintf(outf, "\n"); + } + fclose(outf); + ncDataSet1DDumpStatistics(dset, NULL); + ncVar1DDumpStatistics(v, NULL); + ncVar1DFree(v); + ncDataSet1DFree(dset); +} + + +int main(int argc, char *argv[]) { + if (argc > 1) ncFileName = argv[1]; + else ncFileName = "testfilebig.nc"; + + testChunk(); + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C/0118706_adf_dh895xccvf_hw_data.c b/pool/shard006/C/0118706_adf_dh895xccvf_hw_data.c new file mode 100644 index 0000000000000000000000000000000000000000..7c6ed6bc8abf2fbbdffa83fe387f1db033b04621 --- /dev/null +++ b/pool/shard006/C/0118706_adf_dh895xccvf_hw_data.c @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: (BSD-3-Clause OR GPL-2.0-only) +/* Copyright(c) 2015 - 2020 Intel Corporation */ +#include +#include +#include +#include +#include "adf_dh895xccvf_hw_data.h" + +static struct adf_hw_device_class dh895xcciov_class = { + .name = ADF_DH895XCCVF_DEVICE_NAME, + .type = DEV_DH895XCCVF, + .instances = 0 +}; + +static u32 get_accel_mask(struct adf_hw_device_data *self) +{ + return ADF_DH895XCCIOV_ACCELERATORS_MASK; +} + +static u32 get_ae_mask(struct adf_hw_device_data *self) +{ + return ADF_DH895XCCIOV_ACCELENGINES_MASK; +} + +static u32 get_num_accels(struct adf_hw_device_data *self) +{ + return ADF_DH895XCCIOV_MAX_ACCELERATORS; +} + +static u32 get_num_aes(struct adf_hw_device_data *self) +{ + return ADF_DH895XCCIOV_MAX_ACCELENGINES; +} + +static u32 get_misc_bar_id(struct adf_hw_device_data *self) +{ + return ADF_DH895XCCIOV_PMISC_BAR; +} + +static u32 get_etr_bar_id(struct adf_hw_device_data *self) +{ + return ADF_DH895XCCIOV_ETR_BAR; +} + +static enum dev_sku_info get_sku(struct adf_hw_device_data *self) +{ + return DEV_SKU_VF; +} + +static u32 get_pf2vf_offset(u32 i) +{ + return ADF_DH895XCCIOV_PF2VF_OFFSET; +} + +static int adf_vf_int_noop(struct adf_accel_dev *accel_dev) +{ + return 0; +} + +static void adf_vf_void_noop(struct adf_accel_dev *accel_dev) +{ +} + +void adf_init_hw_data_dh895xcciov(struct adf_hw_device_data *hw_data) +{ + hw_data->dev_class = &dh895xcciov_class; + hw_data->num_banks = ADF_DH895XCCIOV_ETR_MAX_BANKS; + hw_data->num_rings_per_bank = ADF_ETR_MAX_RINGS_PER_BANK; + hw_data->num_accel = ADF_DH895XCCIOV_MAX_ACCELERATORS; + hw_data->num_logical_accel = 1; + hw_data->num_engines = ADF_DH895XCCIOV_MAX_ACCELENGINES; + hw_data->tx_rx_gap = ADF_DH895XCCIOV_RX_RINGS_OFFSET; + hw_data->tx_rings_mask = ADF_DH895XCCIOV_TX_RINGS_MASK; + hw_data->alloc_irq = adf_vf_isr_resource_alloc; + hw_data->free_irq = adf_vf_isr_resource_free; + hw_data->enable_error_correction = adf_vf_void_noop; + hw_data->init_admin_comms = adf_vf_int_noop; + hw_data->exit_admin_comms = adf_vf_void_noop; + hw_data->send_admin_init = adf_vf2pf_notify_init; + hw_data->init_arb = adf_vf_int_noop; + hw_data->exit_arb = adf_vf_void_noop; + hw_data->disable_iov = adf_vf2pf_notify_shutdown; + hw_data->get_accel_mask = get_accel_mask; + hw_data->get_ae_mask = get_ae_mask; + hw_data->get_num_accels = get_num_accels; + hw_data->get_num_aes = get_num_aes; + hw_data->get_etr_bar_id = get_etr_bar_id; + hw_data->get_misc_bar_id = get_misc_bar_id; + hw_data->get_pf2vf_offset = get_pf2vf_offset; + hw_data->get_sku = get_sku; + hw_data->enable_ints = adf_vf_void_noop; + hw_data->enable_pfvf_comms = adf_enable_vf2pf_comms; + hw_data->min_iov_compat_ver = ADF_PFVF_COMPAT_THIS_VERSION; + hw_data->dev_class->instances++; + adf_devmgr_update_class_index(hw_data); + adf_gen2_init_hw_csr_ops(&hw_data->csr_ops); +} + +void adf_clean_hw_data_dh895xcciov(struct adf_hw_device_data *hw_data) +{ + hw_data->dev_class->instances--; + adf_devmgr_update_class_index(hw_data); +} diff --git a/pool/shard006/C/0118707_midi.c b/pool/shard006/C/0118707_midi.c new file mode 100644 index 0000000000000000000000000000000000000000..7fefa5ff515a32dc6aa23ac2a03e2ab55fafd2f2 --- /dev/null +++ b/pool/shard006/C/0118707_midi.c @@ -0,0 +1,44 @@ +#include "vsurface.h" + +snd_seq_t *open_seq() { + + snd_seq_t *seq_handle; + int portid; + + if (snd_seq_open(&seq_handle, "hw", SND_SEQ_OPEN_OUTPUT, 0) < 0) { + fprintf(stderr, "Error opening ALSA sequencer.\n"); + exit(1); + } + + if(snd_seq_set_client_name(seq_handle, "vsurface") < 0){ + printf("Could not set client name"); + } + + if ((portid = snd_seq_create_simple_port(seq_handle, "vsurface", + SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, + SND_SEQ_PORT_TYPE_APPLICATION)) < 0) { + fprintf(stderr, "Error creating sequencer port.\n"); + exit(1); + } + + printf("portid: %d\n", portid); + return(seq_handle); +} + +void midi_action(snd_seq_t *seq, int control, int value){ + snd_seq_event_t ev; + + snd_seq_ev_clear(&ev); + snd_seq_ev_set_source(&ev, 0); + snd_seq_ev_set_subs(&ev); + snd_seq_ev_set_direct(&ev); + + ev.type = SND_SEQ_EVENT_CONTROLLER; + ev.data.control.channel = 0; + ev.data.control.param = control; + ev.data.control.value = value; + + + snd_seq_event_output(seq, &ev); + snd_seq_drain_output(seq); +} diff --git a/pool/shard006/C/0118712_util.c b/pool/shard006/C/0118712_util.c new file mode 100644 index 0000000000000000000000000000000000000000..a8999f207254d146203fee607faa40af98b079f7 --- /dev/null +++ b/pool/shard006/C/0118712_util.c @@ -0,0 +1,68 @@ + +#include +#include +#include "util.h" + +int INT_MIN(int a, int b){ + return a <= b? a: b; +} + +int INT_MAX(int a, int b){ + return a >= b? a: b; +} + + +int INT_POW(int base, int exp){ + int result = 1; + while (exp) + { + if (exp & 1) + result *= base; + exp /= 2; + base *= base; + } + return result; +} + +int INT_QUO(int a, int b){ + div_t d = div(a, b); + if(a<0 && d.rem != 0){ + d.quot += b<0? 1: -1; + } + return d.quot; +} + +int INT_REM(int a, int b){ + div_t d = div(a, b); + if(a<0 && d.rem != 0){ + d.rem += b<0? -b: b; + } + return d.rem; +} + + +char *load_file(const char *filename){ + FILE *f = fopen(filename, "r"); + long f_size; + char *f_buffer; + size_t n_read_bytes; + if(f == NULL){ + fprintf(stderr, "Could not open file: %s\n", filename); + return NULL; + } + + fseek(f, 0, SEEK_END); + f_size = ftell(f); + fseek(f, 0, SEEK_SET); + + f_buffer = malloc(f_size + 1); + if(f_buffer == NULL){ + fprintf(stderr, "Could not allocate buffer for file: %s (%li bytes)\n", filename, f_size); + fclose(f); + return NULL; + } + n_read_bytes = fread(f_buffer, 1, f_size, f); + fclose(f); + return f_buffer; +} + diff --git a/pool/shard006/C/0118715_load.c b/pool/shard006/C/0118715_load.c new file mode 100644 index 0000000000000000000000000000000000000000..fa204189304ceb87040d894f8574736cf2e06024 --- /dev/null +++ b/pool/shard006/C/0118715_load.c @@ -0,0 +1,236 @@ +#include +#include +#include +#include + +#include "extratrees.h" +#include "load.h" +#include "log.h" +#include "util.h" + + +char *new_err_str(char *msg, int line_count, char *line) { + char *error_str; + + line[20] = '\0'; + error_str = malloc(1024); + snprintf(error_str, 1024, + "parsing error on line %d: %s. line=%s...", + line_count, msg, line); + return error_str; +} + + +int parse_line(parse_state *ps, char *line, int line_count) { + int feat_id, n; + double val; + + if (sscanf(line, "%lf%n", &val, &n) != 1) { + ps->on_error(ps, new_err_str("label not found", line_count, line)); + return -1; + } + + line += n; + ps->on_new_label(ps, val); + + while(sscanf(line, "%d : %lf%n", &feat_id, &val, &n) == 2) { + line += n; + ps->on_new_feature(ps, feat_id, val); + } + + while(isspace(*line)) line++; + + if (*line != '\0') { + ps->on_error(ps, new_err_str("feature not found", line_count, line)); + return -1; + } + + return 0; +} + + +void parse_libsvm_file(parse_state *ps, FILE *f, int bufsize) { + char *buffer, *bp; + int line_count = 0; + + rewind(f); + bp = buffer = malloc(bufsize); + check_mem(buffer); + + while(1) { + int c = fgetc(f); + if (c == '\n' || c == EOF) { + if (bp != buffer) { + line_count += 1; + *bp = '\0'; + if (parse_line(ps, buffer, line_count)) break; + bp = buffer; + } + if (c == EOF) break; + } else { + if ((bp - buffer) >= bufsize) { + size_t newbufsize = bufsize * 4; + buffer = realloc(buffer, newbufsize); + check_mem(buffer); + bp = buffer + bufsize; + bufsize = newbufsize; + } + *bp++ = c; + } + } + free(buffer); + return; + + exit: + if (buffer) free(buffer); + ps->on_error(ps, "malloc failed"); + return; +} + + +// ----- size_parser ----- + +typedef struct size_parser { + parse_state ops; + char *error_msg; + int n_samples, n_features; +} size_parser; + +void size_parser_on_error(parse_state *ps, char *error_msg) { + size_parser *sp = (size_parser *) ps; + sp->error_msg = error_msg; +} + +void size_parser_on_new_label(parse_state *ps, double val) { + UNUSED(val); + size_parser *sp = (size_parser *) ps; + sp->n_samples += 1; +} + +void size_parser_on_new_feature(parse_state *ps, int fid, double val) { + UNUSED(val); + size_parser *sp = (size_parser *) ps; + if (fid > sp->n_features) + sp->n_features = fid; +} + +void size_parser_init(size_parser *sp) { + sp->ops.on_error = size_parser_on_error; + sp->ops.on_new_label = size_parser_on_new_label; + sp->ops.on_new_feature = size_parser_on_new_feature; + sp->n_features = 0; + sp->n_samples = 0; + sp->error_msg = NULL; +} + +void size_parser_destroy(size_parser *sp) { + if(sp->error_msg) free(sp->error_msg); +} + + +// ----- load_parser ----- + +typedef struct load_parser { + parse_state ops; + bool error_flag; + float *vectors; + double *labels; + int sample_idx; + int n_samples; + int n_features; +} load_parser; + +void load_parser_on_error(parse_state *ps, char *error_msg) { + UNUSED(error_msg); + load_parser *lp = (load_parser *) ps; + lp->error_flag = true; +} + +void load_parser_on_new_label(parse_state *ps, double val) { + load_parser *lp = (load_parser *) ps; + lp->sample_idx += 1; + lp->labels[lp->sample_idx] = val; +} + +void load_parser_on_new_feature(parse_state *ps, int fid, double val) { + load_parser *lp = (load_parser *) ps; + lp->vectors[lp->sample_idx + lp->n_samples * (fid-1)] = val; +} + +int load_parser_init(load_parser *lp, int n_features, int n_samples) { + float *vectors; + double *labels; + + lp->ops.on_error = load_parser_on_error; + lp->ops.on_new_label = load_parser_on_new_label; + lp->ops.on_new_feature = load_parser_on_new_feature; + lp->error_flag = false; + lp->sample_idx = -1; + lp->n_samples = n_samples; + lp->n_features = n_features; + + vectors = calloc(n_samples * n_features, sizeof(float)); + check_mem(vectors); + labels = calloc(n_samples, sizeof(double)); + check_mem(labels); + + lp->vectors = vectors; + lp->labels = labels; + return 0; + + exit: + lp->error_flag = true; + return -1; +} + +void load_parser_destroy(load_parser* lp) { + if(lp->error_flag) { + if(lp->vectors) free(lp->vectors); + if(lp->labels) free(lp->labels); + } +} + + +ET_problem *ET_load_libsvm_file(char *fname) { + FILE *f; + size_parser *sp = NULL; + load_parser *lp = NULL; + ET_problem *prob = NULL; + + f = fopen(fname, "r"); + check(f, "Could not open %s.", fname); + + sp = calloc(1, sizeof(size_parser)); + check_mem(sp); + size_parser_init(sp); + parse_libsvm_file((parse_state *) sp, f, PARSE_BUF_SIZE); + check(!sp->error_msg, "%s", sp->error_msg); + + lp = calloc(1, sizeof(load_parser)); + check_mem(lp); + check(! load_parser_init(lp, sp->n_features, sp->n_samples), + "load_parser could not allocate enough memory."); + + parse_libsvm_file((parse_state *) lp, f, PARSE_BUF_SIZE); + check(! lp->error_flag, "Unexpected failure in loading phase."); + + prob = malloc(sizeof(ET_problem)); + check_mem(prob); + + prob->vectors = lp->vectors; + prob->labels = lp->labels; + prob->n_features = sp->n_features; + prob->n_samples = sp->n_samples; + + exit: + if (sp) { + size_parser_destroy(sp); + free(sp); + } + if (lp) { + load_parser_destroy(lp); + free(lp); + } + if(f) fclose(f); + return prob; +} diff --git a/pool/shard006/C/0118719_nativesupport.c b/pool/shard006/C/0118719_nativesupport.c new file mode 100644 index 0000000000000000000000000000000000000000..97e0496bfa71826f6b58d38bbba244252122dc7b --- /dev/null +++ b/pool/shard006/C/0118719_nativesupport.c @@ -0,0 +1,176 @@ +#include +#include + +#include "libjtype/defs.h" +#include "core/registers.h" +#include "core/memory.h" +#include "dynarec/arch/x86/nativesupport.h" +#include "core/execute.h" +#include "libjtype/hash.h" +#include "dynarec/block.h" + +#ifdef ROHLE +#include "mach/riscos/fakesys.h" +#endif + +#if defined(ROHLE) || defined(RISCOSE) +uint5 native_execution = 0; +#endif + +void nativesupport_invoke2(machineinfo* machine, uint3* code) +{ + registerinfo* reg = machine->reg; + + fprintf(stderr, "--> entering native code\n"); + +#if defined(ROHLE) || defined(RISCOSE) + native_execution = 1; +#endif + + asm __volatile__( + "pushl %%ebp\n\t" + "movl %0,%%ebp\n\t" + "call *%1\n\t" + "popl %%ebp" + : + : "a" (reg), "b" (code) + : "cx", "dx", "si", "di", "memory"); + +#if defined(ROHLE) || defined(RISCOSE) + native_execution = 0; +#endif + + fprintf(stderr, "<-- leaving native code\n"); + + FLAG(c) = reg->cflag; + FLAG(v) = reg->vflag; + FLAG(n) = reg->nflag; + FLAG(z) = reg->zflag; +} + +#ifdef DEADCODE + +// glue code used to execute native code fragments +void nativesupport_invoke(machineinfo* machine, nativeblockinfo* code) +{ + registerinfo* reg = machine->reg; + hashentry* h; + blockinfo* blk; + uint5 i; + extern uint5 nativehack; + + reg->cflag = FLAG(c); + reg->vflag = FLAG(v); + reg->nflag = FLAG(n); + reg->zflag = FLAG(z); + reg->r[15] &= 0x3fffffc; + + // for RISC OS SWI faking + nativehack = 1; + + do { + int o1, o2; +/* fprintf(stderr, "Calling code at %x\n", code->base); + for (i=0; i<16; i++) fprintf(stderr, "r%d=%x ", i, machine->reg[i]); + fprintf(stderr, "\n");*/ + // "q" means registers a to d - not perfect, but OK + // doesn't seem to understand clobbering %ebp, whoops + asm __volatile__("pushl %%ebp\n\t" \ + "movl %2,%%ebp\n\t" \ + "call *%3\n\t" \ + "popl %%ebp" + : "=r" (o1), "=r" (o2) + : "a" (reg), "b" (code->base) + : "cx", "dx", "si", "di", "memory"); + /* fprintf(stderr, "Returning\n", code->base); + for (i=0; i<16; i++) fprintf(stderr, "r%d=%x ", i, machine->reg[i]); + fprintf(stderr, "\n");*/ + h = hash_lookup(machine->blocks, reg->r[15]-8); + if (h) blk = h->data; else blk = 0; + if (blk) code = blk->native; else code = 0; + } while (code); + + nativehack = 0; + + /*"m" (reg->cflag), + "m" (reg->vflag), "m" (reg->nflag), + "m" (reg->zflag)*/ + FLAG(c) = reg->cflag; + FLAG(v) = reg->vflag; + FLAG(n) = reg->nflag; + FLAG(z) = reg->zflag; +} +#else +void nativesupport_invoke(machineinfo* machine, nativeblockinfo* code) +{ + IGNORE(machine); + IGNORE(code); + assert(!"Please don't call this function"); +} +#endif + +#ifdef ROHLE +void nativesupport_swi(machineinfo* machine, uint5 number) +{ + // just one more level of indirection... + fake_syscall(machine, number); +} +#endif + +/* +void nativesupport_writebyte(meminfo* mem, uint5 address, uint5 byte) +{ + uint3* addr = (uint3*)memory_lookup(mem, (uint5*)address); + *addr = byte; +// fprintf(stderr, "STB @ %x\n", *(uint5*)memory_lookup(mem, (uint5*)0)); + #ifdef VIRTUALFRAMEBUFFER + memory_postwrite(mem, (uint5*)address); + #endif +} + +// QUICKWRITE assumes words are always written to word boundaries +void nativesupport_writeword(meminfo* mem, uint5 address, uint5 word) +{ + uint5* addr = memory_lookup(mem, (uint5*)address); + #ifndef QUICKWRITE + addr = (uint5*)((uint5)addr&~3); + #endif + *addr = word; + #ifdef VIRTUALFRAMEBUFFER + memory_postwrite(mem, (uint5*)address); + #endif +// fprintf(stderr, "Writing %x to %x\n", word, address); +} + +uint5 nativesupport_readbyte(meminfo* mem, uint5 address) +{ + uint3* addr = (uint3*)memory_lookup(mem, (uint5*)address); +// fprintf(stderr, "LDB @ %x\n", *(uint5*)memory_lookup(mem, (uint5*)0)); + return *addr; +} + +// QUICKREAD assumes words are always read from word boundaries +uint5 nativesupport_readword(meminfo* mem, uint5 address) +{ + uint5* addr = memory_lookup(mem, (uint5*)address); +#ifdef QUICKREAD + return *addr; +#else + uint5 byteoffset = (uint5)addr & 3; + addr = (uint5*) ((uint5)addr&~3); + return ROR(*addr, byteoffset*8); +#endif +} + +uint5 nativesupport_reconstructpc(uint5 addr, registerinfo* reg) +{ +#ifdef ARM26BIT + uint5 val = addr | (reg->mode) | (reg->intmask<<26) | (reg->vflag<<28) | + (reg->cflag<<29) | (reg->zflag<<30) | (reg->nflag<<31); +#else + uint5 val = addr; +#endif +// fprintf(stderr, "reconstructing pc, value %x (addr %x)\n", val, addr); + return val; +} +*/ diff --git a/pool/shard006/C/0118720_sbc8560.c b/pool/shard006/C/0118720_sbc8560.c new file mode 100644 index 0000000000000000000000000000000000000000..82394cedfdf89a37a0a5ad48556659f2141bfd7f --- /dev/null +++ b/pool/shard006/C/0118720_sbc8560.c @@ -0,0 +1,235 @@ +/* + * Wind River SBC8560 board specific routines + * + * Maintainer: Kumar Gala + * + * Copyright 2004 Freescale Semiconductor Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* for linux/serial_core.h */ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +static void __init +sbc8560_early_serial_map(void) +{ + struct uart_port uart_req; + + /* Setup serial port access */ + memset(&uart_req, 0, sizeof (uart_req)); + uart_req.irq = MPC85xx_IRQ_EXT9; + uart_req.flags = STD_COM_FLAGS; + uart_req.uartclk = BASE_BAUD * 16; + uart_req.iotype = UPIO_MEM; + uart_req.mapbase = UARTA_ADDR; + uart_req.membase = ioremap(uart_req.mapbase, MPC85xx_UART0_SIZE); + uart_req.type = PORT_16650; + +#ifdef CONFIG_SERIAL_8250 + if (early_serial_setup(&uart_req) != 0) + printk("Early serial init of port 0 failed\n"); +#endif +#ifdef CONFIG_SERIAL_TEXT_DEBUG + gen550_init(0, &uart_req); +#endif +#ifdef CONFIG_KGDB_8250 + kgdb8250_add_port(0, &uart_req); +#endif + + /* Assume early_serial_setup() doesn't modify uart_req */ + uart_req.line = 1; + uart_req.mapbase = UARTB_ADDR; + uart_req.membase = ioremap(uart_req.mapbase, MPC85xx_UART1_SIZE); + uart_req.irq = MPC85xx_IRQ_EXT10; + +#ifdef CONFIG_SERIAL_8250 + if (early_serial_setup(&uart_req) != 0) + printk("Early serial init of port 0 failed\n"); +#endif +#ifdef CONFIG_SERIAL_TEXT_DEBUG + gen550_init(0, &uart_req); +#endif +#ifdef CONFIG_KGDB_8250 + kgdb8250_add_port(0, &uart_req); +#endif +} + +/* ************************************************************************ + * + * Setup the architecture + * + */ +static void __init +sbc8560_setup_arch(void) +{ + bd_t *binfo = (bd_t *) __res; + unsigned int freq; + struct gianfar_platform_data *pdata; + struct gianfar_mdio_data *mdata; + + /* get the core frequency */ + freq = binfo->bi_intfreq; + + if (ppc_md.progress) + ppc_md.progress("sbc8560_setup_arch()", 0); + + /* Set loops_per_jiffy to a half-way reasonable value, + for use until calibrate_delay gets called. */ + loops_per_jiffy = freq / HZ; + +#ifdef CONFIG_PCI + /* setup PCI host bridges */ + mpc85xx_setup_hose(); +#endif + sbc8560_early_serial_map(); +#ifdef CONFIG_SERIAL_TEXT_DEBUG + /* Invalidate the entry we stole earlier the serial ports + * should be properly mapped */ + invalidate_tlbcam_entry(num_tlbcam_entries - 1); +#endif + + /* setup the board related info for the MDIO bus */ + mdata = (struct gianfar_mdio_data *) ppc_sys_get_pdata(MPC85xx_MDIO); + + mdata->irq[25] = MPC85xx_IRQ_EXT6; + mdata->irq[26] = MPC85xx_IRQ_EXT7; + mdata->irq[31] = PHY_POLL; + + /* setup the board related information for the enet controllers */ + pdata = (struct gianfar_platform_data *) ppc_sys_get_pdata(MPC85xx_TSEC1); + if (pdata) { + pdata->board_flags = FSL_GIANFAR_BRD_HAS_PHY_INTR; + pdata->bus_id = 0; + pdata->phy_id = 25; + memcpy(pdata->mac_addr, binfo->bi_enetaddr, 6); + } + + pdata = (struct gianfar_platform_data *) ppc_sys_get_pdata(MPC85xx_TSEC2); + if (pdata) { + pdata->board_flags = FSL_GIANFAR_BRD_HAS_PHY_INTR; + pdata->bus_id = 0; + pdata->phy_id = 26; + memcpy(pdata->mac_addr, binfo->bi_enet1addr, 6); + } + +#ifdef CONFIG_BLK_DEV_INITRD + if (initrd_start) + ROOT_DEV = Root_RAM0; + else +#endif +#ifdef CONFIG_ROOT_NFS + ROOT_DEV = Root_NFS; +#else + ROOT_DEV = Root_HDA1; +#endif +} + +/* ************************************************************************ */ +void __init +platform_init(unsigned long r3, unsigned long r4, unsigned long r5, + unsigned long r6, unsigned long r7) +{ + /* parse_bootinfo must always be called first */ + parse_bootinfo(find_bootinfo()); + + /* + * If we were passed in a board information, copy it into the + * residual data area. + */ + if (r3) { + memcpy((void *) __res, (void *) (r3 + KERNELBASE), + sizeof (bd_t)); + } + +#ifdef CONFIG_SERIAL_TEXT_DEBUG + /* Use the last TLB entry to map CCSRBAR to allow access to DUART regs */ + settlbcam(num_tlbcam_entries - 1, UARTA_ADDR, + UARTA_ADDR, 0x1000, _PAGE_IO, 0); +#endif + +#if defined(CONFIG_BLK_DEV_INITRD) + /* + * If the init RAM disk has been configured in, and there's a valid + * starting address for it, set it up. + */ + if (r4) { + initrd_start = r4 + KERNELBASE; + initrd_end = r5 + KERNELBASE; + } +#endif /* CONFIG_BLK_DEV_INITRD */ + + /* Copy the kernel command line arguments to a safe place. */ + + if (r6) { + *(char *) (r7 + KERNELBASE) = 0; + strcpy(cmd_line, (char *) (r6 + KERNELBASE)); + } + + identify_ppc_sys_by_id(mfspr(SPRN_SVR)); + + /* setup the PowerPC module struct */ + ppc_md.setup_arch = sbc8560_setup_arch; + ppc_md.show_cpuinfo = sbc8560_show_cpuinfo; + + ppc_md.init_IRQ = sbc8560_init_IRQ; + ppc_md.get_irq = openpic_get_irq; + + ppc_md.restart = mpc85xx_restart; + ppc_md.power_off = mpc85xx_power_off; + ppc_md.halt = mpc85xx_halt; + + ppc_md.find_end_of_memory = mpc85xx_find_end_of_memory; + + ppc_md.time_init = NULL; + ppc_md.set_rtc_time = NULL; + ppc_md.get_rtc_time = NULL; + ppc_md.calibrate_decr = mpc85xx_calibrate_decr; + +#if defined(CONFIG_SERIAL_8250) && defined(CONFIG_SERIAL_TEXT_DEBUG) + ppc_md.progress = gen550_progress; +#endif /* CONFIG_SERIAL_8250 && CONFIG_SERIAL_TEXT_DEBUG */ + + if (ppc_md.progress) + ppc_md.progress("sbc8560_init(): exit", 0); +} diff --git a/pool/shard006/C/0118721_dlmisc.c b/pool/shard006/C/0118721_dlmisc.c new file mode 100644 index 0000000000000000000000000000000000000000..908a41254d986e9a3bc486fdca9279fa33e7a8a4 --- /dev/null +++ b/pool/shard006/C/0118721_dlmisc.c @@ -0,0 +1,215 @@ +/** + * \file dlmisc.c + * \brief dynamic loader helpers + * \author Jaroslav Kysela + * \date 2001 + * + * Dynamic loader helpers + */ +/* + * Dynamic loader helpers + * Copyright (c) 2000 by Jaroslav Kysela + * + * + * 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 program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#define _GNU_SOURCE +#include +#include "list.h" +#include "local.h" + +#ifndef DOC_HIDDEN +#ifndef PIC +struct snd_dlsym_link *snd_dlsym_start = NULL; +#endif +#endif + +/** + * \brief Opens a dynamic library - ALSA wrapper for \c dlopen. + * \param name name of the library, similar to \c dlopen. + * \param mode mode flags, similar to \c dlopen. + * \return Library handle if successful, otherwise \c NULL. + * + * This function can emulate dynamic linking for the static build of + * the alsa-lib library. In that case, \p name is set to \c NULL. + */ +void *snd_dlopen(const char *name, int mode) +{ +#ifndef PIC + if (name == NULL) + return &snd_dlsym_start; +#else + if (name == NULL) { + Dl_info dlinfo; + if (dladdr(snd_dlopen, &dlinfo) > 0) + name = dlinfo.dli_fname; + } +#endif + return dlopen(name, mode); +} + +/** + * \brief Closes a dynamic library - ALSA wrapper for \c dlclose. + * \param handle Library handle, similar to \c dlclose. + * \return Zero if successful, otherwise an error code. + * + * This function can emulate dynamic linking for the static build of + * the alsa-lib library. + */ +int snd_dlclose(void *handle) +{ +#ifndef PIC + if (handle == &snd_dlsym_start) + return 0; +#endif + return dlclose(handle); +} + +/** + * \brief Verifies a dynamically loaded symbol. + * \param handle Library handle, similar to \c dlsym. + * \param name Symbol name. + * \param version Version of the symbol. + * \return Zero is successful, otherwise a negative error code. + * + * This function checks that the symbol with the version appended to its name + * does exist in the library. + */ +static int snd_dlsym_verify(void *handle, const char *name, const char *version) +{ + int res; + char *vname; + + if (handle == NULL) + return -EINVAL; + vname = alloca(1 + strlen(name) + strlen(version) + 1); + if (vname == NULL) + return -ENOMEM; + vname[0] = '_'; + strcpy(vname + 1, name); + strcat(vname, version); + res = dlsym(handle, vname) == NULL ? -ENOENT : 0; + // printf("dlsym verify: %i, vname = '%s'\n", res, vname); + if (res < 0) + SNDERR("unable to verify version for symbol %s", name); + return res; +} + +/** + * \brief Resolves a symbol from a dynamic library - ALSA wrapper for \c dlsym. + * \param handle Library handle, similar to \c dlsym. + * \param name Symbol name. + * \param version Version of the symbol. + * + * This function can emulate dynamic linking for the static build of + * the alsa-lib library. + * + * This special version of the \c dlsym function checks also the version + * of the symbol. A versioned symbol should be defined using the + * #SND_DLSYM_BUILD_VERSION macro. + */ +void *snd_dlsym(void *handle, const char *name, const char *version) +{ + int err; + +#ifndef PIC + if (handle == &snd_dlsym_start) { + /* it's the funny part: */ + /* we are looking for a symbol in a static library */ + struct snd_dlsym_link *link = snd_dlsym_start; + while (link) { + if (!strcmp(name, link->dlsym_name)) + return (void *)link->dlsym_ptr; + link = link->next; + } + return NULL; + } +#endif + err = snd_dlsym_verify(handle, name, version); + if (err < 0) + return NULL; + return dlsym(handle, name); +} + +/* + * dlobj cache + * + * FIXME: add reference counter and proper locking + */ + +#ifndef DOC_HIDDEN +struct dlobj_cache { + const char *name; + void *obj; + void *func; + struct list_head list; +}; + +static LIST_HEAD(pcm_dlobj_list); + +void *snd_dlobj_cache_lookup(const char *name) +{ + struct list_head *p; + struct dlobj_cache *c; + + list_for_each(p, &pcm_dlobj_list) { + c = list_entry(p, struct dlobj_cache, list); + if (strcmp(c->name, name) == 0) + return c->func; + } + return NULL; +} + +int snd_dlobj_cache_add(const char *name, void *dlobj, void *open_func) +{ + struct list_head *p; + struct dlobj_cache *c; + + list_for_each(p, &pcm_dlobj_list) { + c = list_entry(p, struct dlobj_cache, list); + if (strcmp(c->name, name) == 0) + return 0; /* already exists */ + } + c = malloc(sizeof(*c)); + if (! c) + return -ENOMEM; + c->name = strdup(name); + if (! c->name) { + free(c); + return -ENOMEM; + } + c->obj = dlobj; + c->func = open_func; + list_add_tail(&c->list, &pcm_dlobj_list); + return 0; +} + +void snd_dlobj_cache_cleanup(void) +{ + struct list_head *p; + struct dlobj_cache *c; + + while (! list_empty(&pcm_dlobj_list)) { + p = pcm_dlobj_list.next; + c = list_entry(p, struct dlobj_cache, list); + list_del(p); + snd_dlclose(c->obj); + free((void *)c->name); /* shut up gcc warning */ + free(c); + } +} +#endif diff --git a/pool/shard006/C/0118723_acquire_cred.c b/pool/shard006/C/0118723_acquire_cred.c new file mode 100644 index 0000000000000000000000000000000000000000..ae9b21b779264aafe813942931e148be827f5c8d --- /dev/null +++ b/pool/shard006/C/0118723_acquire_cred.c @@ -0,0 +1,244 @@ +/* + * Copyright 1999-2006 University of Chicago + * + * 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. + */ + +#ifndef GLOBUS_DONT_DOCUMENT_INTERNAL +/** + * @file acquire_cred.c + * @brief Acquire Credential + * @author Sam Meder, Sam Lang + */ +#endif + +#include "gssapi.h" +#include "gssapi_openssl.h" +#include "globus_i_gsi_gss_utils.h" + +#include +#include + +/** + * @brief Acquire Credential + * @ingroup globus_gsi_gssapi + * @details + * GSSAPI routine to acquire the local credential. + * See the latest IETF draft/RFC on the GSSAPI C bindings. + * + * Gets the local credentials. The proxy_init_cred does most of the + * work of setting up the SSL_ctx, getting the user's cert, key, etc. + + * The globusid will be obtained from the certificate. (Minus + * and /CN=proxy entries.) + * + * @param minor_status + * Mechanism specific status code. In this implementation, + * the minor_status is a cast from a globus_result_t value, which + * is either GLOBUS_SUCCESS or a globus error object ID if an error + * occurred. + * @param desired_name_P + * Name of principle whose credentials should be acquired + * This parameter maps to the desired subject of the cert + * to be acquired as the credential. Possible values are: + * - For a service cert: service name\@fqdn + * - For a host cert: fqdn + * - For a proxy cert: subject name + * - For a user cert: subject name + * This parameter can be NULL, in which case the cert is chosen + * using a default search order of: host, proxy, user, service + * @param time_req + * Number of seconds that credentials should remain valid. + * This value can be GSS_C_INDEFINITE for an unlimited lifetime. + * NOTE: in the current implementation, this parameter is ignored, + * since you can't change the expiration of a signed cert. + * + * @param desired_mechs + * @param cred_usage + * @param output_cred_handle_P + * @param actual_mechs + * @param time_rec + */ +OM_uint32 +GSS_CALLCONV gss_acquire_cred( + OM_uint32 * minor_status, + const gss_name_t desired_name_P, + OM_uint32 time_req, + const gss_OID_set desired_mechs, + gss_cred_usage_t cred_usage, + gss_cred_id_t * output_cred_handle_P, + gss_OID_set * actual_mechs, + OM_uint32 * time_rec) +{ + char * desired_name_string = NULL; + OM_uint32 major_status = GSS_S_NO_CRED; + OM_uint32 local_minor_status; + X509_NAME * desired_name = NULL; + + GLOBUS_I_GSI_GSSAPI_DEBUG_ENTER; + + *minor_status = (OM_uint32) GLOBUS_SUCCESS; + + *output_cred_handle_P = NULL; + + /* module activation if not already done by calling + * globus_module_activate + */ + + globus_thread_once( + &once_control, + globus_l_gsi_gssapi_activate_once); + + globus_mutex_lock(&globus_i_gssapi_activate_mutex); + if (!globus_i_gssapi_active) + { + globus_module_activate(GLOBUS_GSI_GSSAPI_MODULE); + } + globus_mutex_unlock(&globus_i_gssapi_activate_mutex); + + if(desired_name_P) + { + desired_name = ((gss_name_desc *)desired_name_P)->x509n; + } + + major_status = globus_i_gsi_gss_cred_read( + &local_minor_status, + cred_usage, + output_cred_handle_P, + desired_name); + + if(GSS_ERROR(major_status)) + { + GLOBUS_GSI_GSSAPI_ERROR_CHAIN_RESULT( + minor_status, local_minor_status, + GLOBUS_GSI_GSSAPI_ERROR_WITH_GSI_CREDENTIAL); + goto error; + } + + if (time_rec != NULL) + { + time_t lifetime; + globus_result_t result; + + result = globus_gsi_cred_get_lifetime( + ((gss_cred_id_desc *) *output_cred_handle_P)->cred_handle, + &lifetime); + if(result != GLOBUS_SUCCESS) + { + GLOBUS_GSI_GSSAPI_ERROR_CHAIN_RESULT( + minor_status, result, + GLOBUS_GSI_GSSAPI_ERROR_WITH_GSI_CREDENTIAL); + major_status = GSS_S_FAILURE; + goto error; + } + + *time_rec = (OM_uint32) lifetime; + } + + if(desired_name_string) + { + free(desired_name_string); + } + + /* Use new mech OID if present */ + if (desired_mechs != NULL) + { + int present = 0; + + if (desired_mechs->count > 1) + { + major_status = GSS_S_FAILURE; + GLOBUS_GSI_GSSAPI_ERROR_CHAIN_RESULT( + minor_status, local_minor_status, + GLOBUS_GSI_GSSAPI_ERROR_BAD_MECH); + goto error; + } + + if ((gss_test_oid_set_member(&local_minor_status, + (const gss_OID) gss_mech_globus_gssapi_openssl_micv2, + desired_mechs, &present) == GSS_S_COMPLETE) && present) + { + (*output_cred_handle_P)->mech = (const gss_OID)gss_mech_globus_gssapi_openssl_micv2; + } + else if ((gss_test_oid_set_member(&local_minor_status, + (const gss_OID) gss_mech_globus_gssapi_openssl, + desired_mechs, &present) == GSS_S_COMPLETE) && present) + { + (*output_cred_handle_P)->mech = (const gss_OID)gss_mech_globus_gssapi_openssl; + } + else + { + major_status = GSS_S_FAILURE; + GLOBUS_GSI_GSSAPI_ERROR_CHAIN_RESULT( + minor_status, local_minor_status, + GLOBUS_GSI_GSSAPI_ERROR_BAD_MECH); + goto error; + } + } else if (globus_i_backward_compatible_mic) + { + (*output_cred_handle_P)->mech = (const gss_OID)gss_mech_globus_gssapi_openssl; + } else + { + (*output_cred_handle_P)->mech = (const gss_OID)gss_mech_globus_gssapi_openssl_micv2; + } + + GLOBUS_I_GSI_GSSAPI_DEBUG_FPRINTF( + 2, (globus_i_gsi_gssapi_debug_fstream, + "acquire_cred: %s\n", + ((*output_cred_handle_P)->mech == GSS_C_NO_OID)? "NO MECH OID": + ((g_OID_equal((*output_cred_handle_P)->mech, (gss_OID) gss_mech_globus_gssapi_openssl))? + "OLD MECH OID": + ((g_OID_equal((*output_cred_handle_P)->mech, (gss_OID) gss_mech_globus_gssapi_openssl_micv2))? + "MICV2 MECH OID": "UNKNOWN MECH OID")))); + + if (actual_mechs != NULL) + { + if ((*output_cred_handle_P)->mech != GSS_C_NO_OID) + { + major_status = gss_create_empty_oid_set(&local_minor_status, actual_mechs); + if (major_status == GSS_S_COMPLETE) + major_status = gss_add_oid_set_member(&local_minor_status, + (*output_cred_handle_P)->mech, actual_mechs); + } else + major_status = gss_indicate_mechs(&local_minor_status, + actual_mechs); + if (GSS_ERROR(major_status)) + { + GLOBUS_GSI_GSSAPI_ERROR_CHAIN_RESULT( + minor_status, local_minor_status, + GLOBUS_GSI_GSSAPI_ERROR_BAD_MECH); + goto error; + } + } + + goto exit; + + error: + + if(desired_name_string) + { + free(desired_name_string); + } + + if(*output_cred_handle_P) + { + gss_release_cred( + &local_minor_status, + output_cred_handle_P); + } + + exit: + + GLOBUS_I_GSI_GSSAPI_DEBUG_EXIT; + return major_status; +} diff --git a/pool/shard006/C/0118726_main.c b/pool/shard006/C/0118726_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6dd69963bc7c89c644eba3eb34bfd26b51d62d7e --- /dev/null +++ b/pool/shard006/C/0118726_main.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +struct _string { + int len; + char *str; +}; + +typedef struct _string String; + +String *new_String(int len) { + String *str = malloc(sizeof(String) + sizeof(char) * len); + str->len = len; + str->str = (char *)(str + 1); + return str; +} + +void free_String(String *p) { free(p); } + +bool copy_String(String *dest, String *source) { + if (dest->len < source->len) + return false; + for (int i = 0; i < source->len; i++) { + dest->str[i] = source->str[i]; + } + return true; +} + +bool set_String(String *str, char *c_str_source) { + char *curr = str->str; + int copied = 0; + while (*c_str_source != '\0') { + if (copied == str->len) { + puts("String is n0t l0ng en0ughth"); + return false; + } + *curr++ = *c_str_source++; + copied++; + } + return true; +} + +int main(int argc, char *argv[]) { + String *str = new_String(5); + set_String(str, "ololo"); + for (int i = 0; i < 5; i++) + printf("%c", str->str[i]); + free_String(str); +} diff --git a/pool/shard006/C/0118729_service.c b/pool/shard006/C/0118729_service.c new file mode 100644 index 0000000000000000000000000000000000000000..e939c85e6898cdee42ab490553b0f158c9a8ddd4 --- /dev/null +++ b/pool/shard006/C/0118729_service.c @@ -0,0 +1,116 @@ +/* + Unix SMB/CIFS implementation. + + SERVER SERVICE code + + Copyright (C) Andrew Tridgell 2003-2005 + Copyright (C) Stefan (metze) Metzmacher 2004 + + 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 . +*/ + +#include "includes.h" +#include "../lib/util/dlinklist.h" +#include "smbd/process_model.h" + +#undef strcasecmp + +/* + a linked list of registered servers +*/ +static struct registered_server { + struct registered_server *next, *prev; + const char *service_name; + const struct service_details *service_details; +} *registered_servers; + +/* + register a server service. +*/ +NTSTATUS register_server_service(TALLOC_CTX *ctx, + const char *name, + const struct service_details *details) +{ + struct registered_server *srv; + srv = talloc(ctx, struct registered_server); + NT_STATUS_HAVE_NO_MEMORY(srv); + srv->service_name = name; + srv->service_details = + talloc_memdup(ctx, details, sizeof(struct service_details)); + NT_STATUS_HAVE_NO_MEMORY(srv->service_details); + DLIST_ADD_END(registered_servers, srv); + return NT_STATUS_OK; +} + + +/* + initialise a server service +*/ +static NTSTATUS server_service_init(const char *name, + struct tevent_context *event_context, + struct loadparm_context *lp_ctx, + const struct model_ops *model_ops, + int from_parent_fd) +{ + struct registered_server *srv; + for (srv=registered_servers; srv; srv=srv->next) { + if (strcasecmp(name, srv->service_name) == 0) { + return task_server_startup(event_context, lp_ctx, + srv->service_name, + model_ops, + srv->service_details, + from_parent_fd); + } + } + return NT_STATUS_INVALID_SYSTEM_SERVICE; +} + + +/* + startup all of our server services +*/ +NTSTATUS server_service_startup(struct tevent_context *event_ctx, + struct loadparm_context *lp_ctx, + const char *model, const char **server_services, + int from_parent_fd) +{ + int i; + const struct model_ops *model_ops; + + if (!server_services) { + DBG_ERR("server_service_startup: " + "no endpoint servers configured\n"); + return NT_STATUS_INVALID_PARAMETER; + } + + model_ops = process_model_startup(model); + if (!model_ops) { + DBG_ERR("process_model_startup('%s') failed\n", model); + return NT_STATUS_INTERNAL_ERROR; + } + + for (i=0;server_services[i];i++) { + NTSTATUS status; + + status = server_service_init(server_services[i], event_ctx, + lp_ctx, model_ops, from_parent_fd); + if (!NT_STATUS_IS_OK(status)) { + DBG_ERR("Failed to start service '%s' - %s\n", + server_services[i], nt_errstr(status)); + } + NT_STATUS_NOT_OK_RETURN(status); + } + + return NT_STATUS_OK; +} diff --git a/pool/shard006/C/0118733_CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_53d.c b/pool/shard006/C/0118733_CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_53d.c new file mode 100644 index 0000000000000000000000000000000000000000..7816333b4fd65f01e04236a269b184b86f84dce3 --- /dev/null +++ b/pool/shard006/C/0118733_CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_53d.c @@ -0,0 +1,57 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_53d.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml +Template File: sources-sink-53d.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Point data to a buffer that does not have space for a NULL terminator + * GoodSource: Point data to a buffer that includes space for a NULL terminator + * Sink: ncpy + * BadSink : Copy string to data using strncpy() + * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +/* MAINTENANCE NOTE: The length of this string should equal the 10 */ +#define SRC_STRING "AAAAAAAAAA" + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_53d_badSink(char * data) +{ + { + char source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + strncpy(data, source, strlen(source) + 1); + printLine(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE121_Stack_Based_Buffer_Overflow__CWE193_char_declare_ncpy_53d_goodG2BSink(char * data) +{ + { + char source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + strncpy(data, source, strlen(source) + 1); + printLine(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard006/C/0118737_syscall_listen.c b/pool/shard006/C/0118737_syscall_listen.c new file mode 100644 index 0000000000000000000000000000000000000000..6142b48affee50fb47e12b330ecee661c83e0bf7 --- /dev/null +++ b/pool/shard006/C/0118737_syscall_listen.c @@ -0,0 +1,33 @@ +/* +** vmndh - Release v0.1 +** Jonathan Salwan - http://twitter.com/JonathanSalwan +** +** 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 "vmndh.h" + +void syscall_listen(void) +{ + uint16_t arg1; + uint16_t arg2; + + arg1 = core.regs.r1; + arg2 = core.regs.r2; + core.regs.r0 = listen(arg1, arg2); + if (core.flagmode.noverbose == 0) + fprintf(stdout, "[%sSYSCALL output%s]: %d\n", YELLOW, ENDC, core.regs.r0); +} + diff --git a/pool/shard006/C/0118743_neatopack.c b/pool/shard006/C/0118743_neatopack.c new file mode 100644 index 0000000000000000000000000000000000000000..932e03ff5fa8616616525d07dfcba8c7c98c6cdc --- /dev/null +++ b/pool/shard006/C/0118743_neatopack.c @@ -0,0 +1,54 @@ +/* vim:set shiftwidth=4 ts=8: */ + +/************************************************************************* + * Copyright (c) 2011 AT&T Intellectual Property + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: See CVS logs. Details at http://www.graphviz.org/ + *************************************************************************/ + +#include +#include + +int main (int argc, char* argv[]) +{ + graph_t *g; + graph_t *sg; + FILE *fp; + graph_t** cc; + int i, ncc; + GVC_t *gvc; + + gvc = gvContext(); + + if (argc > 1) + fp = fopen(argv[1], "r"); + else + fp = stdin; + g = agread(fp, 0); + + cc = ccomps(g, &ncc, (char*)0); + + for (i = 0; i < ncc; i++) { + sg = cc[i]; + nodeInduce (sg); + gvLayout(gvc, sg, "neato"); + } + pack_graph (ncc, cc, g, 0); + + gvRender(gvc, g, "ps", stdout); + + for (i = 0; i < ncc; i++) { + sg = cc[i]; + gvFreeLayout(gvc, sg); + agdelete(g, sg); + } + + agclose(g); + + return (gvFreeContext(gvc)); + +} diff --git a/pool/shard006/C/0118744_uicartridge.c b/pool/shard006/C/0118744_uicartridge.c new file mode 100644 index 0000000000000000000000000000000000000000..6b83d897f70919e6ba4992bb09f568f494fde93d --- /dev/null +++ b/pool/shard006/C/0118744_uicartridge.c @@ -0,0 +1,79 @@ +/* + * uicartridge.c - Cartridge save image dialog for the Xaw widget set. + * + * Written by + * pottendo + * + * 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" + +#include + +#include "ui.h" +#include "uiarch.h" +#include "uiapi.h" +#include "cartridge.h" +#include "uifileentry.h" +#include "uilib.h" +#include "lib.h" + +#include "uicartridge.h" + + +static GtkWidget *cartridge_dialog; + +void ui_cartridge_save_dialog(int type) +{ + gint res; + char *name; + + if (cartridge_dialog) { + gdk_window_show(gtk_widget_get_window(cartridge_dialog)); + gdk_window_raise(gtk_widget_get_window(cartridge_dialog)); + gtk_widget_show(cartridge_dialog); + } else { + uilib_file_filter_enum_t filter = UILIB_FILTER_ALL; + cartridge_dialog = vice_file_entry(_("Save cartridge image"), NULL, NULL, &filter, 1, UI_FC_SAVE); + g_signal_connect(G_OBJECT(cartridge_dialog), "destroy", G_CALLBACK(gtk_widget_destroyed), &cartridge_dialog); + } + + ui_popup(cartridge_dialog, _("Save cartridge image"), FALSE); + res = gtk_dialog_run(GTK_DIALOG(cartridge_dialog)); + ui_popdown(cartridge_dialog); + + if (res != GTK_RESPONSE_ACCEPT) { + return; + } + + name = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(cartridge_dialog)); + if (!name) { + ui_error(_("Invalid filename")); + return; + } + + if (cartridge_save_image (type, name) < 0) { + ui_error(_("Cannot write cartridge image file\n`%s'\n"), name); + } else { + ui_message(_("Successfully wrote `%s'"), name); + } + lib_free(name); +} diff --git a/pool/shard006/C/0118746_matrix_pipe.c b/pool/shard006/C/0118746_matrix_pipe.c new file mode 100644 index 0000000000000000000000000000000000000000..540f9c6a6fbef00a45ff41b2d9381c68b1ab78e9 --- /dev/null +++ b/pool/shard006/C/0118746_matrix_pipe.c @@ -0,0 +1,208 @@ +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "matrixOps.h" + +#define MAX_BUF_LEN 1024 +#define MAX_DELAY 10 + +// child_one - process reading from standard input +// child_two - process reading from standard output +int child_one, child_two, bufLen; + +//write to the pipe +//taken from provided programs +void writePipe(char * s, int pipe) { + write(pipe, s, strlen(s)); +}; + +//read from the pipe +//taken from provided programs +int readPipe(char * s, int pipe) { + int l = 0, i; + + while ( (i = read(pipe, s, 1)) > 0 ) { + s++; + l++; + } + s[l+1] = '\0'; + + return l; +} + +//print message to console unless it is NULL +void printMessage(char msg[]) { + if (msg != NULL) { + printf("%s", msg); + } +}; + +//print message to console and read number +int readNumber(char msg[]) { + printMessage(msg); + + int * digit = (int *) malloc( sizeof(int) ); + scanf("%d", digit); + return * digit; +}; + +//exit program with success status +void exitMatrix() { + printf("\nExiting\n"); + kill(child_one, SIGINT); + kill(child_two, SIGINT); + exit(EXIT_SUCCESS); +} + +int main() { + int i, j; + + char * pipeName = "mPipe"; + char * buf; + buf = (char *) malloc(sizeof(char) * MAX_BUF_LEN); + + mkfifo(pipeName, S_IRWXU | S_IRWXO); + + child_one = fork(); + if ( child_one < 0 ) { + perror("error creating first child"); + exit(1); + } else if ( child_one == 0 ) { + // child one code + while (1) {/*{{{*/ + //child one reads matrix from stdin and outputs it to pipe + printMessage("Enter matrix\n"); + int rows = readNumber("Enter number of rows in matrix: "), + cols = readNumber("Enter number of cols in matrix: "); + + struct matrix m = { + .r = (int *) malloc( sizeof(int) ), + .c = (int *) malloc( sizeof(int) ), + .m = (int **) malloc( rows * sizeof(int *) ) + }; + *m.r = rows; + *m.c = cols; + for (i = 0; i < rows; i++) { + m.m[i] = (int *) malloc( cols * sizeof(int) ); + } + + printMessage("Enter matrix data:\n"); + for (i = 0; i < rows; i++) { + for (j = 0; j < cols; j++) { + m.m[i][j] = readNumber(NULL); + } + } + + //encode matrix + char * encodedMatrix = encodeMatrix(m); + //open pipe and write data + int woPipe = open(pipeName, O_WRONLY); + writePipe(encodedMatrix, woPipe); + close(woPipe); + + //stop itself + raise(SIGSTOP); + }/*}}}*/ + } else { + child_two = fork(); + if ( child_two < 0 ) { + perror("error creating second child"); + kill(child_one, SIGINT); + exit(1); + } else if (child_two == 0) { + // child two code + while (1) {/*{{{*/ + //child two reads matrix from pipe and prints it to stdout + //open pipe and wait for data + int roPipe = open(pipeName, O_RDONLY); + bufLen = readPipe(buf, roPipe); + close(roPipe); + + //parse matrix + struct matrix m = parseMatrix(buf); + + //print matrix to stdout + printMessage("Your matrix:\n"); + for (i = 0; i < *m.r; i++) { + for (j = 0; j < *m.c; j++) { + printf("%4d ", m.m[i][j]); + } + printf("\n"); + } + + //stop itself + raise(SIGSTOP); + }/*}}}*/ + } else { + // parent code + + //initially stop children + kill(child_one, SIGSTOP); + kill(child_two, SIGSTOP); + + //respond to alarm by exiting program + signal(SIGALRM, exitMatrix); + + while (1) { + int rwPipe; + char * m1_S = NULL, * m2_S = NULL; + + //start alarm + alarm(MAX_DELAY); + //continue first child + kill(child_one, SIGCONT); + //open pipe and wait for data + rwPipe = open(pipeName, O_RDONLY); + readPipe(buf, rwPipe); + close(rwPipe); + + //copy read data from buf + m1_S = malloc(strlen(buf)); + strcpy(m1_S, buf); + + //restart alarm + alarm(MAX_DELAY); + //continue first child again + kill(child_one, SIGCONT); + //open pipe and wait for data + rwPipe = open(pipeName, O_RDONLY); + readPipe(buf, rwPipe); + close(rwPipe); + + //copy read data from buf + m2_S = malloc(strlen(buf)); + strcpy(m2_S, buf); + + //parse inputted matrixes and multiply them + struct matrix m1 = parseMatrix(m1_S), + m2 = parseMatrix(m2_S), + m = multMatrix(m1, m2); + + //encode multiplied matrix + char * m_S = encodeMatrix(m); + + //continue second child + kill(child_two, SIGCONT); + //open pipe and write data into it + rwPipe = open(pipeName, O_WRONLY); + writePipe(m_S, rwPipe); + close(rwPipe); + + //wait until second child finishes before starting new iteration + waitpid(child_two, NULL, WUNTRACED); + } + } + } + + return 0; +}; diff --git a/pool/shard006/C/0118748_ppc64.c b/pool/shard006/C/0118748_ppc64.c new file mode 100644 index 0000000000000000000000000000000000000000..ed263837b4d8b4ae6bccf52517ee729635f6e9c7 --- /dev/null +++ b/pool/shard006/C/0118748_ppc64.c @@ -0,0 +1,94 @@ +/* + * ppc64.c + * + * Created by: Sachin Sant (sachinp@in.ibm.com) + * Copyright (C) IBM Corporation, 2006. All rights reserved + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation (version 2 of the License). + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#ifdef __powerpc__ + +#include "makedumpfile.h" + +int +get_machdep_info_ppc64(void) +{ + unsigned long vmlist, vmalloc_start; + + info->section_size_bits = _SECTION_SIZE_BITS; + info->max_physmem_bits = _MAX_PHYSMEM_BITS; + info->page_offset = __PAGE_OFFSET; + + if (SYMBOL(_stext) == NOT_FOUND_SYMBOL) { + ERRMSG("Can't get the symbol of _stext.\n"); + return FALSE; + } + info->kernel_start = SYMBOL(_stext); + DEBUG_MSG("kernel_start : %lx\n", info->kernel_start); + + /* + * For the compatibility, makedumpfile should run without the symbol + * vmlist and the offset of vm_struct.addr if they are not necessary. + */ + if ((SYMBOL(vmlist) == NOT_FOUND_SYMBOL) + || (OFFSET(vm_struct.addr) == NOT_FOUND_STRUCTURE)) { + return TRUE; + } + if (!readmem(VADDR, SYMBOL(vmlist), &vmlist, sizeof(vmlist))) { + ERRMSG("Can't get vmlist.\n"); + return FALSE; + } + if (!readmem(VADDR, vmlist + OFFSET(vm_struct.addr), &vmalloc_start, + sizeof(vmalloc_start))) { + ERRMSG("Can't get vmalloc_start.\n"); + return FALSE; + } + info->vmalloc_start = vmalloc_start; + DEBUG_MSG("vmalloc_start: %lx\n", vmalloc_start); + + return TRUE; +} + +int +is_vmalloc_addr_ppc64(unsigned long vaddr) +{ + return (info->vmalloc_start && vaddr >= info->vmalloc_start); +} + +unsigned long long +vaddr_to_paddr_ppc64(unsigned long vaddr) +{ + unsigned long long paddr; + + paddr = vaddr_to_paddr_general(vaddr); + if (paddr != NOT_PADDR) + return paddr; + + if ((SYMBOL(vmlist) == NOT_FOUND_SYMBOL) + || (OFFSET(vm_struct.addr) == NOT_FOUND_STRUCTURE)) { + ERRMSG("Can't get necessary information for vmalloc translation.\n"); + return NOT_PADDR; + } + if (!is_vmalloc_addr_ppc64(vaddr)) + return (vaddr - info->kernel_start); + + /* + * TODO: Support vmalloc translation. + */ + ERRMSG("This makedumpfile does not support vmalloc translation.\n"); + return NOT_PADDR; +} + +#endif /* powerpc */ diff --git a/pool/shard006/C/0118750_bsp_dac8501.c b/pool/shard006/C/0118750_bsp_dac8501.c new file mode 100644 index 0000000000000000000000000000000000000000..14256cae72cae02a7962df81b0807c1b45ae87d7 --- /dev/null +++ b/pool/shard006/C/0118750_bsp_dac8501.c @@ -0,0 +1,299 @@ +/* +********************************************************************************************************* +* +* Ä£¿éÃû³Æ : DAC8501 Çý¶¯Ä£¿é(µ¥Í¨µÀ´ø16λDAC) +* ÎļþÃû³Æ : bsp_dac8501.c +* °æ ±¾ : V1.0 +* ˵ Ã÷ : DAC8501Ä£¿éºÍCPUÖ®¼ä²ÉÓÃSPI½Ó¿Ú¡£±¾Çý¶¯³ÌÐòÖ§³ÖÓ²¼þSPI½Ó¿ÚºÍÈí¼þSPI½Ó¿Ú¡£ +* ͨ¹ýºêÇл»¡£ +* +* Ð޸ļǼ : +* °æ±¾ºÅ ÈÕÆÚ ×÷Õß ËµÃ÷ +* V1.0 2014-01-17 armfly Õýʽ·¢²¼ +* +* Copyright (C), 2013-2014, °²¸»À³µç×Ó www.armfly.com +* +********************************************************************************************************* +*/ + +#include "bsp.h" + +/* + DAC8501Ä£¿é¿ÉÒÔÖ±½Ó²åµ½STM32-V5¿ª·¢°åCN19ÅÅĸ(2*4P 2.54mm)½Ó¿ÚÉÏ + + DAC8501Ä£¿é STM32F407¿ª·¢°å + VCC ------ 3.3V + GND ------ GND + SCLK ------ PB3/SPI3_SCK + MOSI ------ PB5/SPI3_MOSI + CS1 ------ PF7/NRF24L01_CSN + CS2 ------ PA4/NRF905_TX_EN/NRF24L01_CE/DAC1_OUT + ------ PB4/SPI3_MISO + ------ PH7/NRF24L01_IRQ + +*/ + +/* + DAC8501»ù±¾ÌØÐÔ: + 1¡¢¹©µç2.7 - 5V; ¡¾±¾ÀýʹÓÃ3.3V¡¿ + 4¡¢²Î¿¼µçѹ2.5V (ÍÆ¼öȱʡµÄ£¬ÍâÖõģ© + + ¶ÔSPIµÄʱÖÓËÙ¶ÈÒªÇó: ¸ß´ï30MHz£¬ ËٶȺܿì. + SCLKϽµÑضÁÈ¡Êý¾Ý, ÿ´Î´«ËÍ24bitÊý¾Ý£¬ ¸ßλÏÈ´« +*/ + +#define DAC8501_RCC_CS1 RCC_AHB1Periph_GPIOF +#define DAC8501_PORT_CS1 GPIOF +#define DAC8501_PIN_CS1 GPIO_Pin_7 +#define DAC8501_CS1_1() DAC8501_PORT_CS1->BSRRL = DAC8501_PIN_CS1 +#define DAC8501_CS1_0() DAC8501_PORT_CS1->BSRRH = DAC8501_PIN_CS1 + +#define DAC8501_RCC_CS2 RCC_AHB1Periph_GPIOA +#define DAC8501_PORT_CS2 GPIOA +#define DAC8501_PIN_CS2 GPIO_Pin_4 +#define DAC8501_CS2_1() DAC8501_PORT_CS2->BSRRL = DAC8501_PIN_CS2 +#define DAC8501_CS2_0() DAC8501_PORT_CS2->BSRRH = DAC8501_PIN_CS2 + +/* ¶¨ÒåµçѹºÍDACÖµ¼äµÄ¹ØÏµ¡£ Á½µãУ׼ xÊÇdac y Êǵçѹ 0.1mV */ +#define X1 100 +#define Y1 50 + +#define X2 65000 +#define Y2 49400 + +static void DAC8501_ConfigGPIO(void); + +/* +********************************************************************************************************* +* º¯ Êý Ãû: bsp_InitDAC8501 +* ¹¦ÄÜ˵Ã÷: ÅäÖÃSTM32µÄGPIOºÍSPI½Ó¿Ú£¬ÓÃÓÚÁ¬½Ó ADS1256 +* ÐÎ ²Î: ÎÞ +* ·µ »Ø Öµ: ÎÞ +********************************************************************************************************* +*/ +void bsp_InitDAC8501(void) +{ + DAC8501_ConfigGPIO(); + + DAC8501_SetDacData(0, 0); + DAC8501_SetDacData(1, 0); +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_CfgSpiHard +* ¹¦ÄÜ˵Ã÷: ÅäÖÃSTM32ÄÚ²¿SPIÓ²¼þµÄ¹¤×÷ģʽ¡¢ËٶȵȲÎÊý£¬ÓÃÓÚ·ÃÎÊTM7705 +* ÐÎ ²Î: ÎÞ +* ·µ »Ø Öµ: ÎÞ +********************************************************************************************************* +*/ +void DAC8501_CfgSpiHard(void) +{ + SPI_InitTypeDef SPI_InitStructure; + + /* ÅäÖà SPI1¹¤×÷ģʽ */ + SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; + SPI_InitStructure.SPI_Mode = SPI_Mode_Master; + SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; + SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; + SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; + SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; /* Èí¼þ¿ØÖÆÆ¬Ñ¡ */ + + SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8; + SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; + SPI_InitStructure.SPI_CRCPolynomial = 7; + SPI_Init(SPI1,&SPI_InitStructure); + + /* ʹÄÜ SPI1 */ + SPI_Cmd(SPI1,ENABLE); +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_SetCS1(0) +* ¹¦ÄÜ˵Ã÷: ÉèÖÃCS1¡£ ÓÃÓÚÔËÐÐÖÐSPI¹²Ïí¡£ +* ÐÎ ²Î: ÎÞ + ·µ »Ø Öµ: ÎÞ +********************************************************************************************************* +*/ +void DAC8501_SetCS1(uint8_t _level) +{ + if (_level == 0) + { + bsp_SpiBusEnter(); /* Õ¼ÓÃSPI×ÜÏߣ¬ ÓÃÓÚ×ÜÏß¹²Ïí */ + + #ifdef SOFT_SPI /* Èí¼þSPI */ + bsp_SetSpiSck(0); + DAC8501_CS1_0(); + #endif + + #ifdef HARD_SPI /* Ó²¼þSPI */ + bsp_SPI_Init(SPI_Direction_2Lines_FullDuplex | SPI_Mode_Master | SPI_DataSize_8b + | SPI_CPOL_Low | SPI_CPHA_1Edge | SPI_NSS_Soft | SPI_BaudRatePrescaler_8 | SPI_FirstBit_MSB); + + DAC8501_CS1_0(); + #endif + } + else + { + DAC8501_CS1_1(); + + bsp_SpiBusExit(); /* ÊÍ·ÅSPI×ÜÏߣ¬ ÓÃÓÚ×ÜÏß¹²Ïí */ + } +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_SetCS2(0) +* ¹¦ÄÜ˵Ã÷: ÉèÖÃCS2¡£ ÓÃÓÚÔËÐÐÖÐSPI¹²Ïí¡£ +* ÐÎ ²Î: ÎÞ + ·µ »Ø Öµ: ÎÞ +********************************************************************************************************* +*/ +void DAC8501_SetCS2(uint8_t _level) +{ + if (_level == 0) + { + bsp_SpiBusEnter(); /* Õ¼ÓÃSPI×ÜÏߣ¬ ÓÃÓÚ×ÜÏß¹²Ïí */ + + #ifdef SOFT_SPI /* Èí¼þSPI */ + bsp_SetSpiSck(0); + DAC8501_CS2_0(); + #endif + + #ifdef HARD_SPI /* Ó²¼þSPI */ + bsp_SPI_Init(SPI_Direction_2Lines_FullDuplex | SPI_Mode_Master | SPI_DataSize_8b + | SPI_CPOL_Low | SPI_CPHA_1Edge | SPI_NSS_Soft | SPI_BaudRatePrescaler_8 | SPI_FirstBit_MSB); + + DAC8501_CS2_0(); + #endif + } + else + { + DAC8501_CS2_1(); + + bsp_SpiBusExit(); /* ÊÍ·ÅSPI×ÜÏߣ¬ ÓÃÓÚ×ÜÏß¹²Ïí */ + } +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_ConfigGPIO +* ¹¦ÄÜ˵Ã÷: ÅäÖÃGPIO¡£ ²»°üÀ¨ SCK MOSI MISO ¹²ÏíµÄSPI×ÜÏß¡£ +* ÐÎ ²Î: ÎÞ +* ·µ »Ø Öµ: ÎÞ +********************************************************************************************************* +*/ +static void DAC8501_ConfigGPIO(void) +{ + GPIO_InitTypeDef GPIO_InitStructure; + + /* ´ò¿ªGPIOʱÖÓ */ + RCC_AHB1PeriphClockCmd(DAC8501_RCC_CS1 | DAC8501_RCC_CS2, ENABLE); + + /* ÅäÖü¸¸öÍÆÍêÊä³öIO */ + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; /* ÉèΪÊä³ö¿Ú */ + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; /* ÉèÎªÍÆÍìģʽ */ + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; /* ÉÏÏÂÀ­µç×費ʹÄÜ */ + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; /* IO¿Ú×î´óËÙ¶È */ + + GPIO_InitStructure.GPIO_Pin = DAC8501_PIN_CS1; + GPIO_Init(DAC8501_PORT_CS1, &GPIO_InitStructure); + + GPIO_InitStructure.GPIO_Pin = DAC8501_PIN_CS2; + GPIO_Init(DAC8501_PORT_CS2, &GPIO_InitStructure); +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_SetDacData +* ¹¦ÄÜ˵Ã÷: ÉèÖÃDACÊý¾Ý +* ÐÎ ²Î: _ch, ͨµÀ, +* _data : Êý¾Ý +* ·µ »Ø Öµ: ÎÞ +********************************************************************************************************* +*/ +void DAC8501_SetDacData(uint8_t _ch, uint16_t _dac) +{ + uint32_t data; + + /* + DAC8501.pdf page 12 ÓÐ24bit¶¨Òå + + DB24:18 = xxxxx ±£Áô + DB17£º PD1 + DB16£º PD0 + + DB15£º0 16λÊý¾Ý + + ÆäÖÐ PD1 PD0 ¾ö¶¨4ÖÖ¹¤×÷ģʽ + 0 0 ---> Õý³£¹¤×÷ģʽ + 0 1 ---> Êä³ö½Ó1KÅ·µ½GND + 1 0 ---> Êä³ö100KÅ·µ½GND + 1 1 ---> Êä³ö¸ß×è + */ + + data = _dac; /* PD1 PD0 = 00 Õý³£Ä£Ê½ */ + + if (_ch == 0) + { + DAC8501_SetCS1(0); + } + else + { + DAC8501_SetCS2(0); + } + + /*¡¡DAC8501 SCLKʱÖӸߴï30M£¬Òò´Ë¿ÉÒÔ²»ÑÓ³Ù */ + bsp_spiWrite0(data >> 16); + bsp_spiWrite0(data >> 8); + bsp_spiWrite0(data); + + if (_ch == 0) + { + DAC8501_SetCS1(1); + } + else + { + DAC8501_SetCS2(1); + } +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_DacToVoltage +* ¹¦ÄÜ˵Ã÷: ½«DACÖµ»»ËãΪµçѹֵ£¬µ¥Î»0.1mV +* ÐÎ ²Î: _dac 16λDAC×Ö +* ·µ »Ø Öµ: µçѹ¡£µ¥Î»0.1mV +********************************************************************************************************* +*/ +int32_t DAC8501_DacToVoltage(uint16_t _dac) +{ + int32_t y; + + /* CaculTwoPoint(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x);*/ + y = CaculTwoPoint(X1, Y1, X2, Y2, _dac); + if (y < 0) + { + y = 0; + } + return y; +} + +/* +********************************************************************************************************* +* º¯ Êý Ãû: DAC8501_DacToVoltage +* ¹¦ÄÜ˵Ã÷: ½«DACÖµ»»ËãΪµçѹֵ£¬µ¥Î» 0.1mV +* ÐÎ ²Î: _volt µçѹ¡£µ¥Î»0.1mV +* ·µ »Ø Öµ: 16λDAC×Ö +********************************************************************************************************* +*/ +uint32_t DAC8501_VoltageToDac(int32_t _volt) +{ + /* CaculTwoPoint(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x);*/ + return CaculTwoPoint(Y1, X1, Y2, X2, _volt); +} + + + +/***************************** °²¸»À³µç×Ó www.armfly.com (END OF FILE) *********************************/ diff --git a/pool/shard006/C/0118751_cuckoo.c b/pool/shard006/C/0118751_cuckoo.c new file mode 100644 index 0000000000000000000000000000000000000000..b7a04a6a39515910b6c22ed9d6f13970b961a33b --- /dev/null +++ b/pool/shard006/C/0118751_cuckoo.c @@ -0,0 +1,251 @@ +/* + * This software module makes it possible to use Open Sound System for Linux + * (the _professional_ version) as a low level driver source for ALSA. + * + * Copyright (C) 2004-2009 Hannu Savolainen (hannu@opensound.com). + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License. + * + * 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. + */ + +/* + * !!!!!!!!!!!!!!!!!!!! Important !!!!!!!!!!!!!!!!!! + * + * If this file doesn't compile, you must not try to resolve the problem + * without perfect understanding of internals of Linux kernel, ALSA and + * Open Sound System. + * + * Instead you need to check that you are using the version of this file + * that matches the versions of ALSA, OSS and Linux you are currently using. + */ + +#ifndef KBUILD_MODNAME +#define KBUILD_MODNAME cuckoo +#endif + +#include "cuckoo.h" + +#include "./checksum.h" + +#ifdef VERMAGIC_STRING +static const char vermagic[] = VERMAGIC_STRING; +#endif + +MODULE_AUTHOR ("Hannu Savolainen "); +MODULE_LICENSE ("GPL v2"); +//MODULE_CLASSES("{sound}"); +MODULE_DESCRIPTION ("OSS low level driver interface for ALSA"); + +#define CUCKOO_MAXCARD SNDRV_CARDS +static int index[CUCKOO_MAXCARD] = SNDRV_DEFAULT_IDX; +static char *id[CUCKOO_MAXCARD] = SNDRV_DEFAULT_STR; +static int enable[CUCKOO_MAXCARD] = SNDRV_DEFAULT_ENABLE_PNP; + +static int +snd_cuckoo_free (cuckoo_t * chip) +{ + // TODO + return 0; +} + +static int +snd_cuckoo_dev_free (snd_device_t * device) +{ + cuckoo_t *cuckoo = (cuckoo_t *) device->device_data; + return snd_cuckoo_free (cuckoo); +} + +static int +snd_cuckoo_create (snd_card_t * card, int osscard, cuckoo_t ** rchip) +{ + cuckoo_t *chip; + int err; + + static snd_device_ops_t ops = { + .dev_free = snd_cuckoo_dev_free + }; + + *rchip = NULL; + + if ((chip = (cuckoo_t *) kmalloc (sizeof (cuckoo_t), GFP_KERNEL)) == NULL) + return -ENOMEM; + + chip->card = card; + chip->osscard = osscard; + chip->ncapture = chip->nplay = chip->npcm = 0; + + if ((err = snd_device_new (card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) + { + snd_cuckoo_free (chip); + return err; + } + + *rchip = chip; + return 0; +} + +static snd_card_t *cards[SNDRV_CARDS]; +static int ncards = 0; + +int +init_module (void) +{ + int err; + int dev, cardno; + char tmp[100]; + int pass; + +#if 0 + // TODO + if ((err = udi_connect (WRAPPER_VERSION)) < 0) + return err; + + if (strcmp (oss_checksum, cuckoo_checksum) != 0) + { + printk + ("cuckoo: Error OSS incompatibility problem. Please recompile.\n"); + return -EIO; + } +#endif + + for (pass = 0; pass < 2; pass++) + { + cardno = -1; + + for (dev = 0; dev < num_audio_engines; dev++) + { + adev_p adev = audio_engines[dev]; + cuckoo_t *chip; + snd_card_t *card = NULL; + + if (pass == 0) + { + // Ignore non-virtual devices + if (!(adev->flags & ADEV_VIRTUAL)) + continue; + } + else + { + // Ignore virtual devices + if ((adev->flags & ADEV_VIRTUAL)) + continue; + } + + if (adev->card_number < 0) + { + printk ("cuckoo: Ignored audio device %d - %s\n", dev, + adev->name); + continue; + } + + if (adev->card_number != cardno) + { + oss_card_info cd; + + cardno = adev->card_number; + + if (oss_get_cardinfo (cardno, &cd) < 0) + { + printk ("oss_get_cardinfo(%d) failed\n", cardno); + continue; + } + + // printk("Card %d: %s/%s\n", cardno, cd.shortname, cd.longname); + printk ("Card %d: %s/%s\n", cardno, cd.shortname, cd.longname); + + if (ncards >= CUCKOO_MAXCARD) + { + printk + ("Cuckoo: Too many audio devices (%d), only %d supported. by ALSA.\n", + num_audio_engines, CUCKOO_MAXCARD); + return -EIO; + } + + if (!enable[ncards]) + { + printk ("cuckoo: Device was not enabled (yet)\n"); + return -EIO; + } + +#if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) + if ((card = + snd_card_new (index[ncards], id[ncards], THIS_MODULE, + 0)) == NULL) +#else + if ( + snd_card_create (index[ncards], id[ncards], THIS_MODULE, + 0, &card) != 0) +#endif + { + printk ("cuckoo: Can't create a card instance\n"); + return -EIO; + } + + if ((err = snd_cuckoo_create (card, cardno, &chip)) < 0) + { + printk ("cuckoo: Couldn't create a chip instance (%d)\n", + err); + snd_card_free (card); + return err; + } + +#define oss_version_string "v4.x" // TODO + sprintf (tmp, "OSS %s", oss_version_string); + strlcpy (card->driver, tmp); + strlcpy (card->shortname, cd.shortname); + strlcpy (card->longname, cd.longname); + + if ((err = install_pcm_instances (chip, cardno)) < 0) + return err; + + if ((err = install_mixer_instances (chip, cardno)) < 0) + return err; + + // if ((err=install_midiport_instances(chip, cardno))<0) + // return err; + + if ((err = snd_card_register (card)) < 0) + { + printk ("cuckoo: Couldn't register card(%s) err=%d\n", + card->shortname, err); + continue; // TODO: Should handle this in more intelligent way + + snd_card_free (card); + return err; + } + + cards[ncards++] = card; + } + } + } + + return 0; +} + +void +cleanup_module (void) +{ + int i; + + for (i = 0; i < ncards; i++) + snd_card_free (cards[i]); +} + +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,5)) +#undef unix +struct module __this_module + __attribute__ ((section (".gnu.linkonce.this_module"))) = +{ + .name = __stringify (KBUILD_MODNAME),.init = init_module, +#ifdef CONFIG_MODULE_UNLOAD + .exit = cleanup_module +#endif +}; +#endif diff --git a/pool/shard006/C/0118754_crc32c-intel.c b/pool/shard006/C/0118754_crc32c-intel.c new file mode 100644 index 0000000000000000000000000000000000000000..969a037f942d24e9509b11217fd3123e01658aea --- /dev/null +++ b/pool/shard006/C/0118754_crc32c-intel.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include +#include +#include "crc32c.h" + +/* + * Based on a posting to lkml by Austin Zhang + * + * Using hardware provided CRC32 instruction to accelerate the CRC32 disposal. + * CRC32C polynomial:0x1EDC6F41(BE)/0x82F63B78(LE) + * CRC32 is a new instruction in Intel SSE4.2, the reference can be found at: + * http://www.intel.com/products/processor/manuals/ + * Intel(R) 64 and IA-32 Architectures Software Developer's Manual + * Volume 2A: Instruction Set Reference, A-M + */ + +#ifdef ARCH_HAVE_SSE4_2 + +#if BITS_PER_LONG == 64 +#define REX_PRE "0x48, " +#define SCALE_F 8 +#else +#define REX_PRE +#define SCALE_F 4 +#endif + +uint32_t crc32c_intel_le_hw_byte(uint32_t crc, unsigned char const *data, + unsigned long length) +{ + while (length--) { + __asm__ __volatile__( + ".byte 0xf2, 0xf, 0x38, 0xf0, 0xf1" + :"=S"(crc) + :"0"(crc), "c"(*data) + ); + data++; + } + + return crc; +} + +/* + * Steps through buffer one byte at at time, calculates reflected + * crc using table. + */ +uint32_t crc32c_intel(unsigned char const *data, unsigned long length) +{ + unsigned int iquotient = length / SCALE_F; + unsigned int iremainder = length % SCALE_F; +#if BITS_PER_LONG == 64 + uint64_t *ptmp = (uint64_t *) data; +#else + uint32_t *ptmp = (uint32_t *) data; +#endif + uint32_t crc = ~0; + + while (iquotient--) { + __asm__ __volatile__( + ".byte 0xf2, " REX_PRE "0xf, 0x38, 0xf1, 0xf1;" + :"=S"(crc) + :"0"(crc), "c"(*ptmp) + ); + ptmp++; + } + + if (iremainder) + crc = crc32c_intel_le_hw_byte(crc, (unsigned char *)ptmp, + iremainder); + + return crc; +} + +static void do_cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx, + unsigned int *edx) +{ + int id = *eax; + + asm("movl %4, %%eax;" + "cpuid;" + "movl %%eax, %0;" + "movl %%ebx, %1;" + "movl %%ecx, %2;" + "movl %%edx, %3;" + : "=r" (*eax), "=r" (*ebx), "=r" (*ecx), "=r" (*edx) + : "r" (id) + : "eax", "ebx", "ecx", "edx"); +} + +int crc32c_intel_works(void) +{ + unsigned int eax, ebx, ecx, edx; + + eax = 1; + + do_cpuid(&eax, &ebx, &ecx, &edx); + return (ecx & (1 << 20)) != 0; +} + +#endif /* ARCH_HAVE_SSE */ diff --git a/pool/shard006/C/0118758_kcmp_test.c b/pool/shard006/C/0118758_kcmp_test.c new file mode 100644 index 0000000000000000000000000000000000000000..6ea7b9f37a411ee60e63160fa117cd7077fad41b --- /dev/null +++ b/pool/shard006/C/0118758_kcmp_test.c @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-2.0 +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "../kselftest.h" + +static long sys_kcmp(int pid1, int pid2, int type, unsigned long fd1, unsigned long fd2) +{ + return syscall(__NR_kcmp, pid1, pid2, type, fd1, fd2); +} + +static const unsigned int duped_num = 64; + +int main(int argc, char **argv) +{ + const char kpath[] = "kcmp-test-file"; + struct kcmp_epoll_slot epoll_slot; + struct epoll_event ev; + int pid1, pid2; + int pipefd[2]; + int fd1, fd2; + int epollfd; + int status; + int fddup; + + fd1 = open(kpath, O_RDWR | O_CREAT | O_TRUNC, 0644); + pid1 = getpid(); + + if (fd1 < 0) { + perror("Can't create file"); + ksft_exit_fail(); + } + + if (pipe(pipefd)) { + perror("Can't create pipe"); + ksft_exit_fail(); + } + + epollfd = epoll_create1(0); + if (epollfd < 0) { + perror("epoll_create1 failed"); + ksft_exit_fail(); + } + + memset(&ev, 0xff, sizeof(ev)); + ev.events = EPOLLIN | EPOLLOUT; + + if (epoll_ctl(epollfd, EPOLL_CTL_ADD, pipefd[0], &ev)) { + perror("epoll_ctl failed"); + ksft_exit_fail(); + } + + fddup = dup2(pipefd[1], duped_num); + if (fddup < 0) { + perror("dup2 failed"); + ksft_exit_fail(); + } + + if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fddup, &ev)) { + perror("epoll_ctl failed"); + ksft_exit_fail(); + } + close(fddup); + + pid2 = fork(); + if (pid2 < 0) { + perror("fork failed"); + ksft_exit_fail(); + } + + if (!pid2) { + int pid2 = getpid(); + int ret; + + fd2 = open(kpath, O_RDWR, 0644); + if (fd2 < 0) { + perror("Can't open file"); + ksft_exit_fail(); + } + + /* An example of output and arguments */ + printf("pid1: %6d pid2: %6d FD: %2ld FILES: %2ld VM: %2ld " + "FS: %2ld SIGHAND: %2ld IO: %2ld SYSVSEM: %2ld " + "INV: %2ld\n", + pid1, pid2, + sys_kcmp(pid1, pid2, KCMP_FILE, fd1, fd2), + sys_kcmp(pid1, pid2, KCMP_FILES, 0, 0), + sys_kcmp(pid1, pid2, KCMP_VM, 0, 0), + sys_kcmp(pid1, pid2, KCMP_FS, 0, 0), + sys_kcmp(pid1, pid2, KCMP_SIGHAND, 0, 0), + sys_kcmp(pid1, pid2, KCMP_IO, 0, 0), + sys_kcmp(pid1, pid2, KCMP_SYSVSEM, 0, 0), + + /* This one should fail */ + sys_kcmp(pid1, pid2, KCMP_TYPES + 1, 0, 0)); + + /* This one should return same fd */ + ret = sys_kcmp(pid1, pid2, KCMP_FILE, fd1, fd1); + if (ret) { + printf("FAIL: 0 expected but %d returned (%s)\n", + ret, strerror(errno)); + ksft_inc_fail_cnt(); + ret = -1; + } else { + printf("PASS: 0 returned as expected\n"); + ksft_inc_pass_cnt(); + } + + /* Compare with self */ + ret = sys_kcmp(pid1, pid1, KCMP_VM, 0, 0); + if (ret) { + printf("FAIL: 0 expected but %d returned (%s)\n", + ret, strerror(errno)); + ksft_inc_fail_cnt(); + ret = -1; + } else { + printf("PASS: 0 returned as expected\n"); + ksft_inc_pass_cnt(); + } + + /* Compare epoll target */ + epoll_slot = (struct kcmp_epoll_slot) { + .efd = epollfd, + .tfd = duped_num, + .toff = 0, + }; + ret = sys_kcmp(pid1, pid1, KCMP_EPOLL_TFD, pipefd[1], + (unsigned long)(void *)&epoll_slot); + if (ret) { + printf("FAIL: 0 expected but %d returned (%s)\n", + ret, strerror(errno)); + ksft_inc_fail_cnt(); + ret = -1; + } else { + printf("PASS: 0 returned as expected\n"); + ksft_inc_pass_cnt(); + } + + ksft_print_cnts(); + + if (ret) + ksft_exit_fail(); + else + ksft_exit_pass(); + } + + waitpid(pid2, &status, P_ALL); + + return ksft_exit_pass(); +} diff --git a/pool/shard006/C/0118762_async-wrapper.c b/pool/shard006/C/0118762_async-wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..23c9795cbe01847c4a564153d6022f50b28ff86a --- /dev/null +++ b/pool/shard006/C/0118762_async-wrapper.c @@ -0,0 +1,39 @@ +/* ©2015 Stephen Chandler Paul + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +#include "async-wrapper.h" + +void +_libwc_blocking_task_init(LibWCBlockingTask *task) { + g_cond_init(&task->cond); + g_mutex_init(&task->mutex); + + g_mutex_lock(&task->mutex); +} + +void +_libwc_blocking_task_wait_until_finish(LibWCBlockingTask *task) { + g_cond_wait(&task->cond, &task->mutex); + g_mutex_unlock(&task->mutex); +} + +void +_libwc_unblock_on_finish(GObject *source_object, + GAsyncResult *res, + void *user_data) { + LibWCBlockingTask *task = user_data; + + task->res = g_object_ref(res); + + g_cond_broadcast(&task->cond); +} diff --git a/pool/shard006/C/0118763_speedstep-ich.c b/pool/shard006/C/0118763_speedstep-ich.c new file mode 100644 index 0000000000000000000000000000000000000000..f2076d72bf39966b7ceff580f663ede1fda4f70a --- /dev/null +++ b/pool/shard006/C/0118763_speedstep-ich.c @@ -0,0 +1,386 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * (C) 2001 Dave Jones, Arjan van de ven. + * (C) 2002 - 2003 Dominik Brodowski + * + * Based upon reverse engineered information, and on Intel documentation + * for chipsets ICH2-M and ICH3-M. + * + * Many thanks to Ducrot Bruno for finding and fixing the last + * "missing link" for ICH2-M/ICH3-M support, and to Thomas Winkler + * for extensive testing. + * + * BIG FAT DISCLAIMER: Work in progress code. Possibly *dangerous* + */ + + +/********************************************************************* + * SPEEDSTEP - DEFINITIONS * + *********************************************************************/ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include + +#include + +#include "speedstep-lib.h" + + +/* speedstep_chipset: + * It is necessary to know which chipset is used. As accesses to + * this device occur at various places in this module, we need a + * static struct pci_dev * pointing to that device. + */ +static struct pci_dev *speedstep_chipset_dev; + + +/* speedstep_processor + */ +static enum speedstep_processor speedstep_processor; + +static u32 pmbase; + +/* + * There are only two frequency states for each processor. Values + * are in kHz for the time being. + */ +static struct cpufreq_frequency_table speedstep_freqs[] = { + {0, SPEEDSTEP_HIGH, 0}, + {0, SPEEDSTEP_LOW, 0}, + {0, 0, CPUFREQ_TABLE_END}, +}; + + +/** + * speedstep_find_register - read the PMBASE address + * + * Returns: -ENODEV if no register could be found + */ +static int speedstep_find_register(void) +{ + if (!speedstep_chipset_dev) + return -ENODEV; + + /* get PMBASE */ + pci_read_config_dword(speedstep_chipset_dev, 0x40, &pmbase); + if (!(pmbase & 0x01)) { + pr_err("could not find speedstep register\n"); + return -ENODEV; + } + + pmbase &= 0xFFFFFFFE; + if (!pmbase) { + pr_err("could not find speedstep register\n"); + return -ENODEV; + } + + pr_debug("pmbase is 0x%x\n", pmbase); + return 0; +} + +/** + * speedstep_set_state - set the SpeedStep state + * @state: new processor frequency state (SPEEDSTEP_LOW or SPEEDSTEP_HIGH) + * + * Tries to change the SpeedStep state. Can be called from + * smp_call_function_single. + */ +static void speedstep_set_state(unsigned int state) +{ + u8 pm2_blk; + u8 value; + unsigned long flags; + + if (state > 0x1) + return; + + /* Disable IRQs */ + local_irq_save(flags); + + /* read state */ + value = inb(pmbase + 0x50); + + pr_debug("read at pmbase 0x%x + 0x50 returned 0x%x\n", pmbase, value); + + /* write new state */ + value &= 0xFE; + value |= state; + + pr_debug("writing 0x%x to pmbase 0x%x + 0x50\n", value, pmbase); + + /* Disable bus master arbitration */ + pm2_blk = inb(pmbase + 0x20); + pm2_blk |= 0x01; + outb(pm2_blk, (pmbase + 0x20)); + + /* Actual transition */ + outb(value, (pmbase + 0x50)); + + /* Restore bus master arbitration */ + pm2_blk &= 0xfe; + outb(pm2_blk, (pmbase + 0x20)); + + /* check if transition was successful */ + value = inb(pmbase + 0x50); + + /* Enable IRQs */ + local_irq_restore(flags); + + pr_debug("read at pmbase 0x%x + 0x50 returned 0x%x\n", pmbase, value); + + if (state == (value & 0x1)) + pr_debug("change to %u MHz succeeded\n", + speedstep_get_frequency(speedstep_processor) / 1000); + else + pr_err("change failed - I/O error\n"); + + return; +} + +/* Wrapper for smp_call_function_single. */ +static void _speedstep_set_state(void *_state) +{ + speedstep_set_state(*(unsigned int *)_state); +} + +/** + * speedstep_activate - activate SpeedStep control in the chipset + * + * Tries to activate the SpeedStep status and control registers. + * Returns -EINVAL on an unsupported chipset, and zero on success. + */ +static int speedstep_activate(void) +{ + u16 value = 0; + + if (!speedstep_chipset_dev) + return -EINVAL; + + pci_read_config_word(speedstep_chipset_dev, 0x00A0, &value); + if (!(value & 0x08)) { + value |= 0x08; + pr_debug("activating SpeedStep (TM) registers\n"); + pci_write_config_word(speedstep_chipset_dev, 0x00A0, value); + } + + return 0; +} + + +/** + * speedstep_detect_chipset - detect the Southbridge which contains SpeedStep logic + * + * Detects ICH2-M, ICH3-M and ICH4-M so far. The pci_dev points to + * the LPC bridge / PM module which contains all power-management + * functions. Returns the SPEEDSTEP_CHIPSET_-number for the detected + * chipset, or zero on failure. + */ +static unsigned int speedstep_detect_chipset(void) +{ + speedstep_chipset_dev = pci_get_subsys(PCI_VENDOR_ID_INTEL, + PCI_DEVICE_ID_INTEL_82801DB_12, + PCI_ANY_ID, PCI_ANY_ID, + NULL); + if (speedstep_chipset_dev) + return 4; /* 4-M */ + + speedstep_chipset_dev = pci_get_subsys(PCI_VENDOR_ID_INTEL, + PCI_DEVICE_ID_INTEL_82801CA_12, + PCI_ANY_ID, PCI_ANY_ID, + NULL); + if (speedstep_chipset_dev) + return 3; /* 3-M */ + + + speedstep_chipset_dev = pci_get_subsys(PCI_VENDOR_ID_INTEL, + PCI_DEVICE_ID_INTEL_82801BA_10, + PCI_ANY_ID, PCI_ANY_ID, + NULL); + if (speedstep_chipset_dev) { + /* speedstep.c causes lockups on Dell Inspirons 8000 and + * 8100 which use a pretty old revision of the 82815 + * host bridge. Abort on these systems. + */ + struct pci_dev *hostbridge; + + hostbridge = pci_get_subsys(PCI_VENDOR_ID_INTEL, + PCI_DEVICE_ID_INTEL_82815_MC, + PCI_ANY_ID, PCI_ANY_ID, + NULL); + + if (!hostbridge) + return 2; /* 2-M */ + + if (hostbridge->revision < 5) { + pr_debug("hostbridge does not support speedstep\n"); + speedstep_chipset_dev = NULL; + pci_dev_put(hostbridge); + return 0; + } + + pci_dev_put(hostbridge); + return 2; /* 2-M */ + } + + return 0; +} + +static void get_freq_data(void *_speed) +{ + unsigned int *speed = _speed; + + *speed = speedstep_get_frequency(speedstep_processor); +} + +static unsigned int speedstep_get(unsigned int cpu) +{ + unsigned int speed; + + /* You're supposed to ensure CPU is online. */ + BUG_ON(smp_call_function_single(cpu, get_freq_data, &speed, 1)); + + pr_debug("detected %u kHz as current frequency\n", speed); + return speed; +} + +/** + * speedstep_target - set a new CPUFreq policy + * @policy: new policy + * @index: index of target frequency + * + * Sets a new CPUFreq policy. + */ +static int speedstep_target(struct cpufreq_policy *policy, unsigned int index) +{ + unsigned int policy_cpu; + + policy_cpu = cpumask_any_and(policy->cpus, cpu_online_mask); + + smp_call_function_single(policy_cpu, _speedstep_set_state, &index, + true); + + return 0; +} + + +struct get_freqs { + struct cpufreq_policy *policy; + int ret; +}; + +static void get_freqs_on_cpu(void *_get_freqs) +{ + struct get_freqs *get_freqs = _get_freqs; + + get_freqs->ret = + speedstep_get_freqs(speedstep_processor, + &speedstep_freqs[SPEEDSTEP_LOW].frequency, + &speedstep_freqs[SPEEDSTEP_HIGH].frequency, + &get_freqs->policy->cpuinfo.transition_latency, + &speedstep_set_state); +} + +static int speedstep_cpu_init(struct cpufreq_policy *policy) +{ + unsigned int policy_cpu; + struct get_freqs gf; + + /* only run on CPU to be set, or on its sibling */ +#ifdef CONFIG_SMP + cpumask_copy(policy->cpus, topology_sibling_cpumask(policy->cpu)); +#endif + policy_cpu = cpumask_any_and(policy->cpus, cpu_online_mask); + + /* detect low and high frequency and transition latency */ + gf.policy = policy; + smp_call_function_single(policy_cpu, get_freqs_on_cpu, &gf, 1); + if (gf.ret) + return gf.ret; + + policy->freq_table = speedstep_freqs; + + return 0; +} + + +static struct cpufreq_driver speedstep_driver = { + .name = "speedstep-ich", + .verify = cpufreq_generic_frequency_table_verify, + .target_index = speedstep_target, + .init = speedstep_cpu_init, + .get = speedstep_get, + .attr = cpufreq_generic_attr, +}; + +static const struct x86_cpu_id ss_smi_ids[] = { + X86_MATCH_VENDOR_FAM_MODEL(INTEL, 6, 0x8, 0), + X86_MATCH_VENDOR_FAM_MODEL(INTEL, 6, 0xb, 0), + X86_MATCH_VENDOR_FAM_MODEL(INTEL, 15, 0x2, 0), + {} +}; + +/** + * speedstep_init - initializes the SpeedStep CPUFreq driver + * + * Initializes the SpeedStep support. Returns -ENODEV on unsupported + * devices, -EINVAL on problems during initiatization, and zero on + * success. + */ +static int __init speedstep_init(void) +{ + if (!x86_match_cpu(ss_smi_ids)) + return -ENODEV; + + /* detect processor */ + speedstep_processor = speedstep_detect_processor(); + if (!speedstep_processor) { + pr_debug("Intel(R) SpeedStep(TM) capable processor " + "not found\n"); + return -ENODEV; + } + + /* detect chipset */ + if (!speedstep_detect_chipset()) { + pr_debug("Intel(R) SpeedStep(TM) for this chipset not " + "(yet) available.\n"); + return -ENODEV; + } + + /* activate speedstep support */ + if (speedstep_activate()) { + pci_dev_put(speedstep_chipset_dev); + return -EINVAL; + } + + if (speedstep_find_register()) + return -ENODEV; + + return cpufreq_register_driver(&speedstep_driver); +} + + +/** + * speedstep_exit - unregisters SpeedStep support + * + * Unregisters SpeedStep support. + */ +static void __exit speedstep_exit(void) +{ + pci_dev_put(speedstep_chipset_dev); + cpufreq_unregister_driver(&speedstep_driver); +} + + +MODULE_AUTHOR("Dave Jones, Dominik Brodowski "); +MODULE_DESCRIPTION("Speedstep driver for Intel mobile processors on chipsets " + "with ICH-M southbridges."); +MODULE_LICENSE("GPL"); + +module_init(speedstep_init); +module_exit(speedstep_exit); diff --git a/pool/shard006/C/0118765_sh-quote.c b/pool/shard006/C/0118765_sh-quote.c new file mode 100644 index 0000000000000000000000000000000000000000..4a8582ee1f99cf54366ece87bb1d39f45798b573 --- /dev/null +++ b/pool/shard006/C/0118765_sh-quote.c @@ -0,0 +1,107 @@ +/* Shell quoting. + Copyright (C) 2001-2004, 2006, 2009-2012 Free Software Foundation, Inc. + Written by Bruno Haible , 2001. + + 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 . */ + +#include + +/* Specification. */ +#include "sh-quote.h" + +#include + +#include "quotearg.h" +#include "xalloc.h" + +/* Describes quoting for sh compatible shells. */ +static struct quoting_options *sh_quoting_options; + +/* Initializes the sh_quoting_options variable. */ +static void +init_sh_quoting_options () +{ + sh_quoting_options = clone_quoting_options (NULL); + set_quoting_style (sh_quoting_options, shell_quoting_style); +} + +/* Returns the number of bytes needed for the quoted string. */ +size_t +shell_quote_length (const char *string) +{ + if (sh_quoting_options == NULL) + init_sh_quoting_options (); + return quotearg_buffer (NULL, 0, string, strlen (string), + sh_quoting_options); +} + +/* Copies the quoted string to p and returns the incremented p. + There must be room for shell_quote_length (string) + 1 bytes at p. */ +char * +shell_quote_copy (char *p, const char *string) +{ + if (sh_quoting_options == NULL) + init_sh_quoting_options (); + return p + quotearg_buffer (p, (size_t)(-1), string, strlen (string), + sh_quoting_options); +} + +/* Returns the freshly allocated quoted string. */ +char * +shell_quote (const char *string) +{ + if (sh_quoting_options == NULL) + init_sh_quoting_options (); + return quotearg_alloc (string, strlen (string), sh_quoting_options); +} + +/* Returns a freshly allocated string containing all argument strings, quoted, + separated through spaces. */ +char * +shell_quote_argv (char * const *argv) +{ + if (*argv != NULL) + { + char * const *argp; + size_t length; + char *command; + char *p; + + length = 0; + for (argp = argv; ; ) + { + length += shell_quote_length (*argp) + 1; + argp++; + if (*argp == NULL) + break; + } + + command = XNMALLOC (length, char); + + p = command; + for (argp = argv; ; ) + { + p = shell_quote_copy (p, *argp); + argp++; + if (*argp == NULL) + break; + *p++ = ' '; + } + *p = '\0'; + + return command; + } + else + return xstrdup (""); +} diff --git a/pool/shard006/C/0118766_gm107.c b/pool/shard006/C/0118766_gm107.c new file mode 100644 index 0000000000000000000000000000000000000000..5afb55e58b517e406451a8203066e664629928c3 --- /dev/null +++ b/pool/shard006/C/0118766_gm107.c @@ -0,0 +1,55 @@ +/* + * Copyright 2013 Red Hat Inc. + * + * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. + * + * Authors: Ben Skeggs + */ +#include "priv.h" +#define gk208_pmu_code gm107_pmu_code +#define gk208_pmu_data gm107_pmu_data +#include "fuc/gk208.fuc5.h" + +static const struct nvkm_pmu_func +gm107_pmu = { + .flcn = >215_pmu_flcn, + .code.data = gm107_pmu_code, + .code.size = sizeof(gm107_pmu_code), + .data.data = gm107_pmu_data, + .data.size = sizeof(gm107_pmu_data), + .enabled = gf100_pmu_enabled, + .reset = gf100_pmu_reset, + .init = gt215_pmu_init, + .fini = gt215_pmu_fini, + .intr = gt215_pmu_intr, + .send = gt215_pmu_send, + .recv = gt215_pmu_recv, +}; + +static const struct nvkm_pmu_fwif +gm107_pmu_fwif[] = { + { -1, gf100_pmu_nofw, &gm107_pmu }, + {} +}; + +int +gm107_pmu_new(struct nvkm_device *device, int index, struct nvkm_pmu **ppmu) +{ + return nvkm_pmu_new_(gm107_pmu_fwif, device, index, ppmu); +} diff --git a/pool/shard006/C/0118768_main.c b/pool/shard006/C/0118768_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5af679d44db64aa5835d6a09d7ea30a262617ae3 --- /dev/null +++ b/pool/shard006/C/0118768_main.c @@ -0,0 +1,199 @@ +/* + *------------------------------------------------------------------ + * Copyright (c) 2005-2016 Cisco and/or its affiliates. + * 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 "g2.h" +#include "props.h" +#include +#include +#include +#include +#include +#include + +/* + * globals + */ + +GtkWidget *g_mainwindow; /* The main window */ + +/* Graphical object heirarchy + * + * [main window] + * [main vbox] + * [main (e.g. file) menubar] + * [view hbox] + * [view bottom menu] + */ + +GtkWidget *g_mainvbox; +GtkWidget *g_mainhbox; + +gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data) +{ + /* Allow window to be destroyed */ + return(FALSE); +} + +void destroy(GtkWidget *widget, gpointer data) +{ + gtk_main_quit(); +} + +int main (int argc, char **argv) +{ + char tmpbuf [128]; + struct passwd *pw; + char *event_file = 0; + char *cpel_file = 0; + char *clib_file =0; + char *title = "none"; + int curarg=1; + char *homedir; + + clib_mem_init (0, ((uword)3<<30)); + + gtk_init(&argc, &argv); + + homedir = getenv ("HOME"); + tmpbuf[0] = 0; + + if (homedir) { + snprintf(tmpbuf, sizeof(tmpbuf), "%s/.g2", homedir); + } else { + pw = getpwuid(geteuid()); + if (pw) { + snprintf(tmpbuf, sizeof(tmpbuf), "%s/.g2", pw->pw_dir); + } + } + if (tmpbuf[0]) + readprops(tmpbuf); + + g_mainwindow = gtk_window_new (GTK_WINDOW_TOPLEVEL); + + gtk_signal_connect (GTK_OBJECT(g_mainwindow), "delete_event", + GTK_SIGNAL_FUNC (delete_event), NULL); + + gtk_signal_connect (GTK_OBJECT(g_mainwindow), "destroy", + GTK_SIGNAL_FUNC (destroy), NULL); + + gtk_container_set_border_width(GTK_CONTAINER(g_mainwindow), 5); + + g_mainvbox = gtk_vbox_new(FALSE, 0); + g_mainhbox = gtk_hbox_new(FALSE, 0); + + /* + * init routines + */ + + menu1_init(); + point_selector_init(); + view1_init(); + event_init(); + + /* + * Now that we're ready to rock 'n roll, see if we've been asked to + * press a few buttons... + */ + + while (curarg < argc) { + if (!strncmp(argv[curarg], "--cpel-input", 4)) { + curarg++; + if (curarg < argc) { + cpel_file = argv[curarg]; + curarg++; + break; + } + g_error("Missing filename after --cpel-input"); + } + if (!strncmp(argv[curarg], "--clib-input", 4)) { + curarg++; + if (curarg < argc) { + clib_file = argv[curarg]; + curarg++; + break; + } + g_error("Missing filename after --cpel-input"); + } + + if (!strncmp(argv[curarg], "--pointdefs", 3)) { + curarg++; + if (curarg < argc) { + read_event_definitions(argv[curarg]); + curarg++; + continue; + } + g_error ("Missing filename after --pointdefs\n"); + } + if (!strncmp(argv[curarg], "--event-log", 3)) { + curarg++; + if (curarg < argc) { + event_file = argv[curarg]; + curarg++; + continue; + } + g_error ("Missing filename after --event-log\n"); + } + + if (!strncmp(argv[curarg], "--ticks-per-us", 3)) { + curarg++; + if (curarg < argc) { + ticks_per_ns = 0.0; + ticks_per_ns = atof(argv[curarg]); + if (ticks_per_ns == 0.0) { + g_error("ticks-per-ns (%s) didn't convert properly\n", + argv[curarg]); + } + ticks_per_ns_set = TRUE; + curarg++; + continue; + } + g_error ("Missing filename after --event-log\n"); + } + + fprintf(stderr, + "g2 [--pointdefs ] [--event-log ]\n"); + fprintf(stderr, " [--ticks-per-us ]\n"); + fprintf(stderr, + " [--cpel-input ] [--clib-input \n"); + fprintf(stderr, + "%s\n%s\n", version_string, minor_v_string); + exit(0); + } + + if (clib_file) { + read_clib_file (clib_file); + title = clib_file; + } else if (cpel_file) { + read_cpel_file(cpel_file); + title = cpel_file; + } else if (event_file) { + read_events(event_file); + title = event_file; + } + + set_window_title(title); + + gtk_signal_connect (GTK_OBJECT (g_mainwindow), "key_press_event", + (GtkSignalFunc) view1_handle_key_press_event, NULL); + gtk_container_add(GTK_CONTAINER(g_mainvbox), g_mainhbox); + gtk_widget_show(g_mainhbox); + gtk_container_add(GTK_CONTAINER(g_mainwindow), g_mainvbox); + gtk_widget_show(g_mainvbox); + gtk_widget_show(g_mainwindow); + + gtk_main(); + return(0); +} diff --git a/pool/shard006/C/0118769_wiring_serial.c b/pool/shard006/C/0118769_wiring_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..6c576d5647782fa66e59e386f5be18d2dd2bd6a6 --- /dev/null +++ b/pool/shard006/C/0118769_wiring_serial.c @@ -0,0 +1,129 @@ +/* + wiring_serial.c - serial functions. + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with this library; if not, write to the + Free Software Foundation, Inc., 59 Temple Place, Suite 330, + Boston, MA 02111-1307 USA + + $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ +*/ + +#include "wiring_private.h" + +// Define constants and variables for buffering incoming serial data. We're +// using a ring buffer (I think), in which rx_buffer_head is the index of the +// location to which to write the next incoming character and rx_buffer_tail +// is the index of the location from which to read. +#define RX_BUFFER_SIZE 128 + +unsigned char rx_buffer[RX_BUFFER_SIZE]; + +int rx_buffer_head = 0; +int rx_buffer_tail = 0; + +void beginSerial(long baud) +{ +#if defined(__AVR_ATmega8__) + UBRRH = ((F_CPU / 16 + baud / 2) / baud - 1) >> 8; + UBRRL = ((F_CPU / 16 + baud / 2) / baud - 1); + + // enable rx and tx + sbi(UCSRB, RXEN); + sbi(UCSRB, TXEN); + + // enable interrupt on complete reception of a byte + sbi(UCSRB, RXCIE); +#else + UBRR0H = ((F_CPU / 16 + baud / 2) / baud - 1) >> 8; + UBRR0L = ((F_CPU / 16 + baud / 2) / baud - 1); + + // enable rx and tx + sbi(UCSR0B, RXEN0); + sbi(UCSR0B, TXEN0); + + // enable interrupt on complete reception of a byte + sbi(UCSR0B, RXCIE0); +#endif + + // defaults to 8-bit, no parity, 1 stop bit +} + +void serialWrite(unsigned char c) +{ +#if defined(__AVR_ATmega8__) + while (!(UCSRA & (1 << UDRE))) + ; + + UDR = c; +#else + while (!(UCSR0A & (1 << UDRE0))) + ; + + UDR0 = c; +#endif +} + +int serialAvailable() +{ + return (RX_BUFFER_SIZE + rx_buffer_head - rx_buffer_tail) % RX_BUFFER_SIZE; +} + +int serialRead() +{ + // if the head isn't ahead of the tail, we don't have any characters + if (rx_buffer_head == rx_buffer_tail) { + return -1; + } else { + unsigned char c = rx_buffer[rx_buffer_tail]; + rx_buffer_tail = (rx_buffer_tail + 1) % RX_BUFFER_SIZE; + return c; + } +} + +void serialFlush() +{ + // don't reverse this or there may be problems if the RX interrupt + // occurs after reading the value of rx_buffer_head but before writing + // the value to rx_buffer_tail; the previous value of rx_buffer_head + // may be written to rx_buffer_tail, making it appear as if the buffer + // were full, not empty. + rx_buffer_head = rx_buffer_tail; +} + +#if defined(__AVR_ATmega8__) +SIGNAL(SIG_UART_RECV) +#else +SIGNAL(USART_RX_vect) +#endif +{ +#if defined(__AVR_ATmega8__) + unsigned char c = UDR; +#else + unsigned char c = UDR0; +#endif + + int i = (rx_buffer_head + 1) % RX_BUFFER_SIZE; + + // if we should be storing the received character into the location + // just before the tail (meaning that the head would advance to the + // current location of the tail), we're about to overflow the buffer + // and so we don't write the character or advance the head. + if (i != rx_buffer_tail) { + rx_buffer[rx_buffer_head] = c; + rx_buffer_head = i; + } +} \ No newline at end of file diff --git a/pool/shard006/C/0118770_gtcm_loop.c b/pool/shard006/C/0118770_gtcm_loop.c new file mode 100644 index 0000000000000000000000000000000000000000..7fb8f165f0b94a8d1339680c1415ac5b65bb1169 --- /dev/null +++ b/pool/shard006/C/0118770_gtcm_loop.c @@ -0,0 +1,255 @@ +/**************************************************************** + * * + * Copyright 2001, 2013 Fidelity Information Services, Inc * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +/* + * gtcm_loop.c --- + * + * GTCM server forever loop. BSD_TCP! + * + */ + +#include "mdef.h" + +#include "gtm_string.h" +#include "gtm_unistd.h" /* for execlp and fork */ +#include "gtm_stdlib.h" /* for exit */ +#include "gtm_stdio.h" /* for SPRINTF */ + +#include /* for wait */ + +#include "gtcm.h" + +#if defined(sun) || defined(mips) +# include +#else +# ifdef SEQUOIA +# include +# else +# include "gtm_time.h" +# endif +#endif + +#include +#ifdef DEBUG +#include "gtm_fcntl.h" +#endif /* defined(DEBUG) */ + +#include "gt_timer.h" /* for cancel_timer and start_timer and TID declaration at least */ +#include "error.h" +#include "gtmio.h" +#include "have_crit.h" +#include "gtm_time.h" + +#ifndef lint +static char rcsid[] = "$Header:$"; +#endif + +GBLREF int psock; +GBLREF int conn_timeout; +GBLREF int history; +GBLREF int omi_pid; +GBLDEF omi_conn *curr_conn; +GBLDEF boolean_t servtime_expired; +GBLREF int per_conn_servtime; + + +void hang_handler(void); +void gcore_server(void); + +error_def(ERR_OMISERVHANG); + +void gtcm_loop(omi_conn_ll *cll) +{ + extern int omi_exitp; + + int nfds, res; + int now, rsp; + fd_set r_fds, e_fds; + omi_conn *cptr, *prev; + struct timeval timeout, *tp; + + if (psock >= 0) + { + timeout.tv_sec = PING_TIMEOUT; + timeout.tv_usec = 0; + tp = &timeout; + } + else + tp = NULL; + + curr_conn = NULL; +/* Loop forever accepting connections and transactions */ + for (;;) { + + FD_ZERO(&r_fds); + FD_ZERO(&e_fds); + +/* Pay attention to the network visible end point */ + if (INV_FD_P((nfds = cll->nve))) + break; + FD_SET(cll->nve, &r_fds); + FD_SET(cll->nve, &e_fds); + if (psock >= 0) + FD_SET(psock, &r_fds); + +/* We will service transactions from any existing connection */ + for (cptr = cll->head; cptr; cptr = cptr->next) { + FD_SET(cptr->fd, &r_fds); + FD_SET(cptr->fd, &e_fds); + if (cptr->fd > nfds) + nfds = cptr->fd; + } + + if (omi_exitp) + break; + +/* Block in the system waiting for network events */ + nfds++; + if ((nfds = select(nfds, &r_fds, (fd_set *)0, (fd_set *)0, tp)) < 0) + { + if (errno == EINTR) { + if (!omi_exitp) + continue; + } + else if (errno == EAGAIN) /* temporary OS condition, retry */ + { + continue; + } + else + gtcm_rep_err("select() call failed", errno); + break; + } + + now = (int)time(0); + +/* if we are doing pinging...check the ping socket */ + if (psock >= 0 && FD_ISSET(psock, &r_fds)) + rsp = get_ping_rsp(); + else + rsp = -1; + +/* Loop through the connections servicing transactions */ + for (cptr = cll->head, prev = (omi_conn *)0; cptr; ) { + if (FD_ISSET(cptr->fd, &r_fds)) + { + servtime_expired = FALSE; /* inside hang handler this is set TRUE */ + start_timer((TID)gtcm_loop, per_conn_servtime * 1000, hang_handler, 0, NULL); + + curr_conn = cptr; + res = omi_srvc_xact(cptr); + curr_conn = NULL; + + cancel_timer((TID)gtcm_loop); + + if (res >= 0) + { + cptr->timeout = now + conn_timeout; + cptr->ping_cnt = 0; + } + else + { + if (prev) + prev->next = cptr->next; + else + cll->head = cptr->next; + if (cll->tail == cptr) + cll->tail = prev; + gtcm_cn_disc(cptr, cll); + cptr = prev; + } + nfds--; + } + else if (cptr->fd == rsp) /* got a ping response for socket */ + { + cptr->timeout = now + conn_timeout; + cptr->ping_cnt = 0; + } + else if (psock >= 0 && now >= cptr->timeout) + { + if (cptr->ping_cnt >= MAX_PING_CNT) + { + OMI_DBG((omi_debug, "%s: no response from connection %d, dropping...\n", + SRVR_NAME,cptr->stats.id)); + if (prev) + prev->next = cptr->next; + else + cll->head = cptr->next; + if (cll->tail == cptr) + cll->tail = prev; + gtcm_cn_disc(cptr, cll); + cptr = prev; + } + else + { + if (cptr->ping_cnt) + OMI_DBG((omi_debug, "%s: no response from connection %d, checking...\n", + SRVR_NAME,cptr->stats.id)); + else + OMI_DBG((omi_debug, "%s: checking connection %d.\n", + SRVR_NAME,cptr->stats.id)); + icmp_ping(cptr->fd); + cptr->ping_cnt++; + cptr->timeout = now + PING_TIMEOUT; + } + } + + if ((prev = cptr)) + cptr = cptr->next; + } + +/* If true, accept a new connection */ + if (nfds > 0 && FD_ISSET(cll->nve, &r_fds)) { + if (gtcm_cn_acpt(cll,now) < 0) { + gtcm_rep_err("Unable to accept new connection", errno); +/* break; eliminated: it is acceptable to retry */ + } + nfds--; + } + /* Sanity check: is nfds == 0? */ + } + return; +} + +void hang_handler(void) +{ + OMI_DBG_STMP; + OMI_DBG((omi_debug, "%s: server appears to be hung...generating core file...\n", + SRVR_NAME)); + gtcm_rep_err("", ERR_OMISERVHANG); + + gcore_server(); + wait(NULL); /* wait for a signal or the child to exit */ + servtime_expired = TRUE; +} + + +void gcore_server(void) +{ + int pid; + + if (history) + { + OMI_DBG((omi_debug, "%s: dumping RC history\n", SRVR_NAME)); + dump_rc_hist(); + } + + pid=fork(); /* BYPASSOK: we are dumping a core, so no FORK_CLEAN needed */ + if (pid < 0) /* fork error */ + { + OMI_DBG((omi_debug, + "%s: unable to start a new process to generate the core\n", + SRVR_NAME)); + perror(SRVR_NAME); + } else if (!pid) /* child */ + DUMP_CORE; +} + + diff --git a/pool/shard006/C/0118779_siginterrupt.c b/pool/shard006/C/0118779_siginterrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..d99b77233786953788f53797ec4ce1c48151cded --- /dev/null +++ b/pool/shard006/C/0118779_siginterrupt.c @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that 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. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)siginterrupt.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD$"); + +#include "namespace.h" +#include +#include "un-namespace.h" +#include "libc_private.h" + +/* + * Set signal state to prevent restart of system calls + * after an instance of the indicated signal. + */ +int +siginterrupt(int sig, int flag) +{ + extern sigset_t _sigintr __hidden; + struct sigaction sa; + int ret; + + if ((ret = __libc_sigaction(sig, (struct sigaction *)0, &sa)) < 0) + return (ret); + if (flag) { + sigaddset(&_sigintr, sig); + sa.sa_flags &= ~SA_RESTART; + } else { + sigdelset(&_sigintr, sig); + sa.sa_flags |= SA_RESTART; + } + return (__libc_sigaction(sig, &sa, (struct sigaction *)0)); +} diff --git a/pool/shard006/C/0118781_Keyboard.c b/pool/shard006/C/0118781_Keyboard.c new file mode 100644 index 0000000000000000000000000000000000000000..2cf16246bc7fb0dfc0d29a28f59afb1bbbad620c --- /dev/null +++ b/pool/shard006/C/0118781_Keyboard.c @@ -0,0 +1,267 @@ +/* + +Copyright 1993 by Davor Matic + +Permission to use, copy, modify, distribute, and sell this software +and its documentation for any purpose is hereby granted without fee, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation. Davor Matic makes no representations about +the suitability of this software for any purpose. It is provided "as +is" without express or implied warranty. + +*/ + +#ifdef HAVE_XNEST_CONFIG_H +#include +#endif + +#include +#include +#include +#include "screenint.h" +#include "inputstr.h" +#include "misc.h" +#include "scrnintstr.h" +#include "servermd.h" + +#include "Xnest.h" + +#include "Display.h" +#include "Screen.h" +#include "Keyboard.h" +#include "Args.h" +#include "Events.h" + +#include +#include "xkbsrv.h" +#include + +extern Bool + XkbQueryExtension(Display * /* dpy */ , + int * /* opcodeReturn */ , + int * /* eventBaseReturn */ , + int * /* errorBaseReturn */ , + int * /* majorRtrn */ , + int * /* minorRtrn */ + ); + +extern XkbDescPtr XkbGetKeyboard(Display * /* dpy */ , + unsigned int /* which */ , + unsigned int /* deviceSpec */ + ); + +extern Status XkbGetControls(Display * /* dpy */ , + unsigned long /* which */ , + XkbDescPtr /* desc */ + ); + +DeviceIntPtr xnestKeyboardDevice = NULL; + +void +xnestBell(int volume, DeviceIntPtr pDev, void *ctrl, int cls) +{ + XBell(xnestDisplay, volume); +} + +void +DDXRingBell(int volume, int pitch, int duration) +{ + XBell(xnestDisplay, volume); +} + +void +xnestChangeKeyboardControl(DeviceIntPtr pDev, KeybdCtrl * ctrl) +{ +#if 0 + unsigned long value_mask; + XKeyboardControl values; + int i; + + value_mask = KBKeyClickPercent | + KBBellPercent | KBBellPitch | KBBellDuration | KBAutoRepeatMode; + + values.key_click_percent = ctrl->click; + values.bell_percent = ctrl->bell; + values.bell_pitch = ctrl->bell_pitch; + values.bell_duration = ctrl->bell_duration; + values.auto_repeat_mode = ctrl->autoRepeat ? + AutoRepeatModeOn : AutoRepeatModeOff; + + XChangeKeyboardControl(xnestDisplay, value_mask, &values); + + /* + value_mask = KBKey | KBAutoRepeatMode; + At this point, we need to walk through the vector and compare it + to the current server vector. If there are differences, report them. + */ + + value_mask = KBLed | KBLedMode; + for (i = 1; i <= 32; i++) { + values.led = i; + values.led_mode = + (ctrl->leds & (1 << (i - 1))) ? LedModeOn : LedModeOff; + XChangeKeyboardControl(xnestDisplay, value_mask, &values); + } +#endif +} + +int +xnestKeyboardProc(DeviceIntPtr pDev, int onoff) +{ + XModifierKeymap *modifier_keymap; + KeySym *keymap; + int mapWidth; + int min_keycode, max_keycode; + KeySymsRec keySyms; + CARD8 modmap[MAP_LENGTH]; + int i, j; + XKeyboardState values; + XkbDescPtr xkb; + int op, event, error, major, minor; + + switch (onoff) { + case DEVICE_INIT: + XDisplayKeycodes(xnestDisplay, &min_keycode, &max_keycode); +#ifdef _XSERVER64 + { + KeySym64 *keymap64; + int len; + + keymap64 = XGetKeyboardMapping(xnestDisplay, + min_keycode, + max_keycode - min_keycode + 1, + &mapWidth); + len = (max_keycode - min_keycode + 1) * mapWidth; + keymap = (KeySym *) malloc(len * sizeof(KeySym)); + for (i = 0; i < len; ++i) + keymap[i] = keymap64[i]; + XFree(keymap64); + } +#else + keymap = XGetKeyboardMapping(xnestDisplay, + min_keycode, + max_keycode - min_keycode + 1, &mapWidth); +#endif + + memset(modmap, 0, sizeof(modmap)); + modifier_keymap = XGetModifierMapping(xnestDisplay); + for (j = 0; j < 8; j++) + for (i = 0; i < modifier_keymap->max_keypermod; i++) { + CARD8 keycode; + + if ((keycode = + modifier_keymap->modifiermap[j * + modifier_keymap-> + max_keypermod + i])) + modmap[keycode] |= 1 << j; + } + XFreeModifiermap(modifier_keymap); + + keySyms.minKeyCode = min_keycode; + keySyms.maxKeyCode = max_keycode; + keySyms.mapWidth = mapWidth; + keySyms.map = keymap; + + if (XkbQueryExtension(xnestDisplay, &op, &event, &error, &major, &minor) + == 0) { + ErrorF("Unable to initialize XKEYBOARD extension.\n"); + goto XkbError; + } + xkb = + XkbGetKeyboard(xnestDisplay, XkbGBN_AllComponentsMask, + XkbUseCoreKbd); + if (xkb == NULL || xkb->geom == NULL) { + ErrorF("Couldn't get keyboard.\n"); + goto XkbError; + } + XkbGetControls(xnestDisplay, XkbAllControlsMask, xkb); + + InitKeyboardDeviceStruct(pDev, NULL, + xnestBell, xnestChangeKeyboardControl); + + XkbApplyMappingChange(pDev, &keySyms, keySyms.minKeyCode, + keySyms.maxKeyCode - keySyms.minKeyCode + 1, + modmap, serverClient); + + XkbDDXChangeControls(pDev, xkb->ctrls, xkb->ctrls); + XkbFreeKeyboard(xkb, 0, False); + free(keymap); + break; + case DEVICE_ON: + xnestEventMask |= XNEST_KEYBOARD_EVENT_MASK; + for (i = 0; i < xnestNumScreens; i++) + XSelectInput(xnestDisplay, xnestDefaultWindows[i], xnestEventMask); + break; + case DEVICE_OFF: + xnestEventMask &= ~XNEST_KEYBOARD_EVENT_MASK; + for (i = 0; i < xnestNumScreens; i++) + XSelectInput(xnestDisplay, xnestDefaultWindows[i], xnestEventMask); + break; + case DEVICE_CLOSE: + break; + } + return Success; + + XkbError: + XGetKeyboardControl(xnestDisplay, &values); + memmove((char *) defaultKeyboardControl.autoRepeats, + (char *) values.auto_repeats, sizeof(values.auto_repeats)); + + InitKeyboardDeviceStruct(pDev, NULL, xnestBell, xnestChangeKeyboardControl); + free(keymap); + return Success; +} + +Bool +LegalModifier(unsigned int key, DeviceIntPtr pDev) +{ + return TRUE; +} + +void +xnestUpdateModifierState(unsigned int state) +{ + DeviceIntPtr pDev = xnestKeyboardDevice; + KeyClassPtr keyc = pDev->key; + int i; + CARD8 mask; + int xkb_state; + + if (!pDev) + return; + + xkb_state = XkbStateFieldFromRec(&pDev->key->xkbInfo->state); + state = state & 0xff; + + if (xkb_state == state) + return; + + for (i = 0, mask = 1; i < 8; i++, mask <<= 1) { + int key; + + /* Modifier is down, but shouldn't be + */ + if ((xkb_state & mask) && !(state & mask)) { + int count = keyc->modifierKeyCount[i]; + + for (key = 0; key < MAP_LENGTH; key++) + if (keyc->xkbInfo->desc->map->modmap[key] & mask) { + if (key_is_down(pDev, key, KEY_PROCESSED)) + xnestQueueKeyEvent(KeyRelease, key); + + if (--count == 0) + break; + } + } + + /* Modifier shoud be down, but isn't + */ + if (!(xkb_state & mask) && (state & mask)) + for (key = 0; key < MAP_LENGTH; key++) + if (keyc->xkbInfo->desc->map->modmap[key] & mask) { + xnestQueueKeyEvent(KeyPress, key); + break; + } + } +} diff --git a/pool/shard006/C/0118785_bagman.c b/pool/shard006/C/0118785_bagman.c new file mode 100644 index 0000000000000000000000000000000000000000..f6ba11e168108c066af56cb2e596c505c554437f --- /dev/null +++ b/pool/shard006/C/0118785_bagman.c @@ -0,0 +1,159 @@ +/*************************************************************************** + + video.c + + Functions to emulate the video hardware of the machine. + +***************************************************************************/ + +#include "emu.h" +#include "video/resnet.h" +#include "includes/bagman.h" + + +WRITE8_HANDLER( bagman_videoram_w ) +{ + bagman_state *state = space->machine().driver_data(); + state->m_videoram[offset] = data; + tilemap_mark_tile_dirty(state->m_bg_tilemap, offset); +} + +WRITE8_HANDLER( bagman_colorram_w ) +{ + bagman_state *state = space->machine().driver_data(); + state->m_colorram[offset] = data; + tilemap_mark_tile_dirty(state->m_bg_tilemap, offset); +} + +/*************************************************************************** + + Convert the color PROMs into a more useable format. + + Bagman has two 32 bytes palette PROMs, connected to the RGB output this + way: + + bit 7 -- 220 ohm resistor -- \ + -- 470 ohm resistor -- | -- 470 ohm pulldown resistor -- BLUE + + -- 220 ohm resistor -- \ + -- 470 ohm resistor -- | -- 470 ohm pulldown resistor -- GREEN + -- 1 kohm resistor -- / + + -- 220 ohm resistor -- \ + -- 470 ohm resistor -- | -- 470 ohm pulldown resistor -- RED + bit 0 -- 1 kohm resistor -- / + +***************************************************************************/ +PALETTE_INIT( bagman ) +{ + int i; + static const int resistances_rg[3] = { 1000, 470, 220 }; + static const int resistances_b [2] = { 470, 220 }; + double weights_r[3], weights_g[3], weights_b[2]; + + + compute_resistor_weights(0, 255, -1.0, + 3, resistances_rg, weights_r, 470, 0, + 3, resistances_rg, weights_g, 470, 0, + 2, resistances_b, weights_b, 470, 0); + + + for (i = 0; i < machine.total_colors(); i++) + { + int bit0, bit1, bit2, r, g, b; + + /* red component */ + bit0 = (color_prom[i] >> 0) & 0x01; + bit1 = (color_prom[i] >> 1) & 0x01; + bit2 = (color_prom[i] >> 2) & 0x01; + r = combine_3_weights(weights_r, bit0, bit1, bit2); + /* green component */ + bit0 = (color_prom[i] >> 3) & 0x01; + bit1 = (color_prom[i] >> 4) & 0x01; + bit2 = (color_prom[i] >> 5) & 0x01; + g = combine_3_weights(weights_g, bit0, bit1, bit2); + /* blue component */ + bit0 = (color_prom[i] >> 6) & 0x01; + bit1 = (color_prom[i] >> 7) & 0x01; + b = combine_2_weights(weights_b, bit0, bit1); + + palette_set_color(machine,i,MAKE_RGB(r,g,b)); + } +} + +WRITE8_HANDLER( bagman_flipscreen_w ) +{ + bagman_state *state = space->machine().driver_data(); + if ((flip_screen_get(space->machine()) ^ data) & 1) + { + flip_screen_set(space->machine(), data & 0x01); + tilemap_mark_all_tiles_dirty(state->m_bg_tilemap); + } +} + +static TILE_GET_INFO( get_bg_tile_info ) +{ + bagman_state *state = machine.driver_data(); + int gfxbank = (machine.gfx[2] && (state->m_colorram[tile_index] & 0x10)) ? 2 : 0; + int code = state->m_videoram[tile_index] + 8 * (state->m_colorram[tile_index] & 0x20); + int color = state->m_colorram[tile_index] & 0x0f; + + SET_TILE_INFO(gfxbank, code, color, 0); +} + +VIDEO_START( bagman ) +{ + bagman_state *state = machine.driver_data(); + state->m_bg_tilemap = tilemap_create(machine, get_bg_tile_info, tilemap_scan_rows, + 8, 8, 32, 32); + + tilemap_set_scrolldy(state->m_bg_tilemap, -1, -1); +} + + +static void draw_sprites(running_machine &machine, bitmap_t *bitmap, const rectangle *cliprect) +{ + bagman_state *state = machine.driver_data(); + UINT8 *spriteram = state->m_spriteram; + int offs; + + for (offs = state->m_spriteram_size - 4;offs >= 0;offs -= 4) + { + int sx,sy,flipx,flipy; + + sx = spriteram[offs + 3]; + sy = 255 - spriteram[offs + 2] - 16; + flipx = spriteram[offs] & 0x40; + flipy = spriteram[offs] & 0x80; + if (flip_screen_x_get(machine)) + { + sx = bitmap->width - sx - 15; + flipx = !flipx; + } + if (flip_screen_y_get(machine)) + { + sy = bitmap->height - sy - 15; + flipy = !flipy; + } + + if (spriteram[offs + 2] && spriteram[offs + 3]) + drawgfx_transpen(bitmap, + cliprect,machine.gfx[1], + (spriteram[offs] & 0x3f) + 2 * (spriteram[offs + 1] & 0x20), + spriteram[offs + 1] & 0x1f, + flipx,flipy, + sx,sy,0); + } +} + +SCREEN_UPDATE( bagman ) +{ + bagman_state *state = screen->machine().driver_data(); + bitmap_fill(bitmap,cliprect,0); + if (*state->m_video_enable == 0) + return 0; + + tilemap_draw(bitmap, cliprect, state->m_bg_tilemap, 0, 0); + draw_sprites(screen->machine(), bitmap, cliprect); + return 0; +} diff --git a/pool/shard006/C/0118786_lzo_wrapper.c b/pool/shard006/C/0118786_lzo_wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..55572def211a2b79c0d987a4d2ae3bc3b6aea706 --- /dev/null +++ b/pool/shard006/C/0118786_lzo_wrapper.c @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2010 LG Electronics + * Chan Jeong + * + * 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. + * + * 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * lzo_wrapper.c + */ + +#include +#include + +#include +#include + +/* worst-case expansion calculation during compression, + see LZO FAQ for more information */ +#define LZO_OUTPUT_BUFFER_SIZE(size) (size + (size/16) + 64 + 3) + +struct lzo_stream { + lzo_voidp wrkmem; + lzo_bytep out; +}; + +int lzo_compress(void **strm, char *d, char *s, int size, int block_size, + int *error) +{ + int res = 0; + lzo_uint outlen; + struct lzo_stream *stream = *strm; + + if(stream == NULL) { + if((stream = *strm = malloc(sizeof(struct lzo_stream))) == NULL) + goto failed; + /* work memory for compression */ + if((stream->wrkmem = malloc(LZO1X_999_MEM_COMPRESS)) == NULL) + goto failed; + /* temporal output buffer */ + if((stream->out = malloc(LZO_OUTPUT_BUFFER_SIZE(block_size))) == NULL) + goto failed; + } + + res = lzo1x_999_compress((lzo_bytep)s, size, stream->out, &outlen, stream->wrkmem); + if(res != LZO_E_OK) + goto failed; + if(outlen >= size) + /* + * Output buffer overflow. Return out of buffer space + */ + return 0; + + /* + * Success, return the compressed size. + */ + memcpy(d, stream->out, outlen); + return outlen; + +failed: + /* + * All other errors return failure, with the compressor + * specific error code in *error + */ + *error = res; + return -1; +} + + +int lzo_uncompress(char *d, char *s, int size, int block_size, int *error) +{ + int res; + lzo_uint bytes = block_size; + + res = lzo1x_decompress_safe((lzo_bytep)s, size, (lzo_bytep)d, &bytes, NULL); + + *error = res; + return res == LZO_E_OK ? bytes : -1; +} diff --git a/pool/shard006/C/0118787_combo.c b/pool/shard006/C/0118787_combo.c new file mode 100644 index 0000000000000000000000000000000000000000..79214d1767704c95558bf7f9b25ff134ae1030e2 --- /dev/null +++ b/pool/shard006/C/0118787_combo.c @@ -0,0 +1,81 @@ + +#include + +U8 generic_combo_timer; + +U8 combo_count; + +U8 right_ramp_count; + +static U8 combo_score_ladder[] = { + SC_100K, SC_200K, SC_300K, SC_400K, SC_500K +}; + +void combo_deff (void) +{ + dmd_alloc_low_clean (); + sprintf ("%d WAY COMBO", combo_count); + font_render_string_center (&font_fixed6, 64, 5, sprintf_buffer); + sprintf_score (score_deff_get ()); + font_render_string_center (&font_fixed6, 64, 15, sprintf_buffer); + dmd_show_low (); + task_sleep_sec (3); + deff_exit (); +} + +void combo_reset (void) +{ + combo_count = 0; + right_ramp_count = 0; +} + +void combo_award (void) +{ + U8 value; + + if (combo_count > 5) + value = SC_500K; + else + value = combo_score_ladder[combo_count - 1]; + score_multiple (value, right_ramp_count+1); + deff_start (DEFF_COMBO); + sound_start (ST_SAMPLE, SND_FIREWORK_LAUNCH2, SL_1S, PRI_GAME_QUICK3); +} + +void combo_running (void) +{ + generic_combo_timer = TIME_4S / TIME_500MS; + while (generic_combo_timer > 0) + { + task_sleep (TIME_500MS); + generic_combo_timer--; + } + combo_reset (); + task_exit (); +} + +void combo_shot (void) +{ + bounded_increment (combo_count, 99); + if (task_find_gid (GID_COMBO)) + combo_award (); + task_recreate_gid (GID_COMBO, combo_running); +} + +CALLSET_ENTRY (combo, left_ramp_shot, striker_shot) +{ + right_ramp_count = 0; + combo_shot (); +} + +CALLSET_ENTRY (combo, right_ramp_shot) +{ + bounded_increment (right_ramp_count, 5); + combo_shot (); +} + +CALLSET_ENTRY (combo, start_ball) +{ + combo_reset (); +} + diff --git a/pool/shard006/C/0118789_x509.c b/pool/shard006/C/0118789_x509.c new file mode 100644 index 0000000000000000000000000000000000000000..ff0d21e816a8facb868ae5fcdaf79ed8e4ddf8df --- /dev/null +++ b/pool/shard006/C/0118789_x509.c @@ -0,0 +1,364 @@ +/* + * Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software Foundation + * Author: Nikos Mavrogiannopoulos, Simon Josefsson, Howard Chu + * + * This file is part of GNUTLS. + * + * The GNUTLS 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 Street, Fifth Floor, Boston, MA 02110-1301, + * USA + * + */ + +/* Functions on X.509 Certificate parsing + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * MHD_gnutls_x509_crt_init - This function initializes a MHD_gnutls_x509_crt_t structure + * @cert: The structure to be initialized + * + * This function will initialize an X.509 certificate structure. + * + * Returns 0 on success. + * + **/ +int +MHD_gnutls_x509_crt_init (MHD_gnutls_x509_crt_t * cert) +{ + MHD_gnutls_x509_crt_t tmp = + MHD_gnutls_calloc (1, sizeof (MHD_gnutls_x509_crt_int)); + int result; + + if (!tmp) + return GNUTLS_E_MEMORY_ERROR; + + result = MHD__asn1_create_element (MHD__gnutls_get_pkix (), + "PKIX1.Certificate", &tmp->cert); + if (result != ASN1_SUCCESS) + { + MHD_gnutls_assert (); + MHD_gnutls_free (tmp); + return MHD_gtls_asn2err (result); + } + + *cert = tmp; + + return 0; /* success */ +} + +/** + * MHD_gnutls_x509_crt_deinit - This function deinitializes memory used by a MHD_gnutls_x509_crt_t structure + * @cert: The structure to be initialized + * + * This function will deinitialize a CRL structure. + * + **/ +void +MHD_gnutls_x509_crt_deinit (MHD_gnutls_x509_crt_t cert) +{ + if (!cert) + return; + + if (cert->cert) + MHD__asn1_delete_structure (&cert->cert); + + MHD_gnutls_free (cert); +} + +/** + * MHD_gnutls_x509_crt_import - This function will import a DER or PEM encoded Certificate + * @cert: The structure to store the parsed certificate. + * @data: The DER or PEM encoded certificate. + * @format: One of DER or PEM + * + * This function will convert the given DER or PEM encoded Certificate + * to the native MHD_gnutls_x509_crt_t format. The output will be stored in @cert. + * + * If the Certificate is PEM encoded it should have a header of "X509 CERTIFICATE", or + * "CERTIFICATE". + * + * Returns 0 on success. + * + **/ +int +MHD_gnutls_x509_crt_import (MHD_gnutls_x509_crt_t cert, + const MHD_gnutls_datum_t * data, + MHD_gnutls_x509_crt_fmt_t format) +{ + int result = 0, need_free = 0; + MHD_gnutls_datum_t _data; + opaque *signature = NULL; + + if (cert == NULL) + { + MHD_gnutls_assert (); + return GNUTLS_E_INVALID_REQUEST; + } + + _data.data = data->data; + _data.size = data->size; + + /* If the Certificate is in PEM format then decode it + */ + if (format == GNUTLS_X509_FMT_PEM) + { + opaque *out; + + /* Try the first header */ + result = + MHD__gnutls_fbase64_decode (PEM_X509_CERT2, data->data, data->size, + &out); + + if (result <= 0) + { + /* try for the second header */ + result = MHD__gnutls_fbase64_decode (PEM_X509_CERT, data->data, + data->size, &out); + + if (result <= 0) + { + if (result == 0) + result = GNUTLS_E_INTERNAL_ERROR; + MHD_gnutls_assert (); + return result; + } + } + + _data.data = out; + _data.size = result; + + need_free = 1; + } + + result = MHD__asn1_der_decoding (&cert->cert, _data.data, _data.size, NULL); + if (result != ASN1_SUCCESS) + { + result = MHD_gtls_asn2err (result); + MHD_gnutls_assert (); + goto cleanup; + } + + /* Since we do not want to disable any extension + */ + cert->use_extensions = 1; + if (need_free) + MHD__gnutls_free_datum (&_data); + + return 0; + +cleanup:MHD_gnutls_free (signature); + if (need_free) + MHD__gnutls_free_datum (&_data); + return result; +} + +/** + * MHD_gnutls_x509_crt_get_version - This function returns the Certificate's version number + * @cert: should contain a MHD_gnutls_x509_crt_t structure + * + * This function will return the version of the specified Certificate. + * + * Returns a negative value on error. + * + **/ +int +MHD_gnutls_x509_crt_get_version (MHD_gnutls_x509_crt_t cert) +{ + opaque version[5]; + int len, result; + + if (cert == NULL) + { + MHD_gnutls_assert (); + return GNUTLS_E_INVALID_REQUEST; + } + + len = sizeof (version); + if ((result = + MHD__asn1_read_value (cert->cert, "tbsCertificate.version", version, + &len)) != ASN1_SUCCESS) + { + + if (result == ASN1_ELEMENT_NOT_FOUND) + return 1; /* the DEFAULT version */ + MHD_gnutls_assert (); + return MHD_gtls_asn2err (result); + } + + return (int) version[0] + 1; +} + +/** + * MHD_gnutls_x509_crt_get_pk_algorithm - This function returns the certificate's PublicKey algorithm + * @cert: should contain a MHD_gnutls_x509_crt_t structure + * @bits: if bits is non null it will hold the size of the parameters' in bits + * + * This function will return the public key algorithm of an X.509 + * certificate. + * + * If bits is non null, it should have enough size to hold the parameters + * size in bits. For RSA the bits returned is the modulus. + * For DSA the bits returned are of the public + * exponent. + * + * Returns a member of the enum MHD_GNUTLS_PublicKeyAlgorithm enumeration on success, + * or a negative value on error. + * + **/ +int +MHD_gnutls_x509_crt_get_pk_algorithm (MHD_gnutls_x509_crt_t cert, + unsigned int *bits) +{ + int result; + + if (cert == NULL) + { + MHD_gnutls_assert (); + return GNUTLS_E_INVALID_REQUEST; + } + + result = MHD__gnutls_x509_get_pk_algorithm (cert->cert, + "tbsCertificate.subjectPublicKeyInfo", + bits); + + if (result < 0) + { + MHD_gnutls_assert (); + return result; + } + + return result; + +} + +inline static int +is_type_printable (int type) +{ + if (type == GNUTLS_SAN_DNSNAME || type == GNUTLS_SAN_RFC822NAME || type + == GNUTLS_SAN_URI) + return 1; + else + return 0; +} + +/** + * MHD_gnutls_x509_crt_get_key_usage - This function returns the certificate's key usage + * @cert: should contain a MHD_gnutls_x509_crt_t structure + * @key_usage: where the key usage bits will be stored + * @critical: will be non zero if the extension is marked as critical + * + * This function will return certificate's key usage, by reading the + * keyUsage X.509 extension (2.5.29.15). The key usage value will ORed values of the: + * GNUTLS_KEY_DIGITAL_SIGNATURE, GNUTLS_KEY_NON_REPUDIATION, + * GNUTLS_KEY_KEY_ENCIPHERMENT, GNUTLS_KEY_DATA_ENCIPHERMENT, + * GNUTLS_KEY_KEY_AGREEMENT, GNUTLS_KEY_KEY_CERT_SIGN, + * GNUTLS_KEY_CRL_SIGN, GNUTLS_KEY_ENCIPHER_ONLY, + * GNUTLS_KEY_DECIPHER_ONLY. + * + * A negative value may be returned in case of parsing error. + * If the certificate does not contain the keyUsage extension + * GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE will be returned. + * + **/ +int +MHD_gnutls_x509_crt_get_key_usage (MHD_gnutls_x509_crt_t cert, + unsigned int *key_usage, + unsigned int *critical) +{ + int result; + MHD_gnutls_datum_t keyUsage; + uint16_t _usage; + + if (cert == NULL) + { + MHD_gnutls_assert (); + return GNUTLS_E_INVALID_REQUEST; + } + + if ((result = + MHD__gnutls_x509_crt_get_extension (cert, "2.5.29.15", 0, &keyUsage, + critical)) < 0) + { + return result; + } + + if (keyUsage.size == 0 || keyUsage.data == NULL) + { + MHD_gnutls_assert (); + return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; + } + + result = MHD__gnutls_x509_ext_extract_keyUsage (&_usage, keyUsage.data, + keyUsage.size); + MHD__gnutls_free_datum (&keyUsage); + + *key_usage = _usage; + + if (result < 0) + { + MHD_gnutls_assert (); + return result; + } + + return 0; +} + + +/** + * MHD_gnutls_x509_crt_export - This function will export the certificate + * @cert: Holds the certificate + * @format: the format of output params. One of PEM or DER. + * @output_data: will contain a certificate PEM or DER encoded + * @output_data_size: holds the size of output_data (and will be + * replaced by the actual size of parameters) + * + * This function will export the certificate to DER or PEM format. + * + * If the buffer provided is not long enough to hold the output, then + * *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will + * be returned. + * + * If the structure is PEM encoded, it will have a header + * of "BEGIN CERTIFICATE". + * + * Return value: In case of failure a negative value will be + * returned, and 0 on success. + **/ +int +MHD_gnutls_x509_crt_export (MHD_gnutls_x509_crt_t cert, + MHD_gnutls_x509_crt_fmt_t format, + void *output_data, size_t * output_data_size) +{ + if (cert == NULL) + { + MHD_gnutls_assert (); + return GNUTLS_E_INVALID_REQUEST; + } + + return MHD__gnutls_x509_export_int (cert->cert, format, "CERTIFICATE", + output_data, output_data_size); +} diff --git a/pool/shard006/C/0118793_i810stub.c b/pool/shard006/C/0118793_i810stub.c new file mode 100644 index 0000000000000000000000000000000000000000..7d5fcf3ce0f1e3850ad78cf9453f9b8078b81d1b --- /dev/null +++ b/pool/shard006/C/0118793_i810stub.c @@ -0,0 +1,81 @@ +/* $XFree86: xc/programs/Xserver/hw/kdrive/i810/i810stub.c,v 1.3 2001/10/28 03:33:10 tsi Exp $ */ +/* COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 2000, 2001 Nokia Home Communications + +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, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, provided that the above +copyright notice(s) and this permission notice appear in all copies of +the Software and that both the above copyright notice(s) and this +permission notice appear in supporting documentation. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY +SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER +RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, use +or other dealings in this Software without prior written authorization +of the copyright holder. + +X Window System is a trademark of The Open Group */ + +/* Stub functions for the i810 KDrive driver + Author: Pontus Lidman +*/ + +#include "kdrive.h" +#include "kxv.h" +#include "i810.h" + +static const int i810Cards[]={ PCI_CHIP_I810, PCI_CHIP_I810_DC100, PCI_CHIP_I810_E }; + +#define numI810Cards (sizeof(i810Cards) / sizeof(i810Cards[0])) + +void +InitCard (char *name) +{ + KdCardAttr attr; + int i; + + Bool LinuxFindPci(CARD16, CARD16, CARD32, KdCardAttr *); + + for (i = 0; i < numI810Cards; i++) + if (LinuxFindPci (0x8086, i810Cards[i], 0, &attr)) + KdCardInfoAdd (&i810Funcs, &attr, (void *) i810Cards[i]); +} + + +void +InitOutput (ScreenInfo *pScreenInfo, int argc, char **argv) +{ + KdInitOutput (pScreenInfo, argc, argv); +} + +void +InitInput (int argc, char **argv) +{ + KdInitInput (&LinuxMouseFuncs, &LinuxKeyboardFuncs); +} + +int +ddxProcessArgument (int argc, char **argv, int i) +{ + int ret; + int KdProcessArgument(int, char **, int); + + ret = KdProcessArgument(argc, argv, i); + return ret; +} diff --git a/pool/shard006/C/0118802_shm_test.c b/pool/shard006/C/0118802_shm_test.c new file mode 100644 index 0000000000000000000000000000000000000000..b3d6aaf79c4ebbf2162fe025b4baef1f8147ab6b --- /dev/null +++ b/pool/shard006/C/0118802_shm_test.c @@ -0,0 +1,361 @@ +/******************************************************************************/ +/* */ +/* Copyright (c) International Business Machines Corp., 2001 */ +/* */ +/* This program is free software; you can redistribute it and/or modify */ +/* it under the terms of the GNU General Public License as published by */ +/* the Free Software Foundation; either version 2 of the License, or */ +/* (at your option) any later version. */ +/* */ +/* This program is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See */ +/* the GNU General Public License for more details. */ +/* */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program; if not, write to the Free Software */ +/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +/* */ +/******************************************************************************/ + +/******************************************************************************/ +/* */ +/* History: Nov - 21 - 2001 Created - Manoj Iyer, IBM Austin TX. */ +/* email:manjo@austin.ibm.com */ +/* */ +/* Nov - 26 - 2001 Modified - Manoj Iyer, IBM Austin Tx. */ +/* - Added function rm_shared_mem. */ +/* */ +/* Dec - 03 - 2001 Modified - Manoj Iyer, IBM Austin Tx. */ +/* - Added code to spawn threads. */ +/* - Removed dead code. */ +/* - Checked in the initial version to CVS */ +/* */ +/* Feb - 27 - 2001 Modified - Manoj Iyer, IBM Austin TX. */ +/* - removed compiler warnings. */ +/* - removed compiler errors. */ +/* */ +/* File: shm_test.c */ +/* */ +/* Description: This program is designed to stress the Memory management sub -*/ +/* system of Linux. This program will spawn multiple pairs of */ +/* reader and writer threads. One thread will create the shared */ +/* segment of random size and write to this memory, the other */ +/* pair will read from this memory. */ +/* */ +/******************************************************************************/ +#include /* required by pthread functions */ +#include /* required by fprintf() */ +#include /* required by exit(), atoi() */ +#include /* required by strncpy() */ +#include /* required by getopt(), mmap() */ +#include /* required by open(), shmat(), shmdt() */ +#include /* required by open() */ +#include /* required by shmat() shmdt(), shmctl() */ +#include /* required by shmat() shmdt(), shmctl() */ +#include /* required by mmap() */ +#include /* required by open() */ +#include /* required by uintptr_t */ + +void noprintf(char *string, ...) +{ +} + +#ifdef DEBUG +#define dprt printf +#else +#define dprt noprintf +#endif + +#define PTHREAD_EXIT(val) do {\ + exit_val = val; \ + dprt("pid[%d]: exiting with %d\n", getpid(),exit_val); \ + pthread_exit((void *)(uintptr_t)exit_val); \ + } while (0) + +#define OPT_MISSING(prog, opt) do{\ + fprintf(stderr, "%s: option -%c ", prog, opt); \ + fprintf(stderr, "requires an argument\n"); \ + usage(prog); \ + } while (0) + +#define MAXT 30 /* default number of threads to create. */ +#define MAXR 1000 /* default number of repatetions to execute */ +#define WRITER 0 /* cause thread function to shmat and write */ +#define READER 1 /* cause thread function to shmat and read */ + +/******************************************************************************/ +/* */ +/* Function: usage */ +/* */ +/* Description: Print the usage message. */ +/* */ +/* Return: exits with -1 */ +/* */ +/******************************************************************************/ +static void usage(char *progname) +{ /* name of this program */ + fprintf(stderr, + "Usage: %s -d NUMDIR -f NUMFILES -h -t NUMTHRD\n" + "\t -h Help!\n" + "\t -l Number of repatetions to execute: Default: 1000\n" + "\t -t Number of threads to generate: Default: 30\n", + progname); + exit(-1); +} + +/******************************************************************************/ +/* */ +/* Function: rm_shared_mem */ +/* */ +/* Description: This function removes the shared segments that were created */ +/* This function is called when shmat fails or logical end of */ +/* the while loop is reached in shmat_rd_wr function. */ +/* */ +/* Input: shm_id - id of the shared memory segment to be removed */ +/* shm_addr - address of the shared memory segment to be removed */ +/* cmd - remove id only or remove id and detach?? */ +/* 0 - remove id dont detach segment. */ +/* 1 - remove id and detach segment. */ +/* */ +/* Output: NONE. */ +/* */ +/* Return: exits with -1 on error, 0 on success */ +/* */ +/******************************************************************************/ +static int rm_shared_mem(key_t shm_id, /* id of shared memory segment to be removed */ + char *shm_addr, /* address of shared mem seg to be removed */ + int cmd) +{ /* remove id only or remove id and detach seg */ + struct shmid *shmbuf = NULL; /* info about the segment pointed by shmkey */ + + dprt("pid[%d]: rm_shared_mem(): shm_id = %d shm_addr = %#x cmd = %d\n", + getpid(), shm_id, shm_addr, cmd); + if (shmctl(shm_id, IPC_RMID, (struct shmid_ds *)shmbuf) == -1) { + dprt("pid[%d]: rm_shared_mem(): shmctl unable to remove shm_id[%d]\n", getpid(), shm_id); + perror("rm_shared_mem(): shmctl()"); + return -1; + } + + if (cmd) { + if (shmdt((void *)shm_addr) == -1) { + dprt("pid[%d]:rm_shared_mem(): shmdt unable to detach addr = %#x\n", getpid(), shm_addr); + perror("rm_shared_mem(): shmdt()"); + return -1; + } + } + return 0; +} + +/******************************************************************************/ +/* */ +/* Function: shmat_rd_wr */ +/* */ +/* Description: This function repeatedly attaches and detaches the memory */ +/* The size of the file is a multiple of page size. */ +/* The function acts as either reader or writer thread depending */ +/* on arg[3]. The reader and writer thread use the same key so */ +/* they get access to the same shared memory segment. */ +/* */ +/* Input: The argument pointer contains the following. */ +/* arg[0] - number of repatetions of the above operation */ +/* arg[1] - shared memory key. */ +/* arg[2] - size of the memory that is to be attached. */ +/* arg[3] - reader or writer. */ +/* */ +/* Return: exits with -1 on error, 0 on success */ +/* */ +/******************************************************************************/ +static void *shmat_rd_wr(void *args) +{ /* arguments to the thread function */ + int shmndx = 0; /* index to the number of attach and detach */ + int index = 0; /* index to the number of blocks touched */ + int reader = 0; /* this thread is a reader thread if set to 1 */ + key_t shm_id = 0; /* shared memory id */ + long *locargs = /* local pointer to arguments */ + (long *)args; + volatile int exit_val = 0; /* exit value of the pthread */ + char *read_from_mem; /* ptr to touch each (4096) block in memory */ + char *write_to_mem; /* ptr to touch each (4096) block in memory */ + char *shmat_addr; /* address of the attached memory */ + char buff; /* temporary buffer */ + + reader = (int)locargs[3]; + while (shmndx++ < (int)locargs[0]) { + dprt("pid[%d]: shmat_rd_wr(): locargs[1] = %#x\n", + getpid(), (int)locargs[1]); + + /* get shared memory id */ + if ((shm_id = + shmget((int)locargs[1], (int)locargs[2], IPC_CREAT | 0666)) + == -1) { + dprt("pid[%d]: shmat_rd_wr(): shmget failed\n", + getpid()); + perror("do_shmat_shmadt(): shmget()"); + PTHREAD_EXIT(-1); + } + + fprintf(stdout, "pid[%d]: shmat_rd_wr(): shmget():" + "success got segment id %d\n", getpid(), shm_id); + + /* get shared memory segment */ + if ((shmat_addr = (char *)shmat(shm_id, NULL, 0)) == (void *)-1) { + rm_shared_mem(shm_id, shmat_addr, 0); + fprintf(stderr, + "pid[%d]: do_shmat_shmadt(): shmat_addr = %#lx\n", + getpid(), (long)shmat_addr); + perror("do_shmat_shmadt(): shmat()"); + PTHREAD_EXIT(-1); + } + dprt("pid[%d]: do_shmat_shmadt(): content of memory shmat_addr = %s\n", getpid(), shmat_addr); + + fprintf(stdout, + "pid[%d]: do_shmat_shmadt(): got shmat address = %#lx\n", + getpid(), (long)shmat_addr); + + if (!reader) { + /* write character 'Y' to that memory area */ + index = 0; + write_to_mem = shmat_addr; + while (index < (int)locargs[2]) { + dprt("pid[%d]: do_shmat_shmatd(): write_to_mem = %#x\n", getpid(), write_to_mem); + *write_to_mem = 'Y'; + index++; + write_to_mem++; + sched_yield(); + } + } else { + /* read from the memory area */ + index = 0; + read_from_mem = shmat_addr; + while (index < (int)locargs[2]) { + buff = *read_from_mem; + index++; + read_from_mem++; + sched_yield(); + } + } + + sched_yield(); + + /* remove the shared memory */ + if (rm_shared_mem(shm_id, shmat_addr, 1) == -1) { + fprintf(stderr, + "pid[%d]: do_shmat_shmatd(): rm_shared_mem(): faild to rm id\n", + getpid()); + PTHREAD_EXIT(-1); + } + } + + PTHREAD_EXIT(0); +} + +/******************************************************************************/ +/* */ +/* Function: main */ +/* */ +/* Description: This is the entry point to the program. This function will */ +/* parse the input arguments and set the values accordingly. If */ +/* no arguments (or desired) are provided default values are used*/ +/* refer the usage function for the arguments that this program */ +/* takes. It also creates the threads which do most of the dirty */ +/* work. If the threads exits with a value '0' the program exits */ +/* with success '0' else it exits with failure '-1'. */ +/* */ +/* Return: -1 on failure */ +/* 0 on success */ +/* */ +/******************************************************************************/ +int main(int argc, /* number of input parameters */ + char **argv) +{ /* pointer to the command line arguments. */ + int c; /* command line options */ + int num_thrd = MAXT; /* number of threads to create */ + int num_reps = MAXR; /* number of repatitions the test is run */ + int thrd_ndx; /* index into the array of thread ids */ + void *th_status; /* exit status of LWP's */ + int map_size; /* size of the file mapped. */ + int shmkey = 1969; /* key used to generate shmid by shmget() */ + pthread_t thrdid[30]; /* maxinum of 30 threads allowed */ + long chld_args[4]; /* arguments to the thread function */ + char *map_address = NULL; + /* address in memory of the mapped file */ + extern int optopt; /* options to the program */ + + while ((c = getopt(argc, argv, "hl:t:")) != -1) { + switch (c) { + case 'h': + usage(argv[0]); + break; + case 'l': /* how many repetitions of the test to exec */ + if ((num_reps = atoi(optarg)) == 0) + OPT_MISSING(argv[0], optopt); + else if (num_reps < 0) { + fprintf(stdout, + "WARNING: bad argument. Using default\n"); + num_reps = MAXR; + } + break; + case 't': + if ((num_thrd = atoi(optarg)) == 0) + OPT_MISSING(argv[0], optopt); + else if (num_thrd < 0) { + fprintf(stdout, + "WARNING: bad argument. Using default\n"); + num_thrd = MAXT; + } + break; + default: + usage(argv[0]); + break; + } + } + + chld_args[0] = num_reps; + + for (thrd_ndx = 0; thrd_ndx < num_thrd; thrd_ndx += 2) { + srand(time(NULL) % 100); + map_size = + (1 + (int)(1000.0 * rand() / (RAND_MAX + 1.0))) * 4096; + + chld_args[1] = shmkey++; + chld_args[2] = map_size; + + dprt("main(): thrd_ndx = %d map_address = %#x map_size = %d\n", + thrd_ndx, map_address, map_size); + + chld_args[3] = WRITER; + + if (pthread_create + (&thrdid[thrd_ndx], NULL, shmat_rd_wr, chld_args)) { + perror("shmat_rd_wr(): pthread_create()"); + exit(-1); + } + + chld_args[3] = READER; + + if (pthread_create + (&thrdid[thrd_ndx + 1], NULL, shmat_rd_wr, chld_args)) { + perror("shmat_rd_wr(): pthread_create()"); + exit(-1); + } + } + + sync(); + + for (thrd_ndx = 0; thrd_ndx < num_thrd; thrd_ndx++) { + if (pthread_join(thrdid[thrd_ndx], &th_status) != 0) { + perror("shmat_rd_wr(): pthread_join()"); + exit(-1); + } else { + dprt("WE ARE HERE %d\n", __LINE__); + if (th_status == (void *)-1) { + fprintf(stderr, + "thread [%ld] - process exited with errors\n", + (long)thrdid[thrd_ndx]); + exit(-1); + } + } + } + exit(0); +} diff --git a/pool/shard006/C/0118805_gstcoolutil.c b/pool/shard006/C/0118805_gstcoolutil.c new file mode 100644 index 0000000000000000000000000000000000000000..133506cea6ba6f941008c31c92e01d6c858c964e --- /dev/null +++ b/pool/shard006/C/0118805_gstcoolutil.c @@ -0,0 +1,157 @@ +/* GStreamer Plugins Cool + * Copyright (C) 2014 LG Electronics, Inc. + * Author : Jeongseok Kim + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstcool.h" +#include "gstcoolutil.h" + +enum +{ + STREAM_AUDIO = 0, + STREAM_VIDEO, + STREAM_TEXT, + STREAM_LAST +}; + +/* blacklisted field for media-info, we don't need to add it to media-info message */ +static const gchar *blacklisted_tag_fields[] = + { GST_TAG_BITRATE, GST_TAG_MINIMUM_BITRATE, GST_TAG_MAXIMUM_BITRATE, + NULL +}; + +static gboolean +append_media_field (GQuark field_id, const GValue * value, gpointer user_data) +{ + GstStructure *media = user_data; + gchar *value_str = gst_value_serialize (value); + + GST_DEBUG_OBJECT (media, "field [%s:%s]", g_quark_to_string (field_id), + value_str); + + gst_structure_id_set_value (media, field_id, value); + + g_free (value_str); + + return TRUE; +} + +/* Return whether stream type is video, audio or subtitle. + * To add media-info structure. + * Returns : (GstCoolStreamType) type or GST_COOL_STREAM_TYPE_UNKNOWN if mime_type is NULL. + */ +GstCoolStreamType +gst_cool_find_type (const gchar * mime_type) +{ + g_return_val_if_fail (mime_type != NULL, STREAM_LAST); + + guint type; + if (g_strrstr (mime_type, "video") || g_strrstr (mime_type, "image")) + type = STREAM_VIDEO; + else if (g_strrstr (mime_type, "audio")) + type = STREAM_AUDIO; + else + type = STREAM_TEXT; + + GST_LOG ("return type = %u", type); + return type; +} + +/* Return media-info structure that is converted from caps information. + * Returns : (GstStructure *) structure or NULL if caps is NULL. + */ +GstStructure * +gst_cool_caps_to_info (GstCaps * caps, char *stream_id) +{ + g_return_val_if_fail (caps != NULL, NULL); + + GstStructure *s = gst_caps_get_structure (caps, 0); + GstStructure *media_info; + const gchar *mime_type = gst_structure_get_name (s); + GstCoolStreamType type = gst_cool_find_type (mime_type); + + GST_DEBUG ("getting caps information: %" GST_PTR_FORMAT, caps); + + media_info = gst_structure_new ("media-info", + "stream-id", G_TYPE_STRING, g_strdup (stream_id), + "type", G_TYPE_INT, type, + "mime-type", G_TYPE_STRING, g_strdup (mime_type), NULL); + + /* append media information from caps's structure to media-info */ + gst_structure_foreach (s, append_media_field, media_info); + GST_DEBUG ("Complete: structure information = [%" GST_PTR_FORMAT "]", + media_info); + + return media_info; +} + +/* Return media-info structure that is converted from taglist. + * Returns : (GstStructure *) structure or NULL if taglist is NULL. + */ +GstStructure * +gst_cool_taglist_to_info (GstTagList * taglist, char *stream_id, + const char *mime_type) +{ + g_return_val_if_fail (taglist != NULL, NULL); + + const gchar *str_structure; + GstStructure *s; + GstStructure *media_info = NULL; + GstCoolStreamType type = gst_cool_find_type (mime_type); + gint i = 0; + + GST_DEBUG ("getting taglist information: %" GST_PTR_FORMAT, taglist); + + str_structure = gst_tag_list_to_string (taglist); + s = gst_structure_new_from_string (str_structure); + + /* filtered out blacklisted fields */ + for (i = 0; blacklisted_tag_fields[i]; i++) { + if (gst_structure_has_field (s, blacklisted_tag_fields[i])) { + GST_DEBUG ("got blacked field : %s", blacklisted_tag_fields[i]); + gst_structure_remove_field (s, blacklisted_tag_fields[i]); + } + } + + /* whether to check structure has any fields or not */ + if (gst_structure_n_fields (s) == 0) { + GST_DEBUG ("No tag fields"); + media_info = NULL; + goto done; + } + + media_info = + gst_structure_new ("media-info", "stream-id", G_TYPE_STRING, + g_strdup (stream_id), "type", G_TYPE_INT, type, "mime-type", + G_TYPE_STRING, g_strdup (mime_type), NULL); + + /* append media information from taglist's structure to media-info */ + gst_structure_foreach (s, append_media_field, media_info); + GST_DEBUG ("Complete: structure information = [%" GST_PTR_FORMAT "]", + media_info); + +done: + gst_structure_free (s); + g_free (str_structure); + + return media_info; +} diff --git a/pool/shard006/C/0118806_OMSbuff_new.c b/pool/shard006/C/0118806_OMSbuff_new.c new file mode 100644 index 0000000000000000000000000000000000000000..b5eff752df975082e85188c6489c5bc63cddc06d --- /dev/null +++ b/pool/shard006/C/0118806_OMSbuff_new.c @@ -0,0 +1,94 @@ +/* * + * $Id: OMSbuff_new.c 327 2006-03-28 16:14:41Z shawill $ + * + * This file is part of Fenice + * + * Fenice -- Open Media Server + * + * Copyright (C) 2004 by + * + * - Giampaolo Mancini + * - Francesco Varano + * - Marco Penno + * - Federico Ridolfo + * - Eugenio Menegatti + * - Stefano Cau + * - Giuliano Emma + * - Stefano Oldrini + * + * Fenice 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. + * + * Fenice 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 Fenice; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * */ + +#include +#include + +#include + +#define OMSNEWBUFF_ERR { \ + free(slots); \ + free(buffer); \ + free(control); \ + return NULL; \ + } +OMSBuffer *OMSbuff_new(uint32 buffer_size) +{ + OMSSlot *slots = NULL; + OMSBuffer *buffer = NULL; + OMSControl *control = NULL; + uint32 index; + pthread_mutexattr_t mutex_attr; + + if (!buffer_size) return NULL; + + if(!(slots = (OMSSlot *)calloc(buffer_size, sizeof(OMSSlot)))) + OMSNEWBUFF_ERR + // *** slots initialization + for(index=0; indexwrite_pos = buffer_size-1; + control->valid_read_pos = 0; // buffer_size-1; + + control->refs = 0; + control->nslots = buffer_size; + + if ( pthread_mutexattr_init(&mutex_attr) ) + OMSNEWBUFF_ERR + if ( pthread_mutex_init(&control->syn, &mutex_attr) ) + OMSNEWBUFF_ERR + + if ( !(buffer = (OMSBuffer *)malloc(sizeof(OMSBuffer))) ) + OMSNEWBUFF_ERR + + buffer->type = buff_local; + *buffer->filename = '\0'; + // buffer->fd = -1; + // buffer->fd = NULL; + buffer->known_slots = buffer_size; + + // link all allocated structs + buffer->slots = slots; + buffer->control = control; + + return buffer; +} +#undef OMSNEWBUFF_ERR + diff --git a/pool/shard006/C/0118807_proxy.c b/pool/shard006/C/0118807_proxy.c new file mode 100644 index 0000000000000000000000000000000000000000..9bc2c7fb1232fa453bf120e289e7fa94292907ab --- /dev/null +++ b/pool/shard006/C/0118807_proxy.c @@ -0,0 +1,39 @@ +/* + * Copyright (C) the libgit2 contributors. All rights reserved. + * + * This file is part of libgit2, distributed under the GNU GPL v2 with + * a Linking Exception. For full terms see the included COPYING file. + */ + +#include "proxy.h" + +#include "git2/proxy.h" + +int git_proxy_init_options(git_proxy_options *opts, unsigned int version) +{ + GIT_INIT_STRUCTURE_FROM_TEMPLATE( + opts, version, git_proxy_options, GIT_PROXY_OPTIONS_INIT); + return 0; +} + +int git_proxy_options_dup(git_proxy_options *tgt, const git_proxy_options *src) +{ + if (!src) { + git_proxy_init_options(tgt, GIT_PROXY_OPTIONS_VERSION); + return 0; + } + + memcpy(tgt, src, sizeof(git_proxy_options)); + if (src->url) { + tgt->url = git__strdup(src->url); + GITERR_CHECK_ALLOC(tgt->url); + } + + return 0; +} + +void git_proxy_options_clear(git_proxy_options *opts) +{ + git__free((char *) opts->url); + opts->url = NULL; +} diff --git a/pool/shard006/C/0118809_memory.c b/pool/shard006/C/0118809_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..7dbd7f43995e07c1eeb92e9470721e7470d1650b --- /dev/null +++ b/pool/shard006/C/0118809_memory.c @@ -0,0 +1,207 @@ +/* + * memory.c + * + * Copyright (c) 2011 Sascha Hauer , Pengutronix + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Begin and End of memory area for malloc(), and current "brk" + */ +static unsigned long malloc_start; +static unsigned long malloc_end; +static unsigned long malloc_brk; + +unsigned long mem_malloc_start(void) +{ + return malloc_start; +} + +unsigned long mem_malloc_end(void) +{ + return malloc_end; +} + +#ifdef CONFIG_MALLOC_TLSF +#include +tlsf_pool tlsf_mem_pool; +#endif + +void mem_malloc_init(void *start, void *end) +{ + malloc_start = (unsigned long)start; + malloc_end = (unsigned long)end; + malloc_brk = malloc_start; +#ifdef CONFIG_MALLOC_TLSF + tlsf_mem_pool = tlsf_create(start, end - start + 1); +#endif +} + +#ifndef __SANDBOX__ +static int mem_malloc_resource(void) +{ + /* + * Normally it's a bug when one of these fails, + * but we have some setups where some of these + * regions are outside of sdram in which case + * the following fails. + */ + request_sdram_region("malloc space", + malloc_start, + malloc_end - malloc_start + 1); + request_sdram_region("barebox", + (unsigned long)&_stext, + (unsigned long)&_etext - + (unsigned long)&_stext); + request_sdram_region("barebox data", + (unsigned long)&_sdata, + (unsigned long)&_edata - + (unsigned long)&_sdata); + request_sdram_region("bss", + (unsigned long)&__bss_start, + (unsigned long)&__bss_stop - + (unsigned long)&__bss_start); +#ifdef STACK_BASE + request_sdram_region("stack", STACK_BASE, STACK_SIZE); +#endif + return 0; +} +coredevice_initcall(mem_malloc_resource); +#endif + +static void *sbrk_no_zero(ptrdiff_t increment) +{ + unsigned long old = malloc_brk; + unsigned long new = old + increment; + + if ((new < malloc_start) || (new > malloc_end)) + return NULL; + + malloc_brk = new; + + return (void *)old; +} + +void *sbrk(ptrdiff_t increment) +{ + void *old = sbrk_no_zero(increment); + + /* Only clear increment, if valid address was returned */ + if (old != NULL) + memset(old, 0, increment); + + return old; +} + +LIST_HEAD(memory_banks); + +int barebox_add_memory_bank(const char *name, resource_size_t start, + resource_size_t size) +{ + struct memory_bank *bank = xzalloc(sizeof(*bank)); + struct device_d *dev; + + bank->res = request_iomem_region(name, start, start + size - 1); + if (!bank->res) + return -EBUSY; + + dev = add_mem_device(name, start, size, IORESOURCE_MEM_WRITEABLE); + + bank->dev = dev; + bank->start = start; + bank->size = size; + + list_add_tail(&bank->list, &memory_banks); + + return 0; +} + +/* + * Request a region from the registered sdram + */ +struct resource *request_sdram_region(const char *name, resource_size_t start, + resource_size_t size) +{ + struct memory_bank *bank; + + for_each_memory_bank(bank) { + struct resource *res; + + res = __request_region(bank->res, name, start, + start + size - 1); + if (res) + return res; + } + + return NULL; +} + +int release_sdram_region(struct resource *res) +{ + return release_region(res); +} + +#ifdef CONFIG_OFTREE + +static int of_memory_fixup(struct device_node *node, void *unused) +{ + struct memory_bank *bank; + int err; + int addr_cell_len, size_cell_len, len = 0; + struct device_node *memnode; + u8 tmp[16 * 16]; /* Up to 64-bit address + 64-bit size */ + + memnode = of_create_node(node, "/memory"); + if (!memnode) + return -ENOMEM; + + err = of_set_property(memnode, "device_type", "memory", sizeof("memory"), 1); + if (err) + return err; + + addr_cell_len = of_n_addr_cells(memnode); + size_cell_len = of_n_size_cells(memnode); + + for_each_memory_bank(bank) { + of_write_number(tmp + len, bank->start, addr_cell_len); + len += addr_cell_len * 4; + of_write_number(tmp + len, bank->size, size_cell_len); + len += size_cell_len * 4; + } + + err = of_set_property(memnode, "reg", tmp, len, 1); + if (err) { + pr_err("could not set reg %s.\n", strerror(-err)); + return err; + } + + return 0; +} + +static int of_register_memory_fixup(void) +{ + return of_register_fixup(of_memory_fixup, NULL); +} +late_initcall(of_register_memory_fixup); +#endif diff --git a/pool/shard006/C/0118810_msgqsnd.c b/pool/shard006/C/0118810_msgqsnd.c new file mode 100644 index 0000000000000000000000000000000000000000..df23d7dd25cd95b3a538ac8787721c33235cadca --- /dev/null +++ b/pool/shard006/C/0118810_msgqsnd.c @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include +#include + +struct message { + long msgtype; //verrà utilizzato nella ricezione del messaggio, deve essere positivo + char msgtxt[500]; //la max lunghezza del messaggio sarà di 500 char +}; + +int main(int argc, char const *argv[]) { + struct message buffer; + int msgq; + if(msgq=msgget(IPC_PRIVATE, IPC_CREAT | IPC_EXCL)==-1) { //crea una nuova coda di messaggi + if(errno==EEXIST) perror("Errore: coda preesistente"); + else perror("Errore non identificato nella creazione della coda"); + } + puts("\nTesto del messaggio:"); + buffer.msgtype=1; //viene impostato un tipo di messaggio qualsiasi + while(fgets(buffer.msgtxt, sizeof(buffer.msgtxt), stdin)!=NULL) { //l'utente inserisce il messaggio + int length=strlen(buffer.msgtxt); + if (buffer.msgtxt[length-1] == '\n') buffer.msgtxt[length-1] = '\0'; //scrive EOF + if(msgsnd(msgq, &buffer, length+1, 0)==-1) perror("Invio messaggio fallito"); //invia il messaggio + } + if(msgctl(msgq, IPC_RMID, NULL)==-1) perror("Chiusura coda di messaggi fallita"); //chiude la coda di messaggi, come specificato da IPC_RMID +} diff --git a/pool/shard006/C/0118816_iconv.c b/pool/shard006/C/0118816_iconv.c new file mode 100644 index 0000000000000000000000000000000000000000..8da4426390d6bf7fa1e47af4ca4b55368c2f751c --- /dev/null +++ b/pool/shard006/C/0118816_iconv.c @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "util/iconv.h" + +unsigned char *iconv_convert(const char *str, const char *from) { + size_t outlen = 0; + return iconv_convert4(str, from, strlen(str), &outlen); +} + +unsigned char *iconv_convert3(const char *str, const char *from, size_t inlen) { + size_t outlen = 0; + return iconv_convert4(str, from, inlen, &outlen); +} + +unsigned char *iconv_convert4(const char *str, const char *from, size_t inlen, size_t *outlen) { + assert(from); + unsigned char *out, *_out, *rv; + const unsigned char *in; + size_t o, _o, len, res, written = 0; + int delta; + iconv_t ic = iconv_open("UTF-8", from); + if (ic == (iconv_t) -1) { + worker_log(L_ERROR, "Failed to convert '%s' to utf-8: unknown encoding, please report", from); + return NULL; + } + len = o = 2 * inlen; + out = rv = calloc(1, len + 1); + in = (const unsigned char *)str; + while (inlen > 0) { + _out = out; + _o = o; + + errno = 0; + res = iconv(ic, (char **)&in, &inlen, (char **)&_out, &_o); + written += delta = o - _o; + // success, or incomplete sequence at the end (discard it) + if (res != (size_t) -1 || errno == EINVAL) { + out = _out, o = _o; + break; + } + // invalid byte sequence: skip a byte and try to continue + if (errno == EILSEQ) { + out = _out, o = _o; + in++, inlen--; + continue; + } + + // grow by inlen * 2 + len += inlen * 2; + rv = realloc(rv, len + 1); + out = rv + written; + o = len - written; + } + + *out = 0; + *outlen = written; + + iconv_close(ic); + return rv; +} diff --git a/pool/shard006/C/0118818_sat2.c b/pool/shard006/C/0118818_sat2.c new file mode 100644 index 0000000000000000000000000000000000000000..5aef1c03451ea2ce561072658ecf7426539964a2 --- /dev/null +++ b/pool/shard006/C/0118818_sat2.c @@ -0,0 +1,87 @@ +/* + * Circuit Satisfiability, Version 2 + * + * This enhanced version of the program also prints the + * total number of solutions. + * + */ + +#include +#include + +/* Return 1 if 'i'th bit of 'n' is 1; 0 otherwise */ +#define EXTRACT_BIT(n, i) ((n & (1< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +pgd_t swapper_pg_dir[PTRS_PER_PGD] __attribute__((__aligned__(PAGE_SIZE))); + +unsigned long empty_zero_page, zero_page_mask; +EXPORT_SYMBOL(empty_zero_page); +EXPORT_SYMBOL(zero_page_mask); + +static void __init setup_zero_pages(void) +{ + struct cpuid cpu_id; + unsigned int order; + struct page *page; + int i; + + get_cpu_id(&cpu_id); + switch (cpu_id.machine) { + case 0x9672: /* g5 */ + case 0x2064: /* z900 */ + case 0x2066: /* z900 */ + case 0x2084: /* z990 */ + case 0x2086: /* z990 */ + case 0x2094: /* z9-109 */ + case 0x2096: /* z9-109 */ + order = 0; + break; + case 0x2097: /* z10 */ + case 0x2098: /* z10 */ + case 0x2817: /* z196 */ + case 0x2818: /* z196 */ + order = 2; + break; + case 0x2827: /* zEC12 */ + case 0x2828: /* zEC12 */ + order = 5; + break; + case 0x2964: /* z13 */ + default: + order = 7; + break; + } + /* Limit number of empty zero pages for small memory sizes */ + while (order > 2 && (totalram_pages >> 10) < (1UL << order)) + order--; + + empty_zero_page = __get_free_pages(GFP_KERNEL | __GFP_ZERO, order); + if (!empty_zero_page) + panic("Out of memory in setup_zero_pages"); + + page = virt_to_page((void *) empty_zero_page); + split_page(page, order); + for (i = 1 << order; i > 0; i--) { + mark_page_reserved(page); + page++; + } + + zero_page_mask = ((PAGE_SIZE << order) - 1) & PAGE_MASK; +} + +/* + * paging_init() sets up the page tables + */ +void __init paging_init(void) +{ + unsigned long max_zone_pfns[MAX_NR_ZONES]; + unsigned long pgd_type, asce_bits; + + init_mm.pgd = swapper_pg_dir; + if (VMALLOC_END > (1UL << 42)) { + asce_bits = _ASCE_TYPE_REGION2 | _ASCE_TABLE_LENGTH; + pgd_type = _REGION2_ENTRY_EMPTY; + } else { + asce_bits = _ASCE_TYPE_REGION3 | _ASCE_TABLE_LENGTH; + pgd_type = _REGION3_ENTRY_EMPTY; + } + S390_lowcore.kernel_asce = (__pa(init_mm.pgd) & PAGE_MASK) | asce_bits; + clear_table((unsigned long *) init_mm.pgd, pgd_type, + sizeof(unsigned long)*2048); + vmem_map_init(); + + /* enable virtual mapping in kernel mode */ + __ctl_load(S390_lowcore.kernel_asce, 1, 1); + __ctl_load(S390_lowcore.kernel_asce, 7, 7); + __ctl_load(S390_lowcore.kernel_asce, 13, 13); + arch_local_irq_restore(4UL << (BITS_PER_LONG - 8)); + + sparse_memory_present_with_active_regions(MAX_NUMNODES); + sparse_init(); + memset(max_zone_pfns, 0, sizeof(max_zone_pfns)); + max_zone_pfns[ZONE_DMA] = PFN_DOWN(MAX_DMA_ADDRESS); + max_zone_pfns[ZONE_NORMAL] = max_low_pfn; + free_area_init_nodes(max_zone_pfns); +} + +void __init mem_init(void) +{ + if (MACHINE_HAS_TLB_LC) + cpumask_set_cpu(0, &init_mm.context.cpu_attach_mask); + cpumask_set_cpu(0, mm_cpumask(&init_mm)); + atomic_set(&init_mm.context.attach_count, 1); + + set_max_mapnr(max_low_pfn); + high_memory = (void *) __va(max_low_pfn * PAGE_SIZE); + + /* Setup guest page hinting */ + cmma_init(); + + /* this will put all low memory onto the freelists */ + free_all_bootmem(); + setup_zero_pages(); /* Setup zeroed pages. */ + + mem_init_print_info(NULL); + printk("Write protected kernel read-only data: %#lx - %#lx\n", + (unsigned long)&_stext, + PFN_ALIGN((unsigned long)&_eshared) - 1); +} + +void free_initmem(void) +{ + free_initmem_default(POISON_FREE_INITMEM); +} + +#ifdef CONFIG_BLK_DEV_INITRD +void __init free_initrd_mem(unsigned long start, unsigned long end) +{ + free_reserved_area((void *)start, (void *)end, POISON_FREE_INITMEM, + "initrd"); +} +#endif + +#ifdef CONFIG_MEMORY_HOTPLUG +int arch_add_memory(int nid, u64 start, u64 size, bool for_device) +{ + unsigned long normal_end_pfn = PFN_DOWN(memblock_end_of_DRAM()); + unsigned long dma_end_pfn = PFN_DOWN(MAX_DMA_ADDRESS); + unsigned long start_pfn = PFN_DOWN(start); + unsigned long size_pages = PFN_DOWN(size); + unsigned long nr_pages; + int rc, zone_enum; + + rc = vmem_add_mapping(start, size); + if (rc) + return rc; + + while (size_pages > 0) { + if (start_pfn < dma_end_pfn) { + nr_pages = (start_pfn + size_pages > dma_end_pfn) ? + dma_end_pfn - start_pfn : size_pages; + zone_enum = ZONE_DMA; + } else if (start_pfn < normal_end_pfn) { + nr_pages = (start_pfn + size_pages > normal_end_pfn) ? + normal_end_pfn - start_pfn : size_pages; + zone_enum = ZONE_NORMAL; + } else { + nr_pages = size_pages; + zone_enum = ZONE_MOVABLE; + } + rc = __add_pages(nid, NODE_DATA(nid)->node_zones + zone_enum, + start_pfn, size_pages); + if (rc) + break; + start_pfn += nr_pages; + size_pages -= nr_pages; + } + if (rc) + vmem_remove_mapping(start, size); + return rc; +} + +unsigned long memory_block_size_bytes(void) +{ + /* + * Make sure the memory block size is always greater + * or equal than the memory increment size. + */ + return max_t(unsigned long, MIN_MEMORY_BLOCK_SIZE, sclp.rzm); +} + +#ifdef CONFIG_MEMORY_HOTREMOVE +int arch_remove_memory(u64 start, u64 size) +{ + /* + * There is no hardware or firmware interface which could trigger a + * hot memory remove on s390. So there is nothing that needs to be + * implemented. + */ + return -EBUSY; +} +#endif +#endif /* CONFIG_MEMORY_HOTPLUG */ diff --git a/pool/shard006/C/0118824_init.c b/pool/shard006/C/0118824_init.c new file mode 100644 index 0000000000000000000000000000000000000000..762eb28b264873a9dee78ed6b66ee7a632b9e892 --- /dev/null +++ b/pool/shard006/C/0118824_init.c @@ -0,0 +1,101 @@ +/* cheb/init.c + * + * Copyright (C) 1996, 1997, 1998, 1999, 2000 Gerard Jungman + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include + +/*-*-*-*-*-*-*-*-*-*-*-* Allocators *-*-*-*-*-*-*-*-*-*-*-*/ + +gsl_cheb_series * +gsl_cheb_alloc(const size_t order) +{ + gsl_cheb_series * cs = (gsl_cheb_series *) malloc(sizeof(gsl_cheb_series)); + + if(cs == 0) { + GSL_ERROR_VAL("failed to allocate gsl_cheb_series struct", GSL_ENOMEM, 0); + } + + cs->order = order; + cs->order_sp = order; + + cs->c = (double *) malloc((order+1) * sizeof(double)); + + if(cs->c == 0) { + GSL_ERROR_VAL("failed to allocate cheb coefficients", GSL_ENOMEM, 0); + } + + cs->f = (double *) malloc((order+1) * sizeof(double)); + + if(cs->f == 0) { + GSL_ERROR_VAL("failed to allocate cheb function space", GSL_ENOMEM, 0); + } + + return cs; +} + + +void gsl_cheb_free(gsl_cheb_series * cs) +{ + free(cs->f); + free(cs->c); + free(cs); +} + +/*-*-*-*-*-*-*-*-*-*-*-* Initializer *-*-*-*-*-*-*-*-*-*-*-*/ + +int gsl_cheb_init(gsl_cheb_series * cs, const gsl_function *func, + const double a, const double b) +{ + size_t k, j; + + if(a >= b) { + GSL_ERROR_VAL("null function interval [a,b]", GSL_EDOM, 0); + } + cs->a = a; + cs->b = b; + /* cs->err = 0.0; */ + + { + double bma = 0.5 * (cs->b - cs->a); + double bpa = 0.5 * (cs->b + cs->a); + double fac = 2.0/(cs->order +1.0); + + for(k = 0; k<=cs->order; k++) { + double y = cos(M_PI * (k+0.5)/(cs->order+1)); + cs->f[k] = GSL_FN_EVAL(func, (y*bma + bpa)); + } + + for(j = 0; j<=cs->order; j++) { + double sum = 0.0; + for(k = 0; k<=cs->order; k++) + sum += cs->f[k]*cos(M_PI * j*(k+0.5)/(cs->order+1)); + cs->c[j] = fac * sum; + } + + } + return GSL_SUCCESS; +} + + + + + diff --git a/pool/shard006/C/0118828_condattr_init_3.c b/pool/shard006/C/0118828_condattr_init_3.c new file mode 100644 index 0000000000000000000000000000000000000000..8608e9117949264d92776a8053f27caf595afe07 --- /dev/null +++ b/pool/shard006/C/0118828_condattr_init_3.c @@ -0,0 +1,58 @@ +/* + If successful, hthread_condattr_init() shall return zero; + + Hardware may be tested in simulation. + + Methodology + 1. Call condattr_init, check the return status. + */ + +#include +#include +#include +#include "hthreadtest.h" + +#define EXPECTED_RESULT SUCCESS + +void * testThread ( void * arg ) { + int retVal; + hthread_condattr_t * condattr = (hthread_condattr_t *) arg; + + retVal = hthread_condattr_init( condattr ); + + hthread_exit( (void *) retVal ); + return NULL; +} + +int main() { + hthread_t test_thread; + hthread_attr_t test_attr; + hthread_condattr_t condattr; + int arg, retVal; + + //Print the name of the test to the screen + printf( "Starting test condattr_init_3\n" ); + + //Set up the arguments for the test + arg = (int) &condattr; + + //Initialize RPC + rpc_setup(); + + //Run the tests + hthread_attr_init( &test_attr ); + if ( HARDWARE ) hthread_attr_sethardware( &test_attr, HWTI_ONE_BASEADDR ); + hthread_create( &test_thread, &test_attr, testThread, (void *) arg ); + hthread_join( test_thread, (void *) &retVal ); + + if ( HARDWARE ) readHWTStatus( HWTI_ONE_BASEADDR ); + + //Evaluate the results + if ( retVal == EXPECTED_RESULT ) { + printf("Test PASSED\n"); + return PTS_PASS; + } else { + printf("Test FAILED [expecting %d, received %d]\n", EXPECTED_RESULT, retVal ); + return PTS_FAIL; + } +} diff --git a/pool/shard006/C/0118829_binding.c b/pool/shard006/C/0118829_binding.c new file mode 100644 index 0000000000000000000000000000000000000000..2c55bf0f6a4dafc43194106672b2f96eef7f811a --- /dev/null +++ b/pool/shard006/C/0118829_binding.c @@ -0,0 +1,45 @@ +#include + +#define FUNCTIONS_MAP(V) \ + V(hello, example_hello) \ + V(add, example_add) + +#define V(name, func) \ + extern napi_value func(napi_env env, napi_callback_info info); + + FUNCTIONS_MAP(V); +#undef V + +#ifdef __GNUC__ +#define UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +#define UNLIKELY(expr) (expr) +#endif + +#define ASSERT_NAPI_OK(expr) \ + if (UNLIKELY((expr) != napi_ok)) { \ + napi_throw_error(env, NULL, "Assertion failed: (" #expr ") != napi_ok"); \ + return NULL; \ + } + +napi_value init_bindings(napi_env env, napi_value exports) { +#define V(name, func) \ + { #name, NULL, func, NULL, NULL, NULL, napi_default, NULL }, + + napi_property_descriptor descriptors[] = { + FUNCTIONS_MAP(V) + }; +#undef V + + napi_status status = napi_define_properties( + env, + exports, + sizeof(descriptors) / sizeof(descriptors[0]), + descriptors); + + ASSERT_NAPI_OK(status); + + return exports; +} + +NAPI_MODULE(NODE_GYP_MODULE_NAME, init_bindings) diff --git a/pool/shard006/C/0118830_gimpoperationerasemode.c b/pool/shard006/C/0118830_gimpoperationerasemode.c new file mode 100644 index 0000000000000000000000000000000000000000..abd8c2deead5b5aa1054de5ff9181b6e1e11db4a --- /dev/null +++ b/pool/shard006/C/0118830_gimpoperationerasemode.c @@ -0,0 +1,90 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * gimpoperationerasemode.c + * Copyright (C) 2008 Michael Natterer + * + * 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 "config.h" + +#include + +#include "gimp-gegl-types.h" + +#include "gimpoperationerasemode.h" + + +static gboolean gimp_operation_erase_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi); + + +G_DEFINE_TYPE (GimpOperationEraseMode, gimp_operation_erase_mode, + GIMP_TYPE_OPERATION_POINT_LAYER_MODE) + + +static void +gimp_operation_erase_mode_class_init (GimpOperationEraseModeClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationPointComposerClass *point_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + point_class = GEGL_OPERATION_POINT_COMPOSER_CLASS (klass); + + gegl_operation_class_set_keys (operation_class, + "name" , "gimp:erase-mode", + "description", "GIMP erase mode operation", + NULL); + + point_class->process = gimp_operation_erase_mode_process; +} + +static void +gimp_operation_erase_mode_init (GimpOperationEraseMode *self) +{ +} + +static gboolean +gimp_operation_erase_mode_process (GeglOperation *operation, + void *in_buf, + void *aux_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi) +{ + gfloat *in = in_buf; + gfloat *layer = aux_buf; + gfloat *out = out_buf; + + while (samples--) + { + out[RED] = in[RED]; + out[GREEN] = in[GREEN]; + out[BLUE] = in[BLUE]; + out[ALPHA] = in[ALPHA]; + + in += 4; + layer += 4; + out += 4; + } + + return TRUE; +} diff --git a/pool/shard006/C/0118831_service.c b/pool/shard006/C/0118831_service.c new file mode 100644 index 0000000000000000000000000000000000000000..7ccf48742e3dd46887b65a8036651e00e7b36cff --- /dev/null +++ b/pool/shard006/C/0118831_service.c @@ -0,0 +1,148 @@ +/*****************************************************************************\ + * Copyright (c) 2014 Lawrence Livermore National Security, LLC. Produced at + * the Lawrence Livermore National Laboratory (cf, AUTHORS, DISCLAIMER.LLNS). + * LLNL-CODE-658032 All rights reserved. + * + * This file is part of the Flux resource manager framework. + * For details, see https://github.com/flux-framework. + * + * 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. + * + * Flux 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 terms and conditions of 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. + * See also: http://www.gnu.org/licenses/ +\*****************************************************************************/ + +#if HAVE_CONFIG_H +#include "config.h" +#endif +#include +#include + +#include "src/common/libutil/xzmalloc.h" +#include "src/common/libutil/log.h" +#include "src/common/libutil/oom.h" + +#include "service.h" + +struct svc_struct { + svc_cb_f cb; + void *cb_arg; + char *alias; +}; + +struct svchash_struct { + zhash_t *services; + zhash_t *aliases; +}; + +svchash_t *svchash_create (void) +{ + svchash_t *sh = xzmalloc (sizeof *sh); + sh->services = zhash_new (); + sh->aliases = zhash_new (); + if (!sh->services || !sh->aliases) + oom (); + return sh; +} + +void svchash_destroy (svchash_t *sh) +{ + if (sh) { + zhash_destroy (&sh->services); + zhash_destroy (&sh->aliases); + free (sh); + } +} + +static void svc_destroy (svc_t *svc) +{ + if (svc) { + if (svc->alias) + free (svc->alias); + free (svc); + } +} + +static svc_t *svc_create (void) +{ + svc_t *svc = xzmalloc (sizeof (*svc)); + return svc; +} + +void svc_remove (svchash_t *sh, const char *name) +{ + svc_t *svc = zhash_lookup (sh->services, name); + if (svc) { + if (svc->alias) + zhash_delete (sh->aliases, svc->alias); + zhash_delete (sh->services, name); + } +} + +svc_t *svc_add (svchash_t *sh, const char *name, const char *alias, + svc_cb_f cb, void *arg) +{ + svc_t *svc; + int rc; + if (zhash_lookup (sh->services, name) + || (alias && zhash_lookup (sh->aliases, alias))) { + errno = EEXIST; + return NULL; + } + svc = svc_create (); + svc->cb = cb; + svc->cb_arg = arg; + rc = zhash_insert (sh->services, name, svc); + assert (rc == 0); + zhash_freefn (sh->services, name, (zhash_free_fn *)svc_destroy); + if (alias) { + svc->alias = xstrdup (alias); + rc = zhash_insert (sh->aliases, alias, svc); + assert (rc == 0); + } + return svc; +} + +int svc_sendmsg (svchash_t *sh, const flux_msg_t *msg) +{ + const char *topic; + int type; + svc_t *svc; + int rc = -1; + + if (flux_msg_get_type (msg, &type) < 0) + goto done; + if (flux_msg_get_topic (msg, &topic) < 0) + goto done; + if (!(svc = zhash_lookup (sh->services, topic))) + svc = zhash_lookup (sh->aliases, topic); + if (!svc && strchr (topic, '.')) { + char *p, *short_topic = xstrdup (topic); + if ((p = strchr (short_topic, '.'))) + *p = '\0'; + if (!(svc = zhash_lookup (sh->services, short_topic))) + svc = zhash_lookup (sh->aliases, short_topic); + free (short_topic); + } + if (!svc) { + errno = ENOSYS; + goto done; + } + rc = svc->cb (msg, svc->cb_arg); +done: + return rc; +} + +/* + * vi:tabstop=4 shiftwidth=4 expandtab + */ diff --git a/pool/shard006/C/0118833_cylinder.c b/pool/shard006/C/0118833_cylinder.c new file mode 100644 index 0000000000000000000000000000000000000000..09c39e5e638631a784faed8106835dbe7e49ff47 --- /dev/null +++ b/pool/shard006/C/0118833_cylinder.c @@ -0,0 +1,200 @@ +/* + * linux/fs/ufs/cylinder.c + * + * Copyright (C) 1998 + * Daniel Pirkl + * Charles University, Faculty of Mathematics and Physics + * + * ext2 - inode (block) bitmap caching inspired + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include "swab.h" +#include "util.h" + +/* + * Read cylinder group into cache. The memory space for ufs_cg_private_info + * structure is already allocated during ufs_read_super. + */ +static void ufs_read_cylinder (struct super_block * sb, + unsigned cgno, unsigned bitmap_nr) +{ + struct ufs_sb_info * sbi = UFS_SB(sb); + struct ufs_sb_private_info * uspi; + struct ufs_cg_private_info * ucpi; + struct ufs_cylinder_group * ucg; + unsigned i, j; + + UFSD("ENTER, cgno %u, bitmap_nr %u\n", cgno, bitmap_nr); + uspi = sbi->s_uspi; + ucpi = sbi->s_ucpi[bitmap_nr]; + ucg = (struct ufs_cylinder_group *)sbi->s_ucg[cgno]->b_data; + + UCPI_UBH(ucpi)->fragment = ufs_cgcmin(cgno); + UCPI_UBH(ucpi)->count = uspi->s_cgsize >> sb->s_blocksize_bits; + /* + * We have already the first fragment of cylinder group block in buffer + */ + UCPI_UBH(ucpi)->bh[0] = sbi->s_ucg[cgno]; + for (i = 1; i < UCPI_UBH(ucpi)->count; i++) + if (!(UCPI_UBH(ucpi)->bh[i] = sb_bread(sb, UCPI_UBH(ucpi)->fragment + i))) + goto failed; + sbi->s_cgno[bitmap_nr] = cgno; + + ucpi->c_cgx = fs32_to_cpu(sb, ucg->cg_cgx); + ucpi->c_ncyl = fs16_to_cpu(sb, ucg->cg_ncyl); + ucpi->c_niblk = fs16_to_cpu(sb, ucg->cg_niblk); + ucpi->c_ndblk = fs32_to_cpu(sb, ucg->cg_ndblk); + ucpi->c_rotor = fs32_to_cpu(sb, ucg->cg_rotor); + ucpi->c_frotor = fs32_to_cpu(sb, ucg->cg_frotor); + ucpi->c_irotor = fs32_to_cpu(sb, ucg->cg_irotor); + ucpi->c_btotoff = fs32_to_cpu(sb, ucg->cg_btotoff); + ucpi->c_boff = fs32_to_cpu(sb, ucg->cg_boff); + ucpi->c_iusedoff = fs32_to_cpu(sb, ucg->cg_iusedoff); + ucpi->c_freeoff = fs32_to_cpu(sb, ucg->cg_freeoff); + ucpi->c_nextfreeoff = fs32_to_cpu(sb, ucg->cg_nextfreeoff); + ucpi->c_clustersumoff = fs32_to_cpu(sb, ucg->cg_u.cg_44.cg_clustersumoff); + ucpi->c_clusteroff = fs32_to_cpu(sb, ucg->cg_u.cg_44.cg_clusteroff); + ucpi->c_nclusterblks = fs32_to_cpu(sb, ucg->cg_u.cg_44.cg_nclusterblks); + UFSD("EXIT\n"); + return; + +failed: + for (j = 1; j < i; j++) + brelse (sbi->s_ucg[j]); + sbi->s_cgno[bitmap_nr] = UFS_CGNO_EMPTY; + ufs_error (sb, "ufs_read_cylinder", "can't read cylinder group block %u", cgno); +} + +/* + * Remove cylinder group from cache, doesn't release memory + * allocated for cylinder group (this is done at ufs_put_super only). + */ +void ufs_put_cylinder (struct super_block * sb, unsigned bitmap_nr) +{ + struct ufs_sb_info * sbi = UFS_SB(sb); + struct ufs_sb_private_info * uspi; + struct ufs_cg_private_info * ucpi; + struct ufs_cylinder_group * ucg; + unsigned i; + + UFSD("ENTER, bitmap_nr %u\n", bitmap_nr); + + uspi = sbi->s_uspi; + if (sbi->s_cgno[bitmap_nr] == UFS_CGNO_EMPTY) { + UFSD("EXIT\n"); + return; + } + ucpi = sbi->s_ucpi[bitmap_nr]; + ucg = ubh_get_ucg(UCPI_UBH(ucpi)); + + if (uspi->s_ncg > UFS_MAX_GROUP_LOADED && bitmap_nr >= sbi->s_cg_loaded) { + ufs_panic (sb, "ufs_put_cylinder", "internal error"); + return; + } + /* + * rotor is not so important data, so we put it to disk + * at the end of working with cylinder + */ + ucg->cg_rotor = cpu_to_fs32(sb, ucpi->c_rotor); + ucg->cg_frotor = cpu_to_fs32(sb, ucpi->c_frotor); + ucg->cg_irotor = cpu_to_fs32(sb, ucpi->c_irotor); + ubh_mark_buffer_dirty (UCPI_UBH(ucpi)); + for (i = 1; i < UCPI_UBH(ucpi)->count; i++) { + brelse (UCPI_UBH(ucpi)->bh[i]); + } + + sbi->s_cgno[bitmap_nr] = UFS_CGNO_EMPTY; + UFSD("EXIT\n"); +} + +/* + * Find cylinder group in cache and return it as pointer. + * If cylinder group is not in cache, we will load it from disk. + * + * The cache is managed by LRU algorithm. + */ +struct ufs_cg_private_info * ufs_load_cylinder ( + struct super_block * sb, unsigned cgno) +{ + struct ufs_sb_info * sbi = UFS_SB(sb); + struct ufs_sb_private_info * uspi; + struct ufs_cg_private_info * ucpi; + unsigned cg, i, j; + + UFSD("ENTER, cgno %u\n", cgno); + + uspi = sbi->s_uspi; + if (cgno >= uspi->s_ncg) { + ufs_panic (sb, "ufs_load_cylinder", "internal error, high number of cg"); + return NULL; + } + /* + * Cylinder group number cg it in cache and it was last used + */ + if (sbi->s_cgno[0] == cgno) { + UFSD("EXIT\n"); + return sbi->s_ucpi[0]; + } + /* + * Number of cylinder groups is not higher than UFS_MAX_GROUP_LOADED + */ + if (uspi->s_ncg <= UFS_MAX_GROUP_LOADED) { + if (sbi->s_cgno[cgno] != UFS_CGNO_EMPTY) { + if (sbi->s_cgno[cgno] != cgno) { + ufs_panic (sb, "ufs_load_cylinder", "internal error, wrong number of cg in cache"); + UFSD("EXIT (FAILED)\n"); + return NULL; + } + else { + UFSD("EXIT\n"); + return sbi->s_ucpi[cgno]; + } + } else { + ufs_read_cylinder (sb, cgno, cgno); + UFSD("EXIT\n"); + return sbi->s_ucpi[cgno]; + } + } + /* + * Cylinder group number cg is in cache but it was not last used, + * we will move to the first position + */ + for (i = 0; i < sbi->s_cg_loaded && sbi->s_cgno[i] != cgno; i++); + if (i < sbi->s_cg_loaded && sbi->s_cgno[i] == cgno) { + cg = sbi->s_cgno[i]; + ucpi = sbi->s_ucpi[i]; + for (j = i; j > 0; j--) { + sbi->s_cgno[j] = sbi->s_cgno[j-1]; + sbi->s_ucpi[j] = sbi->s_ucpi[j-1]; + } + sbi->s_cgno[0] = cg; + sbi->s_ucpi[0] = ucpi; + /* + * Cylinder group number cg is not in cache, we will read it from disk + * and put it to the first position + */ + } else { + if (sbi->s_cg_loaded < UFS_MAX_GROUP_LOADED) + sbi->s_cg_loaded++; + else + ufs_put_cylinder (sb, UFS_MAX_GROUP_LOADED-1); + ucpi = sbi->s_ucpi[sbi->s_cg_loaded - 1]; + for (j = sbi->s_cg_loaded - 1; j > 0; j--) { + sbi->s_cgno[j] = sbi->s_cgno[j-1]; + sbi->s_ucpi[j] = sbi->s_ucpi[j-1]; + } + sbi->s_ucpi[0] = ucpi; + ufs_read_cylinder (sb, cgno, 0); + } + UFSD("EXIT\n"); + return sbi->s_ucpi[0]; +} diff --git a/pool/shard006/C/0118835_ml_SN_init.c b/pool/shard006/C/0118835_ml_SN_init.c new file mode 100644 index 0000000000000000000000000000000000000000..47a0fdeada4068b76c9b18d77a7c65bd58e51bae --- /dev/null +++ b/pool/shard006/C/0118835_ml_SN_init.c @@ -0,0 +1,137 @@ +/* $Id: ml_SN_init.c,v 1.1.1.1 2004/09/28 06:05:42 sure Exp $ + * + * 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. + * + * Copyright (C) 1992 - 1997, 2000-2003 Silicon Graphics, Inc. All rights reserved. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern cpuid_t master_procid; +int maxcpus; + +extern xwidgetnum_t hub_widget_id(nasid_t); + +extern void iograph_early_init(void); + +nasid_t master_nasid = INVALID_NASID; /* This is the partition master nasid */ +nasid_t master_baseio_nasid = INVALID_NASID; /* This is the master base I/O nasid */ + + +/* + * mlreset(void) + * very early machine reset - at this point NO interrupts have been + * enabled; nor is memory, tlb, p0, etc setup. + * + * slave is zero when mlreset is called for the master processor and + * is nonzero thereafter. + */ + + +void +mlreset(int slave) +{ + /* + * We are the master cpu and node. + */ + master_nasid = get_nasid(); + set_master_bridge_base(); + + /* We're the master processor */ + master_procid = smp_processor_id(); + master_nasid = cpuid_to_nasid(master_procid); + + /* + * master_nasid we get back better be same as one from + * get_nasid() + */ + ASSERT_ALWAYS(master_nasid == get_nasid()); + + /* early initialization of iograph */ + iograph_early_init(); + + /* Initialize Hub Pseudodriver Management */ + hubdev_init(); +} + + +/* XXX - Move the meat of this to intr.c ? */ +/* + * Set up the platform-dependent fields in the nodepda. + */ +void init_platform_nodepda(nodepda_t *npda, cnodeid_t node) +{ + hubinfo_t hubinfo; + + extern void router_map_init(nodepda_t *); + extern void router_queue_init(nodepda_t *,cnodeid_t); + extern void intr_init_vecblk(nodepda_t *, cnodeid_t, int); + + /* Allocate per-node platform-dependent data */ + hubinfo = (hubinfo_t)alloc_bootmem_node(NODE_DATA(node), sizeof(struct hubinfo_s)); + + npda->pdinfo = (void *)hubinfo; + hubinfo->h_nodepda = npda; + hubinfo->h_cnodeid = node; + hubinfo->h_nasid = COMPACT_TO_NASID_NODEID(node); + + spin_lock_init(&hubinfo->h_crblock); + + hubinfo->h_widgetid = hub_widget_id(hubinfo->h_nasid); + npda->xbow_peer = INVALID_NASID; + + /* + * Initialize the linked list of + * router info pointers to the dependent routers + */ + npda->npda_rip_first = NULL; + + /* + * npda_rip_last always points to the place + * where the next element is to be inserted + * into the list + */ + npda->npda_rip_last = &npda->npda_rip_first; + npda->geoid.any.type = GEO_TYPE_INVALID; + + mutex_init_locked(&npda->xbow_sema); /* init it locked? */ +} + +void +update_node_information(cnodeid_t cnodeid) +{ + nodepda_t *npda = NODEPDA(cnodeid); + nodepda_router_info_t *npda_rip; + + /* Go through the list of router info + * structures and copy some frequently + * accessed info from the info hanging + * off the corresponding router vertices + */ + npda_rip = npda->npda_rip_first; + while(npda_rip) { + if (npda_rip->router_infop) { + npda_rip->router_portmask = + npda_rip->router_infop->ri_portmask; + npda_rip->router_slot = + npda_rip->router_infop->ri_slotnum; + } else { + /* No router, no ports. */ + npda_rip->router_portmask = 0; + } + npda_rip = npda_rip->router_next; + } +} diff --git a/pool/shard006/C/0118837_rtGetInf.c b/pool/shard006/C/0118837_rtGetInf.c new file mode 100644 index 0000000000000000000000000000000000000000..7ca90ad7cc4616893b4289bec9068fb36e45a5f7 --- /dev/null +++ b/pool/shard006/C/0118837_rtGetInf.c @@ -0,0 +1,140 @@ +/* + * rtGetInf.c + * + * Code generation for model "ctrl_P". + * + * Model version : 1.3 + * Simulink Coder version : 8.6 (R2014a) 27-Dec-2013 + * C source code generated on : Tue Jan 27 16:34:41 2015 + * + * Target selection: NIVeriStand_VxWorks.tlc + * Note: GRT includes extra infrastructure and instrumentation for prototyping + * Embedded hardware selection: 32-bit Generic + * Code generation objectives: Unspecified + * Validation result: Not run + */ +/* + * Abstract: + * Function to intialize non-finite, Inf + */ + +#include "rtGetInf.h" +#define NumBitsPerChar 8U + +/* + * Initialize rtInf needed by the generated code. + * Inf is initialized as non-signaling. Assumes IEEE. + */ +real_T rtGetInf(void) +{ + size_t bitsPerReal = sizeof(real_T) * (NumBitsPerChar); + real_T inf = 0.0; + if (bitsPerReal == 32U) { + inf = rtGetInfF(); + } else { + uint16_T one = 1U; + enum { + LittleEndian, + BigEndian + } machByteOrder = (*((uint8_T *) &one) == 1U) ? LittleEndian : BigEndian; + switch (machByteOrder) { + case LittleEndian: + { + union { + LittleEndianIEEEDouble bitVal; + real_T fltVal; + } tmpVal; + + tmpVal.bitVal.words.wordH = 0x7FF00000U; + tmpVal.bitVal.words.wordL = 0x00000000U; + inf = tmpVal.fltVal; + break; + } + + case BigEndian: + { + union { + BigEndianIEEEDouble bitVal; + real_T fltVal; + } tmpVal; + + tmpVal.bitVal.words.wordH = 0x7FF00000U; + tmpVal.bitVal.words.wordL = 0x00000000U; + inf = tmpVal.fltVal; + break; + } + } + } + + return inf; +} + +/* + * Initialize rtInfF needed by the generated code. + * Inf is initialized as non-signaling. Assumes IEEE. + */ +real32_T rtGetInfF(void) +{ + IEEESingle infF; + infF.wordL.wordLuint = 0x7F800000U; + return infF.wordL.wordLreal; +} + +/* + * Initialize rtMinusInf needed by the generated code. + * Inf is initialized as non-signaling. Assumes IEEE. + */ +real_T rtGetMinusInf(void) +{ + size_t bitsPerReal = sizeof(real_T) * (NumBitsPerChar); + real_T minf = 0.0; + if (bitsPerReal == 32U) { + minf = rtGetMinusInfF(); + } else { + uint16_T one = 1U; + enum { + LittleEndian, + BigEndian + } machByteOrder = (*((uint8_T *) &one) == 1U) ? LittleEndian : BigEndian; + switch (machByteOrder) { + case LittleEndian: + { + union { + LittleEndianIEEEDouble bitVal; + real_T fltVal; + } tmpVal; + + tmpVal.bitVal.words.wordH = 0xFFF00000U; + tmpVal.bitVal.words.wordL = 0x00000000U; + minf = tmpVal.fltVal; + break; + } + + case BigEndian: + { + union { + BigEndianIEEEDouble bitVal; + real_T fltVal; + } tmpVal; + + tmpVal.bitVal.words.wordH = 0xFFF00000U; + tmpVal.bitVal.words.wordL = 0x00000000U; + minf = tmpVal.fltVal; + break; + } + } + } + + return minf; +} + +/* + * Initialize rtMinusInfF needed by the generated code. + * Inf is initialized as non-signaling. Assumes IEEE. + */ +real32_T rtGetMinusInfF(void) +{ + IEEESingle minfF; + minfF.wordL.wordLuint = 0xFF800000U; + return minfF.wordL.wordLreal; +} diff --git a/pool/shard006/C/0118840_sharefile.c b/pool/shard006/C/0118840_sharefile.c new file mode 100644 index 0000000000000000000000000000000000000000..02d25cc2ed9f379aca65da10e79f4ca6e103d5a4 --- /dev/null +++ b/pool/shard006/C/0118840_sharefile.c @@ -0,0 +1,203 @@ +/* sharefile.c -- open files just once. + Copyright (C) 2008-2019 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 . +*/ + +/* config.h always comes first. */ +#include + +/* system headers. */ +#include +#include +#include +#include +#include +#include + +/* gnulib headers. */ +#include "cloexec.h" +#include "hash.h" +#include "stdio-safer.h" + +/* find headers. */ +#include "sharefile.h" +#include "defs.h" + + +enum + { + DefaultHashTableSize = 11 + }; + +struct sharefile +{ + char *mode; + Hash_table *table; +}; + + +/* + * We cannot use the name to determine that two strings represent the + * same file, since that test would be fooled by symbolic links. + * Instead we use the device and inode number. + * + * However, we remember the name of each file that we opened. This + * allows us to issue a fatal error message when (flushing and) + * closing a file fails. + */ +struct SharefileEntry +{ + dev_t device; + ino_t inode; + char *name; /* not the only name for this file; error messages only */ + FILE *fp; +}; + + +static bool +entry_comparator (const void *av, const void *bv) +{ + const struct SharefileEntry *a=av, *b=bv; + return (a->inode == b->inode) && (a->device == b->device); +} + +static void +entry_free (void *pv) +{ + struct SharefileEntry *p = pv; + if (p->fp) + { + if (0 != fclose (p->fp)) + fatal_nontarget_file_error (errno, p->name); + } + free (p->name); + free (p); +} + +static size_t +entry_hashfunc (const void *pv, size_t buckets) +{ + const struct SharefileEntry *p = pv; + return (p->device ^ p->inode) % buckets; +} + + + +sharefile_handle +sharefile_init (const char *mode) +{ + struct Hash_tuning; + + struct sharefile *p = malloc (sizeof (struct sharefile)); + if (p) + { + p->mode = strdup (mode); + if (p->mode) + { + p->table = hash_initialize (DefaultHashTableSize, NULL, + entry_hashfunc, + entry_comparator, + entry_free); + if (p->table) + { + return p; + } + else + { + free (p->mode); + free (p); + } + } + else + { + free (p); + } + } + return NULL; +} + +void +sharefile_destroy (sharefile_handle pv) +{ + struct sharefile *p = pv; + free (p->mode); + hash_free (p->table); +} + + +FILE * +sharefile_fopen (sharefile_handle h, const char *filename) +{ + struct sharefile *p = h; + struct SharefileEntry *new_entry; + + new_entry = malloc (sizeof (struct SharefileEntry)); + if (!new_entry) + return NULL; + + new_entry->name = strdup (filename); + if (NULL == new_entry->name) + { + free (new_entry); + return NULL; + } + + if (NULL == (new_entry->fp = fopen_safer (filename, p->mode))) + { + free (new_entry); + return NULL; + } + else + { + struct stat st; + const int fd = fileno (new_entry->fp); + assert (fd >= 0); + + set_cloexec_flag (fd, true); + if (fstat (fd, &st) < 0) + { + entry_free (new_entry); + return NULL; + } + else + { + void *existing; + + new_entry->device = st.st_dev; + new_entry->inode = st.st_ino; + + existing = hash_lookup (p->table, new_entry); + if (existing) /* We have previously opened that file. */ + { + entry_free (new_entry); /* don't need new_entry. */ + return ((const struct SharefileEntry*)existing)->fp; + } + else /* We didn't open it already */ + { + if (hash_insert (p->table, new_entry)) + { + return new_entry->fp; + } + else /* failed to insert in hashtable. */ + { + const int save_errno = errno; + entry_free (new_entry); + errno = save_errno; + return NULL; + } + } + } + } +} diff --git a/pool/shard006/C/0118841_slot-gpio.c b/pool/shard006/C/0118841_slot-gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..27117ba4707312dad5f06bbf142ffe50c34efa22 --- /dev/null +++ b/pool/shard006/C/0118841_slot-gpio.c @@ -0,0 +1,305 @@ +/* + * Generic GPIO card-detect helper + * + * Copyright (C) 2011, Guennadi Liakhovetski + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include "slot-gpio.h" + +struct mmc_gpio { + struct gpio_desc *ro_gpio; + struct gpio_desc *cd_gpio; + bool override_ro_active_level; + bool override_cd_active_level; + irqreturn_t (*cd_gpio_isr)(int irq, void *dev_id); + char *ro_label; + char cd_label[0]; +}; + +static irqreturn_t mmc_gpio_cd_irqt(int irq, void *dev_id) +{ + /* Schedule a card detection after a debounce timeout */ + struct mmc_host *host = dev_id; + + host->trigger_card_event = true; + mmc_detect_change(host, msecs_to_jiffies(200)); + + return IRQ_HANDLED; +} + +int mmc_gpio_alloc(struct mmc_host *host) +{ + size_t len = strlen(dev_name(host->parent)) + 4; + struct mmc_gpio *ctx = devm_kzalloc(host->parent, + sizeof(*ctx) + 2 * len, GFP_KERNEL); + + if (ctx) { + ctx->ro_label = ctx->cd_label + len; + snprintf(ctx->cd_label, len, "%s cd", dev_name(host->parent)); + snprintf(ctx->ro_label, len, "%s ro", dev_name(host->parent)); + host->slot.handler_priv = ctx; + host->slot.cd_irq = -EINVAL; + } + + return ctx ? 0 : -ENOMEM; +} + +int mmc_gpio_get_ro(struct mmc_host *host) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + + if (!ctx || !ctx->ro_gpio) + return -ENOSYS; + + if (ctx->override_ro_active_level) + return !gpiod_get_raw_value_cansleep(ctx->ro_gpio) ^ + !!(host->caps2 & MMC_CAP2_RO_ACTIVE_HIGH); + + return gpiod_get_value_cansleep(ctx->ro_gpio); +} +EXPORT_SYMBOL(mmc_gpio_get_ro); + +int mmc_gpio_get_cd(struct mmc_host *host) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + + if (!ctx || !ctx->cd_gpio) + return -ENOSYS; + + if (ctx->override_cd_active_level) + return !gpiod_get_raw_value_cansleep(ctx->cd_gpio) ^ + !!(host->caps2 & MMC_CAP2_CD_ACTIVE_HIGH); + + return gpiod_get_value_cansleep(ctx->cd_gpio); +} +EXPORT_SYMBOL(mmc_gpio_get_cd); + +/** + * mmc_gpio_request_ro - request a gpio for write-protection + * @host: mmc host + * @gpio: gpio number requested + * + * As devm_* managed functions are used in mmc_gpio_request_ro(), client + * drivers do not need to worry about freeing up memory. + * + * Returns zero on success, else an error. + */ +int mmc_gpio_request_ro(struct mmc_host *host, unsigned int gpio) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + int ret; + + if (!gpio_is_valid(gpio)) + return -EINVAL; + + ret = devm_gpio_request_one(host->parent, gpio, GPIOF_DIR_IN, + ctx->ro_label); + if (ret < 0) + return ret; + + ctx->override_ro_active_level = true; + ctx->ro_gpio = gpio_to_desc(gpio); + + return 0; +} +EXPORT_SYMBOL(mmc_gpio_request_ro); + +void mmc_gpiod_request_cd_irq(struct mmc_host *host) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + int ret, irq; + + if (host->slot.cd_irq >= 0 || !ctx || !ctx->cd_gpio) + return; + + irq = gpiod_to_irq(ctx->cd_gpio); + + /* + * Even if gpiod_to_irq() returns a valid IRQ number, the platform might + * still prefer to poll, e.g., because that IRQ number is already used + * by another unit and cannot be shared. + */ + if (irq >= 0 && host->caps & MMC_CAP_NEEDS_POLL) + irq = -EINVAL; + + if (irq >= 0) { + if (!ctx->cd_gpio_isr) + ctx->cd_gpio_isr = mmc_gpio_cd_irqt; + ret = devm_request_threaded_irq(host->parent, irq, + NULL, ctx->cd_gpio_isr, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING | IRQF_ONESHOT, + ctx->cd_label, host); + if (ret < 0) + irq = ret; + } + + host->slot.cd_irq = irq; + + if (irq < 0) + host->caps |= MMC_CAP_NEEDS_POLL; +} +EXPORT_SYMBOL(mmc_gpiod_request_cd_irq); + +/* Register an alternate interrupt service routine for + * the card-detect GPIO. + */ +void mmc_gpio_set_cd_isr(struct mmc_host *host, + irqreturn_t (*isr)(int irq, void *dev_id)) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + + WARN_ON(ctx->cd_gpio_isr); + ctx->cd_gpio_isr = isr; +} +EXPORT_SYMBOL(mmc_gpio_set_cd_isr); + +/** + * mmc_gpio_request_cd - request a gpio for card-detection + * @host: mmc host + * @gpio: gpio number requested + * @debounce: debounce time in microseconds + * + * As devm_* managed functions are used in mmc_gpio_request_cd(), client + * drivers do not need to worry about freeing up memory. + * + * If GPIO debouncing is desired, set the debounce parameter to a non-zero + * value. The caller is responsible for ensuring that the GPIO driver associated + * with the GPIO supports debouncing, otherwise an error will be returned. + * + * Returns zero on success, else an error. + */ +int mmc_gpio_request_cd(struct mmc_host *host, unsigned int gpio, + unsigned int debounce) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + int ret; + + ret = devm_gpio_request_one(host->parent, gpio, GPIOF_DIR_IN, + ctx->cd_label); + if (ret < 0) + /* + * don't bother freeing memory. It might still get used by other + * slot functions, in any case it will be freed, when the device + * is destroyed. + */ + return ret; + + if (debounce) { + ret = gpio_set_debounce(gpio, debounce); + if (ret < 0) + return ret; + } + + ctx->override_cd_active_level = true; + ctx->cd_gpio = gpio_to_desc(gpio); + + return 0; +} +EXPORT_SYMBOL(mmc_gpio_request_cd); + +/** + * mmc_gpiod_request_cd - request a gpio descriptor for card-detection + * @host: mmc host + * @con_id: function within the GPIO consumer + * @idx: index of the GPIO to obtain in the consumer + * @override_active_level: ignore %GPIO_ACTIVE_LOW flag + * @debounce: debounce time in microseconds + * @gpio_invert: will return whether the GPIO line is inverted or not, set + * to NULL to ignore + * + * Use this function in place of mmc_gpio_request_cd() to use the GPIO + * descriptor API. Note that it must be called prior to mmc_add_host() + * otherwise the caller must also call mmc_gpiod_request_cd_irq(). + * + * Returns zero on success, else an error. + */ +int mmc_gpiod_request_cd(struct mmc_host *host, const char *con_id, + unsigned int idx, bool override_active_level, + unsigned int debounce, bool *gpio_invert) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + struct gpio_desc *desc; + int ret; + + if (!con_id) + con_id = ctx->cd_label; + + desc = devm_gpiod_get_index(host->parent, con_id, idx, GPIOD_IN); + if (IS_ERR(desc)) + return PTR_ERR(desc); + + if (debounce) { + ret = gpiod_set_debounce(desc, debounce); + if (ret < 0) + return ret; + } + + if (gpio_invert) + *gpio_invert = !gpiod_is_active_low(desc); + + ctx->override_cd_active_level = override_active_level; + ctx->cd_gpio = desc; + + return 0; +} +EXPORT_SYMBOL(mmc_gpiod_request_cd); + +/** + * mmc_gpiod_request_ro - request a gpio descriptor for write protection + * @host: mmc host + * @con_id: function within the GPIO consumer + * @idx: index of the GPIO to obtain in the consumer + * @override_active_level: ignore %GPIO_ACTIVE_LOW flag + * @debounce: debounce time in microseconds + * @gpio_invert: will return whether the GPIO line is inverted or not, + * set to NULL to ignore + * + * Use this function in place of mmc_gpio_request_ro() to use the GPIO + * descriptor API. + * + * Returns zero on success, else an error. + */ +int mmc_gpiod_request_ro(struct mmc_host *host, const char *con_id, + unsigned int idx, bool override_active_level, + unsigned int debounce, bool *gpio_invert) +{ + struct mmc_gpio *ctx = host->slot.handler_priv; + struct gpio_desc *desc; + int ret; + + if (!con_id) + con_id = ctx->ro_label; + + desc = devm_gpiod_get_index(host->parent, con_id, idx, GPIOD_IN); + if (IS_ERR(desc)) + return PTR_ERR(desc); + + if (debounce) { + ret = gpiod_set_debounce(desc, debounce); + if (ret < 0) + return ret; + } + + if (gpio_invert) + *gpio_invert = !gpiod_is_active_low(desc); + + ctx->override_ro_active_level = override_active_level; + ctx->ro_gpio = desc; + + return 0; +} +EXPORT_SYMBOL(mmc_gpiod_request_ro); diff --git a/pool/shard006/C/0118842_add.c b/pool/shard006/C/0118842_add.c new file mode 100644 index 0000000000000000000000000000000000000000..856e4ecb0f17166ff17910bf14391d956fa93576 --- /dev/null +++ b/pool/shard006/C/0118842_add.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009 + * The President and Fellows of Harvard College. + * + * 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 University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 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 UNIVERSITY 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. + */ + +/* + * Simple program to add two numbers (given in as arguments). Used to + * test argument passing to child processes. + * + * Intended for the basic system calls assignment; this should work + * once execv() argument handling is implemented. + */ + +#include +#include +#include + +int +main(int argc, char *argv[]) +{ + int i, j; + + if (argc != 3) { + errx(1, "Usage: add num1 num2"); + } + + i = atoi(argv[1]); + j = atoi(argv[2]); + + printf("Answer: %d\n", i+j); + + return 0; +} diff --git a/pool/shard006/C/0118845_ext2VfsLib.c b/pool/shard006/C/0118845_ext2VfsLib.c new file mode 100644 index 0000000000000000000000000000000000000000..bad3c80476c2258614587ca64a6fd2778ec71f83 --- /dev/null +++ b/pool/shard006/C/0118845_ext2VfsLib.c @@ -0,0 +1,321 @@ +/****************************************************************************** + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * This file is part of Real VMX. + * Copyright (C) 2013 Surplus Users Ham Society + * + * Real VMX 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. + * + * Real VMX 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 Real VMX. If not, see . + */ + +/* ext2VfsLib.c - ext2 filesystem VFS operators library */ + +#include +#include +#include +#include +#include + +/* locals */ + +LOCAL int ext2fsVfsStart ( + struct mount * pMount, + int flags + ); + +LOCAL int ext2fsVfsUnmount ( + struct mount * pMount, + int flags + ); + +LOCAL int ext2fsVfsRoot ( + struct mount * pMount, + struct vnode ** ppVnode + ); + +LOCAL int ext2fsVfsStatVfs ( + struct mount * pMount, + struct statvfs * pStatVfs + ); + +LOCAL int ext2fsVfsVget ( + struct mount * pMount, + ino_t inode, + struct vnode ** ppVnode + ); + +LOCAL void ext2fsVfsInit ( + void + ); + +LOCAL void ext2fsVfsReInit ( + void + ); + +LOCAL void ext2fsVfsDone ( + void + ); + +LOCAL int ext2fsVfsTransStart ( + struct mount * pMount, + BOOL writeFlag + ); + +LOCAL int ext2fsVfsTransEnd ( + struct mount * pMount, + int error + ); + +/* globals */ + +const struct vfsops ext2fsVfsOps = +{ + "Ext2FS", + sizeof (EXT2FS_DEV), + sizeof (EXT2FS_INODE), + 1, + ext2fsVfsStart, + ext2fsVfsUnmount, + ext2fsVfsRoot, + ext2fsVfsStatVfs, + ext2fsVfsVget, + ext2fsVfsInit, + ext2fsVfsReInit, + ext2fsVfsDone, + ext2fsVfsTransStart, + ext2fsVfsTransEnd +}; + +/****************************************************************************** + * + * ext2fsMountCleanup - free resources allocated during mount + * + * RETURNS: N/A + */ + +LOCAL void ext2fsMountCleanup ( + EXT2FS_DEV * pFsDev + ) { + + if (pFsDev->bioSem != NULL) { + semDelete (pFsDev->bioSem); + pFsDev->bioSem = NULL; + } + + if (pFsDev->pScratchBlk != NULL) { + bio_free (pFsDev->pScratchBlk); + pFsDev->pScratchBlk = NULL; + } + + if (pFsDev->ext2fsVolDesc.pSuperBlk != NULL) { + free (pFsDev->ext2fsVolDesc.pSuperBlk); + pFsDev->ext2fsVolDesc.pSuperBlk = NULL; + } +} + +/****************************************************************************** + * + * ext2fsVfsStart - start ext2 filesystem + * + * RETURNS: OK on success, otherwise error + */ + +LOCAL int ext2fsVfsStart ( + struct mount * pMount, + int flags + ) { + EXT2FS_DEV * pFsDev; + int error; + + pFsDev = (EXT2FS_DEV *) pMount->mnt_data; + + error = ext2fsMount (pMount); + if (error != OK) { + ext2fsMountCleanup (pFsDev); + return (error); + } + + error = mountBufAlloc (pMount, EXT2FS_MIN_BUFFERS, + pFsDev->ext2fsVolDesc.blkSize); + if (error != OK) { + ext2fsMountCleanup (pFsDev); + return (error); + } + + return (error); +} + +/****************************************************************************** + * + * ext2fsVfsUnmount - umount ext2 filesystem + * + * RETURNS: OK on success, otherwise error + */ + +LOCAL int ext2fsVfsUnmount ( + struct mount * pMount, + int flags + ) { + EXT2FS_DEV * pFsDev; + + pFsDev = (EXT2FS_DEV *) pMount->mnt_data; + + ext2fsMountCleanup (pFsDev); + + pMount->mnt_data = NULL; + + return (OK); +} + +/****************************************************************************** + * + * ext2fsVfsVget - get vnode for given inode number + * + * RETURNS: OK on success, otherwise error + */ + +LOCAL int ext2fsVfsVget ( + struct mount * pMount, + ino_t inode, + struct vnode ** ppVnode + ) { + + return (vgetino (pMount, inode, &ext2fsOps, ppVnode)); +} + +/****************************************************************************** + * + * ext2fsVfsRoot - get root vnode + * + * RETURNS: OK on success, otherwise error + */ + +LOCAL int ext2fsVfsRoot ( + struct mount * pMount, + struct vnode ** ppVnode + ) { + + return (ext2fsVfsVget (pMount, EXT2FS_ROOT_INODE, ppVnode)); +} + +/****************************************************************************** + * + * ext2fsVfsStatVfs - get filesystem status + * + * RETURNS: OK on success; errno otherwise + */ + +LOCAL int ext2fsVfsStatVfs ( + struct mount * pMount, + struct statvfs * pStatVfs + ) { + + return (ext2fsStat (pMount, pStatVfs)); +} + +/****************************************************************************** + * + * ext2fsVfsInit - initialize + * + * RETURNS: N/A + */ + +LOCAL void ext2fsVfsInit ( + void + ) { + + return; +} + +/****************************************************************************** + * + * ext2fsVfsReInit - reinitialize + * + * RETURNS: N/A + */ + +LOCAL void ext2fsVfsReInit ( + void + ) { + + return; +} + +/****************************************************************************** + * + * ext2fsVfsDone - done + * + * RETURNS: N/A + */ + +LOCAL void ext2fsVfsDone ( + void + ) { + + return; +} + +/****************************************************************************** + * + * ext2fsVfsTransStart - start transaction for read or write + * + * RETURNS: OK on success, otherwise error + */ + +LOCAL int ext2fsVfsTransStart ( + struct mount * pMount, + BOOL writeFlag + ) { + EXT2FS_VOLUME_DESC * pVolDesc; + EXT2FS_DEV * pFsDev; + int error; + + if (writeFlag == TRUE) { + error = VN_EXLOCK (pMount->mnt_syncer); + } + else { + error = VN_SHLOCK (pMount->mnt_syncer); + } + + if (error == OK) { + pFsDev = (EXT2FS_DEV *) pMount->mnt_data; + pVolDesc = &pFsDev->ext2fsVolDesc; + pVolDesc->diskModified = FALSE; + } + + return (error); +} + +/****************************************************************************** + * + * ext2fsVfsTransEnd - end transaction for read or write + * + * + * RETURNS: OK or supplied error + */ + +LOCAL int ext2fsVfsTransEnd ( + struct mount * pMount, + int error + ) { + + if (error != OK) { + VN_UNLOCK (pMount->mnt_syncer); + return (error); + } + + VN_UNLOCK (pMount->mnt_syncer); + + return (OK); +} + diff --git a/pool/shard006/C/0118847_mdinfo.c b/pool/shard006/C/0118847_mdinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..cdd4f19650e3cdfffdb6a223d8d30bab2d681f5f --- /dev/null +++ b/pool/shard006/C/0118847_mdinfo.c @@ -0,0 +1,204 @@ +/* + * mdinfo - Displays information about + * md RAID arrays and their mount point + * + * Copyright (C) 2016 Alexander Mischke + * + * This file is part of mdinfo. + * + * mdinfo 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. + * + * mdinfo 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 mdinfo. If not, see . + * + * Author: Alexander Mischke + * Email: + */ + +#include +#include +#include +#include +#include +#include +#include "mdinfo.h" + + +int main(int argc, char *argv[]) { + + //todo: add param for specific array + + char mdstat[] = "mdstat"; + char mtab[] = "mounts"; + char fstab[] = "fstab"; + + int foobar; + + char line[80]; + char *ptr = NULL; + char *tmp = NULL; + char delim[2] = ":"; + const char devname[22]; + const char *uuid = NULL; + + FILE *fd; + fd = fopen(mdstat, "r"); + + if (fd == NULL) { + printf("Error: Could not open file %s", mdstat); + return 1; + } else { + + + /*******************************************/ + /* Getting number of arrays */ + /*******************************************/ + + int arr_count = 0; + int i = 0; + + while(fgets(line,80,fd) != NULL) { + + //todo: status, metadaten, member + + ptr = strtok(line, delim); + + if(ptr != NULL) { + tmp = truncate_whitespace(ptr, strlen(ptr)); + } + + if (strcmp(tmp, "Personalities") == 0) + continue; + + if (strcmp(tmp, "read_ahead") == 0) + continue; + + if (strcmp(tmp, "unused") == 0) + continue; + + if (tmp[0] == '\n') + continue; + + if (strlen(tmp) < 1) + continue; + + + if((strlen(tmp) > 0) && tmp[0] != '\n') { + arr_count++; + } + + } + + md_array cur_array[arr_count]; + + /*******************************************/ + /* Getting the array name and skipping the */ + /* "Personalities" */ + /* "read_ahead" */ + /* "unused" lines */ + /*******************************************/ + + rewind(fd); + char *p = NULL; + + while(fgets(line,80,fd) != NULL) { + + if(strstr(line, "raid") != NULL) { + + //Found a valid array line + + + p=strstr(line, "raid0"); + if(p != NULL) { + cur_array[i].personality = 0; + } + + p=strstr(line, "raid1"); + if(p != NULL) { + cur_array[i].personality = 1; + } + + p=strstr(line, "raid5"); + if(p != NULL) { + cur_array[i].personality = 5; + } + + p=strstr(line, "raid6"); + if(p != NULL) { + cur_array[i].personality = 6; + } + + p=strstr(line, "raid10"); + if(p != NULL) { + cur_array[i].personality = 10; + } + } + + ptr = strtok(line, delim); + + if(ptr != NULL) { + tmp = truncate_whitespace(ptr, strlen(ptr)); + } + + if (strcmp(tmp, "Personalities") == 0) + continue; + + if (strcmp(tmp, "read_ahead") == 0) + continue; + + if (strcmp(tmp, "unused") == 0) + continue; + + if (tmp[0] == '\n') + continue; + + if (strlen(tmp) < 1) + continue; + + snprintf(cur_array[i].name, sizeof cur_array[i].name, tmp); + snprintf(cur_array[i].devpath, sizeof cur_array[i].devpath, "%s%s", "/dev/", cur_array[i].name); + + uuid = map_uuid(cur_array[i].devpath); + + if((strlen(uuid) != 36)) { + uuid = "N/A"; + snprintf(cur_array[i].uuid, sizeof cur_array[i].uuid, uuid); + } else { + snprintf(cur_array[i].uuid, sizeof cur_array[i].uuid, uuid); + } + + + snprintf(cur_array[i].mnt, sizeof cur_array[i].mnt, get_mountpoint(cur_array[i].devpath, mtab)); + snprintf(cur_array[i].fstab, sizeof cur_array[i].fstab, + get_mountpoint(cur_array[i].devpath, fstab)); + cur_array[i].degraded = 0; + cur_array[i].member_count = 0; + cur_array[i].members = ""; + + i++; + + } + + + fclose(fd); + + for (i = 0; i < arr_count; i++) { + + print_array_information(cur_array, i); + printf("----------------------------------------------------------\n"); + } + +} + + return 0; + +} + diff --git a/pool/shard006/C/0118852_ctr.c b/pool/shard006/C/0118852_ctr.c new file mode 100644 index 0000000000000000000000000000000000000000..467db0f89ae5e456a41ac9d75dc18ada2ab83cd1 --- /dev/null +++ b/pool/shard006/C/0118852_ctr.c @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2002 Nikos Mavroyanopoulos + * + * This library is free software; you can redistribute it and/or modify it + * under the terms of the GNU Library General Public License as published + * by the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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 + +#if !defined(GPAC_DISABLE_MCRYPT) + +typedef struct ctr_buf { + u8* enc_counter; + u8* c_counter; + int c_counter_pos; + int blocksize; +} CTR_BUFFER; + +/* CTR MODE */ + +/* This function will add one to the given number (as a u8 string). + * has been reached. + */ +static void increase_counter( u8 *x, int x_size) { +register int i, y=0; + + for (i=x_size-1;i>=0;i--) { + y = 0; + if ( x[i] == 0xff) { + x[i] = 0; + y = 1; + } else x[i]++; + + if (y==0) break; + } + + return; +} + + +/* size holds the size of the IV (counter in this mode). + * This is the block size. + */ +GF_Err _init_mcrypt( void *buf, void *key, int lenofkey, void *IV, int size) +{ + ((CTR_BUFFER* )buf)->c_counter = ((CTR_BUFFER* )buf)->enc_counter = NULL; + +/* For ctr */ + ((CTR_BUFFER* )buf)->c_counter_pos = 0; + ((CTR_BUFFER* )buf)->blocksize = size; + + ((CTR_BUFFER* )buf)->c_counter = (u8 *)gf_malloc(size); + if (((CTR_BUFFER* )buf)->c_counter==NULL) goto freeall; + + ((CTR_BUFFER* )buf)->enc_counter = (u8 *)gf_malloc(size); + if (((CTR_BUFFER* )buf)->enc_counter==NULL) goto freeall; + + if (IV!=NULL) { + memcpy(((CTR_BUFFER* )buf)->enc_counter, IV, size); + memcpy(((CTR_BUFFER* )buf)->c_counter, IV, size); + } + +/* End ctr */ + + return GF_OK; + freeall: + gf_free(((CTR_BUFFER* )buf)->c_counter); + gf_free(((CTR_BUFFER* )buf)->enc_counter); + return GF_OUT_OF_MEM; +} + +GF_Err _mcrypt_set_state(void *_buf, void *IV, int size) +{ + CTR_BUFFER* buf = (CTR_BUFFER* )_buf; + ((CTR_BUFFER* )buf)->c_counter_pos = ((u8*)IV)[0]; + memcpy(((CTR_BUFFER* )buf)->c_counter, &((u8*)IV)[1], size-1); + memcpy(((CTR_BUFFER* )buf)->enc_counter, &((u8*)IV)[1], size-1); + + return GF_OK; +} + +GF_Err _mcrypt_get_state(void *buf, void *IV, int *size) +{ + if (*size < ((CTR_BUFFER* )buf)->blocksize + 1) { + *size = ((CTR_BUFFER* )buf)->blocksize + 1; + return GF_BAD_PARAM; + } + *size = ((CTR_BUFFER* )buf)->blocksize + 1; + + ((u8 *)IV)[0] = ((CTR_BUFFER* )buf)->c_counter_pos; + memcpy( & ((u8 *) IV)[1], ((CTR_BUFFER* )buf)->c_counter, ((CTR_BUFFER* )buf)->blocksize); + + return GF_OK; +} + + +void _end_mcrypt(void *buf) { + gf_free(((CTR_BUFFER* )buf)->c_counter); + gf_free(((CTR_BUFFER* )buf)->enc_counter); +} + +static GFINLINE +void xor_stuff( CTR_BUFFER *buf, void* akey, void (*func)(void*,void*), u8* plain, int blocksize, int xor_size) +{ + void (*_mcrypt_block_encrypt) (void *, void *); + + _mcrypt_block_encrypt = func; + + if (xor_size == blocksize) { + if (((CTR_BUFFER* )buf)->c_counter_pos == 0) { + + memcpy( ((CTR_BUFFER* )buf)->enc_counter, ((CTR_BUFFER* )buf)->c_counter, blocksize); + _mcrypt_block_encrypt(akey, ((CTR_BUFFER* )buf)->enc_counter); + + memxor( plain, ((CTR_BUFFER* )buf)->enc_counter, blocksize); + + increase_counter( ((CTR_BUFFER* )buf)->c_counter, blocksize); + + + } else { + int size = blocksize - ((CTR_BUFFER* )buf)->c_counter_pos; + + memxor( plain, &((CTR_BUFFER* )buf)->enc_counter[((CTR_BUFFER* )buf)->c_counter_pos], + size); + + increase_counter( ((CTR_BUFFER* )buf)->c_counter, blocksize); + + memcpy( ((CTR_BUFFER* )buf)->enc_counter, ((CTR_BUFFER* )buf)->c_counter, blocksize); + _mcrypt_block_encrypt(akey, ((CTR_BUFFER* )buf)->enc_counter); + + memxor( &plain[size], ((CTR_BUFFER* )buf)->enc_counter, + ((CTR_BUFFER* )buf)->c_counter_pos); + + /* ((CTR_BUFFER* )buf)->c_counter_pos remains the same */ + + } + } else { /* xor_size != blocksize */ + if (((CTR_BUFFER* )buf)->c_counter_pos == 0) { + memcpy( ((CTR_BUFFER* )buf)->enc_counter, ((CTR_BUFFER* )buf)->c_counter, blocksize); + _mcrypt_block_encrypt(akey, ((CTR_BUFFER* )buf)->enc_counter); + + memxor( plain, ((CTR_BUFFER* )buf)->enc_counter, xor_size); + ((CTR_BUFFER* )buf)->c_counter_pos = xor_size; + } else { + int size = blocksize - ((CTR_BUFFER* )buf)->c_counter_pos; + int min_size = size < xor_size ? size: xor_size; + + memxor( plain, &((CTR_BUFFER* )buf)->enc_counter[((CTR_BUFFER* )buf)->c_counter_pos], + min_size); + + ((CTR_BUFFER* )buf)->c_counter_pos += min_size; + + if (min_size >= xor_size) + return; + + increase_counter( ((CTR_BUFFER* )buf)->c_counter, blocksize); + + memcpy( ((CTR_BUFFER* )buf)->enc_counter, ((CTR_BUFFER* )buf)->c_counter, blocksize); + _mcrypt_block_encrypt(akey, ((CTR_BUFFER* )buf)->enc_counter); + + memxor( &plain[min_size], ((CTR_BUFFER* )buf)->enc_counter, + xor_size - min_size); + + ((CTR_BUFFER* )buf)->c_counter_pos = xor_size - min_size; + + } + + } + return; +} + +GF_Err _mcrypt(void * buf,void *plaintext, int len, int blocksize, void* akey, void (*func)(void*,void*), void (*func2)(void*,void*)) +{ /* plaintext can be any size */ + u8 *plain; + int dlen, j=0; + int modlen; + + dlen = len / blocksize; + plain = (u8 *)plaintext; + for (j = 0; j < dlen; j++) { + + xor_stuff((CTR_BUFFER*) buf, akey, func, plain, blocksize, blocksize); + + plain += blocksize; + +/* Put the new register */ + + } + modlen = len % blocksize; + if (modlen > 0) { + /* This is only usefull if encrypting the + * final block. Otherwise you'll not be + * able to decrypt it. + */ + + xor_stuff( (CTR_BUFFER*)buf, akey, func, plain, blocksize, modlen); + + } + + return GF_OK; +} + + +GF_Err _mdecrypt(void * buf,void *plaintext, int len, int blocksize, void* akey, void (*func)(void*,void*), void (*func2)(void*,void*)) +{ /* plaintext can be any size */ + return _mcrypt( buf, plaintext, len, blocksize, akey, func, func2); +} + +void gf_crypt_register_ctr(GF_Crypt *td) +{ + td->mode_name = "CTR"; + td->_init_mcrypt = _init_mcrypt; + td->_end_mcrypt = _end_mcrypt; + td->_mcrypt = _mcrypt; + td->_mdecrypt = _mdecrypt; + td->_mcrypt_get_state = _mcrypt_get_state; + td->_mcrypt_set_state = _mcrypt_set_state; + + td->has_IV = 1; + td->is_block_mode = 1; + td->is_block_algo_mode = 1; + td->mode_size = sizeof(CTR_BUFFER); + td->mode_version = 20020307; +} +#endif /*!defined(GPAC_DISABLE_MCRYPT)*/ diff --git a/pool/shard006/C/0118853_unittests.c b/pool/shard006/C/0118853_unittests.c new file mode 100644 index 0000000000000000000000000000000000000000..9e4be175d4266e7b59363336ac1507e55bb628f6 --- /dev/null +++ b/pool/shard006/C/0118853_unittests.c @@ -0,0 +1,45 @@ +#include +#include "../headers/octo.h" +#include +#include +int main( void ){ + + printf("Unit testing has begun\n"); + + /* len() test */ + char* testy = "BUNZ! "; + printf("The string \"%s\" is %d characters long.\n", testy, len(testy)); + if(len(testy) == 6) printf("TEST PASSED.\n"); + + /* strip() test */ + char buffer2[60] = " NARC! "; + char* testy2 = buffer2; + printf("The stripped string: \"%s\"\n", strip(testy2)); + + /* slice() test */ + char buffer3[60] = "STUFFY!"; + char* testy3 = buffer3; + printf("The sliced string: \"%s\"\n", slice(testy3, 1, 4, 0)); + + /* makeCopy() test */ + char buffer4[60] = "I AM THE walrus."; + char* testy4 = buffer4; + printf("A copy of the string: \"%s\"\n", makeCopy(testy4)); + + /* toUpperCase() test */ + char buffer5[60] = "I AM THE walrus."; + char* testy5 = buffer5; + printf("A uppercase version of the string: \"%s\"\n", toUpperCase(testy5)); + + /* toLowerCase() test */ + char buffer6[60] = "I AM THE walrus."; + char* testy6 = buffer6; + printf("A lowercase version of the string: \"%s\"\n", toLowerCase(testy6)); + + /* replaceBetween() test */ + char buffer7[60] = "The Hello World Code!"; + char* testy7 = replaceBetween(buffer7,5,8,"jjj"); + printf("replaceBetween() test: \"%s\"\n",testy7); + + return 0; +} diff --git a/pool/shard006/C/0118856_io.c b/pool/shard006/C/0118856_io.c new file mode 100644 index 0000000000000000000000000000000000000000..f883132aae94cad294983ba375e8e0e86721b618 --- /dev/null +++ b/pool/shard006/C/0118856_io.c @@ -0,0 +1,280 @@ +//***************************************************************************** +// +// io.c - I/O routines for the enet_io example application. +// +// 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-TM4C129EXL Firmware Package. +// +//***************************************************************************** +#include +#include +#include "inc/hw_ints.h" +#include "inc/hw_memmap.h" +#include "inc/hw_pwm.h" +#include "inc/hw_types.h" +#include "driverlib/gpio.h" +#include "driverlib/pwm.h" +#include "driverlib/sysctl.h" +#include "driverlib/timer.h" +#include "driverlib/interrupt.h" +#include "driverlib/rom.h" +#include "utils/ustdlib.h" +#include "io.h" + +//***************************************************************************** +// +// Hardware connection for the user LED. +// +//***************************************************************************** +#define LED_PORT_BASE GPIO_PORTN_BASE +#define LED_PIN GPIO_PIN_0 + +//***************************************************************************** +// +// Hardware connection for the animation LED. +// +//***************************************************************************** +#define LED_ANIM_PORT_BASE GPIO_PORTN_BASE +#define LED_ANIM_PIN GPIO_PIN_1 + +//***************************************************************************** +// +// The system clock speed. +// +//***************************************************************************** +extern uint32_t g_ui32SysClock; + +//***************************************************************************** +// +// The current speed of the on-screen animation expressed as a percentage. +// +//***************************************************************************** +volatile unsigned long g_ulAnimSpeed = 10; + +//***************************************************************************** +// +// Set the timer used to pace the animation. We scale the timer timeout such +// that a speed of 100% causes the timer to tick once every 20 mS (50Hz). +// +//***************************************************************************** +static void +io_set_timer(unsigned long ulSpeedPercent) +{ + unsigned long ulTimeout; + + // + // Turn the timer off while we are mucking with it. + // + ROM_TimerDisable(TIMER2_BASE, TIMER_A); + + // + // If the speed is non-zero, we reset the timeout. If it is zero, we + // just leave the timer disabled. + // + if(ulSpeedPercent) + { + // + // Set Timeout + // + ulTimeout = g_ui32SysClock / 50; + ulTimeout = (ulTimeout * 100 ) / ulSpeedPercent; + + ROM_TimerLoadSet(TIMER2_BASE, TIMER_A, ulTimeout); + ROM_TimerEnable(TIMER2_BASE, TIMER_A); + } +} + +//***************************************************************************** +// +// Initialize the IO used in this demo +// +//***************************************************************************** +void +io_init(void) +{ + // + // Configure Port N0 for as an output for the status LED. + // + ROM_GPIOPinTypeGPIOOutput(LED_PORT_BASE, LED_PIN); + + // + // Configure Port N0 for as an output for the animation LED. + // + ROM_GPIOPinTypeGPIOOutput(LED_ANIM_PORT_BASE, LED_ANIM_PIN); + + // + // Initialize LED to OFF (0) + // + ROM_GPIOPinWrite(LED_PORT_BASE, LED_PIN, 0); + + // + // Initialize animation LED to OFF (0) + // + ROM_GPIOPinWrite(LED_ANIM_PORT_BASE, LED_ANIM_PIN, 0); + + // + // Enable the peripherals used by this example. + // + ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER2); + + // + // Configure the timer used to pace the animation. + // + ROM_TimerConfigure(TIMER2_BASE, TIMER_CFG_PERIODIC); + + // + // Setup the interrupts for the timer timeouts. + // + ROM_IntEnable(INT_TIMER2A); + ROM_TimerIntEnable(TIMER2_BASE, TIMER_TIMA_TIMEOUT); + + // + // Set the timer for the current animation speed. This enables the + // timer as a side effect. + // + io_set_timer(g_ulAnimSpeed); +} + +//***************************************************************************** +// +// Set the status LED on or off. +// +//***************************************************************************** +void +io_set_led(bool bOn) +{ + // + // Turn the LED on or off as requested. + // + ROM_GPIOPinWrite(LED_PORT_BASE, LED_PIN, bOn ? LED_PIN : 0); +} + +//***************************************************************************** +// +// Return LED state +// +//***************************************************************************** +void +io_get_ledstate(char * pcBuf, int iBufLen) +{ + // + // Get the state of the LED + // + if(ROM_GPIOPinRead(LED_PORT_BASE, LED_PIN)) + { + usnprintf(pcBuf, iBufLen, "ON"); + } + else + { + usnprintf(pcBuf, iBufLen, "OFF"); + } + +} + +//***************************************************************************** +// +// Return LED state as an integer, 1 on, 0 off. +// +//***************************************************************************** +int +io_is_led_on(void) +{ + // + // Get the state of the LED + // + if(ROM_GPIOPinRead(LED_PORT_BASE, LED_PIN)) + { + return(true); + } + else + { + return(0); + } +} + +//***************************************************************************** +// +// Set the speed of the animation shown on the display. In this version, the +// speed is described as a decimal number encoded as an ASCII string. +// +//***************************************************************************** +void +io_set_animation_speed_string(char *pcBuf) +{ + unsigned long ulSpeed; + + // + // Parse the passed parameter as a decimal number. + // + ulSpeed = 0; + while((*pcBuf >= '0') && (*pcBuf <= '9')) + { + ulSpeed *= 10; + ulSpeed += (*pcBuf - '0'); + pcBuf++; + } + + // + // If the number is valid, set the new speed. + // + if(ulSpeed <= 100) + { + g_ulAnimSpeed = ulSpeed; + io_set_timer(g_ulAnimSpeed); + } +} + +//***************************************************************************** +// +// Set the speed of the animation shown on the display. +// +//***************************************************************************** +void +io_set_animation_speed(unsigned long ulSpeed) +{ + // + // If the number is valid, set the new speed. + // + if(ulSpeed <= 100) + { + g_ulAnimSpeed = ulSpeed; + io_set_timer(g_ulAnimSpeed); + } +} + +//***************************************************************************** +// +// Get the current animation speed as an ASCII string. +// +//***************************************************************************** +void +io_get_animation_speed_string(char *pcBuf, int iBufLen) +{ + usnprintf(pcBuf, iBufLen, "%d%%", g_ulAnimSpeed); +} + +//***************************************************************************** +// +// Get the current animation speed as a number. +// +//***************************************************************************** +unsigned long +io_get_animation_speed(void) +{ + return(g_ulAnimSpeed); +} diff --git a/pool/shard006/C/0118858_getnast.c b/pool/shard006/C/0118858_getnast.c new file mode 100644 index 0000000000000000000000000000000000000000..392df324e44b676c1a6495279048ded6db42667c --- /dev/null +++ b/pool/shard006/C/0118858_getnast.c @@ -0,0 +1,65 @@ +#include + +#include +#include +#include +#include + +char *progname; + +void +usage() +{ + fprintf(stderr, "Usage: %s [-s socket] query\n", progname); + exit(1); +} + +int +main(int argc, char *argv[]) +{ + char *sock_n; + nasth *nasthole; + nast_array *aa; + char ch; + int i, rc; + + progname = strrchr(argv[0], '/'); + if (!progname) + progname = argv[0]; + else + progname++; + + sock_n = NULL; + while ((ch = getopt(argc, argv, "s:")) != -1) { + switch (ch) { + case 's': + sock_n = optarg; + break; + default: + usage(); + /* NOTREACHED */ + } + } + + nasthole = nast_sphincter_new(sock_n); + if (nasthole == NULL) { + fprintf(stderr, "ERROR: Couldn't connect to nasthole.\n"); + return 2; + } + + rc = nast_get(nasthole, argv[argc-1]); + if (rc == -1) { + fprintf(stderr, "ERROR: Couldn't perform query: %s.\n", + nast_errmsg(nasthole)); + nast_sphincter_close(nasthole); + return 2; + } + + aa = nast_get_result(nasthole); + for (i = 0; i < aa->nitems; i++) + printf("Result[%d]: `%s'\n", i, aa->items[i]->strdata); + nast_free_result(aa); + + nast_sphincter_close(nasthole); + return 0; +} diff --git a/pool/shard006/C/0118867_ide-scan-pci.c b/pool/shard006/C/0118867_ide-scan-pci.c new file mode 100644 index 0000000000000000000000000000000000000000..acf874800ca4086803d6740d3df32ca38b732017 --- /dev/null +++ b/pool/shard006/C/0118867_ide-scan-pci.c @@ -0,0 +1,115 @@ +/* + * support for probing IDE PCI devices in the PCI bus order + * + * Copyright (c) 1998-2000 Andre Hedrick + * Copyright (c) 1995-1998 Mark Lord + * + * May be copied or modified under the terms of the GNU General Public License + */ + +#include +#include +#include +#include + +/* + * Module interfaces + */ + +static int pre_init = 1; /* Before first ordered IDE scan */ +static LIST_HEAD(ide_pci_drivers); + +/* + * __ide_pci_register_driver - attach IDE driver + * @driver: pci driver + * @module: owner module of the driver + * + * Registers a driver with the IDE layer. The IDE layer arranges that + * boot time setup is done in the expected device order and then + * hands the controllers off to the core PCI code to do the rest of + * the work. + * + * Returns are the same as for pci_register_driver + */ + +int __ide_pci_register_driver(struct pci_driver *driver, struct module *module, + const char *mod_name) +{ + if (!pre_init) + return __pci_register_driver(driver, module, mod_name); + driver->driver.owner = module; + list_add_tail(&driver->node, &ide_pci_drivers); + return 0; +} +EXPORT_SYMBOL_GPL(__ide_pci_register_driver); + +/** + * ide_scan_pcidev - find an IDE driver for a device + * @dev: PCI device to check + * + * Look for an IDE driver to handle the device we are considering. + * This is only used during boot up to get the ordering correct. After + * boot up the pci layer takes over the job. + */ + +static int __init ide_scan_pcidev(struct pci_dev *dev) +{ + struct list_head *l; + struct pci_driver *d; + int ret; + + list_for_each(l, &ide_pci_drivers) { + d = list_entry(l, struct pci_driver, node); + if (d->id_table) { + const struct pci_device_id *id = + pci_match_id(d->id_table, dev); + + if (id != NULL) { + pci_assign_irq(dev); + ret = d->probe(dev, id); + if (ret >= 0) { + dev->driver = d; + pci_dev_get(dev); + return 1; + } + } + } + } + return 0; +} + +/** + * ide_scan_pcibus - perform the initial IDE driver scan + * + * Perform the initial bus rather than driver ordered scan of the + * PCI drivers. After this all IDE pci handling becomes standard + * module ordering not traditionally ordered. + */ + +static int __init ide_scan_pcibus(void) +{ + struct pci_dev *dev = NULL; + struct pci_driver *d; + struct list_head *l, *n; + + pre_init = 0; + for_each_pci_dev(dev) + ide_scan_pcidev(dev); + + /* + * Hand the drivers over to the PCI layer now we + * are post init. + */ + + list_for_each_safe(l, n, &ide_pci_drivers) { + list_del(l); + d = list_entry(l, struct pci_driver, node); + if (__pci_register_driver(d, d->driver.owner, + d->driver.mod_name)) + printk(KERN_ERR "%s: failed to register %s driver\n", + __func__, d->driver.mod_name); + } + + return 0; +} +device_initcall(ide_scan_pcibus); diff --git a/pool/shard006/C/0118868_Cursor.c b/pool/shard006/C/0118868_Cursor.c new file mode 100644 index 0000000000000000000000000000000000000000..d1afe6d91c5c75e4130609c37822cfa6209f07ed --- /dev/null +++ b/pool/shard006/C/0118868_Cursor.c @@ -0,0 +1,102 @@ +/*Copyright (C) 2009 Careil Baptiste + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "dll.h" +#include "Cursor.h" +#include "Point.h" +#include + +static t_point_2d g_saved_cursor_pos = {0, 0}; + +/////////////////////////////////////////////////////////// +/// Permet de placer le curseur en début de ligne. +/////////////////////////////////////////////////////////// +void DLL_IMPEXP CSLP_GotoBeginOfLine() +{ + t_point_2d pos; + + getyx(stdscr, pos.y, pos.x); + move(pos.y, 0); +} + +/////////////////////////////////////////////////////////// +/// Permet de placer le curseur à la ligne précédente +/////////////////////////////////////////////////////////// +int DLL_IMPEXP CSLP_GotoPreviousLine() +{ + t_point_2d pos; + + getyx(stdscr, pos.y, pos.x); + return move(pos.y - 1, 0); +} + +/////////////////////////////////////////////////////////// +/// Permet de placer le curseur à la ligne suivante +/////////////////////////////////////////////////////////// +int DLL_IMPEXP CSLP_GotoNextLine() +{ + t_point_2d pos; + + getyx(stdscr, pos.y, pos.x); + return move(pos.y + 1, 0); +} + +/////////////////////////////////////////////////////////// +/// Permet de déplacer le curseur dans la direction voulue +/////////////////////////////////////////////////////////// +int DLL_IMPEXP CSLP_MoveCursor(CSLP_WAY way, unsigned int value) +{ + int ret_val; + t_point_2d pos; + + ret_val = ERR; + getyx(stdscr, pos.y, pos.x); + if (value != 0) + { + switch (way) + { + case FORWARD: + ret_val = move(pos.y, pos.x + value); break; + case BACKWARD: + ret_val = move(pos.y, pos.x - value); break; + case DOWN: + ret_val = move(pos.y + value, pos.x); break; + case UP: + ret_val = move(pos.y - value, pos.x); break; + default: + fputs("CSLP_MoveCursor : argument way invalid.\n", stderr); + } + } + return ret_val; +} + +/////////////////////////////////////////////////////////// +/// Permet de sauvegarder la position courrente du curseur +/////////////////////////////////////////////////////////// +void DLL_IMPEXP CSLP_SavePos() +{ + getyx(stdscr, g_saved_cursor_pos.y, g_saved_cursor_pos.x); +} + +/////////////////////////////////////////////////////////// +/// Permet de restaurer la position du curseur +/////////////////////////////////////////////////////////// +void DLL_IMPEXP CSLP_RestorePos() +{ + move(g_saved_cursor_pos.y, g_saved_cursor_pos.x); +} + diff --git a/pool/shard006/C/0118870_compat_time.c b/pool/shard006/C/0118870_compat_time.c new file mode 100644 index 0000000000000000000000000000000000000000..2bdf3ae1abf47c338d5a69763fdc345428a36c41 --- /dev/null +++ b/pool/shard006/C/0118870_compat_time.c @@ -0,0 +1,58 @@ +// compat_time addresses following compatibility issue: +// topic: high-resolution timestamps +// issue: is not available on Windows systems +// solution: provide a compatible version for Windows systems + +#include "compat_time.h" + +#ifdef _WIN32 + +#include +#include + +#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) +#define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 +#else +#define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL +#endif + +int gettimeofday(struct timeval *tv, void *tz) +{ + if (tz) + return -1; // we don't support TZ + + FILETIME ft; + unsigned __int64 t64; + GetSystemTimeAsFileTime(&ft); + t64 = (((unsigned __int64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; + t64 /= 10; // convert to microseconds + t64 -= DELTA_EPOCH_IN_MICROSECS; // convert file time to unix epoch + tv->tv_sec = (long)(t64 / 1000000UL); + tv->tv_usec = (long)(t64 % 1000000UL); + + return 0; +} + +#endif // _WIN32 + +int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) +{ + // Perform the carry for the later subtraction by updating y + if (x->tv_usec < y->tv_usec) { + int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; + y->tv_usec -= 1000000 * nsec; + y->tv_sec += nsec; + } + if (x->tv_usec - y->tv_usec > 1000000) { + int nsec = (x->tv_usec - y->tv_usec) / 1000000; + y->tv_usec += 1000000 * nsec; + y->tv_sec -= nsec; + } + + // Compute the time difference, tv_usec is certainly positive + result->tv_sec = x->tv_sec - y->tv_sec; + result->tv_usec = x->tv_usec - y->tv_usec; + + // Return 1 if result is negative + return x->tv_sec < y->tv_sec; +} diff --git a/pool/shard006/C/0118872_lapacke_dgetf2_work.c b/pool/shard006/C/0118872_lapacke_dgetf2_work.c new file mode 100644 index 0000000000000000000000000000000000000000..1d919089cc1fbf22b3847b5618a0a1cc783f9462 --- /dev/null +++ b/pool/shard006/C/0118872_lapacke_dgetf2_work.c @@ -0,0 +1,82 @@ +/***************************************************************************** + Copyright (c) 2011, 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: + + * 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. +***************************************************************************** +* Contents: Native middle-level C interface to LAPACK function dgetf2 +* Author: Intel Corporation +* Generated November, 2011 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_dgetf2_work( int matrix_order, lapack_int m, lapack_int n, + double* a, lapack_int lda, lapack_int* ipiv ) +{ + lapack_int info = 0; + if( matrix_order == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_dgetf2( &m, &n, a, &lda, ipiv, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_order == LAPACK_ROW_MAJOR ) { + lapack_int lda_t = MAX(1,m); + double* a_t = NULL; + /* Check leading dimension(s) */ + if( lda < n ) { + info = -5; + LAPACKE_xerbla( "LAPACKE_dgetf2_work", info ); + return info; + } + /* Allocate memory for temporary array(s) */ + a_t = (double*)LAPACKE_malloc( sizeof(double) * lda_t * MAX(1,n) ); + if( a_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + /* Transpose input matrices */ + LAPACKE_dge_trans( matrix_order, m, n, a, lda, a_t, lda_t ); + /* Call LAPACK function and adjust info */ + LAPACK_dgetf2( &m, &n, a_t, &lda_t, ipiv, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_dge_trans( LAPACK_COL_MAJOR, m, n, a_t, lda_t, a, lda ); + /* Release memory and exit */ + LAPACKE_free( a_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_dgetf2_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_dgetf2_work", info ); + } + return info; +} diff --git a/pool/shard006/C/0118874_main.c b/pool/shard006/C/0118874_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c5ef45e7452b900f98ea247f5304b8bdf63bcf38 --- /dev/null +++ b/pool/shard006/C/0118874_main.c @@ -0,0 +1,316 @@ +/* + FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS 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 >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS 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. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* + * Creates all the demo application tasks, then starts the scheduler. The WEB + * documentation provides more details of the demo application tasks. + * + * Main. c also creates a task called "Check". This only executes every three + * seconds but has the highest priority so is guaranteed to get processor time. + * Its main function is to check that all the other tasks are still operational. + * Each task that does not flash an LED maintains a unique count that is + * incremented each time the task successfully completes its function. Should + * any error occur within such a task the count is permanently halted. The + * check task inspects the count of each task to ensure it has changed since + * the last time the check task executed. If all the count variables have + * changed all the tasks are still executing error free, and the check task + * toggles an LED. Should any task contain an error at any time the LED toggle + * will stop. + * + * The LED flash and communications test tasks do not maintain a count. + */ + +/* +Changes from V1.2.0 + + + Changed the baud rate for the serial test from 19200 to 57600. + +Changes from V1.2.3 + + + The integer and comtest tasks are now used when the cooperative scheduler + is being used. Previously they were only used with the preemptive + scheduler. + +Changes from V1.2.5 + + + Set the baud rate to 38400. This has a smaller error percentage with an + 8MHz clock (according to the manual). + +Changes from V2.0.0 + + + Delay periods are now specified using variables and constants of + TickType_t rather than unsigned long. + +Changes from V2.2.0 + + + File can now be built using either the IAR or WinAVR compiler. + +Changes from V2.6.1 + + + The IAR and WinAVR AVR ports are now maintained separately. + +Changes from V4.0.5 + + + Modified to demonstrate the use of co-routines. +*/ + +#include +#include + +#ifdef GCC_MEGA_AVR + /* EEPROM routines used only with the WinAVR compiler. */ + #include +#endif + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "croutine.h" + +/* Demo file headers. */ +#include "PollQ.h" +#include "integer.h" +#include "serial.h" +#include "comtest.h" +#include "crflash.h" +#include "print.h" +#include "partest.h" +#include "regtest.h" + +/* Priority definitions for most of the tasks in the demo application. Some +tasks just use the idle priority. */ +#define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 3 ) + +/* Baud rate used by the serial port tasks. */ +#define mainCOM_TEST_BAUD_RATE ( ( unsigned long ) 38400 ) + +/* LED used by the serial port tasks. This is toggled on each character Tx, +and mainCOM_TEST_LED + 1 is toggles on each character Rx. */ +#define mainCOM_TEST_LED ( 4 ) + +/* LED that is toggled by the check task. The check task periodically checks +that all the other tasks are operating without error. If no errors are found +the LED is toggled. If an error is found at any time the LED is never toggles +again. */ +#define mainCHECK_TASK_LED ( 7 ) + +/* The period between executions of the check task. */ +#define mainCHECK_PERIOD ( ( TickType_t ) 3000 / portTICK_PERIOD_MS ) + +/* An address in the EEPROM used to count resets. This is used to check that +the demo application is not unexpectedly resetting. */ +#define mainRESET_COUNT_ADDRESS ( ( void * ) 0x50 ) + +/* The number of coroutines to create. */ +#define mainNUM_FLASH_COROUTINES ( 3 ) + +/* + * 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. + * Flashes an LED if everything is okay. + */ +static void prvCheckOtherTasksAreStillRunning( void ); + +/* + * Called on boot to increment a count stored in the EEPROM. This is used to + * ensure the CPU does not reset unexpectedly. + */ +static void prvIncrementResetCount( void ); + +/* + * Idle hook is used to scheduler co-routines. + */ +void vApplicationIdleHook( void ); + +short main( void ) +{ + prvIncrementResetCount(); + + /* Setup the LED's for output. */ + vParTestInitialise(); + + /* Create the standard demo tasks. */ + vStartIntegerMathTasks( tskIDLE_PRIORITY ); + vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainCOM_TEST_BAUD_RATE, mainCOM_TEST_LED ); + vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY ); + vStartRegTestTasks(); + + /* Create the tasks defined within this file. */ + xTaskCreate( vErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL ); + + /* Create the co-routines that flash the LED's. */ + vStartFlashCoRoutines( mainNUM_FLASH_COROUTINES ); + + /* In this port, to use preemptive scheduler define configUSE_PREEMPTION + as 1 in portmacro.h. To use the cooperative scheduler define + configUSE_PREEMPTION as 0. */ + vTaskStartScheduler(); + + return 0; +} +/*-----------------------------------------------------------*/ + +static void vErrorChecks( void *pvParameters ) +{ +static volatile unsigned long ulDummyVariable = 3UL; + + /* The parameters are not used. */ + ( void ) pvParameters; + + /* Cycle for ever, delaying then checking all the other tasks are still + operating without error. */ + for( ;; ) + { + vTaskDelay( mainCHECK_PERIOD ); + + /* Perform a bit of 32bit maths to ensure the registers used by the + integer tasks get some exercise. The result here is not important - + see the demo application documentation for more info. */ + ulDummyVariable *= 3; + + prvCheckOtherTasksAreStillRunning(); + } +} +/*-----------------------------------------------------------*/ + +static void prvCheckOtherTasksAreStillRunning( void ) +{ +static portBASE_TYPE xErrorHasOccurred = pdFALSE; + + if( xAreIntegerMathsTaskStillRunning() != pdTRUE ) + { + xErrorHasOccurred = pdTRUE; + } + + if( xAreComTestTasksStillRunning() != pdTRUE ) + { + xErrorHasOccurred = pdTRUE; + } + + if( xArePollingQueuesStillRunning() != pdTRUE ) + { + xErrorHasOccurred = pdTRUE; + } + + if( xAreRegTestTasksStillRunning() != pdTRUE ) + { + xErrorHasOccurred = pdTRUE; + } + + if( xErrorHasOccurred == pdFALSE ) + { + /* Toggle the LED if everything is okay so we know if an error occurs even if not + using console IO. */ + vParTestToggleLED( mainCHECK_TASK_LED ); + } +} +/*-----------------------------------------------------------*/ + +static void prvIncrementResetCount( void ) +{ +unsigned char ucCount; +const unsigned char ucReadBit = ( unsigned char ) 0x01; +const unsigned char ucWrite1 = ( unsigned char ) 0x04; +const unsigned char ucWrite2 = ( unsigned char ) 0x02; + + /* Increment the EEPROM value at 0x00. + + Setup the EEPROM address. */ + EEARH = 0x00; + EEARL = 0x00; + + /* Set the read enable bit. */ + EECR |= ucReadBit; + + /* Wait for the read. */ + while( EECR & ucReadBit ); + + /* The byte is ready. */ + ucCount = EEDR; + + /* Increment the reset count, then write the byte back. */ + ucCount++; + EEDR = ucCount; + EECR = ucWrite1; + EECR = ( ucWrite1 | ucWrite2 ); +} +/*-----------------------------------------------------------*/ + +void vApplicationIdleHook( void ) +{ + vCoRoutineSchedule(); +} + diff --git a/pool/shard006/C/0118880_ti-des3.c b/pool/shard006/C/0118880_ti-des3.c new file mode 100644 index 0000000000000000000000000000000000000000..2927a1b8969a6f0768200cae50bfb5ddb8b50668 --- /dev/null +++ b/pool/shard006/C/0118880_ti-des3.c @@ -0,0 +1,187 @@ +/* port/ti/ti-des.c + * + * Copyright (C) 2006-2015 wolfSSL Inc. + * + * This file is part of wolfSSL. (formerly known as CyaSSL) + * + * wolfSSL 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. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + +#ifndef NO_DES + +#if defined(WOLFSSL_TI_CRYPT) +#include +#include + +#include +#include +#include + +#include "inc/hw_des.h" +#include "inc/hw_memmap.h" +#include "inc/hw_ints.h" +#include "driverlib/des.h" +#include "driverlib/sysctl.h" +#include "driverlib/rom_map.h" +#include "driverlib/rom.h" + +static int DesSetIV(Des* des, const byte* iv, int tri) +{ + if (des == NULL) + return BAD_FUNC_ARG; + + if (iv) + XMEMCPY(des->reg, iv, tri == DES_CFG_TRIPLE ? DES3_IVLEN : DES_IVLEN); + else + XMEMSET(des->reg, 0, tri == DES_CFG_TRIPLE ? DES3_IVLEN : DES_IVLEN); + + return 0; +} + +static int DesSetKey(Des* des, const byte* key, const byte* iv,int dir, int tri) +{ + if(!wolfSSL_TI_CCMInit())return 1 ; + if ((des == NULL) || (key == NULL) || (iv == NULL)) + return BAD_FUNC_ARG; + if(!((dir == DES_ENCRYPTION) || (dir == DES_DECRYPTION))) + return BAD_FUNC_ARG; + + XMEMCPY(des->key, key, tri == DES_CFG_SINGLE ? DES_KEYLEN : DES3_KEYLEN) ; + return DesSetIV(des, iv, tri); +} + +static int DesCbcAlign16(Des* des, byte* out, const byte* in, word32 sz, word32 dir, word32 tri) +{ + + wolfSSL_TI_lockCCM() ; + ROM_DESReset(DES_BASE); + ROM_DESConfigSet(DES_BASE, (dir | DES_CFG_MODE_CBC | tri)); + ROM_DESIVSet(DES_BASE, (uint32_t*)des->reg); + ROM_DESKeySet(DES_BASE,(uint32_t*)des->key); + if(dir == DES_CFG_DIR_DECRYPT) + /* if input and output same will overwrite input iv */ + XMEMCPY(des->tmp, in + sz - DES_BLOCK_SIZE, DES_BLOCK_SIZE); + ROM_DESDataProcess(DES_BASE, (uint32_t *)in, (uint32_t *)out, sz); + wolfSSL_TI_unlockCCM() ; + + /* store iv for next call */ + if(dir == DES_CFG_DIR_ENCRYPT) + XMEMCPY(des->reg, out + sz - DES_BLOCK_SIZE, DES_BLOCK_SIZE); + else + XMEMCPY(des->reg, des->tmp, DES_BLOCK_SIZE); + + return 0 ; +} + +#define IS_ALIGN16(p) (((unsigned int)(p)&0xf) == 0) + +static int DesCbc(Des* des, byte* out, const byte* in, word32 sz, word32 dir, word32 tri) +{ + const byte * in_p ; byte * out_p ; + word32 size ; + #define TI_BUFFSIZE 1024 + byte buff[TI_BUFFSIZE] ; + if ((des == NULL) || (in == NULL) || (out == NULL)) + return BAD_FUNC_ARG; + if(sz % DES_BLOCK_SIZE) + return BAD_FUNC_ARG; + + while(sz > 0) { + size = sz ; in_p = in ; out_p = out ; + if(!IS_ALIGN16(in)){ + size = sz>TI_BUFFSIZE ? TI_BUFFSIZE : sz ; + XMEMCPY(buff, in, size) ; + in_p = (const byte *)buff ; + } + if(!IS_ALIGN16(out)){ + size = sz>TI_BUFFSIZE ? TI_BUFFSIZE : sz ; + out_p = (byte *)buff ; + } + + DesCbcAlign16(des, out_p, in_p, size, dir, tri) ; + + if(!IS_ALIGN16(out)){ + XMEMCPY(out, buff, size) ; + } + sz -= size ; in += size ; out += size ; + } + return 0 ; +} + +WOLFSSL_API int wc_Des_SetKey(Des* des, const byte* key, const byte* iv,int dir) +{ + return DesSetKey(des, key, iv, dir, DES_CFG_SINGLE) ; +} + +WOLFSSL_API void wc_Des_SetIV(Des* des, const byte* iv) +{ + DesSetIV(des, iv, DES_CFG_SINGLE) ; +} + +WOLFSSL_API int wc_Des3_SetKey(Des3* des, const byte* key, const byte* iv,int dir) +{ + return DesSetKey((Des *)des, key, iv, dir, DES_CFG_TRIPLE) ; +} + +WOLFSSL_API int wc_Des3_SetIV(Des3* des, const byte* iv) +{ + return DesSetIV((Des *)des, iv, DES_CFG_TRIPLE) ; +} + + +WOLFSSL_API int wc_Des_CbcEncrypt(Des* des, byte* out, const byte* in, word32 sz) +{ + return DesCbc(des, out, in, sz, DES_CFG_DIR_ENCRYPT, DES_CFG_SINGLE) ; +} + +WOLFSSL_API int wc_Des_CbcDecrypt(Des* des, byte* out, const byte* in, word32 sz) +{ + return DesCbc(des, out, in, sz, DES_CFG_DIR_DECRYPT, DES_CFG_SINGLE) ; +} + +WOLFSSL_API int wc_Des_CbcDecryptWithKey(byte* out, const byte* in, word32 sz, + const byte* key, const byte* iv) +{ + (void)out; (void)in; (void)sz; (void)key; (void)iv ; + return -1 ; +} + +WOLFSSL_API int wc_Des3_CbcEncrypt(Des3* des, byte* out, const byte* in, word32 sz) +{ + return DesCbc((Des *)des, out, in, sz, DES_CFG_DIR_ENCRYPT, DES_CFG_TRIPLE) ; +} + +WOLFSSL_API int wc_Des3_CbcDecrypt(Des3* des, byte* out, const byte* in, word32 sz) +{ + return DesCbc((Des *)des, out, in, sz, DES_CFG_DIR_DECRYPT, DES_CFG_TRIPLE) ; +} + +WOLFSSL_API int wc_Des3_CbcDecryptWithKey(byte* out, const byte* in, word32 sz, + const byte* key, const byte* iv) +{ + (void)out; (void)in; (void)sz; (void)key; (void)iv ; + return -1 ; + } + + +#endif /* WOLFSSL_TI_CRYPT */ + +#endif /* NO_DES */ diff --git a/pool/shard006/C/0118885_malloc.c b/pool/shard006/C/0118885_malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..5ca425f6023c2f5ed7ac12c47ec41bc72198a408 --- /dev/null +++ b/pool/shard006/C/0118885_malloc.c @@ -0,0 +1,126 @@ +/* + * Author: Andrew Wesie + * + * Copyright (c) 2014 Kaprica Security, Inc. + * + * 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 +#include + +#include "malloc_internal.h" + +static int allocate_span() +{ + void *mem; + if (allocate(SPAN_SIZE << 1, 0, &mem) != 0) + return 1; + + intptr_t span = ((intptr_t)mem + SPAN_SIZE-1) & ~(SPAN_SIZE-1); + if (span - (intptr_t)mem) + deallocate(mem, span - (intptr_t)mem); + deallocate((void *)(span + SPAN_SIZE), ((intptr_t)mem + (SPAN_SIZE << 1)) - (span + SPAN_SIZE)); + + free_block_t *block = (free_block_t *)span; + block->hdr.size = SPAN_SIZE; + block->hdr.free = 1; + block->hdr.cgc_mmap = 0; + block->next = g_malloc.free_list[NUM_BUCKETS-1]; + block->prev = NULL; + g_malloc.free_list[NUM_BUCKETS-1] = block; + return 0; +} + +static free_block_t *pop_block(int i) +{ + free_block_t *blk = g_malloc.free_list[i]; + /* remove from current list */ + if (blk->next != NULL) + blk->next->prev = blk->prev; + if (blk->prev != NULL) + blk->prev->next = blk->next; + else + g_malloc.free_list[i] = blk->next; + + blk->next = NULL; + blk->prev = NULL; + return blk; +} + +void *malloc(size_t size) +{ + size_t min_size = size + OVERHEAD_BYTES; + + if (min_size >= MAX_ALLOC) + { + void *ret; + if (allocate(min_size, 0, &ret) != 0) + return NULL; + block_t *block = (block_t *)ret; + block->free = 0; + block->cgc_mmap = 1; + block->size = min_size; + return (void *)((intptr_t)ret + OVERHEAD_BYTES); + } + + /* use buddy allocator */ + int order; + for (order = 0; min_size > (MIN_ALLOC << order); order++) ; + + /* find first free bucket */ + int i; + for (i = order; i < NUM_BUCKETS && g_malloc.free_list[i] == NULL; i++) ; + + if (i == NUM_BUCKETS) + { + /* allocate new span */ + if (allocate_span() == 0) + i = NUM_BUCKETS-1; + else + return NULL; + } + + /* split block until it is the minimum size */ + for (; i > order; i--) + { + free_block_t *blk = pop_block(i); + + /* split block */ + blk->hdr.size >>= 1; + free_block_t *blk2 = (free_block_t *)((intptr_t)blk ^ blk->hdr.size); + *blk2 = *blk; + + /* add both to next list */ + blk->prev = NULL; + blk->next = blk2; + blk2->prev = blk; + blk2->next = g_malloc.free_list[i-1]; + if (blk2->next) + blk2->next->prev = blk2; + g_malloc.free_list[i-1] = blk; + } + + /* we are now guaranteed that g_malloc.free_list[order] != NULL */ + free_block_t *blk = pop_block(order); + blk->hdr.free = 0; + + //printf("malloc(%d) = %08X\n", size, ((intptr_t)blk + OVERHEAD_BYTES)); + return (void *)((intptr_t)blk + OVERHEAD_BYTES); +} diff --git a/pool/shard006/C/0118888_gimpregionselectoptions.c b/pool/shard006/C/0118888_gimpregionselectoptions.c new file mode 100644 index 0000000000000000000000000000000000000000..74f97fc067fd52aa792468af70e05673e11635a8 --- /dev/null +++ b/pool/shard006/C/0118888_gimpregionselectoptions.c @@ -0,0 +1,232 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995-1999 Spencer Kimball and Peter Mattis + * + * 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 . + */ + +#include "config.h" + +#include + +#include "libgimpconfig/gimpconfig.h" +#include "libgimpwidgets/gimpwidgets.h" + +#include "tools-types.h" + +#include "config/gimpcoreconfig.h" + +#include "core/gimp.h" +#include "core/gimptoolinfo.h" + +#include "widgets/gimppropwidgets.h" +#include "widgets/gimpwidgets-utils.h" + +#include "gimpregionselectoptions.h" +#include "gimpregionselecttool.h" + +#include "gimp-intl.h" + + +enum +{ + PROP_0, + PROP_SELECT_TRANSPARENT, + PROP_SAMPLE_MERGED, + PROP_THRESHOLD, + PROP_SELECT_CRITERION +}; + + +static void gimp_region_select_options_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec); +static void gimp_region_select_options_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec); + +static void gimp_region_select_options_reset (GimpToolOptions *tool_options); + + +G_DEFINE_TYPE (GimpRegionSelectOptions, gimp_region_select_options, + GIMP_TYPE_SELECTION_OPTIONS) + +#define parent_class gimp_region_select_options_parent_class + + +static void +gimp_region_select_options_class_init (GimpRegionSelectOptionsClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GimpToolOptionsClass *options_class = GIMP_TOOL_OPTIONS_CLASS (klass); + + object_class->set_property = gimp_region_select_options_set_property; + object_class->get_property = gimp_region_select_options_get_property; + + options_class->reset = gimp_region_select_options_reset; + + GIMP_CONFIG_INSTALL_PROP_BOOLEAN (object_class, PROP_SELECT_TRANSPARENT, + "select-transparent", + N_("Allow completely transparent regions " + "to be selected"), + TRUE, + GIMP_PARAM_STATIC_STRINGS); + + GIMP_CONFIG_INSTALL_PROP_BOOLEAN (object_class, PROP_SAMPLE_MERGED, + "sample-merged", + N_("Base selection on all visible layers"), + FALSE, + GIMP_PARAM_STATIC_STRINGS); + + GIMP_CONFIG_INSTALL_PROP_DOUBLE (object_class, PROP_THRESHOLD, + "threshold", + N_("Maximum color difference"), + 0.0, 255.0, 15.0, + GIMP_PARAM_STATIC_STRINGS); + + GIMP_CONFIG_INSTALL_PROP_ENUM (object_class, PROP_SELECT_CRITERION, + "select-criterion", NULL, + GIMP_TYPE_SELECT_CRITERION, + GIMP_SELECT_CRITERION_COMPOSITE, + GIMP_PARAM_STATIC_STRINGS); +} + +static void +gimp_region_select_options_init (GimpRegionSelectOptions *options) +{ +} + +static void +gimp_region_select_options_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + GimpRegionSelectOptions *options = GIMP_REGION_SELECT_OPTIONS (object); + + switch (property_id) + { + case PROP_SELECT_TRANSPARENT: + options->select_transparent = g_value_get_boolean (value); + break; + + case PROP_SAMPLE_MERGED: + options->sample_merged = g_value_get_boolean (value); + break; + + case PROP_THRESHOLD: + options->threshold = g_value_get_double (value); + break; + + case PROP_SELECT_CRITERION: + options->select_criterion = g_value_get_enum (value); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gimp_region_select_options_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + GimpRegionSelectOptions *options = GIMP_REGION_SELECT_OPTIONS (object); + + switch (property_id) + { + case PROP_SELECT_TRANSPARENT: + g_value_set_boolean (value, options->select_transparent); + break; + + case PROP_SAMPLE_MERGED: + g_value_set_boolean (value, options->sample_merged); + break; + + case PROP_THRESHOLD: + g_value_set_double (value, options->threshold); + break; + + case PROP_SELECT_CRITERION: + g_value_set_enum (value, options->select_criterion); + break; + + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +gimp_region_select_options_reset (GimpToolOptions *tool_options) +{ + GParamSpec *pspec; + + pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (tool_options), + "threshold"); + + if (pspec) + G_PARAM_SPEC_DOUBLE (pspec)->default_value = + tool_options->tool_info->gimp->config->default_threshold; + + GIMP_TOOL_OPTIONS_CLASS (parent_class)->reset (tool_options); +} + +GtkWidget * +gimp_region_select_options_gui (GimpToolOptions *tool_options) +{ + GObject *config = G_OBJECT (tool_options); + GtkWidget *vbox = gimp_selection_options_gui (tool_options); + GtkWidget *button; + GtkWidget *table; + GtkWidget *scale; + GtkWidget *combo; + + /* the select transparent areas toggle */ + button = gimp_prop_check_button_new (config, "select-transparent", + _("Select transparent areas")); + gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + /* the sample merged toggle */ + button = gimp_prop_check_button_new (config, "sample-merged", + _("Sample merged")); + gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); + gtk_widget_show (button); + + /* the threshold scale */ + scale = gimp_prop_spin_scale_new (config, "threshold", + _("Threshold"), + 1.0, 16.0, 1); + gtk_box_pack_start (GTK_BOX (vbox), scale, FALSE, FALSE, 0); + gtk_widget_show (scale); + + /* the select criterion combo */ + table = gtk_table_new (1, 3, FALSE); + gtk_table_set_col_spacings (GTK_TABLE (table), 2); + gtk_table_set_row_spacings (GTK_TABLE (table), 2); + gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, FALSE, 0); + gtk_widget_show (table); + + combo = gimp_prop_enum_combo_box_new (config, "select-criterion", 0, 0); + gimp_table_attach_aligned (GTK_TABLE (table), 0, 1, + _("Select by:"), 0.0, 0.5, + combo, 2, FALSE); + + return vbox; +} diff --git a/pool/shard006/C/0118889_eq_td.c b/pool/shard006/C/0118889_eq_td.c new file mode 100644 index 0000000000000000000000000000000000000000..ed2d548f45daf47c3f08e03dacca318696ea4cd7 --- /dev/null +++ b/pool/shard006/C/0118889_eq_td.c @@ -0,0 +1,46 @@ +/* Copyright (C) 2007 Free Software Foundation, Inc. + +This file is part of GCC. + +GCC is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free +Software Foundation; either version 2, or (at your option) any later +version. + +In addition to the permissions in the GNU General Public License, the +Free Software Foundation gives you unlimited permission to link the +compiled version of this file into combinations with other programs, +and to distribute those combinations without any restriction coming +from the use of this file. (The General Public License restrictions +do apply in other respects; for example, they cover modification of +the file, and distribution when not linked into a combine +executable.) + +GCC is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +You should have received a copy of the GNU General Public License +along with GCC; see the file COPYING. If not, write to the Free +Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301, USA. */ + +#include "bid_conf.h" +#include "bid_functions.h" +#include "bid_gcc_intrinsics.h" + +CMPtype +__bid_eqtd2 (_Decimal128 x, _Decimal128 y) { + CMPtype res; + union decimal128 ux, uy; + + ux.d = x; + uy.d = y; + res = __bid128_quiet_equal (ux.i, uy.i); + if (res == 0) + res = 1; + else + res = 0; + return (res); +} diff --git a/pool/shard006/C/0118895_transports_icons.c b/pool/shard006/C/0118895_transports_icons.c new file mode 100644 index 0000000000000000000000000000000000000000..9b9981f4f4f142b4e8bece14ebed565e51c37935 --- /dev/null +++ b/pool/shard006/C/0118895_transports_icons.c @@ -0,0 +1,110 @@ +#include +#include "string_util.h" +#include "main.h" +#include "transports_icons.h" + +extern const char PATH_TO_PIC[]; +const char transports_img_folder[] = "transports\\"; +static TransportIconsList * til_top = NULL; + +/* + Çàãðóçèòü èç ïàïêè "..\img\transports\" âñå ïàïêè ñ èêîíêàìè òðàíñïîðòîâ. +*/ +void LoadTranspostIconsList() +{ + DIR_ENTRY de; + TransportIconsList * til; + unsigned int err = 0; + char * tr_folder = malloc(strlen(PATH_TO_PIC) + 32); + strcpy(tr_folder, PATH_TO_PIC); + strcat(tr_folder, transports_img_folder); + if (isdir(tr_folder, &err)) // Ïðîâåðÿåì åñòü ëè âîîáùå ïàïêà "transports" + { + strcat(tr_folder, "*.*"); + if (FindFirstFile(&de, tr_folder, &err)) + { + do + { + if (de.file_attr & FA_DIRECTORY) // Íàøëè ïàïêó + { + til = malloc(sizeof(TransportIconsList)); // Ñîçäàåì íîâûé ñïèñîê + strcpy(til->name, de.file_name); // Êîïèðóåì èìÿ ïàïêè â ñïèñîê + til->next = NULL; + if (til_top) + { + TransportIconsList * til_r = (TransportIconsList *)&til_top; + TransportIconsList * til_t = til_top; + while(stricmp(til_t->name, til->name) < 0) + { + til_r = til_t; + til_t = til_t->next; + if (!til_t) break; + } + til->next = til_t; + til_r->next = til; + } + else + til_top = til; + } + } + while(FindNextFile(&de, &err)); + } + FindClose(&de, &err); + } + mfree(tr_folder); +} + +void FreeTranspostIconsList() +{ + while(til_top) + { + TransportIconsList * til = til_top; + til_top = til_top->next; + mfree(til); + } +} + +/* + Äîáàâèòü â ïóòü ê èêîíêå ïàïêó ñ èêîíêàìè òðàíñïîðòà. + Èìÿ ïàïêè áåðåì èç æèäà êîíòàêòà òðàíñïîðòà (xxxx@icq.jabber.ru -> icq) +*/ +void GetTransportIconsPath(char * path_to_pic, TRESOURCE * resEx) +{ + int len = 0; // Äëèíà èìåíè òðàíñïîðòà + char * tr_name = NULL; // Èìÿ òðàíñïîðòà + TransportIconsList * til = til_top; + if (!til) return; + if(resEx->entry_type == T_TRANSPORT) // Ñàì òðàíñïîðò + { + while(resEx->full_name[len] != '.') // Ïîêà íå äîøëè äî òî÷êè + len ++; + tr_name = malloc(len + 1); + strncpy(tr_name, resEx->full_name, len); // Êîïèðóåì èìÿ òðàíñïîðòà + tr_name[len] = 0; + } + else + { + char * tmp = strrchr(resEx->full_name, '@'); // Êîíòàêò èç òðàíñïîðòà + if (tmp) + { + while(tmp[len + 1] != '.') + len ++; + tr_name = malloc(len + 1); + strncpy(tr_name, tmp + 1, len); + tr_name[len] = 0; + } + } + if (!tr_name) return; // Íàø êîíòàêò íå ÿâëÿåòñÿ òðàíñïîðòîì. Çàêðûâàåì ëàâî÷êó ;) + while(til) // Èùåì â ñïèñêå íàøó ïàïêó + { + if (!stricmp(til->name, tr_name)) // Íàøëè! + { + strcat(path_to_pic, transports_img_folder); // Äîáàâëÿåì ïàïêó "transports" â ïóòü ê èêîíêå + strcat(path_to_pic, til->name); // Äîáàâëÿåì íàøó ïàïêó â ïóòü ê èêîíêå + strcat(path_to_pic, "\\"); + break; + } + til = til->next; + } + mfree(tr_name); +} diff --git a/pool/shard006/C/0118900_item_del.c b/pool/shard006/C/0118900_item_del.c new file mode 100644 index 0000000000000000000000000000000000000000..b8e2ce88b20384eee7f4cf7999ff3a9f77c7e2ca --- /dev/null +++ b/pool/shard006/C/0118900_item_del.c @@ -0,0 +1,58 @@ +// gcc item_del.c -o item_del.cgi utils/get_cookie.o utils/base64.o -lcrypto +#include +#include +#include + + +// EXTERNAL +extern int getCookie(char *cookie); +extern int base64_decode(char *source, char *dest, char *scramble_string); +extern int curl (char *url); +// EXTERNAL + + +int main(void) +{ +char cookie[128]; + +memset(cookie,0,128); +if (getCookie(cookie)) return 0; +// ... + +char item[64]; +char *data=NULL; +int len; + +data = getenv("QUERY_STRING"); +if (!data) return 0; + +len=strlen(data); +if (len>64) len=64; + +memset(item,0,64); +memcpy(item, data, len); + +// Decode string passed +char szDest[64]; +memset(szDest, 0, 64); + +int ret; +ret=base64_decode(item, szDest, cookie); +if (ret) return 0; +// + + +char url[512]; +memset(url, 0, 512); +sprintf(url, "http://rest:9000/delItem?cookie=%s¶meter=%s", cookie, szDest); + +int res; +res = curl(url); + +// Update totals +res = setCart__TOTALS(cookie); + +end: + return 0; + +} diff --git a/pool/shard006/C/0118903_detach.c b/pool/shard006/C/0118903_detach.c new file mode 100644 index 0000000000000000000000000000000000000000..d11088df158dc7591807951e0f6782affd9a06ad --- /dev/null +++ b/pool/shard006/C/0118903_detach.c @@ -0,0 +1,146 @@ +/* $NetBSD: detach.c,v 1.3 2014/05/28 10:12:43 tron Exp $ */ + +/* detach.c -- routines to daemonize a process */ +/* $OpenLDAP$ */ +/* This work is part of OpenLDAP Software . + * + * Copyright 1998-2014 The OpenLDAP Foundation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in the file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ +/* + * Copyright (c) 1990, 1994 Regents of the University of Michigan. + * All rights reserved. + * + * Redistribution and use in source and binary forms are permitted + * provided that this notice is preserved and that due credit is given + * to the University of Michigan at Ann Arbor. The name of the University + * may not be used to endorse or promote products derived from this + * software without specific prior written permission. This software + * is provided ``as is'' without express or implied warranty. + */ +/* This work was originally developed by the University of Michigan + * and distributed as part of U-MICH LDAP. + */ + +#include "portable.h" + +#include + +#include +#include +#include +#include + +#include +#include + +#ifdef HAVE_SYS_FILE_H +#include +#endif +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#include "lutil.h" + +int +lutil_detach( int debug, int do_close ) +{ + int i, sd, nbits, pid; + +#ifdef HAVE_SYSCONF + nbits = sysconf( _SC_OPEN_MAX ); +#elif defined(HAVE_GETDTABLESIZE) + nbits = getdtablesize(); +#else + nbits = FD_SETSIZE; +#endif + +#ifdef FD_SETSIZE + if ( nbits > FD_SETSIZE ) { + nbits = FD_SETSIZE; + } +#endif /* FD_SETSIZE */ + + if ( debug == 0 ) { + for ( i = 0; i < 5; i++ ) { +#ifdef HAVE_THR + pid = fork1(); +#else + pid = fork(); +#endif + switch ( pid ) + { + case -1: + sleep( 5 ); + continue; + + case 0: + break; + + default: + return pid; + } + break; + } + + if ( (sd = open( "/dev/null", O_RDWR )) == -1 && + (sd = open( "/dev/null", O_RDONLY )) == -1 && + /* Panic -- open *something* */ + (sd = open( "/", O_RDONLY )) == -1 ) { + perror("/dev/null"); + } else { + /* redirect stdin, stdout, stderr to /dev/null */ + dup2( sd, STDIN_FILENO ); + dup2( sd, STDOUT_FILENO ); + dup2( sd, STDERR_FILENO ); + + switch( sd ) { + default: + close( sd ); + case STDIN_FILENO: + case STDOUT_FILENO: + case STDERR_FILENO: + break; + } + } + + if ( do_close ) { + /* close everything else */ + for ( i = 0; i < nbits; i++ ) { + if( i != STDIN_FILENO && + i != STDOUT_FILENO && + i != STDERR_FILENO ) + { + close( i ); + } + } + } + +#ifdef CHDIR_TO_ROOT + (void) chdir( "/" ); +#endif + +#ifdef HAVE_SETSID + (void) setsid(); +#elif defined(TIOCNOTTY) + if ( (sd = open( "/dev/tty", O_RDWR )) != -1 ) { + (void) ioctl( sd, TIOCNOTTY, NULL ); + (void) close( sd ); + } +#endif + } + +#ifdef SIGPIPE + (void) SIGNAL( SIGPIPE, SIG_IGN ); +#endif + return 0; +} diff --git a/pool/shard006/C/0118904_parser.c b/pool/shard006/C/0118904_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..86fff225d82202233a53bdd6ca00fe55bf5be0ce --- /dev/null +++ b/pool/shard006/C/0118904_parser.c @@ -0,0 +1,243 @@ +#include +#include +#include +#include +#include +#include +#include +#include "parser.h" +#include "stats.h" + +FILE *queue_file_4; +FILE *queue_file_9; +FILE *queue_file_18; +queue_stats *queue_4; +queue_stats *queue_9; +queue_stats *queue_18; +FILE *emmissions; +FILE *losses; +FILE *losses_n4; + +int parse_line(char *str, struct node_stats stats) { + extern uint64_t packets_all, packets_lost_all, packets_send_all, packets_received_all; + static uint64_t packets_current = 0; + static uint64_t n4_losses_current = 0; + static int times_went_through = 0; + float time; + int code = -1, pid, fid, tos, bif, s, d, pos; + unsigned short return_code = 0; + struct node_stats* obj = NULL; + + // dirty hack + for (size_t i = 0; code == -1; i++) { + if(str[i] == ' ') { + code = atoi(&str[i+1]); + break; + } + } + + if(code != 4) { + sscanf(str, "%f %d %d %d %d %d N%d N%d N%d", + &time, &code, &pid, &fid, &tos, &bif, &s, &d, &pos); + obj = tommy_hashdyn_search(&stats_map, compare, &pos, + tommy_inthash_u32(pos)); + } else { // in this case the line has a different format + sscanf(str, "%f %d %d %d %d N%d N%d N%d", + &time, &code, &pid, &fid, &tos, &s, &d, &pos); + obj = tommy_hashdyn_search(&stats_map, compare, &pos, + tommy_inthash_u32(pos)); + } + + if (!obj) { + fprintf(stdout, + "Unable to access stats map object with node id %d.\n", + pos); + return_code = 1; + } else { + switch(code) { + case 0: + packets_all++; + packets_send_all++; + packets_current++; + obj->packets_treated++; + obj->packets_transmitted++; + /*if(pos == 4 || pos == 9 || pos == 18) { + if(pos == 4) { + add_value_to_queue(queue_4, pid, time); + fprintf(queue_file_4, "%.9f %d\n", time, obj->queue_occupation); + } else if(pos == 9) { + add_value_to_queue(queue_9, pid, time); + fprintf(queue_file_9, "1 %.9f %d\n", time, obj->queue_occupation); + } else if(pos == 18) { + add_value_to_queue(queue_18, pid, time); + fprintf(queue_file_18, "%.9f %d\n", time, obj->queue_occupation); + } + }*/ + break; + case 1: + /*obj->queue_occupation++; + if(pos == 4 || pos == 9 || pos == 18) { + if(pos == 4) { + add_value_to_queue(queue_4, pid, time); + fprintf(queue_file_4, "%.9f %d\n", time, obj->queue_occupation); + } else if(pos == 9) { + add_value_to_queue(queue_9, pid, time); + fprintf(queue_file_9, "1 %.9f %d\n", time, obj->queue_occupation); + } else if(pos == 18) { + add_value_to_queue(queue_18, pid, time); + fprintf(queue_file_18, "%.9f %d\n", time, obj->queue_occupation); + } + }*/ + break; + case 2: + packets_current++; + obj->packets_treated++; + /*printf("%d\n", queue_9->first->value); + if((queue_4->first != NULL) && queue_4->first->value == pid) { + int node = 4; + struct node_stats *tmp = tommy_hashdyn_search(&stats_map, compare, + &node, tommy_inthash_u32(node)); + tmp->queue_occupation--; + remove_head_from_queue(queue_4); + fprintf(queue_file_4, "%.9f %d\n", time, tmp->queue_occupation); + } else if((queue_9->first != NULL) && queue_9->first->value == pid) { + int node = 9; + struct node_stats *tmp = tommy_hashdyn_search(&stats_map, compare, + &node, tommy_inthash_u32(node)); + tmp->queue_occupation--; + remove_head_from_queue(queue_9); + fprintf(queue_file_9, "2 %.9f %d\n", time, tmp->queue_occupation); + } else if((queue_18->first != NULL) && queue_18->first->value == pid) { + int node = 18; + struct node_stats *tmp = tommy_hashdyn_search(&stats_map, compare, + &node, tommy_inthash_u32(node)); + tmp->queue_occupation--; + remove_head_from_queue(queue_18); + fprintf(queue_file_18, "%.9f %d\n", time, tmp->queue_occupation); + }*/ + break; + case 3: + packets_received_all++; + //packets_current--; + obj->packets_received++; + break; + case 4: + packets_lost_all++; + //packets_current--; + obj->packets_lost++; + if(pos == 4) n4_losses_current++; + /*obj->queue_occupation--; + if(pos == 4 || pos == 9 || pos == 18) { + if(pos == 4) { + fprintf(queue_file_4, "%.9f %d\n", time, obj->queue_occupation); + } else if(pos == 9) { + fprintf(queue_file_9, "4 %.9f %d\n", time, obj->queue_occupation); + } else if(pos == 18) { + fprintf(queue_file_18, "%.9f %d\n", time, obj->queue_occupation); + } + }*/ + break; + } + } + if(time > (times_went_through*0.1)) { + fprintf(emmissions, "%f %lu\n", time, packets_current); + fprintf(losses, "%f %lu\n", time, packets_lost_all); + fprintf(losses_n4, "%f %lu\n", time, n4_losses_current); + packets_current = 0; + n4_losses_current = 0; + times_went_through++; + } + + return return_code; +} + +off_t get_size(int fd) { + struct stat tmp_stat; + + if(fstat(fd, &tmp_stat) == -1) { + fprintf(stderr, "Error retrieving stats from file\n"); + exit(-1); + } + + off_t size = tmp_stat.st_size; + return size; +} + +int compare(const void* arg, const void* obj) { + return *(const int*)arg != ((const struct node_stats*)obj)->id; +} + +void* parser_worker(void* arguments) { + char* line = NULL; + char* tokens = NULL; + size_t len = 0; + ssize_t read; + struct node_stats current_stats; + struct worker_args* args = (struct worker_args*) arguments; + + FILE* file = fdopen((int)args->fd, "r"); + if(file == NULL) { + fprintf(stderr, "Error opening stream from file descriptor\n"); + exit(EXIT_FAILURE); + } + + emmissions = fopen("data/emissions.csv", "w"); + if(emmissions == NULL) { + fprintf(stderr, "Error opening emissions variation file\n"); + exit(EXIT_FAILURE); + } + + losses = fopen("data/losses.csv", "w"); + if(losses == NULL) { + fprintf(stderr, "Error opening losses variation file\n"); + exit(EXIT_FAILURE); + } + + losses_n4 = fopen("data/losses_n4.csv", "w"); + if(losses_n4 == NULL) { + fprintf(stderr, "Error opening losses_n4 variation file\n"); + exit(EXIT_FAILURE); + } + + queue_file_4 = fopen("data/queue_variation_4.csv", "w"); + queue_file_9 = fopen("data/queue_variation_9.csv", "w"); + queue_file_18 = fopen("data/queue_variation_18.csv", "w"); + if(queue_file_4 == NULL) + fprintf(stderr, "Error opening queue variation file\n"); + if(queue_file_9 == NULL) + fprintf(stderr, "Error opening queue variation file\n"); + if(queue_file_18 == NULL) + fprintf(stderr, "Error opening queue variation file\n"); + queue_4 = new_queue_stats(); + queue_9 = new_queue_stats(); + queue_18 = new_queue_stats(); + + // Set the file position indicator to start + fseek(file, (long)args->start, SEEK_SET); + fprintf(stdout, "Thread #%d/%d starting at %lu for %d bytes\n", + (args->id)+1, + N, + ftell(file), + args->size); + + while ((read = getline(&line, &len, file)) != -1) { + tokens = strtok(line, "\t"); + while(tokens != NULL) { + parse_line(tokens, current_stats); + tokens = strtok(NULL, "\t"); + } + } + + fprintf(stdout, "Thread #%d has finished. Cleaning up...\n", ((int)args->id)+1); + + free(line); + free(tokens); + + fclose(emmissions); + fclose(losses); + fclose(queue_file_4); + fclose(queue_file_9); + fclose(queue_file_18); + fclose(file); + pthread_exit(0); +} diff --git a/pool/shard006/C/0118907_ewt.c b/pool/shard006/C/0118907_ewt.c new file mode 100644 index 0000000000000000000000000000000000000000..ca83d3d2a96aeaddc662c70a78d6e0e13f6c0d52 --- /dev/null +++ b/pool/shard006/C/0118907_ewt.c @@ -0,0 +1,234 @@ +/* -*- mode: c; c-basic-offset: 2 -*- */ +/* + * Copyright (C) 2007-2012 David Bird (Coova Technologies) + * + * 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 . + * + */ + +#include "chilli.h" +#include "json.h" + +int http_parse_input(char *src, int len, int is_cookie) { + bstring name = bfromcstr(""); + bstring value = bfromcstr(""); + int start_pos=0, eq_pos=0, end_pos=0; + int i, ret = 0; + + char stop = (is_cookie) ? ';' : '&'; + + for (i=0; i <= len; i++) { + if (i == len || src[i] == stop) { end_pos = i; } + else if (!eq_pos && src[i] == '=') { eq_pos = i; } + + if (eq_pos && end_pos && start_pos != eq_pos) { + + bassigncstr(name, ""); + bassigncstr(value, ""); + + if (is_cookie) { + bassigncstr(name,"COOKIE_"); + bcatblk(name,src+start_pos,eq_pos-start_pos); + } else { + bassigncstr(name,"CAP_"); + bcatblk(name,src+start_pos,eq_pos-start_pos); + } + + /*bunescape(name);*/ + + if ((eq_pos + 1) == end_pos || (end_pos - eq_pos) <= 1) { + log_dbg("%s = nil", name->data); + } else { + bassignblk(value, src+eq_pos+1, end_pos-eq_pos-1); + /*bunescape(value);*/ + log_dbg("%s = %s", name->data, value->data); + setenv((char *)name->data, (char *)value->data, 1); + } + start_pos = end_pos + 1; + if (start_pos < len) + while (src[start_pos] == ' ' && i < len) + i++, start_pos++; + + end_pos = eq_pos = 0; + } + } + + ret = 1; + bdestroy(name); + bdestroy(value); + return ret; +} + +/* +static int chilli_status(bstring s) { + return 0; + }*/ + +static int chilli_garden(bstring b) { + return 0; +} + +static int chilli_sessions(bstring b) { + struct dhcp_conn_t *conn = dhcp->firstusedconn; + + char *state = "Authorized"; + + bstring s = bfromcstr(""); + bcatcstr(b, "{\"service\":[{ \""); + bcatcstr(b, getenv("CAP_table")); + bcatcstr(b, "\":[ "); + + while (conn) { + struct app_conn_t *appconn = (struct app_conn_t *)conn->peer; + + if (appconn && appconn->s_state.authenticated) { + + } else { + state = "Redirect"; + } + + bassignformat(s, + "{" + "\"state\":\"%s\"," + "\"macAddress\":\"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X\"," + "\"ipAddress\":\"%s\",", + state, + conn->hismac[0], conn->hismac[1], conn->hismac[2], + conn->hismac[3], conn->hismac[4], conn->hismac[5], + inet_ntoa(conn->hisip) + ); + + conn = conn->next; + if (appconn) { + session_json_params(&appconn->s_state, &appconn->s_params, s, 0); + bcatcstr(s, ","); + session_json_acct(&appconn->s_state, &appconn->s_params, s, 0); + } + bcatcstr(s, "},"); + bconcat(b, s); + } + + bcatcstr(b, "]} ]}"); + return 0; +} + +struct ewt_service { + char *name; + int (* func) (bstring s); +} ewt_services[] = { + /* { "hot-status", chilli_status },*/ + { "chilli-garden", chilli_garden }, + { "chilli-sessions", chilli_sessions }, +}; + +static int NUM_SERVICES = sizeof(ewt_services) / sizeof(struct ewt_service); + +static void json_walk(bstring prefix, struct json_object *obj) { + json_object_object_foreach(obj, key, val) { + bstring tmp = bfromcstr(""); + switch(json_object_get_type(val)) { + case json_type_object: + bassign(tmp, prefix); + bcatcstr(tmp, key); + bcatcstr(tmp, "_0_"); + json_walk(tmp, val); + break; + case json_type_array: + bassign(tmp, prefix); + bcatcstr(tmp, key); + log_dbg("a %s=%s", tmp->data, json_object_to_json_string(val)); + break; + default: + bassign(tmp, prefix); + bcatcstr(tmp, key); + log_dbg("%s=%s", tmp->data, json_object_to_json_string(val)); + break; + } + bdestroy(tmp); + } +} + +int ewtapi(struct redir_t *redir, + struct redir_socket_t *sock, + struct redir_conn_t *conn, + struct redir_httpreq_t *httpreq) { + char path[1024]; + char *binqqargs[3] = { path, 0, 0 }; + bstring b = bfromcstr(""); + bstring s = bfromcstr(""); + bstring res = bfromcstr(""); + int i; + + log_dbg("EWT API Request"); + + redir_getparam(redir, httpreq->qs, "s", s); + redir_getparam(redir, httpreq->qs, "res", res); + + if (httpreq->qs) { + http_parse_input(httpreq->qs, strlen(httpreq->qs), 0); + } + + if (httpreq->clen) { + struct json_object *obj = 0; + bblk_fromfd(b, 0, httpreq->clen); + if ((obj = json_tokener_parse((char *)b->data))) { + log_dbg("obj.to_string()=%s", json_object_to_json_string(obj)); + json_object_object_foreach(obj, key, val) { + if (!strcmp(key, (char *)s->data)) { + bstring tmp = bfromcstr("CAP_"); + json_walk(tmp, val); + bdestroy(tmp); + } + } + } + /* delete obj */ + } + + bassignformat(b, + "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n" + "Pragma: no-cache\r\n" + "Expires: Fri, 01 Jan 1971 00:00:00 GMT\r\n" + "Cache-Control: no-cache, must-revalidate\r\n" + "Content-type: application/json\r\n\r\n"); + + if (safe_write(1, b->data, b->slen) < 0) { + log_err(errno, "redir_write()"); + } + + safe_snprintf(path, sizeof(path), + "/var/coova/scripts/%s.sh", s->data); + + for (i=0; i < NUM_SERVICES; i++) { + bassigncstr(b, ""); + if (!strcmp(ewt_services[i].name, (char *)s->data)) { + ewt_services[i].func(b); + log_dbg("Internal EWT Service %s -> %s", ewt_services[i].name, b->data); + if (safe_write(1, b->data, b->slen) < 0) { + log_err(errno, "redir_write()"); + } + bdestroy(b); + bdestroy(s); + bdestroy(res); + return 0; + } + } + + setenv("EWTAPI", "1", 1); + log_dbg("EWT API Running %s", *binqqargs); + + execv(*binqqargs, binqqargs); + log_err(errno, "count not exec %s", *binqqargs); + return -1; +} diff --git a/pool/shard006/C/0118916_cache_req_initgroups_by_name.c b/pool/shard006/C/0118916_cache_req_initgroups_by_name.c new file mode 100644 index 0000000000000000000000000000000000000000..75ac44e1ad36238f01342eced9188d07daa50720 --- /dev/null +++ b/pool/shard006/C/0118916_cache_req_initgroups_by_name.c @@ -0,0 +1,239 @@ +/* + Authors: + Pavel Březina + + Copyright (C) 2016 Red Hat + + 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 . +*/ + +#include +#include + +#include "db/sysdb.h" +#include "util/util.h" +#include "providers/data_provider.h" +#include "responder/common/cache_req/cache_req_plugin.h" + +static errno_t +cache_req_initgroups_by_name_prepare_domain_data(struct cache_req *cr, + struct cache_req_data *data, + struct sss_domain_info *domain) +{ + TALLOC_CTX *tmp_ctx; + const char *name; + errno_t ret; + + if (cr->data->name.name == NULL) { + DEBUG(SSSDBG_CRIT_FAILURE, "Bug: parsed name is NULL?\n"); + return ERR_INTERNAL; + } + + tmp_ctx = talloc_new(NULL); + if (tmp_ctx == NULL) { + return ENOMEM; + } + + name = sss_get_cased_name(tmp_ctx, cr->data->name.name, + domain->case_sensitive); + if (name == NULL) { + ret = ENOMEM; + goto done; + } + + name = sss_reverse_replace_space(tmp_ctx, name, cr->rctx->override_space); + if (name == NULL) { + ret = ENOMEM; + goto done; + } + + name = sss_create_internal_fqname(tmp_ctx, name, domain->name); + if (name == NULL) { + ret = ENOMEM; + goto done; + } + + talloc_zfree(data->name.lookup); + data->name.lookup = talloc_steal(data, name); + + ret = EOK; + +done: + talloc_free(tmp_ctx); + return ret; +} + +static const char * +cache_req_initgroups_by_name_create_debug_name(TALLOC_CTX *mem_ctx, + struct cache_req_data *data, + struct sss_domain_info *domain) +{ + return talloc_strdup(mem_ctx, data->name.lookup); +} + +static errno_t +cache_req_initgroups_by_name_ncache_check(struct sss_nc_ctx *ncache, + struct sss_domain_info *domain, + struct cache_req_data *data) +{ + return sss_ncache_check_user(ncache, domain, data->name.lookup); +} + +static errno_t +cache_req_initgroups_by_name_ncache_add(struct sss_nc_ctx *ncache, + struct sss_domain_info *domain, + struct cache_req_data *data) +{ + return sss_ncache_set_user(ncache, false, domain, data->name.lookup); +} + +static errno_t +cache_req_initgroups_by_name_lookup(TALLOC_CTX *mem_ctx, + struct cache_req *cr, + struct cache_req_data *data, + struct sss_domain_info *domain, + struct ldb_result **_result) +{ + return sysdb_initgroups_with_views(mem_ctx, domain, data->name.lookup, + _result); +} + +static errno_t +cache_req_initgroups_by_name_dpreq_params(TALLOC_CTX *mem_ctx, + struct cache_req *cr, + struct ldb_result *result, + const char **_string, + uint32_t *_id, + const char **_flag) +{ + struct ldb_result *user; + const char *name; + errno_t ret; + + *_id = 0; + *_string = cr->data->name.lookup; + *_flag = NULL; + + if (!DOM_HAS_VIEWS(cr->domain)) { + return EOK; + } + + /* We must search with views. */ + if (result == NULL || result->count == 0) { + *_flag = EXTRA_INPUT_MAYBE_WITH_VIEW; + return EOK; + } + + /* If domain has views we will try to use original values instead of the + * overridden ones. This is a must for the LOCAL view since we can't look + * it up otherwise. But it is also a shortcut for non-local views where + * we will not fail over to the overridden value. */ + + ret = sysdb_getpwnam_with_views(NULL, cr->domain, + cr->data->name.lookup, &user); + if (ret != EOK || user == NULL || user->count != 1) { + /* Case where the user is not found has been already handled. If + * this is not OK, it is an error. */ + CACHE_REQ_DEBUG(SSSDBG_CRIT_FAILURE, cr, + "Unable to match initgroups user [%d]: %s\n", + ret, sss_strerror(ret)); + return ret; + } + + name = ldb_msg_find_attr_as_string(user->msgs[0], SYSDB_NAME, NULL); + if (name == NULL) { + DEBUG(SSSDBG_CRIT_FAILURE, "Bug: name cannot be NULL\n"); + talloc_free(user); + return ERR_INTERNAL; + } + + /* Now we have the original name. We don't have to search with + * views unless some error occurred. */ + *_string = talloc_steal(mem_ctx, name); + + talloc_free(user); + + return EOK; +} + +static struct tevent_req * +cache_req_initgroups_by_name_dp_send(TALLOC_CTX *mem_ctx, + struct cache_req *cr, + struct cache_req_data *data, + struct sss_domain_info *domain, + struct ldb_result *result) +{ + const char *string; + const char *flag; + uint32_t id; + errno_t ret; + + ret = cache_req_initgroups_by_name_dpreq_params(mem_ctx, cr, result, + &string, &id, &flag); + if (ret != EOK) { + return NULL; + } + + return sss_dp_get_account_send(mem_ctx, cr->rctx, domain, true, + SSS_DP_INITGROUPS, string, id, flag); +} + +const struct cache_req_plugin cache_req_initgroups_by_name = { + .name = "Initgroups by name", + .attr_expiration = SYSDB_INITGR_EXPIRE, + .parse_name = true, + .ignore_default_domain = false, + .bypass_cache = false, + .only_one_result = false, + .search_all_domains = false, + .require_enumeration = false, + .allow_missing_fqn = false, + .allow_switch_to_upn = true, + .upn_equivalent = CACHE_REQ_INITGROUPS_BY_UPN, + .get_next_domain_flags = SSS_GND_DESCEND, + + .is_well_known_fn = NULL, + .prepare_domain_data_fn = cache_req_initgroups_by_name_prepare_domain_data, + .create_debug_name_fn = cache_req_initgroups_by_name_create_debug_name, + .global_ncache_add_fn = NULL, + .ncache_check_fn = cache_req_initgroups_by_name_ncache_check, + .ncache_add_fn = cache_req_initgroups_by_name_ncache_add, + .ncache_filter_fn = NULL, + .lookup_fn = cache_req_initgroups_by_name_lookup, + .dp_send_fn = cache_req_initgroups_by_name_dp_send, + .dp_recv_fn = cache_req_common_dp_recv +}; + +struct tevent_req * +cache_req_initgr_by_name_send(TALLOC_CTX *mem_ctx, + struct tevent_context *ev, + struct resp_ctx *rctx, + struct sss_nc_ctx *ncache, + int cache_refresh_percent, + enum cache_req_dom_type req_dom_type, + const char *domain, + const char *name) +{ + struct cache_req_data *data; + + data = cache_req_data_name(mem_ctx, CACHE_REQ_INITGROUPS, name); + if (data == NULL) { + return NULL; + } + + return cache_req_steal_data_and_send(mem_ctx, ev, rctx, ncache, + cache_refresh_percent, + req_dom_type, domain, + data); +} diff --git a/pool/shard006/C/0118919_failure_prints_errno.c b/pool/shard006/C/0118919_failure_prints_errno.c new file mode 100644 index 0000000000000000000000000000000000000000..dc05fa91edada770e49448f1dea2ea735a9a1964 --- /dev/null +++ b/pool/shard006/C/0118919_failure_prints_errno.c @@ -0,0 +1,34 @@ +// REQUIRES: preload, c_api_execvpe +// RUN: %{compile} '-D_PROGRAM="/path/to/not/existing"' -o %t %s +// RUN: %t > %t.without.errno +// RUN: %{intercept} --output %t.json -- %t > %t.with.errno +// RUN: diff %t.with.errno %t.without.errno +// RUN: assert_intercepted %t.json count -eq 1 +// RUN: assert_intercepted %t.json contains -program %t + +#include "config.h" + +#include +#include +#include +#include + +#if defined HAVE_UNISTD_H +#include +#endif + +extern char **environ; + +int main() +{ + char *const program = _PROGRAM; + char *const argv[] = { _PROGRAM, "hi there", 0 }; + + if (-1 == execve(program, argv, environ)) { + const int error = errno; + printf("errno: %d (%s)\n", error, strerror(error)); + return EXIT_SUCCESS; + } + + return EXIT_FAILURE; +} diff --git a/pool/shard006/C/0118921_testarray1.c b/pool/shard006/C/0118921_testarray1.c new file mode 100644 index 0000000000000000000000000000000000000000..8e04b7962d8a346e35ecc7d70c1ae6ff9586d2dd --- /dev/null +++ b/pool/shard006/C/0118921_testarray1.c @@ -0,0 +1,17 @@ +// address: 0x8048368 +int main(int argc, char *argv[], char *envp[]) { + __size32 edx; // r26 + int local0; // m[esp - 12] + int local1; // m[esp - 8] + + local0 = 0; + local1 = 0; + while (local1 <= 4) { + edx = (int) *(local1 + 0x80495bc); + local0 += edx; + local1++; + } + printf("Sum is %d\n", local0); + return 0; +} + diff --git a/pool/shard006/C/0118923_redboot_linux_exec.c b/pool/shard006/C/0118923_redboot_linux_exec.c new file mode 100644 index 0000000000000000000000000000000000000000..d74a6f37bf90dab33df666ba0e18f9e97b88ddda --- /dev/null +++ b/pool/shard006/C/0118923_redboot_linux_exec.c @@ -0,0 +1,254 @@ +//========================================================================== +// +// redboot_linux_exec.c +// +// RedBoot command to boot Linux +// +//========================================================================== +//####ECOSGPLCOPYRIGHTBEGIN#### +// ------------------------------------------- +// This file is part of eCos, the Embedded Configurable Operating System. +// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Red Hat, Inc. +// Copyright (C) 2002, 2003, 2004 Gary Thomas +// +// eCos 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. +// +// eCos 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 eCos; if not, write to the Free Software Foundation, Inc., +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. +// +// As a special exception, if other files instantiate templates or use macros +// or inline functions from this file, or you compile this file and link it +// with other works to produce a work based on this file, this file does not +// by itself cause the resulting work to be covered by the GNU General Public +// License. However the source code for this file must still be made available +// in accordance with section (3) of the GNU General Public License. +// +// This exception does not invalidate any other reasons why a work based on +// this file might be covered by the GNU General Public License. +// +// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc. +// at http://sources.redhat.com/ecos/ecos-license/ +// ------------------------------------------- +//####ECOSGPLCOPYRIGHTEND#### +//####OTHERCOPYRIGHTBEGIN#### +// +// The structure definitions below are taken from include/asm-/redboot.h in +// the Linux kernel, Copyright (c) 2002, 2003 Gary Thomas, Copyright (c) 1997 Dan Malek. +// Their presence here is for the express purpose of communication with the Linux +// kernel being booted and is considered 'fair use' by the original author and +// are included with their permission. +// +//####OTHERCOPYRIGHTEND#### +//========================================================================== +//#####DESCRIPTIONBEGIN#### +// +// Author(s): msalter +// Contributors: gthomas,msalter +// Date: 2002-01-14 +// Purpose: +// Description: +// +// This code is part of RedBoot (tm). +// +//####DESCRIPTIONEND#### +// +//========================================================================== + +#include + +#include +#include +#include +#include + +#ifdef CYGPKG_REDBOOT_NETWORKING +#include +#endif + +#ifdef CYGPKG_IO_ETH_DRIVERS +#include // Logical driver interfaces +#endif + +#include CYGHWR_MEMORY_LAYOUT_H + +#include + + +//========================================================================= + +// Exported CLI function(s) +static void do_exec(int argc, char *argv[]); +RedBoot_cmd("exec", + "Execute a Linux image - with MMU off", + "[-w timeout]\n" + " [-c \"kernel command line\"] []", + do_exec + ); + +// +// Execute a Linux kernel - this is a RedBoot CLI command +// +static void +do_exec(int argc, char *argv[]) +{ + unsigned long entry; + bool wait_time_set, cmd_line_set; + int wait_time; + char *cmd_line; + char *cline; + struct option_info opts[2]; + hal_virtual_comm_table_t *__chan; + int baud_rate; + + bd_t *board_info; + CYG_INTERRUPT_STATE oldints; + unsigned long sp = CYGMEM_REGION_ram+CYGMEM_REGION_ram_SIZE; + + init_opts(&opts[0], 'w', true, OPTION_ARG_TYPE_NUM, + (void *)&wait_time, (bool *)&wait_time_set, "wait timeout"); + init_opts(&opts[1], 'c', true, OPTION_ARG_TYPE_STR, + (void *)&cmd_line, (bool *)&cmd_line_set, "kernel command line"); + entry = entry_address; // Default from last 'load' operation + if (!scan_opts(argc, argv, 1, opts, 2, (void *)&entry, OPTION_ARG_TYPE_NUM, + "[physical] starting address")) { + return; + } + if (entry == (unsigned long)NO_MEMORY) { + diag_printf("Can't execute Linux - invalid entry address\n"); + return; + } + + // Determine baud rate on current console + __chan = CYGACC_CALL_IF_CONSOLE_PROCS(); + baud_rate = CYGACC_COMM_IF_CONTROL(*__chan, __COMMCTL_GETBAUD); + if (baud_rate <= 0) { + baud_rate = CYGNUM_HAL_VIRTUAL_VECTOR_CONSOLE_CHANNEL_BAUD; + } + // Make a little space at the top of the stack, and align to + // 64-bit boundary. + sp = (sp-128) & ~7; // The Linux boot code uses this space for FIFOs + + // Copy the commandline onto the stack, and set the SP to just below it. + if (cmd_line_set) { + int len,i; + + // get length of string + for( len = 0; cmd_line[len] != '\0'; len++ ); + + // decrement sp by length of string and align to + // word boundary. + sp = (sp-(len+1)) & ~3; + + // assign this SP value to command line start + cline = (char *)sp; + + // copy command line over. + for( i = 0; i < len; i++ ) + cline[i] = cmd_line[i]; + cline[len] = '\0'; + + } else { + cline = (char *)NULL; + } + + // Set up parameter struct at top of stack + sp = sp-sizeof(bd_t); + board_info = (bd_t *)sp; + memset(board_info, sizeof(*board_info), 0); + + board_info->bi_tag = 0x42444944; + board_info->bi_size = sizeof(*board_info); + board_info->bi_revision = 1; + board_info->bi_bdate = 0x06012002; + board_info->bi_memstart = CYGMEM_REGION_ram; + board_info->bi_memsize = CYGMEM_REGION_ram_SIZE; + board_info->bi_baudrate = baud_rate; + board_info->bi_cmdline = cline; +#ifdef CYGPKG_REDBOOT_NETWORKING + memcpy(board_info->bi_enetaddr, __local_enet_addr, sizeof(enet_addr_t)); +#endif + // Call platform specific code to fill in the platform/architecture specific details + plf_redboot_linux_exec(board_info); + + // adjust SP to 64 byte boundary, and leave a little space + // between it and the commandline for PowerPC calling + // conventions. + + sp = (sp-64)&~63; + + if (wait_time_set) { + int script_timeout_ms = wait_time * 1000; +#ifdef CYGFUN_REDBOOT_BOOT_SCRIPT + unsigned char *hold_script = script; + script = (unsigned char *)0; +#endif + diag_printf("About to start execution at %p - abort with ^C within %d seconds\n", + (void *)entry, wait_time); + while (script_timeout_ms >= CYGNUM_REDBOOT_CLI_IDLE_TIMEOUT) { + int res; + char line[80]; + res = _rb_gets(line, sizeof(line), CYGNUM_REDBOOT_CLI_IDLE_TIMEOUT); + if (res == _GETS_CTRLC) { +#ifdef CYGFUN_REDBOOT_BOOT_SCRIPT + script = hold_script; // Re-enable script +#endif + return; + } + script_timeout_ms -= CYGNUM_REDBOOT_CLI_IDLE_TIMEOUT; + } + } + +#ifdef CYGPKG_IO_ETH_DRIVERS + eth_drv_stop(); +#endif + + // Disable interrupts + HAL_DISABLE_INTERRUPTS(oldints); + + // Put the caches to sleep. + HAL_DCACHE_SYNC(); + HAL_ICACHE_DISABLE(); + HAL_DCACHE_DISABLE(); + HAL_DCACHE_SYNC(); + HAL_ICACHE_INVALIDATE_ALL(); + HAL_DCACHE_INVALIDATE_ALL(); + +// diag_printf("entry %08x, sp %08x, info %08x, cmd line %08x, baud %d\n", +// entry, sp, board_info, cline, baud_rate); +// breakpoint(); + + // Call into Linux + __asm__ volatile ( + // Start by disabling MMU - the mappings are + // 1-1 so this should not cause any problems + "mfmsr 3\n" + "li 4,0xFFFFFFCF\n" + "and 3,3,4\n" + "sync\n" + "mtmsr 3\n" + "sync\n" + + // Now set up parameters to jump into linux + + "mtlr %0\n" // set entry address in LR + "mr 1,%1\n" // set stack pointer + "mr 3,%2\n" // set board info in R3 + "mr 4,%3\n" // set command line in R4 + "blr \n" // jump into linux + : + : "r"(entry),"r"(sp),"r"(board_info),"r"(cline) + : "r3", "r4" + + ); +} + +//========================================================================= +// EOF redboot_linux_exec.c diff --git a/pool/shard006/C/0118926_n2b_d.c b/pool/shard006/C/0118926_n2b_d.c new file mode 100644 index 0000000000000000000000000000000000000000..2ad23284a100c70d0b41f3355e1f61f42799ab59 --- /dev/null +++ b/pool/shard006/C/0118926_n2b_d.c @@ -0,0 +1,126 @@ +/* + n2b_d.c -- implementation of the NRV2B decompression algorithm + This file is part of the UCL data compression library. + Copyright (C) 1996-2004 Markus Franz Xaver Johannes Oberhumer + */ +// +// actual implementation used by a recursive #include +// +#ifdef getbit + +#define SAFE // @v9.1.1 + +#ifdef SAFE + #define fail(x, r) if(x) { *dst_len = olen; return r; } +#else + #define fail(x, r) +#endif +{ + ucl_uint32 bb = 0; + #ifdef TEST_OVERLAP + ucl_uint ilen = src_off, olen = 0, last_m_off = 1; + #else + ucl_uint ilen = 0, olen = 0, last_m_off = 1; + #endif + #ifdef SAFE + const ucl_uint oend = *dst_len; + #endif + ACC_UNUSED(wrkmem); + #ifdef TEST_OVERLAP + src_len += src_off; + fail(oend >= src_len, UCL_E_OVERLAP_OVERRUN); + #endif + for(;;) { + ucl_uint m_off, m_len; + while(getbit(bb)) { + fail(ilen >= src_len, UCL_E_INPUT_OVERRUN); + fail(olen >= oend, UCL_E_OUTPUT_OVERRUN); + #ifdef TEST_OVERLAP + fail(olen > ilen, UCL_E_OVERLAP_OVERRUN); + olen++; ilen++; + #else + dst[olen++] = src[ilen++]; + #endif + } + m_off = 1; + do { + m_off = m_off*2+getbit(bb); + fail(ilen >= src_len, UCL_E_INPUT_OVERRUN); + fail(m_off > UCL_UINT32_C(0xffffff)+3, UCL_E_LOOKBEHIND_OVERRUN); + } while(!getbit(bb)); + if(m_off == 2) { + m_off = last_m_off; + } + else { + fail(ilen >= src_len, UCL_E_INPUT_OVERRUN); + m_off = (m_off-3)*256+src[ilen++]; + if(m_off == UCL_UINT32_C(0xffffffff)) + break; + last_m_off = ++m_off; + } + m_len = getbit(bb); + m_len = m_len*2+getbit(bb); + if(m_len == 0) { + m_len++; + do { + m_len = m_len*2+getbit(bb); + fail(ilen >= src_len, UCL_E_INPUT_OVERRUN); + fail(m_len >= oend, UCL_E_OUTPUT_OVERRUN); + } while(!getbit(bb)); + m_len += 2; + } + m_len += (m_off > 0xd00); + fail(olen+m_len > oend, UCL_E_OUTPUT_OVERRUN); + fail(m_off > olen, UCL_E_LOOKBEHIND_OVERRUN); + #ifdef TEST_OVERLAP + olen += m_len+1; + fail(olen > ilen, UCL_E_OVERLAP_OVERRUN); + #else + { + const ucl_bytep m_pos = dst+olen-m_off; + dst[olen++] = *m_pos++; + do { + dst[olen++] = *m_pos++; + } while(--m_len > 0); + } + #endif + } + *dst_len = olen; + return ilen == src_len ? UCL_E_OK : (ilen < src_len ? UCL_E_INPUT_NOT_CONSUMED : UCL_E_INPUT_OVERRUN); +} + +#undef fail + +#endif /* getbit */ +// +// decompressor entries for the different bit-buffer sizes +// +#ifndef getbit + +#include "ucl_conf.h" +#include +#include "getbit.h" + +UCL_PUBLIC(int) ucl_nrv2b_decompress_8(const ucl_bytep src, ucl_uint src_len, ucl_bytep dst, ucl_uintp dst_len, ucl_voidp wrkmem) +{ + #define getbit(bb) getbit_8(bb, src, ilen) + #include "n2b_d.c" + #undef getbit +} + +UCL_PUBLIC(int) ucl_nrv2b_decompress_le16(const ucl_bytep src, ucl_uint src_len, ucl_bytep dst, ucl_uintp dst_len, ucl_voidp wrkmem) +{ + #define getbit(bb) getbit_le16(bb, src, ilen) + #include "n2b_d.c" + #undef getbit +} + +UCL_PUBLIC(int) ucl_nrv2b_decompress_le32(const ucl_bytep src, ucl_uint src_len, ucl_bytep dst, ucl_uintp dst_len, ucl_voidp wrkmem) +{ + unsigned bc = 0; + #define getbit(bb) getbit_le32(bb, bc, src, ilen) + #include "n2b_d.c" + #undef getbit +} + +#endif /* !getbit */ diff --git a/pool/shard006/C/0118933_base64url.c b/pool/shard006/C/0118933_base64url.c new file mode 100644 index 0000000000000000000000000000000000000000..4da7f5ed7f5ac105ecbfaeee3a037acdb1393570 --- /dev/null +++ b/pool/shard006/C/0118933_base64url.c @@ -0,0 +1,96 @@ +#include "test.h" + +#include + +typedef struct base64url_test_s { + const char* encoded; + const char* decoded; + size_t decodedLen; +} base64url_test_t; + +static base64url_test_t base64url_tests[] = { + // Test vectors from RFC 4648, section 10. + {"", "", 0}, + {"Zg", "f", 1}, + {"Zg==", "f", 1}, + {"Zm8", "fo", 2}, + {"Zm8=", "fo", 2}, + {"Zm9v", "foo", 3}, + {"Zm9vYg", "foob", 4}, + {"Zm9vYg==", "foob", 4}, + {"Zm9vYmE", "fooba", 5}, + {"Zm9vYmE=", "fooba", 5}, + {"Zm9vYmFy", "foobar", 6}, + + // Examples from RFC 4648, section 9.g + {"FPucA9l-", "\x14\xfb\x9c\x03\xd9\x7e", 6}, + {"FPucA9k", "\x14\xfb\x9c\x03\xd9", 5}, + {"FPucA9k=", "\x14\xfb\x9c\x03\xd9", 5}, + {"FPucAw", "\x14\xfb\x9c\x03", 4}, + {"FPucAw==", "\x14\xfb\x9c\x03", 4}, +}; + +void +test_base64url_decode() { + size_t tests = sizeof(base64url_tests) / sizeof(base64url_test_t); + for (size_t i = 0; i < tests; i++) { + base64url_test_t t = base64url_tests[i]; + + size_t encodedLen = strlen(t.encoded); + size_t minDecodedLen = ece_base64url_decode( + t.encoded, encodedLen, ECE_BASE64URL_IGNORE_PADDING, NULL, 0); + + if (!t.decodedLen) { + ece_assert(!minDecodedLen, "Got minimum decoded length %zu", + minDecodedLen); + continue; + } + + ece_assert(minDecodedLen == t.decodedLen, + "Got minimum decoded length %zu for `%s`; want %zu", + minDecodedLen, t.encoded, t.decodedLen); + + uint8_t* decoded = calloc(t.decodedLen, sizeof(uint8_t)); + ece_assert(decoded, "Failed to allocate buffer for `%s`", t.encoded); + + size_t decodedLen = + ece_base64url_decode(t.encoded, encodedLen, ECE_BASE64URL_IGNORE_PADDING, + decoded, t.decodedLen); + ece_assert(decodedLen == t.decodedLen, + "Got length %zu for `%s` with padding ignored; want %zu", + decodedLen, t.encoded, t.decodedLen); + ece_assert(!memcmp(decoded, t.decoded, decodedLen), + "Wrong output for `%s` with padding ignored", t.encoded); + + const char* padStart = strchr(t.encoded, '='); + if (padStart) { + decodedLen = ece_base64url_decode(t.encoded, encodedLen, + ECE_BASE64URL_REJECT_PADDING, decoded, + t.decodedLen); + ece_assert(!decodedLen, + "Got length %zu decoding `%s` with padding rejected", + decodedLen, t.encoded); + + size_t unpaddedLen = (size_t)(padStart - t.encoded); + decodedLen = ece_base64url_decode(t.encoded, unpaddedLen, + ECE_BASE64URL_REQUIRE_PADDING, decoded, + t.decodedLen); + ece_assert(!decodedLen, + "Got length %zu decoding `%s` with required padding trimmed", + decodedLen, t.encoded); + } + + if (padStart || !(encodedLen % 4)) { + decodedLen = ece_base64url_decode(t.encoded, encodedLen, + ECE_BASE64URL_REQUIRE_PADDING, decoded, + t.decodedLen); + ece_assert(decodedLen == t.decodedLen, + "Got length %zu for `%s` with padding required; want %zu", + decodedLen, t.encoded, t.decodedLen); + ece_assert(!memcmp(decoded, t.decoded, decodedLen), + "Wrong output for `%s` with padding required", t.encoded); + } + + free(decoded); + } +} diff --git a/pool/shard006/C/0118935_tokenization_test.c b/pool/shard006/C/0118935_tokenization_test.c new file mode 100644 index 0000000000000000000000000000000000000000..c70529872deeb8b9a5487061848107e832d0a804 --- /dev/null +++ b/pool/shard006/C/0118935_tokenization_test.c @@ -0,0 +1,59 @@ +#include +#include + +#include "llamapun/unicode_normalizer.h" +#include "llamapun/tokenizer.h" + +#include +#include + +int main(void) { + //load example document + fprintf(stderr, "\n\n Tokenization tests\n\n"); + initialize_tokenizer("../../third-party/senna/"); + + xmlDocPtr doc = xmlReadFile("../../t/documents/1311.0066.xhtml", NULL, XML_PARSE_RECOVER | XML_PARSE_NONET); + if (doc == NULL) { return 1;} + unicode_normalize_dom(doc); + //Create DNM, with normalized math tags, and ignoring cite tags + dnmPtr mydnm = create_DNM(xmlDocGetRootElement(doc), DNM_NORMALIZE_TAGS | DNM_IGNORE_LATEX_NOTES); + if (mydnm == NULL) { return 1;} + char* text = mydnm->plaintext; + dnmRanges sentences = tokenize_sentences(text); + // TODO: We need better tokenization tests, this is a hack... + if (sentences.length < 730) { //something could have gone wrong... + fprintf(stderr, "There were too few sentences tokenized: %d!\n", sentences.length); + return 1; + } + if (sentences.length > 750) { //something could have gone wrong... + fprintf(stderr, "There were too many sentences tokenized: %d!\n",sentences.length); + return 1; + } + + int sentence_index; + for (sentence_index=0; sentence_index < sentences.length; sentence_index++) { + if (sentences.range[sentence_index].end < sentences.range[sentence_index].start) { + fprintf(stderr, "Invalid sentence, start appears after end!\n"); + return 1; + } + dnmRanges words = tokenize_words(text, sentences.range[sentence_index], TOKENIZER_ACCEPT_ALL); +// fprintf(stderr,"=====\n"); +// fprintf(stderr,"%.*s\n",(sentences.range[sentence_index].end-sentences.range[sentence_index].start+1),(text+sentences.range[sentence_index].start)); +// fprintf(stderr,"-----\n"); +// display_ranges(words, mydnm->plaintext); + if (words.length == 0) { + fprintf(stderr, "Sentence had no words tokenized, aborting.\n"); + return 1; + } + free(words.range); + } + + //clean up + free_tokenizer(); + free(sentences.range); + free_DNM(mydnm); + xmlFreeDoc(doc); + xmlCleanupParser(); + + return 0; +} diff --git a/pool/shard006/C/0118937_myid.c b/pool/shard006/C/0118937_myid.c new file mode 100644 index 0000000000000000000000000000000000000000..d0eb86c66cb6f072906ecf696c42258d262c0b7b --- /dev/null +++ b/pool/shard006/C/0118937_myid.c @@ -0,0 +1,200 @@ +/* identity representation, as in IKE ID Payloads (RFC 2407 DOI 4.6.2.1) + * Copyright (C) 1999-2001 D. Hugh Redelmeier + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See . + * + * 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. + * + * RCSID $Id: id.c,v 1.47 2005/08/05 19:10:43 mcr Exp $ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "sysdep.h" +#include "constants.h" +#include "defs.h" +#include "oswalloc.h" +#include "oswlog.h" +#include "log.h" +#include "id.h" +#include "x509.h" +#include "pgp.h" +#include "certs.h" +#include "smartcard.h" +#include "connections.h" +#include "packet.h" +#include "whack.h" + +enum myid_state myid_state = MYID_UNKNOWN; +struct id myids[MYID_SPECIFIED+1]; /* %myid */ +char *myid_str[MYID_SPECIFIED+1]; /* string form of IDs */ + +const struct id *resolve_myid(const struct id *id) +{ + if((id)->kind == ID_MYID) { + return &myids[myid_state]; + } else { + return (id); + } +} + +void +show_myid_status(void) +{ + char idstr[IDTOA_BUF]; + + (void)idtoa(&myids[myid_state], idstr, sizeof(idstr)); + whack_log(RC_COMMENT, "%%myid = %s", idstr); +} + +/* Fills in myid from environment variable IPSECmyid or defaultrouteaddr + */ +void +init_id(void) +{ + passert(empty_id.kind == ID_NONE); + myid_state = MYID_UNKNOWN; + { + enum myid_state s; + + for (s = MYID_UNKNOWN; s <= MYID_SPECIFIED; s++) + { + myids[s] = empty_id; + myid_str[s] = NULL; + } + } + set_myid(MYID_SPECIFIED, getenv("IPSECmyid")); + set_myid(MYID_IP, getenv("defaultrouteaddr")); + set_myFQDN(); +} + +static void +calc_myid_str(enum myid_state s) +{ + /* preformat the ID name */ + char buf[IDTOA_BUF]; + + idtoa(&myids[s], buf, IDTOA_BUF); + replace(myid_str[s], clone_str(buf, "myid string")); +} + + +void +set_myid(enum myid_state s, char *idstr) +{ + if (idstr != NULL) + { + struct id id; + err_t ugh = atoid(idstr, &id, FALSE); + + if (ugh != NULL) + { + loglog(RC_BADID, "myid malformed: %s \"%s\"", ugh, idstr); + } + else + { + free_id_content(&myids[s]); + unshare_id_content(&id); + myids[s] = id; + if (s == MYID_SPECIFIED) + myid_state = MYID_SPECIFIED; + + calc_myid_str(s); + } + } +} + +void +set_myFQDN(void) +{ + char FQDN[HOST_NAME_MAX + 1]; + int r = gethostname(FQDN, sizeof(FQDN)); + + free_id_content(&myids[MYID_HOSTNAME]); + myids[MYID_HOSTNAME] = empty_id; + if (r != 0) + { + log_errno((e, "gethostname() failed in set_myFQDN")); + } + else + { + FQDN[sizeof(FQDN) - 1] = '\0'; /* insurance */ + + { + size_t len = strlen(FQDN); + + if (len > 0 && FQDN[len-1] == '.') + { + /* nuke trailing . */ + FQDN[len-1]='\0'; + } + } + + if (!strcaseeq(FQDN, "localhost.localdomain")) + { + clonetochunk(myids[MYID_HOSTNAME].name, FQDN, strlen(FQDN), "my FQDN"); + myids[MYID_HOSTNAME].kind = ID_FQDN; + calc_myid_str(MYID_HOSTNAME); + } + } +} + +/* build an ID payload + * Note: no memory is allocated for the body of the payload (tl->ptr). + * We assume it will end up being a pointer into a sufficiently + * stable datastructure. It only needs to last a short time. + */ +void +build_id_payload(struct isakmp_ipsec_id *hd, chunk_t *tl, struct end *end) +{ + const struct id *id = resolve_myid(&end->id); + + zero(hd); + zero(tl); + hd->isaiid_idtype = id->kind; + switch (id->kind) + { + case ID_NONE: + hd->isaiid_idtype = aftoinfo(addrtypeof(&end->host_addr))->id_addr; + tl->len = addrbytesptr(&end->host_addr + , (const unsigned char **)&tl->ptr); /* sets tl->ptr too */ + break; + case ID_FQDN: + case ID_USER_FQDN: + case ID_DER_ASN1_DN: + case ID_KEY_ID: + *tl = id->name; + break; + case ID_IPV4_ADDR: + case ID_IPV6_ADDR: + tl->len = addrbytesptr(&id->ip_addr + , (const unsigned char **)&tl->ptr); /* sets tl->ptr too */ + break; + default: + bad_case(id->kind); + } +} + +/* + * Local Variables: + * c-basic-offset:4 + * c-style: pluto + * End: + */ diff --git a/pool/shard006/C/0118938_iosocket_iocontrol.c b/pool/shard006/C/0118938_iosocket_iocontrol.c new file mode 100644 index 0000000000000000000000000000000000000000..cc917f34edc9707110d42ea3fc2e7180563c9757 --- /dev/null +++ b/pool/shard006/C/0118938_iosocket_iocontrol.c @@ -0,0 +1,99 @@ +/**************************************************************** + * * + * Copyright 2001, 2002 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +/* iosocket_iocontrol.c */ + +#include "mdef.h" + +#include "gtm_socket.h" +#include "gtm_inet.h" +#include "gtm_stdio.h" +#include "gtm_string.h" + +#include "io.h" +#include "iotimer.h" +#include "iotcpdef.h" +#include "gt_timer.h" +#include "iosocketdef.h" +#include "gtm_caseconv.h" + +GBLREF io_pair io_curr_device; + +void iosocket_iocontrol(mstr *d) +{ + char action[MAX_DEVCTL_LENGTH]; + unsigned short depth; /* serve as depth for LISTEN and timeout for WAIT */ + int length, n; + + error_def(ERR_INVCTLMNE); + + if (0 == d->len) + return; + memset(&action[0], 0, sizeof(action)); + if (2 != (n = SSCANF(d->addr, "%[^(](%hu)", &action[0], &depth))) + memcpy(&action[0], d->addr, d->len); + if (0 == (length = strlen(&action[0]))) + return; + lower_to_upper((uchar_ptr_t)&action[0], (uchar_ptr_t)&action[0], length); + if (0 == memcmp(&action[0], "LISTEN", length)) + { + if (2 != n) + depth = DEFAULT_LISTEN_DEPTH; + iosocket_listen(io_curr_device.out, depth); + } + else if (0 == memcmp(&action[0], "WAIT", length)) + { + if (2 != n) + depth = NO_M_TIMEOUT; + iosocket_wait(io_curr_device.out, depth); /* depth really means timeout here. */ + } + else + { + rts_error(VARLSTCNT(1) ERR_INVCTLMNE); + } + + return; +} + +void iosocket_dlr_device(mstr *d) +{ + io_desc *iod; + int len; + d_socket_struct *dsocketptr; + + iod = io_curr_device.out; + dsocketptr = (d_socket_struct *)iod->dev_sp; + + len = strlen(dsocketptr->dollar_device); + /* verify internal buffer has enough space for $DEVICE string value */ + assert((int)d->len > len); + memcpy(d->addr, dsocketptr->dollar_device, len); + d->len = len; + return; +} + +void iosocket_dlr_key(mstr *d) +{ + io_desc *iod; + int len; + d_socket_struct *dsocketptr; + + iod = io_curr_device.out; + dsocketptr = (d_socket_struct *)iod->dev_sp; + + len = strlen(dsocketptr->dollar_key); + /* verify internal buffer has enough space for $DEVICE string value */ + assert((int)d->len > len); + if (len > 0) + memcpy(d->addr, dsocketptr->dollar_key, len); + d->len = len; + return; +} diff --git a/pool/shard006/C/0118943_simulator.c b/pool/shard006/C/0118943_simulator.c new file mode 100644 index 0000000000000000000000000000000000000000..b863d13a2a6d7bb44842d6e0c40ddcc3a62b1dd5 --- /dev/null +++ b/pool/shard006/C/0118943_simulator.c @@ -0,0 +1,147 @@ +/* + simulator.c - functions to simulate how the buffer is emptied and the + stepper interrupt is called + + Part of Grbl Simulator + + Copyright (c) 2012-2014 Jens Geisler + Copyright (c) 2014-2015 Adam Shelly + + Grbl 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. + + Grbl 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 Grbl. If not, see . +*/ + +#include +#include + +#include "simulator.h" +#include "avr/eeprom.h" +#include "avr/io.h" +#include "avr/interrupt.h" + + +sim_vars_t sim={0}; + +enum {sh_INIT,sh_TICK,sh_BYTE,sh_EXIT}; +void sim_nop(void) {} +sim_hook_fp sim_hook[4]={sim_nop,sim_nop,sim_nop,sim_nop}; +void sim_add_hooks(sim_hook_fp initialize, + sim_hook_fp per_tick, + sim_hook_fp per_byte, + sim_hook_fp shutdown) +{ + if (initialize) sim_hook[sh_INIT]=initialize; + if (per_tick) sim_hook[sh_TICK]=per_tick; + if (per_byte) sim_hook[sh_BYTE]=per_byte; + if (shutdown) sim_hook[sh_EXIT]=shutdown; +} + +//setup +void init_simulator(float time_multiplier) { + sim.speedup = time_multiplier; + + sim_hook[sh_INIT](); +} + + + +//shutdown simulator - call exit hooks, save eeprom +void shutdown_simulator() { + sim_hook[sh_EXIT](); + eeprom_close(); +} + + +void simulate_hardware(bool do_serial){ + + //do one tick + sim.masterclock++; + sim.sim_time = (float)sim.masterclock/F_CPU; + + timer_interrupts(); + + if (do_serial) simulate_serial(); + + //TODO: + // check limit pins, call pinchange interrupt if enabled + // can ignore pinout int vect - hw start/hold not supported + +} + +//runs the hardware simulator at the desired rate until sim.exit is set +void sim_loop(){ + uint64_t simulated_ticks=0; + uint32_t ns_prev = platform_ns(); + uint64_t next_byte_tick = F_CPU; //wait 1 sec before reading IO. + + + while (sim.exit != exit_OK ) { //don't quit until idle + + if (sim.speedup) { + //calculate how many ticks to do. + uint32_t ns_now = platform_ns(); + uint32_t ns_elapsed = (ns_now-ns_prev)*sim.speedup; //todo: try multipling nsnow + simulated_ticks += F_CPU/1e9*ns_elapsed; + ns_prev = ns_now; + } + else { + simulated_ticks++; //as fast as possible + } + + while (sim.masterclock < simulated_ticks){ + + //only read serial port as fast as the baud rate allows + bool read_serial = (sim.masterclock >= next_byte_tick); + + //do low level hardware + simulate_hardware(read_serial); + + // do app-specific per-tick processing + sim_hook[sh_TICK](); + + if (read_serial){ + //decode baud rate. //TODO: maybe do this only once, baud shouldn't change on the fly + sim.baud_ticks = 2*((UBRR0H<<8)+UBRR0L)+1; + if (UCSR0A & (1<=127) { + if (args.comment_char && !continuation){ + fprintf(args.serial_out_file,"%c ",args.comment_char); + } + buf[len]=0; + fprintf(args.serial_out_file,"%s",buf); + //don't print comment on next line if we are just printing to avoid buffer overflow + continuation = (len>=128); + len=0; + } +} + diff --git a/pool/shard006/C/0118945_ump_ukk_ref_wrappers.c b/pool/shard006/C/0118945_ump_ukk_ref_wrappers.c new file mode 100644 index 0000000000000000000000000000000000000000..6b799826db6b0785e5379835b66d11daeeb09740 --- /dev/null +++ b/pool/shard006/C/0118945_ump_ukk_ref_wrappers.c @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2010, 2013-2014 ARM Limited. All rights reserved. + * + * This program is free software and is provided to you under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. + * + * A copy of the licence is included with the program, and can also be obtained from Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +/** + * @file ump_ukk_wrappers.c + * Defines the wrapper functions which turn Linux IOCTL calls into _ukk_ calls for the reference implementation + */ + + +#include /* user space access */ + +#include "ump_osk.h" +#include "ump_uk_types.h" +#include "ump_ukk.h" +#include "ump_kernel_common.h" + +/* + * IOCTL operation; Allocate UMP memory + */ +int ump_allocate_wrapper(u32 __user *argument, struct ump_session_data *session_data) +{ + _ump_uk_allocate_s user_interaction; + _mali_osk_errcode_t err; + + /* Sanity check input parameters */ + if (NULL == argument || NULL == session_data) { + MSG_ERR(("NULL parameter in ump_ioctl_allocate()\n")); + return -ENOTTY; + } + + /* Copy the user space memory to kernel space (so we safely can read it) */ + if (0 != copy_from_user(&user_interaction, argument, sizeof(user_interaction))) { + MSG_ERR(("copy_from_user() in ump_ioctl_allocate()\n")); + return -EFAULT; + } + + user_interaction.ctx = (void *) session_data; + + err = _ump_ukk_allocate(&user_interaction); + if (_MALI_OSK_ERR_OK != err) { + DBG_MSG(1, ("_ump_ukk_allocate() failed in ump_ioctl_allocate()\n")); + return map_errcode(err); + } + user_interaction.ctx = NULL; + + if (0 != copy_to_user(argument, &user_interaction, sizeof(user_interaction))) { + /* If the copy fails then we should release the memory. We can use the IOCTL release to accomplish this */ + _ump_uk_release_s release_args; + + MSG_ERR(("copy_to_user() failed in ump_ioctl_allocate()\n")); + + release_args.ctx = (void *) session_data; + release_args.secure_id = user_interaction.secure_id; + + err = _ump_ukk_release(&release_args); + if (_MALI_OSK_ERR_OK != err) { + MSG_ERR(("_ump_ukk_release() also failed when trying to release newly allocated memory in ump_ioctl_allocate()\n")); + } + + return -EFAULT; + } + + return 0; /* success */ +} diff --git a/pool/shard006/C/0118946_Tpm2Session.c b/pool/shard006/C/0118946_Tpm2Session.c new file mode 100644 index 0000000000000000000000000000000000000000..65b15cb23c300c91b97cb2924cb3cae86d446e26 --- /dev/null +++ b/pool/shard006/C/0118946_Tpm2Session.c @@ -0,0 +1,174 @@ +/** @file + Implement TPM2 Session related command. + +Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.
+This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +**/ + +#include +#include +#include +#include +#include +#include + +#pragma pack(1) + +typedef struct { + TPM2_COMMAND_HEADER Header; + TPMI_DH_OBJECT TpmKey; + TPMI_DH_ENTITY Bind; + TPM2B_NONCE NonceCaller; + TPM2B_ENCRYPTED_SECRET Salt; + TPM_SE SessionType; + TPMT_SYM_DEF Symmetric; + TPMI_ALG_HASH AuthHash; +} TPM2_START_AUTH_SESSION_COMMAND; + +typedef struct { + TPM2_RESPONSE_HEADER Header; + TPMI_SH_AUTH_SESSION SessionHandle; + TPM2B_NONCE NonceTPM; +} TPM2_START_AUTH_SESSION_RESPONSE; + +#pragma pack() + +/** + This command is used to start an authorization session using alternative methods of + establishing the session key (sessionKey) that is used for authorization and encrypting value. + + @param[in] TpmKey Handle of a loaded decrypt key used to encrypt salt. + @param[in] Bind Entity providing the authValue. + @param[in] NonceCaller Initial nonceCaller, sets nonce size for the session. + @param[in] Salt Value encrypted according to the type of tpmKey. + @param[in] SessionType Indicates the type of the session. + @param[in] Symmetric The algorithm and key size for parameter encryption. + @param[in] AuthHash Hash algorithm to use for the session. + @param[out] SessionHandle Handle for the newly created session. + @param[out] NonceTPM The initial nonce from the TPM, used in the computation of the sessionKey. + + @retval EFI_SUCCESS Operation completed successfully. + @retval EFI_DEVICE_ERROR The command was unsuccessful. +**/ +EFI_STATUS +EFIAPI +Tpm2StartAuthSession ( + IN TPMI_DH_OBJECT TpmKey, + IN TPMI_DH_ENTITY Bind, + IN TPM2B_NONCE *NonceCaller, + IN TPM2B_ENCRYPTED_SECRET *Salt, + IN TPM_SE SessionType, + IN TPMT_SYM_DEF *Symmetric, + IN TPMI_ALG_HASH AuthHash, + OUT TPMI_SH_AUTH_SESSION *SessionHandle, + OUT TPM2B_NONCE *NonceTPM + ) +{ + EFI_STATUS Status; + TPM2_START_AUTH_SESSION_COMMAND SendBuffer; + TPM2_START_AUTH_SESSION_RESPONSE RecvBuffer; + UINT32 SendBufferSize; + UINT32 RecvBufferSize; + UINT8 *Buffer; + + // + // Construct command + // + SendBuffer.Header.tag = SwapBytes16(TPM_ST_NO_SESSIONS); + SendBuffer.Header.commandCode = SwapBytes32(TPM_CC_StartAuthSession); + + SendBuffer.TpmKey = SwapBytes32 (TpmKey); + SendBuffer.Bind = SwapBytes32 (Bind); + Buffer = (UINT8 *)&SendBuffer.NonceCaller; + + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (NonceCaller->size)); + Buffer += sizeof(UINT16); + CopyMem (Buffer, NonceCaller->buffer, NonceCaller->size); + Buffer += NonceCaller->size; + + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Salt->size)); + Buffer += sizeof(UINT16); + CopyMem (Buffer, Salt->secret, Salt->size); + Buffer += Salt->size; + + *(TPM_SE *)Buffer = SessionType; + Buffer++; + + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->algorithm)); + Buffer += sizeof(UINT16); + switch (Symmetric->algorithm) { + case TPM_ALG_NULL: + break; + case TPM_ALG_AES: + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->keyBits.aes)); + Buffer += sizeof(UINT16); + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->mode.aes)); + Buffer += sizeof(UINT16); + break; + case TPM_ALG_SM4: + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->keyBits.SM4)); + Buffer += sizeof(UINT16); + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->mode.SM4)); + Buffer += sizeof(UINT16); + break; + case TPM_ALG_SYMCIPHER: + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->keyBits.sym)); + Buffer += sizeof(UINT16); + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->mode.sym)); + Buffer += sizeof(UINT16); + break; + case TPM_ALG_XOR: + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (Symmetric->keyBits.xor)); + Buffer += sizeof(UINT16); + break; + default: + ASSERT (FALSE); + DEBUG ((EFI_D_ERROR, "Tpm2StartAuthSession - Symmetric->algorithm - %x\n", Symmetric->algorithm)); + return EFI_UNSUPPORTED; + } + + WriteUnaligned16 ((UINT16 *)Buffer, SwapBytes16 (AuthHash)); + Buffer += sizeof(UINT16); + + SendBufferSize = (UINT32) ((UINTN)Buffer - (UINTN)&SendBuffer); + SendBuffer.Header.paramSize = SwapBytes32 (SendBufferSize); + + // + // send Tpm command + // + RecvBufferSize = sizeof (RecvBuffer); + Status = Tpm2SubmitCommand (SendBufferSize, (UINT8 *)&SendBuffer, &RecvBufferSize, (UINT8 *)&RecvBuffer); + if (EFI_ERROR (Status)) { + return Status; + } + + if (RecvBufferSize < sizeof (TPM2_RESPONSE_HEADER)) { + DEBUG ((EFI_D_ERROR, "Tpm2StartAuthSession - RecvBufferSize Error - %x\n", RecvBufferSize)); + return EFI_DEVICE_ERROR; + } + if (SwapBytes32(RecvBuffer.Header.responseCode) != TPM_RC_SUCCESS) { + DEBUG ((EFI_D_ERROR, "Tpm2StartAuthSession - responseCode - %x\n", SwapBytes32(RecvBuffer.Header.responseCode))); + return EFI_DEVICE_ERROR; + } + + // + // Return the response + // + *SessionHandle = SwapBytes32 (RecvBuffer.SessionHandle); + NonceTPM->size = SwapBytes16 (RecvBuffer.NonceTPM.size); + if (NonceTPM->size > sizeof(TPMU_HA)) { + DEBUG ((DEBUG_ERROR, "Tpm2StartAuthSession - NonceTPM->size error %x\n", NonceTPM->size)); + return EFI_DEVICE_ERROR; + } + + CopyMem (NonceTPM->buffer, &RecvBuffer.NonceTPM.buffer, NonceTPM->size); + + return EFI_SUCCESS; +} diff --git a/pool/shard006/C/0118948_save_image_png.c b/pool/shard006/C/0118948_save_image_png.c new file mode 100644 index 0000000000000000000000000000000000000000..2a39c79812d3de2154eaaa0537ba347a060742bf --- /dev/null +++ b/pool/shard006/C/0118948_save_image_png.c @@ -0,0 +1,251 @@ +/*******************************************************************************# +# guvcview http://guvcview.sourceforge.net # +# # +# Paulo Assis # +# # +# 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gviewv4l2core.h" +#include "save_image.h" +#include "colorspaces.h" + +/* + * save rgb data into png format file + * args: + * filename - string with filename + * width - image width (in pixels) + * height - image height (in pixels) + * data -pointer to rgb data to save + * + * asserts: + * data is not null + * + * returns: error code + */ +static int save_png(const char *filename, int width, int height, uint8_t *data) +{ + /*assertions*/ + assert(data != NULL); + + int l=0; + FILE *fp; + png_structp png_ptr; + png_infop info_ptr; + png_text text_ptr[3]; + + png_bytep row_pointers[height]; + /* open the file */ + fp = fopen(filename, "wb"); + if (fp == NULL) + return (E_FILE_IO_ERR); + + /* + * Create and initialize the png_struct with the desired error handler + * functions. If you want to use the default stderr and longjump method, + * you can supply NULL for the last three parameters. We also check that + * the library version is compatible with the one used at compile time, + * in case we are using dynamically linked libraries. + */ + png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, + NULL, NULL, NULL); + + if (png_ptr == NULL) + { + fclose(fp); + return (E_ALLOC_ERR); + } + + /* Allocate/initialize the image information data. */ + info_ptr = png_create_info_struct(png_ptr); + if (info_ptr == NULL) + { + fclose(fp); + png_destroy_write_struct(&png_ptr, NULL); + return (E_ALLOC_ERR); + } + + /* Set error handling. REQUIRED if you aren't supplying your own + * error handling functions in the png_create_write_struct() call. + */ + if (setjmp(png_jmpbuf(png_ptr))) + { + fclose(fp); + png_destroy_write_struct(&png_ptr, &info_ptr); + return (E_ALLOC_ERR); + } + + /* set up the output control using standard C streams */ + png_init_io(png_ptr, fp); + + /* + * turn on or off filtering, and/or choose + * specific filters. You can use either a single + * PNG_FILTER_VALUE_NAME or the bitwise OR of one + * or more PNG_FILTER_NAME masks. + */ + //png_set_filter(png_ptr, 0, + // PNG_FILTER_NONE | PNG_FILTER_VALUE_NONE | + // PNG_FILTER_SUB | PNG_FILTER_VALUE_SUB | + // PNG_FILTER_UP | PNG_FILTER_VALUE_UP | + // PNG_FILTER_AVE | PNG_FILTER_VALUE_AVE | + // PNG_FILTER_PAETH | PNG_FILTER_VALUE_PAETH| + // PNG_ALL_FILTERS); + + /* set the zlib compression level */ + //png_set_compression_level(png_ptr, + // Z_BEST_COMPRESSION); + + /* set other zlib parameters */ + //png_set_compression_mem_level(png_ptr, 8); + //png_set_compression_strategy(png_ptr, + // Z_DEFAULT_STRATEGY); + //png_set_compression_window_bits(png_ptr, 15); + //png_set_compression_method(png_ptr, 8); + //png_set_compression_buffer_size(png_ptr, 8192); + + png_set_IHDR(png_ptr, info_ptr, width, height, + 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, + PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); + + /* + * Optional gamma chunk is strongly suggested if you have any guess + * as to the correct gamma of the image. + */ + //png_set_gAMA(png_ptr, info_ptr, gamma); + + /* Optionally write comments into the image */ + text_ptr[0].key = "Title"; + text_ptr[0].text = (char *) filename; + text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE; + text_ptr[1].key = "Software"; + text_ptr[1].text = "guvcview"; + text_ptr[1].compression = PNG_TEXT_COMPRESSION_NONE; + text_ptr[2].key = "Description"; + text_ptr[2].text = "File generated by guvcview "; + text_ptr[2].compression = PNG_TEXT_COMPRESSION_NONE; +#ifdef PNG_iTXt_SUPPORTED + text_ptr[0].lang = NULL; + text_ptr[1].lang = NULL; + text_ptr[2].lang = NULL; +#endif + png_set_text(png_ptr, info_ptr, text_ptr, 3); + + /* Write the file header information. REQUIRED */ + png_write_info(png_ptr, info_ptr); + + /* flip BGR pixels to RGB */ + //png_set_bgr(png_ptr); /*?no longuer required?*/ + + /* Write the image data.*/ + for (l = 0; l < height; l++) + row_pointers[l] = data + l * width * 3; + + png_write_image(png_ptr, row_pointers); + + /* + * You can write optional chunks like tEXt, zTXt, and tIME at the end + * as well. Shouldn't be necessary in 1.1.0 and up as all the public + * chunks are supported and you can use png_set_unknown_chunks() to + * register unknown chunks into the info structure to be written out. + */ + + /* It is REQUIRED to call this to finish writing the rest of the file */ + png_write_end(png_ptr, info_ptr); + + /* + * If you png_malloced a palette, free it here + * (don't free info_ptr->palette, as recommended in versions 1.0.5m + * and earlier of this example; + * if libpng mallocs info_ptr->palette, libpng will free it). + * If you allocated it with malloc() instead of png_malloc(), + * use free() instead of png_free(). + */ + //png_free(png_ptr, palette); + //palette=NULL; + + /* + * Similarly, if you png_malloced any data that you passed in with + * png_set_something(), such as a hist or trans array, free it here, + * when you can be sure that libpng is through with it. + */ + //png_free(png_ptr, trans); + //trans=NULL; + + /* clean up after the write, and free any memory allocated */ + png_destroy_write_struct(&png_ptr, &info_ptr); + + /* close the file */ + fflush(fp); //flush data stream to file system + if(fsync(fileno(fp)) || fclose(fp)) + { + fprintf(stderr, "V4L2_CORE: (save png) couldn't write to file: %s\n", strerror(errno)); + return(E_FILE_IO_ERR); + } + + /* that's it */ + return (E_OK); +} + +/* + * save frame data into a png file + * args: + * vd - pointer to device data + * frame - pointer to frame buffer + * filename - string with png filename name + * + * asserts: + * vd is not null + * + * returns: error code + */ +int save_image_png(v4l2_dev_t *vd, v4l2_frame_buff_t *frame, const char *filename) +{ + /*assertions*/ + assert(vd != NULL); + + int width = vd->format.fmt.pix.width; + int height = vd->format.fmt.pix.height; + + uint8_t *rgb = calloc( width * height * 3, sizeof(uint8_t)); + if(rgb == NULL) + { + fprintf(stderr, "V4L2_CORE: FATAL memory allocation failure (save_image_png): %s\n", strerror(errno)); + exit(-1); + } +#ifdef USE_PLANAR_YUV + yu12_to_rgb24(rgb, frame->yuv_frame, width, height); +#else + yuyv2rgb(frame->yuv_frame, rgb, width, height); +#endif + + int ret = save_png(filename, width, height, rgb); + + free(rgb); + + return ret; +} diff --git a/pool/shard006/C/0118949_setid.c b/pool/shard006/C/0118949_setid.c new file mode 100644 index 0000000000000000000000000000000000000000..eddc8d3c92c7e3f57e321ca0ed32e3dd05ee6fcb --- /dev/null +++ b/pool/shard006/C/0118949_setid.c @@ -0,0 +1,226 @@ +/***************************************************************************** + * setid.c: set ID/lang on a stream + ***************************************************************************** + * Copyright © 2009-2011 VLC authors and VideoLAN + * + * Authors: Christophe Massiot + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. + *****************************************************************************/ + +/***************************************************************************** + * Preamble + *****************************************************************************/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include + +#include +#include +#include + +/***************************************************************************** + * Module descriptor + *****************************************************************************/ +#define ID_TEXT N_("Elementary Stream ID") +#define ID_LONGTEXT N_( \ + "Specify an identifier integer for this elementary stream" ) + +#define NEWID_TEXT N_("New ES ID") +#define NEWID_LONGTEXT N_( \ + "Specify an new identifier integer for this elementary stream" ) + +#define LANG_TEXT N_("Language") +#define LANG_LONGTEXT N_( \ + "Specify an ISO-639 code (three characters) for this elementary stream" ) + +static int OpenId ( vlc_object_t * ); +static int OpenLang ( vlc_object_t * ); +static void Close ( vlc_object_t * ); + +#define SOUT_CFG_PREFIX_ID "sout-setid-" +#define SOUT_CFG_PREFIX_LANG "sout-setlang-" + +vlc_module_begin() + set_shortname( N_("Set ID")) + set_section( N_("Set ES id"), NULL ) + set_description( N_("Change the id of an elementary stream")) + set_capability( "sout stream", 50 ) + add_shortcut( "setid" ) + set_category( CAT_SOUT ) + set_subcategory( SUBCAT_SOUT_STREAM ) + set_callbacks( OpenId, Close ) + add_integer( SOUT_CFG_PREFIX_ID "id", 0, ID_TEXT, ID_LONGTEXT, false ) + add_integer( SOUT_CFG_PREFIX_ID "new-id", 0, NEWID_TEXT, NEWID_LONGTEXT, + false ) + + add_submodule () + set_section( N_("Set ES Lang"), NULL ) + set_shortname( N_("Set Lang")) + set_description( N_("Change the language of an elementary stream")) + set_capability( "sout stream", 50 ) + add_shortcut( "setlang" ); + set_callbacks( OpenLang, Close ) + add_integer( SOUT_CFG_PREFIX_LANG "id", 0, ID_TEXT, ID_LONGTEXT, false ) + add_string( SOUT_CFG_PREFIX_LANG "lang", "eng", LANG_TEXT, LANG_LONGTEXT, + false ); + +vlc_module_end() + + +/***************************************************************************** + * Local prototypes + *****************************************************************************/ +static const char *ppsz_sout_options_id[] = { + "id", "new-id", NULL +}; + +static const char *ppsz_sout_options_lang[] = { + "id", "lang", NULL +}; + +static sout_stream_id_t *AddId ( sout_stream_t *, es_format_t * ); +static sout_stream_id_t *AddLang ( sout_stream_t *, es_format_t * ); +static int Del ( sout_stream_t *, sout_stream_id_t * ); +static int Send ( sout_stream_t *, sout_stream_id_t *, block_t * ); + +struct sout_stream_sys_t +{ + int i_id; + int i_new_id; + char *psz_language; +}; + +/***************************************************************************** + * Open: + *****************************************************************************/ +static int OpenCommon( vlc_object_t *p_this ) +{ + sout_stream_t *p_stream = (sout_stream_t*)p_this; + sout_stream_sys_t *p_sys; + + if( !p_stream->p_next ) + { + msg_Err( p_stream, "cannot create chain" ); + return VLC_EGENERIC; + } + + p_sys = malloc( sizeof( sout_stream_sys_t ) ); + if( unlikely( !p_sys ) ) + return VLC_ENOMEM; + + p_stream->pf_del = Del; + p_stream->pf_send = Send; + + p_stream->p_sys = p_sys; + + return VLC_SUCCESS; +} + +static int OpenId( vlc_object_t *p_this ) +{ + int i_ret = OpenCommon( p_this ); + if( i_ret != VLC_SUCCESS ) + return i_ret; + + sout_stream_t *p_stream = (sout_stream_t*)p_this; + + config_ChainParse( p_stream, SOUT_CFG_PREFIX_ID, ppsz_sout_options_id, + p_stream->p_cfg ); + + p_stream->p_sys->i_id = var_GetInteger( p_stream, SOUT_CFG_PREFIX_ID "id" ); + p_stream->p_sys->i_new_id = var_GetInteger( p_stream, SOUT_CFG_PREFIX_ID "new-id" ); + p_stream->p_sys->psz_language = NULL; + + p_stream->pf_add = AddId; + + return VLC_SUCCESS; +} + +static int OpenLang( vlc_object_t *p_this ) +{ + int i_ret = OpenCommon( p_this ); + if( i_ret != VLC_SUCCESS ) + return i_ret; + + sout_stream_t *p_stream = (sout_stream_t*)p_this; + + config_ChainParse( p_stream, SOUT_CFG_PREFIX_LANG, ppsz_sout_options_lang, + p_stream->p_cfg ); + + p_stream->p_sys->i_id = var_GetInteger( p_stream, SOUT_CFG_PREFIX_LANG "id" ); + p_stream->p_sys->i_new_id = -1; + p_stream->p_sys->psz_language = var_GetString( p_stream, SOUT_CFG_PREFIX_LANG "lang" ); + + p_stream->pf_add = AddLang; + + return VLC_SUCCESS; +} + +/***************************************************************************** + * Close: + *****************************************************************************/ +static void Close( vlc_object_t * p_this ) +{ + sout_stream_t *p_stream = (sout_stream_t*)p_this; + sout_stream_sys_t *p_sys = (sout_stream_sys_t *)p_stream->p_sys; + + free( p_sys->psz_language ); + free( p_sys ); +} + +static sout_stream_id_t * AddId( sout_stream_t *p_stream, es_format_t *p_fmt ) +{ + sout_stream_sys_t *p_sys = (sout_stream_sys_t *)p_stream->p_sys; + + if ( p_fmt->i_id == p_sys->i_id ) + { + msg_Dbg( p_stream, "turning ID %d to %d", + p_sys->i_id, p_sys->i_new_id ); + p_fmt->i_id = p_sys->i_new_id; + } + + return p_stream->p_next->pf_add( p_stream->p_next, p_fmt ); +} + +static sout_stream_id_t * AddLang( sout_stream_t *p_stream, es_format_t *p_fmt ) +{ + sout_stream_sys_t *p_sys = (sout_stream_sys_t *)p_stream->p_sys; + + if ( p_fmt->i_id == p_sys->i_id ) + { + msg_Dbg( p_stream, "turning language %s of ID %d to %s", + p_fmt->psz_language ? p_fmt->psz_language : "unk", + p_sys->i_id, p_sys->psz_language ); + p_fmt->psz_language = strdup( p_sys->psz_language ); + } + + return p_stream->p_next->pf_add( p_stream->p_next, p_fmt ); +} + +static int Del( sout_stream_t *p_stream, sout_stream_id_t *id ) +{ + return p_stream->p_next->pf_del( p_stream->p_next, id ); +} + +static int Send( sout_stream_t *p_stream, sout_stream_id_t *id, + block_t *p_buffer ) +{ + return p_stream->p_next->pf_send( p_stream->p_next, id, p_buffer ); +} diff --git a/pool/shard006/C/0118952_ext-gpio.c b/pool/shard006/C/0118952_ext-gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..aa51ef75ce2d24b7b58cffa7eba5e1e323e3af61 --- /dev/null +++ b/pool/shard006/C/0118952_ext-gpio.c @@ -0,0 +1,158 @@ +/* + * GPIOLIB interface for BF538/9 PORT C, D, and E GPIOs + * + * Copyright 2009-2011 Analog Devices Inc. + * + * Licensed under the GPL-2 or later. + */ + +#include +#include +#include +#include +#include + +#define DEFINE_REG(reg, off) \ +static inline u16 read_##reg(void __iomem *port) \ + { return bfin_read16(port + off); } \ +static inline void write_##reg(void __iomem *port, u16 v) \ + { bfin_write16(port + off, v); } + +DEFINE_REG(PORTIO, 0x00) +DEFINE_REG(PORTIO_CLEAR, 0x10) +DEFINE_REG(PORTIO_SET, 0x20) +DEFINE_REG(PORTIO_DIR, 0x40) +DEFINE_REG(PORTIO_INEN, 0x50) + +static void __iomem *gpio_chip_to_mmr(struct gpio_chip *chip) +{ + switch (chip->base) { + default: /* not really needed, but keeps gcc happy */ + case GPIO_PC0: return (void __iomem *)PORTCIO; + case GPIO_PD0: return (void __iomem *)PORTDIO; + case GPIO_PE0: return (void __iomem *)PORTEIO; + } +} + +static int bf538_gpio_get_value(struct gpio_chip *chip, unsigned gpio) +{ + void __iomem *port = gpio_chip_to_mmr(chip); + return !!(read_PORTIO(port) & (1u << gpio)); +} + +static void bf538_gpio_set_value(struct gpio_chip *chip, unsigned gpio, int value) +{ + void __iomem *port = gpio_chip_to_mmr(chip); + if (value) + write_PORTIO_SET(port, (1u << gpio)); + else + write_PORTIO_CLEAR(port, (1u << gpio)); +} + +static int bf538_gpio_direction_input(struct gpio_chip *chip, unsigned gpio) +{ + void __iomem *port = gpio_chip_to_mmr(chip); + write_PORTIO_DIR(port, read_PORTIO_DIR(port) & ~(1u << gpio)); + write_PORTIO_INEN(port, read_PORTIO_INEN(port) | (1u << gpio)); + return 0; +} + +static int bf538_gpio_direction_output(struct gpio_chip *chip, unsigned gpio, int value) +{ + void __iomem *port = gpio_chip_to_mmr(chip); + write_PORTIO_INEN(port, read_PORTIO_INEN(port) & ~(1u << gpio)); + bf538_gpio_set_value(port, gpio, value); + write_PORTIO_DIR(port, read_PORTIO_DIR(port) | (1u << gpio)); + return 0; +} + +static int bf538_gpio_request(struct gpio_chip *chip, unsigned gpio) +{ + return bfin_special_gpio_request(chip->base + gpio, chip->label); +} + +static void bf538_gpio_free(struct gpio_chip *chip, unsigned gpio) +{ + return bfin_special_gpio_free(chip->base + gpio); +} + +/* We don't set the irq fields as these banks cannot generate interrupts */ + +static struct gpio_chip bf538_portc_chip = { + .label = "GPIO-PC", + .direction_input = bf538_gpio_direction_input, + .get = bf538_gpio_get_value, + .direction_output = bf538_gpio_direction_output, + .set = bf538_gpio_set_value, + .request = bf538_gpio_request, + .free = bf538_gpio_free, + .base = GPIO_PC0, + .ngpio = GPIO_PC9 - GPIO_PC0 + 1, +}; + +static struct gpio_chip bf538_portd_chip = { + .label = "GPIO-PD", + .direction_input = bf538_gpio_direction_input, + .get = bf538_gpio_get_value, + .direction_output = bf538_gpio_direction_output, + .set = bf538_gpio_set_value, + .request = bf538_gpio_request, + .free = bf538_gpio_free, + .base = GPIO_PD0, + .ngpio = GPIO_PD13 - GPIO_PD0 + 1, +}; + +static struct gpio_chip bf538_porte_chip = { + .label = "GPIO-PE", + .direction_input = bf538_gpio_direction_input, + .get = bf538_gpio_get_value, + .direction_output = bf538_gpio_direction_output, + .set = bf538_gpio_set_value, + .request = bf538_gpio_request, + .free = bf538_gpio_free, + .base = GPIO_PE0, + .ngpio = GPIO_PE15 - GPIO_PE0 + 1, +}; + +static int __init bf538_extgpio_setup(void) +{ + return gpiochip_add(&bf538_portc_chip) | + gpiochip_add(&bf538_portd_chip) | + gpiochip_add(&bf538_porte_chip); +} +arch_initcall(bf538_extgpio_setup); + +#ifdef CONFIG_PM +static struct { + u16 data, dir, inen; +} gpio_bank_saved[3]; + +static void __iomem * const port_bases[3] = { + (void *)PORTCIO, + (void *)PORTDIO, + (void *)PORTEIO, +}; + +void bfin_special_gpio_pm_hibernate_suspend(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(port_bases); ++i) { + gpio_bank_saved[i].data = read_PORTIO(port_bases[i]); + gpio_bank_saved[i].inen = read_PORTIO_INEN(port_bases[i]); + gpio_bank_saved[i].dir = read_PORTIO_DIR(port_bases[i]); + } +} + +void bfin_special_gpio_pm_hibernate_restore(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(port_bases); ++i) { + write_PORTIO_INEN(port_bases[i], gpio_bank_saved[i].inen); + write_PORTIO_SET(port_bases[i], + gpio_bank_saved[i].data & gpio_bank_saved[i].dir); + write_PORTIO_DIR(port_bases[i], gpio_bank_saved[i].dir); + } +} +#endif diff --git a/pool/shard006/C/0118954_st-drawing-area.c b/pool/shard006/C/0118954_st-drawing-area.c new file mode 100644 index 0000000000000000000000000000000000000000..f044cbf310e0dcbfa19b38a6e518a520b6189bbc --- /dev/null +++ b/pool/shard006/C/0118954_st-drawing-area.c @@ -0,0 +1,268 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ +/* + * st-drawing-area.c: A dynamically-sized Cairo drawing area + * + * Copyright 2009, 2010 Red Hat, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +/** + * SECTION:st-drawing-area + * @short_description: A dynamically-sized Cairo drawing area + * + * #StDrawingArea is similar to #ClutterCairoTexture in that + * it allows drawing via Cairo; the primary difference is that + * it is dynamically sized. To use, connect to the #StDrawingArea::repaint + * signal, and inside the signal handler, call + * st_drawing_area_get_context() to get the Cairo context to draw to. The + * #StDrawingArea::repaint signal will be emitted by default when the area is + * resized or the CSS style changes; you can use the + * st_drawing_area_queue_repaint() as well. + */ + +#include "st-drawing-area.h" + +#include + +G_DEFINE_TYPE(StDrawingArea, st_drawing_area, ST_TYPE_WIDGET); + +struct _StDrawingAreaPrivate { + CoglHandle texture; + CoglHandle material; + cairo_t *context; + guint needs_repaint : 1; + guint in_repaint : 1; +}; + +/* Signals */ +enum +{ + REPAINT, + LAST_SIGNAL +}; + +static guint st_drawing_area_signals [LAST_SIGNAL] = { 0 }; + +static void +st_drawing_area_dispose (GObject *object) +{ + StDrawingArea *area = ST_DRAWING_AREA (object); + StDrawingAreaPrivate *priv = area->priv; + + if (priv->material != COGL_INVALID_HANDLE) + { + cogl_handle_unref (priv->material); + priv->material = COGL_INVALID_HANDLE; + } + + if (priv->texture != COGL_INVALID_HANDLE) + { + cogl_handle_unref (priv->texture); + priv->texture = COGL_INVALID_HANDLE; + } + + G_OBJECT_CLASS (st_drawing_area_parent_class)->dispose (object); +} + +static void +st_drawing_area_paint (ClutterActor *self) +{ + StDrawingArea *area = ST_DRAWING_AREA (self); + StDrawingAreaPrivate *priv = area->priv; + StThemeNode *theme_node = st_widget_get_theme_node (ST_WIDGET (self)); + ClutterActorBox allocation_box; + ClutterActorBox content_box; + int width, height; + CoglColor color; + guint8 paint_opacity; + + (CLUTTER_ACTOR_CLASS (st_drawing_area_parent_class))->paint (self); + + clutter_actor_get_allocation_box (self, &allocation_box); + st_theme_node_get_content_box (theme_node, &allocation_box, &content_box); + + width = (int)(0.5 + content_box.x2 - content_box.x1); + height = (int)(0.5 + content_box.y2 - content_box.y1); + + if (priv->material == COGL_INVALID_HANDLE) + priv->material = cogl_material_new (); + + if (priv->texture != COGL_INVALID_HANDLE && + (width != cogl_texture_get_width (priv->texture) || + height != cogl_texture_get_height (priv->texture))) + { + cogl_handle_unref (priv->texture); + priv->texture = COGL_INVALID_HANDLE; + } + + if (width > 0 && height > 0) + { + if (priv->texture == COGL_INVALID_HANDLE) + { + priv->texture = cogl_texture_new_with_size (width, height, + COGL_TEXTURE_NONE, + CLUTTER_CAIRO_FORMAT_ARGB32); + priv->needs_repaint = TRUE; + } + + if (priv->needs_repaint) + { + cairo_surface_t *surface; + + surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); + priv->context = cairo_create (surface); + priv->in_repaint = TRUE; + priv->needs_repaint = FALSE; + + g_signal_emit ((GObject*)area, st_drawing_area_signals[REPAINT], 0); + + priv->in_repaint = FALSE; + cairo_destroy (priv->context); + priv->context = NULL; + + cogl_texture_set_region (priv->texture, 0, 0, 0, 0, width, height, width, height, + CLUTTER_CAIRO_FORMAT_ARGB32, + cairo_image_surface_get_stride (surface), + cairo_image_surface_get_data (surface)); + + cairo_surface_destroy (surface); + } + } + + cogl_material_set_layer (priv->material, 0, priv->texture); + + if (priv->texture) + { + paint_opacity = clutter_actor_get_paint_opacity (self); + cogl_color_set_from_4ub (&color, + paint_opacity, paint_opacity, paint_opacity, paint_opacity); + cogl_material_set_color (priv->material, &color); + + cogl_set_source (priv->material); + cogl_rectangle_with_texture_coords (content_box.x1, content_box.y1, + content_box.x2, content_box.y2, + 0.0f, 0.0f, 1.0f, 1.0f); + } +} + +static void +st_drawing_area_style_changed (StWidget *self) +{ + StDrawingArea *area = ST_DRAWING_AREA (self); + StDrawingAreaPrivate *priv = area->priv; + + (ST_WIDGET_CLASS (st_drawing_area_parent_class))->style_changed (self); + + priv->needs_repaint = TRUE; +} + +static void +st_drawing_area_class_init (StDrawingAreaClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + ClutterActorClass *actor_class = CLUTTER_ACTOR_CLASS (klass); + StWidgetClass *widget_class = ST_WIDGET_CLASS (klass); + + gobject_class->dispose = st_drawing_area_dispose; + actor_class->paint = st_drawing_area_paint; + widget_class->style_changed = st_drawing_area_style_changed; + + st_drawing_area_signals[REPAINT] = + g_signal_new ("repaint", + G_TYPE_FROM_CLASS (klass), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (StDrawingAreaClass, repaint), + NULL, NULL, NULL, + G_TYPE_NONE, 0); + + g_type_class_add_private (gobject_class, sizeof (StDrawingAreaPrivate)); +} + +static void +st_drawing_area_init (StDrawingArea *area) +{ + area->priv = G_TYPE_INSTANCE_GET_PRIVATE (area, ST_TYPE_DRAWING_AREA, + StDrawingAreaPrivate); + area->priv->texture = COGL_INVALID_HANDLE; +} + +/** + * st_drawing_area_queue_repaint: + * @area: the #StDrawingArea + * + * Will cause the actor to emit a ::repaint signal before it is next + * drawn to the scene. Useful if some parameters for the area being + * drawn other than the size or style have changed. Note that + * clutter_actor_queue_redraw() will simply result in the same + * contents being drawn to the scene again. + */ +void +st_drawing_area_queue_repaint (StDrawingArea *area) +{ + StDrawingAreaPrivate *priv; + + g_return_if_fail (ST_IS_DRAWING_AREA (area)); + + priv = area->priv; + + priv->needs_repaint = TRUE; + clutter_actor_queue_redraw (CLUTTER_ACTOR (area)); +} + +/** + * st_drawing_area_get_context: + * @area: the #StDrawingArea + * + * Gets the Cairo context to paint to. This function must only be called + * from a signal hander for the ::repaint signal. + * + * Return Value: (transfer none): the Cairo context for the paint operation + */ +cairo_t * +st_drawing_area_get_context (StDrawingArea *area) +{ + g_return_val_if_fail (ST_IS_DRAWING_AREA (area), NULL); + g_return_val_if_fail (area->priv->in_repaint, NULL); + + return area->priv->context; +} + +/** + * st_drawing_area_get_surface_size: + * @area: the #StDrawingArea + * @width: (out): location to store the width of the painted area + * @height: (out): location to store the height of the painted area + * + * Gets the size of the cairo surface being painted to, which is equal + * to the size of the content area of the widget. This function must + * only be called from a signal hander for the ::repaint signal. + */ +void +st_drawing_area_get_surface_size (StDrawingArea *area, + guint *width, + guint *height) +{ + StDrawingAreaPrivate *priv; + + g_return_if_fail (ST_IS_DRAWING_AREA (area)); + g_return_if_fail (area->priv->in_repaint); + + priv = area->priv; + + if (width) + *width = cogl_texture_get_width (priv->texture); + if (height) + *height = cogl_texture_get_height (priv->texture); +} diff --git a/pool/shard006/C/0118957_rtas_hotplug.c b/pool/shard006/C/0118957_rtas_hotplug.c new file mode 100644 index 0000000000000000000000000000000000000000..c9658c67751aa4d3ebc8057983f00b2f77676edd --- /dev/null +++ b/pool/shard006/C/0118957_rtas_hotplug.c @@ -0,0 +1,95 @@ +/** + * @file rtas_hotplug.c + * @brief RTAS version 6 Hotplug section routines + * + * Copyright (C) 2013 IBM Corporation + * Common Public License Version 1.0 (see COPYRIGHT) + * + * @author Tyrel Datwyler + */ + +#include +#include +#include +#include + +#include "librtasevent.h" +#include "rtas_event.h" + +/** + * parse_hotplug_scn + * + */ +int +parse_hotplug_scn(struct rtas_event *re) +{ + struct rtas_hotplug_scn *hotplug; + + hotplug = malloc(sizeof(*hotplug)); + if (hotplug == NULL) { + errno = ENOMEM; + return -1; + } + + hotplug->shdr.raw_offset = re->offset; + + rtas_copy(RE_SHDR_OFFSET(hotplug), re, RE_HOTPLUG_SCN_SZ); + add_re_scn(re, hotplug, RTAS_HP_SCN); + + /* TODO: Fixup scn size when drc_name is included */ + + return 0; +} + +/** + * rtas_get_hotplug_scn + * @brief Retrieve the Hotplug section of the RTAS Event + * + * @param re rtas_event pointer + * @return rtas_event_scn pointer to Hotplug section + */ +struct rtas_hotplug_scn * +rtas_get_hotplug_scn(struct rtas_event *re) +{ + return (struct rtas_hotplug_scn *)get_re_scn(re, RTAS_HP_SCN); +} + +/** + * print_re_hotplug_scn + * @brief Print the contents of a version 6 Hotplug section + * + * @param res rtas_event_scn pointer for Hotplug section + * @param verbosity verbose level of output + * @return number of bytes written + */ +int +print_re_hotplug_scn(struct scn_header *shdr, int verbosity) +{ + struct rtas_hotplug_scn *hotplug; + int len = 0; + + if (shdr->scn_id != RTAS_HP_SCN) { + errno = EFAULT; + return 0; + } + + hotplug = (struct rtas_hotplug_scn *)shdr; + + len += print_v6_hdr("Hotplug section", &hotplug->v6hdr, verbosity); + len += rtas_print(PRNT_FMT_R, "Hotplug Type:", hotplug->type); + + len += rtas_print(PRNT_FMT_R, "Hotplug Action:", hotplug->action); + + len += rtas_print(PRNT_FMT_R, "Hotplug Identifier:", hotplug->identifier); + + if (hotplug->identifier == RTAS_HP_ID_DRC_NAME) { + len += rtas_print("%-20s%s", "Hotplug drc_name:", hotplug->u1.drc_name); + } else if (hotplug->identifier == RTAS_HP_ID_DRC_INDEX) { + len += rtas_print(PRNT_FMT_R, "Hotplug drc_index:", hotplug->u1.drc_index); + } else { + len += rtas_print(PRNT_FMT_R, "Hotplug count:", hotplug->u1.count); + } + + len += rtas_print("\n"); + return len; +} diff --git a/pool/shard006/C/0118958_pic.c b/pool/shard006/C/0118958_pic.c new file mode 100644 index 0000000000000000000000000000000000000000..66ce8733d6536f5136a0cffe07601420d3fcee4c --- /dev/null +++ b/pool/shard006/C/0118958_pic.c @@ -0,0 +1,179 @@ +/* pic.c -- Simulation of OpenRISC 1000 programmable interrupt controller + + Copyright (C) 1999 Damjan Lampret, lampret@opencores.org + Copyright (C) 2008 Embecosm Limited + Copyright (C) 2009 Stefan Wallentowitz, stefan.wallentowitz@tum.de + + Contributor Jeremy Bennett + + This file is part of OpenRISC 1000 Architectural Simulator. + + 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 . */ + +/* This program is commented throughout in a fashion suitable for processing + with Doxygen. */ + + +/* Autoconf and/or portability configuration */ +#include "config.h" +#include "port.h" + +/* System includes */ +#include +#include + +/* Package includes */ +#include "arch.h" +#include "abstract.h" +#include "pic.h" +#include "opcode/or32.h" +#include "spr-defs.h" +#include "execute.h" +#include "except.h" +#include "sprs.h" +#include "sim-config.h" +#include "sched.h" + + +/* Reset. It initializes PIC registers. */ +void +pic_reset (or1ksim *sim) +{ + PRINTF ("Resetting PIC.\n"); + sim->cpu_state.sprs[SPR_PICMR] = 0; + sim->cpu_state.sprs[SPR_PICPR] = 0; + sim->cpu_state.sprs[SPR_PICSR] = 0; +} + +/* Handles the reporting of an interrupt if it had to be delayed */ +static void +pic_rep_int (or1ksim *sim,void *dat) +{ + if (sim->cpu_state.sprs[SPR_PICSR]) + { + except_handle (sim,EXCEPT_INT, sim->cpu_state.sprs[SPR_EEAR_BASE]); + } +} + +/* Called whenever interrupts get enabled */ +void +pic_ints_en (or1ksim *sim) +{ + if ((sim->cpu_state.sprs[SPR_PICMR] & sim->cpu_state.sprs[SPR_PICSR])) + SCHED_ADD (pic_rep_int, NULL, 0); +} + +/* Asserts interrupt to the PIC. */ +/* WARNING: If this is called during a simulated instruction (ie. from a read/ + * write mem callback), the interrupt will be delivered after the instruction + * has finished executeing */ +void +report_interrupt (or1ksim *sim,int line) +{ + uint32_t lmask = 1 << line; + + /* Disable doze and sleep mode */ + sim->cpu_state.sprs[SPR_PMR] &= ~(SPR_PMR_DME | SPR_PMR_SME); + + /* If PIC is disabled, don't set any register, just raise EXCEPT_INT */ + if (!sim->config.pic.enabled) + { + if (sim->cpu_state.sprs[SPR_SR] & SPR_SR_IEE) + except_handle (sim, EXCEPT_INT, sim->cpu_state.sprs[SPR_EEAR_BASE]); + return; + } + + if (sim->cpu_state.pic_lines & lmask) + { + /* No edge occured, warn about performance penalty and exit */ + fprintf (stderr, "Warning: Int line %d did not change state\n", line); + return; + } + + sim->cpu_state.pic_lines |= lmask; + sim->cpu_state.sprs[SPR_PICSR] |= lmask; + + if ((sim->cpu_state.sprs[SPR_PICMR] & lmask) || line < 2) + if (sim->cpu_state.sprs[SPR_SR] & SPR_SR_IEE) + SCHED_ADD (pic_rep_int, NULL, 0); +} + +/* Clears an int on a pic line */ +void +clear_interrupt (or1ksim *sim,int line) +{ + sim->cpu_state.pic_lines &= ~(1 << line); + + if (!sim->config.pic.edge_trigger) + sim->cpu_state.sprs[SPR_PICSR] &= ~(1 << line); +} + +/*----------------------------------------------------[ PIC configuration ]---*/ + + +/*---------------------------------------------------------------------------*/ +/*!Enable or disable the programmable interrupt controller + + Set the corresponding field in the UPR + + @param[in] val The value to use + @param[in] dat The config data structure (not used here) */ +/*---------------------------------------------------------------------------*/ +static void +pic_enabled (or1ksim *sim,union param_val val, + void *dat) +{ + if (val.int_val) + { + sim->cpu_state.sprs[SPR_UPR] |= SPR_UPR_PICP; + } + else + { + sim->cpu_state.sprs[SPR_UPR] &= ~SPR_UPR_PICP; + } + + sim->config.pic.enabled = val.int_val; + +} /* pic_enabled() */ + + +/*---------------------------------------------------------------------------*/ +/*!Enable or disable edge triggering of interrupts + + @param[in] val The value to use + @param[in] dat The config data structure (not used here) */ +/*---------------------------------------------------------------------------*/ +static void +pic_edge_trigger (or1ksim *sim,union param_val val, + void *dat) +{ + sim->config.pic.edge_trigger = val.int_val; + +} /* pic_edge_trigger() */ + + +/*---------------------------------------------------------------------------*/ +/*!Initialize a new interrupt controller configuration + + ALL parameters are set explicitly to default values in init_defconfig() */ +/*---------------------------------------------------------------------------*/ +void +reg_pic_sec (or1ksim *sim) +{ + struct config_section *sec = reg_config_sec (sim, "pic", NULL, NULL); + + reg_config_param (sec, "enabled", paramt_int, pic_enabled); + reg_config_param (sec, "edge_trigger", paramt_int, pic_edge_trigger); + +} /* reg_pic_sec() */ diff --git a/pool/shard006/C/0118959_type_logic.c b/pool/shard006/C/0118959_type_logic.c new file mode 100644 index 0000000000000000000000000000000000000000..d126d7b420cd058aa89f5ec248c4aef1e8339313 --- /dev/null +++ b/pool/shard006/C/0118959_type_logic.c @@ -0,0 +1,97 @@ +/* + * This file is part of the libsigrokdecode project. + * + * Copyright (C) 2012 Bert Vermeulen + * + * 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 . + */ + +#include +#include "libsigrokdecode-internal.h" /* First, so we avoid a _POSIX_C_SOURCE warning. */ +#include "libsigrokdecode.h" +#include +#include + +static PyObject *srd_logic_iter(PyObject *self) +{ + return self; +} + +static PyObject *srd_logic_iternext(PyObject *self) +{ + srd_logic *logic; + PyObject *py_samplenum, *py_samples; + uint8_t *sample_pos, sample; + int byte_offset, bit_offset, i; + + logic = (srd_logic *)self; + if (logic->itercnt >= logic->inbuflen / logic->di->data_unitsize) { + /* End iteration loop. */ + return NULL; + } + + /* + * Convert the bit-packed sample to an array of bytes, with only 0x01 + * and 0x00 values, so the PD doesn't need to do any bitshifting. + */ + sample_pos = logic->inbuf + logic->itercnt * logic->di->data_unitsize; + for (i = 0; i < logic->di->dec_num_channels; i++) { + /* A channelmap value of -1 means "unused optional channel". */ + if (logic->di->dec_channelmap[i] == -1) { + /* Value of unused channel is 0xff, instead of 0 or 1. */ + logic->di->channel_samples[i] = 0xff; + } else { + byte_offset = logic->di->dec_channelmap[i] / 8; + bit_offset = logic->di->dec_channelmap[i] % 8; + sample = *(sample_pos + byte_offset) & (1 << bit_offset) ? 1 : 0; + logic->di->channel_samples[i] = sample; + } + } + + /* Prepare the next samplenum/sample list in this iteration. */ + py_samplenum = + PyLong_FromUnsignedLongLong(logic->start_samplenum + + logic->itercnt); + PyList_SetItem(logic->sample, 0, py_samplenum); + py_samples = PyBytes_FromStringAndSize((const char *)logic->di->channel_samples, + logic->di->dec_num_channels); + PyList_SetItem(logic->sample, 1, py_samples); + Py_INCREF(logic->sample); + logic->itercnt++; + + return logic->sample; +} + +/** Create the srd_logic type. + * @return The new type object. + * @private + */ +SRD_PRIV PyObject *srd_logic_type_new(void) +{ + PyType_Spec spec; + PyType_Slot slots[] = { + { Py_tp_doc, "sigrokdecode logic sample object" }, + { Py_tp_iter, (void *)&srd_logic_iter }, + { Py_tp_iternext, (void *)&srd_logic_iternext }, + { Py_tp_new, (void *)&PyType_GenericNew }, + { 0, NULL } + }; + spec.name = "srd_logic"; + spec.basicsize = sizeof(srd_logic); + spec.itemsize = 0; + spec.flags = Py_TPFLAGS_DEFAULT; + spec.slots = slots; + + return PyType_FromSpec(&spec); +} diff --git a/pool/shard006/C/0118962_TestArrayList.c b/pool/shard006/C/0118962_TestArrayList.c new file mode 100644 index 0000000000000000000000000000000000000000..4a0d2740df5489440f73a6390c0bb53ade8ed7c1 --- /dev/null +++ b/pool/shard006/C/0118962_TestArrayList.c @@ -0,0 +1,83 @@ + +#include +#include +#include + +int TestArrayList(int argc, char* argv[]) +{ + size_t index; + int count; + int rc; + size_t val; + wArrayList* arrayList; + const size_t elemsToInsert = 10; + + WINPR_UNUSED(argc); + WINPR_UNUSED(argv); + + arrayList = ArrayList_New(TRUE); + if (!arrayList) + return -1; + + for (index = 0; index < elemsToInsert; index++) + { + if (!ArrayList_Append(arrayList, (void*)index)) + return -1; + } + + count = ArrayList_Count(arrayList); + + printf("ArrayList count: %d\n", count); + + index = ArrayList_IndexOf(arrayList, (void*)(size_t)6, -1, -1); + + printf("ArrayList index: %" PRIdz "\n", index); + + if (index != 6) + return -1; + + ArrayList_Insert(arrayList, 5, (void*)(size_t)100); + + index = ArrayList_IndexOf(arrayList, (void*)(size_t)6, -1, -1); + printf("ArrayList index: %" PRIdz "\n", index); + + if (index != 7) + return -1; + + ArrayList_Remove(arrayList, (void*)(size_t)100); + + rc = ArrayList_IndexOf(arrayList, (void*)(size_t)6, -1, -1); + printf("ArrayList index: %d\n", rc); + + if (rc != 6) + return -1; + + for (index = 0; index < elemsToInsert; index++) + { + val = (size_t)ArrayList_GetItem(arrayList, 0); + if (!ArrayList_RemoveAt(arrayList, 0)) + return -1; + if (val != index) + { + printf("ArrayList: shifted %" PRIdz " entries, expected value %" PRIdz ", got %" PRIdz + "\n", + index, index, val); + return -1; + } + } + + rc = ArrayList_IndexOf(arrayList, (void*)(size_t)elemsToInsert, -1, -1); + printf("ArrayList index: %d\n", rc); + if (rc != -1) + return -1; + + count = ArrayList_Count(arrayList); + printf("ArrayList count: %d\n", count); + if (count != 0) + return -1; + + ArrayList_Clear(arrayList); + ArrayList_Free(arrayList); + + return 0; +} diff --git a/pool/shard006/C/0118964_p7_hmmwindow.c b/pool/shard006/C/0118964_p7_hmmwindow.c new file mode 100644 index 0000000000000000000000000000000000000000..e186418c62a1bcf6ffd89a5d6f2885fcc8afd8dc --- /dev/null +++ b/pool/shard006/C/0118964_p7_hmmwindow.c @@ -0,0 +1,108 @@ +/* The Plan7 MSVDATA data structure, which holds a compact representation + * of substitution scores and maximal extensions, used by nhmmer. + * + * Contents: + * 1. The P7_MSVDATA object: allocation, initialization, destruction. + * 2. Unit tests. + * 3. Test driver. + * 4. Copyright and license. + * + */ +#include "p7_config.h" +#include "hmmer.h" + + +/********************************************************************* + *# 1. The P7_MSVDATA object: allocation, initialization, destruction. + *********************************************************************/ + + +/* Function: p7_hmmwindow_init() + * + * Synopsis: initialize the object used to store a list of sequence windows + * + * Returns: eslEMEM in event of allocation failure, otherwise eslOK + */ +int +p7_hmmwindow_init (P7_HMM_WINDOWLIST *list) { + int status; + list->size = 10000; + list->count = 0; + ESL_ALLOC(list->windows, list->size * sizeof(P7_HMM_WINDOW)); + + return eslOK; + +ERROR: + return eslEMEM; + +} + +/* Function: p7_hmmwindow_new() + * + * Synopsis: Return a pointer to the next window element on the list + * + * Purpose: Accepts , , , , , , + * and , assigns those to the next window + * element, then returns it, increasing the size of the + * list, if necessary. + * + * Returns: NULL in event of allocation failure, otherwise pointer to + * the next seed diagonal + */ + +P7_HMM_WINDOW * +p7_hmmwindow_new (P7_HMM_WINDOWLIST *list, uint32_t id, uint32_t pos, uint32_t fm_pos, uint16_t k, uint32_t length, float score, uint8_t complementarity) { + int status; + P7_HMM_WINDOW *window; + + if (list->count == list->size) { + list->size *= 4; + ESL_REALLOC(list->windows, list->size * sizeof(P7_HMM_WINDOW)); + } + window = list->windows + list->count; + + window->id = id; + window->n = pos; + window->fm_n = fm_pos; + window->k = k; + window->length = length; + window->score = score; + window->complementarity = complementarity; + + list->count++; + + return window; + +ERROR: + return NULL; +} + + + + +/***************************************************************** + * 2. Unit tests + *****************************************************************/ + + + +/***************************************************************** + * 3. Test driver + *****************************************************************/ + + + +/************************************************************ + * HMMER - Biological sequence analysis with profile HMMs + * Version 3.1b1; May 2013 + * Copyright (C) 2013 Howard Hughes Medical Institute. + * Other copyrights also apply. See the COPYRIGHT file for a full list. + * + * HMMER is distributed under the terms of the GNU General Public License + * (GPLv3). See the LICENSE file for details. + * + * SVN $Id: p7_hmmwindow.c 3784 2011-12-07 21:51:25Z wheelert $ + * SVN $URL: https://svn.janelia.org/eddylab/eddys/src/hmmer/trunk/src/p7_hmmwindow.c $ + ************************************************************/ + + diff --git a/pool/shard006/C/0118968_exprNodeSList.c b/pool/shard006/C/0118968_exprNodeSList.c new file mode 100644 index 0000000000000000000000000000000000000000..b71bce1379f9267254d9bde425dc207b3cef3b00 --- /dev/null +++ b/pool/shard006/C/0118968_exprNodeSList.c @@ -0,0 +1,138 @@ +/* +** Splint - annotation-assisted static program checker +** Copyright (C) 1994-2003 University of Virginia, +** Massachusetts Institute of Technology +** +** 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. +** +** The GNU General Public License is available from http://www.gnu.org/ or +** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, +** MA 02111-1307, USA. +** +** For information on splint: info@splint.org +** To report a bug: splint-bug@splint.org +** For more information: http://www.splint.org +*/ +/* +** exprNodeSList.c +** +** based on list_template.c +** +** where T has T_equal (or change this) and T_unparse +*/ + +# include "splintMacros.nf" +# include "basic.h" +# include "exprNodeSList.h" + +exprNodeSList + exprNodeSList_new () +{ + exprNodeSList s = (exprNodeSList) dmalloc (sizeof (*s)); + + s->nelements = 0; + s->nspace = exprNodeSListBASESIZE; + s->elements = (exprNode *) + dmalloc (sizeof (*s->elements) * exprNodeSListBASESIZE); + + return (s); +} + +static void +exprNodeSList_grow (exprNodeSList s) +{ + int i; + exprNode *newelements; + + s->nspace += exprNodeSListBASESIZE; + + newelements = (exprNode *) dmalloc (sizeof (*newelements) + * (s->nelements + s->nspace)); + + if (newelements == (exprNode *) 0) + { + llfatalerror (cstring_makeLiteral ("exprNodeSList_grow: out of memory!")); + } + + for (i = 0; i < s->nelements; i++) + { + newelements[i] = s->elements[i]; + } + + sfree (s->elements); + s->elements = newelements; +} + +void exprNodeSList_addh (exprNodeSList s, /*@exposed@*/ /*@dependent@*/ exprNode el) +{ + llassert (exprNodeSListBASESIZE > 0); + + if (s->nspace <= 0) + exprNodeSList_grow (s); + + s->nspace--; + s->elements[s->nelements] = el; + s->nelements++; +} + +/* +** appends s2 to s1 +*/ + +exprNodeSList exprNodeSList_append (/*@returned@*/ exprNodeSList s1, /*@only@*/ exprNodeSList s2) +{ + exprNodeSList_elements (s2, x) + { + exprNodeSList_addh (s1, x); + } end_exprNodeSList_elements; + + exprNodeSList_free (s2); + return s1; +} + +/*@only@*/ exprNodeSList exprNodeSList_singleton (/*@exposed@*/ /*@dependent@*/ exprNode e) +{ + exprNodeSList s = (exprNodeSList) dmalloc (sizeof (*s)); + + s->nelements = 1; + s->nspace = exprNodeSListBASESIZE - 1; + s->elements = (exprNode *) dmalloc (sizeof (*s->elements) * exprNodeSListBASESIZE); + s->elements[0] = e; + + return (s); +} + +/*@only@*/ cstring +exprNodeSList_unparse (exprNodeSList s) +{ + int i; + cstring st = cstring_undefined; + + for (i = 0; i < s->nelements; i++) + { + if (i == 0) + { + st = cstring_copy (exprNode_unparse (s->elements[i])); + } + else + st = message ("%q, %s", st, exprNode_unparse (s->elements[i])); + } + + return st; +} + +void +exprNodeSList_free (exprNodeSList s) +{ + sfree (s->elements); + sfree (s); +} + diff --git a/pool/shard006/C/0118970_test.c b/pool/shard006/C/0118970_test.c new file mode 100644 index 0000000000000000000000000000000000000000..2ee504e241808b344a6984c057209250bd4e75c5 --- /dev/null +++ b/pool/shard006/C/0118970_test.c @@ -0,0 +1,14 @@ +#include "chatroom.h" + +int main() +{ + char buf[100]={"helloworld"}; + int n; + char msg[100] = {0}; + makeAMsg(msg,buf,NORMALM); + printf("msg[%s]\n", msg); + memset(buf,0x00,sizeof(buf)); + parseAMsg(msg,buf,&n); + printf("n[%d],msg[%s]\n",n,buf); + return 0; +} diff --git a/pool/shard006/C/0118971_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02.c b/pool/shard006/C/0118971_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02.c new file mode 100644 index 0000000000000000000000000000000000000000..1ab92b6cff628b1d1a476477e58f37d5b9742f1d --- /dev/null +++ b/pool/shard006/C/0118971_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02.c @@ -0,0 +1,142 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE806.label.xml +Template File: sources-sink-02.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sink: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 02 Control flow: if(1) and if(0) + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02_bad() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if(1) + { + /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ + wmemset(data, L'A', 100-1); /* fill with L'A's */ + data[100-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[50] = L""; + size_t i, dataLen; + dataLen = wcslen(data); + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + for (i = 0; i < dataLen; i++) + { + dest[i] = data[i]; + } + dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the 1 to 0 */ +static void goodG2B1() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if(0) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[50] = L""; + size_t i, dataLen; + dataLen = wcslen(data); + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + for (i = 0; i < dataLen; i++) + { + dest[i] = data[i]; + } + dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + free(data); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if(1) + { + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[50] = L""; + size_t i, dataLen; + dataLen = wcslen(data); + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + for (i = 0; i < dataLen; i++) + { + dest[i] = data[i]; + } + dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_02_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0118974_zgdu.c b/pool/shard006/C/0118974_zgdu.c new file mode 100644 index 0000000000000000000000000000000000000000..18ce71d2467ba59e569aafffaba8202b1d99f1a9 --- /dev/null +++ b/pool/shard006/C/0118974_zgdu.c @@ -0,0 +1,65 @@ +/* This file is part of the YAZ toolkit. + * Copyright (C) 1995-2012 Index Data + * See the file LICENSE for details. + */ +/** + * \file zgdu.c + * \brief Implements HTTP and Z39.50 encoding and decoding. + */ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +int z_GDU(ODR o, Z_GDU **p, int opt, const char *name) +{ + if (o->direction == ODR_DECODE) { + *p = (Z_GDU *) odr_malloc(o, sizeof(**p)); + if (o->size > 10 && !memcmp(o->buf, "HTTP/", 5)) + { + (*p)->which = Z_GDU_HTTP_Response; + return yaz_decode_http_response(o, &(*p)->u.HTTP_Response); + + } + else if (o->size > 5 && + o->buf[0] >= 0x20 && o->buf[0] < 0x7f + && o->buf[1] >= 0x20 && o->buf[1] < 0x7f + && o->buf[2] >= 0x20 && o->buf[2] < 0x7f + && o->buf[3] >= 0x20 && o->buf[3] < 0x7f) + { + (*p)->which = Z_GDU_HTTP_Request; + return yaz_decode_http_request(o, &(*p)->u.HTTP_Request); + } + else + { + (*p)->which = Z_GDU_Z3950; + return z_APDU(o, &(*p)->u.z3950, opt, 0); + } + } + else /* ENCODE or PRINT */ + { + switch((*p)->which) + { + case Z_GDU_HTTP_Response: + return yaz_encode_http_response(o, (*p)->u.HTTP_Response); + case Z_GDU_HTTP_Request: + return yaz_encode_http_request(o, (*p)->u.HTTP_Request); + case Z_GDU_Z3950: + return z_APDU(o, &(*p)->u.z3950, opt, 0); + } + } + return 0; +} + +/* + * Local variables: + * c-basic-offset: 4 + * c-file-style: "Stroustrup" + * indent-tabs-mode: nil + * End: + * vim: shiftwidth=4 tabstop=8 expandtab + */ + diff --git a/pool/shard006/C/0118977_iio-trig-sysfs.c b/pool/shard006/C/0118977_iio-trig-sysfs.c new file mode 100644 index 0000000000000000000000000000000000000000..127a2a33e4db1d8694f100271db9c4f5ecafef3b --- /dev/null +++ b/pool/shard006/C/0118977_iio-trig-sysfs.c @@ -0,0 +1,108 @@ +/* + * Copyright 2011 Analog Devices Inc. + * + * Licensed under the GPL-2. + * + */ + +#include +#include +#include +#include + +#include "../iio.h" +#include "../trigger.h" + +static ssize_t iio_sysfs_trigger_poll(struct device *dev, + struct device_attribute *attr, const char *buf, size_t count) +{ + struct iio_trigger *trig = dev_get_drvdata(dev); + iio_trigger_poll(trig, 0); + + return count; +} + +static DEVICE_ATTR(trigger_now, S_IWUSR, NULL, iio_sysfs_trigger_poll); +static IIO_TRIGGER_NAME_ATTR; + +static struct attribute *iio_sysfs_trigger_attrs[] = { + &dev_attr_trigger_now.attr, + &dev_attr_name.attr, + NULL, +}; + +static const struct attribute_group iio_sysfs_trigger_attr_group = { + .attrs = iio_sysfs_trigger_attrs, +}; + +static int __devinit iio_sysfs_trigger_probe(struct platform_device *pdev) +{ + struct iio_trigger *trig; + int ret; + + trig = iio_allocate_trigger(); + if (!trig) { + ret = -ENOMEM; + goto out1; + } + + trig->control_attrs = &iio_sysfs_trigger_attr_group; + trig->owner = THIS_MODULE; + trig->name = kasprintf(GFP_KERNEL, "sysfstrig%d", pdev->id); + if (trig->name == NULL) { + ret = -ENOMEM; + goto out2; + } + + ret = iio_trigger_register(trig); + if (ret) + goto out3; + + platform_set_drvdata(pdev, trig); + + return 0; +out3: + kfree(trig->name); +out2: + iio_put_trigger(trig); +out1: + + return ret; +} + +static int __devexit iio_sysfs_trigger_remove(struct platform_device *pdev) +{ + struct iio_trigger *trig = platform_get_drvdata(pdev); + + iio_trigger_unregister(trig); + kfree(trig->name); + iio_put_trigger(trig); + + return 0; +} + +static struct platform_driver iio_sysfs_trigger_driver = { + .driver = { + .name = "iio_sysfs_trigger", + .owner = THIS_MODULE, + }, + .probe = iio_sysfs_trigger_probe, + .remove = __devexit_p(iio_sysfs_trigger_remove), +}; + +static int __init iio_sysfs_trig_init(void) +{ + return platform_driver_register(&iio_sysfs_trigger_driver); +} +module_init(iio_sysfs_trig_init); + +static void __exit iio_sysfs_trig_exit(void) +{ + platform_driver_unregister(&iio_sysfs_trigger_driver); +} +module_exit(iio_sysfs_trig_exit); + +MODULE_AUTHOR("Michael Hennerich "); +MODULE_DESCRIPTION("Sysfs based trigger for the iio subsystem"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:iio-trig-sysfs"); diff --git a/pool/shard006/C/0118978_function-variable-same-name.c b/pool/shard006/C/0118978_function-variable-same-name.c new file mode 100644 index 0000000000000000000000000000000000000000..d219a2ff51a98e014726efa5ace69db0a0932587 --- /dev/null +++ b/pool/shard006/C/0118978_function-variable-same-name.c @@ -0,0 +1,18 @@ +char b() { return 'a'; } +char a2() { return 'a'; } + +int i() { return 2; } + +int main() { + int i[] = {1, 2, 3}; + + // function a2() does not have same identifier as char a[] + char a[] = {a2(), 'b', 'c'}; + + // function b has same identifier as char b[] + // => error: called object 'b' is not a function or function pointer + // our error: function: undefined reference to 'b', is ok? + char b[] = {b(), 'b', 'c'}; + + return 0; +} diff --git a/pool/shard006/C/0118982_libfsmpo08.c b/pool/shard006/C/0118982_libfsmpo08.c new file mode 100644 index 0000000000000000000000000000000000000000..3eca44a82073065e168092c0c1f6db38e223b2e0 --- /dev/null +++ b/pool/shard006/C/0118982_libfsmpo08.c @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include "FSM/FSMDevice/fcmprotocol.h" +#include "FSM/FSMDevice/FSMSysCtl.h" +#include "FSM/FSMDevice/FSM_DeviceProcess.h" +struct FSM_SendCmdUserspace fsmdat; + +void FSM_CCK_PO08_SendCMD(enum FSMPO08Command fsmcmd,unsigned short IDDevice) +{ + fsmdat.IDDevice=IDDevice; + fsmdat.cmd=fsmcmd; + FSM_SendCtlCmd(&fsmdat); +} + +void FSM_CCK_PO08_SendCMD_Set(enum FSMPO08Command fsmcmd,unsigned short IDDevice) +{ + fsmdat.IDDevice=IDDevice; + fsmdat.cmd=fsmcmd; + fsmdat.Data[0]=1; + FSM_SendCtlCmd(&fsmdat); +} +void FSM_CCK_PO08_SendCMD_ReSet(enum FSMPO08Command fsmcmd,unsigned short IDDevice) +{ + fsmdat.IDDevice=IDDevice; + fsmdat.cmd=fsmcmd; + fsmdat.Data[0]=0; + FSM_SendCtlCmd(&fsmdat); +} \ No newline at end of file diff --git a/pool/shard006/C/0118983_nsxfobj.c b/pool/shard006/C/0118983_nsxfobj.c new file mode 100644 index 0000000000000000000000000000000000000000..51a83298c18d19e6201b4d5f041f690a76377beb --- /dev/null +++ b/pool/shard006/C/0118983_nsxfobj.c @@ -0,0 +1,246 @@ +/******************************************************************************* + * + * Module Name: nsxfobj - Public interfaces to the ACPI subsystem + * ACPI Object oriented interfaces + * + ******************************************************************************/ + +/* + * Copyright (C) 2000 - 2014, 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. + */ + +#define EXPORT_ACPI_INTERFACES + +#include +#include "accommon.h" +#include "acnamesp.h" + +#define _COMPONENT ACPI_NAMESPACE +ACPI_MODULE_NAME("nsxfobj") + +/******************************************************************************* + * + * FUNCTION: acpi_get_type + * + * PARAMETERS: handle - Handle of object whose type is desired + * ret_type - Where the type will be placed + * + * RETURN: Status + * + * DESCRIPTION: This routine returns the type associatd with a particular handle + * + ******************************************************************************/ +acpi_status acpi_get_type(acpi_handle handle, acpi_object_type * ret_type) +{ + struct acpi_namespace_node *node; + acpi_status status; + + /* Parameter Validation */ + + if (!ret_type) { + return (AE_BAD_PARAMETER); + } + + /* + * Special case for the predefined Root Node + * (return type ANY) + */ + if (handle == ACPI_ROOT_OBJECT) { + *ret_type = ACPI_TYPE_ANY; + return (AE_OK); + } + + status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE(status)) { + return (status); + } + + /* Convert and validate the handle */ + + node = acpi_ns_validate_handle(handle); + if (!node) { + (void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); + return (AE_BAD_PARAMETER); + } + + *ret_type = node->type; + + status = acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); + return (status); +} + +ACPI_EXPORT_SYMBOL(acpi_get_type) + +/******************************************************************************* + * + * FUNCTION: acpi_get_parent + * + * PARAMETERS: handle - Handle of object whose parent is desired + * ret_handle - Where the parent handle will be placed + * + * RETURN: Status + * + * DESCRIPTION: Returns a handle to the parent of the object represented by + * Handle. + * + ******************************************************************************/ +acpi_status acpi_get_parent(acpi_handle handle, acpi_handle * ret_handle) +{ + struct acpi_namespace_node *node; + struct acpi_namespace_node *parent_node; + acpi_status status; + + if (!ret_handle) { + return (AE_BAD_PARAMETER); + } + + /* Special case for the predefined Root Node (no parent) */ + + if (handle == ACPI_ROOT_OBJECT) { + return (AE_NULL_ENTRY); + } + + status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE(status)) { + return (status); + } + + /* Convert and validate the handle */ + + node = acpi_ns_validate_handle(handle); + if (!node) { + status = AE_BAD_PARAMETER; + goto unlock_and_exit; + } + + /* Get the parent entry */ + + parent_node = node->parent; + *ret_handle = ACPI_CAST_PTR(acpi_handle, parent_node); + + /* Return exception if parent is null */ + + if (!parent_node) { + status = AE_NULL_ENTRY; + } + +unlock_and_exit: + + (void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); + return (status); +} + +ACPI_EXPORT_SYMBOL(acpi_get_parent) + +/******************************************************************************* + * + * FUNCTION: acpi_get_next_object + * + * PARAMETERS: type - Type of object to be searched for + * parent - Parent object whose children we are getting + * last_child - Previous child that was found. + * The NEXT child will be returned + * ret_handle - Where handle to the next object is placed + * + * RETURN: Status + * + * DESCRIPTION: Return the next peer object within the namespace. If Handle is + * valid, Scope is ignored. Otherwise, the first object within + * Scope is returned. + * + ******************************************************************************/ +acpi_status +acpi_get_next_object(acpi_object_type type, + acpi_handle parent, + acpi_handle child, acpi_handle * ret_handle) +{ + acpi_status status; + struct acpi_namespace_node *node; + struct acpi_namespace_node *parent_node = NULL; + struct acpi_namespace_node *child_node = NULL; + + /* Parameter validation */ + + if (type > ACPI_TYPE_EXTERNAL_MAX) { + return (AE_BAD_PARAMETER); + } + + status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); + if (ACPI_FAILURE(status)) { + return (status); + } + + /* If null handle, use the parent */ + + if (!child) { + + /* Start search at the beginning of the specified scope */ + + parent_node = acpi_ns_validate_handle(parent); + if (!parent_node) { + status = AE_BAD_PARAMETER; + goto unlock_and_exit; + } + } else { + /* Non-null handle, ignore the parent */ + /* Convert and validate the handle */ + + child_node = acpi_ns_validate_handle(child); + if (!child_node) { + status = AE_BAD_PARAMETER; + goto unlock_and_exit; + } + } + + /* Internal function does the real work */ + + node = acpi_ns_get_next_node_typed(type, parent_node, child_node); + if (!node) { + status = AE_NOT_FOUND; + goto unlock_and_exit; + } + + if (ret_handle) { + *ret_handle = ACPI_CAST_PTR(acpi_handle, node); + } + +unlock_and_exit: + + (void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); + return (status); +} + +ACPI_EXPORT_SYMBOL(acpi_get_next_object) diff --git a/pool/shard006/C/0118985_udev-watch.c b/pool/shard006/C/0118985_udev-watch.c new file mode 100644 index 0000000000000000000000000000000000000000..d67083b51b3a67e3d14f9d2a7b6b4ef5113646a2 --- /dev/null +++ b/pool/shard006/C/0118985_udev-watch.c @@ -0,0 +1,173 @@ +/* + * Copyright (C) 2004-2008 Kay Sievers + * Copyright (C) 2009 Canonical Ltd. + * Copyright (C) 2009 Scott James Remnant + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "udev.h" + +static int inotify_fd = -1; + +/* inotify descriptor, will be shared with rules directory; + * set to cloexec since we need our children to be able to add + * watches for us + */ +int udev_watch_init(struct udev *udev) +{ + inotify_fd = inotify_init1(IN_CLOEXEC); + if (inotify_fd < 0) + err(udev, "inotify_init failed: %m\n"); + return inotify_fd; +} + +/* move any old watches directory out of the way, and then restore + * the watches + */ +void udev_watch_restore(struct udev *udev) +{ + char filename[UTIL_PATH_SIZE], oldname[UTIL_PATH_SIZE]; + + if (inotify_fd < 0) + return; + + util_strscpyl(oldname, sizeof(oldname), udev_get_dev_path(udev), "/.udev/watch.old", NULL); + util_strscpyl(filename, sizeof(filename), udev_get_dev_path(udev), "/.udev/watch", NULL); + if (rename(filename, oldname) == 0) { + DIR *dir; + struct dirent *ent; + + dir = opendir(oldname); + if (dir == NULL) { + err(udev, "unable to open old watches dir '%s', old watches will not be restored: %m", oldname); + return; + } + + for (ent = readdir(dir); ent != NULL; ent = readdir(dir)) { + char device[UTIL_PATH_SIZE]; + char *s; + size_t l; + ssize_t len; + struct udev_device *dev; + + if (ent->d_name[0] < '0' || ent->d_name[0] > '9') + continue; + + s = device; + l = util_strpcpy(&s, sizeof(device), udev_get_sys_path(udev)); + len = readlinkat(dirfd(dir), ent->d_name, s, l); + if (len <= 0 || len >= (ssize_t)l) { + unlinkat(dirfd(dir), ent->d_name, 0); + continue; + } + s[len] = '\0'; + dbg(udev, "old watch to '%s' found\n", device); + dev = udev_device_new_from_syspath(udev, device); + if (dev == NULL) { + unlinkat(dirfd(dir), ent->d_name, 0); + continue; + } + + info(udev, "restoring old watch on '%s'\n", udev_device_get_devnode(dev)); + udev_watch_begin(udev, dev); + + udev_device_unref(dev); + unlinkat(dirfd(dir), ent->d_name, 0); + } + + closedir(dir); + rmdir(oldname); + + } else if (errno != ENOENT) { + err(udev, "unable to move watches dir '%s', old watches will not be restored: %m", filename); + } +} + +void udev_watch_begin(struct udev *udev, struct udev_device *dev) +{ + char filename[UTIL_PATH_SIZE]; + int wd; + + if (inotify_fd < 0) + return; + + info(udev, "adding watch on '%s'\n", udev_device_get_devnode(dev)); + wd = inotify_add_watch(inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE); + if (wd < 0) { + err(udev, "inotify_add_watch(%d, %s, %o) failed: %m\n", + inotify_fd, udev_device_get_devnode(dev), IN_CLOSE_WRITE); + return; + } + + snprintf(filename, sizeof(filename), "%s/.udev/watch/%d", udev_get_dev_path(udev), wd); + util_create_path(udev, filename); + unlink(filename); + symlink(udev_device_get_devpath(dev), filename); + + udev_device_set_watch_handle(dev, wd); +} + +void udev_watch_end(struct udev *udev, struct udev_device *dev) +{ + int wd; + char filename[UTIL_PATH_SIZE]; + + if (inotify_fd < 0) + return; + + wd = udev_device_get_watch_handle(dev); + if (wd < 0) + return; + + info(udev, "removing watch on '%s'\n", udev_device_get_devnode(dev)); + inotify_rm_watch(inotify_fd, wd); + + snprintf(filename, sizeof(filename), "%s/.udev/watch/%d", udev_get_dev_path(udev), wd); + unlink(filename); + + udev_device_set_watch_handle(dev, -1); +} + +struct udev_device *udev_watch_lookup(struct udev *udev, int wd) +{ + char filename[UTIL_PATH_SIZE]; + char syspath[UTIL_PATH_SIZE]; + char *s; + size_t l; + ssize_t len; + + if (inotify_fd < 0 || wd < 0) + return NULL; + + snprintf(filename, sizeof(filename), "%s/.udev/watch/%d", udev_get_dev_path(udev), wd); + s = syspath; + l = util_strpcpy(&s, sizeof(syspath), udev_get_sys_path(udev)); + len = readlink(filename, s, l); + if (len < 0 || (size_t)len >= l) + return NULL; + s[len] = '\0'; + return udev_device_new_from_syspath(udev, syspath); +} diff --git a/pool/shard006/C/0118989_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnlp_64b.c b/pool/shard006/C/0118989_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnlp_64b.c new file mode 100644 index 0000000000000000000000000000000000000000..eadfebb474693844c1008b7ee528b6096f342f8d --- /dev/null +++ b/pool/shard006/C/0118989_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnlp_64b.c @@ -0,0 +1,89 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnlp_64b.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-64b.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sinks: w32_spawnlp + * BadSink : execute command with wspawnlp + * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnlp_64b_badSink(void * dataVoidPtr) +{ + /* cast void pointer to a pointer of the appropriate type */ + wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr; + /* dereference dataPtr into data */ + wchar_t * data = (*dataPtr); + /* wspawnlp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_spawnlp_64b_goodG2BSink(void * dataVoidPtr) +{ + /* cast void pointer to a pointer of the appropriate type */ + wchar_t * * dataPtr = (wchar_t * *)dataVoidPtr; + /* dereference dataPtr into data */ + wchar_t * data = (*dataPtr); + /* wspawnlp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _wspawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITGOOD */ diff --git a/pool/shard006/C/0118992_vm_ptr.c b/pool/shard006/C/0118992_vm_ptr.c new file mode 100644 index 0000000000000000000000000000000000000000..9496332a3fe64d3b1a69e5ecdfb5ad4ffdf30cd6 --- /dev/null +++ b/pool/shard006/C/0118992_vm_ptr.c @@ -0,0 +1,41 @@ +// RUN: %ocheck 0 %s +void abort(void) __attribute__((noreturn)); + +gs; + +g(void) +{ + gs++; + return 3; +} + +int (*f(int a[g()]))[] // called once +{ + int (*p)[g()] = a; // called once + + return p + 1; +} + +main() +{ +#include "../ocheck-init.c" + int a[2][g()]; + + a[0][0] = 0; + a[0][1] = 1; + a[0][2] = 2; + + a[1][0] = 3; + a[1][1] = 4; + a[1][2] = 5; + + int (*p)[] = f(a); + + if((*p)[1] != 4) + abort(); + + if(gs != 3) + abort(); + + return 0; +} diff --git a/pool/shard006/C/0118993_image.c b/pool/shard006/C/0118993_image.c new file mode 100644 index 0000000000000000000000000000000000000000..564208864d6c14ef798dfea1c5bf314d03179be6 --- /dev/null +++ b/pool/shard006/C/0118993_image.c @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "image.h" +#include "math_utils.h" + +image_t image_new(size_t width, size_t height) +{ + color_t *pixels = malloc(height * width * sizeof(color_t)); + memset(pixels, 0, height * width * sizeof(color_t)); + return (image_t) { + .width = width, + .height = height, + .pixels = pixels + }; +} + +void image_dispose(image_t image) +{ + free(image.pixels); +} + +size_t image_size(image_t image) +{ + return image.width * image.height; +} + +void image_save_ppm(const char * filename, image_t image) +{ + FILE *f = fopen(filename, "wb"); + fprintf(f, "P3\n%zd %zd\n%d\n", image.width, image.height, 255); + for (int i = 0; i < image_size(image) ; i++) + { + fprintf( + f, "%d %d %d ", + ratio_to_int(clamp(image.pixels[i].x, 0.0, 1.0), 255), + ratio_to_int(clamp(image.pixels[i].y, 0.0, 1.0), 255), + ratio_to_int(clamp(image.pixels[i].z, 0.0, 1.0), 255) + ); + } + fclose(f); +} diff --git a/pool/shard006/C/0118997_exemple_serveur_daytime.c b/pool/shard006/C/0118997_exemple_serveur_daytime.c new file mode 100644 index 0000000000000000000000000000000000000000..f966905bd386ab95c9770e50d1f34af01b4f5a55 --- /dev/null +++ b/pool/shard006/C/0118997_exemple_serveur_daytime.c @@ -0,0 +1,147 @@ + #include + #include + #include + + #include + #include + #include + + #include + #include + + int cree_socket_stream (const char * nom_hote, + const char * nom_service, + const char * nom_proto); + int affiche_adresse_socket (int sock); + int serveur_tcp (void); + int quitter_le_serveur (void); + void traite_connexion (int sock); + + int +cree_socket_stream (const char * nom_hote, const char * nom_service, const char * nom_proto) +{ + int sock; + struct sockaddr_in adresse; + struct hostent * hostent = NULL; + struct servent * servent = NULL; + struct protoent * protoent = NULL; + + if (nom_hote != NULL) + if ((hostent = gethostbyname (nom_hote)) == NULL) { + perror ("gethostbyname"); + return (-1); + } + + if ((protoent = getprotobyname (nom_proto)) == NULL) { + perror ("getprotobyname"); + return (-1); + } + if (nom_service != NULL) + if ((servent = getservbyname (nom_service, + protoent -> p_name)) == NULL) { + perror ("getservbyname"); + return (-1); + } + if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) { + perror ("socket"); + return (-1); + } + memset (& adresse, 0, sizeof (struct sockaddr_in)); + adresse . sin_family = AF_INET; + if (servent != NULL) + adresse . sin_port = servent -> s_port; + else + adresse . sin_port = htons (0); + if (hostent != NULL) + adresse . sin_addr . s_addr = + ((struct in_addr *) (hostent -> h_addr)) -> s_addr; + else + adresse . sin_addr . s_addr = htonl (INADDR_ANY); + if (bind (sock, (struct sockaddr *) & adresse, + sizeof (struct sockaddr_in)) < 0) { + close (sock); + perror ("bind"); + return (-1); + } + return (sock); +} + + + int +affiche_adresse_socket (int sock) +{ + struct sockaddr_in adresse; + socklen_t longueur; + + longueur = sizeof (struct sockaddr_in); + if (getsockname (sock, & adresse, & longueur) < 0) { + perror ("getsockname"); + return (-1); + } + fprintf (stdout, "IP = %s, Port = %u \n", + inet_ntoa (adresse . sin_addr), + ntohs (adresse . sin_port)); + return (0); +} + + + int +serveur_tcp (void) +{ + int sock_contact; + int sock_connectee; + struct sockaddr_in adresse; + socklen_t longueur; + + sock_contact = cree_socket_stream (NULL, NULL, "tcp"); + if (sock_contact < 0) + return (-1); + listen (sock_contact, 5); + fprintf (stdout, "Mon adresse >> "); + affiche_adresse_socket (sock_contact); + while (! quitter_le_serveur ()) { + longueur = sizeof (struct sockaddr_in); + sock_connectee = accept (sock_contact, & adresse, & longueur); + if (sock_connectee < 0) { + perror ("accept"); + return (-1); + } + switch (fork ()) { + case 0 : /* fils */ + close (sock_contact); + traite_connexion (sock_connectee); + exit (0); + case -1 : + perror ("fork"); + return (-1); + default : /* père */ + close (sock_connectee); + } + } + return (0); +} + + int +quitter_le_serveur (void) +{ + return (0); +} + + void +traite_connexion (int sock) +{ + time_t heure; + char buffer [256]; + + heure = time (NULL); + sprintf (buffer, "%s", ctime (& heure)); + write (sock, buffer, strlen (buffer)); + close (sock); +} + + int +main (int argc, char * argv []) +{ + return (serveur_tcp ()); +} + diff --git a/pool/shard006/C/0119000_picload.c b/pool/shard006/C/0119000_picload.c new file mode 100644 index 0000000000000000000000000000000000000000..d05b320e46b0cc3b01a789ec9edcca97d7243de7 --- /dev/null +++ b/pool/shard006/C/0119000_picload.c @@ -0,0 +1,85 @@ +/* + * OpenTyrian: A modern cross-platform port of Tyrian + * Copyright (C) 2007-2009 The OpenTyrian Development Team + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +#include "picload.h" +#include "file.h" +#include "palette.h" +#include "pcxmast.h" +#include "video.h" + +#include + +void JE_loadPic(SDL_Surface *screen, uint8_t PCXnumber, bool storepal ) +{ + PCXnumber--; + + FILE *f = dir_fopen_die(data_dir(), "tyrian.pic", "rb"); + + static bool first = true; + if (first) + { + first = false; + + uint16_t temp; + efread(&temp, sizeof(uint16_t), 1, f); + for (int i = 0; i < PCX_NUM; i++) + { + efread(&pcxpos[i], sizeof(int32_t), 1, f); + } + + pcxpos[PCX_NUM] = ftell_eof(f); + } + + uint32_t size = pcxpos[PCXnumber + 1] - pcxpos[PCXnumber]; + uint8_t *buffer = malloc(size); + + fseek(f, pcxpos[PCXnumber], SEEK_SET); + efread(buffer, sizeof(uint8_t), size, f); + fclose(f); + + uint8_t *p = buffer; + uint8_t *s; /* screen pointer, 8-bit specific */ + + s = (uint8_t *)screen->pixels; + + for (int i = 0; i < 320 * 200; ) + { + if ((*p & 0xc0) == 0xc0) + { + i += (*p & 0x3f); + memset(s, *(p + 1), (*p & 0x3f)); + s += (*p & 0x3f); p += 2; + } else { + i++; + *s = *p; + s++; p++; + } + if (i && (i % 320 == 0)) + { + s += screen->pitch - 320; + } + } + + free(buffer); + + memcpy(colors, palettes[pcxpal[PCXnumber]], sizeof(colors)); + + if (storepal) + set_palette(colors, 0, 255); +} + diff --git a/pool/shard006/C/0119001_prompter-tty.c b/pool/shard006/C/0119001_prompter-tty.c new file mode 100644 index 0000000000000000000000000000000000000000..0616a5cf2903b26aed99e8cb116db8a7bf917643 --- /dev/null +++ b/pool/shard006/C/0119001_prompter-tty.c @@ -0,0 +1,197 @@ +/* GNU Mailutils -- a suite of utilities for electronic mail + Copyright (C) 2010-2012 Free Software Foundation, Inc. + + GNU Mailutils is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + GNU Mailutils 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 GNU Mailutils. If not, see . */ + +/* MH prompter - traditional tty/termios support */ + +#include +#include "prompter.h" +#include "muaux.h" +#if HAVE_TERMIOS_H +# include +#endif + +mu_stream_t strin; +#if HAVE_TCGETATTR +struct termios tios; +#endif + +static int +decode_key (const char *keyseq) +{ + if (keyseq[0] == '^' && keyseq[1]) + { + if (keyseq[2]) + { + mu_error (_("invalid keysequence (%s near %d)"), + keyseq, 2); + exit (1); + } + return keyseq[1] + 0100; + } + else if (keyseq[0] == '\\') + { + int i; + int c = 0; + for (i = 1; i <= 3; i++) + { + int n; + switch (keyseq[i]) + { + case '0': + n = 0; + break; + case '1': + n = 1; + break; + case '2': + n = 2; + break; + case '3': + n = 3; + break; + case '4': + n = 4; + break; + case '5': + n = 5; + break; + case '6': + n = 6; + break; + case '7': + n = 7; + break; + default: + mu_error (_("invalid keysequence (%s near %d)"), + keyseq, i); + exit (1); + } + c = (c << 3) + n; + } + if (keyseq[i]) + { + mu_error (_("invalid keysequence (%s near %d)"), + keyseq, i); + exit (1); + } + return c; + } + else if (keyseq[1]) + { + mu_error (_("invalid keysequence (%s near %d)"), + keyseq, 2); + exit (1); + } + + return keyseq[0]; +} + +static RETSIGTYPE +sighan (int signo) +{ + prompter_done (); + exit (0); +} + +void +prompter_init () +{ + int rc; + if ((rc = mu_stdio_stream_create (&strin, MU_STDIN_FD, MU_STREAM_READ))) + { + mu_error (_("cannot open stdout: %s"), mu_strerror (rc)); + exit (1); + } +#if HAVE_TCGETATTR + rc = tcgetattr (MU_STDOUT_FD, &tios); + if (rc) + { + mu_error (_("tcgetattr failed: %s"), mu_strerror (rc)); + exit (1); + } + else + { + static int sigtab[] = { SIGPIPE, SIGABRT, SIGINT, SIGQUIT, SIGTERM }; + mu_set_signals (sighan, sigtab, MU_ARRAY_SIZE (sigtab)); + } +#endif +} + +void +prompter_done () +{ +#if HAVE_TCGETATTR + int rc = tcsetattr (MU_STDOUT_FD, TCSANOW, &tios); + if (rc) + mu_error (_("tcsetattr failed: %s"), mu_strerror (rc)); +#endif +} + +void +prompter_set_erase (const char *keyseq) +{ +#if HAVE_TCGETATTR + int rc; + struct termios t = tios; + + t.c_lflag |= ICANON; + t.c_cc[VERASE] = decode_key (keyseq); + rc = tcsetattr (MU_STDOUT_FD, TCSANOW, &t); + if (rc) + mu_error (_("tcsetattr failed: %s"), mu_strerror (rc)); +#endif +} + +void +prompter_set_kill (const char *keyseq) +{ +#if HAVE_TCGETATTR + int rc; + struct termios t = tios; + + t.c_lflag |= ICANON; + t.c_cc[VKILL] = decode_key (keyseq); + rc = tcsetattr (MU_STDOUT_FD, TCSANOW, &t); + if (rc) + mu_error (_("tcsetattr failed: %s"), mu_strerror (rc)); +#endif +} + +char * +prompter_get_value (const char *name) +{ + size_t size = 0, n; + char *buf = NULL; + + mu_stream_printf (strout, "%s: ", name); + mu_stream_flush (strout); + if (mu_stream_getline (strin, &buf, &size, &n) || n == 0) + return NULL; + mu_rtrim_cset (buf, "\n"); + return buf; +} + +char * +prompter_get_line () +{ + size_t size = 0, n; + char *buf = NULL; + + if (mu_stream_getline (strin, &buf, &size, &n) || n == 0) + return NULL; + mu_rtrim_cset (buf, "\n"); + return doteof_filter (buf); +} diff --git a/pool/shard006/C/0119002_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c b/pool/shard006/C/0119002_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c new file mode 100644 index 0000000000000000000000000000000000000000..555ca32d1c784d228767fe71d3d547ba31688853 --- /dev/null +++ b/pool/shard006/C/0119002_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c @@ -0,0 +1,150 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c +Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml +Template File: sources-sink-11.tmpl.c +*/ +/* + * @description + * CWE: 195 Signed to Unsigned Conversion Error + * BadSource: fgets Read data from the console using fgets() + * GoodSource: Positive integer + * Sink: malloc + * BadSink : Allocate memory using malloc() with the size of data + * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) + +#ifndef OMITBAD + +void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_bad() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsTrue()) + { + { + char inputBuffer[CHAR_ARRAY_SIZE] = ""; + /* POTENTIAL FLAW: Read data from the console using fgets() */ + if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) + { + /* Convert to int */ + data = atoi(inputBuffer); + } + else + { + printLine("fgets() failed."); + } + } + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ +static void goodG2B1() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsTrue()) + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0119013_pop3_timer.c b/pool/shard006/C/0119013_pop3_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..50332790dd0b20eb3d7069f195104fad72867952 --- /dev/null +++ b/pool/shard006/C/0119013_pop3_timer.c @@ -0,0 +1,73 @@ +/* libpop3 0.5 -:- (C)opyright 2001 - 2004 Kristian Van Der Vliet +/ +/ This library is free software; you can redistribute it and/or +/ modify it under the terms of the GNU Library General Public +/ License as published by the Free Software Foundation; either +/ version 2 of the License, or (at your option) any later version. +/ +/ 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 +/ Library General Public License for more details. +/ +/ You should have received a copy of the GNU Library 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 +#include +#include + +/* Internal functions, mostly used to deal with timeout signals */ +static void __pop3_sig_handler( int signal, siginfo_t *info, void *data ) +{ + /* Handle signals; only deal with SIGALRM */ + switch( info->si_signo ) + { + case SIGALRM: + { + struct pop3_session *session = (struct pop3_session*)data; + if( session ) + session->status |= POP3_TIME; + } + } +} + +int __pop3_setup_sighandler( const struct pop3_session *session ) +{ + struct sigaction sig_action; + + /* Setup the signal handler to catch SIGALRM timeout signals */ + sig_action.sa_sigaction = __pop3_sig_handler; + sig_action.sa_flags = SA_NOMASK | SA_SIGINFO; + if( sigaction( SIGALRM, &sig_action, &session->old_sigaction ) < 0 ) + return ECONNABORTED; + return 0; +} + +void __pop3_teardown_sighandler( const struct pop3_session *session ) +{ + /* Reset the current signal handlers to their previous configuration */ + if( session ) + sigaction( SIGALRM, &session->old_sigaction, NULL ); +} + +void __pop3_start_timer( const struct pop3_session *session ) +{ + /* Setup a timer to generate SIGALRM after the timeout period elapses */ + struct itimerval alarm; + alarm.it_interval.tv_sec = session->timeout; + setitimer( ITIMER_REAL, &alarm, NULL ); +} + +void __pop3_stop_timer( struct pop3_session *session ) +{ + /* Clear a currently running timer */ + struct itimerval alarm; + alarm.it_interval.tv_sec = 0; + setitimer( ITIMER_REAL, &alarm, NULL ); + if( session->status & POP3_TIME ) + session->status ^= POP3_TIME; +} diff --git a/pool/shard006/C/0119014_rpf.c b/pool/shard006/C/0119014_rpf.c new file mode 100644 index 0000000000000000000000000000000000000000..e76319cc861910b9764d19b53e08ad73765a0700 --- /dev/null +++ b/pool/shard006/C/0119014_rpf.c @@ -0,0 +1,223 @@ +/* + * rpf.c: Conversion of float to reduced precision format values + * + * Written by: Stefan Frank + * Richard Krampfl + * Ullrich Hafner + * + * This file is part of FIASCO ([F]ractal [I]mage [A]nd [S]equence [CO]dec) + * Copyright (C) 1994-2000 Ullrich Hafner + */ + +/* + * $Date: 2000/06/14 20:49:37 $ + * $Author: hafner $ + * $Revision: 5.1 $ + * $State: Exp $ + */ + +#include "config.h" + +#include "types.h" +#include "macros.h" +#include "error.h" + +#include "misc.h" +#include "rpf.h" + +/* + * CAUTION: The IEEE float format must be used by your compiler, + * or all following code is void! + */ + +#ifdef WORDS_BIGENDIAN +/* + * Big-Endian Architecture (e.g. SUN, Motorola) + * Memory representation of integer 0x00112233 is 00,11,22,33 + */ + +enum real_bytes {BYTE_0, BYTE_1, BYTE_2, BYTE_3}; + +#else /* not WORDS_BIGENDIAN */ +/* + * Little-Endian Architecture (e.g. Intel, VAX, Alpha) + * Memory representation of integer 0x00112233 is 33,22,11,00 + */ + +enum real_bytes {BYTE_3, BYTE_2, BYTE_1, BYTE_0}; + +#endif /* not WORDS_BIGENDIAN */ + +const int RPF_ZERO = -1; + +/***************************************************************************** + + private code + +*****************************************************************************/ + +int +rtob (real_t f, const rpf_t *rpf) +/* + * Convert real number 'f' into fixed point format. + * The real number in [-'range'; +'range'] is scaled to [-1 ; +1]. + * Sign and the first 'precision' - 1 bits of the mantissa are + * packed into one integer. + * + * Return value: + * real value in reduced precision format + */ +{ + unsigned int mantissa; + int exponent, sign; + union + { + float f; + unsigned char c[4]; + } v; /* conversion dummy */ + + f /= rpf->range; /* scale f to [-1,+1] */ + v.f = f; + + /* + * Extract mantissa (23 Bits), exponent (8 Bits) and sign (1 Bit) + */ + + mantissa = ((((v.c[BYTE_1] & 127) << 8 ) | v.c[BYTE_2]) << 8) | v.c[BYTE_3]; + exponent = (((v.c[BYTE_0] & 127) << 1) | (v.c[BYTE_1] & 128 ? 1 : 0)) - 126; + sign = v.c[BYTE_0] & 128 ? 1 : 0; + + /* + * Generate reduced precision mantissa. + */ + mantissa >>= 1; /* shift 1 into from left */ + mantissa |= (1 << 22); + if (exponent > 0) + mantissa <<= exponent; + else + mantissa >>= -exponent; + + mantissa >>= (23 - rpf->mantissa_bits - 1); + + mantissa += 1; /* Round last bit. */ + mantissa >>= 1; + + if (mantissa == 0) /* close to zero */ + return RPF_ZERO; + else if (mantissa >= (1U << rpf->mantissa_bits)) /* overflow */ + return sign; + else + return ((mantissa & ((1U << rpf->mantissa_bits) - 1)) << 1) | sign; +} + +float +btor (int binary, const rpf_t *rpf) +/* + * Convert value 'binary' in reduced precision format to a real value. + * For more information refer to function lin_rtob() above. + * + * Return value: + * converted value + */ +{ + unsigned int mantissa; + int sign, exponent; + union + { + float f; + unsigned char c[4]; + } value; + + if (binary == RPF_ZERO) + return 0; + + if (binary < 0 || binary >= 1 << (rpf->mantissa_bits + 1)) + error ("Reduced precision format: value %d out of range.", binary); + + /* + * Restore IEEE float format: + * mantissa (23 Bits), exponent (8 Bits) and sign (1 Bit) + */ + + sign = binary & 1; + mantissa = (binary & ((1 << (rpf->mantissa_bits + 1)) - 1)) >> 1; + mantissa <<= (23 - rpf->mantissa_bits); + exponent = 0; + + if (mantissa == 0) + { + value.f = (sign ? -1.0 : 1.0); + } + else + { + while (!(mantissa & (1 << 22))) /* normalize mantissa */ + { + exponent--; + mantissa <<= 1; + } + mantissa <<= 1; + + value.c[BYTE_0] = (sign << 7) | ((exponent + 126) >> 1); + value.c[BYTE_1] = (((exponent + 126) & 1) << 7) + | ((mantissa >> 16) & 127); + value.c[BYTE_2] = (mantissa >> 8) & 255; + value.c[BYTE_3] = mantissa & 255; + } + + return value.f * rpf->range; /* expand [ -1 ; +1 ] to + [ -range ; +range ] */ +} + +rpf_t * +alloc_rpf (unsigned mantissa, fiasco_rpf_range_e range) +/* + * Reduced precision format constructor. + * Allocate memory for the rpf_t structure. + * Number of mantissa bits is given by `mantissa'. + * The range of the real values is in the interval [-`range', +`range']. + * In case of invalid parameters, a structure with default values is + * returned. + * + * Return value + * pointer to the new rpf structure + */ +{ + rpf_t *rpf = fiasco_calloc (1, sizeof (rpf_t)); + + if (mantissa < 2) + { + warning (_("Size of RPF mantissa has to be in the interval [2,8]. " + "Using minimum value 2.\n")); + mantissa = 2; + } + else if (mantissa > 8) + { + warning (_("Size of RPF mantissa has to be in the interval [2,8]. " + "Using maximum value 8.\n")); + mantissa = 2; + } + + rpf->mantissa_bits = mantissa; + rpf->range_e = range; + switch (range) + { + case FIASCO_RPF_RANGE_0_75: + rpf->range = 0.75; + break; + case FIASCO_RPF_RANGE_1_50: + rpf->range = 1.50; + break; + case FIASCO_RPF_RANGE_2_00: + rpf->range = 2.00; + break; + case FIASCO_RPF_RANGE_1_00: + rpf->range = 1.00; + break; + default: + warning (_("Invalid RPF range specified. Using default value 1.0.")); + rpf->range = 1.00; + rpf->range_e = FIASCO_RPF_RANGE_1_00; + break; + } + return rpf; +} diff --git a/pool/shard006/C/0119025_E10_ex1.c b/pool/shard006/C/0119025_E10_ex1.c new file mode 100644 index 0000000000000000000000000000000000000000..c40c0d1b42cb01515630cd05306464922856905e --- /dev/null +++ b/pool/shard006/C/0119025_E10_ex1.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +sem_t sem1; +sem_t sem2; +sem_t sem3; +sem_t sem4; +sem_t sem5; +sem_t sem6; + +static void *readFile (void *); + +int main (){ + + int ret=0,i=0; + pthread_t tids[6]; + + if(sem_init (&sem1, 0, 1)!=0){ + printf("Semaphore initialize failed"); + exit(EXIT_FAILURE); + } + if(sem_init (&sem2, 0, 0)!=0){ + printf("Semaphore initialize failed"); + exit(EXIT_FAILURE); + } + if(sem_init (&sem3, 0, 0)!=0){ + printf("Semaphore initialize failed"); + exit(EXIT_FAILURE); + } + if(sem_init (&sem4, 0, 0)!=0){ + printf("Semaphore initialize failed"); + exit(EXIT_FAILURE); + } + if(sem_init (&sem5, 0, 0)!=0){ + printf("Semaphore initialize failed"); + exit(EXIT_FAILURE); + } + if(sem_init (&sem6, 0, 0)!=0){ + printf("Semaphore initialize failed"); + exit(EXIT_FAILURE); + } + + ret = pthread_create(&tids[0], NULL, readFile,(void*)&"A"); + if (ret) + printf("Thread creation failed!!\n");exit(EXIT_FAILURE); + + ret = pthread_create(&tids[1], NULL, readFile,(void*)&"B"); + if (ret) + printf("Thread creation failed!!\n");exit(EXIT_FAILURE); + + ret = pthread_create(&tids[2], NULL, readFile,(void*)&"C"); + if (ret) + printf("Thread creation failed!!\n");exit(EXIT_FAILURE); + + ret = pthread_create(&tids[3], NULL, readFile,(void*)&"D"); + if (ret) + printf("Thread creation failed!!\n");exit(EXIT_FAILURE); + + ret = pthread_create(&tids[4], NULL, readFile,(void*)&"E"); + if (ret) + printf("Thread creation failed!!\n");exit(EXIT_FAILURE); + + ret = pthread_create(&tids[5], NULL, readFile,(void*)&"F"); + if (ret) + printf("Thread creation failed!!\n");exit(EXIT_FAILURE); + + for (i=0; i<6; i++) { + pthread_join (tids[i], (void**)&ret); + } + + return 0; +} + +static void *readFile (void *arg){ + char* t = (char*)arg; + int i=0; + for (i=0; i<10; i++) { + if (strcmp(t, "A")==0) { + sem_wait (&sem1); + printf("A"); + printf("\n"); + sem_post (&sem2); + sem_post (&sem3); + }else if (strcmp(t, "B")==0){ + sem_wait (&sem2); + printf("B"); + printf("\n"); + sem_post (&sem4); + }else if (strcmp(t, "C")==0){ + sem_wait (&sem3); + printf("C"); + printf("\n"); + sem_post (&sem4); + }else if (strcmp(t, "D")==0){ + sem_wait (&sem4); + sem_wait (&sem4); + printf("D"); + printf("\n"); + sem_post (&sem1); + }else{ + pthread_exit ((void *) 1); + return NULL; + } + } + pthread_exit ((void *) 1); + return NULL; +} diff --git a/pool/shard006/C/0119028_cmpiTestIndicationProvider.c b/pool/shard006/C/0119028_cmpiTestIndicationProvider.c new file mode 100644 index 0000000000000000000000000000000000000000..b1ecdeed1b5a8f3db300b1e35acfa39810c14038 --- /dev/null +++ b/pool/shard006/C/0119028_cmpiTestIndicationProvider.c @@ -0,0 +1,176 @@ +#include +#include +#include + +#define CMPI_VER_86 + +#include "cmpidt.h" +#include "cmpift.h" +#include "cmpimacs.h" + +static const CMPIBroker *broker; + +unsigned char CMPI_true = 1; +unsigned char CMPI_false = 0; + +static int enabled = 0; +static int _nextUID = 0; + + +static void +generateIndication (const char *methodname, const CMPIContext * ctx) +{ + + CMPIInstance *inst; + CMPIObjectPath *cop; + CMPIDateTime *dat; + CMPIArray *ar; + CMPIStatus rc; + char buffer[32]; + + if (enabled) + { + cop = + CMNewObjectPath (broker, "root/cimv2", + "Test_Indication", &rc); + inst = CMNewInstance (broker, cop, &rc); + + sprintf (buffer, "%d", _nextUID++); + CMSetProperty (inst, "IndicationIdentifier", buffer, CMPI_chars); + + dat = CMNewDateTime (broker, &rc); + CMSetProperty (inst, "IndicationTime", &dat, CMPI_dateTime); + + CMSetProperty (inst, "MethodName", methodname, CMPI_chars); + + ar = CMNewArray (broker, 0, CMPI_string, &rc); + CMSetProperty (inst, "CorrelatedIndications", &ar, CMPI_stringA); + + rc = CBDeliverIndication (broker, ctx, "root/interop", inst); + if (rc.rc != CMPI_RC_OK) + { + fprintf (stderr, "+++ Could not send the indication!\n"); + } + } + fprintf (stderr, "+++ generateIndication() done\n"); +} + +//---------------------------------------------------------- +//--- +// Method Provider +//--- +//---------------------------------------------------------- + + +CMPIStatus +indProvMethodCleanup (CMPIMethodMI * cThis, const CMPIContext * ctx, + CMPIBoolean term) +{ + CMReturn (CMPI_RC_OK); +} + +CMPIStatus indProvInvokeMethod + (CMPIMethodMI * cThis, const CMPIContext * ctx, const CMPIResult * rslt, + const CMPIObjectPath * cop, const char *method, const CMPIArgs * in, + CMPIArgs * out) +{ + CMPIValue value; + fprintf (stderr, "+++ indProvInvokeMethod()\n"); + + if (enabled == 0) + { + fprintf (stderr, "+++ PROVIDER NOT ENABLED\n"); + } + else + { + generateIndication (method, ctx); + } + + value.uint32 = 0; + CMReturnData (rslt, &value, CMPI_uint32); + CMReturnDone (rslt); + CMReturn (CMPI_RC_OK); +} + +//---------------------------------------------------------- +//--- +// Indication Provider +//--- +//---------------------------------------------------------- + + +CMPIStatus +indProvIndicationCleanup (CMPIIndicationMI * cThis, const CMPIContext * ctx, + CMPIBoolean term) +{ + CMReturn (CMPI_RC_OK); +} + +CMPIStatus indProvAuthorizeFilter + (CMPIIndicationMI * cThis, const CMPIContext * ctx, + const CMPISelectExp * filter, const char *indType, + const CMPIObjectPath * classPath, const char *owner) +{ + + CMReturn (CMPI_RC_OK); +} + +CMPIStatus indProvMustPoll + (CMPIIndicationMI * cThis, const CMPIContext * ctx, + const CMPISelectExp * filter, const char *indType, + const CMPIObjectPath * classPath) +{ + + CMReturn (CMPI_RC_OK); +} + +CMPIStatus indProvActivateFilter + (CMPIIndicationMI * cThis, const CMPIContext * ctx, + const CMPISelectExp * exp, const char *clsName, + const CMPIObjectPath * classPath, CMPIBoolean firstActivation) +{ + fprintf (stderr, "+++ indProvActivateFilter()\n"); + enabled=1; + fprintf (stderr, "--- enabled: %d\n", enabled); + CMReturn (CMPI_RC_OK); +} + +CMPIStatus indProvDeActivateFilter + (CMPIIndicationMI * cThis, const CMPIContext * ctx, + const CMPISelectExp * filter, const char *clsName, + const CMPIObjectPath * classPath, CMPIBoolean lastActivation) +{ + fprintf (stderr, "+++ indProvDeActivateFilter\n"); + enabled=0; + fprintf (stderr, "--- disabled: %d\n", enabled); + CMReturn (CMPI_RC_OK); +} + +CMPIStatus +indProvEnableIndications (CMPIIndicationMI * cThis, const CMPIContext * ctx) +{ + fprintf (stderr, "+++ indProvEnableIndications\n"); + CMReturn (CMPI_RC_OK); +} + +CMPIStatus +indProvDisableIndications (CMPIIndicationMI * cThis, const CMPIContext * ctx) +{ + fprintf (stderr, "+++ indProvDisableIndications\n"); + CMReturn (CMPI_RC_OK); +} + + +//---------------------------------------------------------- +//--- +// Provider Factory Stubs +//--- +//---------------------------------------------------------- + +CMMethodMIStub (indProv, TestIndicationProvider, broker, CMNoHook) +//---------------------------------------------------------- + + +CMIndicationMIStub (indProv, TestIndicationProvider, broker, CMNoHook) + +//---------------------------------------------------------- diff --git a/pool/shard006/C/0119030_yaffs_mtdif2.c b/pool/shard006/C/0119030_yaffs_mtdif2.c new file mode 100644 index 0000000000000000000000000000000000000000..90b19a8706461b8dafd36d95a727c94a84752680 --- /dev/null +++ b/pool/shard006/C/0119030_yaffs_mtdif2.c @@ -0,0 +1,270 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein + * is confidential and proprietary to MediaTek Inc. and/or its licensors. + * Without the prior written permission of MediaTek inc. and/or its licensors, + * any reproduction, modification, use or disclosure of MediaTek Software, + * and information contained herein, in whole or in part, shall be strictly prohibited. + * + * MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON + * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. + * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE + * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR + * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH + * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES + * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES + * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK + * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND + * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, + * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, + * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO + * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek Software") + * have been modified by MediaTek Inc. All revisions are subject to any receiver's + * applicable license agreements with MediaTek Inc. + */ + +/* + * YAFFS: Yet Another Flash File System. A NAND-flash specific file system. + * + * Copyright (C) 2002-2007 Aleph One Ltd. + * for Toby Churchill Ltd and Brightstar Engineering + * + * Created by Charles Manning + * + * 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. + */ + +/* mtd interface for YAFFS2 */ + +/* XXX U-BOOT XXX */ +#include +#include "asm/errno.h" + +const char *yaffs_mtdif2_c_version = + "$Id: yaffs_mtdif2.c,v 1.17 2007/02/14 01:09:06 wookey Exp $"; + +#include "yportenv.h" + + +#include "yaffs_mtdif2.h" + +#include "linux/mtd/mtd.h" +#include "linux/types.h" +#include "linux/time.h" + +#include "yaffs_packedtags2.h" + +int nandmtd2_WriteChunkWithTagsToNAND(yaffs_Device * dev, int chunkInNAND, + const __u8 * data, + const yaffs_ExtendedTags * tags) +{ + struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) + struct mtd_oob_ops ops; +#else + size_t dummy; +#endif + int retval = 0; + + loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk; + + yaffs_PackedTags2 pt; + + T(YAFFS_TRACE_MTD, + (TSTR + ("nandmtd2_WriteChunkWithTagsToNAND chunk %d data %p tags %p" + TENDSTR), chunkInNAND, data, tags)); + +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) + if (tags) + yaffs_PackTags2(&pt, tags); + else + BUG(); /* both tags and data should always be present */ + + if (data) { + ops.mode = MTD_OOB_AUTO; + ops.ooblen = sizeof(pt); + ops.len = dev->nDataBytesPerChunk; + ops.ooboffs = 0; + ops.datbuf = (__u8 *)data; + ops.oobbuf = (void *)&pt; + retval = mtd->write_oob(mtd, addr, &ops); + } else + BUG(); /* both tags and data should always be present */ +#else + if (tags) { + yaffs_PackTags2(&pt, tags); + } + + if (data && tags) { + if (dev->useNANDECC) + retval = + mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk, + &dummy, data, (__u8 *) & pt, NULL); + else + retval = + mtd->write_ecc(mtd, addr, dev->nDataBytesPerChunk, + &dummy, data, (__u8 *) & pt, NULL); + } else { + if (data) + retval = + mtd->write(mtd, addr, dev->nDataBytesPerChunk, &dummy, + data); + if (tags) + retval = + mtd->write_oob(mtd, addr, mtd->oobsize, &dummy, + (__u8 *) & pt); + + } +#endif + + if (retval == 0) + return YAFFS_OK; + else + return YAFFS_FAIL; +} + +int nandmtd2_ReadChunkWithTagsFromNAND(yaffs_Device * dev, int chunkInNAND, + __u8 * data, yaffs_ExtendedTags * tags) +{ + struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) + struct mtd_oob_ops ops; +#endif + size_t dummy; + int retval = 0; + + loff_t addr = ((loff_t) chunkInNAND) * dev->nDataBytesPerChunk; + + yaffs_PackedTags2 pt; + + T(YAFFS_TRACE_MTD, + (TSTR + ("nandmtd2_ReadChunkWithTagsFromNAND chunk %d data %p tags %p" + TENDSTR), chunkInNAND, data, tags)); + +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)) + if (data && !tags) + retval = mtd->read(mtd, addr, dev->nDataBytesPerChunk, + &dummy, data); + else if (tags) { + ops.mode = MTD_OOB_AUTO; + ops.ooblen = sizeof(pt); + ops.len = data ? dev->nDataBytesPerChunk : sizeof(pt); + ops.ooboffs = 0; + ops.datbuf = data; + ops.oobbuf = dev->spareBuffer; + retval = mtd->read_oob(mtd, addr, &ops); + } +#else + if (data && tags) { + if (dev->useNANDECC) { + retval = + mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk, + &dummy, data, dev->spareBuffer, + NULL); + } else { + retval = + mtd->read_ecc(mtd, addr, dev->nDataBytesPerChunk, + &dummy, data, dev->spareBuffer, + NULL); + } + } else { + if (data) + retval = + mtd->read(mtd, addr, dev->nDataBytesPerChunk, &dummy, + data); + if (tags) + retval = + mtd->read_oob(mtd, addr, mtd->oobsize, &dummy, + dev->spareBuffer); + } +#endif + + memcpy(&pt, dev->spareBuffer, sizeof(pt)); + + if (tags) + yaffs_UnpackTags2(tags, &pt); + + if(tags && retval == -EBADMSG && tags->eccResult == YAFFS_ECC_RESULT_NO_ERROR) + tags->eccResult = YAFFS_ECC_RESULT_UNFIXED; + + if (retval == 0) + return YAFFS_OK; + else + return YAFFS_FAIL; +} + +int nandmtd2_MarkNANDBlockBad(struct yaffs_DeviceStruct *dev, int blockNo) +{ + struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); + int retval; + T(YAFFS_TRACE_MTD, + (TSTR("nandmtd2_MarkNANDBlockBad %d" TENDSTR), blockNo)); + + retval = + mtd->block_markbad(mtd, + blockNo * dev->nChunksPerBlock * + dev->nDataBytesPerChunk); + + if (retval == 0) + return YAFFS_OK; + else + return YAFFS_FAIL; + +} + +int nandmtd2_QueryNANDBlock(struct yaffs_DeviceStruct *dev, int blockNo, + yaffs_BlockState * state, int *sequenceNumber) +{ + struct mtd_info *mtd = (struct mtd_info *)(dev->genericDevice); + int retval; + + T(YAFFS_TRACE_MTD, + (TSTR("nandmtd2_QueryNANDBlock %d" TENDSTR), blockNo)); + retval = + mtd->block_isbad(mtd, + blockNo * dev->nChunksPerBlock * + dev->nDataBytesPerChunk); + + if (retval) { + T(YAFFS_TRACE_MTD, (TSTR("block is bad" TENDSTR))); + + *state = YAFFS_BLOCK_STATE_DEAD; + *sequenceNumber = 0; + } else { + yaffs_ExtendedTags t; + nandmtd2_ReadChunkWithTagsFromNAND(dev, + blockNo * + dev->nChunksPerBlock, NULL, + &t); + + if (t.chunkUsed) { + *sequenceNumber = t.sequenceNumber; + *state = YAFFS_BLOCK_STATE_NEEDS_SCANNING; + } else { + *sequenceNumber = 0; + *state = YAFFS_BLOCK_STATE_EMPTY; + } + } + T(YAFFS_TRACE_MTD, + (TSTR("block is bad seq %d state %d" TENDSTR), *sequenceNumber, + *state)); + + if (retval == 0) + return YAFFS_OK; + else + return YAFFS_FAIL; +} diff --git a/pool/shard006/C/0119033_lge_factory_misc.c b/pool/shard006/C/0119033_lge_factory_misc.c new file mode 100644 index 0000000000000000000000000000000000000000..01dd6b8cd81925fb244861f68f6c6787fd275ec3 --- /dev/null +++ b/pool/shard006/C/0119033_lge_factory_misc.c @@ -0,0 +1,88 @@ +/* drivers/misc/lge_factory_misc.c + * + * Interface to calibrate display color temperature. + * + * Copyright (C) 2015 LGE + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include "lge_factory_misc.h" + +static struct platform_device factory_misc_platrom_device = { + .name = "factory_misc", +}; + +static int __init factory_misc_init(void) +{ + return platform_device_register(&factory_misc_platrom_device); +} + +static ssize_t key_lock_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + int value; + if (sscanf(buf, "%d", &value) <= 0) + return count; + + printk("**************************** Key lock %d ****************************\n", value); + + evdev_set_event_lock(value); + + return count; +} + +static ssize_t key_lock_show(struct device *dev, struct device_attribute *attr, + char *buf) +{ + ssize_t ret_len = 0; + bool key_lock_status = evdev_get_event_lock(); + ret_len = snprintf(buf, PAGE_SIZE, + "Key lock status %s\n", + key_lock_status ? "Enabled" : "Disabled"); + + return ret_len; +} + +static DEVICE_ATTR(key_lock, 0644, key_lock_show, key_lock_store); + +static int factory_misc_ctrl_probe(struct platform_device *pdev) +{ + if (device_create_file(&pdev->dev, &dev_attr_key_lock) !=0) + return -EPERM; + + return 0; +} + +static struct platform_driver this_driver = { + .probe = factory_misc_ctrl_probe, + .driver = { + .name = "factory_misc", + }, +}; + +int __init factory_misc_ctrl_init(void) +{ + return platform_driver_register(&this_driver); +} + +device_initcall(factory_misc_init); +device_initcall(factory_misc_ctrl_init); + + +MODULE_DESCRIPTION("LGE factory misc driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard006/C/0119034_ppopt.c b/pool/shard006/C/0119034_ppopt.c new file mode 100644 index 0000000000000000000000000000000000000000..32cdfc9c9638b5f433bc65446aee958a9e9cb6ee --- /dev/null +++ b/pool/shard006/C/0119034_ppopt.c @@ -0,0 +1,256 @@ + +/* Pre-processing routines to for OPT simulation */ + +#include +#include + +#include "../host.h" +#include "../misc.h" +#include "../machine.h" +#include "libcheetah.h" + +#define toggle(i) if(i==1)i=0;else{i=1;} + +#define LA_DIST 100000 /* Lookahead distance */ +#define HASHNO 7211 + +struct ft_hash_table { + md_addr_t addr; + int pt; + struct ft_hash_table *nxt; +} ft_slot[HASHNO]; + +short ft_slot_flag[HASHNO]; /* Hash table */ + +unsigned addr_array[2*LA_DIST], /* Trace input to stack_proc */ + time_array[2*LA_DIST]; /* Next time of arrival of addresses */ + +static int la_limit, /* Look-ahead limit in current iteration */ + base, /* Base time in current iteration */ + oe_flag=1; /* Whether top or bottom half of array */ + +static int p_inum; /* Address count */ + + +/*************************************************************** +Free list handlers +***************************************************************/ + +static struct ft_hash_table *head_free_list; + +void +LA_Add_to_free_list(struct ft_hash_table *free_ptr) +{ + free_ptr->nxt = head_free_list; + head_free_list = free_ptr; +} + + +struct ft_hash_table * +LA_Get_from_free_list(void) +{ + struct ft_hash_table *free_ptr; + + if (head_free_list == NULL) + return NULL; + else + { + free_ptr = head_free_list; + head_free_list = head_free_list->nxt; + return free_ptr; + } +} + + +/*************************************************************** +Hashing routine. Adds addr to the hash table + +Input: address +Output: -1 if addr is not found + previous time of arrival if it is +Side effects: An entry for address is added to the hash table if address + is not found. +***************************************************************/ + +int +ft_hash(md_addr_t addr) /* address to be looked up */ +{ + int loc; + int prev_time = 0; + struct ft_hash_table *ptr, *oldptr; + + loc = addr % HASHNO; + if (ft_slot_flag[loc] == 0) + { + /* ++tot_addrs;*/ + ft_slot_flag[loc] = 1; + ft_slot[loc].addr = addr; + ft_slot[loc].nxt = NULL; + ft_slot[loc].pt = p_inum; + return -1; + } + else + { + ptr = &ft_slot[loc]; + while (ptr) + { + oldptr = ptr; + if (ptr->addr == addr) + break; + ptr = ptr->nxt; + } + if (ptr) + { + prev_time = ptr->pt; + ptr->pt = p_inum; + return(prev_time); + } + else + { + /*++tot_addrs;*/ + if ((oldptr->nxt = LA_Get_from_free_list()) == NULL) + { + oldptr->nxt = calloc(1, sizeof(struct ft_hash_table)); + if (!oldptr->nxt) + fatal("out of virtual memory"); + } + oldptr->nxt->addr = addr; + oldptr->nxt->nxt = NULL; + oldptr->nxt->pt = p_inum; + return -1; + } + } +} + + +/************************************************************************ +Deletes addresses from the hash table. It is used when entries are deleted +from the stack due to stack overflow. + +Input: Address +Output: None +Side effects: The entry for the address is deleted from the hash table + (The address need not necessarily be found, (e.g.) when + an address is referenced multiple times in the same window + and both references overflow). +*************************************************************************/ +void +ft_hash_del(md_addr_t addr) +{ + int loc; /* Scratch variables */ + struct ft_hash_table *ptr, *oldptr; + + loc = addr % HASHNO; + if (ft_slot_flag[loc] == 0) + printf ("Error: addr not found in hash_table\n"); + else if (ft_slot[loc].addr == addr) + { + if (ft_slot[loc].nxt == NULL) + ft_slot_flag[loc] = 0; + else + { + ft_slot[loc].addr = ft_slot[loc].nxt->addr; + ft_slot[loc].pt = ft_slot[loc].nxt->pt; + ptr = ft_slot[loc].nxt; + ft_slot[loc].nxt = ft_slot[loc].nxt->nxt; + LA_Add_to_free_list(ptr); + } + } + else + { + ptr = &ft_slot[loc]; + while (ptr) + { + if (ptr->addr == addr) + break; + oldptr = ptr; + ptr = ptr->nxt; + } + if (ptr) + { + oldptr->nxt = ptr->nxt; + LA_Add_to_free_list(ptr); + } + else + printf("Error: addr not found in hash_table\n"); + } +} + + +/********************************************************************* +Pre-processor for optimal simulation. Reads in trace addresses and goes back +to their previous point of reference and stores current time. The stack +processing routine can use this information to determine the priority of +addresses. There is a lookahead of at least LA_DIST always. +Calls 'inf_handler' to correct the stack when an address +whose priority was unknown is encountered. + +Input: the line size +Output: None +Side effects: Does pre-processing on the trace and calls stack_proc till + the trace is processed or the limit on the address count is + reached (checked inside stack_proc). +*********************************************************************/ + +static int start, end; + +void +init_optpp(void) +{ + la_limit = 2*LA_DIST; + base = 0; +} + +void +optpp(md_addr_t addr, int L, + int (*stack_proc)(int start, int end), + void (*inf_handler)(md_addr_t addr, int cur_time)) +{ + int prev_time, sf; + + if (p_inum > la_limit-1) + { + start = (la_limit % (2*LA_DIST)); + end = start + LA_DIST; + if ((sf = (*stack_proc)(start, end)) == 1) + return; + la_limit += LA_DIST; + toggle(oe_flag); + if (oe_flag) + base += 2*LA_DIST; + } + addr >>= L; + addr_array[(p_inum - base) % (2*LA_DIST)] = addr; + if ((prev_time = ft_hash(addr)) >= 0) + { + if ((la_limit - prev_time) <= 2*LA_DIST) + time_array[(prev_time - base) % (2*LA_DIST)] = p_inum; + else + (*inf_handler)(addr, p_inum); + } + else + (*inf_handler)(addr, p_inum); + ++p_inum; +} + + +/* residual processing */ +void +term_optpp(int (*stack_proc)()) +{ + start = la_limit % (2*LA_DIST); + end = start + LA_DIST; + if (p_inum < LA_DIST) + end = p_inum; /* For small traces */ + (*stack_proc)(start, end); + if (p_inum >= LA_DIST) + { + toggle(oe_flag); + if (oe_flag) + base += 2*LA_DIST; + la_limit += LA_DIST; + start = la_limit % (2*LA_DIST); + end = start + (((p_inum % LA_DIST) == 0) ? LA_DIST : (p_inum % LA_DIST)); + (*stack_proc)(start, end); + } +} diff --git a/pool/shard006/C/0119035_advanced.c b/pool/shard006/C/0119035_advanced.c new file mode 100644 index 0000000000000000000000000000000000000000..4a19e7e6d70531100d62a120c596e8b5f88d95f6 --- /dev/null +++ b/pool/shard006/C/0119035_advanced.c @@ -0,0 +1,224 @@ +/********************************************************************/ +/* */ +/* L I QQ U U I DD W W A RR 555 */ +/* L I Q Q U U I D D W W A A R R 5 */ +/* L I Q Q U U I D D W W W AAA RR 55 */ +/* L I Q Q U U I D D WW WW A A R R 5 */ +/* LLL I Q Q U I DD W W A A R R 55 */ +/* */ +/* b */ +/* bb y y */ +/* b b yyy */ +/* bb y */ +/* yy */ +/* */ +/* U U FFF O O TTT */ +/* U U F O O O O T */ +/* U U TIRET FF O O O O T */ +/* U U F O O O O T */ +/* U F O O T */ +/* */ +/********************************************************************/ + +/*****************************************************************************/ +/* Liquid War is a multiplayer wargame */ +/* Copyright (C) 1998-2013 Christian Mauduit */ +/* */ +/* This program is free software; you can redistribute it and/or modify */ +/* it under the terms of the GNU General Public License as published by */ +/* the Free Software Foundation; either version 2 of the License, or */ +/* (at your option) any later version. */ +/* */ +/* This program is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ +/* GNU General Public License for more details. */ +/* */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program; if not, write to the Free Software */ +/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ +/* */ +/* Liquid War homepage : http://www.ufoot.org/liquidwar/v5 */ +/* Contact author : ufoot@ufoot.org */ +/*****************************************************************************/ + +/********************************************************************/ +/* nom : advanced.c */ +/* contenu : choix des options de jeu avancees */ +/* date de modif : 3 mai 98 */ +/********************************************************************/ + +/*==================================================================*/ +/* includes */ +/*==================================================================*/ + +#include + +#include "advanced.h" +#include "config.h" +#include "dialog.h" +#include "disk.h" +#include "help.h" +#include "time.h" +#include "menu.h" +#include "log.h" +#include "lang.h" + +/*==================================================================*/ +/* variables globales */ +/*==================================================================*/ + +/*------------------------------------------------------------------*/ +static char * +get_asm_algorithm_str (void) +{ + if (CONFIG_ASM_ALGORITHM) + return (lw_lang_string (LW_LANG_STRING_ADVANCED_ASSEMBLY)); + else + return (lw_lang_string (LW_LANG_STRING_ADVANCED_STANDARDC)); +} + +/*------------------------------------------------------------------*/ +static char * +get_cpu_vs_human_str (void) +{ + char *result = ""; + + switch (CONFIG_CPU_VS_HUMAN) + { + case CONFIG_CPU_VS_HUMAN_ALWAYS: + result = (lw_lang_string (LW_LANG_STRING_ADVANCED_ALWAYS)); + break; + case CONFIG_CPU_VS_HUMAN_NEVER: + result = (lw_lang_string (LW_LANG_STRING_ADVANCED_NEVER)); + break; + default: + result = (lw_lang_string (LW_LANG_STRING_ADVANCED_RANDOM)); + break; + } + + return result; +} + +/*------------------------------------------------------------------*/ +static char * +get_allow_network_bots_str (void) +{ + if (CONFIG_ALLOW_NETWORK_BOTS) + return (lw_lang_string (LW_LANG_STRING_ADVANCED_YES)); + else + return (lw_lang_string (LW_LANG_STRING_ADVANCED_NO)); +} + +/*==================================================================*/ +/* fonctions */ +/*==================================================================*/ + +/*------------------------------------------------------------------*/ +int +advanced_options (void) +{ + int *temp; + DIALOG d[21]; + int i, retour = 0, choix = 4; + static int y_pos[8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; + + memset (d, 0, sizeof (d)); + + for (i = 0; i < 8; ++i) + { + standard_button (d + i + 4, 0, y_pos[i], 2, 8); + d[i + 4].proc = my_textbox_proc; + } + for (i = 0; i < 8; ++i) + { + standard_button (d + i + 12, 1, y_pos[i], 2, 8); + d[i + 12].proc = my_slider_proc; + } + d[17].proc = d[18].proc = d[19].proc = my_button_proc; + + quick_buttons (d); + d[4].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_ATTACK); + d[5].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_DEFENSE); + d[6].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_BASEHEALTH); + d[7].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_WINNERHELP); + d[8].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_CPUSTRENGTH); + d[9].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_CPUVSHUMAN); + d[10].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_ALLOWNETWORKBOTS); + d[11].dp = lw_lang_string (LW_LANG_STRING_ADVANCED_ASMALGORITHM); + d[12].d1 = d[13].d1 = d[14].d1 = d[15].d1 = 16; + d[16].d1 = 4; + d[12].dp3 = &CONFIG_FIGHTER_ATTACK; + d[13].dp3 = &CONFIG_FIGHTER_DEFENSE; + d[14].dp3 = &CONFIG_FIGHTER_NEW_HEALTH; + d[15].dp3 = &CONFIG_NUMBER_INFLUENCE; + d[16].dp3 = &CONFIG_CPU_ADVANTAGE; + d[17].dp = get_cpu_vs_human_str (); + d[18].dp = get_allow_network_bots_str (); + d[19].dp = get_asm_algorithm_str (); + for (i = 12; i < 17; ++i) + { + d[i].dp = NULL; + d[i].dp2 = slider_int; + temp = d[i].dp3; + d[i].d2 = *temp; + } + +#ifndef ASM + /* + * If no assembly code has been compiled, we disable the button + */ + d[10].flags = D_HIDDEN; + d[18].flags = D_HIDDEN; +#endif + + d[20].proc = 0; + + while (retour == 0) + { + choix = my_do_dialog (d, choix); + switch (choix) + { + case -1: + case MENU_QUICK_BACK: + retour = 1; + break; + case MENU_QUICK_MAIN: + retour = MENU_TOP; + break; + case MENU_QUICK_QUIT: + if (confirm_quit ()) + retour = MENU_EXIT; + break; + case MENU_QUICK_PLAY: + retour = MENU_PLAY; + break; + case 17: + CONFIG_CPU_VS_HUMAN = (CONFIG_CPU_VS_HUMAN + 1) % 3; + d[17].dp = get_cpu_vs_human_str (); + scare_mouse (); + my_button_proc (MSG_DRAW, d + 17, 0); + unscare_mouse (); + break; + case 18: + CONFIG_ALLOW_NETWORK_BOTS = CONFIG_ALLOW_NETWORK_BOTS ? 0 : 1; + d[18].dp = get_allow_network_bots_str (); + scare_mouse (); + my_button_proc (MSG_DRAW, d + 18, 0); + unscare_mouse (); + break; + case 19: + CONFIG_ASM_ALGORITHM = CONFIG_ASM_ALGORITHM ? 0 : 1; + d[19].dp = get_asm_algorithm_str (); + scare_mouse (); + my_button_proc (MSG_DRAW, d + 19, 0); + unscare_mouse (); + break; + } + } + + if (retour > 0) + retour--; + + return retour; +} diff --git a/pool/shard006/C/0119038_dma-coherent.c b/pool/shard006/C/0119038_dma-coherent.c new file mode 100644 index 0000000000000000000000000000000000000000..b44544747dd704bdebbbef6756dc0bc853184bf4 --- /dev/null +++ b/pool/shard006/C/0119038_dma-coherent.c @@ -0,0 +1,152 @@ +/* + * Copyright (C) 2004-2006 Atmel Corporation + * + * 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 +#include +#include + +#include +#include + +void dma_cache_sync(struct device *dev, void *vaddr, size_t size, int direction) +{ + /* + * No need to sync an uncached area + */ + if (PXSEG(vaddr) == P2SEG) + return; + + switch (direction) { + case DMA_FROM_DEVICE: /* invalidate only */ + invalidate_dcache_region(vaddr, size); + break; + case DMA_TO_DEVICE: /* writeback only */ + clean_dcache_region(vaddr, size); + break; + case DMA_BIDIRECTIONAL: /* writeback and invalidate */ + flush_dcache_region(vaddr, size); + break; + default: + BUG(); + } +} +EXPORT_SYMBOL(dma_cache_sync); + +static struct page *__dma_alloc(struct device *dev, size_t size, + dma_addr_t *handle, gfp_t gfp) +{ + struct page *page, *free, *end; + int order; + + /* Following is a work-around (a.k.a. hack) to prevent pages + * with __GFP_COMP being passed to split_page() which cannot + * handle them. The real problem is that this flag probably + * should be 0 on AVR32 as it is not supported on this + * platform--see CONFIG_HUGETLB_PAGE. */ + gfp &= ~(__GFP_COMP); + + size = PAGE_ALIGN(size); + order = get_order(size); + + page = alloc_pages(gfp, order); + if (!page) + return NULL; + split_page(page, order); + + /* + * When accessing physical memory with valid cache data, we + * get a cache hit even if the virtual memory region is marked + * as uncached. + * + * Since the memory is newly allocated, there is no point in + * doing a writeback. If the previous owner cares, he should + * have flushed the cache before releasing the memory. + */ + invalidate_dcache_region(phys_to_virt(page_to_phys(page)), size); + + *handle = page_to_bus(page); + free = page + (size >> PAGE_SHIFT); + end = page + (1 << order); + + /* + * Free any unused pages + */ + while (free < end) { + __free_page(free); + free++; + } + + return page; +} + +static void __dma_free(struct device *dev, size_t size, + struct page *page, dma_addr_t handle) +{ + struct page *end = page + (PAGE_ALIGN(size) >> PAGE_SHIFT); + + while (page < end) + __free_page(page++); +} + +void *dma_alloc_coherent(struct device *dev, size_t size, + dma_addr_t *handle, gfp_t gfp) +{ + struct page *page; + void *ret = NULL; + + page = __dma_alloc(dev, size, handle, gfp); + if (page) + ret = phys_to_uncached(page_to_phys(page)); + + return ret; +} +EXPORT_SYMBOL(dma_alloc_coherent); + +void dma_free_coherent(struct device *dev, size_t size, + void *cpu_addr, dma_addr_t handle) +{ + void *addr = phys_to_cached(uncached_to_phys(cpu_addr)); + struct page *page; + + pr_debug("dma_free_coherent addr %p (phys %08lx) size %u\n", + cpu_addr, (unsigned long)handle, (unsigned)size); + BUG_ON(!virt_addr_valid(addr)); + page = virt_to_page(addr); + __dma_free(dev, size, page, handle); +} +EXPORT_SYMBOL(dma_free_coherent); + +void *dma_alloc_writecombine(struct device *dev, size_t size, + dma_addr_t *handle, gfp_t gfp) +{ + struct page *page; + dma_addr_t phys; + + page = __dma_alloc(dev, size, handle, gfp); + if (!page) + return NULL; + + phys = page_to_phys(page); + *handle = phys; + + /* Now, map the page into P3 with write-combining turned on */ + return __ioremap(phys, size, _PAGE_BUFFER); +} +EXPORT_SYMBOL(dma_alloc_writecombine); + +void dma_free_writecombine(struct device *dev, size_t size, + void *cpu_addr, dma_addr_t handle) +{ + struct page *page; + + iounmap(cpu_addr); + + page = phys_to_page(handle); + __dma_free(dev, size, page, handle); +} +EXPORT_SYMBOL(dma_free_writecombine); diff --git a/pool/shard006/C/0119040_chap4.c b/pool/shard006/C/0119040_chap4.c new file mode 100644 index 0000000000000000000000000000000000000000..26fa28e4946fcbe4edf0975e4e493e4cf95ceceb --- /dev/null +++ b/pool/shard006/C/0119040_chap4.c @@ -0,0 +1,123 @@ +// demo for chapter 2 + +// headers +#include "myxlib.h" + +// global colors +unsigned long black, white, red; +unsigned long green, blue, magenta; + +// draw the shit +void +redraw(Display *display, Window window, GC gc) +{ + XSetForeground(display, gc, blue); + XDrawLine(display, window, gc, 1, 1, 100, 100); + + XSetForeground(display, gc, red); + XDrawRectangle(display, window, gc, 100, 100, 100, 100); + + XSetForeground(display, gc, green); + XFillRectangle(display, window, gc, 200, 200, 100, 100); + + XSetForeground(display, gc, black); + DrawOval(display, window, gc, 100, 100, 100, 100); + + XSetForeground(display, gc, magenta); + FillOval(display, window, gc, 110, 110, 64, 64); + + XFlush(display); + + return; +} + +// main routine +main(int argc, char **argv) +{ + // connect to x-server + int screen; + Window rootwindow; + Display *display = ConnectToServer(NULL, screen, rootwindow); + if (display == NULL) + { + ERROR("connect to server failed.", EINVAL); + return(2); + } + + // find a pseudo-color visual for the window + int depth; + Visual *visual = CopyFromParent; + int status = SetUpVisual(display, screen, visual, depth); + if (status != True) + { + ERROR("unable to find pseudo-color visual.", EINVAL); + XCloseDisplay(display); + exit(2); + } + + // create a window + int x = 10; + int y = 10; + int width = 300; + int height = 300; + Window window = OpenWindow(display, + rootwindow, + x, y, width, height, + BlackPixel(display, screen), + WhitePixel(display, screen), + ExposureMask, visual); + + // set hints for window + SetStandardHints(display, window, argv[0], argv[0], + x, y, width, height); + + // set up colormap + Colormap colormap; + status = SetUpColormap(display, screen, window, + visual, colormap); + if (status != True) + { + ERROR("unable to find colormap.", EINVAL); + XCloseDisplay(display); + exit(2); + } + + // set up colors in colormap + black = AllocNamedColor(display, colormap, "black", + BlackPixel(display, screen)); + white = AllocNamedColor(display, colormap, "white", + BlackPixel(display, screen)); + red = AllocNamedColor(display, colormap, "red", + BlackPixel(display, screen)); + blue = AllocNamedColor(display, colormap, "blue", + BlackPixel(display, screen)); + green = AllocNamedColor(display, colormap, "green", + BlackPixel(display, screen)); + magenta = AllocNamedColor(display, colormap, "magenta", + BlackPixel(display, screen)); + + // create GC for drawing + GC gc = CreateGC(display, window, black, white); + + // map window + XMapRaised(display, window); + XFlush(display); + + // event loop: max of 20 events, then exit. + XEvent event; + for (int count = 0; count < 20; ) + { + XNextEvent(display, &event); + if (event.type == Expose) + { + redraw(display, window, gc); + count++; + } + } + + // close connection + XCloseDisplay(display); + + // all done + return(0); +} diff --git a/pool/shard006/C/0119047_main.c b/pool/shard006/C/0119047_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f0c8e7b9e62c9c49f0d6360ee8e7b0a3e94f3849 --- /dev/null +++ b/pool/shard006/C/0119047_main.c @@ -0,0 +1,181 @@ +#include +#include +#include "ft_philo.h" + +pthread_mutex_t g_mut_status; + +int baguette_in_use(t_philo *phil) +{ + int ret; + + ret = 0; + if (!phil->gauche.in_use && phil->last_action != 1 && (phil->phil_gauche->life * 100 / MAX_LIFE >= 80 || phil->life * 100 / MAX_LIFE <= 80)) + { + phil->bag1 = &phil->gauche; + phil->gauche.in_use = 1; + ++ret; + } + printf("life : %d\n", phil->life * 100 / MAX_LIFE); + if (!phil->droite->in_use && phil->last_action != 2 && (phil->phil_droite->life * 100 / MAX_LIFE >= 80 || phil->life * 100 / MAX_LIFE <= 80)) + { + if (phil->bag1) + phil->bag2 = phil->droite; + else + phil->bag1 = phil->droite; + phil->droite->in_use = 1; + ++ret; + } + return (ret); +} + +void release_baguettes(t_philo *phil) +{ + if (phil->bag1) + { + phil->bag1->in_use = 0; + phil->bag1 = NULL; + } + if (phil->bag2) + { + phil->bag2->in_use = 0; + phil->bag2 = NULL; + } +} + +void *thread(void *data) +{ + t_philo *phil; + int n; + + phil = (t_philo *)data; + while (1) + { + //printf("philo %d has %d life\n", phil->n, phil->life); + if (!phil->eating && !phil->sleeping && !phil->thinking) + { + pthread_mutex_lock(&g_mut_status); + if ((n = baguette_in_use(phil)) > 0) + { + if (n == 1) + { + printf("phil(%d) thinking\n", phil->n); + phil->thinking = 1; + phil->last_action = 1; + } + else + { + printf("phil(%d) eating\n", phil->n); + phil->eating = 1; + phil->last_action = 2; + } + } + else + { + printf("phil(%d) sleeping\n", phil->n); + phil->sleeping = 1; + phil->last_action = 3; + } + pthread_mutex_unlock(&g_mut_status); + } + // usleep(100); + } + pthread_exit(NULL); +} + +int loose_life(t_philo **phils, int n) +{ + int i; + int ret; + + i = 0; + ret = 0; + while (i < 7) + { + ++phils[i]->actiontime; + if (!phils[i]->eating) + { + phils[i]->life -= n; + if (phils[i]->life <= 0) + ret = 1; + if (phils[i]->thinking && phils[i]->actiontime == THINK_T) + { + pthread_mutex_lock(&g_mut_status); + printf("phil(%d) stop thinking\n", phils[i]->n); + release_baguettes(phils[i]); + phils[i]->thinking = 0; + phils[i]->actiontime = 0; + pthread_mutex_unlock(&g_mut_status); + } + else if (phils[i]->sleeping && phils[i]->actiontime == REST_T) + { + pthread_mutex_lock(&g_mut_status); + printf("phil(%d) stop sleeping\n", phils[i]->n); + phils[i]->sleeping = 0; + phils[i]->actiontime = 0; + pthread_mutex_unlock(&g_mut_status); + } + } + else + { + if (phils[i]->actiontime == EAT_T) + { + pthread_mutex_lock(&g_mut_status); + printf("phils(%d) stop eating\n", phils[i]->n); + release_baguettes(phils[i]); + phils[i]->eating = 0; + phils[i]->life = MAX_LIFE; + phils[i]->actiontime = 0; + pthread_mutex_unlock(&g_mut_status); + } + } + ++i; + } + return (ret); +} + +int main(void) +{ + t_philo *phils[7]; + int i; + int phils_alive; + pthread_t threads[7]; + time_t beg; + time_t end; + t_baguette *last; + t_philo *phil_last; + + last = NULL; + phil_last = NULL; + pthread_mutex_init(&g_mut_status, NULL); + for (i = 0; i < 7; ++i) + { + phils[i] = ft_create_philo(last, i); + phils[i]->phil_droite = phil_last; + last = &phils[i]->gauche; + phil_last = phils[i]; + if (i > 0) + phils[i - 1]->phil_gauche = phils[i]; + if (i == 6) + { + phils[0]->droite = last; + phils[0]->phil_droite = phil_last; + phils[i]->phil_gauche = phils[0]; + } + } + for (i = 0; i < 7; ++i) + pthread_create(&phils[i]->id, NULL, thread, (void *)phils[i]); + phils_alive = 1; + beg = time(NULL); + while (1) + { + if ((end = time(NULL) - beg) > 0) + { + beg = time(NULL); + if (loose_life(phils, end)) + return (0); + } + usleep(100); + } + pthread_exit(NULL); + return (0); +} diff --git a/pool/shard006/C/0119050_fstat.c b/pool/shard006/C/0119050_fstat.c new file mode 100644 index 0000000000000000000000000000000000000000..dd2c408b6824aea236245b77b18f8775ddef2a39 --- /dev/null +++ b/pool/shard006/C/0119050_fstat.c @@ -0,0 +1,48 @@ +/* Copyright 2011; All Rights Reserved + * Please see http://www.coactionos.com/license.html for + * licensing information. + */ + + +/*! \addtogroup UNI_FILDES + * @{ + */ + +/*! \file */ + +#include "unistd_fs.h" +#include "unistd_flags.h" + + +/*! \details This function gets various file statistics for + * the specified file descriptor. + * + * \return Zero on success or -1 on error with errno (see \ref ERRNO) set to: + * - EBADF: \a fildes is invalid + * - EINVAL: \a buf is NULL + * + */ +int fstat(int fildes, struct stat *buf); + +int _fstat(int fildes, struct stat *buf){ + void * handle; + const sysfs_t * fs; + + fildes = unistd_fildes_is_bad(fildes); + if ( fildes < 0 ){ + return -1; + } + + handle = get_handle(fildes); + memset (buf, 0, sizeof (* buf)); + fs = get_fs(fildes); + if ( fs != NULL ){ + return fs->fstat(fs->cfg, handle, buf); + } else { + errno = EBADF; + return -1; + } +} + +/*! @} */ + diff --git a/pool/shard006/C/0119051_indexed.c b/pool/shard006/C/0119051_indexed.c new file mode 100644 index 0000000000000000000000000000000000000000..11bed65e20b4656a7cec10c2ed5cc6b48e0140a1 --- /dev/null +++ b/pool/shard006/C/0119051_indexed.c @@ -0,0 +1,103 @@ +/* + Copyright(c) Pennsylvania Sumerian Dictionary and Steve Tinney + 1997 under the GNU General Public License (see /psd/COPYING). + + $Id: indexed.c,v 0.3 1997/09/08 14:50:15 sjt Exp s $ +*/ +#include "index.h" +#include "property.h" + +struct indexed *curr_indexed; +struct any_type *indexed_mm; +static int indexed_id; + +extern int swc_flag; + +void +begin_indexed () +{ + if (curr_indexed) + { + curr_indexed->next = new (indexed_mm); + curr_indexed = curr_indexed->next; + } + else + { + curr_indexed = new (indexed_mm); + curr_indexed->next = NULL; + } + curr_node = curr_indexed->nodes = new_node (); + curr_node->used_flag = 0; + curr_indexed->id = indexed_id++; + /* split-word support just won't work when there are multiple + * exemplars, i.e., multiple branches + */ + curr_node->l.branch_id = branch_id = 1; + if (!swc_flag) + start_column = 0; +} + +void +end_indexed () +{ + struct grapheme *gnp; + struct parallel *pp; + + for (gnp = grapheme_list_base; gnp; gnp = gnp->next) + { + /* this is an empty index-material entry */ + if (!gnp->node) + continue; + + if (gnp->node->end_of_branch_flag) + { + for (pp = gnp->node->parallel_info; pp && pp->parent; pp = pp->parent) + ; + gnp->node->l.end_column = pp->end_column; + if (!gnp->node->boundary && gnp->node->parallel_info->boundary) + gnp->node->boundary = gnp->node->parallel_info->boundary; + } + else + { + int logo = is_logo(gnp->node->l.end_column); + gnp->node->l.end_column = mask_sc(gnp->node->l.start_column); + if (logo) + gnp->node->l.end_column |= G_LOGO; + } + /* the left/right tests in prop setting are for when a sign + is double-indexed, e.g., as be2 and BI */ + if (NULL == gnp->node->left + || (gnp->node->left->l.start_column == gnp->node->l.start_column + && NULL == gnp->node->left->left)) + { + set_property (gnp->node->l.properties, PROP_LB); + set_property (gnp->node->l.properties, PROP_WB); + } + else if (gnp->node->left->boundary == ' ') + set_property (gnp->node->l.properties, PROP_WB); + + if (NULL == gnp->node->right + || (gnp->node->right->l.start_column == gnp->node->l.start_column + && NULL == gnp->node->right->right)) + { + set_property (gnp->node->l.properties, PROP_LE); + set_property (gnp->node->l.properties, PROP_WE); + } + else if (gnp->node->boundary == ' ' + || (gnp->node->right->l.start_column == gnp->node->l.start_column + && gnp->node->right->boundary == ' ')) + set_property (gnp->node->l.properties, PROP_WE); + } +#if 0 + if (debug_flag) + dump_graphemes (); +#endif + + if (index_flag) + add_graphemes (); + + reset (node_mm); + reset (grapheme_mm); + reset (parallels_mm); + curr_node = NULL; +} diff --git a/pool/shard006/C/0119053_disco_query.c b/pool/shard006/C/0119053_disco_query.c new file mode 100644 index 0000000000000000000000000000000000000000..b81e4f360f04086795932a6d8555bfc07391f441 --- /dev/null +++ b/pool/shard006/C/0119053_disco_query.c @@ -0,0 +1,125 @@ +/* $Id: disco_query.c,v 1.0 2005/10/14 15:17:55 fpeters Exp $ + * + * Lasso - A free implementation of the Liberty Alliance specifications. + * + * Copyright (C) 2004-2007 Entr'ouvert + * http://lasso.entrouvert.org + * + * Authors: See AUTHORS file in top-level directory. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include "../private.h" +#include "disco_query.h" +#include "idwsf2_strings.h" + +/** + * SECTION:disco_query + * @short_description: <disco:Query> + * + *
Schema fragment for disco:Query + * + * + * + * + * + * + * + * ]]> + *
+ */ + +/*****************************************************************************/ +/* private methods */ +/*****************************************************************************/ + + +static struct XmlSnippet schema_snippets[] = { + { "RequestedService", SNIPPET_LIST_NODES, + G_STRUCT_OFFSET(LassoIdWsf2DiscoQuery, RequestedService), + "LassoIdWsf2DiscoRequestedService", NULL, NULL }, + { "attributes", SNIPPET_ATTRIBUTE | SNIPPET_ANY, + G_STRUCT_OFFSET(LassoIdWsf2DiscoQuery, attributes), NULL, NULL, NULL}, + {NULL, 0, 0, NULL, NULL, NULL} +}; + +static LassoNodeClass *parent_class = NULL; + + +/*****************************************************************************/ +/* instance and class init functions */ +/*****************************************************************************/ + +static void +instance_init(LassoIdWsf2DiscoQuery *node) +{ + node->attributes = g_hash_table_new_full( + g_str_hash, g_str_equal, g_free, g_free); +} + +static void +class_init(LassoIdWsf2DiscoQueryClass *klass) +{ + LassoNodeClass *nclass = LASSO_NODE_CLASS(klass); + + parent_class = g_type_class_peek_parent(klass); + nclass->node_data = g_new0(LassoNodeClassData, 1); + lasso_node_class_set_nodename(nclass, "Query"); + lasso_node_class_set_ns(nclass, LASSO_IDWSF2_DISCOVERY_HREF, LASSO_IDWSF2_DISCOVERY_PREFIX); + lasso_node_class_add_snippets(nclass, schema_snippets); +} + +GType +lasso_idwsf2_disco_query_get_type() +{ + static GType this_type = 0; + + if (!this_type) { + static const GTypeInfo this_info = { + sizeof (LassoIdWsf2DiscoQueryClass), + NULL, + NULL, + (GClassInitFunc) class_init, + NULL, + NULL, + sizeof(LassoIdWsf2DiscoQuery), + 0, + (GInstanceInitFunc) instance_init, + NULL + }; + + this_type = g_type_register_static(LASSO_TYPE_NODE, + "LassoIdWsf2DiscoQuery", &this_info, 0); + } + return this_type; +} + +/** + * lasso_idwsf2_disco_query_new: + * + * Creates a new #LassoIdWsf2DiscoQuery object. + * + * Return value: a newly created #LassoIdWsf2DiscoQuery object + **/ +LassoIdWsf2DiscoQuery* +lasso_idwsf2_disco_query_new() +{ + return g_object_new(LASSO_TYPE_IDWSF2_DISCO_QUERY, NULL); +} diff --git a/pool/shard006/C/0119054_CWE665_Improper_Initialization__wchar_t_cat_51b.c b/pool/shard006/C/0119054_CWE665_Improper_Initialization__wchar_t_cat_51b.c new file mode 100644 index 0000000000000000000000000000000000000000..4763b0dc9a253e61f0f0056436cc4b3c72e83f6b --- /dev/null +++ b/pool/shard006/C/0119054_CWE665_Improper_Initialization__wchar_t_cat_51b.c @@ -0,0 +1,54 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE665_Improper_Initialization__wchar_t_cat_51b.c +Label Definition File: CWE665_Improper_Initialization.label.xml +Template File: sources-sink-51b.tmpl.c +*/ +/* + * @description + * CWE: 665 Improper Initialization + * BadSource: Do not initialize data properly + * GoodSource: Initialize data + * Sink: cat + * BadSink : Copy string to data using wcscat + * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void CWE665_Improper_Initialization__wchar_t_cat_51b_badSink(wchar_t * data) +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: If data is not initialized properly, wcscat() may not function correctly */ + wcscat(data, source); + printWLine(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE665_Improper_Initialization__wchar_t_cat_51b_goodG2BSink(wchar_t * data) +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: If data is not initialized properly, wcscat() may not function correctly */ + wcscat(data, source); + printWLine(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard006/C/0119055_SPI_PULLUP_1.c b/pool/shard006/C/0119055_SPI_PULLUP_1.c new file mode 100644 index 0000000000000000000000000000000000000000..e3d8a780cd0f01aa346cb4f5ac2cba5bd1dd9eb3 --- /dev/null +++ b/pool/shard006/C/0119055_SPI_PULLUP_1.c @@ -0,0 +1,231 @@ +/******************************************************************************* +* File Name: SPI_PULLUP_1.c +* Version 2.20 +* +* Description: +* This file contains API to enable firmware control of a Pins component. +* +* Note: +* +******************************************************************************** +* Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved. +* You may use this file only in accordance with the license, terms, conditions, +* disclaimers, and limitations in the end user license agreement accompanying +* the software package with which this file was provided. +*******************************************************************************/ + +#include "cytypes.h" +#include "SPI_PULLUP_1.h" + +/* APIs are not generated for P15[7:6] on PSoC 5 */ +#if !(CY_PSOC5A &&\ + SPI_PULLUP_1__PORT == 15 && ((SPI_PULLUP_1__MASK & 0xC0) != 0)) + + +/******************************************************************************* +* Function Name: SPI_PULLUP_1_Write +****************************************************************************//** +* +* \brief Writes the value to the physical port (data output register), masking +* and shifting the bits appropriately. +* +* The data output register controls the signal applied to the physical pin in +* conjunction with the drive mode parameter. This function avoids changing +* other bits in the port by using the appropriate method (read-modify-write or +* bit banding). +* +* Note This function should not be used on a hardware digital output pin +* as it is driven by the hardware signal attached to it. +* +* \param value +* Value to write to the component instance. +* +* \return +* None +* +* \sideeffect +* If you use read-modify-write operations that are not atomic; the Interrupt +* Service Routines (ISR) can cause corruption of this function. An ISR that +* interrupts this function and performs writes to the Pins component data +* register can cause corrupted port data. To avoid this issue, you should +* either use the Per-Pin APIs (primary method) or disable interrupts around +* this function. +* +* \funcusage +* \snippet SPI_PULLUP_1_SUT.c usage_SPI_PULLUP_1_Write +*******************************************************************************/ +void SPI_PULLUP_1_Write(uint8 value) +{ + uint8 staticBits = (SPI_PULLUP_1_DR & (uint8)(~SPI_PULLUP_1_MASK)); + SPI_PULLUP_1_DR = staticBits | ((uint8)(value << SPI_PULLUP_1_SHIFT) & SPI_PULLUP_1_MASK); +} + + +/******************************************************************************* +* Function Name: SPI_PULLUP_1_SetDriveMode +****************************************************************************//** +* +* \brief Sets the drive mode for each of the Pins component's pins. +* +* Note This affects all pins in the Pins component instance. Use the +* Per-Pin APIs if you wish to control individual pin's drive modes. +* +* \param mode +* Mode for the selected signals. Valid options are documented in +* \ref driveMode. +* +* \return +* None +* +* \sideeffect +* If you use read-modify-write operations that are not atomic, the ISR can +* cause corruption of this function. An ISR that interrupts this function +* and performs writes to the Pins component Drive Mode registers can cause +* corrupted port data. To avoid this issue, you should either use the Per-Pin +* APIs (primary method) or disable interrupts around this function. +* +* \funcusage +* \snippet SPI_PULLUP_1_SUT.c usage_SPI_PULLUP_1_SetDriveMode +*******************************************************************************/ +void SPI_PULLUP_1_SetDriveMode(uint8 mode) +{ + CyPins_SetPinDriveMode(SPI_PULLUP_1_0, mode); + CyPins_SetPinDriveMode(SPI_PULLUP_1_1, mode); +} + + +/******************************************************************************* +* Function Name: SPI_PULLUP_1_Read +****************************************************************************//** +* +* \brief Reads the associated physical port (pin status register) and masks +* the required bits according to the width and bit position of the component +* instance. +* +* The pin's status register returns the current logic level present on the +* physical pin. +* +* \return +* The current value for the pins in the component as a right justified number. +* +* \funcusage +* \snippet SPI_PULLUP_1_SUT.c usage_SPI_PULLUP_1_Read +*******************************************************************************/ +uint8 SPI_PULLUP_1_Read(void) +{ + return (SPI_PULLUP_1_PS & SPI_PULLUP_1_MASK) >> SPI_PULLUP_1_SHIFT; +} + + +/******************************************************************************* +* Function Name: SPI_PULLUP_1_ReadDataReg +****************************************************************************//** +* +* \brief Reads the associated physical port's data output register and masks +* the correct bits according to the width and bit position of the component +* instance. +* +* The data output register controls the signal applied to the physical pin in +* conjunction with the drive mode parameter. This is not the same as the +* preferred SPI_PULLUP_1_Read() API because the +* SPI_PULLUP_1_ReadDataReg() reads the data register instead of the status +* register. For output pins this is a useful function to determine the value +* just written to the pin. +* +* \return +* The current value of the data register masked and shifted into a right +* justified number for the component instance. +* +* \funcusage +* \snippet SPI_PULLUP_1_SUT.c usage_SPI_PULLUP_1_ReadDataReg +*******************************************************************************/ +uint8 SPI_PULLUP_1_ReadDataReg(void) +{ + return (SPI_PULLUP_1_DR & SPI_PULLUP_1_MASK) >> SPI_PULLUP_1_SHIFT; +} + + +/* If interrupt is connected for this Pins component */ +#if defined(SPI_PULLUP_1_INTSTAT) + + /******************************************************************************* + * Function Name: SPI_PULLUP_1_SetInterruptMode + ****************************************************************************//** + * + * \brief Configures the interrupt mode for each of the Pins component's + * pins. Alternatively you may set the interrupt mode for all the pins + * specified in the Pins component. + * + * Note The interrupt is port-wide and therefore any enabled pin + * interrupt may trigger it. + * + * \param position + * The pin position as listed in the Pins component. You may OR these to be + * able to configure the interrupt mode of multiple pins within a Pins + * component. Or you may use SPI_PULLUP_1_INTR_ALL to configure the + * interrupt mode of all the pins in the Pins component. + * - SPI_PULLUP_1_0_INTR (First pin in the list) + * - SPI_PULLUP_1_1_INTR (Second pin in the list) + * - ... + * - SPI_PULLUP_1_INTR_ALL (All pins in Pins component) + * + * \param mode + * Interrupt mode for the selected pins. Valid options are documented in + * \ref intrMode. + * + * \return + * None + * + * \sideeffect + * It is recommended that the interrupt be disabled before calling this + * function to avoid unintended interrupt requests. Note that the interrupt + * type is port wide, and therefore will trigger for any enabled pin on the + * port. + * + * \funcusage + * \snippet SPI_PULLUP_1_SUT.c usage_SPI_PULLUP_1_SetInterruptMode + *******************************************************************************/ + void SPI_PULLUP_1_SetInterruptMode(uint16 position, uint16 mode) + { + if((position & SPI_PULLUP_1_0_INTR) != 0u) + { + SPI_PULLUP_1_0_INTTYPE_REG = (uint8)mode; + } + if((position & SPI_PULLUP_1_1_INTR) != 0u) + { + SPI_PULLUP_1_1_INTTYPE_REG = (uint8)mode; + } + } + + + /******************************************************************************* + * Function Name: SPI_PULLUP_1_ClearInterrupt + ****************************************************************************//** + * + * \brief Clears any active interrupts attached with the component and returns + * the value of the interrupt status register allowing determination of which + * pins generated an interrupt event. + * + * \return + * The right-shifted current value of the interrupt status register. Each pin + * has one bit set if it generated an interrupt event. For example, bit 0 is + * for pin 0 and bit 1 is for pin 1 of the Pins component. + * + * \sideeffect + * Clears all bits of the physical port's interrupt status register, not just + * those associated with the Pins component. + * + * \funcusage + * \snippet SPI_PULLUP_1_SUT.c usage_SPI_PULLUP_1_ClearInterrupt + *******************************************************************************/ + uint8 SPI_PULLUP_1_ClearInterrupt(void) + { + return (SPI_PULLUP_1_INTSTAT & SPI_PULLUP_1_MASK) >> SPI_PULLUP_1_SHIFT; + } + +#endif /* If Interrupts Are Enabled for this Pins component */ + +#endif /* CY_PSOC5A... */ + + +/* [] END OF FILE */ diff --git a/pool/shard006/C/0119057_slayer_server_stats.c b/pool/shard006/C/0119057_slayer_server_stats.c new file mode 100644 index 0000000000000000000000000000000000000000..f604ef5f0caeab4305a487544ea608e1f1f77d79 --- /dev/null +++ b/pool/shard006/C/0119057_slayer_server_stats.c @@ -0,0 +1,90 @@ +#include "simplejson.h" +#include "slayer_server_stats.h" + +/* $Id: slayer_server_stats.c,v 1.1 2008/02/29 00:18:52 derek Exp $ */ + +slayer_server_stats_t * slayer_server_stat_init(apr_pool_t *mpool,int nslice, int tslice) { + apr_status_t status; + apr_pool_t *lpool; + slayer_server_stats_t *stats; + status = apr_pool_create(&lpool,mpool); + stats = apr_palloc(lpool,sizeof(slayer_server_stats_t)); + stats->mpool = lpool; + status = apr_thread_mutex_create(&stats->mutex,APR_THREAD_MUTEX_DEFAULT,stats->mpool); + stats->offset = stats->total_requests = 0; + stats->nslice = nslice + 1; + stats->tslice = tslice; + stats->hits = apr_pcalloc(stats->mpool,sizeof(int) * stats->nslice); + stats->slices = apr_pcalloc(stats->mpool,sizeof(time_t) * stats->nslice); + stats->start_time = stats->slices[stats->offset] = apr_time_now() / (1000*1000); + return stats; +} + +void slayer_server_stat_update(slayer_server_stats_t *stats) { + apr_thread_mutex_lock(stats->mutex); + (stats->hits[stats->offset])++; + (stats->total_requests)++; + apr_thread_mutex_unlock(stats->mutex); +} + +void slayer_server_stats_get(slayer_server_stats_t *istats, slayer_server_stats_t *ostats) { + apr_thread_mutex_lock(istats->mutex); + memcpy(ostats,istats,sizeof(slayer_server_stats_t)); + apr_thread_mutex_unlock(istats->mutex); +} +void slayer_server_stats_tick(slayer_server_stats_t *stats) { + apr_thread_mutex_lock(stats->mutex); + stats->offset++; + if (stats->offset == stats->nslice ) { + stats->offset = 0; + } + stats->hits[stats->offset] = 0; + stats->slices[stats->offset] = apr_time_now() / (1000*1000); + apr_thread_mutex_unlock(stats->mutex); +} + +void *slayer_server_stats_timer_thread_run(apr_thread_t *mthread, void *x) { + slayer_server_stats_t *stats = (slayer_server_stats_t*) x; + while (1) { + apr_sleep(1000*1000 * stats->tslice); + slayer_server_stats_tick(stats); + } + return NULL; +} + +void slayer_server_stats_timer_thread(apr_pool_t *mpool,slayer_server_stats_t *stats) { + apr_threadattr_t *thread_attr; + apr_thread_t *thread; + apr_threadattr_create(&thread_attr,mpool); + apr_threadattr_detach_set(thread_attr,1); // detach + apr_threadattr_stacksize_set(thread_attr,4096*10); + apr_thread_create(&thread,thread_attr,slayer_server_stats_timer_thread_run,stats,mpool); +} + +char * slayer_server_stats_tojson(slayer_server_stats_t *istats,apr_pool_t *mpool) { + slayer_server_stats_t stats; + slayer_server_stats_get(istats,&stats); + + json_value *container = json_object_create(mpool); + json_object_add(container,"total_requests",json_long_create(mpool,stats.total_requests)); + json_value *hits = json_array_create(mpool,stats.nslice); + json_value *slices = json_array_create(mpool,stats.nslice); + int i; + for ( i = stats.offset+1; i < stats.nslice; i++) { + if (stats.slices[i] != 0) { + json_array_append(hits,json_long_create(mpool,stats.hits[i])); + json_array_append(slices,json_long_create(mpool,stats.slices[i])); + } + } + for ( i = 0; i < stats.offset; i++) { + if (stats.slices[i] != 0) { + json_array_append(hits,json_long_create(mpool,stats.hits[i])); + json_array_append(slices,json_long_create(mpool,stats.slices[i])); + } + } + json_object_add(container,"hits",hits); + json_object_add(container,"slices",slices); + json_object_add(container,"start_time",json_long_create(mpool,stats.start_time)); + json_object_add(container,"current_time",json_long_create(mpool,apr_time_now() / (1000*1000))); + return json_serialize(mpool,container); +} diff --git a/pool/shard006/C/0119059_concurrent_access.c b/pool/shard006/C/0119059_concurrent_access.c new file mode 100644 index 0000000000000000000000000000000000000000..866f7077423ce5cc3358bf9a9fdf40e4d10483c4 --- /dev/null +++ b/pool/shard006/C/0119059_concurrent_access.c @@ -0,0 +1,136 @@ +#include +#include +#include +#include + +#define DEFAULT_INITIAL_VALUE 500000 +#define DEFAULT_NTHREADS 50 + +/* Global variable that will be decremented by threads. */ +volatile unsigned int value = 0; + +/* Mutex that will be used for access to VALUE in + * synchronized functions. */ +pthread_mutex_t value_mtx = PTHREAD_MUTEX_INITIALIZER; + +char* program_name = NULL; + +/* Function performs NTIMES decrement operations on global + * variable VALUE without using a mutex. */ +void *not_synchronized(void *ntimes) +{ + unsigned int i; + + for (i = *(unsigned int *)ntimes; i > 0; i--) { + value--; + } + + pthread_exit(NULL); +} + +/* Function performs NTIMES decrement operations on global + * variable VALUE using a mutex for synchronization.*/ +void *synchronized(void *ntimes) +{ + unsigned int i; + + for (i = *(unsigned int *)ntimes; i > 0; i--) { + pthread_mutex_lock(&value_mtx); + value--; + pthread_mutex_unlock(&value_mtx); + } + + pthread_exit(NULL); +} + +void usage() +{ + printf("Usage: %s number_of_threads initial_value\n", program_name); +} + +int main(int argc, char **argv) +{ + unsigned int initial_value; + unsigned int nthreads; + + program_name = argv[0]; + + /* Did the user specify number of threads and initial value? */ + if (argc == 3) { + initial_value = abs(atoi(argv[1])); + nthreads = abs(atoi(argv[2])); + + /* Valid numeric arguments are expected */ + if (initial_value == 0 || nthreads == 0) { + usage(); + return -1; + } + + /* Use default values if not arguments were specified */ + } else if (argc == 1) { + printf("Using default initial value and number of threads.\n\n"); + initial_value = DEFAULT_INITIAL_VALUE; + nthreads = DEFAULT_NTHREADS; + + /* Print usage and exit in case a weird number + * of arguments were specified */ + } else { + usage(); + return -1; + } + + /* Each thread will decrement the global variable QUOTIENT times. */ + unsigned int quotient = initial_value / nthreads; + unsigned int remainder = initial_value - (quotient * nthreads); + unsigned int i; + pthread_t* threads = calloc(nthreads, sizeof(pthread_t)); + + printf("Using initial value %d with %d threads. Each thread will decrement\n" + "the global value %d times (initial value / number of threads).\n" + "Resulting value should be %d.\n\n", + initial_value, + nthreads, + quotient, + remainder); + + /* Unsynchronized threads */ + value = initial_value; + for (i = 0; i < nthreads; i++) { + if (pthread_create(&threads[i], NULL, not_synchronized, "ient) != 0) { + perror("pthread_create"); + return -1; + } + } + + /* Wait for threads to finish */ + for (i = 0; i < nthreads; i++) { + if (pthread_join(threads[i], NULL) != 0) { + perror("pthread_join"); + return -1; + } + } + printf("%i threads, not synchronized; Resulting value is %i\n", nthreads, value); + + /* Synchronized threads */ + value = initial_value; + for (i = 0; i < nthreads; i++) { + if (pthread_create(&threads[i], NULL, synchronized, "ient) != 0) { + perror("pthread_create"); + return -1; + } + } + + /* Wait for threads to finish */ + for (i = 0; i < nthreads; i++) { + if (pthread_join(threads[i], NULL) != 0) { + perror("pthread_join"); + return -1; + } + } + printf("%i threads, synchronized; Resulting value is %i\n", nthreads, value); + + /* Free allocated pthread_t structures */ + free(threads); + + return 0; +} diff --git a/pool/shard006/C/0119063_nft_log.c b/pool/shard006/C/0119063_nft_log.c new file mode 100644 index 0000000000000000000000000000000000000000..6271e40a3dd6d00b0a19f31a5ef5509185120505 --- /dev/null +++ b/pool/shard006/C/0119063_nft_log.c @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2008-2009 Patrick McHardy + * Copyright (c) 2012-2014 Pablo Neira Ayuso + * + * 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. + * + * Development of this code funded by Astaro AG (http://www.astaro.com/) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const char *nft_log_null_prefix = ""; + +struct nft_log { + struct nf_loginfo loginfo; + char *prefix; +}; + +static void nft_log_eval(const struct nft_expr *expr, + struct nft_regs *regs, + const struct nft_pktinfo *pkt) +{ + const struct nft_log *priv = nft_expr_priv(expr); + + nf_log_packet(nft_net(pkt), nft_pf(pkt), nft_hook(pkt), pkt->skb, + nft_in(pkt), nft_out(pkt), &priv->loginfo, "%s", + priv->prefix); +} + +static const struct nla_policy nft_log_policy[NFTA_LOG_MAX + 1] = { + [NFTA_LOG_GROUP] = { .type = NLA_U16 }, + [NFTA_LOG_PREFIX] = { .type = NLA_STRING }, + [NFTA_LOG_SNAPLEN] = { .type = NLA_U32 }, + [NFTA_LOG_QTHRESHOLD] = { .type = NLA_U16 }, + [NFTA_LOG_LEVEL] = { .type = NLA_U32 }, + [NFTA_LOG_FLAGS] = { .type = NLA_U32 }, +}; + +static int nft_log_init(const struct nft_ctx *ctx, + const struct nft_expr *expr, + const struct nlattr * const tb[]) +{ + struct nft_log *priv = nft_expr_priv(expr); + struct nf_loginfo *li = &priv->loginfo; + const struct nlattr *nla; + int err; + + li->type = NF_LOG_TYPE_LOG; + if (tb[NFTA_LOG_LEVEL] != NULL && + tb[NFTA_LOG_GROUP] != NULL) + return -EINVAL; + if (tb[NFTA_LOG_GROUP] != NULL) { + li->type = NF_LOG_TYPE_ULOG; + if (tb[NFTA_LOG_FLAGS] != NULL) + return -EINVAL; + } + + nla = tb[NFTA_LOG_PREFIX]; + if (nla != NULL) { + priv->prefix = kmalloc(nla_len(nla) + 1, GFP_KERNEL); + if (priv->prefix == NULL) + return -ENOMEM; + nla_strlcpy(priv->prefix, nla, nla_len(nla) + 1); + } else { + priv->prefix = (char *)nft_log_null_prefix; + } + + switch (li->type) { + case NF_LOG_TYPE_LOG: + if (tb[NFTA_LOG_LEVEL] != NULL) { + li->u.log.level = + ntohl(nla_get_be32(tb[NFTA_LOG_LEVEL])); + } else { + li->u.log.level = LOGLEVEL_WARNING; + } + if (li->u.log.level > LOGLEVEL_DEBUG) { + err = -EINVAL; + goto err1; + } + + if (tb[NFTA_LOG_FLAGS] != NULL) { + li->u.log.logflags = + ntohl(nla_get_be32(tb[NFTA_LOG_FLAGS])); + if (li->u.log.logflags & ~NF_LOG_MASK) { + err = -EINVAL; + goto err1; + } + } + break; + case NF_LOG_TYPE_ULOG: + li->u.ulog.group = ntohs(nla_get_be16(tb[NFTA_LOG_GROUP])); + if (tb[NFTA_LOG_SNAPLEN] != NULL) { + li->u.ulog.flags |= NF_LOG_F_COPY_LEN; + li->u.ulog.copy_len = + ntohl(nla_get_be32(tb[NFTA_LOG_SNAPLEN])); + } + if (tb[NFTA_LOG_QTHRESHOLD] != NULL) { + li->u.ulog.qthreshold = + ntohs(nla_get_be16(tb[NFTA_LOG_QTHRESHOLD])); + } + break; + } + + err = nf_logger_find_get(ctx->afi->family, li->type); + if (err < 0) + goto err1; + + return 0; + +err1: + if (priv->prefix != nft_log_null_prefix) + kfree(priv->prefix); + return err; +} + +static void nft_log_destroy(const struct nft_ctx *ctx, + const struct nft_expr *expr) +{ + struct nft_log *priv = nft_expr_priv(expr); + struct nf_loginfo *li = &priv->loginfo; + + if (priv->prefix != nft_log_null_prefix) + kfree(priv->prefix); + + nf_logger_put(ctx->afi->family, li->type); +} + +static int nft_log_dump(struct sk_buff *skb, const struct nft_expr *expr) +{ + const struct nft_log *priv = nft_expr_priv(expr); + const struct nf_loginfo *li = &priv->loginfo; + + if (priv->prefix != nft_log_null_prefix) + if (nla_put_string(skb, NFTA_LOG_PREFIX, priv->prefix)) + goto nla_put_failure; + switch (li->type) { + case NF_LOG_TYPE_LOG: + if (nla_put_be32(skb, NFTA_LOG_LEVEL, htonl(li->u.log.level))) + goto nla_put_failure; + + if (li->u.log.logflags) { + if (nla_put_be32(skb, NFTA_LOG_FLAGS, + htonl(li->u.log.logflags))) + goto nla_put_failure; + } + break; + case NF_LOG_TYPE_ULOG: + if (nla_put_be16(skb, NFTA_LOG_GROUP, htons(li->u.ulog.group))) + goto nla_put_failure; + + if (li->u.ulog.flags & NF_LOG_F_COPY_LEN) { + if (nla_put_be32(skb, NFTA_LOG_SNAPLEN, + htonl(li->u.ulog.copy_len))) + goto nla_put_failure; + } + if (li->u.ulog.qthreshold) { + if (nla_put_be16(skb, NFTA_LOG_QTHRESHOLD, + htons(li->u.ulog.qthreshold))) + goto nla_put_failure; + } + break; + } + return 0; + +nla_put_failure: + return -1; +} + +static struct nft_expr_type nft_log_type; +static const struct nft_expr_ops nft_log_ops = { + .type = &nft_log_type, + .size = NFT_EXPR_SIZE(sizeof(struct nft_log)), + .eval = nft_log_eval, + .init = nft_log_init, + .destroy = nft_log_destroy, + .dump = nft_log_dump, +}; + +static struct nft_expr_type nft_log_type __read_mostly = { + .name = "log", + .ops = &nft_log_ops, + .policy = nft_log_policy, + .maxattr = NFTA_LOG_MAX, + .owner = THIS_MODULE, +}; + +static int __init nft_log_module_init(void) +{ + return nft_register_expr(&nft_log_type); +} + +static void __exit nft_log_module_exit(void) +{ + nft_unregister_expr(&nft_log_type); +} + +module_init(nft_log_module_init); +module_exit(nft_log_module_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Patrick McHardy "); +MODULE_ALIAS_NFT_EXPR("log"); diff --git a/pool/shard006/C/0119065_mm.c b/pool/shard006/C/0119065_mm.c new file mode 100644 index 0000000000000000000000000000000000000000..efb0b6c2079b3d6f73fb65a5c9baf582517c2584 --- /dev/null +++ b/pool/shard006/C/0119065_mm.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +extern heap_t *kheap; +extern page_directory_t *kernel_directory; + +uint32_t placement_address = 0x200000;// (uint32_t)&end; + +uint32_t kmalloc_int(uint32_t size, uint8_t align, uint32_t *phys) +{ + if(kheap != 0) + { + void *addr = alloc(size, align, kheap); + + if(phys != 0) + { + page_t *page = get_page((uint32_t)addr, 1, kernel_directory); + *phys = page->frame_addr*PAGE_SIZE+((uint32_t)addr&0x00000FFF); + } + + kprintf("kmalloc heap: %X\n", (uint32_t)addr); + return (uint32_t)addr; + } + + /* For now, we just assign memory at placement_address */ + /* and increment it by size. Even when we have coded our kernel */ + /* heap, this will be useful for use before the heap is initialized */ + + if(align == 1 && (placement_address & 0xFFFFF000)) + { + /* align the placement address */ + placement_address &= 0xFFFFF000; + placement_address += PAGE_SIZE; + } + + if(phys) + { + *phys = placement_address; + } + + uint32_t temp = placement_address; + placement_address += size; + return temp; +} + +uint32_t kmalloc_a(uint32_t size) +{ + return kmalloc_int(size, 1, 0); +} + +uint32_t kmalloc_p(uint32_t size, uint32_t *phys) +{ + return kmalloc_int(size, 0, phys); +} + +uint32_t kmalloc_ap(uint32_t size, uint32_t *phys) +{ + return kmalloc_int(size, 1, phys); +} + +uint32_t kmalloc(uint32_t size) +{ + return kmalloc_int(size, 0, 0); +} diff --git a/pool/shard006/C/0119066_dyncmd.c b/pool/shard006/C/0119066_dyncmd.c new file mode 100644 index 0000000000000000000000000000000000000000..ca9a8228914b2dd92708c9907a64fa0a4b94a53e --- /dev/null +++ b/pool/shard006/C/0119066_dyncmd.c @@ -0,0 +1,170 @@ +/* dyncmd.c - support dynamic command */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2009 Free Software Foundation, Inc. + * + * GRUB 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. + * + * GRUB 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 GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +static grub_err_t +grub_dyncmd_dispatcher (struct grub_command *cmd, + int argc, char **args) +{ + char *modname = cmd->data; + grub_dl_t mod; + grub_err_t ret; + + mod = grub_dl_load (modname); + if (mod) + { + char *name; + + grub_free (modname); + grub_dl_ref (mod); + + name = (char *) cmd->name; + grub_unregister_command (cmd); + + cmd = grub_command_find (name); + if (cmd) + ret = (cmd->func) (cmd, argc, args); + else + ret = grub_errno; + + grub_free (name); + } + else + ret = grub_errno; + + return ret; +} + +/* Read the file command.lst for auto-loading. */ +void +read_command_list (void) +{ + const char *prefix; + + prefix = grub_env_get ("prefix"); + if (prefix) + { + char *filename; + + filename = grub_xasprintf ("%s/command.lst", prefix); + if (filename) + { + grub_file_t file; + + file = grub_file_open (filename); + if (file) + { + char *buf = NULL; + grub_command_t ptr, last = 0, next; + + /* Override previous commands.lst. */ + for (ptr = grub_command_list; ptr; ptr = next) + { + next = ptr->next; + if (ptr->func == grub_dyncmd_dispatcher) + { + if (last) + last->next = ptr->next; + else + grub_command_list = ptr->next; + grub_free (ptr); + } + else + last = ptr; + } + + for (;; grub_free (buf)) + { + char *p, *name, *modname; + grub_command_t cmd; + int prio = 0; + + buf = grub_file_getline (file); + + if (! buf) + break; + + name = buf; + if (*name == '*') + { + name++; + prio++; + } + + if (! grub_isgraph (name[0])) + continue; + + p = grub_strchr (name, ':'); + if (! p) + continue; + + *p = '\0'; + while (*++p == ' ') + ; + + if (! grub_isgraph (*p)) + continue; + + if (grub_dl_get (p)) + continue; + + name = grub_strdup (name); + if (! name) + continue; + + modname = grub_strdup (p); + if (! modname) + { + grub_free (name); + continue; + } + + cmd = grub_register_command_prio (name, + grub_dyncmd_dispatcher, + 0, N_("not loaded"), prio); + if (! cmd) + { + grub_free (name); + grub_free (modname); + continue; + } + cmd->flags |= GRUB_COMMAND_FLAG_DYNCMD; + cmd->data = modname; + + /* Update the active flag. */ + grub_command_find (name); + } + + grub_file_close (file); + } + + grub_free (filename); + } + } + + /* Ignore errors. */ + grub_errno = GRUB_ERR_NONE; +} diff --git a/pool/shard006/C/0119067_file1.c b/pool/shard006/C/0119067_file1.c new file mode 100644 index 0000000000000000000000000000000000000000..a4430cfca669061c087f0ff1c1d2b6bbf3492219 --- /dev/null +++ b/pool/shard006/C/0119067_file1.c @@ -0,0 +1,18 @@ +#include +#include +int main() +{ + int x; + int y; + char ch; + FILE *fin; + fin=fopen("E:\\ME7EC\\codes\\for\\xy.txt","r"); + + while((ch=getc(fin))!=EOF) + { + printf("%c\n",ch); + } + + fclose(fin); + return 0; +} diff --git a/pool/shard006/C/0119068_bli_axpyf_opt_var1.c b/pool/shard006/C/0119068_bli_axpyf_opt_var1.c new file mode 100644 index 0000000000000000000000000000000000000000..16b8dacbd0742662df43427b6e96e451b8dd2157 --- /dev/null +++ b/pool/shard006/C/0119068_bli_axpyf_opt_var1.c @@ -0,0 +1,219 @@ +/* + + BLIS + An object-based framework for developing high-performance BLAS-like + libraries. + + Copyright (C) 2014, The University of Texas at Austin + + 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 The University of Texas at Austin nor the names + of its contributors may be used to endorse or promote products + derived derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include "blis.h" + + + +void bli_saxpyf_opt_var1( + conj_t conja, + conj_t conjx, + dim_t m, + dim_t b_n, + float* restrict alpha, + float* restrict a, inc_t inca, inc_t lda, + float* restrict x, inc_t incx, + float* restrict y, inc_t incy + ) +{ + /* Just call the reference implementation. */ + BLIS_SAXPYF_KERNEL_REF( conja, + conjx, + m, + b_n, + alpha, + a, inca, lda, + x, incx, + y, incy ); +} + + + +void bli_daxpyf_opt_var1( + conj_t conja, + conj_t conjx, + dim_t m, + dim_t b_n, + double* restrict alpha, + double* restrict a, inc_t inca, inc_t lda, + double* restrict x, inc_t incx, + double* restrict y, inc_t incy + ) +{ + if ( bli_zero_dim2( m, b_n ) ) return; + + bool_t use_ref = FALSE; +// printf("%d\t%d\t%d\t%d\t%d\t%d\t%d\n", b_n, PASTEMAC(d, axpyf_fusefac), inca, incx, incy, bli_is_unaligned_to(a, 32), bli_is_unaligned_to( y, 32)); + // If there is anything that would interfere with our use of aligned + // vector loads/stores, call the reference implementation. + if ( b_n < PASTEMAC(d,axpyf_fusefac) || inca != 1 || incx != 1 || incy != 1 || bli_is_unaligned_to( a, 32 ) || bli_is_unaligned_to( y, 32 ) ) + use_ref = TRUE; + // Call the reference implementation if needed. + if ( use_ref == TRUE ) + { +// printf("%d\t%d\t%d\t%d\t%d\t%d\n", PASTEMAC(d, axpyf_fusefac), inca, incx, incy, bli_is_unaligned_to(a, 32), bli_is_unaligned_to( y, 32)); +// printf("DEFAULTING TO REFERENCE IMPLEMENTATION\n"); + BLIS_DAXPYF_KERNEL_REF( conja, conjx, m, b_n, alpha, a, inca, lda, x, incx, y, incy ); + return; + } + + dim_t m_run = m / 4; + dim_t m_left = m % 4; + + double * a0 = a + 0*lda; + double * a1 = a + 1*lda; + double * a2 = a + 2*lda; + double * a3 = a + 3*lda; + double * a4 = a + 4*lda; + double * a5 = a + 5*lda; + double * a6 = a + 6*lda; + double * a7 = a + 7*lda; + double * y0 = y; + + double chi0 = *(x + 0*incx); + double chi1 = *(x + 1*incx); + double chi2 = *(x + 2*incx); + double chi3 = *(x + 3*incx); + double chi4 = *(x + 4*incx); + double chi5 = *(x + 5*incx); + double chi6 = *(x + 6*incx); + double chi7 = *(x + 7*incx); + + PASTEMAC2(d,d,scals)( *alpha, chi0 ); + PASTEMAC2(d,d,scals)( *alpha, chi1 ); + PASTEMAC2(d,d,scals)( *alpha, chi2 ); + PASTEMAC2(d,d,scals)( *alpha, chi3 ); + PASTEMAC2(d,d,scals)( *alpha, chi4 ); + PASTEMAC2(d,d,scals)( *alpha, chi5 ); + PASTEMAC2(d,d,scals)( *alpha, chi6 ); + PASTEMAC2(d,d,scals)( *alpha, chi7 ); + + vector4double a0v, a1v, a2v, a3v, a4v, a5v, a6v, a7v; + vector4double yv; + vector4double chi0v, chi1v, chi2v, chi3v, chi4v, chi5v, chi6v, chi7v; + chi0v = vec_splats( chi0 ); + chi1v = vec_splats( chi1 ); + chi2v = vec_splats( chi2 ); + chi3v = vec_splats( chi3 ); + chi4v = vec_splats( chi4 ); + chi5v = vec_splats( chi5 ); + chi6v = vec_splats( chi6 ); + chi7v = vec_splats( chi7 ); + + for ( dim_t i = 0; i < m_run; i += 1 ) + { + yv = vec_lda( 0 * sizeof(double), &y0[i*4]); + + a0v = vec_lda( 0 * sizeof(double), &a0[i*4]); + a1v = vec_lda( 0 * sizeof(double), &a1[i*4]); + a2v = vec_lda( 0 * sizeof(double), &a2[i*4]); + a3v = vec_lda( 0 * sizeof(double), &a3[i*4]); + a4v = vec_lda( 0 * sizeof(double), &a4[i*4]); + a5v = vec_lda( 0 * sizeof(double), &a5[i*4]); + a6v = vec_lda( 0 * sizeof(double), &a6[i*4]); + a7v = vec_lda( 0 * sizeof(double), &a7[i*4]); + + yv = vec_madd( chi0v, a0v, yv ); + yv = vec_madd( chi1v, a1v, yv ); + yv = vec_madd( chi2v, a2v, yv ); + yv = vec_madd( chi3v, a3v, yv ); + yv = vec_madd( chi4v, a4v, yv ); + yv = vec_madd( chi5v, a5v, yv ); + yv = vec_madd( chi6v, a6v, yv ); + yv = vec_madd( chi7v, a7v, yv ); + + vec_sta( yv, 0 * sizeof(double), &y0[i*4]); + } + + for ( dim_t i = 0; i < m_left; ++i ) + { + y0[4*m_run + i] += chi0 * a0[4*m_run + i] + + chi1 * a1[4*m_run + i] + + chi2 * a2[4*m_run + i] + + chi3 * a3[4*m_run + i] + + chi4 * a4[4*m_run + i] + + chi5 * a5[4*m_run + i] + + chi6 * a6[4*m_run + i] + + chi7 * a7[4*m_run + i]; + } + +} + + + +void bli_caxpyf_opt_var1( + conj_t conja, + conj_t conjx, + dim_t m, + dim_t b_n, + scomplex* restrict alpha, + scomplex* restrict a, inc_t inca, inc_t lda, + scomplex* restrict x, inc_t incx, + scomplex* restrict y, inc_t incy + ) +{ + /* Just call the reference implementation. */ + BLIS_CAXPYF_KERNEL_REF( conja, + conjx, + m, + b_n, + alpha, + a, inca, lda, + x, incx, + y, incy ); +} + + +void bli_zaxpyf_opt_var1( + conj_t conja, + conj_t conjx, + dim_t m, + dim_t b_n, + dcomplex* restrict alpha, + dcomplex* restrict a, inc_t inca, inc_t lda, + dcomplex* restrict x, inc_t incx, + dcomplex* restrict y, inc_t incy + ) +{ + /* Just call the reference implementation. */ + BLIS_ZAXPYF_KERNEL_REF( conja, + conjx, + m, + b_n, + alpha, + a, inca, lda, + x, incx, + y, incy ); +} + diff --git a/pool/shard006/C/0119069_rst.c b/pool/shard006/C/0119069_rst.c new file mode 100644 index 0000000000000000000000000000000000000000..6de141c5570a9be6f7e0e6c40e6ad61eeef34ff8 --- /dev/null +++ b/pool/shard006/C/0119069_rst.c @@ -0,0 +1,69 @@ +/* AMBER RST */ +int rrst(char *filename, int *atomnum, ATOM atom[], CONTROLINFO cinfo) +{ + int i, j; + int overflow_flag = 0; + FILE *fpin; + char line[MAXCHAR]; + +/* since rst file only has coordinates information, it can only be the additional file */ + if ((fpin = fopen(filename, "r")) == NULL) { + fprintf(stdout, "Cannot open rst file: %s, exit\n", filename); + exit(1); + } +/* readin the amber rst file */ + i = 0; + j = 0; + for (;;) { + if (fgets(line, MAXCHAR, fpin) == NULL) { +/* printf("\nFinished reading %s .", filename); */ + break; + } + j++; + if (j == 2) + sscanf(line, "%d", atomnum); + if (strncmp(".", &line[4], 1) == 0 + && strncmp(".", &line[16], 1) == 0 + && strncmp(".", &line[28], 1) == 0) { + if (overflow_flag == 0) + sscanf(&line[1], "%lf%lf%lf%lf%lf%lf", &atom[i].x, + &atom[i].y, &atom[i].z, &atom[i + 1].x, + &atom[i + 1].y, &atom[i + 1].z); + i = i + 2; + if (i >= *atomnum) break; + if (i >= cinfo.maxatom && overflow_flag == 0) { + printf + ("\nInfo: the atom number exceeds the MAXATOM, need reallocate memory automatically"); + overflow_flag = 1; + } + + } + } + fclose(fpin); + return overflow_flag; + +} +void wrst(char *filename, int atomnum, ATOM atom[]) +{ + int i, j; + FILE *fpout; + if ((fpout = fopen(filename, "w")) == NULL) { + fprintf(stdout, "Cannot open a file %s to write, exit\n", filename); + exit(1); + } + fprintf(fpout, "MOLECULE\n"); + fprintf(fpout, "%5d\n", atomnum); + i = 0; + j = 0; + while (i < atomnum) { + fprintf(fpout, "%12.7lf%12.7lf%12.7lf", atom[i].x, atom[i].y, + atom[i].z); + i++; + j++; + if (j == 2) { + fprintf(fpout, "\n"); + j = 0; + } + } + fclose(fpout); +} diff --git a/pool/shard006/C/0119071_task_fork_fair.c b/pool/shard006/C/0119071_task_fork_fair.c new file mode 100644 index 0000000000000000000000000000000000000000..2bbefefefafc14ef46230f87cf3b5b19b300c065 --- /dev/null +++ b/pool/shard006/C/0119071_task_fork_fair.c @@ -0,0 +1,58 @@ +/* + * called on fork with the child task as argument from the parent's context + * - child not yet on the tasklist + * - preemption disabled + */ +static void task_fork_fair(struct task_struct *p) +{ + struct cfs_rq *cfs_rq; + struct sched_entity *se = &p->se, *curr; + int this_cpu = smp_processor_id(); + struct rq *rq = this_rq(); + unsigned long flags; + + raw_spin_lock_irqsave(&rq->lock, flags); + + update_rq_clock(rq); + + cfs_rq = task_cfs_rq(current); + curr = cfs_rq->curr; + + /* + * Not only the cpu but also the task_group of the parent might have + * been changed after parent->se.parent,cfs_rq were copied to + * child->se.parent,cfs_rq. So call __set_task_cpu() to make those + * of child point to valid ones. + */ + rcu_read_lock(); + __set_task_cpu(p, this_cpu); + rcu_read_unlock(); + + /* 更新统计量 */ + update_curr(cfs_rq); + + if (curr) + se->vruntime = curr->vruntime; + /* 调整调度实体se的虚拟运行时间 */ + place_entity(cfs_rq, se, 1); + + /* 如果设置了sysctl_sched_child_runs_first期望se进程先运行 + * 但是se进行的虚拟运行时间却大于当前进程curr + * 此时我们需要保证se的entity_key小于curr, 才能保证se先运行 + * 内核此处是通过swap(curr, se)的虚拟运行时间来完成的 */ + if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) + { + /* + * Upon rescheduling, sched_class::put_prev_task() will place + * 'current' within the tree based on its new key value. + */ + /* 由于curr的vruntime较小, 为了使se先运行, 交换两者的vruntime */ + swap(curr->vruntime, se->vruntime); + /* 设置重调度标识, 通知内核在合适的时间进行进程调度 */ + resched_curr(rq); + } + + se->vruntime -= cfs_rq->min_vruntime; + + raw_spin_unlock_irqrestore(&rq->lock, flags); +} \ No newline at end of file diff --git a/pool/shard006/C/0119073_nft_objref.c b/pool/shard006/C/0119073_nft_objref.c new file mode 100644 index 0000000000000000000000000000000000000000..bf92a40dd1b2dc62cf027424453c2b7baee84904 --- /dev/null +++ b/pool/shard006/C/0119073_nft_objref.c @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2012-2016 Pablo Neira Ayuso + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define nft_objref_priv(expr) *((struct nft_object **)nft_expr_priv(expr)) + +static void nft_objref_eval(const struct nft_expr *expr, + struct nft_regs *regs, + const struct nft_pktinfo *pkt) +{ + struct nft_object *obj = nft_objref_priv(expr); + + obj->ops->eval(obj, regs, pkt); +} + +static int nft_objref_init(const struct nft_ctx *ctx, + const struct nft_expr *expr, + const struct nlattr * const tb[]) +{ + struct nft_object *obj = nft_objref_priv(expr); + u8 genmask = nft_genmask_next(ctx->net); + u32 objtype; + + if (!tb[NFTA_OBJREF_IMM_NAME] || + !tb[NFTA_OBJREF_IMM_TYPE]) + return -EINVAL; + + objtype = ntohl(nla_get_be32(tb[NFTA_OBJREF_IMM_TYPE])); + obj = nft_obj_lookup(ctx->table, tb[NFTA_OBJREF_IMM_NAME], objtype, + genmask); + if (IS_ERR(obj)) + return -ENOENT; + + nft_objref_priv(expr) = obj; + obj->use++; + + return 0; +} + +static int nft_objref_dump(struct sk_buff *skb, const struct nft_expr *expr) +{ + const struct nft_object *obj = nft_objref_priv(expr); + + if (nla_put_string(skb, NFTA_OBJREF_IMM_NAME, obj->name) || + nla_put_be32(skb, NFTA_OBJREF_IMM_TYPE, + htonl(obj->ops->type->type))) + goto nla_put_failure; + + return 0; + +nla_put_failure: + return -1; +} + +static void nft_objref_deactivate(const struct nft_ctx *ctx, + const struct nft_expr *expr, + enum nft_trans_phase phase) +{ + struct nft_object *obj = nft_objref_priv(expr); + + if (phase == NFT_TRANS_COMMIT) + return; + + obj->use--; +} + +static void nft_objref_activate(const struct nft_ctx *ctx, + const struct nft_expr *expr) +{ + struct nft_object *obj = nft_objref_priv(expr); + + obj->use++; +} + +static struct nft_expr_type nft_objref_type; +static const struct nft_expr_ops nft_objref_ops = { + .type = &nft_objref_type, + .size = NFT_EXPR_SIZE(sizeof(struct nft_object *)), + .eval = nft_objref_eval, + .init = nft_objref_init, + .activate = nft_objref_activate, + .deactivate = nft_objref_deactivate, + .dump = nft_objref_dump, +}; + +struct nft_objref_map { + struct nft_set *set; + enum nft_registers sreg:8; + struct nft_set_binding binding; +}; + +static void nft_objref_map_eval(const struct nft_expr *expr, + struct nft_regs *regs, + const struct nft_pktinfo *pkt) +{ + struct nft_objref_map *priv = nft_expr_priv(expr); + const struct nft_set *set = priv->set; + const struct nft_set_ext *ext; + struct nft_object *obj; + bool found; + + found = set->ops->lookup(nft_net(pkt), set, ®s->data[priv->sreg], + &ext); + if (!found) { + regs->verdict.code = NFT_BREAK; + return; + } + obj = *nft_set_ext_obj(ext); + obj->ops->eval(obj, regs, pkt); +} + +static int nft_objref_map_init(const struct nft_ctx *ctx, + const struct nft_expr *expr, + const struct nlattr * const tb[]) +{ + struct nft_objref_map *priv = nft_expr_priv(expr); + u8 genmask = nft_genmask_next(ctx->net); + struct nft_set *set; + int err; + + set = nft_set_lookup_global(ctx->net, ctx->table, + tb[NFTA_OBJREF_SET_NAME], + tb[NFTA_OBJREF_SET_ID], genmask); + if (IS_ERR(set)) + return PTR_ERR(set); + + if (!(set->flags & NFT_SET_OBJECT)) + return -EINVAL; + + priv->sreg = nft_parse_register(tb[NFTA_OBJREF_SET_SREG]); + err = nft_validate_register_load(priv->sreg, set->klen); + if (err < 0) + return err; + + priv->binding.flags = set->flags & NFT_SET_OBJECT; + + err = nf_tables_bind_set(ctx, set, &priv->binding); + if (err < 0) + return err; + + priv->set = set; + return 0; +} + +static int nft_objref_map_dump(struct sk_buff *skb, const struct nft_expr *expr) +{ + const struct nft_objref_map *priv = nft_expr_priv(expr); + + if (nft_dump_register(skb, NFTA_OBJREF_SET_SREG, priv->sreg) || + nla_put_string(skb, NFTA_OBJREF_SET_NAME, priv->set->name)) + goto nla_put_failure; + + return 0; + +nla_put_failure: + return -1; +} + +static void nft_objref_map_deactivate(const struct nft_ctx *ctx, + const struct nft_expr *expr, + enum nft_trans_phase phase) +{ + struct nft_objref_map *priv = nft_expr_priv(expr); + + nf_tables_deactivate_set(ctx, priv->set, &priv->binding, phase); +} + +static void nft_objref_map_activate(const struct nft_ctx *ctx, + const struct nft_expr *expr) +{ + struct nft_objref_map *priv = nft_expr_priv(expr); + + priv->set->use++; +} + +static void nft_objref_map_destroy(const struct nft_ctx *ctx, + const struct nft_expr *expr) +{ + struct nft_objref_map *priv = nft_expr_priv(expr); + + nf_tables_destroy_set(ctx, priv->set); +} + +static struct nft_expr_type nft_objref_type; +static const struct nft_expr_ops nft_objref_map_ops = { + .type = &nft_objref_type, + .size = NFT_EXPR_SIZE(sizeof(struct nft_objref_map)), + .eval = nft_objref_map_eval, + .init = nft_objref_map_init, + .activate = nft_objref_map_activate, + .deactivate = nft_objref_map_deactivate, + .destroy = nft_objref_map_destroy, + .dump = nft_objref_map_dump, +}; + +static const struct nft_expr_ops * +nft_objref_select_ops(const struct nft_ctx *ctx, + const struct nlattr * const tb[]) +{ + if (tb[NFTA_OBJREF_SET_SREG] && + (tb[NFTA_OBJREF_SET_NAME] || + tb[NFTA_OBJREF_SET_ID])) + return &nft_objref_map_ops; + else if (tb[NFTA_OBJREF_IMM_NAME] && + tb[NFTA_OBJREF_IMM_TYPE]) + return &nft_objref_ops; + + return ERR_PTR(-EOPNOTSUPP); +} + +static const struct nla_policy nft_objref_policy[NFTA_OBJREF_MAX + 1] = { + [NFTA_OBJREF_IMM_NAME] = { .type = NLA_STRING, + .len = NFT_OBJ_MAXNAMELEN - 1 }, + [NFTA_OBJREF_IMM_TYPE] = { .type = NLA_U32 }, + [NFTA_OBJREF_SET_SREG] = { .type = NLA_U32 }, + [NFTA_OBJREF_SET_NAME] = { .type = NLA_STRING, + .len = NFT_SET_MAXNAMELEN - 1 }, + [NFTA_OBJREF_SET_ID] = { .type = NLA_U32 }, +}; + +static struct nft_expr_type nft_objref_type __read_mostly = { + .name = "objref", + .select_ops = nft_objref_select_ops, + .policy = nft_objref_policy, + .maxattr = NFTA_OBJREF_MAX, + .owner = THIS_MODULE, +}; + +static int __init nft_objref_module_init(void) +{ + return nft_register_expr(&nft_objref_type); +} + +static void __exit nft_objref_module_exit(void) +{ + nft_unregister_expr(&nft_objref_type); +} + +module_init(nft_objref_module_init); +module_exit(nft_objref_module_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Pablo Neira Ayuso "); +MODULE_ALIAS_NFT_EXPR("objref"); diff --git a/pool/shard006/C/0119074_ssh.c b/pool/shard006/C/0119074_ssh.c new file mode 100644 index 0000000000000000000000000000000000000000..06c6bf281b9dad7b8ca6a8929e59b5098b568572 --- /dev/null +++ b/pool/shard006/C/0119074_ssh.c @@ -0,0 +1,65 @@ +/* + + Tomato Firmware + Copyright (C) 2006-2009 Jonathan Zarate + +*/ + +#include "rc.h" + +static inline int check_host_key(const char *ktype, const char *nvname, const char *hkfn) +{ + unlink(hkfn); + + if (!nvram_get_file(nvname, hkfn, 2048)) { + eval("dropbearkey", "-t", (char *)ktype, "-f", (char *)hkfn); + if (nvram_set_file(nvname, hkfn, 2048)) { + return 1; + } + } + + return 0; +} + +void start_sshd(void) +{ + int dirty = 0; + char *argv[11]; + int argc; + char *p; + + if (!nvram_match("sshd_enable", "1")) + return; + + mkdir("/etc/dropbear", 0700); + mkdir("/root/.ssh", 0700); + + f_write_string("/root/.ssh/authorized_keys", nvram_safe_get("sshd_authkeys"), 0, 0700); + + dirty |= check_host_key("rsa", "sshd_hostkey", "/etc/dropbear/dropbear_rsa_host_key"); + dirty |= check_host_key("dss", "sshd_dsskey", "/etc/dropbear/dropbear_dss_host_key"); + if (dirty) + nvram_commit_x(); + + argv[0] = "dropbear"; + argv[1] = "-p"; + argv[2] = nvram_safe_get("sshd_port"); + argc = 3; + + if (!nvram_get_int("sshd_pass")) argv[argc++] = "-s"; + + argv[argc++] = "-a"; + + if (((p = nvram_get("sshd_rwb")) != NULL) && (*p)) { + argv[argc++] = "-W"; + argv[argc++] = p; + } + + argv[argc] = NULL; + _eval(argv, NULL, 0, NULL); +} + +void stop_sshd(void) +{ + killall("dropbear", SIGTERM); +} diff --git a/pool/shard006/C/0119075_tl_video.c b/pool/shard006/C/0119075_tl_video.c new file mode 100644 index 0000000000000000000000000000000000000000..ddb5f22dea4fafc0c49304f0e0d931bf1f03e4e1 --- /dev/null +++ b/pool/shard006/C/0119075_tl_video.c @@ -0,0 +1,143 @@ +/* +** thinlib (c) 2001 Matthew Conte (matt@conte.com) +** +** +** tl_video.h +** +** thinlib video routines +** +** $Id: tl_video.c,v 1.1.1.1 2003/07/04 19:19:58 joshua Exp $ +*/ + +#include "tl_types.h" +#include "tl_video.h" +#include "tl_vesa.h" +#include "tl_vga.h" +#include "tl_log.h" + +typedef struct viddriver_s +{ + const char *name; + int (*init)(int width, int height, int bpp, int param); + void (*shutdown)(void); + int (*setmode)(int width, int height, int bpp); + void (*setpalette)(rgb_t *palette, int index, int length); + void (*waitvsync)(void); + bitmap_t *(*lock)(void); + void (*free)(int num_dirties, rect_t *dirty_rects); + void (*blit)(bitmap_t *primary, int num_dirties, rect_t *dirty_rects); + int caps; +} viddriver_t; + +static viddriver_t vesa = +{ + "VESA 3.0 LFB", + thin_vesa_init, + thin_vesa_shutdown, + thin_vesa_setmode, + thin_vga_setpalette, + thin_vga_waitvsync, + thin_vesa_lockwrite, + thin_vesa_freewrite, + NULL, + 0, +}; + +static viddriver_t vga = +{ + "VGA", + thin_vga_init, + thin_vga_shutdown, + thin_vga_setmode, + thin_vga_setpalette, + thin_vga_waitvsync, + thin_vga_lockwrite, + thin_vga_freewrite, + NULL, + 0, /*THIN_VIDEO_SCANLINES,*/ +}; + +static viddriver_t *driver_list[] = +{ + &vesa, + &vga, + NULL +}; + +static viddriver_t driver; + +int thin_vid_init(int width, int height, int bpp, int param) +{ + /* cascade driver checks by iterating through all drivers */ + viddriver_t **iter; + + for (iter = driver_list; *iter != NULL; iter++) + { + if (0 == (*iter)->init(width, height, bpp, param)) + { + driver = **iter; + return 0; + } + } + + driver.name = NULL; + thin_printf("thinlib.video: could not find any matching video modes.\n"); + return -1; +} + +void thin_vid_shutdown(void) +{ + if (NULL != driver.name) + { + driver.shutdown(); + memset(&driver, 0, sizeof(viddriver_t)); + } +} + +int thin_vid_getcaps(void) +{ + return driver.caps; +} + +int thin_vid_setmode(int width, int height, int bpp) +{ + if (driver.setmode(width, height, bpp)) + { + thin_printf("thinlib.video: could not set %s video mode %dx%d %dbpp\n", + driver.name, width, height, bpp); + return -1; + } + + return 0; +} + +void thin_vid_setpalette(rgb_t *palette, int index, int length) +{ + driver.setpalette(palette, index, length); +} + +bitmap_t *thin_vid_lockwrite(void) +{ + return driver.lock(); +} + +void thin_vid_freewrite(int num_dirties, rect_t *dirty_rects) +{ + if (NULL != driver.free) + driver.free(num_dirties, dirty_rects); +} + +void thin_vid_customblit(bitmap_t *primary, int num_dirties, + rect_t *dirty_rects) +{ + THIN_ASSERT(driver.blit); + + driver.blit(primary, num_dirties, dirty_rects); +} + +/* +** $Log: tl_video.c,v $ +** Revision 1.1.1.1 2003/07/04 19:19:58 joshua +** initial import +** +*/ diff --git a/pool/shard006/C/0119076_core.c b/pool/shard006/C/0119076_core.c new file mode 100644 index 0000000000000000000000000000000000000000..975bc7a3cb927232c988e20af10adaf1f8b4ca7c --- /dev/null +++ b/pool/shard006/C/0119076_core.c @@ -0,0 +1,129 @@ +/* + * ===================================================================================== + * + * Filename: fileUtil.c + * + * Description: + * + * Version: 1.0 + * Created: 2017年02月19日 23时33分38秒 + * Revision: none + * Compiler: gcc + * + * Author: Ni Zhiyang (), nizyt1@163.com + * Organization: + * + * ===================================================================================== + */ +#undef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include "debug.h" +#include "data.h" +#include "core.h" + +int generate(unsigned char *app, unsigned char *username, unsigned char *b64_pwd, int pwd_len) +{ + unsigned char *password = (unsigned char *)malloc((pwd_len + 1) * sizeof(unsigned char)); + memset(password, '\0', pwd_len+1); + + pwd_gene(app, username, password, pwd_len); + + int len_cip = (strlen(password)/AES_ARR_LEN+1)*AES_ARR_LEN; + unsigned char *ciphertext = (unsigned char *)malloc((len_cip + 1)*sizeof(unsigned char )); + memset(ciphertext, '\0', len_cip + 1); + + unsigned char *key = "0123456789ABCDEF"; + + encrypt(password, ciphertext, key); + PDEBUG("CIPHER: %s\n", ciphertext); + Base64Encode(ciphertext, &b64_pwd); + PDEBUG("BASE64: %s\n", b64_pwd); + free(password); + free(ciphertext); + +} + +int insert(unsigned char *app, unsigned char *username, unsigned char *password) +{ + unsigned char *buffer; + int length = strlen(app)+strlen(username)+strlen(password) + 4; + buffer = (unsigned char *)malloc(length*sizeof(unsigned char)); + memset(buffer, '\0', length); + strcat(buffer, app); + strcat(buffer, ":"); + strcat(buffer, username); + strcat(buffer, ":"); + strcat(buffer, password); + strcat(buffer, "\n"); + + PDEBUG("buffer: %s\n", buffer); + + if(strlen(buffer) < 1) + { + PDEBUG("BUFFER_EMPTY\n"); + return BUFFER_EMPTY; + } + + unsigned char *home = getenv("HOME"); + PDEBUG("HOME: %s\n", home); + + int pwd_path_len = strlen(home) + strlen(PWDDIR) + strlen(PWDFILE) + 3; + unsigned char *pwdpath = (unsigned char *)malloc((strlen(home) + strlen(PWDDIR) + strlen(PWDFILE) + 2)*sizeof(unsigned char)); + + memset(pwdpath, '\0', pwd_path_len); + strcat(pwdpath, home); + strcat(pwdpath, "/"); + strcat(pwdpath, PWDDIR); + + PDEBUG("Path: %s\n", pwdpath); + + if(access(pwdpath, F_OK) < 0) + { + PDEBUG("DIR not exsit\n"); + mkdir(pwdpath, DIR_MASK); + }else{ + PDEBUG("DIR exsit\n"); + } + + strcat(pwdpath, "/"); + strcat(pwdpath, PWDFILE); + + PDEBUG("PWDFile: %s\n", PWDFILE); + + int fd; + if( (fd = open(pwdpath, O_RDWR | O_APPEND | O_CREAT , FILE_MASK)) == -1) + { + PDEBUG("FILE_NOT_EXSIT: %s %d\n", PWDFILE, fd); + return FILE_NOT_EXSIT; + } + + write(fd, buffer, strlen(buffer)); + + close(fd); + + return INSERT_SUCCESS; +} + +int search(unsigned char *app, unsigned char *username) +{ + if(true) + return USER_EXSIT; + else + return USER_NOT_EXSIT; +} + +int update(unsigned char *app, unsigned char *username, unsigned char *password) +{ + +} + +int delete(unsigned char *app, unsigned char *username) +{ + +} diff --git a/pool/shard006/C/0119077_giggle-helpers.c b/pool/shard006/C/0119077_giggle-helpers.c new file mode 100644 index 0000000000000000000000000000000000000000..c62d88a2a893b26b08630f6eb569239ad78ce95d --- /dev/null +++ b/pool/shard006/C/0119077_giggle-helpers.c @@ -0,0 +1,222 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ +/* + * Copyright (C) 2007 Imendio AB + * + * 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 "config.h" +#include "giggle-helpers.h" + +#include "libgiggle-git/giggle-git.h" + +#include +#include + +static void +remote_editor_tree_selection_get_branches (GtkTreeModel *model, + GtkTreePath *path, + GtkTreeIter *iter, + GList **branches) +{ + *branches = g_list_prepend (*branches, gtk_tree_row_reference_new (model, path)); +} + +static void +remote_editor_remove_branch (GtkTreeRowReference *ref) +{ + GtkTreeModel *model; + GtkTreeIter iter; + + model = gtk_tree_row_reference_get_model (ref); + gtk_tree_model_get_iter (model, &iter, + gtk_tree_row_reference_get_path (ref)); + gtk_list_store_remove (GTK_LIST_STORE (model), &iter); + + gtk_tree_row_reference_free (ref); +} + +/* returns TRUE if the key press was delete and at least one row has been + * deleted */ +gboolean +giggle_list_view_delete_selection (GtkWidget *treeview, + GdkEventKey *event) +{ + if (event->keyval == GDK_Delete) { + GtkTreeSelection* sel; + sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); + + if (gtk_tree_selection_count_selected_rows (sel) > 0) { + GList* branches = NULL; + gtk_tree_selection_selected_foreach (sel, + (GtkTreeSelectionForeachFunc) + remote_editor_tree_selection_get_branches, + &branches); + g_list_foreach (branches, (GFunc)remote_editor_remove_branch, NULL); + g_list_free (branches); + return TRUE; + } + } + return FALSE; +} + +static gboolean +tree_model_find_string (GtkTreeModel *model, + GtkTreeIter *iter, + GtkTreeIter *parent, + int column, + const char *pattern) +{ + GtkTreeIter child; + char *text; + + if (gtk_tree_model_iter_children (model, iter, parent)) { + do { + gtk_tree_model_get (model, iter, column, &text, -1); + + if (!g_strcmp0 (text, pattern)) { + g_free (text); + return TRUE; + } + + g_free (text); + + if (tree_model_find_string (model, &child, iter, column, pattern)) { + *iter = child; + return TRUE; + } + } while (gtk_tree_model_iter_next (model, iter)); + } + + return FALSE; +} + +gboolean +giggle_tree_view_select_row_by_string (GtkWidget *treeview, + int column, + const char *pattern) +{ + GtkTreeSelection *selection; + GtkTreeModel *model; + GtkTreeIter iter; + GtkTreePath *path; + char *text; + + selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview)); + + if (gtk_tree_selection_get_selected (selection, &model, &iter)) { + gtk_tree_model_get (model, &iter, column, &text, -1); + } else { + model = gtk_tree_view_get_model (GTK_TREE_VIEW (treeview)); + text = NULL; + } + + if (!g_strcmp0 (text, pattern)) { + g_free (text); + return TRUE; + } + + if (tree_model_find_string (model, &iter, NULL, column, pattern)) { + path = gtk_tree_model_get_path (model, &iter); + gtk_tree_view_expand_to_path (GTK_TREE_VIEW (treeview), path); + gtk_tree_path_free (path); + + gtk_tree_selection_select_iter (selection, &iter); + + return TRUE; + } + + return FALSE; +} + +GtkActionGroup * +giggle_ui_manager_get_action_group (GtkUIManager *manager, + const char *group_name) +{ + GList *groups; + + groups = gtk_ui_manager_get_action_groups (manager); + + while (groups) { + if (!g_strcmp0 (group_name, + gtk_action_group_get_name (groups->data))) + return groups->data; + + groups = groups->next; + } + + return NULL; +} + +GAppLaunchContext * +giggle_create_app_launch_context (GtkWidget *widget) +{ +#if GTK_CHECK_VERSION(2,14,0) + GdkAppLaunchContext *context; + GdkScreen *screen = NULL; + + context = gdk_app_launch_context_new (); + + if (widget) { + screen = gtk_widget_get_screen (widget); + gdk_app_launch_context_set_screen (context, screen); + } + + return G_APP_LAUNCH_CONTEXT (context); +#else + return g_app_launch_context_new (); +#endif +} + +void +giggle_open_file_with_context (GAppLaunchContext *context, + const char *directory, + const char *filename) +{ + GError *error = NULL; + char *path, *uri; + + g_return_if_fail (G_IS_APP_LAUNCH_CONTEXT (context)); + g_return_if_fail (NULL != filename); + + if (!directory) + directory = giggle_git_get_directory (giggle_git_get ()); + + g_return_if_fail (NULL != directory); + + path = g_build_filename (directory, filename, NULL); + uri = g_filename_to_uri (path, NULL, &error); + + if (!uri || !g_app_info_launch_default_for_uri (uri, context, &error)) { + g_warning ("%s: %s", G_STRFUNC, error->message); + g_clear_error (&error); + } + + g_free (path); + g_free (uri); +} + +void +giggle_open_file (GtkWidget *widget, + const char *directory, + const char *filename) +{ + GAppLaunchContext *context; + + context = giggle_create_app_launch_context (widget); + giggle_open_file_with_context (context, directory, filename); + g_object_unref (context); +} diff --git a/pool/shard006/C/0119078_ddr.c b/pool/shard006/C/0119078_ddr.c new file mode 100644 index 0000000000000000000000000000000000000000..0b16982f06ab56a664fadd8167efbcc5a6f08d7f --- /dev/null +++ b/pool/shard006/C/0119078_ddr.c @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Copyright 2014 Freescale Semiconductor, Inc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "ddr.h" + +DECLARE_GLOBAL_DATA_PTR; + +void fsl_ddr_board_options(memctl_options_t *popts, + dimm_params_t *pdimm, + unsigned int ctrl_num) +{ + const struct board_specific_parameters *pbsp, *pbsp_highest = NULL; + ulong ddr_freq; + + if (ctrl_num > 1) { + printf("Not supported controller number %d\n", ctrl_num); + return; + } + if (!pdimm->n_ranks) + return; + + pbsp = udimms[0]; + + /* Get clk_adjust, wrlvl_start, wrlvl_ctl, according to the board ddr + * freqency and n_banks specified in board_specific_parameters table. + */ + ddr_freq = get_ddr_freq(0) / 1000000; + while (pbsp->datarate_mhz_high) { + if (pbsp->n_ranks == pdimm->n_ranks && + (pdimm->rank_density >> 30) >= pbsp->rank_gb) { + if (ddr_freq <= pbsp->datarate_mhz_high) { + popts->clk_adjust = pbsp->clk_adjust; + popts->wrlvl_start = pbsp->wrlvl_start; + popts->wrlvl_ctl_2 = pbsp->wrlvl_ctl_2; + popts->wrlvl_ctl_3 = pbsp->wrlvl_ctl_3; + goto found; + } + pbsp_highest = pbsp; + } + pbsp++; + } + + if (pbsp_highest) { + printf("Error: board specific timing not found"); + printf("for data rate %lu MT/s\n", ddr_freq); + printf("Trying to use the highest speed (%u) parameters\n", + pbsp_highest->datarate_mhz_high); + popts->clk_adjust = pbsp_highest->clk_adjust; + popts->wrlvl_start = pbsp_highest->wrlvl_start; + popts->wrlvl_ctl_2 = pbsp->wrlvl_ctl_2; + popts->wrlvl_ctl_3 = pbsp->wrlvl_ctl_3; + } else { + panic("DIMM is not supported by this board"); + } +found: + debug("Found timing match: n_ranks %d, data rate %d, rank_gb %d\n" + "\tclk_adjust %d, wrlvl_start %d, wrlvl_ctrl_2 0x%x, " + "wrlvl_ctrl_3 0x%x\n", + pbsp->n_ranks, pbsp->datarate_mhz_high, pbsp->rank_gb, + pbsp->clk_adjust, pbsp->wrlvl_start, pbsp->wrlvl_ctl_2, + pbsp->wrlvl_ctl_3); + + /* + * Factors to consider for half-strength driver enable: + * - number of DIMMs installed + */ + popts->half_strength_driver_enable = 0; + /* + * Write leveling override + */ + popts->wrlvl_override = 1; + popts->wrlvl_sample = 0xf; + + /* + * Rtt and Rtt_WR override + */ + popts->rtt_override = 0; + + /* Enable ZQ calibration */ + popts->zq_en = 1; + + /* DHC_EN =1, ODT = 75 Ohm */ + popts->ddr_cdr1 = DDR_CDR1_DHC_EN | DDR_CDR1_ODT(DDR_CDR_ODT_75ohm); + popts->ddr_cdr2 = DDR_CDR2_ODT(DDR_CDR_ODT_75ohm); + + /* optimize cpo for erratum A-009942 */ + popts->cpo_sample = 0x54; +} + +int dram_init(void) +{ + phys_size_t dram_size; + +#if defined(CONFIG_SPL_BUILD) || !defined(CONFIG_RAMBOOT_PBL) + puts("Initializing....using SPD\n"); + dram_size = fsl_ddr_sdram(); +#else + /* DDR has been initialised by first stage boot loader */ + dram_size = fsl_ddr_sdram_size(); +#endif + dram_size = setup_ddr_tlbs(dram_size / 0x100000); + dram_size *= 0x100000; + + gd->ram_size = dram_size; + + return 0; +} diff --git a/pool/shard006/C/0119083_descriptor.c b/pool/shard006/C/0119083_descriptor.c new file mode 100644 index 0000000000000000000000000000000000000000..86cef33ab13241f4b8028d9d21b200663cb04d20 --- /dev/null +++ b/pool/shard006/C/0119083_descriptor.c @@ -0,0 +1,83 @@ +#include +#include + +#ifndef NULL +#define NULL ((void *) 0) +#endif + +JNIEXPORT jfloatArray JNICALL +Java_com_jmr_1android_jmr_SingleColorDescription_meanC(JNIEnv *env, jobject instance, + jintArray image_) { + jint *image = (*env)->GetIntArrayElements(env, image_, NULL); + + (*env)->ReleaseIntArrayElements(env, image_, image, 0); + int size = (*env)->GetArrayLength(env, image_); + + int width = 0; + int height = 0; + int x, y; + + int imagesize = 200 * 200; + + float mean[3] = {0.0f, 0.0f, 0.0f}; + + jint *body = (*env)->GetIntArrayElements(env, image_, 0); + + int i = 0; + for(i = 0; i < size; i++){ + mean[0] += (body[i] >> 16) & 0xFF; + mean[1] += (body[i] >> 8) & 0xFF; + mean[2] += body[i] & 0xFF; + } + + mean[0] /= imagesize; + mean[1] /= imagesize; + mean[2] /= imagesize; + + + jfloatArray mean2 = (*env)->NewFloatArray(env, 3); + + (*env)->SetFloatArrayRegion(env, mean2, 0, 3, mean); + return mean2; +} + +JNIEXPORT jint JNICALL +Java_com_jmr_1android_jmr_MPEG7ColorStructure_quantFuncC(JNIEnv *env, jobject instance, jdouble x) { + + int i = 0; + double stepIn[] = {0.000000001, 0.037, 0.08, 0.195, 0.32, 1}; + int stepInLength = 6; + int stepOut[] = {-1, 0, 25, 45, 80, 115}; + int y = 0; + if (x <= 0) { + y = 0; + } else if (x >= 1) { + y = 255; + } else { + y = (int) round(((x - 0.32) / (1 - 0.32)) * 140.0); + for (i = 0; i < stepInLength; i++) { + if (x < stepIn[i]) { + y += stepOut[i]; + break; + } + } + // Since there is a bug in Caliph & emir version the data + // are between -66 and 255 + y = (int) (255.0 * ((double) y + 66) / (255.0 + 66.0)); + } + return y; + +} + +JNIEXPORT jdouble JNICALL +Java_com_jmr_1android_jmr_SingleColorDescription_compare__IIIIII(JNIEnv *env, jobject instance, + jint red1, jint green1, jint blue1, + jint red2, jint green2, + jint blue2) { + + double rDif = pow(red1 - red2, 2); + double gDif = pow(green1 - green2, 2); + double bDif = pow(blue1 - blue2, 2); + return sqrt(rDif + gDif + bDif); + +} \ No newline at end of file diff --git a/pool/shard006/C/0119087_NGAP_AveragingWindow.c b/pool/shard006/C/0119087_NGAP_AveragingWindow.c new file mode 100644 index 0000000000000000000000000000000000000000..176a6114f23526a348e124f819fc48961665e0b1 --- /dev/null +++ b/pool/shard006/C/0119087_NGAP_AveragingWindow.c @@ -0,0 +1,71 @@ +/* + * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) + * From ASN.1 module "NGAP-IEs" + * found in "../support/ngap-r16.4.0/38413-g40.asn" + * `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps -no-gen-BER -no-gen-XER -no-gen-OER -no-gen-UPER` + */ + +#include "NGAP_AveragingWindow.h" + +int +NGAP_AveragingWindow_constraint(const asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + ASN__CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0L && value <= 4095L)) { + /* Constraint check succeeded */ + return 0; + } else { + ASN__CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +/* + * This type is implemented using NativeInteger, + * so here we adjust the DEF accordingly. + */ +#if !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) +asn_per_constraints_t asn_PER_type_NGAP_AveragingWindow_constr_1 CC_NOTUSED = { + { APC_CONSTRAINED | APC_EXTENSIBLE, 12, 12, 0, 4095 } /* (0..4095,...) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +#endif /* !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) */ +static const ber_tlv_tag_t asn_DEF_NGAP_AveragingWindow_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_NGAP_AveragingWindow = { + "AveragingWindow", + "AveragingWindow", + &asn_OP_NativeInteger, + asn_DEF_NGAP_AveragingWindow_tags_1, + sizeof(asn_DEF_NGAP_AveragingWindow_tags_1) + /sizeof(asn_DEF_NGAP_AveragingWindow_tags_1[0]), /* 1 */ + asn_DEF_NGAP_AveragingWindow_tags_1, /* Same as above */ + sizeof(asn_DEF_NGAP_AveragingWindow_tags_1) + /sizeof(asn_DEF_NGAP_AveragingWindow_tags_1[0]), /* 1 */ + { +#if !defined(ASN_DISABLE_OER_SUPPORT) + 0, +#endif /* !defined(ASN_DISABLE_OER_SUPPORT) */ +#if !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) + &asn_PER_type_NGAP_AveragingWindow_constr_1, +#endif /* !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) */ + NGAP_AveragingWindow_constraint + }, + 0, 0, /* No members */ + 0 /* No specifics */ +}; + diff --git a/pool/shard006/C/0119089_wdidle3.c b/pool/shard006/C/0119089_wdidle3.c new file mode 100644 index 0000000000000000000000000000000000000000..ecefd365dc1715f94198b59a436acae7a6d299d8 --- /dev/null +++ b/pool/shard006/C/0119089_wdidle3.c @@ -0,0 +1,212 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sgio.h" +#include "hdparm.h" + +extern int verbose; /* hdparm.c */ + +/* + * The Western Digital (WD) "Green" drive IDLE3 timeout value is 8-bits. + * Earlier models used a strict value from 8.0 to 25.5 seconds (0x50 to 0xff). + * Later models use 8.0 to 12.7 secs (0x50 to 0x7f), and 30 to 300 secs (0x81 to 0x8a). + * Other values are undefined, but have been observed on some drives. + * + * Older drives (from WDIDLE3.EXE documentation): + * 0x00 timer disabled. + * 0x50-0xff timeout in tenths of a second, from 8.0 to 25.5 seconds. + * + * + * Some drives (found by observation): + * 0x01-0x50 timeout in seconds, from 1 to 30 seconds (?). + * + * Newer drives (from WDIDLE3.EXE documentation): + * 0x00 timer disabled. + * 0x01-0x49 not permitted by WDIDLE3.EXE; reports as 0.1 to 7.9 seconds. + * 0x50-0x7f timeout in tenths of a second, from 8.0 to 12.7 seconds. + * 0x80 not permitted by WDIDLE3.EXE; reports as 12.8 seconds. + * 0x81-0x8a timeout in 30s of seconds, from 30 to 300 seconds. + * 0x90-0xff not permitted; reports as 330 to 3810 seconds. + * + * A WD whitepaper identified some models/versions of drives with the "older" firmware, + * but no comprehensive list exists. Models with firmware 02.01B01 are "older", + * and models with "02.01B02" are "newer". + * + * The real WDIDLE3 utility determines the correct value ranges + * by interogating the drive somehow, or perhaps based on the reported firmware version. + * + * WDIDLE3.EXE also writes some scary looking full 512-byte sequences to the drives + * in addition to what we do here. + * + * So this (hdparm) method may be somewhat risky, since it doesn't do everything WD does. + */ + +enum { + WDC_VSC_DISABLED = 'D', + WDC_VSC_ENABLED = 'E', + WDC_IDLE3_READ = 1, + WDC_IDLE3_WRITE = 2, + WDC_OP_TIMEOUT_SECS = 12, + WDC_TIMEOUT_THRESHOLD = 128, +}; + +static int wdidle3_issue (int fd, int rw, struct ata_tf *tf, void *data, const char *msg) +{ + int ret = sg16(fd, rw, SG_PIO, tf, data, data ? 512 : 0, WDC_OP_TIMEOUT_SECS); + if (ret != 0) { + ret = errno; + perror(msg); + } + return ret; +} + +/* + * Note: when WD vendor-specific-commands (vsc) are enabled, + * the ATA_OP_SMART command is "enhanced" to support additional + * functions to read/write specific data "registers" from the firmware. + * This may (or not) also cause regular SMART commands to fail (?). + */ +static int wdidle3_vsc_enable_disable (int fd, int setting) +{ + struct ata_tf tf; + unsigned long long vendor_WD0 = ('W' << 16) | ('D' << 8) | 0; + + tf_init(&tf, ATA_OP_VENDOR_SPECIFIC_0x80, vendor_WD0, 0); + tf.lob.feat = setting; + tf.dev = 0xa0; + return wdidle3_issue(fd, SG_WRITE, &tf, NULL, __func__); +} + +/* + * This sends a key (password? I2C address?) to the drive + * in preparation for a data_in or data_out command. + */ +static int wdidle3_vsc_send_key (int fd, int rw) +{ + char data[512]; + struct ata_tf tf; + + memset(data, 0, sizeof(data)); + tf_init(&tf, ATA_OP_SMART, 0xc24fbe, 1); + tf.lob.feat = 0xd6; + tf.dev = 0xa0; + data[ 0] = 0x2a; + data[ 2] = rw; + data[ 4] = 0x02; + data[ 6] = 0x0d; + data[ 8] = 0x16; + data[10] = 0x01; + return wdidle3_issue(fd, SG_WRITE, &tf, data, __func__); +} + +/* + * This reads a data value from the drive. + */ +static int wdidle3_data_in (int fd, unsigned char *timeout) +{ + char data[512]; + int ret; + struct ata_tf tf; + + memset(data, 0, sizeof(data)); + tf_init(&tf, ATA_OP_SMART, 0xc24fbf, 1); + tf.lob.feat = 0xd5; + tf.dev = 0xa0; + ret = wdidle3_issue(fd, SG_READ, &tf, data, __func__); + if (!ret) + *timeout = data[0]; + return ret; +} + +/* + * This writes a data value to the drive. + */ +static int wdidle3_vsc_data_out (int fd, unsigned char timeout) +{ + char data[512]; + struct ata_tf tf; + + memset(data, 0, sizeof(data)); + tf_init(&tf, ATA_OP_SMART, 0xc24fbf, 1); + tf.lob.feat = 0xd6; + tf.dev = 0xa0; + data[0] = timeout; + return wdidle3_issue(fd, SG_WRITE, &tf, data, __func__); +} + +int wdidle3_set_timeout (int fd, unsigned char timeout) +{ + int ret, ret2; + + ret = wdidle3_vsc_enable_disable(fd, WDC_VSC_ENABLED); + if (!ret) { + ret = wdidle3_vsc_send_key(fd, WDC_IDLE3_WRITE); + if (!ret) + ret = wdidle3_vsc_data_out(fd, timeout); + ret2 = wdidle3_vsc_enable_disable(fd, WDC_VSC_DISABLED); + if (!ret) + ret = ret2; + } + return ret; +} + +int wdidle3_get_timeout (int fd, unsigned char *timeout) +{ + int ret, ret2; + + ret = wdidle3_vsc_enable_disable(fd, WDC_VSC_ENABLED); + if (!ret) { + ret = wdidle3_vsc_send_key(fd, WDC_IDLE3_READ); + if (!ret) + ret = wdidle3_data_in(fd, timeout); + ret2 = wdidle3_vsc_enable_disable(fd, WDC_VSC_DISABLED); + if (!ret) + ret = ret2; + } + return ret; +} + +unsigned char wdidle3_msecs_to_timeout (unsigned int secs) +{ + unsigned char timeout; + + if (secs == 0) + timeout = 0; /* disabled */ + else if (secs < 8) + timeout = 80; /* 8.0 seconds minimum */ + else if (secs <= (WDC_TIMEOUT_THRESHOLD / 10)) + timeout = secs * 10; /* 8.0 to 12.7 seconds */ + else { + secs += 29; /* round up to next multiple of 30 */ + if (secs > 300) + secs = 300; /* max timeout is 300 secs */ + timeout = (secs / 30) + WDC_TIMEOUT_THRESHOLD; + } + return timeout; +} + +void wdidle3_print_timeout (unsigned char timeout) +{ + if (verbose) + printf("[raw=0x%02x] ", timeout); //FIXME + if (timeout == 0) + printf("disabled"); + else if (timeout < 0x50 || timeout == WDC_TIMEOUT_THRESHOLD) + printf("%u ??", timeout); + else if (timeout < WDC_TIMEOUT_THRESHOLD) + printf("%u.%u secs", timeout / 10, timeout % 10); + else { + if (timeout > (WDC_TIMEOUT_THRESHOLD + 10)) + printf("%u ??", timeout); + else + printf("%u secs", (timeout - WDC_TIMEOUT_THRESHOLD) * 30); + printf(" (or %u.%u secs for older drives)", timeout / 10, timeout % 10); + } +} diff --git a/pool/shard006/C/0119092_CWE78_OS_Command_Injection__char_environment_w32spawnl_03.c b/pool/shard006/C/0119092_CWE78_OS_Command_Injection__char_environment_w32spawnl_03.c new file mode 100644 index 0000000000000000000000000000000000000000..92316bfca7a0c29015a05ec6aedf7600dbde8362 --- /dev/null +++ b/pool/shard006/C/0119092_CWE78_OS_Command_Injection__char_environment_w32spawnl_03.c @@ -0,0 +1,146 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_environment_w32spawnl_03.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-03.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: environment Read input from an environment variable + * GoodSource: Fixed string + * Sink: w32spawnl + * BadSink : execute command with spawnl + * Flow Variant: 03 Control flow: if(5==5) and if(5!=5) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "ls" +#define COMMAND_ARG2 "-la" +#define COMMAND_ARG3 data +#endif + +#define ENV_VARIABLE "ADD" + +#ifdef _WIN32 +#define GETENV getenv +#else +#define GETENV getenv +#endif + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_environment_w32spawnl_03_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(5==5) + { + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the 5==5 to 5!=5 */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(5!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(5==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__char_environment_w32spawnl_03_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_environment_w32spawnl_03_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_environment_w32spawnl_03_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0119096_brk.c b/pool/shard006/C/0119096_brk.c new file mode 100644 index 0000000000000000000000000000000000000000..4d83acf3f5e10fc48b82e36b4ffbe54295d1aee6 --- /dev/null +++ b/pool/shard006/C/0119096_brk.c @@ -0,0 +1,47 @@ +/* brk system call for Linux/SH. + Copyright (C) 1999-2017 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, see + . */ + +#include +#include +#include + +/* This must be initialized data because commons can't have aliases. */ +void *__curbrk = 0; + +int +__brk (void *addr) +{ + void *newbrk; + register long r3 asm ("%r3") = SYS_ify (brk); + register long r4 asm ("%r4") = (long)addr; + + asm volatile ("trapa #0x11\n\t" SYSCALL_INST_PAD + : "=z"(newbrk) + : "r" (r3), "r" (r4)); + + __curbrk = newbrk; + + if (newbrk < addr) + { + __set_errno (ENOMEM); + return -1; + } + + return 0; +} +weak_alias (__brk, brk) diff --git a/pool/shard006/C/0119097_globus_xio_ftp_server.c b/pool/shard006/C/0119097_globus_xio_ftp_server.c new file mode 100644 index 0000000000000000000000000000000000000000..f9ce389d6c1268d7a43798da5194f0e7b39b7fa7 --- /dev/null +++ b/pool/shard006/C/0119097_globus_xio_ftp_server.c @@ -0,0 +1,94 @@ +/* + * Copyright 1999-2006 University of Chicago + * + * 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 "globus_xio.h" +#include "globus_xio_tcp_driver.h" + +#define LINE_LEN 1024 + +void +test_res( + globus_result_t res, + int line) +{ + if(res == GLOBUS_SUCCESS) + { + return; + } + + fprintf(stderr, "ERROR @ %d: %s\n", line, globus_error_print_chain( + globus_error_get(res))); + + globus_assert(0); +} + +int +main( + int argc, + char ** argv) +{ + globus_xio_driver_t tcp_driver; + globus_xio_driver_t ftp_driver; + globus_xio_stack_t stack; + globus_xio_handle_t xio_handle; + char * cs; + globus_result_t res; + char line[LINE_LEN]; + globus_bool_t done = GLOBUS_FALSE; + globus_size_t nbytes; + globus_xio_server_t server_handle; + + globus_module_activate(GLOBUS_XIO_MODULE); + globus_xio_stack_init(&stack, NULL); + + res = globus_xio_driver_load("tcp", &tcp_driver); + test_res(res, __LINE__); + res = globus_xio_stack_push_driver(stack, tcp_driver); + test_res(res, __LINE__); + res = globus_xio_driver_load("gssapi_ftp", &ftp_driver); + test_res(res, __LINE__); + res = globus_xio_stack_push_driver(stack, ftp_driver); + test_res(res, __LINE__); + + globus_xio_server_create(&server_handle, NULL, stack); + + globus_xio_server_get_contact_string(server_handle, &cs); + fprintf(stdout, "Contact: %s\n", cs); + + globus_xio_server_accept(&xio_handle, server_handle); + + res = globus_xio_open(xio_handle, NULL, NULL); + test_res(res, __LINE__); + res = globus_xio_write(xio_handle, "220 hello\r\n", strlen("220 hello\r\n"), + strlen("220 hello\r\n"), &nbytes, NULL); + test_res(res, __LINE__); + + while(!done) + { + res = globus_xio_read( + xio_handle, line, LINE_LEN, 1, &nbytes, NULL); + test_res(res, __LINE__); + line[nbytes] = '\0'; + + fprintf(stdout, "%s", line); + } + + globus_xio_close(xio_handle, NULL); + + globus_module_activate(GLOBUS_XIO_MODULE); + + return 0; +} diff --git a/pool/shard006/C/0119098_example13_species.c b/pool/shard006/C/0119098_example13_species.c new file mode 100644 index 0000000000000000000000000000000000000000..f15e7c9b12895e1d8d7cd2d46b76393132b2ac10 --- /dev/null +++ b/pool/shard006/C/0119098_example13_species.c @@ -0,0 +1,77 @@ +// +// This file is part of the Bones source-to-source compiler examples. This C-code +// example is meant to illustrate the use of Bones. For more information on Bones +// use the contact information below. +// +// == More information on Bones +// Contact............Cedric Nugteren +// Web address........http://parse.ele.tue.nl/bones/ +// +// == File information +// Filename...........element/example13.c +// Author.............Cedric Nugteren +// Last modified on...07-May-2013 +// + +#include + +// This is 'example13', an example with multiple loop nests and various if-statements +int main(void) { + int i,j; + int N = 256; + + // Declare input/output arrays + int A[N]; + int B[N]; + int C[N]; + int D[N][N]; + int E[N][N]; + + // Set the input data + for(i=0;i B[11:N-1]|element ^ A[0:5]|element + for (i = 0; i < N; i++) { + if (i > 10) { + B[i] = C[i]; + } + if (i < 6) { + A[i] = C[i]; + } + } + #pragma species endkernel example13_k1 + #pragma species kernel A[50:N-1]|element -> B[50:N-1]|element + for (i = 0; i < N - 9; i++) { + if (i + 10 > 50) { + B[i + 9] = A[i + 9]; + } + } + #pragma species endkernel example13_k2 + #pragma species kernel E[5:N-1,0:N-1]|element -> D[5:N-1,0:N-1]|element + for (i = 0; i < N; i++) { + for (j = 0; j < N; j++) { + if (i > 4) { + D[i][j] = E[i][j]; + } + } + } + #pragma species endkernel example13_k3 + } + #pragma endscop + + // Clean-up and exit the function + fflush(stdout); + return 0; +} + diff --git a/pool/shard006/C/0119102_CoYield.c b/pool/shard006/C/0119102_CoYield.c new file mode 100644 index 0000000000000000000000000000000000000000..2c0d5c209e85c693224348888a51a1f569703c17 --- /dev/null +++ b/pool/shard006/C/0119102_CoYield.c @@ -0,0 +1,121 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015 Matthew J. Runyan +// +// 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 "include/lua.h" +#include "include/lauxlib.h" +#include +#include + +#define DEFAULT_INSTRUCTIONS 100000 +#define MINIMUM_INSTRUCTIONS 1000 // having any less than this likely will cause performance issues because of so much switching + +int justYielded = 0; + +static void CoYield_Yield(lua_State *L, lua_Debug *ar) +{ + justYielded = 1; + lua_yield(L, 0); +} + +static int CoYield_MakeCoYield(lua_State *L) +{ + // get and lua thread (first arg) + luaL_checktype(L, 1, LUA_TTHREAD); + lua_State *L1 = lua_tothread(L, 1); + + // get number of instructions (second arg) + int instructions = DEFAULT_INSTRUCTIONS; + if (lua_gettop(L) >= 2 && !lua_isnil(L, 2)) + { + lua_Number tmp = luaL_checknumber(L, 2); + if (tmp > (lua_Number)INT_MAX) + instructions = INT_MAX; + else if (tmp < (lua_Number)MINIMUM_INSTRUCTIONS) + instructions = MINIMUM_INSTRUCTIONS; + else + instructions = (int)tmp; + } + + lua_sethook(L1, CoYield_Yield, LUA_MASKCOUNT, instructions); + return 0; +} + +static int CoYeild_Resume(lua_State *L) +{ + // same as ( LUA_REGISTRYINDEX["CoYield_lib"][1] )(...) + luaL_checktype(L, 1, LUA_TTHREAD); + lua_getfield(L, LUA_REGISTRYINDEX, "CoYield_lib"); + lua_rawgeti(L, -1, 1); + lua_remove(L, -2); + lua_insert(L, 1); + // run the coroutine (a.k.a. where the magic happens) + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + + // now replace the bool status returned by lua's resume with more descript stuff + if (justYielded) { + justYielded = 0; + lua_pushboolean(L, 0); // coroutine is paused + } else { + lua_pushboolean(L, 1); // coroutine is finished + // remove coroutine error message. it doesn't really matter + if (lua_isstring(L, 2) && strcmp(lua_tolstring(L, 2, NULL), "cannot resume dead coroutine") == 0) + lua_remove(L, 2); + } + lua_replace(L, 1); // replace the first arg with the boolean + + return lua_gettop(L); +} + +static void CoYeild_SaveGlobalLuaCoResumeFunc(lua_State *L) +{ + // same as: LUA_REGISTRYINDEX["CoYield_lib"] = { coroutine.resume } + + // create table in private space + lua_createtable(L, 1, 0); + // get "coroutine.resume" and save this function to the table at position zero + lua_getglobal(L, "coroutine"); + if (!lua_istable(L, -1)) + luaL_error(L, "Global coroutine is not a table."); + lua_getfield(L, -1, "resume"); + if (!lua_iscfunction(L, -1)) + luaL_error(L, "The global \"coroutine.resume\" is not a c function."); + lua_remove(L, -2); + lua_rawseti(L, -2, 1); + // push this table to the private space + lua_setfield(L, LUA_REGISTRYINDEX, "CoYield_lib"); +} + +static const struct luaL_reg CoYield_lib [] = { + {"makeCoYield", CoYield_MakeCoYield}, + {"resume", CoYeild_Resume}, + {NULL, NULL} +}; + +#ifndef __declspec +#define __declspec(a) +#endif +__declspec(dllexport) int luaopen_CoYield (lua_State *L) +{ + CoYeild_SaveGlobalLuaCoResumeFunc(L); + luaL_register(L, "CoYield", CoYield_lib); + return 1; +} diff --git a/pool/shard006/C/0119105_modperl_bucket.c b/pool/shard006/C/0119105_modperl_bucket.c new file mode 100644 index 0000000000000000000000000000000000000000..21b5a974f6d104bfb99c554afc7d965f9f2838b5 --- /dev/null +++ b/pool/shard006/C/0119105_modperl_bucket.c @@ -0,0 +1,159 @@ +/* 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 "mod_perl.h" + +/* + * modperl_bucket_sv code derived from mod_snake's ModSnakePyBucket + * by Jon Travis + */ + +typedef struct { + apr_bucket_refcount refcount; + SV *sv; + PerlInterpreter *perl; +} modperl_bucket_sv_t; + +static apr_status_t +modperl_bucket_sv_read(apr_bucket *bucket, const char **str, + apr_size_t *len, apr_read_type_e block) +{ + modperl_bucket_sv_t *svbucket = bucket->data; + dTHXa(svbucket->perl); + STRLEN svlen; + char *pv = SvPV(svbucket->sv, svlen); + + *str = pv + bucket->start; + *len = bucket->length; + + if (svlen < bucket->start + bucket->length) { + /* XXX log error? */ + return APR_EGENERAL; + } + + return APR_SUCCESS; +} + +static void modperl_bucket_sv_destroy(void *data) +{ + modperl_bucket_sv_t *svbucket = data; + dTHXa(svbucket->perl); + + if (!apr_bucket_shared_destroy(svbucket)) { + MP_TRACE_f(MP_FUNC, "bucket refcnt=%d", + ((apr_bucket_refcount *)svbucket)->refcount); + return; + } + + MP_TRACE_f(MP_FUNC, "sv=0x%lx, refcnt=%d", + (unsigned long)svbucket->sv, SvREFCNT(svbucket->sv)); + + SvREFCNT_dec(svbucket->sv); + + apr_bucket_free(svbucket); +} + +static +apr_status_t modperl_bucket_sv_setaside(apr_bucket *bucket, apr_pool_t *pool) +{ + modperl_bucket_sv_t *svbucket = bucket->data; + dTHXa(svbucket->perl); + STRLEN svlen; + char *pv = SvPV(svbucket->sv, svlen); + + if (svlen < bucket->start + bucket->length) { + /* XXX log error? */ + return APR_EGENERAL; + } + + pv = apr_pstrmemdup(pool, pv + bucket->start, bucket->length); + if (pv == NULL) { + return APR_ENOMEM; + } + + /* changes bucket guts by reference */ + if (apr_bucket_pool_make(bucket, pv, bucket->length, pool) == NULL) { + return APR_ENOMEM; + } + + modperl_bucket_sv_destroy(svbucket); + return APR_SUCCESS; +} + +static const apr_bucket_type_t modperl_bucket_sv_type = { + "mod_perl SV bucket", 4, +#if MODULE_MAGIC_NUMBER >= 20020602 + APR_BUCKET_DATA, +#endif + modperl_bucket_sv_destroy, + modperl_bucket_sv_read, + modperl_bucket_sv_setaside, + apr_bucket_shared_split, + apr_bucket_shared_copy, +}; + +static apr_bucket *modperl_bucket_sv_make(pTHX_ + apr_bucket *bucket, + SV *sv, + apr_off_t offset, + apr_size_t len) +{ + modperl_bucket_sv_t *svbucket; + + svbucket = apr_bucket_alloc(sizeof(*svbucket), bucket->list); + + bucket = apr_bucket_shared_make(bucket, svbucket, offset, len); + if (!bucket) { + apr_bucket_free(svbucket); + return NULL; + } + + /* XXX: need to deal with PerlInterpScope */ +#ifdef USE_ITHREADS + svbucket->perl = aTHX; +#endif + + /* PADTMP SVs belong to perl and can't be stored away, since perl + * is going to reuse them, so we have no choice but to copy the + * data away, before storing sv */ + if (SvPADTMP(sv)) { + STRLEN len; + char *pv = SvPV(sv, len); + svbucket->sv = newSVpvn(pv, len); + } + else { + svbucket->sv = sv; + (void)SvREFCNT_inc(svbucket->sv); + } + + MP_TRACE_f(MP_FUNC, "sv=0x%lx, refcnt=%d", + (unsigned long)svbucket->sv, SvREFCNT(svbucket->sv)); + + bucket->type = &modperl_bucket_sv_type; + return bucket; +} + +apr_bucket *modperl_bucket_sv_create(pTHX_ apr_bucket_alloc_t *list, SV *sv, + apr_off_t offset, apr_size_t len) +{ + apr_bucket *bucket; + + bucket = apr_bucket_alloc(sizeof(*bucket), list); + APR_BUCKET_INIT(bucket); + bucket->list = list; + bucket->free = apr_bucket_free; + return modperl_bucket_sv_make(aTHX_ bucket, sv, offset, len); +} diff --git a/pool/shard006/C/0119107_event_kernel.c b/pool/shard006/C/0119107_event_kernel.c new file mode 100644 index 0000000000000000000000000000000000000000..1690a327c6778e680e8aede34896ff39a02e13ef --- /dev/null +++ b/pool/shard006/C/0119107_event_kernel.c @@ -0,0 +1,93 @@ + +#include "defs.h" +#include "../drivers/irq/mouse.h" +#include "../drivers/irq/keyboard.h" +#include "../drivers/irq/pit.h" + +void event_init(void) { + + +} + +event_list_t event_update(void) { /// TODO + event_list_t event_list = { + .event_count = 0, + + }; + + event_t event = { + .type = __AQUA__EVENT_TYPE_WINDOW, + .window_type = __AQUA__EVENT_QUIT, + + .button = 0, + .released = 0, + + .x = 0, + .y = 0, + + .timestamp = 0, + .clicks = 0, + + .keyboard_detected = 1, + + }; + + uint8_t mp = get_mouse_press(); + uint8_t mr = get_mouse_release(); + + keyboard_detected = 1;//~keyboard_echo(); + event.keyboard_detected = keyboard_detected; + + if (!keyboard_detected) { + printf_warn("Keyboard was not found. It may have been unplugged ...\n"); + + } + + uint8_t kp = get_key_press(); + uint8_t kr = get_key_release(); + + if (mp != 127) { + event.type = __AQUA__EVENT_TYPE_MOUSE; + event.button = mp; + + } else if (mr != 127) { + event.type = __AQUA__EVENT_TYPE_MOUSE; + event.button = mr; + event.released = 1; + + } + + if (mp != 127 || mr != 127) { + event.x = mouse_x; + event.y = mouse_y; + + event.timestamp = pit_uptime; + event.clicks = 1; + + event_list.events[event_list.event_count] = event; + event_list.event_count++; + + } + + if (kp != 127) { + event.type = __AQUA__EVENT_TYPE_KEYBOARD; + event.button = kp; + + } else if (kr != 127) { + event.type = __AQUA__EVENT_TYPE_KEYBOARD; + event.button = kr; + event.released = 1; + + } + + if (kp != 127 || kr != 127) { + event.timestamp = pit_uptime; + + event_list.events[event_list.event_count] = event; + event_list.event_count++; + + } + + return event_list; + +} diff --git a/pool/shard006/C/0119110_cmwc.c b/pool/shard006/C/0119110_cmwc.c new file mode 100644 index 0000000000000000000000000000000000000000..fe3502a012bfb4e589b6af80eeee6902e4caff29 --- /dev/null +++ b/pool/shard006/C/0119110_cmwc.c @@ -0,0 +1,47 @@ +#include +#include +#include + +#define PHY 0x9e3779b9 + +static uint32_t Q[4096], c = 343287; + +void init_cmwc (uint32_t x); +uint32_t rand_cmwc (void); + +void init_cmwc (uint32_t x) { + int i; + + Q[0] = x; + Q[1] = x + (uint32_t)time(NULL) * rand(); + Q[2] = x + (uint32_t)time(NULL) * rand() + (uint32_t)time(NULL) * rand(); + + for (i = 3; i < 4096; i++) { + Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHY ^ i; + } + +/* + for (i = 13; i < 24; i++) { + printf("%zu\n", Q[i]); + } +*/ +} + +uint32_t rand_cmwc (void) { + static uint32_t i = 4096; + uint64_t t; + + i = (i + 1) & 4096; + t = (1875ULL * Q[i]) + c; + c = t >> 32; + Q[i] = 0XFFFFFFFE - t; + + return Q[i]; +} + +int main (void) { + init_cmwc((uint32_t)rand_cmwc); //(uint32_t)time(NULL) + printf("time: %lu\n", (unsigned long)time(NULL)); + + return 0; +} diff --git a/pool/shard006/C/0119111_event.c b/pool/shard006/C/0119111_event.c new file mode 100644 index 0000000000000000000000000000000000000000..c584574d3aced0670a0baa63ec8bdf1650dbce91 --- /dev/null +++ b/pool/shard006/C/0119111_event.c @@ -0,0 +1,89 @@ +#include "event.h" + +#include "assert.h" +#include "atomic.h" +#include "bits.h" +#include "nvic.h" + +void event_queue_init(event_queue_t *que) +{ + ASSERT(que != NULL); + + que->event_id = 0; + que->events = malloc(8 * sizeof(event_t)); + que->n_events = 8; + que->pending = 0; + + memzero(que->events, 8 * sizeof(event_t)); + + signal_init(&que->wait_queue); +} + +event_t * event_queue_create_event(event_queue_t *que) +{ + ASSERT(que != NULL); + + event_t ret = que->event_id++; + if (ret >= que->n_events) { + que->events = realloc(que->events, que->n_events * 2); + memzero(que->events + que->n_events, que->n_events * sizeof(event_t)); + que->n_events *= 2; + } + + return &que->events[ret]; +} + +void event_queue_signal(event_queue_t *que, event_t *evt) +{ + ASSERT(que != NULL && evt != NULL); + + int idx = evt - que->events; + + nvic_disable_int(); + + if (que->events[idx] == 0) { + que->events[idx] = 1; + ++que->pending; + } + + nvic_enable_int(); + + signal_wake_all(&que->wait_queue); +} + +event_t * event_queue_wait(event_queue_t *que) +{ + ASSERT(que != NULL); + + while (1) { + nvic_disable_int(); + if (que->pending == 0) { + signal_enqueue(&que->wait_queue); + nvic_enable_int(); + task_yield(); + } + else { + nvic_enable_int(); + break; + } + } + + event_t *ret; + + for (int i = 0; i < que->event_id; ++i) { + if (que->events[i] > 0) { + nvic_disable_int(); + + --que->pending; + que->events[i] = 0; + + nvic_enable_int(); + + ret = &que->events[i]; + + break; + } + } + + return ret; +} diff --git a/pool/shard006/C/0119114_test_ipconnections_target_with_args.c b/pool/shard006/C/0119114_test_ipconnections_target_with_args.c new file mode 100644 index 0000000000000000000000000000000000000000..ac3a76be044b79dd284117b5c2adec400da9fc37 --- /dev/null +++ b/pool/shard006/C/0119114_test_ipconnections_target_with_args.c @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +void send_tcp(const char *remote, const int port) +{ + int sd = socket(AF_INET, SOCK_STREAM, 0); + assert(sd > 0); + + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = inet_addr(remote); + addr.sin_port = htons(port); + + connect(sd, (struct sockaddr *)&addr , sizeof(addr)); + close(sd); +} + +int main(int argc, char *argv[]) +{ + send_tcp(argv[1], 80); + return 0; +} diff --git a/pool/shard006/C/0119117_sctp-server.c b/pool/shard006/C/0119117_sctp-server.c new file mode 100644 index 0000000000000000000000000000000000000000..87d65e1301e512e487cc2c81ad98a5160df445f3 --- /dev/null +++ b/pool/shard006/C/0119117_sctp-server.c @@ -0,0 +1,70 @@ +/* sctp-server.c + * + * Copyright (C) 2006-2017 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL 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. + * + * wolfSSL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA + */ + + +/* sctp */ +#include +#include +#include + +/* std */ +#include +#include +#include + +int main() +{ + int sd = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP); + + if (sd < 0) + perror("sctp socket error"); + + struct sockaddr_in sa; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = htonl(INADDR_ANY); + sa.sin_port = htons(12345); + + int ret = bind(sd, (struct sockaddr*)&sa, sizeof(sa)); + if (ret < 0) + perror("sctp bind error"); + + listen(sd, 3); + + int client_sd = accept(sd, NULL, NULL); + if (client_sd < 0) + perror("sctp accept error"); + + const char* response = "hi there"; + char buffer[80]; + + int got = (int)recv(client_sd, buffer, sizeof(buffer), 0); + if (got > 0) { + buffer[got] = 0; + printf("client said: %s\n", buffer); + } + send(client_sd, response, strlen(response), 0); + + + close(sd); + + return 0; +} diff --git a/pool/shard006/C/0119127_prm2bits.c b/pool/shard006/C/0119127_prm2bits.c new file mode 100644 index 0000000000000000000000000000000000000000..547b43e260a4f12786ab311cd2f40e49e7c541d6 --- /dev/null +++ b/pool/shard006/C/0119127_prm2bits.c @@ -0,0 +1,116 @@ +/* +******************************************************************************** +* +* 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 : prm2bits.c +* Purpose : Converts the encoder parameter vector into a +* : vector of serial bits. +* +******************************************************************************** +*/ +/* +******************************************************************************** +* MODULE INCLUDE FILE AND VERSION ID +******************************************************************************** +*/ +#include "prm2bits.h" + +/* +******************************************************************************** +* INCLUDE FILES +******************************************************************************** +*/ +#include "codec_op_etsi.h" +#include "mode.h" +#include "cnst.h" + +/* +******************************************************************************** +* LOCAL VARIABLES AND TABLES +******************************************************************************** +*/ +#include "bitno_tab.c" +#define MASK 0x0001 + +/* +******************************************************************************** +* LOCAL PROGRAM CODE +******************************************************************************** +*/ + +/************************************************************************* + * + * FUNCTION: Int2bin + * + * PURPOSE: convert integer to binary and write the bits to the array + * bitstream[]. The most significant bits are written first. + * + *************************************************************************/ + +static void Int2bin ( + Word16 value, /* input : value to be converted to binary */ + Word16 no_of_bits, /* input : number of bits associated with value */ + Word16 *bitstream /* output: address where bits are written */ +) +{ + Word16 *pt_bitstream, i, bit; + + pt_bitstream = &bitstream[no_of_bits]; + + for (i = 0; i < no_of_bits; i++) + { + bit = value & MASK; + + if (bit == 0) + { + *--pt_bitstream = BIT_0; + } + else + { + *--pt_bitstream = BIT_1; + } + value = shr (value, 1); + } +} + +/* +******************************************************************************** +* PUBLIC PROGRAM CODE +******************************************************************************** +*/ +/************************************************************************* + * + * FUNCTION: Prm2bits + * + * PURPOSE: converts the encoder parameter vector into a vector of serial + * bits. + * + * DESCRIPTION: depending on the mode, different numbers of parameters + * (with differing numbers of bits) are processed. Details + * are found in bitno.tab + * + *************************************************************************/ +void Prm2bits ( + enum Mode mode, /* i : AMR mode */ + Word16 prm[], /* i : analysis parameters (size <= MAX_PRM_SIZE) */ + Word16 bits[] /* o : serial bits (size <= MAX_SERIAL_SIZE) */ +) +{ + Word16 i; + + /* account for pointer init (bitno[mode]) */ + + for (i = 0; i < prmno[mode]; i++) + { + Int2bin (prm[i], bitno[mode][i], bits); + bits += bitno[mode][i]; + add(0,0); /* account for above pointer update */ + } + + return; +} diff --git a/pool/shard006/C/0119130_pvscan.c b/pool/shard006/C/0119130_pvscan.c new file mode 100644 index 0000000000000000000000000000000000000000..b24b7ab51b8680bdbd5650a53e467b5bbe5d9ae1 --- /dev/null +++ b/pool/shard006/C/0119130_pvscan.c @@ -0,0 +1,205 @@ +/* + * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. + * Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved. + * + * This file is part of LVM2. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU Lesser General Public License v.2.1. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "tools.h" + +int pv_max_name_len = 0; +int vg_max_name_len = 0; + +static void _pvscan_display_single(struct cmd_context *cmd, + struct physical_volume *pv, + void *handle __attribute__((unused))) +{ + char uuid[64] __attribute__((aligned(8))); + unsigned vg_name_len = 0; + + char pv_tmp_name[NAME_LEN] = { 0, }; + char vg_tmp_name[NAME_LEN] = { 0, }; + char vg_name_this[NAME_LEN] = { 0, }; + + /* short listing? */ + if (arg_count(cmd, short_ARG) > 0) { + log_print("%s", pv_dev_name(pv)); + return; + } + + if (arg_count(cmd, verbose_ARG) > 1) { + /* FIXME As per pv_display! Drop through for now. */ + /* pv_show(pv); */ + + /* FIXME - Moved to Volume Group structure */ + /* log_print("System Id %s", pv->vg->system_id); */ + + /* log_print(" "); */ + /* return; */ + } + + memset(pv_tmp_name, 0, sizeof(pv_tmp_name)); + + vg_name_len = strlen(pv_vg_name(pv)) + 1; + + if (arg_count(cmd, uuid_ARG)) { + if (!id_write_format(&pv->id, uuid, sizeof(uuid))) { + stack; + return; + } + + sprintf(pv_tmp_name, "%-*s with UUID %s", + pv_max_name_len - 2, pv_dev_name(pv), uuid); + } else { + sprintf(pv_tmp_name, "%s", pv_dev_name(pv)); + } + + if (is_orphan(pv)) { + log_print("PV %-*s %-*s %s [%s]", + pv_max_name_len, pv_tmp_name, + vg_max_name_len, " ", + pv->fmt ? pv->fmt->name : " ", + display_size(cmd, pv_size(pv))); + return; + } + + if (pv_status(pv) & EXPORTED_VG) { + strncpy(vg_name_this, pv_vg_name(pv), vg_name_len); + log_print("PV %-*s is in exported VG %s " + "[%s / %s free]", + pv_max_name_len, pv_tmp_name, + vg_name_this, + display_size(cmd, (uint64_t) pv_pe_count(pv) * + pv_pe_size(pv)), + display_size(cmd, (uint64_t) (pv_pe_count(pv) - + pv_pe_alloc_count(pv)) + * pv_pe_size(pv))); + return; + } + + sprintf(vg_tmp_name, "%s", pv_vg_name(pv)); + log_print("PV %-*s VG %-*s %s [%s / %s free]", pv_max_name_len, + pv_tmp_name, vg_max_name_len, vg_tmp_name, + pv->fmt ? pv->fmt->name : " ", + display_size(cmd, (uint64_t) pv_pe_count(pv) * + pv_pe_size(pv)), + display_size(cmd, (uint64_t) (pv_pe_count(pv) - + pv_pe_alloc_count(pv)) * + pv_pe_size(pv))); +} + +int pvscan(struct cmd_context *cmd, int argc __attribute__((unused)), + char **argv __attribute__((unused))) +{ + int new_pvs_found = 0; + int pvs_found = 0; + + struct dm_list *pvslist; + struct pv_list *pvl; + struct physical_volume *pv; + + uint64_t size_total = 0; + uint64_t size_new = 0; + + int len = 0; + pv_max_name_len = 0; + vg_max_name_len = 0; + + if (arg_count(cmd, novolumegroup_ARG) && arg_count(cmd, exported_ARG)) { + log_error("Options -e and -n are incompatible"); + return EINVALID_CMD_LINE; + } + + if (arg_count(cmd, exported_ARG) || arg_count(cmd, novolumegroup_ARG)) + log_warn("WARNING: only considering physical volumes %s", + arg_count(cmd, exported_ARG) ? + "of exported volume group(s)" : "in no volume group"); + + if (!lock_vol(cmd, VG_GLOBAL, LCK_VG_WRITE)) { + log_error("Unable to obtain global lock."); + return ECMD_FAILED; + } + + persistent_filter_wipe(cmd->filter); + lvmcache_destroy(cmd, 1); + + log_verbose("Walking through all physical volumes"); + if (!(pvslist = get_pvs(cmd))) { + unlock_vg(cmd, VG_GLOBAL); + stack; + return ECMD_FAILED; + } + + /* eliminate exported/new if required */ + dm_list_iterate_items(pvl, pvslist) { + pv = pvl->pv; + + if ((arg_count(cmd, exported_ARG) + && !(pv_status(pv) & EXPORTED_VG)) + || (arg_count(cmd, novolumegroup_ARG) && (!is_orphan(pv)))) { + dm_list_del(&pvl->list); + continue; + } + + /* Also check for MD use? */ +/******* + if (MAJOR(pv_create_kdev_t(pv[p]->pv_name)) != MD_MAJOR) { + log_warn + ("WARNING: physical volume \"%s\" belongs to a meta device", + pv[p]->pv_name); + } + if (MAJOR(pv[p]->pv_dev) != MD_MAJOR) + continue; +********/ + pvs_found++; + + if (is_orphan(pv)) { + new_pvs_found++; + size_new += pv_size(pv); + size_total += pv_size(pv); + } else + size_total += (uint64_t) pv_pe_count(pv) * pv_pe_size(pv); + } + + /* find maximum pv name length */ + pv_max_name_len = vg_max_name_len = 0; + dm_list_iterate_items(pvl, pvslist) { + pv = pvl->pv; + len = strlen(pv_dev_name(pv)); + if (pv_max_name_len < len) + pv_max_name_len = len; + len = strlen(pv_vg_name(pv)); + if (vg_max_name_len < len) + vg_max_name_len = len; + } + pv_max_name_len += 2; + vg_max_name_len += 2; + + dm_list_iterate_items(pvl, pvslist) + _pvscan_display_single(cmd, pvl->pv, NULL); + + if (!pvs_found) { + log_print("No matching physical volumes found"); + unlock_vg(cmd, VG_GLOBAL); + return ECMD_PROCESSED; + } + + log_print("Total: %d [%s] / in use: %d [%s] / in no VG: %d [%s]", + pvs_found, + display_size(cmd, size_total), + pvs_found - new_pvs_found, + display_size(cmd, (size_total - size_new)), + new_pvs_found, display_size(cmd, size_new)); + + unlock_vg(cmd, VG_GLOBAL); + + return ECMD_PROCESSED; +} diff --git a/pool/shard006/C/0119131_pl-bag.c b/pool/shard006/C/0119131_pl-bag.c new file mode 100644 index 0000000000000000000000000000000000000000..f362b18acfc9ccdfe826cc3c327d6fb94acd2c93 --- /dev/null +++ b/pool/shard006/C/0119131_pl-bag.c @@ -0,0 +1,157 @@ +/* $Id: pl-bag.c,v 1.25 2001/06/14 08:21:56 jan Exp $ + + Part of SWI-Prolog + + Author: Jan Wielemaker + E-mail: jan@swi.psy.uva.nl + WWW: http://www.swi.psy.uva.nl/projects/SWI-Prolog/ + Copying: GPL-2. See the file COPYING or http://www.gnu.org + + Copyright (C) 1990-2000 SWI, University of Amsterdam. All rights reserved. +*/ + +/*#define O_SECURE 1*/ +#include "pl-incl.h" + +#undef LD +#define LD LOCAL_LD + +/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +This module defines support predicates for the Prolog all-solutions +predicates findall/3, bagof/3 and setof/3. These predicates are: + + $record_bag(Key, Value) Record a value under a key. + $collect_bag(Bindings, Values) Retract all Solutions matching + Bindings. + +The (toplevel) remainder of the all-solutions predicates is written in +Prolog. +- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + +#define alist LD->bags.bags /* Each thread has its own */ + /* storage for this */ + +typedef struct assoc +{ Record record; + struct assoc *next; +} *Assoc; + + +static void +freeAssoc(Assoc prev, Assoc a) +{ if ( prev == NULL ) + { GET_LD + alist = a->next; + } else + prev->next = a->next; + + if ( a->record ) + freeRecord(a->record); + + freeHeap(a, sizeof(*a)); +} + +/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +$record_bag(Key-Value) + +Record a solution of bagof. Key is a term v(V0, ...Vn), holding the +variable binding for solution `Gen'. Key is ATOM_mark for the mark. +- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + +word +pl_record_bag(term_t t) +{ GET_LD + Assoc a = allocHeap(sizeof(*a)); + + if ( PL_is_atom(t) ) + { a->record = 0; + } else + a->record = compileTermToHeap(t, 0); + + a->next = alist; + alist = a; + + succeed; +} + +/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +This predicate will fail if no more records are left before the mark. +- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + +word +pl_collect_bag(term_t bindings, term_t bag) +{ GET_LD + term_t var_term = PL_new_term_ref(); /* v() term on global stack */ + term_t list = PL_new_term_ref(); /* list to construct */ + term_t binding = PL_new_term_ref(); /* current binding */ + term_t tmp = PL_new_term_ref(); + Assoc a, next; + Assoc prev = NULL; + + if ( !(a = alist) ) + fail; + if ( !a->record ) + { freeAssoc(prev, a); + fail; /* trapped the mark */ + } + + PL_put_nil(list); + /* get variable term on global stack */ + copyRecordToGlobal(binding, a->record PASS_LD); + PL_get_arg(1, binding, var_term); + PL_unify(bindings, var_term); + PL_get_arg(2, binding, tmp); + PL_cons_list(list, tmp, list); + + next = a->next; + freeAssoc(prev, a); + + if ( next != NULL ) + { for( a = next, next = a->next; next; a = next, next = a->next ) + { if ( !a->record ) + break; + + if ( !structuralEqualArg1OfRecord(var_term, a->record PASS_LD) ) + { prev = a; + continue; + } + + copyRecordToGlobal(binding, a->record PASS_LD); + PL_get_arg(1, binding, tmp); + PL_unify(tmp, bindings); + PL_get_arg(2, binding, tmp); + PL_cons_list(list, tmp, list); + SECURE(checkData(valTermRef(list))); + freeAssoc(prev, a); + } + } + + SECURE(checkData(valTermRef(var_term))); + + return PL_unify(bag, list); +} + + +/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +An exception was generated during the execution of the generator of +findall/3, bagof/3 or setof/3. Reclaim all records and re-throw the +exception. +- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ + +foreign_t +pl_except_bag(term_t ex) +{ GET_LD + Assoc a, next; + + for( a=alist; a; a = next ) + { if ( a->record ) + { freeRecord(a->record); + next = a->next; + } else + next = NULL; + + freeHeap(a, sizeof(*a)); + } + + return PL_raise_exception(ex); +} diff --git a/pool/shard006/C/0119134_null_dvfs.c b/pool/shard006/C/0119134_null_dvfs.c new file mode 100644 index 0000000000000000000000000000000000000000..892086a9440f03acc77de7e62a7f71b44ca3189e --- /dev/null +++ b/pool/shard006/C/0119134_null_dvfs.c @@ -0,0 +1,60 @@ +/** + * @file + * @brief Creates /dev/null + * @author Denis Deryugin + * @version 0.1 + * @date 2015-10-05 + */ +#include +#include +#include + +#include + +#include +#include + +#define NULL_DEV_NAME "null" + +/* forward declaration */ +static struct idesc_ops idesc_cdev_null_ops; +static struct file_operations null_ops; + +static struct idesc *null_open(struct inode *node, struct idesc *idesc) { + struct file *file; + + file = dvfs_alloc_file(); + if (!file) { + return err_ptr(ENOMEM); + } + *file = (struct file) { + .f_idesc = { + .idesc_ops = &idesc_cdev_null_ops, + }, + }; + return &file->f_idesc; +} + +static void null_close(struct idesc *desc) { + dvfs_destroy_file((struct file *)desc); +} + +static ssize_t null_write(struct idesc *desc, const void *buf, size_t size) { + return size; +} + +static ssize_t null_read(struct idesc *desc, void *buf, size_t size) { + return 0; +} + +static struct file_operations null_ops = { + .open = null_open, +}; + +static struct idesc_ops idesc_cdev_null_ops = { + .close = null_close, + .read = null_read, + .write = null_write, +}; + +CHAR_DEV_DEF(NULL_DEV_NAME, &null_ops, &idesc_cdev_null_ops, NULL); diff --git a/pool/shard006/C/0119138_strtok.c b/pool/shard006/C/0119138_strtok.c new file mode 100644 index 0000000000000000000000000000000000000000..08806500c60a9aa82b6ce4a41a4c17bdabdc9ce5 --- /dev/null +++ b/pool/shard006/C/0119138_strtok.c @@ -0,0 +1,108 @@ +/*__________________________________________________________________________ + + strtok á strtok c-string function wrapper + + Copyright (C) 2003 jan schacher + + 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 + + initial build 20030507 + +____________________________________________________________________________*/ + +#include "m_pd.h" +#include + + +typedef struct strtok +{ + t_object ob; + void *s_outlet; + char s_tempstring[4096]; +} t_strtok; + +void *strtok_class; +void *strtok_new(t_symbol *s, long argc, t_atom *argv); +void strtok_free(t_strtok *x); +//void strtok_assist(t_strtok *x, void *b, long msg, long arg, char *dst); +void strtok_anything(t_strtok *x, t_symbol *s, long argc, t_atom *argv); +void strtok_set(t_strtok *x, t_symbol *s, long argc, t_atom *argv); + +void strtok_setup(void) +{ + strtok_class = class_new(gensym("strtok"), (t_newmethod)strtok_new, + (t_method)strtok_free, sizeof(t_strtok), 0, A_GIMME, 0); + class_addsymbol(strtok_class, (t_method)strtok_anything); + class_addmethod(strtok_class, (t_method)strtok_set, gensym("set"), A_GIMME, 0); + post(". strtok . jasch . "__DATE__" ",0); + + +} + +void *strtok_new(t_symbol *s, long argc, t_atom *argv) +{ + t_strtok *x; + x = (t_strtok *)pd_new(strtok_class); + x->s_outlet = outlet_new(&x->ob, gensym("list")); + if((argc >= 1)&&(argv[0].a_type == A_SYMBOL)){ + strcpy(x->s_tempstring, argv[0].a_w.w_symbol->s_name); + // post("argument is %s", argv[0].a_w.w_symbol->s_name); + }else{ + strcpy(x->s_tempstring, "/"); + // post("defualt-argument is %s", x->s_tempstring); + } + return (x); +} + +void strtok_anything(t_strtok *x, t_symbol *s, long argc, t_atom *argv) +{ + char *ptr; + char local[4096]; + long status = 0; + short i, j; + t_atom result[256]; + t_atom head; + i = 0; + + strcpy(local, s->s_name); + ptr = strtok(local,x->s_tempstring); + while (ptr != NULL){ + result[i].a_type = A_SYMBOL; + result[i].a_w.w_symbol = gensym(ptr); + ptr = strtok (NULL, x->s_tempstring); + i++; + } + j = i; + head.a_w.w_symbol = result[0].a_w.w_symbol; + for(j=0;js_outlet,head.a_w.w_symbol,i-1,result); + return; +} + +void strtok_set(t_strtok *x, t_symbol *s, long argc, t_atom *argv) +{ + switch (argv[0].a_type) { + case A_FLOAT: error("wrong argument type for set");break; + // case A_LONG:error("wrong argument type for set"); break; + case A_SYMBOL: strcpy(x->s_tempstring, argv[0].a_w.w_symbol->s_name); break; + } +} + +void strtok_free(t_strtok *x) +{ + // notify_free((t_object *)x); +} + + diff --git a/pool/shard006/C/0119139_test_thread_dispatcher.c b/pool/shard006/C/0119139_test_thread_dispatcher.c new file mode 100644 index 0000000000000000000000000000000000000000..cb6006b0376ccb7da6c3321b9c5a69ddad59c2ea --- /dev/null +++ b/pool/shard006/C/0119139_test_thread_dispatcher.c @@ -0,0 +1,168 @@ +#include "config.h" +#undef NDEBUG +#include + +#include +#include +#include +#include +#include "oe_common.h" +#include "Oe_Thread_Dispatcher.h" +#include "Oec_Future.h" +#include "Oec_CountdownLatch.h" + +Arena_T arena; + +Oe_Thread_Dispatcher dispatcher; +Oec_CountdownLatch latch; + +void decrement_latch(void *dummy) { + sleep(1);//sleep 1000 milliseconds + Oec_CountdownLatch_decrement(latch); +} + +Oec_Future future_name; +void set_my_name_in_the_future(void *name) { + sleep(1);//sleep 1000 milliseconds + Oec_Future_set(future_name, name); +} +char *say_my_name_in_the_future(void) { + char *res; + res = Oec_Future_get(future_name, 3500); + return res; +} + +char * makeString(char *str) { + char *name_stor; + name_stor = Arena_calloc(arena, 1, strlen(str) + 1, __FILE__, __LINE__); + strcpy(name_stor, str); + return name_stor; +} + +bool say_my_name_ran_fast = false; +int say_my_name_count_fast = 0; +void say_my_name_fast(void *name) { + //oe_log(NULL, "my name is %s. my tid is %ld\n", name, pthread_self() ); + say_my_name_ran_fast = true; + say_my_name_count_fast++; + //usleep(2); +} + +bool say_my_name_ran = false; +int say_my_name_count = 0; +void say_my_name(void *name) { + //oe_log(NULL, "my name is %s. my tid is %ld\n", name, pthread_self() ); + say_my_name_ran = true; + say_my_name_count++; + usleep(1000 * 2 * 2); +} + +void test_dispatcher_init(void) { + dispatcher = Oe_Thread_Dispatcher_new(1); + assert(dispatcher); + Oe_Thread_Dispatcher_start(dispatcher); +} + +void test_dispatcher_test1(void) { + + int ITER = 8; + + oe_time start = oec_get_time_milliseconds(); + for (int i = 0; i < ITER; i++) { + Oe_Thread_Dispatcher_exec(dispatcher, say_my_name, makeString("martha")); + } + usleep(1000 * 2 * 100); + oe_time stop = oec_get_time_milliseconds(); + oe_time dur = stop - start; + OE_ILOG(NULL, "thread dispatcher t1 dur: %lld size: %d\n", dur, say_my_name_count); + assert( say_my_name_ran ); + assert( say_my_name_count == ITER); +} + +void test_dispatcher_test2(void) { + + int ITER = 8000; + + oe_time start = oec_get_time_milliseconds(); + for (int i = 0; i < ITER; i++) { + Oe_Thread_Dispatcher_exec(dispatcher, say_my_name_fast, makeString("mary")); + } + usleep(1000 * 100 * 10); + oe_time stop = oec_get_time_milliseconds(); + oe_time dur = stop - start; + OE_ILOG(NULL, "thread dispatcher t2 dur: %lld size: %d\n", dur, say_my_name_count_fast); + assert( say_my_name_ran_fast ); + assert( say_my_name_count_fast == ITER); +} + +void test_futures(void) { + + char *name = makeString("jen the hen"); + char *res; + + oe_time start = oec_get_time_milliseconds(); + Oe_Thread_Dispatcher_exec( dispatcher, set_my_name_in_the_future, name ); + + res = say_my_name_in_the_future(); + oe_time now = oec_get_time_milliseconds(); + oe_time dur = now - start; + printf("test_futures dur: %lld\n", dur); + assert( res ); + assert( res == name); + assert( dur >= 1000 ); //there is a sleep of 1 sec in the set... impl +} + +void test_countdown_latch(void) { + + + Oec_CountdownLatch_increment(latch); + Oec_CountdownLatch_increment(latch); + int c = Oec_CountdownLatch_increment(latch); + //printf("latch size: %d\n", c); + assert(c == 3); + + c = Oec_CountdownLatch_get(latch, 1000); + assert(c <= 0); //1 means success, this test should fail since we have not decremented latch + + oe_time start = oec_get_time_milliseconds(); + Oe_Thread_Dispatcher_exec( dispatcher, decrement_latch, NULL ); + Oe_Thread_Dispatcher_exec( dispatcher, decrement_latch, NULL ); + Oe_Thread_Dispatcher_exec( dispatcher, decrement_latch, NULL ); + + c = Oec_CountdownLatch_get(latch, OEC_FOREVER); + assert(c == 1); + oe_time now = oec_get_time_milliseconds(); + oe_time dur = now - start; + //printf("test_countdown dur: %lld\n", dur); + assert( dur >= 500 ); +} + +void test_dispatcher_stop(void) { + Oe_Thread_Dispatcher_stop(dispatcher); + Oe_Thread_Dispatcher_free(&dispatcher); +} + +//suite +int main(void) { + + arena = Arena_new(); + + future_name = Oec_Future_new(); + latch = Oec_CountdownLatch_new(); + + test_dispatcher_init(); + + test_dispatcher_test1(); + test_dispatcher_test2(); + test_futures(); + test_countdown_latch(); + + test_dispatcher_stop(); + + Arena_free(arena); + Arena_dispose(&arena); + Oec_Future_free(&future_name); + + return 0; +} + diff --git a/pool/shard006/C/0119140_amd_info.c b/pool/shard006/C/0119140_amd_info.c new file mode 100644 index 0000000000000000000000000000000000000000..062651f496760c082f33491b8976c130c6f0b6f9 --- /dev/null +++ b/pool/shard006/C/0119140_amd_info.c @@ -0,0 +1,119 @@ +/* ========================================================================= */ +/* === AMD_info ============================================================ */ +/* ========================================================================= */ + +/* ------------------------------------------------------------------------- */ +/* AMD, Copyright (c) Timothy A. Davis, */ +/* Patrick R. Amestoy, and Iain S. Duff. See ../README.txt for License. */ +/* email: DrTimothyAldenDavis@gmail.com */ +/* ------------------------------------------------------------------------- */ + +/* User-callable. Prints the output statistics for AMD. See amd.h + * for details. If the Info array is not present, nothing is printed. + */ + +#include "amd_internal.h" + +#define PRI(format,x) { if (x >= 0) { SUITESPARSE_PRINTF ((format, x)) ; }} + +GLOBAL void AMD_info +( + double Info [ ] +) +{ + double n, ndiv, nmultsubs_ldl, nmultsubs_lu, lnz, lnzd ; + + SUITESPARSE_PRINTF (("\nAMD version %d.%d.%d, %s, results:\n", + AMD_MAIN_VERSION, AMD_SUB_VERSION, AMD_SUBSUB_VERSION, AMD_DATE)) ; + + if (!Info) + { + return ; + } + + n = Info [AMD_N] ; + ndiv = Info [AMD_NDIV] ; + nmultsubs_ldl = Info [AMD_NMULTSUBS_LDL] ; + nmultsubs_lu = Info [AMD_NMULTSUBS_LU] ; + lnz = Info [AMD_LNZ] ; + lnzd = (n >= 0 && lnz >= 0) ? (n + lnz) : (-1) ; + + /* AMD return status */ + SUITESPARSE_PRINTF ((" status: ")) ; + if (Info [AMD_STATUS] == AMD_OK) + { + SUITESPARSE_PRINTF (("OK\n")) ; + } + else if (Info [AMD_STATUS] == AMD_OUT_OF_MEMORY) + { + SUITESPARSE_PRINTF (("out of memory\n")) ; + } + else if (Info [AMD_STATUS] == AMD_INVALID) + { + SUITESPARSE_PRINTF (("invalid matrix\n")) ; + } + else if (Info [AMD_STATUS] == AMD_OK_BUT_JUMBLED) + { + SUITESPARSE_PRINTF (("OK, but jumbled\n")) ; + } + else + { + SUITESPARSE_PRINTF (("unknown\n")) ; + } + + /* statistics about the input matrix */ + PRI (" n, dimension of A: %.20g\n", n); + PRI (" nz, number of nonzeros in A: %.20g\n", + Info [AMD_NZ]) ; + PRI (" symmetry of A: %.4f\n", + Info [AMD_SYMMETRY]) ; + PRI (" number of nonzeros on diagonal: %.20g\n", + Info [AMD_NZDIAG]) ; + PRI (" nonzeros in pattern of A+A' (excl. diagonal): %.20g\n", + Info [AMD_NZ_A_PLUS_AT]) ; + PRI (" # dense rows/columns of A+A': %.20g\n", + Info [AMD_NDENSE]) ; + + /* statistics about AMD's behavior */ + PRI (" memory used, in bytes: %.20g\n", + Info [AMD_MEMORY]) ; + PRI (" # of memory compactions: %.20g\n", + Info [AMD_NCMPA]) ; + + /* statistics about the ordering quality */ + SUITESPARSE_PRINTF (("\n" + " The following approximate statistics are for a subsequent\n" + " factorization of A(P,P) + A(P,P)'. They are slight upper\n" + " bounds if there are no dense rows/columns in A+A', and become\n" + " looser if dense rows/columns exist.\n\n")) ; + + PRI (" nonzeros in L (excluding diagonal): %.20g\n", + lnz) ; + PRI (" nonzeros in L (including diagonal): %.20g\n", + lnzd) ; + PRI (" # divide operations for LDL' or LU: %.20g\n", + ndiv) ; + PRI (" # multiply-subtract operations for LDL': %.20g\n", + nmultsubs_ldl) ; + PRI (" # multiply-subtract operations for LU: %.20g\n", + nmultsubs_lu) ; + PRI (" max nz. in any column of L (incl. diagonal): %.20g\n", + Info [AMD_DMAX]) ; + + /* total flop counts for various factorizations */ + + if (n >= 0 && ndiv >= 0 && nmultsubs_ldl >= 0 && nmultsubs_lu >= 0) + { + SUITESPARSE_PRINTF (("\n" + " chol flop count for real A, sqrt counted as 1 flop: %.20g\n" + " LDL' flop count for real A: %.20g\n" + " LDL' flop count for complex A: %.20g\n" + " LU flop count for real A (with no pivoting): %.20g\n" + " LU flop count for complex A (with no pivoting): %.20g\n\n", + n + ndiv + 2*nmultsubs_ldl, + ndiv + 2*nmultsubs_ldl, + 9*ndiv + 8*nmultsubs_ldl, + ndiv + 2*nmultsubs_lu, + 9*ndiv + 8*nmultsubs_lu)) ; + } +} diff --git a/pool/shard006/C/0119143_ptrack.c b/pool/shard006/C/0119143_ptrack.c new file mode 100644 index 0000000000000000000000000000000000000000..a1c3dc311884ce31a667583c9fa2e8327e68733f --- /dev/null +++ b/pool/shard006/C/0119143_ptrack.c @@ -0,0 +1,65 @@ +#include "plumber.h" + +int sporth_ptrack(sporth_stack *stack, void *ud) +{ + plumber_data *pd = ud; + SPFLOAT in; + SPFLOAT freq; + SPFLOAT amp; + int ihopsize; + int ipeaks; + sp_ptrack *ptrack; + + switch(pd->mode) { + case PLUMBER_CREATE: + +#ifdef DEBUG_MODE + fprintf(stderr, "ptrack: Creating\n"); +#endif + + sp_ptrack_create(&ptrack); + plumber_add_ugen(pd, SPORTH_PTRACK, ptrack); + if(sporth_check_args(stack, "fff") != SPORTH_OK) { + fprintf(stderr,"Not enough arguments for ptrack\n"); + stack->error++; + return PLUMBER_NOTOK; + } + ihopsize = sporth_stack_pop_float(stack); + ipeaks = sporth_stack_pop_float(stack); + in = sporth_stack_pop_float(stack); + sporth_stack_push_float(stack, 0); + sporth_stack_push_float(stack, 0); + break; + case PLUMBER_INIT: + +#ifdef DEBUG_MODE + fprintf(stderr, "ptrack: Initialising\n"); +#endif + + ihopsize = sporth_stack_pop_float(stack); + ipeaks = sporth_stack_pop_float(stack); + in = sporth_stack_pop_float(stack); + ptrack = pd->last->ud; + sp_ptrack_init(pd->sp, ptrack, ihopsize, ipeaks); + sporth_stack_push_float(stack, 0); + sporth_stack_push_float(stack, 0); + break; + case PLUMBER_COMPUTE: + ihopsize = sporth_stack_pop_float(stack); + ipeaks = sporth_stack_pop_float(stack); + in = sporth_stack_pop_float(stack); + ptrack = pd->last->ud; + sp_ptrack_compute(pd->sp, ptrack, &in, &freq, &); + sporth_stack_push_float(stack, freq); + sporth_stack_push_float(stack, amp); + break; + case PLUMBER_DESTROY: + ptrack = pd->last->ud; + sp_ptrack_destroy(&ptrack); + break; + default: + fprintf(stderr, "ptrack: Unknown mode!\n"); + break; + } + return PLUMBER_OK; +} diff --git a/pool/shard006/C/0119145_clone05.c b/pool/shard006/C/0119145_clone05.c new file mode 100644 index 0000000000000000000000000000000000000000..f5577871e1fb52ff110fccdb824c9d09ef59e30c --- /dev/null +++ b/pool/shard006/C/0119145_clone05.c @@ -0,0 +1,175 @@ +/* + * Copyright (c) Wipro Technologies Ltd, 2002. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it would be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ +/********************************************************** + * + * TEST IDENTIFIER : clone05 + * + * EXECUTED BY : anyone + * + * TEST TITLE : test for CLONE_VFORK flag + * + * TEST CASE TOTAL : 1 + * + * AUTHOR : Saji Kumar.V.R + * + * SIGNALS + * Uses SIGUSR1 to pause before test if option set. + * (See the parse_opts(3) man page). + * + * DESCRIPTION + * Call clone() with CLONE_VFORK flag set. verify that + * execution of parent is suspended until child finishes + * + * Setup: + * Setup signal handling. + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call with CLONE_VM & CLONE_VFORK flags + * + * CHILD: + * sleeps for a second, changes parent_variable to 1 + * PARENT: + * If return code is not -1 and parent_variable == 1 + * test passed + * else + * test failed + * Cleanup: + * Print errno log and/or timing stats if options given + * + * USAGE: + * clone05 [-c n] [-e] [-i n] [-I x] [-P x] [-t] [-h] [-f] [-p] + * where, -c n : Run n copies concurrently. + * -e : Turn on errno logging. + * -h : Show help screen + * -f : Turn off functional testing + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -p : Pause for SIGUSR1 before starting + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + ****************************************************************/ + +#if defined UCLINUX && !__THROW +/* workaround for libc bug */ +#define __THROW +#endif + +#define _GNU_SOURCE + +#include +#include +#include +#include "test.h" +#include "usctest.h" +#include "clone_platform.h" + +#define FLAG CLONE_VM | CLONE_VFORK + +static void setup(); +static void cleanup(); +static int child_fn(); + +static int parent_variable = 0; + +char *TCID = "clone05"; /* Test program identifier. */ +int TST_TOTAL = 1; /* Total number of test cases. */ + +int main(int ac, char **av) +{ + + int lc; + char *msg; + void *child_stack; /* stack for child */ + + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + setup(); + + /* Allocate stack for child */ + if ((child_stack = (void *)malloc(CHILD_STACK_SIZE)) == NULL) { + tst_brkm(TBROK, cleanup, "Cannot allocate stack for child"); + } + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + Tst_count = 0; + + /* + * Call clone(2) + */ + TEST(ltp_clone(FLAG, child_fn, NULL, CHILD_STACK_SIZE, + child_stack)); + + /* check return code & parent_variable */ + if ((TEST_RETURN != -1) && (parent_variable)) { + tst_resm(TPASS, "Test Passed"); + } else { + tst_resm(TFAIL, "Test Failed"); + } + + /* Reset parent_variable */ + parent_variable = 0; + } + + free(child_stack); + + cleanup(); + tst_exit(); + +} + +/* setup() - performs all ONE TIME setup for this test */ +void setup() +{ + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + +} + +/* + *cleanup() - performs all ONE TIME cleanup for this test at + * completion or premature exit. + */ +void cleanup() +{ + + /* + * print timing stats if that option was specified. + * print errno log if that option was specified. + */ + TEST_CLEANUP; + +} + +/* + * do_child() - function executed by child + */ +int child_fn() +{ + /* + * Sleep for a second, to ensure that child does not exit + * immediately + */ + sleep(1); + parent_variable = 1; + exit(1); +} diff --git a/pool/shard006/C/0119148_rtpdec_vc2hq.c b/pool/shard006/C/0119148_rtpdec_vc2hq.c new file mode 100644 index 0000000000000000000000000000000000000000..62da59a516ca2f4a511a95f1cf91cf9cf4de14d6 --- /dev/null +++ b/pool/shard006/C/0119148_rtpdec_vc2hq.c @@ -0,0 +1,225 @@ +/* + * RTP parser for VC-2 HQ payload format (draft version 1) - experimental + * Copyright (c) 2016 Thomas Volkert + * + * 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/intreadwrite.h" +#include "libavcodec/dirac.h" + +#include "avio_internal.h" +#include "rtpdec_formats.h" + +#define RTP_VC2HQ_PL_HEADER_SIZE 4 + +#define DIRAC_DATA_UNIT_HEADER_SIZE 13 +#define DIRAC_PIC_NR_SIZE 4 +#define DIRAC_RTP_PCODE_HQ_PIC_FRAGMENT 0xEC + +struct PayloadContext { + AVIOContext *buf; + uint32_t frame_size; + uint32_t frame_nr; + uint32_t timestamp; + uint32_t last_unit_size; + int seen_sequence_header; +}; + +static const uint8_t start_sequence[] = { 'B', 'B', 'C', 'D' }; + +static void fill_parse_info_header(PayloadContext *pl_ctx, uint8_t *buf, + uint8_t parse_code, uint32_t data_unit_size) +{ + memcpy(buf, start_sequence, sizeof(start_sequence)); + buf[4] = parse_code; + AV_WB32(&buf[5], data_unit_size); + AV_WB32(&buf[9], pl_ctx->last_unit_size); + + pl_ctx->last_unit_size = data_unit_size; +} + +static int vc2hq_handle_sequence_header(PayloadContext *pl_ctx, AVStream *st, AVPacket *pkt, + const uint8_t *buf, int len) +{ + int res; + uint32_t size = DIRAC_DATA_UNIT_HEADER_SIZE + len; + + if ((res = av_new_packet(pkt, DIRAC_DATA_UNIT_HEADER_SIZE + len)) < 0) + return res; + + fill_parse_info_header(pl_ctx, pkt->data, 0x00, size); + /* payload of seq. header */ + memcpy(pkt->data + DIRAC_DATA_UNIT_HEADER_SIZE, buf, len); + pkt->stream_index = st->index; + + pl_ctx->seen_sequence_header = 1; + + return 0; +} + +static int vc2hq_mark_end_of_sequence(PayloadContext *pl_ctx, AVStream *st, AVPacket *pkt) +{ + int res; + uint32_t size = 0; + + /* create A/V packet */ + if ((res = av_new_packet(pkt, DIRAC_DATA_UNIT_HEADER_SIZE)) < 0) + return res; + + fill_parse_info_header(pl_ctx, pkt->data, 0x10, size); + pkt->stream_index = st->index; + + pl_ctx->seen_sequence_header = 0; + + return 0; +} + +static int vc2hq_handle_frame_fragment(AVFormatContext *ctx, PayloadContext *pl_ctx, AVStream *st, + AVPacket *pkt, uint32_t *timestamp, const uint8_t *buf, int len, + int flags) +{ + int res; + uint32_t pic_nr; + uint16_t frag_len; + uint16_t no_slices; + + /* sanity check for size of input packet: 16 bytes header in any case as minimum */ + if (len < 16) { + av_log(ctx, AV_LOG_ERROR, "Too short RTP/VC2hq packet, got %d bytes\n", len); + return AVERROR_INVALIDDATA; + } + + pic_nr = AV_RB32(&buf[4]); + frag_len = AV_RB16(&buf[12]); + no_slices = AV_RB16(&buf[14]); + + if (pl_ctx->buf && pl_ctx->frame_nr != pic_nr) { + av_log(ctx, AV_LOG_WARNING, "Dropping buffered RTP/VC2hq packet fragments - non-continuous picture numbers\n"); + ffio_free_dyn_buf(&pl_ctx->buf); + } + + /* transform parameters? */ + if (no_slices == 0) { + if (len < frag_len + 16) { + av_log(ctx, AV_LOG_ERROR, "Too short RTP/VC2hq packet, got %d bytes\n", len); + return AVERROR_INVALIDDATA; + } + + /* start frame buffering with new dynamic buffer */ + if (!pl_ctx->buf) { + + res = avio_open_dyn_buf(&pl_ctx->buf); + if (res < 0) + return res; + + /* reserve memory for frame header */ + res = avio_seek(pl_ctx->buf, DIRAC_DATA_UNIT_HEADER_SIZE + DIRAC_PIC_NR_SIZE, SEEK_SET); + if (res < 0) + return res; + + pl_ctx->frame_nr = pic_nr; + pl_ctx->timestamp = *timestamp; + pl_ctx->frame_size = DIRAC_DATA_UNIT_HEADER_SIZE + DIRAC_PIC_NR_SIZE; + } + + avio_write(pl_ctx->buf, buf + 16 /* skip pl header */, frag_len); + pl_ctx->frame_size += frag_len; + + return AVERROR(EAGAIN); + } else { + if (len < frag_len + 20) { + av_log(ctx, AV_LOG_ERROR, "Too short RTP/VC2hq packet, got %d bytes\n", len); + return AVERROR_INVALIDDATA; + } + + /* transform parameters were missed, no buffer available */ + if (!pl_ctx->buf) + return AVERROR_INVALIDDATA; + + avio_write(pl_ctx->buf, buf + 20 /* skip pl header */, frag_len); + pl_ctx->frame_size += frag_len; + + /* RTP marker bit means: last fragment of current frame was received; + otherwise, an additional fragment is needed for the current frame */ + if (!(flags & RTP_FLAG_MARKER)) + return AVERROR(EAGAIN); + } + + /* close frame buffering and create A/V packet */ + res = ff_rtp_finalize_packet(pkt, &pl_ctx->buf, st->index); + if (res < 0) + return res; + + fill_parse_info_header(pl_ctx, pkt->data, 0xE8, pl_ctx->frame_size); + AV_WB32(&pkt->data[13], pl_ctx->frame_nr); + + pl_ctx->frame_size = 0; + + return 0; +} + +static int vc2hq_handle_packet(AVFormatContext *ctx, PayloadContext *pl_ctx, + AVStream *st, AVPacket *pkt, uint32_t *timestamp, + const uint8_t *buf, int len, uint16_t seq, + int flags) +{ + uint8_t parse_code = 0; + int res = 0; + + if (pl_ctx->buf && pl_ctx->timestamp != *timestamp) { + av_log(ctx, AV_LOG_WARNING, "Dropping buffered RTP/VC2hq packet fragments - non-continuous timestamps\n"); + ffio_free_dyn_buf(&pl_ctx->buf); + pl_ctx->frame_size = 0; + } + + /* sanity check for size of input packet: needed header data as minimum */ + if (len < RTP_VC2HQ_PL_HEADER_SIZE) { + av_log(ctx, AV_LOG_ERROR, "Too short RTP/VC2hq packet, got %d bytes\n", len); + return AVERROR_INVALIDDATA; + } + + parse_code = buf[3]; + + /* wait for next sequence header? */ + if (pl_ctx->seen_sequence_header || parse_code == DIRAC_PCODE_SEQ_HEADER) { + switch(parse_code) { + /* sequence header */ + case DIRAC_PCODE_SEQ_HEADER: + res = vc2hq_handle_sequence_header(pl_ctx, st, pkt, buf + RTP_VC2HQ_PL_HEADER_SIZE, len - RTP_VC2HQ_PL_HEADER_SIZE); + break; + /* end of sequence */ + case DIRAC_PCODE_END_SEQ: + res = vc2hq_mark_end_of_sequence(pl_ctx, st, pkt); + break; + /* HQ picture fragment */ + case DIRAC_RTP_PCODE_HQ_PIC_FRAGMENT: + res = vc2hq_handle_frame_fragment(ctx, pl_ctx, st, pkt, timestamp, buf, len, flags); + break; + } + } + + return res; +} + +RTPDynamicProtocolHandler ff_vc2hq_dynamic_handler = { + .enc_name = "VC2", + .codec_type = AVMEDIA_TYPE_VIDEO, + .codec_id = AV_CODEC_ID_DIRAC, + .priv_data_size = sizeof(PayloadContext), + .parse_packet = vc2hq_handle_packet +}; diff --git a/pool/shard006/C/0119157_AKTdln.c b/pool/shard006/C/0119157_AKTdln.c new file mode 100644 index 0000000000000000000000000000000000000000..178e7a439205c2f1bf33fc31594b0ea8bd624296 --- /dev/null +++ b/pool/shard006/C/0119157_AKTdln.c @@ -0,0 +1,174 @@ +/*D*********************************************************** + * Name: AKTdln.c + * + * Modul: AKT base moduls + * Handle DLN reisenden functions + * + * Copyright: yafra.org, Basel, Switzerland + *************************************************************/ + +/* RCS static ID */ +static char rcsid[]="$Header: /yafra/cvsroot/mapo/source/act/lib/AKTdln.c,v 1.2 2008-11-02 19:55:50 mwn Exp $"; + +/* MarcoPolo API includes */ +#include /* Standard Includefile */ + + +/*P--- EXTERNALS -----------------------------------------------------------*/ + + +/*--- LAYOUT ---------------------------------------------------------------*/ + + +/*--- GLOBALS -------------------------------------------------------------*/ + + + + + +/*F-------------------------------------------------------------------------- + * Function: AKTdlnGetNames () + * write single participant to travel + * In: -the current DLNid, where to write, format + * out: - + * Return: - + *--------------------------------------------------------------------------- + */ +void AKTdlnGetNames( int aDlnid, char* aTargetText, char* aFormat) +{ + extern DLN_VIEW dlnv; + + char vor[_CHAR30+1], name[_CHAR30+1]; + int id; + + /*--- Get name from dlnview ---------*/ + id = MPAPIselectOneId((int)_DLN_VIEW, aDlnid, (char *)&dlnv); + if (id != (int)MPOK) + { + copyTextTo( vor, dlnv.vor, _CHAR30) ; + copyTextTo( name, dlnv.name, _CHAR30) ; + /*--- print out ---------------------*/ + sprintf( aTargetText, aFormat, name, vor ); + } + else + sprintf( aTargetText, aFormat, " ", " " ); +} + + + + +/*SF------------------------------------------------------------------------- + * Function: OUTdlnGetAgeAscii() + * - compute age stuff for ticket, faktura etc.... + * In: - + * out: - + * Return: - completion code + *--------------------------------------------------------------------------- + */ +static int OUTdlnGetAgeAscii( int aDlnid, int aAdultLimit, char *aAge, int *adultFlag ) +{ + extern int AgeAdult; /* global */ + + REISENDER rei; + int age, len ; + int id; + int status; + + /*--- Init ----------------------------------*/ + status = (int)MPOK; + id = (int)0; + + /*-- Reisender ----------------------*/ + id = MPAPIselectOneId( (int)_REISENDER, aDlnid, (char*)&rei ); + + /*-- no date or no correct characters ---*/ + if ( ((len = strlen(rei.age)) == 0) || (isdigit(rei.age[0]) == 0) ) + { + sprintf(aAge, "%s", "-" ); + *adultFlag = 1; + } + else + { + /*-- Age in digits ------------------*/ + age = AKTdateConvertToAge( rei.age ); + if ( age == -1 ) + { + sprintf(aAge, "%s", "-" ); /* wrong string */ + *adultFlag = 1; + } + if ( age == 0 ) + { + sprintf(aAge, "%s", "1" ); + *adultFlag = 0; + } + else if (age >= aAdultLimit) + { + (void)copyTextTo( aAge, "A", _CHAR4); + *adultFlag = 1; + } + else + { + sprintf(aAge, "%3d", age ); + *adultFlag = 0; + } + } + return (status); +} + + + + +/*SF------------------------------------------------------------------------- + * Function: OUTdlnGetNextAdult() + * - Among all Dln, get the next: 2 Adults then other + * In: - + * out: - + * Return: - completion code + *--------------------------------------------------------------------------- + */ +static int OUTticketGetNextDln( int aAlreadyBooked, int aTarifLimit ) +{ + extern BCH_DLN *bchdln ; + extern int anzBd ; + + int status, i, theDlnid ; + int adultFlag = 1 ; /* 1 means adult */ + char ageTxt[_CHAR30+1]; /* age in ascii */ + BCH_DLN *pBchdln; + + /*-- Adults first ---------------------------*/ + if (aAlreadyBooked < aTarifLimit) + { + /*-- look for adults -----*/ + for ( i = 0; i < anzBd ; i++ ) + { + pBchdln = &bchdln[i]; + theDlnid = pBchdln->dln_id; + /*-- check if adult -----*/ + //status = OUTticketDlnAge( theDlnid, ageTxt, &adultFlag); + if ( (theDlnid != (int)UNDEF) && (adultFlag == 1) ) + { + /*-- this Dln has been treated --------------*/ + pBchdln->dln_id = (int)UNDEF; + return ( theDlnid); /*>>>> exit */ + } + } + } + + /*-- Whatever Dln not selected -------------*/ + for ( i = 0; i < anzBd ; i++ ) + { + pBchdln = &bchdln[i]; + theDlnid = pBchdln->dln_id; + if (theDlnid != (int)UNDEF) + { + /*-- this Dln has been treated --*/ + pBchdln->dln_id = (int)UNDEF; + return ( theDlnid); /*>>>> exit */ + } + } + + return ((int)UNDEF); +} + + diff --git a/pool/shard006/C/0119162_adxdec.c b/pool/shard006/C/0119162_adxdec.c new file mode 100644 index 0000000000000000000000000000000000000000..dca9748301f49118803b96173bf21d62d489fb3b --- /dev/null +++ b/pool/shard006/C/0119162_adxdec.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Justin Ruggles + * + * This file is part of Libav. + * + * Libav 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. + * + * Libav 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 Libav; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * CRI ADX demuxer + */ + +#include "libavutil/intreadwrite.h" +#include "libavcodec/adx.h" +#include "avformat.h" +#include "internal.h" + +#define BLOCK_SIZE 18 +#define BLOCK_SAMPLES 32 + +typedef struct ADXDemuxerContext { + int header_size; +} ADXDemuxerContext; + +static int adx_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + ADXDemuxerContext *c = s->priv_data; + AVCodecContext *avctx = s->streams[0]->codec; + int ret, size; + + size = BLOCK_SIZE * avctx->channels; + + pkt->pos = avio_tell(s->pb); + pkt->stream_index = 0; + + ret = av_get_packet(s->pb, pkt, size); + if (ret != size) { + av_free_packet(pkt); + return ret < 0 ? ret : AVERROR(EIO); + } + if (AV_RB16(pkt->data) & 0x8000) { + av_free_packet(pkt); + return AVERROR_EOF; + } + pkt->size = size; + pkt->duration = 1; + pkt->pts = (pkt->pos - c->header_size) / size; + + return 0; +} + +static int adx_read_header(AVFormatContext *s, AVFormatParameters *ap) +{ + ADXDemuxerContext *c = s->priv_data; + AVCodecContext *avctx; + int ret; + + AVStream *st = avformat_new_stream(s, NULL); + if (!st) + return AVERROR(ENOMEM); + avctx = s->streams[0]->codec; + + if (avio_rb16(s->pb) != 0x8000) + return AVERROR_INVALIDDATA; + c->header_size = avio_rb16(s->pb) + 4; + avio_seek(s->pb, -4, SEEK_CUR); + + avctx->extradata = av_mallocz(c->header_size + FF_INPUT_BUFFER_PADDING_SIZE); + if (!avctx->extradata) + return AVERROR(ENOMEM); + if (avio_read(s->pb, avctx->extradata, c->header_size) < c->header_size) { + av_freep(&avctx->extradata); + return AVERROR(EIO); + } + avctx->extradata_size = c->header_size; + + ret = avpriv_adx_decode_header(avctx, avctx->extradata, + avctx->extradata_size, &c->header_size, + NULL); + if (ret) + return ret; + + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = s->iformat->value; + + avpriv_set_pts_info(st, 64, BLOCK_SAMPLES, avctx->sample_rate); + + return 0; +} + +AVInputFormat ff_adx_demuxer = { + .name = "adx", + .long_name = NULL_IF_CONFIG_SMALL("CRI ADX"), + .priv_data_size = sizeof(ADXDemuxerContext), + .read_header = adx_read_header, + .read_packet = adx_read_packet, + .extensions = "adx", + .value = CODEC_ID_ADPCM_ADX, +}; diff --git a/pool/shard006/C/0119164_cn_i2c.c b/pool/shard006/C/0119164_cn_i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..16d13919838161850cb928c58f0992dcd9a2b75c --- /dev/null +++ b/pool/shard006/C/0119164_cn_i2c.c @@ -0,0 +1,64 @@ +#include +#include "soft_timer.h" +#include "iotlab_time.h" + +#include "iotlab_i2c_slave.h" +#include "iotlab_i2c/iotlab_i2c_.h" + +#include "cn_i2c.h" + +#include "debug.h" + +void get_timestamp(struct soft_timer_timeval *time) +{ + time->tv_sec = 0; + time->tv_sec = 0; + iotlab_time_extend_relative(time, soft_timer_time()); +} + + +static void rx_time(struct iotlab_i2c_handler_arg *arg) +{ + // Put saved timestamp in buffer + memcpy(arg->payload, &arg->timestamp, sizeof(struct soft_timer_timeval)); + log_info("Send time: %u.%06u", arg->timestamp.tv_sec, + arg->timestamp.tv_usec); +} +static struct iotlab_i2c_handler rx_time_handler = { + .header = IOTLAB_I2C_RX_TIME, // RX for open node // TX for CN + .type = IOTLAB_I2C_SLAVE_TX, + .payload_len = sizeof(struct soft_timer_timeval), + .handler = (handler_t)rx_time, + .next = NULL, +}; + +static void tx_event(struct iotlab_i2c_handler_arg *arg) +{ + uint16_t event; + memcpy(&event, arg->payload, sizeof(uint16_t)); + log_info("Got event %u", event); +} +static struct iotlab_i2c_handler tx_event_handler = { + .header = IOTLAB_I2C_TX_EVENT, // RX for open node // TX for CN + .type = IOTLAB_I2C_SLAVE_RX, + .payload_len = sizeof(uint16_t), + .handler = (handler_t)tx_event, + .next = NULL, +}; + + + +void cn_i2c_start() +{ + // register handlers + iotlab_i2c_slave_register_handler(&rx_time_handler); + iotlab_i2c_slave_register_handler(&tx_event_handler); + + iotlab_i2c_slave_register_timestamp_fct(get_timestamp); + iotlab_i2c_slave_start(); +} + +void cn_i2c_stop() +{ + iotlab_i2c_slave_stop(); +} diff --git a/pool/shard006/C/0119165_handlers.c b/pool/shard006/C/0119165_handlers.c new file mode 100644 index 0000000000000000000000000000000000000000..ffbfd374dcf7c86a7d56d0bf3c3776d175c3a47c --- /dev/null +++ b/pool/shard006/C/0119165_handlers.c @@ -0,0 +1,253 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * Copyright 2008-2015 MonetDB B.V. + */ + +#include "monetdb_config.h" +#include +#include +#include /* isatty */ +#include /* time, localtime */ +#include /* str* */ +#include /* open */ +#include /* wait */ +#include /* open */ +#include /* open */ +#include +#include + +#include + +#include "merovingian.h" +#include "handlers.h" + + +static char *sigint = "SIGINT"; +static char *sigterm = "SIGTERM"; +static char *sigquit = "SIGQUIT"; +static char *sighup = "SIGHUP"; +static char *sigabrt = "SIGABRT"; +static char *sigsegv = "SIGSEGV"; +static char *sigbus = "SIGBUS"; +static char *sigkill = "SIGKILL"; +static char * +sigtostr(int sig) +{ + switch (sig) { + case SIGINT: + return(sigint); + case SIGTERM: + return(sigterm); + case SIGQUIT: + return(sigquit); + case SIGHUP: + return(sighup); + case SIGABRT: + return(sigabrt); + case SIGSEGV: + return(sigsegv); +#ifdef SIGBUS + case SIGBUS: + return(sigbus); +#endif + case SIGKILL: + return(sigkill); + default: + return(NULL); + } +} + +/** + * Handler for SIGINT, SIGTERM and SIGQUIT. This starts a graceful + * shutdown of merovingian. + */ +void +handler(int sig) +{ + char *signame = sigtostr(sig); + if (signame == NULL) { + Mfprintf(stdout, "caught signal %d, starting shutdown sequence\n", sig); + } else { + Mfprintf(stdout, "caught %s, starting shutdown sequence\n", signame); + } + _mero_keep_listening = 0; +} + +/** + * Handler for SIGHUP, causes a re-read of the .merovingian_properties + * file and the logfile to be reopened. + */ +void +huphandler(int sig) +{ + int t; + time_t now = time(NULL); + struct tm *tmp = localtime(&now); + char mytime[20]; + char *f; + confkeyval *kv; + + (void)sig; + + /* re-read properties, we're in our dbfarm */ + readProps(_mero_props, "."); + + /* check and trim the hash-algo from the passphrase for easy use + * lateron */ + kv = findConfKey(_mero_props, "passphrase"); + if (kv->val != NULL) { + char *h = kv->val + 1; + if ((f = strchr(h, '}')) == NULL) { + Mfprintf(stderr, "ignoring invalid passphrase: %s\n", kv->val); + setConfVal(kv, NULL); + } else { + *f++ = '\0'; + if (strcmp(h, MONETDB5_PASSWDHASH) != 0) { + Mfprintf(stderr, "ignoring passphrase with incompatible " + "password hash: %s\n", h); + setConfVal(kv, NULL); + } else { + setConfVal(kv, f); + } + } + } + + /* have to make sure the logger is not logging anything */ + pthread_mutex_lock(&_mero_topdp_lock); + + strftime(mytime, sizeof(mytime), "%Y-%m-%d %H:%M:%S", tmp); + + f = getConfVal(_mero_props, "logfile"); + /* reopen (or open new) file */ + t = open(f, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR); + if (t == -1) { + Mfprintf(stderr, "forced to ignore SIGHUP: unable to open " + "'%s': %s\n", f, strerror(errno)); + } else { + Mfprintf(_mero_logfile, "%s END merovingian[" LLFMT "]: " + "caught SIGHUP, closing logfile\n", + mytime, (long long int)_mero_topdp->next->pid); + fflush(_mero_logfile); + _mero_topdp->out = _mero_topdp->err = t; + _mero_logfile = fdopen(t, "a"); + Mfprintf(_mero_logfile, "%s BEG merovingian[" LLFMT "]: " + "reopening logfile\n", + mytime, (long long int)_mero_topdp->next->pid); + } + + /* logger go ahead! */ + pthread_mutex_unlock(&_mero_topdp_lock); +} + +/** + * Handles SIGCHLD signals, that is, signals that a parent receives + * about its children. This handler deals with terminated children, by + * deregistering them from the internal administration (_mero_topdp) + * with the necessary cleanup. + */ +void +childhandler(int sig, siginfo_t *si, void *unused) +{ + dpair p, q; + + (void)sig; + (void)unused; + + /* wait for the child to get properly terminated, hopefully filling + * in the siginfo struct on FreeBSD */ + if (waitpid(-1, NULL, WNOHANG) <= 0) { + /* if no child has exited, we may have already waited for it + * in e.g. ctl_handle_client() */ + return; + } + + if (si->si_code != CLD_EXITED && + si->si_code != CLD_KILLED && + si->si_code != CLD_DUMPED) + { + /* ignore traps, stops and continues, we only want terminations + * of the client process */ + return; + } + + pthread_mutex_lock(&_mero_topdp_lock); + + /* get the pid from the former child, and locate it in our list */ + q = _mero_topdp->next; + p = q->next; + while (p != NULL) { + if (p->pid == si->si_pid) { + /* log everything that's still in the pipes */ + logFD(p->out, "MSG", p->dbname, (long long int)p->pid, _mero_logfile); + /* remove from the list */ + q->next = p->next; + /* close the descriptors */ + close(p->out); + close(p->err); + if (si->si_code == CLD_EXITED) { + Mfprintf(stdout, "database '%s' (%lld) has exited with " + "exit status %d\n", p->dbname, + (long long int)p->pid, si->si_status); + } else if (si->si_code == CLD_KILLED) { + char *sigstr = sigtostr(si->si_status); + char signum[8]; + if (sigstr == NULL) { + snprintf(signum, 8, "%d", si->si_status); + sigstr = signum; + } + Mfprintf(stdout, "database '%s' (%lld) was killed by signal " + "%s\n", p->dbname, + (long long int)p->pid, sigstr); + } else if (si->si_code == CLD_DUMPED) { + Mfprintf(stdout, "database '%s' (%lld) has crashed " + "(dumped core)\n", p->dbname, + (long long int)p->pid); + } + if (p->dbname) + free(p->dbname); + free(p); + pthread_mutex_unlock(&_mero_topdp_lock); + return; + } + q = p; + p = q->next; + } + + pthread_mutex_unlock(&_mero_topdp_lock); + + Mfprintf(stdout, "received SIGCHLD from unknown child with pid %lld\n", + (long long int)si->si_pid); +} + +/** + * Last resort handler to give a message in the log. + */ +void +segvhandler(int sig) { + struct sigaction sa; + + (void)sig; + + /* (try to) ignore any further segfaults */ + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = SIG_IGN; + sigaction(SIGSEGV, &sa, NULL); + + if (_mero_topdp != NULL) { + char errmsg[] = "\nSEGMENTATION FAULT OCCURRED\n" + "\nA fatal error has occurred which prevents monetdbd from operating." + "\nThis is likely a bug in monetdbd, please report it on http://bugs.monetdb.org/" + "\nand include the tail of this log in your bugreport with your explanation of " + "\nwhat you were doing, if possible.\n" + "\nABORTING NOW, YOU HAVE TO MANUALLY KILL ALL REMAINING mserver5 PROCESSES\n"; + if (write(_mero_topdp->err, errmsg, sizeof(errmsg) - 1) >= 0) + sync(); + } + abort(); +} + +/* vim:set ts=4 sw=4 noexpandtab: */ diff --git a/pool/shard006/C/0119177_ita2_irr.c b/pool/shard006/C/0119177_ita2_irr.c new file mode 100644 index 0000000000000000000000000000000000000000..1b1e0781a12fa5a1592988c6aa6ae53557467f29 --- /dev/null +++ b/pool/shard006/C/0119177_ita2_irr.c @@ -0,0 +1,377 @@ +/* + * ita2_irr.c - example of how to use code range restriction with the Itanium2 PMU + * + * Copyright (c) 2002-2006 Hewlett-Packard Development Company, L.P. + * Contributed by Stephane Eranian + * + * 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. + * + * This file is part of libpfm, a performance monitoring support library for + * applications on Linux/ia64. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define NUM_PMCS PFMLIB_MAX_PMCS +#define NUM_PMDS PFMLIB_MAX_PMDS + +#define MAX_EVT_NAME_LEN 128 +#define MAX_PMU_NAME_LEN 32 + +#define VECTOR_SIZE 1000000UL + +typedef struct { + char *event_name; + unsigned long expected_value; +} event_desc_t; + +static event_desc_t event_list[]={ + { "fp_ops_retired", VECTOR_SIZE<<1 }, + { NULL, 0UL } +}; + + +static void fatal_error(char *fmt,...) __attribute__((noreturn)); + +static void +fatal_error(char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vfprintf(stderr, fmt, ap); + va_end(ap); + + exit(1); +} + + +void +saxpy(double *a, double *b, double *c, unsigned long size) +{ + unsigned long i; + + for(i=0; i < size; i++) { + c[i] = 2*a[i] + b[i]; + } + printf("done saxpy\n"); +} + +void +saxpy2(double *a, double *b, double *c, unsigned long size) +{ + unsigned long i; + + for(i=0; i < size; i++) { + c[i] = 2*a[i] + b[i]; + } + printf("done saxpy2\n"); +} + + + +static int +do_test(void) +{ + unsigned long size; + double *a, *b, *c; + + size = VECTOR_SIZE; + + a = malloc(size*sizeof(double)); + b = malloc(size*sizeof(double)); + c = malloc(size*sizeof(double)); + + if (a == NULL || b == NULL || c == NULL) fatal_error("Cannot allocate vectors\n"); + + memset(a, 0, size*sizeof(double)); + memset(b, 0, size*sizeof(double)); + memset(c, 0, size*sizeof(double)); + + saxpy(a,b,c, size); + saxpy2(a,b,c, size); + + return 0; +} + +int +main(int argc, char **argv) +{ + event_desc_t *p; + unsigned long range_start, range_end; + int ret, type = 0; + pfmlib_input_param_t inp; + pfmlib_output_param_t outp; + pfmlib_ita2_input_param_t ita2_inp; + pfmlib_ita2_output_param_t ita2_outp; + pfarg_pmr_t pd[NUM_PMDS]; + pfarg_pmr_t pc[NUM_PMCS]; + pfarg_pmr_t ibrs[8]; + pfmlib_options_t pfmlib_options; + struct fd { /* function descriptor */ + unsigned long addr; + unsigned long gp; + } *fd; + unsigned int i; + int id; + char name[MAX_EVT_NAME_LEN]; + + /* + * Initialize pfm library (required before we can use it) + */ + ret = pfm_initialize(); + if (ret != PFMLIB_SUCCESS) + fatal_error("Cannot initialize library: %s\n", pfm_strerror(ret)); + + /* + * Let's make sure we run this on the right CPU family + */ + pfm_get_pmu_type(&type); + if (type != PFMLIB_ITANIUM2_PMU) { + char model[MAX_PMU_NAME_LEN]; + pfm_get_pmu_name(model, MAX_PMU_NAME_LEN); + fatal_error("this program does not work with %s PMU\n", model); + } + /* + * pass options to library (optional) + */ + memset(&pfmlib_options, 0, sizeof(pfmlib_options)); + pfmlib_options.pfm_debug = 1; /* set to 1 for debug */ + pfmlib_options.pfm_verbose = 1; /* set to 1 for verbose */ + pfm_set_options(&pfmlib_options); + + /* + * Compute the range we are interested in + * + * On IA-64, the function pointer does not point directly + * to the function but to a descriptor which contains two + * unsigned long: the first one is the actual start address + * of the function, the second is the gp (global pointer) + * to load into r1 before jumping into the function. Unlesss + * we're jumping into a shared library the gp is the same as + * the current gp. + * + * In the artificial example, we also rely on the compiler/linker + * NOT reordering code layout. We depend on saxpy2() being just + * after saxpy(). + * + */ + fd = (struct fd *)saxpy; + range_start = fd->addr; + + fd = (struct fd *)saxpy2; + range_end = fd->addr; + + /* + * linker may reorder saxpy() and saxpy2() + */ + if (range_end < range_start) { + unsigned long tmp; + tmp = range_start; + range_start = range_end; + range_end = tmp; + } + + memset(pc, 0, sizeof(pc)); + memset(pd, 0, sizeof(pd)); + memset(ibrs,0, sizeof(ibrs)); + + memset(&inp,0, sizeof(inp)); + memset(&outp,0, sizeof(outp)); + memset(&ita2_inp,0, sizeof(ita2_inp)); + memset(&ita2_outp,0, sizeof(ita2_outp)); + + /* + * find requested event + */ + p = event_list; + for (i=0; p->event_name ; i++, p++) { + if (pfm_find_event(p->event_name, &inp.pfp_events[i].event) != PFMLIB_SUCCESS) { + fatal_error("cannot find %s event\n", p->event_name); + } + } + + /* + * set the privilege mode: + * PFM_PLM3 : user level only + */ + inp.pfp_dfl_plm = PFM_PLM3; + /* + * how many counters we use + */ + inp.pfp_event_count = i; + + /* + * We use the library to figure out how to program the debug registers + * to cover the data range we are interested in. The rr_end parameter + * must point to the byte after the last element of the range (C-style range). + * + * Because of the masking mechanism and therefore alignment constraints used to implement + * this feature, it may not be possible to exactly cover a given range. It may be that + * the coverage exceeds the desired range. So it is possible to capture noise if + * the surrounding addresses are also heavily used. You can figure out by how much the + * actual range is off compared to the requested range by checking the rr_soff and rr_eoff + * fields on return from the library call. + * + * Upon return, the rr_dbr array is programmed and the number of debug registers (not pairs) + * used to cover the range is in rr_nbr_used. + * + * In the case of code range restriction on Itanium 2, the library will try to use the fine + * mode first and then it will default to using multiple pairs to cover the range. + */ + + ita2_inp.pfp_ita2_irange.rr_used = 1; /* indicate we use code range restriction */ + ita2_inp.pfp_ita2_irange.rr_limits[0].rr_start = range_start; + ita2_inp.pfp_ita2_irange.rr_limits[0].rr_end = range_end; + + + /* + * let the library figure out the values for the PMCS + */ + if ((ret=pfm_dispatch_events(&inp, &ita2_inp, &outp, &ita2_outp)) != PFMLIB_SUCCESS) { + fatal_error("cannot configure events: %s\n", pfm_strerror(ret)); + } + + /* + * print offsets + */ + printf("code range : [0x%016lx-0x%016lx)\n" + "start_offset:-0x%lx end_offset:+0x%lx\n" + "%d pairs of debug registers used\n", + range_start, + range_end, + ita2_outp.pfp_ita2_irange.rr_infos[0].rr_soff, + ita2_outp.pfp_ita2_irange.rr_infos[0].rr_eoff, + ita2_outp.pfp_ita2_irange.rr_nbr_used >> 1); + + /* + * create session + */ + id = pfm_create(0, NULL); + if (id == -1) { + if (errno == ENOSYS) { + fatal_error("Your kernel does not have performance monitoring support!\n"); + } + fatal_error("cannot create session %s\n", strerror(errno)); + } + /* + * Now prepare the argument to initialize the PMDs and PMCS. + * We must pfp_pmc_count to determine the number of PMC to intialize. + * We must use pfp_event_count to determine the number of PMD to initialize. + * Some events cause extra PMCs to be used, so pfp_pmc_count may be >= pfp_event_count. + * + * This step is new compared to libpfm-2.x. It is necessary because the library no + * longer knows about the kernel data structures. + */ + + for (i=0; i < outp.pfp_pmc_count; i++) { + pc[i].reg_num = outp.pfp_pmcs[i].reg_num; + pc[i].reg_value = outp.pfp_pmcs[i].reg_value; + } + + /* + * figure out pmd mapping from output pmc + */ + for (i=0; i < outp.pfp_pmd_count; i++) + pd[i].reg_num = outp.pfp_pmds[i].reg_num; + + /* + * propagate the setup for the debug registers from the library to the arguments + * to the syscall. The library does not know the type of the syscall + * anymore. The code debug registers start at PMC256 on all Itanium processors. + */ + for (i=0; i < ita2_outp.pfp_ita2_irange.rr_nbr_used; i++) { + ibrs[i].reg_num = 256+ita2_outp.pfp_ita2_irange.rr_br[i].reg_num; + ibrs[i].reg_value = ita2_outp.pfp_ita2_irange.rr_br[i].reg_value; + } + /* + * Now program the registers + * + * We don't use the save variable to indicate the number of elements passed to + * the kernel because, as we said earlier, pc may contain more elements than + * the number of events we specified, i.e., contains more than coutning monitors. + */ + if (pfm_write(id, 0, PFM_RW_PMC, pc, outp.pfp_pmc_count * sizeof(*pc)) == -1) + fatal_error("pfm_write error errno %d\n",errno); + + /* + * Program the code debug registers. + */ + if (pfm_write(id, 0, PFM_RW_PMC, ibrs, ita2_outp.pfp_ita2_irange.rr_nbr_used * sizeof(*ibrs)) == -1) + fatal_error("pfm_write error errno %d\n",errno); + + + if (pfm_write(id, 0, PFM_RW_PMD, pd, outp.pfp_pmd_count * sizeof(*pd)) == -1) + fatal_error("pfm_write(PMD) error errno %d\n",errno); + /* + * now we attach the session to pid + */ + if (pfm_attach(id, 0, getpid()) == -1) + fatal_error("pfm_attach error errno %d\n",errno); + + /* + * Let's roll now. + * + * We run two distinct copies of the same function but we restrict measurement + * to the first one (saxpy). Therefore the expected count is half what you would + * get if code range restriction was not used. The core loop in both case uses + * two floating point operation per iteration. + */ + if (pfm_set_state(id, 0, PFM_ST_START)) + fatal_error("pfm_set_state error errno %d\n",errno); + + do_test(); + + if (pfm_set_state(id, 0, PFM_ST_STOP)) + fatal_error("pfm_set_state error errno %d\n",errno); + /* + * now read the results + */ + if (pfm_read(id, 0, PFM_RW_PMD, pd, inp.pfp_event_count * sizeof(*pd)) == -1) + fatal_error("pfm_read(PMD) error errno %d\n",errno); + + /* + * print the results + * + * It is important to realize, that the first event we specified may not + * be in PMD4. Not all events can be measured by any monitor. That's why + * we need to use the pc[] array to figure out where event i was allocated. + */ + for (i=0; i < inp.pfp_event_count; i++) { + pfm_get_full_event_name(&inp.pfp_events[i], name, MAX_EVT_NAME_LEN); + printf("PMD%-3u %20lu %s (expected %lu)\n", + pd[i].reg_num, + pd[i].reg_value, + name, event_list[i].expected_value); + } + /* + * let's stop this now + */ + close(id); + + return 0; +} diff --git a/pool/shard006/C/0119179_egg-dn.c b/pool/shard006/C/0119179_egg-dn.c new file mode 100644 index 0000000000000000000000000000000000000000..79363e3be9a30c91bc59aeb7d41c156c9c46c7ea --- /dev/null +++ b/pool/shard006/C/0119179_egg-dn.c @@ -0,0 +1,291 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* egg-asn1.c - ASN.1 helper routines + + Copyright (C) 2007 Stefan Walter + + The Mate Keyring Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public License as + published by the Free Software Foundation; either version 2 of the + License, or (at your option) any later version. + + The Mate Keyring Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the Mate Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + Boston, MA 02110-1301, USA. + + Author: Stef Walter +*/ + +#include "config.h" + +#include "egg-asn1-defs.h" +#include "egg-asn1x.h" +#include "egg-dn.h" +#include "egg-oid.h" + +#include + +static const char HEXC[] = "0123456789ABCDEF"; + +static gchar* +dn_print_hex_value (const guchar *data, gsize len) +{ + GString *result = g_string_sized_new (len * 2 + 1); + gsize i; + + g_string_append_c (result, '#'); + for (i = 0; i < len; ++i) { + g_string_append_c (result, HEXC[data[i] >> 4 & 0xf]); + g_string_append_c (result, HEXC[data[i] & 0xf]); + } + + return g_string_free (result, FALSE); +} + +static gchar* +dn_print_oid_value_parsed (GQuark oid, guint flags, const guchar *data, gsize len) +{ + GNode *asn1, *node; + gconstpointer value; + gsize n_value; + gchar *result; + + g_assert (data); + g_assert (len); + + asn1 = egg_asn1x_create_quark (pkix_asn1_tab, oid); + g_return_val_if_fail (asn1, NULL); + + if (!egg_asn1x_decode (asn1, data, len)) { + g_message ("couldn't decode value for OID: %s: %s", + g_quark_to_string (oid), egg_asn1x_message (asn1)); + egg_asn1x_destroy (asn1); + return NULL; + } + + /* + * If it's a choice element, then we have to read depending + * on what's there. + */ + if (flags & EGG_OID_IS_CHOICE) + node = egg_asn1x_get_choice (asn1); + else + node = asn1; + + value = egg_asn1x_get_raw_value (node, &n_value); + + /* + * Now we make sure it's UTF-8. + */ + + if (!value) { + g_message ("couldn't read value for OID: %s", g_quark_to_string (oid)); + result = NULL; + + } else if (!g_utf8_validate (value, n_value, NULL)) { + result = dn_print_hex_value ((guchar*)value, n_value); + + } else { + result = g_strndup (value, n_value); + } + + egg_asn1x_destroy (asn1); + + return result; +} + +static gchar* +dn_print_oid_value (GQuark oid, guint flags, const guchar *data, gsize len) +{ + gchar *value; + + g_assert (data); + g_assert (len); + + if (flags & EGG_OID_PRINTABLE) { + value = dn_print_oid_value_parsed (oid, flags, data, len); + if (value != NULL) + return value; + } + + return dn_print_hex_value (data, len); +} + +static gchar* +dn_parse_rdn (GNode *asn) +{ + const gchar *name; + guint flags; + GQuark oid; + gconstpointer value; + gsize n_value; + gchar *display; + gchar *result; + + g_assert (asn); + + oid = egg_asn1x_get_oid_as_quark (egg_asn1x_node (asn, "type", NULL)); + g_return_val_if_fail (oid, NULL); + + flags = egg_oid_get_flags (oid); + name = egg_oid_get_name (oid); + + value = egg_asn1x_get_raw_element (egg_asn1x_node (asn, "value", NULL), &n_value); + g_return_val_if_fail (value, NULL); + + display = dn_print_oid_value (oid, flags, value, n_value); + result = g_strconcat ((flags & EGG_OID_PRINTABLE) ? name : g_quark_to_string (oid), + "=", display, NULL); + g_free (display); + + return result; +} + +gchar* +egg_dn_read (GNode* asn) +{ + gboolean done = FALSE; + GString *result; + GNode *node; + gchar *rdn; + gint i, j; + + g_return_val_if_fail (asn, NULL); + + result = g_string_sized_new (64); + + /* Each (possibly multi valued) RDN */ + for (i = 1; !done; ++i) { + + /* Each type=value pair of an RDN */ + for (j = 1; TRUE; ++j) { + node = egg_asn1x_node (asn, i, j, NULL); + if (!node) { + done = j == 1; + break; + } + + rdn = dn_parse_rdn (node); + g_return_val_if_fail (rdn, NULL); + + /* Account for multi valued RDNs */ + if (j > 1) + g_string_append (result, "+"); + else if (i > 1) + g_string_append (result, ", "); + + g_string_append (result, rdn); + g_free (rdn); + } + } + + /* Returns null when string is empty */ + return g_string_free (result, (result->len == 0)); +} + +gchar* +egg_dn_read_part (GNode *asn, const gchar *match) +{ + gboolean done = FALSE; + const gchar *name; + gconstpointer value; + gsize n_value; + GNode *node; + GQuark oid; + gint i, j; + + g_return_val_if_fail (asn, NULL); + g_return_val_if_fail (match, NULL); + + /* Each (possibly multi valued) RDN */ + for (i = 1; !done; ++i) { + + /* Each type=value pair of an RDN */ + for (j = 1; TRUE; ++j) { + node = egg_asn1x_node (asn, i, j, "type", NULL); + if (!node) { + done = j == 1; + break; + } + + oid = egg_asn1x_get_oid_as_quark (node); + g_return_val_if_fail (oid, NULL); + + /* Does it match either the OID or the displayable? */ + if (g_ascii_strcasecmp (g_quark_to_string (oid), match) != 0) { + name = egg_oid_get_name (oid); + if (!g_ascii_strcasecmp (name, match) == 0) + continue; + } + + node = egg_asn1x_node (asn, i, j, "value", NULL); + g_return_val_if_fail (node, NULL); + + value = egg_asn1x_get_raw_element (node, &n_value); + g_return_val_if_fail (value, NULL); + + return dn_print_oid_value (oid, egg_oid_get_flags (oid), value, n_value); + } + } + + return NULL; +} + +gboolean +egg_dn_parse (GNode *asn, EggDnCallback callback, gpointer user_data) +{ + gboolean done = FALSE; + GNode *node; + gconstpointer value; + gsize n_value; + GQuark oid; + guint i, j; + + g_return_val_if_fail (asn, FALSE); + + /* Each (possibly multi valued) RDN */ + for (i = 1; !done; ++i) { + + /* Each type=value pair of an RDN */ + for (j = 1; TRUE; ++j) { + + /* Dig out the type */ + node = egg_asn1x_node (asn, i, j, "type", NULL); + if (!node) { + done = j == 1; + break; + } + + oid = egg_asn1x_get_oid_as_quark (node); + g_return_val_if_fail (oid, FALSE); + + /* Dig out the value */ + node = egg_asn1x_node (asn, i, j, "value", NULL); + if (!node) { + done = j == 1; + break; + } + + value = egg_asn1x_get_raw_element (node, &n_value); + + if (callback) + (callback) (i, oid, value, n_value, user_data); + } + } + + return i > 1; +} + +gchar* +egg_dn_print_value (GQuark oid, const guchar *value, gsize n_value) +{ + g_return_val_if_fail (oid, NULL); + g_return_val_if_fail (value || !n_value, NULL); + + return dn_print_oid_value (oid, egg_oid_get_flags (oid), value, n_value); +} diff --git a/pool/shard006/C/0119180_xstat.c b/pool/shard006/C/0119180_xstat.c new file mode 100644 index 0000000000000000000000000000000000000000..1e99d7ecef805921582559efec42368b89eef50b --- /dev/null +++ b/pool/shard006/C/0119180_xstat.c @@ -0,0 +1,102 @@ +/* xstat using old-style Unix stat system call. + Copyright (C) 1991,95,96,97,98,2000 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. */ + +/* Ho hum, if xstat == xstat64 we must get rid of the prototype or gcc + will complain since they don't strictly match. */ +#define __xstat64 __xstat64_disable + +#include +#include +#include +#include + +#include +#include +#include + +#include "kernel-features.h" + +#include + +extern int __syscall_stat (const char *__unbounded, + struct kernel_stat *__unbounded); + +#ifdef __NR_stat64 +extern int __syscall_stat64 (const char *__unbounded, + struct stat64 *__unbounded); +# if __ASSUME_STAT64_SYSCALL == 0 +/* The variable is shared between all wrappers around *stat64 calls. */ +extern int __have_no_stat64; +# endif +#endif + + +/* Get information about the file NAME in BUF. */ +int +__xstat (int vers, const char *name, struct stat *buf) +{ +#if __ASSUME_STAT64_SYSCALL == 0 + struct kernel_stat kbuf; +#endif + int result; + + if (vers == _STAT_VER_KERNEL) + return INLINE_SYSCALL (stat, 2, CHECK_STRING (name), CHECK_1 ((struct kernel_stat *) buf)); + +#if __ASSUME_STAT64_SYSCALL > 0 + { + struct stat64 buf64; + + result = INLINE_SYSCALL (stat64, 2, CHECK_STRING (name), __ptrvalue (&buf64)); + if (result == 0) + result = xstat32_conv (vers, &buf64, buf); + return result; + } +#else +# if defined __NR_stat64 + /* To support 32 bit UIDs, we have to use stat64. The normal stat call only returns + 16 bit UIDs. */ + if (! __have_no_stat64) + { + struct stat64 buf64; + + result = INLINE_SYSCALL (stat64, 2, CHECK_STRING (name), __ptrvalue (&buf64)); + + if (result == 0) + result = xstat32_conv (vers, &buf64, buf); + + if (result != -1 || errno != ENOSYS) + return result; + + __have_no_stat64 = 1; + } +# endif + result = INLINE_SYSCALL (stat, 2, CHECK_STRING (name), __ptrvalue (&kbuf)); + if (result == 0) + result = xstat_conv (vers, &kbuf, buf); + + return result; +#endif /* __ASSUME_STAT64_SYSCALL */ +} + +weak_alias (__xstat, _xstat); +#ifdef XSTAT_IS_XSTAT64 +# undef __xstat64 +strong_alias (__xstat, __xstat64); +#endif diff --git a/pool/shard006/C/0119188_initializers.c b/pool/shard006/C/0119188_initializers.c new file mode 100644 index 0000000000000000000000000000000000000000..381007c60a2e2eb770643069ad39814ec06437f3 --- /dev/null +++ b/pool/shard006/C/0119188_initializers.c @@ -0,0 +1,185 @@ +/* Special Initializers for certain USB Mass Storage devices + * + * Current development and maintenance by: + * (c) 1999, 2000 Matthew Dharm (mdharm-usb@one-eyed-alien.net) + * + * This driver is based on the 'USB Mass Storage Class' document. This + * describes in detail the protocol used to communicate with such + * devices. Clearly, the designers had SCSI and ATAPI commands in + * mind when they created this document. The commands are all very + * similar to commands in the SCSI-II and ATAPI specifications. + * + * It is important to note that in a number of cases this class + * exhibits class-specific exemptions from the USB specification. + * Notably the usage of NAK, STALL and ACK differs from the norm, in + * that they are used to communicate wait, failed and OK on commands. + * + * Also, for certain devices, the interrupt endpoint is used to convey + * status of a command. + * + * Please see http://www.one-eyed-alien.net/~mdharm/linux-usb for more + * information about this driver. + * + * 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. + * + * 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., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include + +#include "usb.h" +#include "initializers.h" +#include "debug.h" +#include "transport.h" + +/* This places the Shuttle/SCM USB<->SCSI bridge devices in multi-target + * mode */ +int usb_stor_euscsi_init(struct us_data *us) +{ + int result; + + US_DEBUGP("Attempting to init eUSCSI bridge...\n"); + us->iobuf[0] = 0x1; + result = usb_stor_control_msg(us, us->send_ctrl_pipe, + 0x0C, USB_RECIP_INTERFACE | USB_TYPE_VENDOR, + 0x01, 0x0, us->iobuf, 0x1, 5000); + US_DEBUGP("-- result is %d\n", result); + + return 0; +} + +/* This function is required to activate all four slots on the UCR-61S2B + * flash reader */ +int usb_stor_ucr61s2b_init(struct us_data *us) +{ + struct bulk_cb_wrap *bcb = (struct bulk_cb_wrap*) us->iobuf; + struct bulk_cs_wrap *bcs = (struct bulk_cs_wrap*) us->iobuf; + int res; + unsigned int partial; + static char init_string[] = "\xec\x0a\x06\x00$PCCHIPS"; + + US_DEBUGP("Sending UCR-61S2B initialization packet...\n"); + + bcb->Signature = cpu_to_le32(US_BULK_CB_SIGN); + bcb->Tag = 0; + bcb->DataTransferLength = cpu_to_le32(0); + bcb->Flags = bcb->Lun = 0; + bcb->Length = sizeof(init_string) - 1; + memset(bcb->CDB, 0, sizeof(bcb->CDB)); + memcpy(bcb->CDB, init_string, sizeof(init_string) - 1); + + res = usb_stor_bulk_transfer_buf(us, us->send_bulk_pipe, bcb, + US_BULK_CB_WRAP_LEN, &partial); + if (res) + return -EIO; + + US_DEBUGP("Getting status packet...\n"); + res = usb_stor_bulk_transfer_buf(us, us->recv_bulk_pipe, bcs, + US_BULK_CS_WRAP_LEN, &partial); + if (res) + return -EIO; + + return 0; +} + +/* This places the HUAWEI E220 devices in multi-port mode */ +int usb_stor_huawei_e220_init(struct us_data *us) +{ +#if 0 + int result; + + result = usb_stor_control_msg(us, us->send_ctrl_pipe, + USB_REQ_SET_FEATURE, + USB_TYPE_STANDARD | USB_RECIP_DEVICE, + 0x01, 0x0, NULL, 0x0, 1000); + US_DEBUGP("Huawei mode set result is %d\n", result); + return 0; +#else + printk("====usb_stor_huawei_e220_init===>\n"); + return -ENODEV; +#endif + +} + +//AC560--ZTE-- 0x19d20026->0x19d20094 before convert to modem,don't report disk dev +int usb_stor_ZTE_AC580_init(struct us_data *us) // PID = 0x0026 +{ +#if 0 + int result = 0; + int act_len = 0; + + result = usb_stor_control_msg(us, us->send_ctrl_pipe,USB_REQ_CLEAR_FEATURE, + USB_TYPE_STANDARD | USB_RECIP_ENDPOINT,0x0, 0x89, NULL, 0x0, 1000); + + US_DEBUGP("usb_stor_control_msg performing result is %d\n", result); + printk("====AC580/AC560===>usb_stor_control_msg performing result is %d\n", result); + + result = usb_stor_control_msg(us, us->send_ctrl_pipe,USB_REQ_CLEAR_FEATURE, + USB_TYPE_STANDARD | USB_RECIP_ENDPOINT,0x0, 0x9, NULL, 0x0, 1000); + + US_DEBUGP("usb_stor_control_msg performing result is %d\n", result); + printk("====AC580/AC560===>usb_stor_control_msg performing result is %d\n", result); + return (result ? 0 : -ENODEV); +#else + return -ENODEV; +#endif +} + +//AC560--ZTE-- 0x19d20026->0x19d20094 before convert to modem,don't report disk dev +int usb_stor_ZTE_AC580_init2(struct us_data *us) // PID = 0x0026 +{ + return -ENODEV; +} + +int usb_stor_ASB_init(struct us_data *us) +{ + printk("====%s===>\n",__FUNCTION__); + return -ENODEV; +} + +int usb_stor_TechFaith_init(struct us_data *us) +{ + usb_stor_port_reset(us); + return -ENODEV; +} + +int usb_stor_Shichuangxing_init(struct us_data *us) +{ + printk("====usb_stor_Shichuangxing_init===>\n"); + return -ENODEV; +} + +int usb_stor_wangxun_init(struct us_data *us) +{ + + printk("====usb_stor_wangxun_init===>\n"); + usb_stor_port_reset(us); + return -ENODEV; + +} +int usb_stor_people_init(struct us_data *us) +{ + printk("====people_init===>\n"); + usb_stor_control_msg(us, us->send_ctrl_pipe, USB_REQ_CLEAR_FEATURE, + USB_TYPE_STANDARD | USB_RECIP_ENDPOINT,0x0, 0x83, NULL, 0x0, 1000); + return -ENODEV; +} + +int usb_modem_init(struct us_data *us) +{ + printk("====modem_init===>\n"); + usb_stor_control_msg(us, us->send_ctrl_pipe, USB_REQ_CLEAR_FEATURE, + USB_TYPE_STANDARD | USB_RECIP_ENDPOINT,0x0, 0x85, NULL, 0x0, 1000); + return -ENODEV; +} + diff --git a/pool/shard006/C/0119190_mainTask.c b/pool/shard006/C/0119190_mainTask.c new file mode 100644 index 0000000000000000000000000000000000000000..92f7841162d332087b8765d484487b93e18914ab --- /dev/null +++ b/pool/shard006/C/0119190_mainTask.c @@ -0,0 +1,163 @@ +/* + * mainTask.c + * + * Created: 11.9.2014 11:05:32 + * Author: Tomas Baca + */ + +#include "mainTask.h" +#include "system.h" +#include "controllers.h" +#include "commTask.h" +#include "mpcHandler.h" +#include "trajectories.h" + +// for on-off by AUX3 channel +volatile int8_t AUX1_previous = 0; +volatile int16_t setpointChangeTrigger = 0; +volatile int16_t currentSetpointIdx = 0; + +#ifdef MULTICON + + #include "multiCon.h" + float correctionX = 0; + float correctionY = 0; + +#endif + +#ifdef RASPBERRY_PI + + #include "raspberryPi.h" + float correctionX = -0.5; + float correctionY = 0; + +#endif + +void mainTask(void *p) { + + main2commMessage_t main2commMessage; + main2commMessage.messageType = CLEAR_STATES; + xQueueSend(main2commsQueue, &main2commMessage, 0); + + vTaskDelay(50); + + int16_t aux2filtered = PPM_IN_MIDDLE_LENGTH; + int16_t aux3filtered = PPM_IN_MIDDLE_LENGTH; + + while (1) { + + // controller on/off + if (abs(RCchannel[AUX1] - PPM_IN_MIDDLE_LENGTH) < 500) { + + if (AUX1_previous == 0) { + enableAltitudeController(); + } + + disableMpcController(); + AUX1_previous = 1; + + } else if (RCchannel[AUX1] > (PPM_IN_MIDDLE_LENGTH + 500)) { + + if (AUX1_previous == 1) { + + main2commMessage.messageType = CLEAR_STATES; + main2commMessage.data.simpleSetpoint.elevator = 0; + main2commMessage.data.simpleSetpoint.aileron = 0; + xQueueSend(main2commsQueue, &main2commMessage, 0); + + // wait between reseting the kalman and starting the controller + vTaskDelay(50); + + enablePositionController(); + } + + AUX1_previous = 2; + + } else { + + disableAltitudeController(); + disableMpcController(); + AUX1_previous = 0; + } + + #ifdef GRIPPER + + // aux stick for setting the setpoint + aux3filtered = aux3filtered*0.997 + RCchannel[AUX3]*0.003; + + // up + if ((aux3filtered > (PPM_IN_MIDDLE_LENGTH + 300))) { + + ioport_set_pin_level(GRIP_PIN, true); + + // down + } else { + + ioport_set_pin_level(GRIP_PIN, false); + } + + #endif + + // AUX switch on RC transmitter + aux2filtered = aux2filtered*0.997 + RCchannel[AUX2]*0.003; + + if (auxSetpointFlag == 1) { + + if (setpointChangeTrigger++ == 10) { + + setpointChangeTrigger = 1; + + // switch is DOWN + if ((aux2filtered < (PPM_IN_MIDDLE_LENGTH - 300))) { + + main2commMessage.messageType = SET_SETPOINT; + main2commMessage.data.simpleSetpoint.elevator = 0; + main2commMessage.data.simpleSetpoint.aileron = 0; + xQueueSend(main2commsQueue, &main2commMessage, 0); + + led_orange_off(); + + // switch is in the MIDDLE + } else if ((abs(aux2filtered - PPM_IN_MIDDLE_LENGTH) <= 300)) { + + main2commMessage.messageType = SET_SETPOINT; + main2commMessage.data.simpleSetpoint.elevator = 0; + main2commMessage.data.simpleSetpoint.aileron = 0; + xQueueSend(main2commsQueue, &main2commMessage, 0); + + led_orange_on(); + + // switch is UP + } else if ((aux2filtered > (PPM_IN_MIDDLE_LENGTH + 300))) { + + main2commMessage.messageType = SET_TRAJECTORY; + + // when the trajectory is over + if (++currentSetpointIdx >= TRAJECTORY_LENGTH-1) + currentSetpointIdx = 0; // reset it and go again + + int16_t futureSetpointIdx = currentSetpointIdx; + + int i; + for (i = 0; i < 5; i++) { + + main2commMessage.data.trajectory.elevatorTrajectory[i] = pgm_read_float(&(trajectoryElevator[futureSetpointIdx])); + main2commMessage.data.trajectory.aileronTrajectory[i] = pgm_read_float(&(trajectoryAileron[futureSetpointIdx])); + + futureSetpointIdx = futureSetpointIdx + 50; + + if (futureSetpointIdx > (TRAJECTORY_LENGTH-1)) + futureSetpointIdx -= TRAJECTORY_LENGTH; + } + + xQueueSend(main2commsQueue, &main2commMessage, 0); + + led_orange_toggle(); + } + + } + + auxSetpointFlag = 0; + } + } +} \ No newline at end of file diff --git a/pool/shard006/C/0119191_emmc_partitions.c b/pool/shard006/C/0119191_emmc_partitions.c new file mode 100644 index 0000000000000000000000000000000000000000..f112180bf228e74a6a7da356d23f9e6ffeeb666c --- /dev/null +++ b/pool/shard006/C/0119191_emmc_partitions.c @@ -0,0 +1,180 @@ +/* arch/arm/mach-msm/nand_partitions.c + * + * Code to extract partition information from ATAG set up by the + * bootloader. + * + * Copyright (C) 2007 Google, Inc. + * Author: Brian Swetland + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include + +#include + +#ifdef CONFIG_MMC_MUST_PREVENT_WP_VIOLATION +#include +#endif + + +#define ATAG_MSM_PARTITION 0x4d534D70 + +struct msm_ptbl_entry { + char name[16]; + __u32 offset; + __u32 size; + __u32 flags; +}; + +#define MSM_MAX_PARTITIONS 32 + +static struct mtd_partition msm_nand_partitions[MSM_MAX_PARTITIONS]; +static char msm_nand_names[MSM_MAX_PARTITIONS * 16]; + +int emmc_partition_read_proc(char *page, char **start, off_t off, + int count, int *eof, void *data) +{ + struct mtd_partition *ptn = msm_nand_partitions; + char *p = page; + int i; + uint64_t offset; + uint64_t size; + + p += sprintf(p, "dev: size erasesize name\n"); + for (i = 0; i < MSM_MAX_PARTITIONS && ptn->name; i++, ptn++) { + offset = ptn->offset; + size = ptn->size; + p += sprintf(p, "mmcblk0p%llu: %08llx %08x \"%s\"\n", offset, size * 512, 512, ptn->name); + } + + return p - page; +} + +int get_partition_num_by_name(char *name) +{ + struct mtd_partition *ptn = msm_nand_partitions; + int i; + + for (i = 0; i < MSM_MAX_PARTITIONS && ptn->name; i++, ptn++) { + if (strcmp(ptn->name, name) == 0) + return ptn->offset; + } + return -1; +} +EXPORT_SYMBOL(get_partition_num_by_name); + +const char *get_partition_name_by_num(int partnum) +{ + struct mtd_partition *ptn = msm_nand_partitions; + int i; + + for (i = 0; i < MSM_MAX_PARTITIONS && ptn->name; i++, ptn++) { + if (ptn->offset == partnum) + return ptn->name; + } + return NULL; +} +EXPORT_SYMBOL(get_partition_name_by_num); + +extern char devlog_part[64]; + +static int __init parse_tag_msm_partition(const struct tag *tag) +{ + struct mtd_partition *ptn = msm_nand_partitions; + char *name = msm_nand_names; + struct msm_ptbl_entry *entry = (void *) &tag->u; + unsigned count, n; + unsigned have_kpanic = 0; + + count = (tag->hdr.size - 2) / + (sizeof(struct msm_ptbl_entry) / sizeof(__u32)); + + if (count > MSM_MAX_PARTITIONS) + count = MSM_MAX_PARTITIONS; + + for (n = 0; n < count; n++) { + memcpy(name, entry->name, 15); + name[15] = 0; + + if (!strcmp(name, "kpanic")) + have_kpanic = 1; + + ptn->name = name; + ptn->offset = entry->offset; + ptn->size = entry->size; + +#ifdef CONFIG_MMC_MUST_PREVENT_WP_VIOLATION + if (!strncmp(ptn->name, "system", 6)) + mmc_blk_set_wp_prevention_partno((int) ptn->offset); +#endif + + name += 16; + entry++; + ptn++; + } + +#ifdef CONFIG_VIRTUAL_KPANIC_PARTITION + if (!have_kpanic) { + int i; + uint64_t kpanic_off = 0; + + if (count == MSM_MAX_PARTITIONS) { + printk(KERN_ERR "Cannot create virtual 'kpanic' partition\n"); + goto out; + } + + for (i = 0; i < count; i++) { + ptn = &msm_nand_partitions[i]; + if (!strcmp(ptn->name, CONFIG_VIRTUAL_KPANIC_SRC)) { + ptn->size -= CONFIG_VIRTUAL_KPANIC_PSIZE; + kpanic_off = ptn->offset + ptn->size; + break; + } + } + if (i == count) { + printk(KERN_ERR "Partition %s not found\n", + CONFIG_VIRTUAL_KPANIC_SRC); + goto out; + } + + ptn = &msm_nand_partitions[count]; + ptn->name = "kpanic"; + ptn->offset = kpanic_off; + ptn->size = CONFIG_VIRTUAL_KPANIC_PSIZE; + + printk(KERN_INFO "Virtual mtd partition '%s' created @%llx (%llu)\n", + ptn->name, ptn->offset, ptn->size); + + count++; + } +out: +#endif + msm_nand_data.nr_parts = count; + msm_nand_data.parts = msm_nand_partitions; + + return 0; +} + +__tagtable(ATAG_MSM_PARTITION, parse_tag_msm_partition); diff --git a/pool/shard006/C/0119192_fast-usbserial.c b/pool/shard006/C/0119192_fast-usbserial.c new file mode 100644 index 0000000000000000000000000000000000000000..18595fb0e4f52ecf075bbc29e04e34d27d35a597 --- /dev/null +++ b/pool/shard006/C/0119192_fast-usbserial.c @@ -0,0 +1,203 @@ +/* Based on arduino-usbserial and LUFA. but made + * into a stand-alone LUFA subset and heavily modified + * by Urja Rannikko 2015. My modifications are under the LUFA + * License below. */ + +/* + LUFA Library + Copyright (C) Dean Camera, 2010. + + dean [at] fourwalledcubicle [dot] com + www.fourwalledcubicle.com +*/ + +/* + Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + The author disclaim all warranties with regard to this + software, including all implied warranties of merchantability + and fitness. In no event shall the author be liable for any + special, indirect or consequential damages or any damages + whatsoever resulting from loss of use, data or profits, whether + in an action of contract, negligence or other tortious action, + arising out of or in connection with the use or performance of + this software. +*/ + +#include "main.h" +#include "fast-usbserial.h" +/* We implement the old uart.h API for libfrser */ +#include "uart.h" + + +USB_ClassInfo_CDC_Device_t VirtualSerial_CDC_Interface; + +static uint8_t usb_rxpacket_leftb = 0; +static uint8_t usb_txpacket_leftb = 0; + +static void usb_process(void) { + Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP); + do { + if (Endpoint_IsSETUPReceived()) + USB_Device_ProcessControlRequest(); + } while (USB_DeviceState != DEVICE_STATE_Configured); +} + + +uint8_t uart_recv(void) { + do { + if (usb_rxpacket_leftb) { + uint8_t d; + Endpoint_SelectEndpoint(CDC_RX_EPNUM); + d = Endpoint_Read_Byte(); + usb_rxpacket_leftb--; + if (!usb_rxpacket_leftb) + Endpoint_ClearOUT(); + return d; + } + usb_process(); + usb_rxpacket_leftb = CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface); + if ((!usb_rxpacket_leftb)&&(usb_txpacket_leftb)) { + Endpoint_SelectEndpoint(CDC_TX_EPNUM); + Endpoint_ClearIN(); /* Go data, GO. */ + usb_txpacket_leftb = 0; + } + } while (1); +} + +void uart_send(uint8_t d) { + do { + if (usb_txpacket_leftb) { + Endpoint_SelectEndpoint(CDC_TX_EPNUM); + Endpoint_Write_Byte(d); + usb_txpacket_leftb--; + if (usb_txpacket_leftb == 1) { + Endpoint_ClearIN(); /* Go data, GO. */ + usb_txpacket_leftb = 0; + } + return; + } + usb_process(); + if (CDC_Device_SendByte_Prep(&VirtualSerial_CDC_Interface) == 0) + usb_txpacket_leftb = CDC_IN_EPSIZE; + } while (1); +} + +uint8_t uart_isdata(void) { + if (usb_rxpacket_leftb) { + Endpoint_SelectEndpoint(CDC_RX_EPNUM); + return usb_rxpacket_leftb; + } + usb_process(); + usb_rxpacket_leftb = CDC_Device_BytesReceived(&VirtualSerial_CDC_Interface); + return usb_rxpacket_leftb; +} + +uint8_t uart_send_getfree(void) { + if (usb_txpacket_leftb) { + Endpoint_SelectEndpoint(CDC_TX_EPNUM); + return usb_txpacket_leftb-1; + } + do { + usb_process(); + if (CDC_Device_SendByte_Prep(&VirtualSerial_CDC_Interface) == 0) { + usb_txpacket_leftb = CDC_IN_EPSIZE; + return usb_txpacket_leftb-1; + } + } while (1); +} + +void uart_wait_txdone(void) { + if (usb_txpacket_leftb) { + Endpoint_SelectEndpoint(CDC_TX_EPNUM); + Endpoint_ClearIN(); /* Go data, GO. */ + usb_txpacket_leftb = 0; + } +} + +/* These are to be used very responsibly by code that knows what its doing. */ +void uart_recv_ctrl_cnt(uint8_t b) { + usb_rxpacket_leftb -= b; + if (!usb_rxpacket_leftb) + Endpoint_ClearOUT(); +} + +void uart_send_ctrl_cnt(uint8_t b) { + usb_txpacket_leftb -= b; + if (usb_txpacket_leftb == 1) { + Endpoint_ClearIN(); /* Go data, GO. */ + usb_txpacket_leftb = 0; + } +} + + +/** Configures the board hardware and chip peripherals for the demo's functionality. */ +void SetupHardware(void) +{ + /* Disable watchdog if enabled by bootloader/fuses */ + MCUSR &= ~(1 << WDRF); + wdt_disable(); + + /* Hardware Initialization */ + USB_Init(); + +} + +/** Event handler for the library USB Configuration Changed event. */ +void EVENT_USB_Device_ConfigurationChanged(void) +{ + CDC_Device_ConfigureEndpoints(&VirtualSerial_CDC_Interface); +} + +/** Event handler for the library USB Unhandled Control Request event. */ +void EVENT_USB_Device_UnhandledControlRequest(void) +{ + CDC_Device_ProcessControlRequest(&VirtualSerial_CDC_Interface); +} + + +static void bl_1200_check(void) { +#if (defined __AVR_ATmega16U4__) || (defined __AVR_ATmega32U4__) + // We check DTR state to determine if host port is open (bit 0 of lineState). + if ((VirtualSerial_CDC_Interface.State.LineEncoding.BaudRateBPS == 1200) && (VirtualSerial_CDC_Interface.State.ControlLineStates.HostToDevice & 0x01) == 0) + { + /* This has to be the stupidest thing i've heard, but we'll live with it, i guess. *sigh* */ + /* Btw it means: do not use more than 1792 bytes of .data+.bss or 766 bytes of stack. geeze. */ + *(uint16_t *)0x0800 = 0x7777; + wdt_enable(WDTO_120MS); + } + else + { + wdt_disable(); + wdt_reset(); + *(uint16_t *)0x0800 = 0x0; + } +#endif +} + +/** Event handler for the CDC Class driver Line Encoding Changed event. + * + * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced + */ +void EVENT_CDC_Device_LineEncodingChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo) +{ + bl_1200_check(); +} + +/** Event handler for the CDC Class driver Host-to-Device Line Encoding Changed event. + * + * \param[in] CDCInterfaceInfo Pointer to the CDC class interface configuration structure being referenced + */ +void EVENT_CDC_Device_ControLineStateChanged(USB_ClassInfo_CDC_Device_t* const CDCInterfaceInfo) +{ + bl_1200_check(); +} diff --git a/pool/shard006/C/0119193_common_func.c b/pool/shard006/C/0119193_common_func.c new file mode 100644 index 0000000000000000000000000000000000000000..6899a73d221c4c6be66694fbbda044cb7361839c --- /dev/null +++ b/pool/shard006/C/0119193_common_func.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "common_func.h" + +int getFileContent(const char *filename, char **buff, int64_t *file_size) +{ + int fd; + + fd = open(filename, O_RDONLY); + if (fd < 0) + { + *buff = NULL; + *file_size = 0; + return errno != 0 ? errno : ENOENT; + } + + if ((*file_size=lseek(fd, 0, SEEK_END)) < 0) + { + *buff = NULL; + *file_size = 0; + close(fd); + return errno != 0 ? errno : EIO; + } + + *buff = (char *)malloc(*file_size + 1); + if (*buff == NULL) + { + *file_size = 0; + close(fd); + + return errno != 0 ? errno : ENOMEM; + } + + if (lseek(fd, 0, SEEK_SET) < 0) + { + *buff = NULL; + *file_size = 0; + close(fd); + return errno != 0 ? errno : EIO; + } + if (read(fd, *buff, *file_size) != *file_size) + { + free(*buff); + *buff = NULL; + *file_size = 0; + close(fd); + return errno != 0 ? errno : EIO; + } + + (*buff)[*file_size] = '\0'; + close(fd); + + return 0; +} + diff --git a/pool/shard006/C/0119194_cctables.c b/pool/shard006/C/0119194_cctables.c new file mode 100644 index 0000000000000000000000000000000000000000..65f3f52a719cb9507ed1a29fc04d159489dad21f --- /dev/null +++ b/pool/shard006/C/0119194_cctables.c @@ -0,0 +1,203 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + + +/** + * Class diagram: + * + * (singleton) + * /---\ 1 * /-----\ + * |Map|----------|Table| + * \---/ \-----/ + * |1 + * | + * | + * /---------\ 1 1 /------\ + * |Container|------|Worker| + * \---------/ \------/ + * + * A worker (PThread or process) has a local container which maintains allocated + * tables. Tables are allocated in fixed order because all workers execute the + * same deterministic code. + * Before a table is allocated, the container checks the global Map structure + * whether or not it the table with this index was already allocated (remember + * the fixed order). If not allocates it, adds it to the map and the container. + * Otherwise, it reads the existing table from the Map and adds it to the + * local container. + * + * A function pointer in allocator switches the allocator to a inter-process + * allocator when tables are create or when values are added to the tables. + * An rw mutex takes care of mutual exclusion (it is initialized as + * inter-process mutex depending on the value of shared). + */ + +static const size_t MAX_TABLES = 500; + + + +struct cct_map_s { + ticket_rwlock_t rw_lock; + bool shared; // shared or private allocation + value_table_t *table; // list of tables (pointers) + set_ll_allocator_t *set_allocator; +}; + + +cct_map_t * +cct_create_map (bool shared) +{ + RTswitchAlloc (shared); // global shared-memory allocation? + cct_map_t *map = RTmalloc(sizeof(cct_map_t)); + map->shared = shared; + map->table = RTmallocZero (sizeof(value_table_t[MAX_TABLES])); + RTswitchAlloc (false); + + rwticket_init (&map->rw_lock); + + map->set_allocator = set_ll_init_allocator(shared); + return map; +} + + +/** +\typedef a chunk table +use malloc +*/ +struct value_table_s { + set_ll_t *string_set; + cct_map_t *map; +}; + +size_t +cct_print_stats (log_t log, log_t details, lts_type_t ltstype, cct_map_t *map) +{ + size_t i = 0; + size_t total = 0; + total += set_ll_print_alloc_stats(log, map->set_allocator); + while (map->table[i] != NULL) { + char *name = lts_type_get_type(ltstype, i); + total += set_ll_print_stats(details, map->table[i]->string_set, name); + i++; + } + Warning (log, "Total memory used for chunk indexing: %zuMB", total >> 20); + return total; +} + +static value_index_t +put_chunk (value_table_t vt,chunk item) +{ + return set_ll_put(vt->string_set, item.data, item.len); +} + +static void +put_at_chunk (value_table_t vt,chunk item,value_index_t pos) +{ + HREbarrier (HREglobal()); + rwticket_wrlock (&vt->map->rw_lock); + set_ll_install(vt->string_set, item.data, item.len, pos); + rwticket_wrunlock (&vt->map->rw_lock); + HREbarrier (HREglobal()); +} + +static chunk +get_chunk (value_table_t vt,value_index_t idx) +{ + int len; + const char *data = set_ll_get(vt->string_set, (int)idx, &len); + return chunk_ld(len, (char *)data); +} + +static int +get_count (value_table_t vt) +{ + return set_ll_count(vt->string_set); +} + +struct table_iterator_s { + set_ll_iterator_t *it; +}; + +static chunk it_next (table_iterator_t it){ + chunk c; + c.data = set_ll_iterator_next (it->it, (int *)&c.len); + return c; +} + +static int it_has_next (table_iterator_t it){ + return set_ll_iterator_has_next (it->it); +} + +static table_iterator_t +iterator_create (value_table_t vt) { + table_iterator_t it = ITcreateBase (sizeof (struct table_iterator_s)); + it->it = set_ll_iterator (vt->string_set); + ITnextSet (it, it_next); + IThasNextSet (it, it_has_next); + return it; +} + + +struct table_factory_s { + size_t map_index; + cct_map_t *map; //shared +}; + +static value_table_t +cct_create_vt (table_factory_t tf, int index) +{ + cct_map_t *map = tf->map; + RTswitchAlloc (map->shared); + value_table_t vt = VTcreateBase ("Concurrent chunk map", + sizeof(struct value_table_s)); + RTswitchAlloc (false); + VTdestroySet(vt,NULL); + VTputChunkSet(vt,put_chunk); + VTputAtChunkSet(vt,put_at_chunk); + VTgetChunkSet(vt,get_chunk); + VTgetCountSet(vt,get_count); + VTiteratorSet(vt,iterator_create); + vt->string_set = set_ll_create (map->set_allocator, index); + vt->map = map; + return vt; +} + +static value_table_t +new_map (table_factory_t tf) +{ + cct_map_t *map = tf->map; + rwticket_rdlock (&map->rw_lock); + if (tf->map_index >= MAX_TABLES) + Abort("Chunk table limit reached: %zu.", MAX_TABLES); + rwticket_rdunlock (&map->rw_lock); + size_t index = tf->map_index++; + if (!map->table[index]) { + rwticket_wrlock (&map->rw_lock); + if (!map->table[index]) { + map->table[index] = cct_create_vt (tf, index); + } + rwticket_wrunlock (&map->rw_lock); + } + return map->table[index]; +} + + +table_factory_t +cct_create_table_factory (cct_map_t *map) +{ + // can be locally allocated + table_factory_t factory = TFcreateBase (sizeof(struct table_factory_s)); + TFnewTableSet (factory, new_map); + factory->map_index = 0; + factory->map = map; + return factory; +} + diff --git a/pool/shard006/C/0119200_CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17.c b/pool/shard006/C/0119200_CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17.c new file mode 100644 index 0000000000000000000000000000000000000000..a609cde4f7edb93c3209bb9b0167126c752df1d2 --- /dev/null +++ b/pool/shard006/C/0119200_CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17.c @@ -0,0 +1,116 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17.c +Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml +Template File: sources-sink-17.tmpl.c +*/ +/* + * @description + * CWE: 124 Buffer Underwrite + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sink: loop + * BadSink : Copy string to data using a loop + * Flow Variant: 17 Control flow: for loops + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17_bad() +{ + int i; + wchar_t * data; + wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + for(i = 0; i < 1; i++) + { + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + { + size_t i; + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */ +static void goodG2B() +{ + int h; + wchar_t * data; + wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + for(h = 0; h < 1; h++) + { + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + { + size_t i; + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + } +} + +void CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17_good() +{ + goodG2B(); +} + +#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()..."); + CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE124_Buffer_Underwrite__wchar_t_alloca_loop_17_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0119201_vswscanf.c b/pool/shard006/C/0119201_vswscanf.c new file mode 100644 index 0000000000000000000000000000000000000000..9bad55177261d1817e3653fcd9e69855464a8b0c --- /dev/null +++ b/pool/shard006/C/0119201_vswscanf.c @@ -0,0 +1,81 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Portions copyright (c) 1999, 2000 + * Intel Corporation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * + * This product includes software developed by the University of + * California, Berkeley, Intel Corporation, and its contributors. + * + * 4. Neither the name of University, Intel Corporation, or their respective + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS, INTEL CORPORATION 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 REGENTS, + * INTEL CORPORATION 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. + * + */ + +// wide character version +// efi/lib/libc/wchar/vswscanf.c + +#include +#include +#include + +static int +weofread __P((void *, char *, int)); + +/* ARGSUSED */ +static int +weofread(cookie, buf, len) + void *cookie; + char *buf; + int len; +{ + + return (0); +} + +int +vswscanf(str, fmt, ap) + const wchar_t *str; + const wchar_t *fmt; + _BSD_VA_LIST_ ap; +{ + FILE f; + + f._file = -1; + f._flags = __SRD; + f._bf._base = f._p = (unsigned char *)str; + f._bf._size = f._r = (int)wcslen(str)*sizeof(wchar_t); + f._read = weofread; + f._ub._base = NULL; + f._lb._base = NULL; + return (__svfwscanf(&f, fmt, ap)); +} diff --git a/pool/shard006/C/0119206_http.c b/pool/shard006/C/0119206_http.c new file mode 100644 index 0000000000000000000000000000000000000000..585082a87180dfe5785c6ffe6d6f56c182da4619 --- /dev/null +++ b/pool/shard006/C/0119206_http.c @@ -0,0 +1,237 @@ +/* + * Copyright (C) 2015 Adrien Vergé + * + * 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 . + */ + +#include "http.h" +#include "log.h" +#include "ssl.h" + +#define BUFSZ 0x8000 + +/* + * Sends data to the HTTP server. + * + * @param[in] request the data to send to the server + * @return 1 in case of success + * < 0 in case of error + */ +int http_send(struct tunnel *tunnel, const char *request, ...) +{ + va_list args; + char buffer[BUFSZ]; + int length; + int n = 0; + + va_start(args, request); + length = vsnprintf(buffer, BUFSZ, request, args); + va_end(args); + + if (length < 0) + return ERR_HTTP_INVALID; + else if (length == BUFSZ) + return ERR_HTTP_TOO_LONG; + + while (n == 0) + n = safe_ssl_write(tunnel->ssl_handle, (uint8_t *) buffer, + length); + if (n < 0) { + log_debug("Error writing to SSL connection (%s).\n", + err_ssl_str(n)); + return ERR_HTTP_SSL; + } + + return 1; +} + +/* + * Receives data from the HTTP server. + * + * @param[out] response if not NULL, this pointer is set to reference + * the new allocated buffer containing the data + * sent by the server + * @return 1 in case of success + * < 0 in case of error + */ +int http_receive(struct tunnel *tunnel, char **response) +{ + char *buffer, *res; + int n = 0; + int bytes_read = 0; + + buffer = malloc(BUFSZ); + if (buffer == NULL) + return ERR_HTTP_NO_MEM; + + do { + n = safe_ssl_read(tunnel->ssl_handle, + (uint8_t *) buffer + bytes_read, + BUFSZ - 1 - bytes_read); + if (n > 0) { + bytes_read += n; + + if (bytes_read >= 4 + && !memcmp(&buffer[bytes_read - 4], "\r\n\r\n", 4)) + break; + + if (bytes_read == BUFSZ - 1) { + log_warn("Response too big\n"); + free(buffer); + return ERR_HTTP_SSL; + } + } + } while (n >= 0); + + if (n < 0) { + log_debug("Error reading from SSL connection (%s).\n", + err_ssl_str(n)); + free(buffer); + return ERR_HTTP_SSL; + } + + if (response == NULL) { + free(buffer); + return 1; + } + + res = realloc(buffer, bytes_read + 1); + if (res == NULL) { + free(buffer); + return ERR_HTTP_NO_MEM; + } + res[bytes_read] = '\0'; + + *response = res; + return 1; +} + +static int do_http_request(struct tunnel *tunnel, const char *method, + const char *uri, const char *data, char **response) +{ + int ret; + char template[] = + "%s %s HTTP/1.1\r\n" + "Host: %s:%d\r\n" + "User-Agent: Mozilla/5.0 SV1\r\n" + "Accept: text/plain\r\n" + "Accept-Encoding: identify\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n" + "Cookie: %s\r\n" + "Content-Length: %d\r\n" + "\r\n%s"; + + ret = http_send(tunnel, template, method, uri, + tunnel->config->gateway_host, + tunnel->config->gateway_port, tunnel->config->cookie, + strlen(data), data); + if (ret != 1) + return ret; + + return http_receive(tunnel, response); +} +/* + * Sends and receives data from the HTTP server. + * + * @param[out] response if not NULL, this pointer is set to reference + * the new allocated buffer containing the data + * sent by the server + * @return 1 in case of success + * < 0 in case of error + */ +static int http_request(struct tunnel *tunnel, const char *method, + const char *uri, const char *data, char **response) +{ + int ret = do_http_request (tunnel, method, uri, data, response); + + if (ret == ERR_HTTP_SSL) { + ssl_connect (tunnel); + ret = do_http_request (tunnel, method, uri, data, response); + } + + if (ret != 1) + log_warn("Error issuing %s request\n", uri); + + return ret; +} + +/* + * Authenticates to gateway by sending username and password. + * + * @return 1 in case of success + * < 0 in case of error + */ +int auth_log_in(struct tunnel *tunnel) +{ + int ret; + char data[256]; + char *res, *line, *end; + + tunnel->config->cookie[0] = '\0'; + + snprintf(data, 256, "username=%s&credential=%s&realm=&ajax=1" + "&redir=%%2Fremote%%2Findex&just_logged_in=1", + tunnel->config->username, tunnel->config->password); + + ret = http_request(tunnel, "POST", "/remote/logincheck", data, &res); + if (ret != 1) + return ret; + + if (strncmp(res, "HTTP/1.1 200 OK\r\n", 17)) { + ret = ERR_HTTP_BAD_RES_CODE; + goto end; + } + + ret = ERR_HTTP_NO_COOKIE; + // Look for cookie in the headers + line = strtok(res, "\r\n\r\n"); + while (line != NULL) { + if (strncmp(line, "Set-Cookie: SVPNCOOKIE=", 23) == 0) { + line = &line[12]; + if (line[11] == ';' || line[11] == '\0') { + log_debug("Empty cookie.\n"); + } else { + end = strstr(line, ";"); + if (end != NULL) + end[0] = '\0'; + strncpy(tunnel->config->cookie, line, + COOKIE_SIZE); + ret = 1; // success + goto end; + } + } else if (strstr(line, "permission_denied denied") || + strstr(line, "Permission denied")) { + ret = ERR_HTTP_PERMISSION; + goto end; + } + line = strtok(NULL, "\r\n"); + } +end: + free(res); + return ret; +} + +int auth_log_out(struct tunnel *tunnel) +{ + return http_request(tunnel, "GET", "/remote/logout", "", NULL); +} + +int auth_request_vpn_allocation(struct tunnel *tunnel) +{ + int ret = http_request(tunnel, "GET", "/remote/index", "", NULL); + if (ret != 1) + return ret; + + return http_request(tunnel, "GET", "/remote/fortisslvpn", "", NULL); +} diff --git a/pool/shard006/C/0119207_pgtable-hash64.c b/pool/shard006/C/0119207_pgtable-hash64.c new file mode 100644 index 0000000000000000000000000000000000000000..188b4107584d2a741645aac48382bffadbfb4116 --- /dev/null +++ b/pool/shard006/C/0119207_pgtable-hash64.c @@ -0,0 +1,457 @@ +/* + * Copyright 2005, Paul Mackerras, IBM Corporation. + * Copyright 2009, Benjamin Herrenschmidt, IBM Corporation. + * Copyright 2015-2016, Aneesh Kumar K.V, IBM Corporation. + * + * 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 +#include +#include + +#include +#include +#include +#include +#include + +#include "mmu_decl.h" + +#define CREATE_TRACE_POINTS +#include + +#ifdef CONFIG_SPARSEMEM_VMEMMAP +/* + * vmemmap is the starting address of the virtual address space where + * struct pages are allocated for all possible PFNs present on the system + * including holes and bad memory (hence sparse). These virtual struct + * pages are stored in sequence in this virtual address space irrespective + * of the fact whether the corresponding PFN is valid or not. This achieves + * constant relationship between address of struct page and its PFN. + * + * During boot or memory hotplug operation when a new memory section is + * added, physical memory allocation (including hash table bolting) will + * be performed for the set of struct pages which are part of the memory + * section. This saves memory by not allocating struct pages for PFNs + * which are not valid. + * + * ---------------------------------------------- + * | PHYSICAL ALLOCATION OF VIRTUAL STRUCT PAGES| + * ---------------------------------------------- + * + * f000000000000000 c000000000000000 + * vmemmap +--------------+ +--------------+ + * + | page struct | +--------------> | page struct | + * | +--------------+ +--------------+ + * | | page struct | +--------------> | page struct | + * | +--------------+ | +--------------+ + * | | page struct | + +------> | page struct | + * | +--------------+ | +--------------+ + * | | page struct | | +--> | page struct | + * | +--------------+ | | +--------------+ + * | | page struct | | | + * | +--------------+ | | + * | | page struct | | | + * | +--------------+ | | + * | | page struct | | | + * | +--------------+ | | + * | | page struct | | | + * | +--------------+ | | + * | | page struct | +-------+ | + * | +--------------+ | + * | | page struct | +-----------+ + * | +--------------+ + * | | page struct | No mapping + * | +--------------+ + * | | page struct | No mapping + * v +--------------+ + * + * ----------------------------------------- + * | RELATION BETWEEN STRUCT PAGES AND PFNS| + * ----------------------------------------- + * + * vmemmap +--------------+ +---------------+ + * + | page struct | +-------------> | PFN | + * | +--------------+ +---------------+ + * | | page struct | +-------------> | PFN | + * | +--------------+ +---------------+ + * | | page struct | +-------------> | PFN | + * | +--------------+ +---------------+ + * | | page struct | +-------------> | PFN | + * | +--------------+ +---------------+ + * | | | + * | +--------------+ + * | | | + * | +--------------+ + * | | | + * | +--------------+ +---------------+ + * | | page struct | +-------------> | PFN | + * | +--------------+ +---------------+ + * | | | + * | +--------------+ + * | | | + * | +--------------+ +---------------+ + * | | page struct | +-------------> | PFN | + * | +--------------+ +---------------+ + * | | page struct | +-------------> | PFN | + * v +--------------+ +---------------+ + */ +/* + * On hash-based CPUs, the vmemmap is bolted in the hash table. + * + */ +int __meminit hash__vmemmap_create_mapping(unsigned long start, + unsigned long page_size, + unsigned long phys) +{ + int rc = htab_bolt_mapping(start, start + page_size, phys, + pgprot_val(PAGE_KERNEL), + mmu_vmemmap_psize, mmu_kernel_ssize); + if (rc < 0) { + int rc2 = htab_remove_mapping(start, start + page_size, + mmu_vmemmap_psize, + mmu_kernel_ssize); + BUG_ON(rc2 && (rc2 != -ENOENT)); + } + return rc; +} + +#ifdef CONFIG_MEMORY_HOTPLUG +void hash__vmemmap_remove_mapping(unsigned long start, + unsigned long page_size) +{ + int rc = htab_remove_mapping(start, start + page_size, + mmu_vmemmap_psize, + mmu_kernel_ssize); + BUG_ON((rc < 0) && (rc != -ENOENT)); + WARN_ON(rc == -ENOENT); +} +#endif +#endif /* CONFIG_SPARSEMEM_VMEMMAP */ + +/* + * map_kernel_page currently only called by __ioremap + * map_kernel_page adds an entry to the ioremap page table + * and adds an entry to the HPT, possibly bolting it + */ +int hash__map_kernel_page(unsigned long ea, unsigned long pa, unsigned long flags) +{ + pgd_t *pgdp; + pud_t *pudp; + pmd_t *pmdp; + pte_t *ptep; + + BUILD_BUG_ON(TASK_SIZE_USER64 > H_PGTABLE_RANGE); + if (slab_is_available()) { + pgdp = pgd_offset_k(ea); + pudp = pud_alloc(&init_mm, pgdp, ea); + if (!pudp) + return -ENOMEM; + pmdp = pmd_alloc(&init_mm, pudp, ea); + if (!pmdp) + return -ENOMEM; + ptep = pte_alloc_kernel(pmdp, ea); + if (!ptep) + return -ENOMEM; + set_pte_at(&init_mm, ea, ptep, pfn_pte(pa >> PAGE_SHIFT, + __pgprot(flags))); + } else { + /* + * If the mm subsystem is not fully up, we cannot create a + * linux page table entry for this mapping. Simply bolt an + * entry in the hardware page table. + * + */ + if (htab_bolt_mapping(ea, ea + PAGE_SIZE, pa, flags, + mmu_io_psize, mmu_kernel_ssize)) { + printk(KERN_ERR "Failed to do bolted mapping IO " + "memory at %016lx !\n", pa); + return -ENOMEM; + } + } + + smp_wmb(); + return 0; +} + +#ifdef CONFIG_TRANSPARENT_HUGEPAGE + +unsigned long hash__pmd_hugepage_update(struct mm_struct *mm, unsigned long addr, + pmd_t *pmdp, unsigned long clr, + unsigned long set) +{ + __be64 old_be, tmp; + unsigned long old; + +#ifdef CONFIG_DEBUG_VM + WARN_ON(!hash__pmd_trans_huge(*pmdp) && !pmd_devmap(*pmdp)); + assert_spin_locked(&mm->page_table_lock); +#endif + + __asm__ __volatile__( + "1: ldarx %0,0,%3\n\ + and. %1,%0,%6\n\ + bne- 1b \n\ + andc %1,%0,%4 \n\ + or %1,%1,%7\n\ + stdcx. %1,0,%3 \n\ + bne- 1b" + : "=&r" (old_be), "=&r" (tmp), "=m" (*pmdp) + : "r" (pmdp), "r" (cpu_to_be64(clr)), "m" (*pmdp), + "r" (cpu_to_be64(H_PAGE_BUSY)), "r" (cpu_to_be64(set)) + : "cc" ); + + old = be64_to_cpu(old_be); + + trace_hugepage_update(addr, old, clr, set); + if (old & H_PAGE_HASHPTE) + hpte_do_hugepage_flush(mm, addr, pmdp, old); + return old; +} + +pmd_t hash__pmdp_collapse_flush(struct vm_area_struct *vma, unsigned long address, + pmd_t *pmdp) +{ + pmd_t pmd; + + VM_BUG_ON(address & ~HPAGE_PMD_MASK); + VM_BUG_ON(pmd_trans_huge(*pmdp)); + VM_BUG_ON(pmd_devmap(*pmdp)); + + pmd = *pmdp; + pmd_clear(pmdp); + /* + * Wait for all pending hash_page to finish. This is needed + * in case of subpage collapse. When we collapse normal pages + * to hugepage, we first clear the pmd, then invalidate all + * the PTE entries. The assumption here is that any low level + * page fault will see a none pmd and take the slow path that + * will wait on mmap_sem. But we could very well be in a + * hash_page with local ptep pointer value. Such a hash page + * can result in adding new HPTE entries for normal subpages. + * That means we could be modifying the page content as we + * copy them to a huge page. So wait for parallel hash_page + * to finish before invalidating HPTE entries. We can do this + * by sending an IPI to all the cpus and executing a dummy + * function there. + */ + kick_all_cpus_sync(); + /* + * Now invalidate the hpte entries in the range + * covered by pmd. This make sure we take a + * fault and will find the pmd as none, which will + * result in a major fault which takes mmap_sem and + * hence wait for collapse to complete. Without this + * the __collapse_huge_page_copy can result in copying + * the old content. + */ + flush_tlb_pmd_range(vma->vm_mm, &pmd, address); + return pmd; +} + +/* + * We want to put the pgtable in pmd and use pgtable for tracking + * the base page size hptes + */ +void hash__pgtable_trans_huge_deposit(struct mm_struct *mm, pmd_t *pmdp, + pgtable_t pgtable) +{ + pgtable_t *pgtable_slot; + assert_spin_locked(&mm->page_table_lock); + /* + * we store the pgtable in the second half of PMD + */ + pgtable_slot = (pgtable_t *)pmdp + PTRS_PER_PMD; + *pgtable_slot = pgtable; + /* + * expose the deposited pgtable to other cpus. + * before we set the hugepage PTE at pmd level + * hash fault code looks at the deposted pgtable + * to store hash index values. + */ + smp_wmb(); +} + +pgtable_t hash__pgtable_trans_huge_withdraw(struct mm_struct *mm, pmd_t *pmdp) +{ + pgtable_t pgtable; + pgtable_t *pgtable_slot; + + assert_spin_locked(&mm->page_table_lock); + pgtable_slot = (pgtable_t *)pmdp + PTRS_PER_PMD; + pgtable = *pgtable_slot; + /* + * Once we withdraw, mark the entry NULL. + */ + *pgtable_slot = NULL; + /* + * We store HPTE information in the deposited PTE fragment. + * zero out the content on withdraw. + */ + memset(pgtable, 0, PTE_FRAG_SIZE); + return pgtable; +} + +void hash__pmdp_huge_split_prepare(struct vm_area_struct *vma, + unsigned long address, pmd_t *pmdp) +{ + VM_BUG_ON(address & ~HPAGE_PMD_MASK); + VM_BUG_ON(REGION_ID(address) != USER_REGION_ID); + VM_BUG_ON(pmd_devmap(*pmdp)); + + /* + * We can't mark the pmd none here, because that will cause a race + * against exit_mmap. We need to continue mark pmd TRANS HUGE, while + * we spilt, but at the same time we wan't rest of the ppc64 code + * not to insert hash pte on this, because we will be modifying + * the deposited pgtable in the caller of this function. Hence + * clear the _PAGE_USER so that we move the fault handling to + * higher level function and that will serialize against ptl. + * We need to flush existing hash pte entries here even though, + * the translation is still valid, because we will withdraw + * pgtable_t after this. + */ + pmd_hugepage_update(vma->vm_mm, address, pmdp, 0, _PAGE_PRIVILEGED); +} + +/* + * A linux hugepage PMD was changed and the corresponding hash table entries + * neesd to be flushed. + */ +void hpte_do_hugepage_flush(struct mm_struct *mm, unsigned long addr, + pmd_t *pmdp, unsigned long old_pmd) +{ + int ssize; + unsigned int psize; + unsigned long vsid; + unsigned long flags = 0; + const struct cpumask *tmp; + + /* get the base page size,vsid and segment size */ +#ifdef CONFIG_DEBUG_VM + psize = get_slice_psize(mm, addr); + BUG_ON(psize == MMU_PAGE_16M); +#endif + if (old_pmd & H_PAGE_COMBO) + psize = MMU_PAGE_4K; + else + psize = MMU_PAGE_64K; + + if (!is_kernel_addr(addr)) { + ssize = user_segment_size(addr); + vsid = get_vsid(mm->context.id, addr, ssize); + WARN_ON(vsid == 0); + } else { + vsid = get_kernel_vsid(addr, mmu_kernel_ssize); + ssize = mmu_kernel_ssize; + } + + tmp = cpumask_of(smp_processor_id()); + if (cpumask_equal(mm_cpumask(mm), tmp)) + flags |= HPTE_LOCAL_UPDATE; + + return flush_hash_hugepage(vsid, addr, pmdp, psize, ssize, flags); +} + +pmd_t hash__pmdp_huge_get_and_clear(struct mm_struct *mm, + unsigned long addr, pmd_t *pmdp) +{ + pmd_t old_pmd; + pgtable_t pgtable; + unsigned long old; + pgtable_t *pgtable_slot; + + old = pmd_hugepage_update(mm, addr, pmdp, ~0UL, 0); + old_pmd = __pmd(old); + /* + * We have pmd == none and we are holding page_table_lock. + * So we can safely go and clear the pgtable hash + * index info. + */ + pgtable_slot = (pgtable_t *)pmdp + PTRS_PER_PMD; + pgtable = *pgtable_slot; + /* + * Let's zero out old valid and hash index details + * hash fault look at them. + */ + memset(pgtable, 0, PTE_FRAG_SIZE); + /* + * Serialize against find_linux_pte_or_hugepte which does lock-less + * lookup in page tables with local interrupts disabled. For huge pages + * it casts pmd_t to pte_t. Since format of pte_t is different from + * pmd_t we want to prevent transit from pmd pointing to page table + * to pmd pointing to huge page (and back) while interrupts are disabled. + * We clear pmd to possibly replace it with page table pointer in + * different code paths. So make sure we wait for the parallel + * find_linux_pte_or_hugepage to finish. + */ + kick_all_cpus_sync(); + return old_pmd; +} + +int hash__has_transparent_hugepage(void) +{ + + if (!mmu_has_feature(MMU_FTR_16M_PAGE)) + return 0; + /* + * We support THP only if PMD_SIZE is 16MB. + */ + if (mmu_psize_defs[MMU_PAGE_16M].shift != PMD_SHIFT) + return 0; + /* + * We need to make sure that we support 16MB hugepage in a segement + * with base page size 64K or 4K. We only enable THP with a PAGE_SIZE + * of 64K. + */ + /* + * If we have 64K HPTE, we will be using that by default + */ + if (mmu_psize_defs[MMU_PAGE_64K].shift && + (mmu_psize_defs[MMU_PAGE_64K].penc[MMU_PAGE_16M] == -1)) + return 0; + /* + * Ok we only have 4K HPTE + */ + if (mmu_psize_defs[MMU_PAGE_4K].penc[MMU_PAGE_16M] == -1) + return 0; + + return 1; +} +#endif /* CONFIG_TRANSPARENT_HUGEPAGE */ + +#ifdef CONFIG_STRICT_KERNEL_RWX +void hash__mark_rodata_ro(void) +{ + unsigned long start = (unsigned long)_stext; + unsigned long end = (unsigned long)__init_begin; + unsigned long idx; + unsigned int step, shift; + unsigned long newpp = PP_RXXX; + + shift = mmu_psize_defs[mmu_linear_psize].shift; + step = 1 << shift; + + start = ((start + step - 1) >> shift) << shift; + end = (end >> shift) << shift; + + pr_devel("marking ro start %lx, end %lx, step %x\n", + start, end, step); + + if (start == end) { + pr_warn("could not set rodata ro, relocate the start" + " of the kernel to a 0x%x boundary\n", step); + return; + } + + for (idx = start; idx < end; idx += step) + /* Not sure if we can do much with the return value */ + mmu_hash_ops.hpte_updateboltedpp(newpp, idx, mmu_linear_psize, + mmu_kernel_ssize); + +} +#endif diff --git a/pool/shard006/C/0119211_e_ilogbl.c b/pool/shard006/C/0119211_e_ilogbl.c new file mode 100644 index 0000000000000000000000000000000000000000..4088238f3043982d3a0828115de62d3823d79bbf --- /dev/null +++ b/pool/shard006/C/0119211_e_ilogbl.c @@ -0,0 +1,70 @@ +/* s_ilogbl.c -- long double version of s_ilogb.c. + * Conversion to IEEE quad long double by Jakub Jelinek, jj@ultra.linux.cz. + */ + +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#if defined(LIBM_SCCS) && !defined(lint) +static char rcsid[] = "$NetBSD: $"; +#endif + +/* ilogbl(long double x) + * return the binary exponent of non-zero x + * ilogbl(0) = FP_ILOGB0 + * ilogbl(NaN) = FP_ILOGBNAN (no signal is raised) + * ilogbl(+-Inf) = INT_MAX (no signal is raised) + */ + +#include +#include +#include +#include + +int __ieee754_ilogbl(long double x) +{ + int64_t hx, hxs; + int ix; + double xhi, xlo; + + ldbl_unpack (x, &xhi, &xlo); + EXTRACT_WORDS64 (hx, xhi); + hxs = hx; + hx &= 0x7fffffffffffffffLL; + if(hx <= 0x0010000000000000LL) { + if(hx==0) + return FP_ILOGB0; /* ilogbl(0) = FP_ILOGB0 */ + else /* subnormal x */ + for (ix = -1022, hx<<=11; hx>0; hx<<=1) ix -=1; + return ix; + } + else if (hx < 0x7ff0000000000000LL) + { + int hexp = (hx >> 52) - 0x3ff; + /* If the high part is a power of 2, and the low part is + nonzero with the opposite sign, the low part affects + the exponent. */ + if ((hx & 0x000fffffffffffffLL) == 0) + { + int64_t lx; + EXTRACT_WORDS64 (lx, xlo); + if ((hxs ^ lx) < 0 && (lx & 0x7fffffffffffffffLL) != 0) + hexp--; + } + return hexp; + } + else if (FP_ILOGBNAN != INT_MAX) { + /* ISO C99 requires ilogbl(+-Inf) == INT_MAX. */ + if (hx==0x7ff0000000000000LL) + return INT_MAX; + } + return FP_ILOGBNAN; +} diff --git a/pool/shard006/C/0119213_blasius.c b/pool/shard006/C/0119213_blasius.c new file mode 100644 index 0000000000000000000000000000000000000000..fd79c1de87176d8e640801dc11d1fca28ff7dd77 --- /dev/null +++ b/pool/shard006/C/0119213_blasius.c @@ -0,0 +1,76 @@ +// A simple GNU Scientific Library-based driver to compute the Blasius function +// via implicit integration. Licensed as GPL3 per GSL dependency. + +#include +#include +#include +#include +#include +#include +#include +#include + +// Blasius equation is f''' = - f * f'' / 2 producing a 3D first-order system +enum { ndim = 3 }; + +// Evaluate the Blasius function RHS +static inline int +forward (double eta, const double f[ndim], double df[ndim], void *params) +{ + (void) eta; + (void) params; + df[0] = f[1]; + df[1] = f[2]; + df[2] = - f[0] * f[2] / 2; + return GSL_SUCCESS; +} + +// Use \tilde{\eta} = -\eta to reverse evolution for increasing \tilde{\eta} +static inline int +backward (double eta, const double f[ndim], double df[ndim], void *params) +{ + const int status = forward(-eta, f, df, params); + for (int i = 0; i < ndim; ++i) df[i] = -df[i]; + return status; +} + +// Use GSL ODEIV2 to advance the solution outputting at regular intervals +int +main (int argc, const char *argv[]) +{ + // Process optional parameters from command line + const double etaf = (argc > 1) ? atof(argv[1]) : 13.6; + const double deleta = (argc > 2) ? atof(argv[2]) : 0.2; + const double tol = (argc > 3) ? atof(argv[3]) : GSL_DBL_EPSILON; + + // Define the problem, tolerance, and initial step size including + // performing forward or backwards integration from eta=0 initial condition + const gsl_odeiv2_system sys = {etaf > 0 ? forward : backward, 0L, ndim, 0L}; + + // Do /not/ blindly trust the tolerance as Blasius is notoriously difficult + gsl_odeiv2_driver* const d = gsl_odeiv2_driver_alloc_yp_new ( + &sys, gsl_odeiv2_step_rk8pd, tol*10, tol, 0.0); + + // Initial condition from equation 11 of http://arxiv.org/abs/1006.3888 + // Having a high-precision initial condition avoids shooting approaches + double eta = 0.0; + double f[ndim] = { 0.0, 0.0, 0.33205733621519630 }; + + // Integrate until either final time achieved or error encountered + int err = 0; + printf("%23s %23s %23s %23s\n", "eta", "f", "fp", "fpp"); + const double aetaf = fabs(etaf); + for (int niter = 0; eta < aetaf; ++niter) { // Odd, but avoids drift + err = gsl_odeiv2_driver_apply(d, &eta, GSL_MIN(aetaf, niter*deleta), f); + if (err) { + fprintf(stderr, "At %g encountered error %d: %s\n", + GSL_SIGN(etaf)*eta, err, gsl_strerror(err)); + break; + } + printf("%23.16e %23.16e %23.16e %23.16e\n", + GSL_SIGN(etaf)*eta, f[0], f[1], f[2]); + } + + gsl_odeiv2_driver_free (d); + return err; +} diff --git a/pool/shard006/C/0119216_XpExtVer.c b/pool/shard006/C/0119216_XpExtVer.c new file mode 100644 index 0000000000000000000000000000000000000000..d6fcbd0b16513d6e2dffe0cdcc0b0038b2c1f39e --- /dev/null +++ b/pool/shard006/C/0119216_XpExtVer.c @@ -0,0 +1,123 @@ +/****************************************************************************** + ****************************************************************************** + ** + ** (c) Copyright 1996 Hewlett-Packard Company + ** (c) Copyright 1996 International Business Machines Corp. + ** (c) Copyright 1996, Oracle and/or its affiliates. All rights reserved. + ** (c) Copyright 1996 Novell, Inc. + ** (c) Copyright 1996 Digital Equipment Corp. + ** (c) Copyright 1996 Fujitsu Limited + ** (c) Copyright 1996 Hitachi, 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 + ** 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. + ** + ** Except as contained in this notice, the names of the copyright holders shall + ** not be used in advertising or otherwise to promote the sale, use or other + ** dealings in this Software without prior written authorization from said + ** copyright holders. + ** + ****************************************************************************** + *****************************************************************************/ + +#define NEED_REPLIES + +#ifdef HAVE_CONFIG_H +#include +#endif +#include +#include +#include "XpExtUtil.h" + + +Bool +XpQueryExtension ( + Display *dpy, + int *event_base_return, /* return value */ + int *error_base_return /* return value */ +) +{ + XExtDisplayInfo *info = (XExtDisplayInfo *) xp_find_display (dpy); + + if (XextHasExtension (info)) { + *event_base_return = info->codes->first_event; + *error_base_return = info->codes->first_error; + return True; + } else { + return False; + } +} + +/* Prototype for |XpCheckExtInitUnlocked()| + * See XpExtUtil.c - same as |XpCheckExtInit()| but does not obtain the Xlib global lock */ +extern int XpCheckExtInitUnlocked( + register Display *dpy, + register int version_index +); + +Status +XpQueryVersion ( + Display *dpy, + short *major_version, + short *minor_version +) +{ + xPrintQueryVersionReq *req; + xPrintQueryVersionReply rep; + XExtDisplayInfo *info = (XExtDisplayInfo *) xp_find_display (dpy); + + /* + * Note: many extensions treat major and minor as "ints", but + * protocol wise and internal wise, they're shorts. + */ + *major_version = 0; + *minor_version = 0; + +#ifdef Would_Need_xpPrintData_Struct_Def + /* + * We may already have the answer cached from a previous query. + */ + if (( info->data ) && ( ((xpPrintData *) info->data)->vers->present )) { + *major_version = ((xpPrintData *) info->data)->vers->major_version ; + *minor_version = ((xpPrintData *) info->data)->vers->minor_version ; + return (/* non-zero indicates extension present */ True); + } +#endif /* Would_Need_xpPrintData_Struct_Def */ + + if (XpCheckExtInitUnlocked(dpy, XP_DONT_CHECK) == -1) + return (/* No such extension */ False); + + LockDisplay (dpy); + + GetReq(PrintQueryVersion,req); + req->reqType = info->codes->major_opcode; + req->printReqType = X_PrintQueryVersion; + + if (! _XReply (dpy, (xReply *) &rep, 0, xTrue)) { + UnlockDisplay(dpy); + SyncHandle(); + return(/* No such extension */ False); + } + + *major_version = rep.majorVersion; + *minor_version = rep.minorVersion; + + UnlockDisplay(dpy); + SyncHandle(); + return (/* non-zero indicates extension present */ True); +} + diff --git a/pool/shard006/C/0119217_irt_fdio.c b/pool/shard006/C/0119217_irt_fdio.c new file mode 100644 index 0000000000000000000000000000000000000000..a8b52bbe70e9dfaa049cc3c6436daae4e5af1e8c --- /dev/null +++ b/pool/shard006/C/0119217_irt_fdio.c @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2011 The Native Client Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "native_client/src/untrusted/irt/irt.h" +#include "native_client/src/untrusted/nacl/syscall_bindings_trampoline.h" + +static int nacl_irt_close(int fd) { + return -NACL_SYSCALL(close)(fd); +} + +static int nacl_irt_read(int fd, void *buf, size_t count, size_t *nread) { + int rv = NACL_GC_WRAP_SYSCALL(NACL_SYSCALL(read)(fd, buf, count)); + if (rv < 0) + return -rv; + *nread = rv; + return 0; +} + +static int nacl_irt_write(int fd, const void *buf, size_t count, + size_t *nwrote) { + int rv = NACL_GC_WRAP_SYSCALL(NACL_SYSCALL(write)(fd, buf, count)); + if (rv < 0) + return -rv; + *nwrote = rv; + return 0; +} + +static int nacl_irt_seek(int fd, off_t offset, int whence, off_t *new_offset) { + int rv = NACL_SYSCALL(lseek)(fd, &offset, whence); + if (rv < 0) + return -rv; + *new_offset = offset; + return 0; +} + +static int nacl_irt_dup(int fd, int *newfd) { + int rv = NACL_SYSCALL(dup)(fd); + if (rv < 0) + return -rv; + *newfd = rv; + return 0; +} + +static int nacl_irt_dup2(int fd, int newfd) { + int rv = NACL_SYSCALL(dup2)(fd, newfd); + if (rv < 0) + return -rv; + return 0; +} + +static int nacl_irt_fstat(int fd, struct stat *st) { + return -NACL_SYSCALL(fstat)(fd, st); +} + +static int nacl_irt_getdents(int fd, struct dirent *buf, size_t count, + size_t *nread) { + int rv = NACL_GC_WRAP_SYSCALL(NACL_SYSCALL(getdents)(fd, buf, count)); + if (rv < 0) + return -rv; + *nread = rv; + return 0; +} + +const struct nacl_irt_fdio nacl_irt_fdio = { + nacl_irt_close, + nacl_irt_dup, + nacl_irt_dup2, + nacl_irt_read, + nacl_irt_write, + nacl_irt_seek, + nacl_irt_fstat, + nacl_irt_getdents, +}; diff --git a/pool/shard006/C/0119219_files-netgrp.c b/pool/shard006/C/0119219_files-netgrp.c new file mode 100644 index 0000000000000000000000000000000000000000..34d2b64473c3a2573a69c0bea44d13efe91b5807 --- /dev/null +++ b/pool/shard006/C/0119219_files-netgrp.c @@ -0,0 +1,287 @@ +/* Netgroup file parser in nss_files modules. + Copyright (C) 1996, 1997, 2000 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1996. + + 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. */ + +#include +#include +#include +#include +#include +#include +#include "nsswitch.h" +#include "netgroup.h" + +#define DATAFILE "/etc/netgroup" + + +#define EXPAND(needed) \ + do \ + { \ + size_t old_cursor = result->cursor - result->data; \ + \ + result->data_size += 512 > 2 * needed ? 512 : 2 * needed; \ + result->data = realloc (result->data, result->data_size); \ + \ + if (result->data == NULL) \ + { \ + status = NSS_STATUS_UNAVAIL; \ + goto the_end; \ + } \ + \ + result->cursor = result->data + old_cursor; \ + } \ + while (0) + + +enum nss_status +_nss_files_setnetgrent (const char *group, struct __netgrent *result) +{ + FILE *fp; + enum nss_status status; + + if (group[0] == '\0') + return NSS_STATUS_UNAVAIL; + + /* Find the netgroups file and open it. */ + fp = fopen (DATAFILE, "r"); + if (fp == NULL) + status = errno == EAGAIN ? NSS_STATUS_TRYAGAIN : NSS_STATUS_UNAVAIL; + else + { + /* Read the file line by line and try to find the description + GROUP. We must take care for long lines. */ + char *line = NULL; + size_t line_len = 0; + const ssize_t group_len = strlen (group); + + status = NSS_STATUS_NOTFOUND; + result->cursor = result->data; + + while (!feof (fp)) + { + ssize_t curlen = getline (&line, &line_len, fp); + int found; + + if (curlen < 0) + { + status = NSS_STATUS_NOTFOUND; + break; + } + + found = (curlen > group_len && strncmp (line, group, group_len) == 0 + && isspace (line[group_len])); + + /* Read the whole line (including continuation) and store it + if FOUND in nonzero. Otherwise we don't need it. */ + if (found) + { + /* Store the data from the first line. */ + EXPAND (curlen - group_len); + memcpy (result->cursor, &line[group_len + 1], + curlen - group_len); + result->cursor += (curlen - group_len) - 1; + } + + while (line[curlen - 1] == '\n' && line[curlen - 2] == '\\') + { + /* Yes, we have a continuation line. */ + if (found) + /* Remove these characters from the stored line. */ + result->cursor -= 2; + + /* Get next line. */ + curlen = getline (&line, &line_len, fp); + if (curlen <= 0) + break; + + if (found) + { + /* Make sure we have enough room. */ + EXPAND (1 + curlen + 1); + + /* Add separator in case next line starts immediately. */ + *result->cursor++ = ' '; + + /* Copy new line. */ + memcpy (result->cursor, line, curlen + 1); + result->cursor += curlen; + } + } + + if (found) + { + /* Now we have read the line. */ + status = NSS_STATUS_SUCCESS; + result->cursor = result->data; + result->first = 1; + break; + } + } + + the_end: + /* We don't need the file and the line buffer anymore. */ + free (line); + fclose (fp); + } + + return status; +} + + +int +_nss_files_endnetgrent (struct __netgrent *result) +{ + /* Free allocated memory for data if some is present. */ + if (result->data != NULL) + { + free (result->data); + result->data = NULL; + result->data_size = 0; + result->cursor = NULL; + } + + return NSS_STATUS_SUCCESS; +} + +static char * +strip_whitespace (char *str) +{ + char *cp = str; + + /* Skip leading spaces. */ + while (isspace (*cp)) + cp++; + + str = cp; + while (*cp != '\0' && ! isspace(*cp)) + cp++; + + /* Null-terminate, stripping off any trailing spaces. */ + *cp = '\0'; + + return *str == '\0' ? NULL : str; +} + +enum nss_status +_nss_netgroup_parseline (char **cursor, struct __netgrent *result, + char *buffer, size_t buflen, int *errnop) +{ + enum nss_status status; + const char *host, *user, *domain; + char *cp = *cursor; + + /* Some sanity checks. */ + if (cp == NULL) + return NSS_STATUS_NOTFOUND; + + /* First skip leading spaces. */ + while (isspace (*cp)) + ++cp; + + if (*cp != '(') + { + /* We have a list of other netgroups. */ + char *name = cp; + + while (*cp != '\0' && ! isspace (*cp)) + ++cp; + + if (name != cp) + { + /* It is another netgroup name. */ + int last = *cp == '\0'; + + result->type = group_val; + result->val.group = name; + *cp = '\0'; + if (! last) + ++cp; + *cursor = cp; + result->first = 0; + + return NSS_STATUS_SUCCESS; + } + + return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; + } + + /* Match host name. */ + host = ++cp; + while (*cp != ',') + if (*cp++ == '\0') + return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; + + /* Match user name. */ + user = ++cp; + while (*cp != ',') + if (*cp++ == '\0') + return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; + + /* Match domain name. */ + domain = ++cp; + while (*cp != ')') + if (*cp++ == '\0') + return result->first ? NSS_STATUS_NOTFOUND : NSS_STATUS_RETURN; + ++cp; + + + /* When we got here we have found an entry. Before we can copy it + to the private buffer we have to make sure it is big enough. */ + if (cp - host > buflen) + { + *errnop = ERANGE; + status = NSS_STATUS_UNAVAIL; + } + else + { + memcpy (buffer, host, cp - host); + result->type = triple_val; + + buffer[(user - host) - 1] = '\0'; /* Replace ',' with '\0'. */ + result->val.triple.host = strip_whitespace (buffer); + + buffer[(domain - host) - 1] = '\0'; /* Replace ',' with '\0'. */ + result->val.triple.user = strip_whitespace (buffer + (user - host)); + + buffer[(cp - host) - 1] = '\0'; /* Replace ')' with '\0'. */ + result->val.triple.domain = strip_whitespace (buffer + (domain - host)); + + status = NSS_STATUS_SUCCESS; + + /* Remember where we stopped reading. */ + *cursor = cp; + + result->first = 0; + } + + return status; +} + + +enum nss_status +_nss_files_getnetgrent_r (struct __netgrent *result, char *buffer, + size_t buflen, int *errnop) +{ + enum nss_status status; + + status = _nss_netgroup_parseline (&result->cursor, result, buffer, buflen, + errnop); + + return status; +} diff --git a/pool/shard006/C/0119221_py_samr_conv.c b/pool/shard006/C/0119221_py_samr_conv.c new file mode 100644 index 0000000000000000000000000000000000000000..7523ee7dfcbcb3206d57fb37b3b66fabd7827162 --- /dev/null +++ b/pool/shard006/C/0119221_py_samr_conv.c @@ -0,0 +1,131 @@ +/* + Python wrappers for DCERPC/SMB client routines. + + Copyright (C) Tim Potter, 2002 + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include "python/py_samr.h" +#include "python/py_conv.h" + +/* + * Convert between SAM_USER_INFO_10 and Python + */ + +struct pyconv py_SAM_USER_INFO_10[] = { + { "acb_info", PY_UINT32, offsetof(SAM_USER_INFO_10, acb_info) }, + { NULL } +}; + +BOOL py_from_SAM_USER_INFO_10(PyObject **dict, SAM_USER_INFO_10 *info) +{ + *dict = from_struct(info, py_SAM_USER_INFO_10); + PyDict_SetItemString(*dict, "level", PyInt_FromLong(0x10)); + return True; +} + +BOOL py_to_SAM_USER_INFO_10(SAM_USER_INFO_10 *info, PyObject *dict) +{ + PyObject *obj, *dict_copy = PyDict_Copy(dict); + BOOL result = False; + + if (!(obj = PyDict_GetItemString(dict_copy, "level")) || + !PyInt_Check(obj)) + goto done; + + PyDict_DelItemString(dict_copy, "level"); + + if (!to_struct(info, dict_copy, py_SAM_USER_INFO_10)) + goto done; + + result = True; + +done: + Py_DECREF(dict_copy); + return result; +} + +/* + * Convert between SAM_USER_INFO_21 and Python + */ + +struct pyconv py_SAM_USER_INFO_21[] = { + { NULL } +}; + +BOOL py_from_SAM_USER_INFO_21(PyObject **dict, SAM_USER_INFO_21 *info) +{ + *dict = from_struct(info, py_SAM_USER_INFO_21); + PyDict_SetItemString(*dict, "level", PyInt_FromLong(21)); + return True; +} + +BOOL py_to_SAM_USER_INFO_21(SAM_USER_INFO_21 *info, PyObject *dict) +{ + PyObject *obj, *dict_copy = PyDict_Copy(dict); + BOOL result = False; + + if (!(obj = PyDict_GetItemString(dict_copy, "level")) || + !PyInt_Check(obj)) + goto done; + + PyDict_DelItemString(dict_copy, "level"); + + if (!to_struct(info, dict_copy, py_SAM_USER_INFO_21)) + goto done; + + result = True; + +done: + Py_DECREF(dict_copy); + return result; +} + +/* + * Convert between acct_info and Python + */ + +BOOL py_from_acct_info(PyObject **array, struct acct_info *info, int num_accts) +{ + int i; + + *array = PyList_New(num_accts); + + for (i = 0; i < num_accts; i++) { + PyObject *obj; + + obj = PyDict_New(); + + PyDict_SetItemString( + obj, "name", PyString_FromString(info[i].acct_name)); + + PyDict_SetItemString( + obj, "description", + PyString_FromString(info[i].acct_desc)); + + PyDict_SetItemString(obj, "rid", PyInt_FromLong(info[i].rid)); + + PyList_SetItem(*array, i, obj); + } + + return True; +} + +BOOL py_to_acct_info(PRINTER_INFO_3 *info, PyObject *dict, + TALLOC_CTX *mem_ctx) +{ + return False; +} diff --git a/pool/shard006/C/0119224_xauth_default_verifier.c b/pool/shard006/C/0119224_xauth_default_verifier.c new file mode 100644 index 0000000000000000000000000000000000000000..673ad73257656d5a96fcd680aa0a45b0e3f5beae --- /dev/null +++ b/pool/shard006/C/0119224_xauth_default_verifier.c @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2010 Andreas Steffen + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See . + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include + +#include "xauth_default_verifier.h" + +typedef struct private_xauth_default_verifier_t private_xauth_default_verifier_t; + +/** + * private data of xauth_default_verifier + */ +struct private_xauth_default_verifier_t { + + /** + * public functions + */ + xauth_verifier_t public; +}; + +METHOD(xauth_verifier_t, verify_secret, bool, + private_xauth_default_verifier_t *this, connection_t *c, chunk_t secret) +{ + identification_t *user, *server; + chunk_t xauth_secret; + bool success = FALSE; + + server = c->spd.this.id; + user = (c->xauth_identity) ? c->xauth_identity : c->spd.that.id; + + if (get_xauth_secret(c, user, server, &xauth_secret)) + { + success = chunk_equals(secret, xauth_secret); + chunk_clear(&xauth_secret); + } + return success; +} + +METHOD(xauth_verifier_t, destroy, void, + private_xauth_default_verifier_t *this) +{ + free(this); +} + + +/* + * Described in header. + */ +xauth_verifier_t *xauth_default_verifier_create() +{ + private_xauth_default_verifier_t *this; + + INIT(this, + .public = { + .verify_secret = _verify_secret, + .destroy = _destroy, + } + ); + + return &this->public; +} + diff --git a/pool/shard006/C/0119228_thttp_auth.c b/pool/shard006/C/0119228_thttp_auth.c new file mode 100644 index 0000000000000000000000000000000000000000..bd92d6b95cbd8146ad642c34d467b4ecdc47fb65 --- /dev/null +++ b/pool/shard006/C/0119228_thttp_auth.c @@ -0,0 +1,271 @@ +/* +* Copyright (C) 2010-2011 Mamadou Diop. +* +* Contact: Mamadou Diop +* +* This file is part of Open Source Doubango Framework. +* +* DOUBANGO 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. +* +* DOUBANGO 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 DOUBANGO. +* +*/ +/**@file thttp_auth.c + * @brief HTTP basic/digest authetication (RFC 2617) implementations. + * + * @author Mamadou Diop + * + + */ +#include "tinyhttp/auth/thttp_auth.h" + +#include "tsk_string.h" +#include "tsk_sha1.h" +#include "tsk_base64.h" +#include "tsk_buffer.h" +#include "tsk_memory.h" +#include "tsk_debug.h" + +#include + +/**@defgroup thttp_auth_group HTTP basic/digest authentication (RFC 2617) +*/ + +/**@ingroup thttp_auth_group + * + * Generates HTTP-basic response as per RFC 2617. + * + * @param [in,out] userid The user-id. + * @param [in,out] password The user-password. + * @param [in,out] response A pointer to the response. It will be up to the caller to free the newly allocated buffer. + * + * @return The size of the response. +**/ +tsk_size_t thttp_auth_basic_response(const char* userid, const char* password, char** response) +{ + tsk_size_t ret; + + /* RFC 2617 - 2 Basic Authentication Scheme + + To receive authorization, the client sends the userid and password, + separated by a single colon (":") character, within a base64 [7] + encoded string in the credentials. + */ + + char *res = 0; + tsk_sprintf(&res, "%s:%s", userid, password); + ret = tsk_base64_encode((const uint8_t*)res, tsk_strlen(res), response); + TSK_FREE(res); + + return ret; +} + + +/**@ingroup thttp_auth_group + * Generates digest HA1 value as per RFC 2617 subclause 3.2.2.2. + * + * + * @param [in,out] username The user's name (unquoted) in the specified @a realm. + * @param [in,out] realm The realm. (unquoted) + * @param [in,out] password The user's password. + * @param [in,out] ha1 A pointer to the result. + * + * @return Zero if succeed and non-zero error code otherwise. +**/ +int thttp_auth_digest_HA1(const char* username, const char* realm, const char* password, tsk_md5string_t* ha1) +{ + int ret; + + /* RFC 2617 - 3.2.2.2 A1 + A1 = unq(username-value) ":" unq(realm-value) ":" passwd + */ + char *a1 = tsk_null; + tsk_sprintf(&a1, "%s:%s:%s", username, realm, password); + ret = tsk_md5compute(a1, tsk_strlen(a1), ha1); + TSK_FREE(a1); + + return ret; +} + +/**@ingroup thttp_auth_group + * + * Generates digest HA1 value for 'MD5-sess' algo as per RFC 2617 subclause 3.2.2.2. + * + * + * @param [in,out] username The user's name (unquoted) in the specified @a realm. + * @param [in,out] realm The realm (unquoted). + * @param [in,out] password The user's password. + * @param [in,out] nonce The nonce (unquoted). + * @param [in,out] cnonce The client nonce (unquoted). + * @param [in,out] ha1sess A pointer to the result. + * + * @return Zero if succeed and non-zero error code otherwise. +**/ +int thttp_auth_digest_HA1sess(const char* username, const char* realm, const char* password, const char* nonce, const char* cnonce, tsk_md5string_t* ha1sess) +{ + int ret; + + /* RFC 2617 - 3.2.2.2 A1 + A1 = H( unq(username-value) ":" unq(realm-value) + ":" passwd ) + ":" unq(nonce-value) ":" unq(cnonce-value) + */ + + char *a1sess = tsk_null; + tsk_sprintf(&a1sess, "%s:%s:%s:%s:%s", username, realm, password, nonce, cnonce); + ret = tsk_md5compute(a1sess, tsk_strlen(a1sess), ha1sess); + TSK_FREE(a1sess); + + return ret; +} + +/**@ingroup thttp_auth_group + * Generates digest HA2 value as per RFC 2617 subclause 3.2.2.3. + * + * + * @param [in,out] method The HTTP/SIP method name. + * @param [in,out] url The HTTP URL or SIP URI of the request. + * @param [in,out] entity_body The entity body. + * @param [in,out] qop The Quality Of Protection. + * @param [in,out] ha2 A pointer to the response. + * + * @return Zero if succeed and non-zero error code otherwise. +**/ +int thttp_auth_digest_HA2(const char* method, const char* url, const tsk_buffer_t* entity_body, const char* qop, tsk_md5string_t* ha2) +{ + int ret; + /* RFC 2617 - 3.2.2.3 A2 + + If the "qop" directive's value is "auth" or is unspecified, then A2 + is: + A2 = Method ":" digest-url-value + + If the "qop" value is "auth-int", then A2 is: + A2 = Method ":" digest-url-value ":" H(entity-body) + */ + + char *a2 = tsk_null; + + if(!qop || tsk_strempty(qop) || tsk_striequals(qop, "auth")){ + tsk_sprintf(&a2, "%s:%s", method, url); + } + else if(tsk_striequals(qop, "auth-int")) + { + if(entity_body && entity_body->data){ + tsk_md5string_t hEntity; + if((ret = tsk_md5compute(entity_body->data, entity_body->size, &hEntity))){ + goto bail; + } + tsk_sprintf(&a2, "%s:%s:%s", method, url, hEntity); + } + else{ + tsk_sprintf(&a2, "%s:%s:%s", method, url, TSK_MD5_EMPTY); + } + } + + ret = tsk_md5compute(a2, tsk_strlen(a2), ha2); + +bail: + TSK_FREE(a2); + + return ret; +} + + +/**@ingroup thttp_auth_group + * + * Generates HTTP digest response as per RFC 2617 subclause 3.2.2.1. + * + * @param [in,out] ha1 HA1 string generated using @ref thttp_auth_digest_HA1 or @ref thttp_auth_digest_HA1sess. + * @param [in,out] nonce The nonce value. + * @param [in,out] noncecount The nonce count. + * @param [in,out] cnonce The client nounce (unquoted). + * @param [in,out] qop The Quality Of Protection (unquoted). + * @param [in,out] ha2 HA2 string generated using @ref thttp_auth_digest_HA2. + * @param [in,out] response A pointer to the response. + * + * @return Zero if succeed and non-zero error code otherwise. +**/ +int thttp_auth_digest_response(const tsk_md5string_t *ha1, const char* nonce, const nonce_count_t noncecount, const char* cnonce, + const char* qop, const tsk_md5string_t* ha2, tsk_md5string_t* response) +{ + int ret; + + /* RFC 2617 3.2.2.1 Request-Digest + + ============ CASE 1 ============ + If the "qop" value is "auth" or "auth-int": + request-digest = <"> < KD ( H(A1), unq(nonce-value) + ":" nc-value + ":" unq(cnonce-value) + ":" unq(qop-value) + ":" H(A2) + ) <"> + ============ CASE 2 ============ + If the "qop" directive is not present (this construction is for + compatibility with RFC 2069): + request-digest = + <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > + <"> + */ + + char *res = tsk_null; + + if(tsk_striequals(qop, "auth") || tsk_striequals(qop, "auth-int")){ + /* CASE 1 */ + tsk_sprintf(&res, "%s:%s:%s:%s:%s:%s", *ha1, nonce, noncecount, cnonce, qop, *ha2); + } + else{ + /* CASE 2 */ + tsk_sprintf(&res, "%s:%s:%s", *ha1, nonce, *ha2); + } + + ret = tsk_md5compute(res, tsk_strlen(res), response); + TSK_FREE(res); + + return ret; +} + +/**@ingroup thttp_auth_group + * + * Generates WebSocket Accept key. + * @param [in] key The value of the key received from the client ("Sec-WebSocket-Key" header). Must be null-terminated. + * @param [in,out] response The response ("Sec-WebSocket-Value" header). + * + * @return The size of the response. Zero if error. + */ +tsk_size_t thttp_auth_ws_response(const char* key, thttp_auth_ws_keystring_t* response) +{ + if(!key || !response){ + TSK_DEBUG_ERROR("invalid parameter"); + return 0; + } + else{ + tsk_sha1string_t sha1result; + char* tmp = tsk_null; + long ret; + tsk_size_t size, i; + uint8_t result[21] = { 0 }; + + tsk_strcat_2(&tmp, "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key); + + tsk_sha1compute(tmp, tsk_strlen(tmp), &sha1result); + size = tsk_strlen((char*)sha1result); + for(i = 0; i> 1] = (char)ret; + } + } + TSK_FREE(tmp); + return tsk_base64_encode(result, (size >> 1), (char**)&response); + } +} diff --git a/pool/shard006/C/0119237_xLWinfo.c b/pool/shard006/C/0119237_xLWinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..b58b21ed6f2612d8812c8e947a1190f29c5618e3 --- /dev/null +++ b/pool/shard006/C/0119237_xLWinfo.c @@ -0,0 +1,69 @@ +/*D*********************************************************** + * Modul: DBI - database info + * Kursinformationen + * + * Copyright: yafra.org, Basel, Switzerland + **************************************************************/ +#include +#include +#include /* Prototypes f�r ANSI-C */ + +static char rcsid[]="$Header: /yafra/cvsroot/mapo/source/dbi/xLWinfo.c,v 1.2 2008-11-02 19:55:35 mwn Exp $"; + +#define _SEL_LW_KURSE "SELECT * FROM TDBADMIN.LAND_WHR WHERE LAND_ID = %d \ + ORDER BY KURS_TYP, WHR_ID;" + +int LWinfo(char *buffer) +{ + extern MEMOBJ sqlmem; + extern int sprache; + extern WAEHRUNG whr; + extern LAND land; + extern LAND_WHR lw; + extern char sqlquery[]; + + LAND_WHR *lwptr; + char whrbez[_BEZLEN]; + char tmp_buffer[_RECORDLEN]; + char *to_buffers[MAX_MENU_ITEMS]; + int status=(int)MPOK; + int anzahl; + int i; + + ACTIONTYP = INFOTXT; + + status = UtilSplitMenubuffer(buffer, to_buffers, (char)NULL); + if (status != MPOK) + { + UtilMsg((int)MPE_CUTBUFFERIN, MSGTYP_ERROR, NULL); + return((int)MPERROR); + } + + /* get LAND */ + lw.land_id = MPAPIselectEntry((int)_LAND, to_buffers[MLW_LAND], + (char *)&land, sizeof(land), sizeof(land.land_id)); + (void)sprintf(buffer, "\nFolgende Kurse sind fuer das Land %s gueltig:\n\n", + to_buffers[MLW_LAND]); + + /* make loop over all WHR in LAND *****/ + (void)sprintf(sqlquery, _SEL_LW_KURSE, land.land_id); + status = MPAPIdb_sqlquery((int)_LAND_WHR, &sqlmem.buffer, sqlquery, + &anzahl, &sqlmem.datalen, &sqlmem.alloclen); + lwptr = (LAND_WHR *)sqlmem.buffer; + if (status != (int)MPOK || anzahl == (int)0) + { +/*!!! new msg */ + UtilMsg((int)MPE_NOINFO, MSGTYP_ERROR, NULL); + return((int)MPWARNING); + } + for (i=0; i +#include +#include + +/** Read method of the buffer ioport */ +int buffer_read (ioport *io, char *into, size_t sz) { + bufferstorage *S = (bufferstorage *) io->storage; + if (S->rpos + sz > S->bufsz) return 0; + if (S->pos && (S->rpos + sz > S->pos)) return 0; + if ((S->buf+S->rpos) != into) memcpy (into, S->buf + S->rpos, sz); + S->rpos += sz; + return 1; +} + +/** Write method of the buffer ioport */ +int buffer_write (ioport *io, const char *dat, size_t sz) { + bufferstorage *S = (bufferstorage *) io->storage; + if (S->pos + sz > S->bufsz) { + if (! S->owned) return 0; + while (S->pos + sz > S->bufsz) S->bufsz += 4096; + S->buf = (char *) realloc (S->buf, S->bufsz); + } + if (S->buf + S->pos != dat) { + if ((S->buf+S->pos) != dat) memcpy (S->buf + S->pos, dat, sz); + } + S->pos += sz; + return 1; +} + +/** Close method of the buffer ioport */ +void buffer_close (ioport *io) { + bufferstorage *S = (bufferstorage *) io->storage; + if (S->owned) free (S->buf); + free (S); + free (io); +} + +/** Return number of bytes still available for reading */ +size_t buffer_read_available (ioport *io) { + bufferstorage *S = (bufferstorage *) io->storage; + if (S->pos) return S->pos - S->rpos; + return S->bufsz - S->rpos; +} + +/** Return available buffer space */ +size_t buffer_write_available (ioport *io) { + bufferstorage *S = (bufferstorage *) io->storage; + return S->bufsz - S->pos; +} + +/** Return address of the buffer */ +char *buffer_get_buffer (ioport *io) { + bufferstorage *S = (bufferstorage *) io->storage; + return S->buf; +} + +/** Reset read position */ +void buffer_reset_read (ioport *io) { + bufferstorage *S = (bufferstorage *) io->storage; + S->rpos = 0; +} + +/** Create a buffer instance. + * \param buf Backend buffer storage + * \param sz The buffer's size + * \return The freshly created ioport + */ +ioport *ioport_create_buffer (void *buf, size_t sz) { + ioport *res = (ioport *) malloc (sizeof (ioport)); + res->write = buffer_write; + res->close = buffer_close; + res->read = buffer_read; + res->read_available = buffer_read_available; + res->write_available = buffer_write_available; + res->get_buffer = buffer_get_buffer; + res->reset_read = buffer_reset_read; + res->bitpos = 0; + res->bitbuffer = 0; + + bufferstorage *S = res->storage = malloc (sizeof (bufferstorage)); + S->bufsz = sz; + S->pos = 0; + S->rpos = 0; + if (buf) { + S->buf = (char *) buf; + S->owned = 0; + } + else { + S->buf = (char *) malloc (sz); + S->owned = 1; + } + return res; +} + diff --git a/pool/shard006/C/0119245_asb-package-alpm.c b/pool/shard006/C/0119245_asb-package-alpm.c new file mode 100644 index 0000000000000000000000000000000000000000..fb9ef88d890eef93f2db56261cda218446a684a8 --- /dev/null +++ b/pool/shard006/C/0119245_asb-package-alpm.c @@ -0,0 +1,252 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2014 Fabien Bourigault + * + * SPDX-License-Identifier: LGPL-2.1+ + */ + +/** + * SECTION:asb-package-alpm + * @short_description: Object representing a .tar.xz (pacman) package file. + * @stability: Unstable + * + * This object represents one .tar.xz (pacman) package file. + */ + +#include "config.h" + +#include + +#include + +#include "asb-package-alpm.h" +#include "asb-plugin.h" + +typedef struct +{ + alpm_handle_t *handle; + alpm_pkg_t *package; +} AsbPackageAlpmPrivate; + +G_DEFINE_TYPE_WITH_PRIVATE (AsbPackageAlpm, asb_package_alpm, ASB_TYPE_PACKAGE) + +#define GET_PRIVATE(o) (asb_package_alpm_get_instance_private (o)) + +static void +asb_package_alpm_finalize (GObject *object) +{ + AsbPackageAlpm *pkg = ASB_PACKAGE_ALPM (object); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg); + + /* TODO: handle errors */ + alpm_pkg_free (priv->package); + alpm_release (priv->handle); + + G_OBJECT_CLASS (asb_package_alpm_parent_class)->finalize (object); +} + +static void +asb_package_alpm_init (AsbPackageAlpm *pkg) +{ +} + +static GPtrArray * +asb_package_alpm_list_to_array (alpm_list_t *list) +{ + alpm_list_t *current; + GPtrArray *array = g_ptr_array_new_with_free_func (g_free); + + for (current = list; current; current = alpm_list_next (current)) { + g_ptr_array_add (array, g_strdup (current->data)); + } + g_ptr_array_add (array, NULL); + + return array; +} + +static gboolean +asb_package_alpm_ensure_license (AsbPackage *pkg, GError **error) +{ + AsbPackageAlpm *pkg_alpm = ASB_PACKAGE_ALPM (pkg); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg_alpm); + + alpm_list_t *alpm_licenses; + GPtrArray *licenses; + gchar *license; + + alpm_licenses = alpm_pkg_get_licenses (priv->package); + licenses = asb_package_alpm_list_to_array (alpm_licenses); + /* TODO: translate licenses to SPDX licenses (makes licenses clickable + * is GNOME Software) */ + license = g_strjoinv (" AND ", (gchar **)(licenses->pdata)); + + asb_package_set_license (pkg, license); + + g_ptr_array_free (licenses, TRUE); + return TRUE; +} + +static void +asb_package_alpm_ensure_version (AsbPackage *pkg, GError **error) +{ + AsbPackageAlpm *pkg_alpm = ASB_PACKAGE_ALPM (pkg); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg_alpm); + + g_auto(GStrv) split = NULL; + + split = g_strsplit (alpm_pkg_get_version (priv->package), ":-", 3); + + /* epoch:version:release */ + if (g_strv_length (split) == 3) { + asb_package_set_epoch (pkg, (guint) g_ascii_strtoull (split[0], NULL, 0)); + asb_package_set_version (pkg, split[1]); + asb_package_set_release (pkg, split[2]); + } else {/* version:release */ + asb_package_set_version (pkg, split[0]); + asb_package_set_release (pkg, split[1]); + } +} + +#if 0 +static gboolean +asb_package_alpm_ensure_releases (AsbPackage *pkg, GError **error) +{ + AsbPackageAlpm *pkg_alpm = ASB_PACKAGE_ALPM (pkg); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg_alpm); + return TRUE; +} +#endif + +static gboolean +asb_package_alpm_ensure_depends (AsbPackage *pkg, GError **error) +{ + AsbPackageAlpm *pkg_alpm = ASB_PACKAGE_ALPM (pkg); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg_alpm); + alpm_list_t *alpm_depends; + alpm_list_t *current; + + alpm_depends = alpm_pkg_get_depends (priv->package); + for (current = alpm_depends; current; current = alpm_list_next (current)) + asb_package_add_dep (pkg, current->data); + + return TRUE; +} + +static gboolean +asb_package_alpm_ensure_filelists (AsbPackage *pkg, GError **error) +{ + AsbPackageAlpm *pkg_alpm = ASB_PACKAGE_ALPM (pkg); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg_alpm); + + alpm_filelist_t *pkgfiles = alpm_pkg_get_files (priv->package); + guint i; + GPtrArray *filelist = g_ptr_array_new_with_free_func (g_free); + + for (i = 0; i < pkgfiles->count; i++) { + const alpm_file_t *file = pkgfiles->files + i; + g_ptr_array_add (filelist, g_strconcat ("/", file->name, NULL)); + } + g_ptr_array_add (filelist, NULL); + + asb_package_set_filelist (pkg, (gchar **)(filelist->pdata)); + + g_ptr_array_free (filelist, TRUE); + return TRUE; +} + +static gboolean +asb_package_alpm_open (AsbPackage *pkg, const gchar *filename, GError **error) +{ + AsbPackageAlpm *pkg_alpm = ASB_PACKAGE_ALPM (pkg); + AsbPackageAlpmPrivate *priv = GET_PRIVATE (pkg_alpm); + + alpm_errno_t alpm_error; + + /* initialize the alpm library */ + priv->handle = alpm_initialize ("/", "/tmp", &alpm_error); + if (priv->handle == NULL) { + g_set_error (error, + ASB_PLUGIN_ERROR, + ASB_PLUGIN_ERROR_FAILED, + "libalpm initialization failed %s (%u) for %s", + alpm_strerror (alpm_error), + alpm_error, + filename); + return FALSE; + } + + /* open the package */ + if (alpm_pkg_load (priv->handle, filename, TRUE, 0, &priv->package) == -1) { + g_set_error (error, + ASB_PLUGIN_ERROR, + ASB_PLUGIN_ERROR_FAILED, + "Failed to load package %s : %s (%u)", + filename, + alpm_strerror (alpm_errno (priv->handle)), + alpm_errno (priv->handle)); + alpm_release (priv->handle); + return FALSE; + } + + asb_package_set_name (pkg, alpm_pkg_get_name (priv->package)); + asb_package_set_url (pkg, alpm_pkg_get_url (priv->package)); + asb_package_set_arch (pkg, alpm_pkg_get_arch (priv->package)); + asb_package_alpm_ensure_version (pkg, error); + + return TRUE; +} + +static gint +asb_package_alpm_compare (AsbPackage *pkg1, AsbPackage *pkg2) +{ + AsbPackageAlpm *pkg_alpm1 = ASB_PACKAGE_ALPM (pkg1); + AsbPackageAlpmPrivate *priv1 = GET_PRIVATE (pkg_alpm1); + + AsbPackageAlpm *pkg_alpm2 = ASB_PACKAGE_ALPM (pkg2); + AsbPackageAlpmPrivate *priv2 = GET_PRIVATE (pkg_alpm2); + + const gchar *pkg1_version = alpm_pkg_get_version (priv1->package); + const gchar *pkg2_version = alpm_pkg_get_version (priv2->package); + + return alpm_pkg_vercmp (pkg1_version, pkg2_version); +} + +static gboolean +asb_package_alpm_ensure (AsbPackage *pkg, + AsbPackageEnsureFlags flags, + GError **error) +{ + if ((flags & ASB_PACKAGE_ENSURE_DEPS) > 0) { + if (!asb_package_alpm_ensure_depends (pkg, error)) + return FALSE; + } + if ((flags & ASB_PACKAGE_ENSURE_FILES) > 0) { + if (!asb_package_alpm_ensure_filelists (pkg, error)) + return FALSE; + } + if ((flags & ASB_PACKAGE_ENSURE_LICENSE) > 0) { + if (!asb_package_alpm_ensure_license (pkg, error)) + return FALSE; + } + return TRUE; +} + +static void +asb_package_alpm_class_init (AsbPackageAlpmClass *klass) +{ + AsbPackageClass *package_class = ASB_PACKAGE_CLASS (klass); + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + object_class->finalize = asb_package_alpm_finalize; + package_class->open = asb_package_alpm_open; + package_class->ensure = asb_package_alpm_ensure; + package_class->compare = asb_package_alpm_compare; +} + +AsbPackage * +asb_package_alpm_new (void) +{ + AsbPackage *pkg; + pkg = g_object_new (ASB_TYPE_PACKAGE_ALPM, NULL); + return ASB_PACKAGE (pkg); +} diff --git a/pool/shard006/C/0119246_CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31.c b/pool/shard006/C/0119246_CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31.c new file mode 100644 index 0000000000000000000000000000000000000000..463d3520891f105719077882b789000f169458f9 --- /dev/null +++ b/pool/shard006/C/0119246_CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31.c @@ -0,0 +1,108 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml +Template File: sources-sink-31.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Set data pointer to the bad buffer + * GoodSource: Set data pointer to the good buffer + * Sinks: loop + * BadSink : Copy int64_t array to data using a loop + * Flow Variant: 31 Data flow using a copy of data within the same function + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31_bad() +{ + int64_t * data; + int64_t * dataBadBuffer = (int64_t *)ALLOCA(50*sizeof(int64_t)); + int64_t * dataGoodBuffer = (int64_t *)ALLOCA(100*sizeof(int64_t)); + /* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination + * buffer in various memory copying functions using a "large" source buffer. */ + data = dataBadBuffer; + { + int64_t * dataCopy = data; + int64_t * data = dataCopy; + { + int64_t source[100] = {0}; /* fill with 0's */ + { + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + printLongLongLine(data[0]); + } + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2B() +{ + int64_t * data; + int64_t * dataBadBuffer = (int64_t *)ALLOCA(50*sizeof(int64_t)); + int64_t * dataGoodBuffer = (int64_t *)ALLOCA(100*sizeof(int64_t)); + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + { + int64_t * dataCopy = data; + int64_t * data = dataCopy; + { + int64_t source[100] = {0}; /* fill with 0's */ + { + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + printLongLongLine(data[0]); + } + } + } +} + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31_good() +{ + goodG2B(); +} + +#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()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE805_int64_t_alloca_loop_31_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0119250_makecpmloader.c b/pool/shard006/C/0119250_makecpmloader.c new file mode 100644 index 0000000000000000000000000000000000000000..2f2854015fab6671e4c1298f0d4113affbae4b5b --- /dev/null +++ b/pool/shard006/C/0119250_makecpmloader.c @@ -0,0 +1,160 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * 2014-12-21 William R Sowerbutts + * + * Create a CP/M program which boots Fuzix. + * + * The CP/M executable file contains a small loader program, followed by some + * data describing where the kernel should be loaded, and then the kernel + * itself. + * + * When run, the CP/M program copies a small (20 byte) program to the very + * start of memory, which then copies the kernel to the correct address and + * executes it. + * + * + * Syntax: makecpmloader
+ * + * loader -- normally cpmload.bin, assembled from cpmload.s + * kernel -- fuzix.bin from the Fuzix build process + * address -- the kernel's load address (normally 0x88) + * output -- output file name + * + */ + +#define LOADER_TRIM 0x100 /* CP/M loads us at 0x100 */ +#define MAX_LOADER_LENGTH 0x200 /* Loader should really be teeny tiny */ +#define MAX_KERNEL_LENGTH 0x10000 /* Kernel can't be larger than 64KB ... yet ... */ +#define BYTESWAP16(x) (((x>>8) & 0xFF) | ((x & 0xFF) << 8)) + +char loader_data[MAX_LOADER_LENGTH]; +char kernel_data[MAX_KERNEL_LENGTH]; + +struct loader_trailer { + unsigned short load_address; + unsigned short load_length; +}; + +int load_file(const char *filename, char *buffer, int buffer_len) +{ + int fd, length, r; + + fd = open(filename, O_RDONLY); + + if(fd < 0){ + fprintf(stderr, "Cannot open \"%s\": %s\n", filename, strerror(errno)); + return -1; + } + + length = 0; + while(1){ + r = read(fd, &buffer[length], buffer_len - length); + if(r == 0) /* EOF */ + break; + else if(r > 0) + length += r; + else{ + fprintf(stderr, "Cannot read \"%s\": %s\n", filename, strerror(errno)); + close(fd); + return -1; + } + if(length == buffer_len){ + fprintf(stderr, "Out of buffer space reading \"%s\"\n", filename); + close(fd); + return -1; + } + } + + close(fd); + return length; +} + +int parse_int(char *str) +{ + int base = 10; + long val; + char *end; + + end = str; + if(strncasecmp(end, "0x", 2) == 0){ + base = 16; + end = end + 2; + } + + val = strtol(end, &end, base); + + if(*end == 0 && *str != 0) + return val; + else{ + fprintf(stderr, "Cannot parse load address \"%s\"\n", str); + return -1; + } +} + +int main(int argc, char **argv) +{ + int loader_length; + int load_address; + int kernel_length; + int fd; + struct loader_trailer trailer; + + if(argc < 5){ + fprintf(stderr, "%s [loader] [kernel] [address] [output]\n", argv[0]); + return 1; + } + + loader_length = load_file(argv[1], loader_data, MAX_LOADER_LENGTH); + if(loader_length < 0) + return 1; + if(loader_length <= LOADER_TRIM){ + fprintf(stderr, "Loader image is too small\n"); + return 1; + } + + kernel_length = load_file(argv[2], kernel_data, MAX_KERNEL_LENGTH); + if(kernel_length < 0) + return 1; + + load_address = parse_int(argv[3]); + + if(load_address < 0 || load_address > 0xFFFF){ + fprintf(stderr, "Bad load address.\n"); + return 1; + } + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + trailer.load_length = kernel_length; + trailer.load_address = load_address; +#else + trailer.load_length = BYTESWAP16(kernel_length); + trailer.load_address = BYTESWAP16(load_address); +#endif + + fd = open(argv[4], O_WRONLY | O_CREAT | O_TRUNC, 0666); + if(fd < 0){ + fprintf(stderr, "Cannot open \"%s\": %s\n", argv[4], strerror(errno)); + return 1; + } + + if(write(fd, &loader_data[LOADER_TRIM], loader_length - LOADER_TRIM) != (loader_length - LOADER_TRIM) || + write(fd, &trailer, sizeof(trailer)) != sizeof(trailer) || + write(fd, kernel_data, kernel_length) != kernel_length){ + fprintf(stderr, "Write to \"%s\" failed: %s\n", argv[4], strerror(errno)); + close(fd); + unlink(argv[4]); + return 1; + } + + close(fd); + + return 0; +} diff --git a/pool/shard006/C/0119251_s3cfb_56.c b/pool/shard006/C/0119251_s3cfb_56.c new file mode 100644 index 0000000000000000000000000000000000000000..27b29b855cd4bb1837f2c83f7864de6f1bb7cb7c --- /dev/null +++ b/pool/shard006/C/0119251_s3cfb_56.c @@ -0,0 +1,213 @@ +/* + * s3cfb_70.c for 7 inch lcd + * + * (C) Copyright 2001-2002 + * Wolfgang Denk, DENX Software Engineering -- wd@denx.de + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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 + */ + +/************************************************************************/ +/* ** HEADER FILES */ +/************************************************************************/ + +/* #define DEBUG */ + +#include +#include +#include +#include +#include +#include +#include + + +#include +#include + + +#include +#include +#include + + +#ifdef CONFIG_LCD + +#define S3CFB_HFP 16 /* front porch */ +#define S3CFB_HSW 10 /* hsync width */ +#define S3CFB_HBP 144 /* back porch */ + +#define S3CFB_VFP 32 /* front porch */ +#define S3CFB_VSW 2 /* vsync width */ +#define S3CFB_VBP 13 /* back porch */ + +#define S3CFB_HRES 640 +#define S3CFB_VRES 480 + +#define S3CFB_VFRAME_FREQ 103 + +#define S3CFB_IVCLK 0//CFG_LOW +#define S3CFB_IHSYNC 1//CFG_HIGH +#define S3CFB_IVSYNC 1//CFG_HIGH +#define S3CFB_IVDEN 0//CFG_LOW + + +#define S3CFB_PIXEL_CLOCK (S3CFB_VFRAME_FREQ * (S3CFB_HFP + S3CFB_HSW + S3CFB_HBP + S3CFB_HRES) * (S3CFB_VFP + S3CFB_VSW + S3CFB_VBP + S3CFB_VRES)) + +extern uchar *osd_frame_buffer; + +void lcd_ctrl_init_56(void *lcdbase) +{ + ulong freq_lcdclk; + ulong freq_Hclk; + ulong fb_size; + unsigned char nn; + unsigned short *pp; + int i; + + GPICON_REG = 0xaaaaaaaa; + GPIPUD_REG = 0xaaaaaaaa; + GPJCON_REG = 0xaaaaaaaa; + GPJPUD_REG = 0xaaaaaaaa; + + lcd_disable(); + S3C_WINCON0 &= (~(S3C_WINCONx_ENWIN_F_ENABLE)); + + MIFPCON_REG &= (~SEL_BYPASS_MASK); + SPCON_REG &= (~LCD_SEL_MASK); + SPCON_REG |= (RGB_IF_STYLE_MASK); + + freq_lcdclk = S3CFB_PIXEL_CLOCK; + freq_Hclk = get_HCLK(); + + nn = (unsigned char)(freq_Hclk / freq_lcdclk) - 1; + if(freq_lcdclk < freq_Hclk/2) + { + S3C_VIDCON0 = S3C_VIDCON0_INTERLACE_F_PROGRESSIVE + S3C_VIDCON0_VIDOUT_RGB_IF + \ + S3C_VIDCON0_PNRMODE_RGB_P + S3C_VIDCON0_CLKVALUP_ST_FRM + S3C_VIDCON0_CLKVAL_F(nn) + \ + S3C_VIDCON0_CLKDIR_DIVIDED + S3C_VIDCON0_CLKSEL_F_HCLK; + }else + { + S3C_VIDCON0 = S3C_VIDCON0_INTERLACE_F_PROGRESSIVE + S3C_VIDCON0_VIDOUT_RGB_IF + \ + S3C_VIDCON0_PNRMODE_RGB_P + S3C_VIDCON0_CLKVALUP_ST_FRM + S3C_VIDCON0_CLKVAL_F(0) + \ + S3C_VIDCON0_CLKDIR_DIRECTED + S3C_VIDCON0_CLKSEL_F_HCLK; + } + + nn = 0; + if(S3CFB_IVCLK) + { + nn += S3C_VIDCON1_IVCLK_RISE_EDGE; + } + if(S3CFB_IHSYNC) + { + nn += S3C_VIDCON1_IHSYNC_INVERT; + } + if(S3CFB_IVSYNC) + { + nn += S3C_VIDCON1_IVSYNC_INVERT; + } + if(S3CFB_IVDEN) + { + nn += S3C_VIDCON1_IVDEN_INVERT; + } + S3C_VIDCON1 = (unsigned int)nn; + S3C_VIDCON2 = 0; + + S3C_VIDTCON0 = S3C_VIDTCON0_VBPD(S3CFB_VBP - 1) | S3C_VIDTCON0_VFPD(S3CFB_VFP - 1) | S3C_VIDTCON0_VSPW(S3CFB_VSW - 1); + S3C_VIDTCON1 = S3C_VIDTCON1_HBPD(S3CFB_HBP - 1) | S3C_VIDTCON1_HFPD(S3CFB_HFP -1) | S3C_VIDTCON1_HSPW(S3CFB_HSW - 1); + S3C_VIDTCON2 = S3C_VIDTCON2_LINEVAL(S3CFB_VRES - 1) | S3C_VIDTCON2_HOZVAL(S3CFB_HRES - 1); + +#if LCD_BPP == LCD_COLOR32 + S3C_WINCON0 = S3C_WINCONx_BPPMODE_F_24BPP_888; + S3C_WINCON1 = S3C_WINCONx_BPPMODE_F_24BPP_888 | S3C_WINCONx_BLD_PIX_PIXEL; +#else + S3C_WINCON0 = S3C_WINCONx_BPPMODE_F_16BPP_565 | S3C_WINCONx_HAWSWP_ENABLE; + S3C_WINCON1 = S3C_WINCONx_BPPMODE_F_16BPP_565 | S3C_WINCONx_HAWSWP_ENABLE | S3C_WINCONx_BLD_PIX_PIXEL; +#endif + + S3C_WINCON2 = 0; + S3C_WINCON3 = 0; + S3C_WINCON4 = 0; + + S3C_VIDOSD0A = S3C_VIDOSDxA_OSD_LTX_F(0) + S3C_VIDOSDxA_OSD_LTY_F(0); + S3C_VIDOSD0B = S3C_VIDOSDxB_OSD_RBX_F(S3CFB_HRES - 1) | S3C_VIDOSDxB_OSD_RBY_F(S3CFB_VRES - 1); + S3C_VIDOSD0C = S3C_VIDOSD0C_OSDSIZE(S3CFB_HRES*S3CFB_VRES); + + S3C_VIDOSD1A = S3C_VIDOSDxA_OSD_LTX_F(0) + S3C_VIDOSDxA_OSD_LTY_F(0); + S3C_VIDOSD1B = S3C_VIDOSDxB_OSD_RBX_F(S3CFB_HRES - 1) | S3C_VIDOSDxB_OSD_RBY_F(S3CFB_VRES - 1); + S3C_VIDOSD1C = 0xDDD000;/*alpha blending*/ + S3C_VIDOSD1D = S3C_VIDOSD0C_OSDSIZE(S3CFB_HRES*S3CFB_VRES); + + S3C_VIDOSD2A = 0; + S3C_VIDOSD2B = 0; + S3C_VIDOSD2C = 0; + S3C_VIDOSD2D = 0; + S3C_VIDOSD3A = 0; + S3C_VIDOSD3B = 0; + S3C_VIDOSD3C = 0; + S3C_VIDOSD4A = 0; + S3C_VIDOSD4B = 0; + S3C_VIDOSD4C = 0; + + fb_size = calc_fbsize(); + + S3C_VIDW00ADD0B0 = virt_to_phys(lcdbase); + S3C_VIDW00ADD0B1 = 0; + S3C_VIDW01ADD0B0 = virt_to_phys(osd_frame_buffer); + S3C_VIDW01ADD0B1 = 0; + S3C_VIDW02ADD0 = 0; + S3C_VIDW03ADD0 = 0; + S3C_VIDW04ADD0 = 0; + + S3C_VIDW00ADD1B0 = virt_to_phys((unsigned int)(lcdbase) + fb_size); + S3C_VIDW00ADD1B1 = 0; + S3C_VIDW01ADD1B0 = virt_to_phys(osd_frame_buffer) + fb_size; + S3C_VIDW01ADD1B1 = 0; + S3C_VIDW02ADD1 = 0; + S3C_VIDW03ADD1 = 0; + S3C_VIDW04ADD1 = 0; + + S3C_VIDW00ADD2 = 0;//S3C_VIDWxxADD2_OFFSIZE_F(0) | (S3C_VIDWxxADD2_PAGEWIDTH_F(panel_info.vl_col*panel_info.vl_bpix/8)); + S3C_VIDW01ADD2 = 0;//S3C_VIDWxxADD2_OFFSIZE_F(0) | (S3C_VIDWxxADD2_PAGEWIDTH_F(panel_info.vl_col*panel_info.vl_bpix/8)); + S3C_VIDW02ADD2 = 0; + S3C_VIDW03ADD2 = 0; + S3C_VIDW04ADD2 = 0; + + S3C_W1KEYCON0 = S3C_WxKEYCON0_KEYBLEN_ENABLE | S3C_WxKEYCON0_KEYEN_F_ENABLE | S3C_WxKEYCON0_COMPKEY(0xFFFF); + S3C_W1KEYCON1 = 0x00000000;/*color key*/ + +#if 1 + memset(lcdbase,0x00,fb_size*2); +#else + pp = lcdbase; + for(i=0;i< S3CFB_HRES * S3CFB_VRES;i++) + { + *pp = 0xf100; + pp++; + } +#endif + lcd_enable(); + + S3C_WINCON0 |= S3C_WINCONx_ENWIN_F_ENABLE; + S3C_WINCON1 |= S3C_WINCONx_ENWIN_F_ENABLE; + return (0); +} + + +#endif /* CONFIG_LCD */ diff --git a/pool/shard006/C/0119252_nortsong.c b/pool/shard006/C/0119252_nortsong.c new file mode 100644 index 0000000000000000000000000000000000000000..b033e87af4938e8b437ef9b21d67122f3fb7bf2b --- /dev/null +++ b/pool/shard006/C/0119252_nortsong.c @@ -0,0 +1,221 @@ +/* + * OpenTyrian: A modern cross-platform port of Tyrian + * Copyright (C) 2007-2009 The OpenTyrian Development Team + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +#include "nortsong.h" +#include "file.h" +#include "joystick.h" +#include "keyboard.h" +#include "loudness.h" +#include "musmast.h" +#include "params.h" +#include "sndmast.h" +#include "vga256d.h" + +uint32_t target, target2; + +bool notYetLoadedSound = true; + +uint16_t frameCount, frameCount2, frameCountMax; + +uint8_t *digiFx[SAMPLE_COUNT] = { NULL }; /* [1..soundnum + 9] */ +uint16_t fxSize[SAMPLE_COUNT]; /* [1..soundnum + 9] */ + +uint16_t tyrMusicVolume, fxVolume; +uint16_t fxPlayVol; +uint16_t tempVolume; + +uint16_t speed; /* JE: holds timer speed for 70Hz */ + +float jasondelay = 1000.0f / (1193180.0f / 0x4300); + +void setdelay( uint8_t delay ) +{ + target = (delay * 16) + SDL_GetTicks(); +} + +void setjasondelay( int delay ) +{ + target = SDL_GetTicks() + delay * jasondelay; +} + +void setjasondelay2( int delay ) +{ + target2 = SDL_GetTicks() + delay * jasondelay; +} + +int delaycount( void ) +{ + return (SDL_GetTicks() < target ? target - SDL_GetTicks() : 0); +} + +int delaycount2( void ) +{ + return (SDL_GetTicks() < target2 ? target2 - SDL_GetTicks() : 0); +} + +void wait_delay( void ) +{ + int32_t delay = target - SDL_GetTicks(); + if (delay > 0) + SDL_Delay(delay); +} + +void service_wait_delay( void ) +{ + while (SDL_GetTicks() < target) + { + SDL_Delay(SDL_GetTicks() - target > SDL_POLL_INTERVAL ? SDL_POLL_INTERVAL : SDL_GetTicks() - target); + service_SDL_events(false); + } +} + +void wait_delayorinput( bool keyboard, bool mouse, bool joystick ) +{ + service_SDL_events(true); + while (SDL_GetTicks() < target && !((keyboard && keydown) || (mouse && mousedown) || (joystick && joydown))) + { + SDL_Delay(SDL_GetTicks() - target > SDL_POLL_INTERVAL ? SDL_POLL_INTERVAL : SDL_GetTicks() - target); + push_joysticks_as_keyboard(); + service_SDL_events(false); + } +} + +void JE_loadSndFile( const char *effects_sndfile, const char *voices_sndfile ) +{ + uint8_t y, z; + uint16_t x; + int32_t templ; + int32_t sndPos[2][SAMPLE_COUNT + 1]; + uint16_t sndNum; + + FILE *fi; + + /* SYN: Loading offsets into TYRIAN.SND */ + fi = dir_fopen_die(data_dir(), effects_sndfile, "rb"); + efread(&sndNum, sizeof(sndNum), 1, fi); + + for (x = 0; x < sndNum; x++) + { + efread(&sndPos[0][x], sizeof(sndPos[0][x]), 1, fi); + } + fseek(fi, 0, SEEK_END); + sndPos[0][sndNum] = ftell(fi); /* Store file size */ + + for (z = 0; z < sndNum; z++) + { + fseek(fi, sndPos[0][z], SEEK_SET); + fxSize[z] = (sndPos[0][z+1] - sndPos[0][z]); /* Store sample sizes */ + free(digiFx[z]); + digiFx[z] = malloc(fxSize[z]); + efread(digiFx[z], 1, fxSize[z], fi); /* JE: Load sample to buffer */ + } + + fclose(fi); + + /* SYN: Loading offsets into VOICES.SND */ + fi = dir_fopen_die(data_dir(), voices_sndfile, "rb"); + + efread(&sndNum, sizeof(sndNum), 1, fi); + + for (x = 0; x < sndNum; x++) + { + efread(&sndPos[1][x], sizeof(sndPos[1][x]), 1, fi); + } + fseek(fi, 0, SEEK_END); + sndPos[1][sndNum] = ftell(fi); /* Store file size */ + + z = SAMPLE_COUNT - 9; + + for (y = 0; y < sndNum; y++) + { + fseek(fi, sndPos[1][y], SEEK_SET); + + templ = (sndPos[1][y+1] - sndPos[1][y]) - 100; /* SYN: I'm not entirely sure what's going on here. */ + if (templ < 1) templ = 1; + fxSize[z + y] = templ; /* Store sample sizes */ + digiFx[z + y] = malloc(fxSize[z + y]); + efread(digiFx[z + y], 1, fxSize[z + y], fi); /* JE: Load sample to buffer */ + } + + fclose(fi); + + notYetLoadedSound = false; + +} + +void JE_playSampleNum( uint8_t samplenum ) +{ + JE_multiSamplePlay(digiFx[samplenum-1], fxSize[samplenum-1], 0, fxPlayVol); +} + +void JE_calcFXVol( void ) // TODO: not sure *exactly* what this does +{ + fxPlayVol = (fxVolume - 1) >> 5; +} + +void JE_setTimerInt( void ) +{ + jasondelay = 1000.0f / (1193180.0f / speed); +} + +void JE_resetTimerInt( void ) +{ + jasondelay = 1000.0f / (1193180.0f / 0x4300); +} + +void JE_changeVolume( uint16_t *music, int music_delta, uint16_t *sample, int sample_delta ) +{ + int music_temp = *music + music_delta, + sample_temp = *sample + sample_delta; + + if (music_delta) + { + if (music_temp > 255) + { + music_temp = 255; + JE_playSampleNum(S_CLINK); + } + else if (music_temp < 0) + { + music_temp = 0; + JE_playSampleNum(S_CLINK); + } + } + + if (sample_delta) + { + if (sample_temp > 255) + { + sample_temp = 255; + JE_playSampleNum(S_CLINK); + } + else if (sample_temp < 0) + { + sample_temp = 0; + JE_playSampleNum(S_CLINK); + } + } + + *music = music_temp; + *sample = sample_temp; + + JE_calcFXVol(); + + set_volume(*music, *sample); +} + diff --git a/pool/shard006/C/0119254_s_isinf.c b/pool/shard006/C/0119254_s_isinf.c new file mode 100644 index 0000000000000000000000000000000000000000..0015433ccca240342214b66c67528b6a5c4fc97e --- /dev/null +++ b/pool/shard006/C/0119254_s_isinf.c @@ -0,0 +1,69 @@ +/*- + * Copyright (c) 2004 David Schultz + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $FreeBSD$ + */ + +#include + +#include "fpmath.h" +#undef isinf + +/* + * XXX These routines belong in libm, but they must remain in libc for + * binary compat until we can bump libm's major version number. + */ + +int +isinf(double d) +{ + union IEEEd2bits u; + + u.d = d; + return (u.bits.exp == 2047 && u.bits.manl == 0 && u.bits.manh == 0); +} + +int +__isinff(float f) +{ + union IEEEf2bits u; + + u.f = f; + return (u.bits.exp == 255 && u.bits.man == 0); +} + +int +__isinfl(long double e) +{ + union IEEEl2bits u; + + u.e = e; + mask_nbit_l(u); +#ifndef __alpha__ + return (u.bits.exp == 32767 && u.bits.manl == 0 && u.bits.manh == 0); +#else + return (u.bits.exp == 2047 && u.bits.manl == 0 && u.bits.manh == 0); +#endif +} diff --git a/pool/shard006/C/0119256_remlock.c b/pool/shard006/C/0119256_remlock.c new file mode 100644 index 0000000000000000000000000000000000000000..ea65ef38b1034d720e9e4dec5810a7796fac9ee4 --- /dev/null +++ b/pool/shard006/C/0119256_remlock.c @@ -0,0 +1,290 @@ +/* + * PROJECT: Kernel + * LICENSE: GPL - See COPYING in the top level directory + * FILE: ntoskrnl/io/iomgr/remlock.c + * PURPOSE: Remove Lock Support + * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org) + * Filip Navara (navaraf@reactos.org) + * Pierre Schweitzer (pierre.schweitzer@reactos.org) + */ + +/* INCLUDES ******************************************************************/ + +#include +#define NDEBUG +#include + +typedef struct _IO_REMOVE_LOCK_TRACKING_BLOCK +{ + PIO_REMOVE_LOCK_TRACKING_BLOCK Next; + PVOID Tag; + LARGE_INTEGER LockMoment; + LPCSTR File; + ULONG Line; +} IO_REMOVE_LOCK_TRACKING_BLOCK; + +/* FUNCTIONS *****************************************************************/ + +/* + * @implemented + */ +VOID +NTAPI +IoInitializeRemoveLockEx(IN PIO_REMOVE_LOCK RemoveLock, + IN ULONG AllocateTag, + IN ULONG MaxLockedMinutes, + IN ULONG HighWatermark, + IN ULONG RemlockSize) +{ + PEXTENDED_IO_REMOVE_LOCK Lock = (PEXTENDED_IO_REMOVE_LOCK)RemoveLock; + PAGED_CODE(); + + DPRINT("%s(%p 0x%08x %u %u %u)\n", __FUNCTION__, RemoveLock, AllocateTag, MaxLockedMinutes, HighWatermark, RemlockSize); + + ASSERT(HighWatermark < MAXLONG); + + /* If no lock given, nothing to do */ + if (!Lock) + { + return; + } + + switch (RemlockSize) + { + /* Check if this is a debug lock */ + case (sizeof(IO_REMOVE_LOCK_DBG_BLOCK) + sizeof(IO_REMOVE_LOCK_COMMON_BLOCK)): + /* Setup debug parameters */ + Lock->Dbg.Signature = 'COLR'; + Lock->Dbg.HighWatermark = HighWatermark; + Lock->Dbg.MaxLockedTicks = KeQueryTimeIncrement() * MaxLockedMinutes * 600000000; + Lock->Dbg.AllocateTag = AllocateTag; + KeInitializeSpinLock(&(Lock->Dbg.Spin)); + Lock->Dbg.LowMemoryCount = 0; + Lock->Dbg.Blocks = NULL; + + case sizeof(IO_REMOVE_LOCK_COMMON_BLOCK): + /* Setup a free block */ + Lock->Common.Removed = FALSE; + Lock->Common.IoCount = 1; + KeInitializeEvent(&Lock->Common.RemoveEvent, + SynchronizationEvent, + FALSE); + } +} + +/* + * @implemented + */ +NTSTATUS +NTAPI +IoAcquireRemoveLockEx(IN PIO_REMOVE_LOCK RemoveLock, + IN OPTIONAL PVOID Tag, + IN LPCSTR File, + IN ULONG Line, + IN ULONG RemlockSize) +{ + KIRQL OldIrql; + LONG LockValue; + PIO_REMOVE_LOCK_TRACKING_BLOCK TrackingBlock; + PEXTENDED_IO_REMOVE_LOCK Lock = (PEXTENDED_IO_REMOVE_LOCK)RemoveLock; + + DPRINT("%s(%p %p %s %u %u)\n", __FUNCTION__, RemoveLock, Tag, File, Line, RemlockSize); + + /* Increase the lock count */ + LockValue = InterlockedIncrement(&(Lock->Common.IoCount)); + ASSERT(LockValue > 0); + if (!Lock->Common.Removed) + { + /* Check what kind of lock this is */ + if (RemlockSize == (sizeof(IO_REMOVE_LOCK_DBG_BLOCK) + sizeof(IO_REMOVE_LOCK_COMMON_BLOCK))) + { + ASSERT(Lock->Dbg.HighWatermark == 0 || LockValue <= Lock->Dbg.HighWatermark); + + /* Allocate a tracking block */ + TrackingBlock = ExAllocatePoolWithTag(NonPagedPool, sizeof(IO_REMOVE_LOCK_TRACKING_BLOCK), Lock->Dbg.AllocateTag); + if (!TrackingBlock) + { + /* Keep count of failures for lock release and missing tags */ + InterlockedIncrement(&(Lock->Dbg.LowMemoryCount)); + } + else + { + /* Initialize block */ + RtlZeroMemory(TrackingBlock, sizeof(IO_REMOVE_LOCK_TRACKING_BLOCK)); + TrackingBlock->Tag = Tag; + TrackingBlock->File = File; + TrackingBlock->Line = Line; + KeQueryTickCount(&(TrackingBlock->LockMoment)); + + /* Queue the block */ + KeAcquireSpinLock(&(Lock->Dbg.Spin), &OldIrql); + TrackingBlock->Next = Lock->Dbg.Blocks; + Lock->Dbg.Blocks = TrackingBlock; + KeReleaseSpinLock(&(Lock->Dbg.Spin), OldIrql); + } + } + } + else + { + /* Otherwise, decrement the count and check if it's gone */ + if (!InterlockedDecrement(&(Lock->Common.IoCount))) + { + /* Signal the event */ + KeSetEvent(&(Lock->Common.RemoveEvent), IO_NO_INCREMENT, FALSE); + } + + /* Return pending delete */ + return STATUS_DELETE_PENDING; + } + + /* Otherwise, return success */ + return STATUS_SUCCESS; +} + +/* + * @implemented + */ +VOID +NTAPI +IoReleaseRemoveLockEx(IN PIO_REMOVE_LOCK RemoveLock, + IN PVOID Tag, + IN ULONG RemlockSize) +{ + KIRQL OldIrql; + LONG LockValue; + BOOLEAN TagFound; + LARGE_INTEGER CurrentMoment; + PIO_REMOVE_LOCK_TRACKING_BLOCK TrackingBlock; + PIO_REMOVE_LOCK_TRACKING_BLOCK *TrackingBlockLink; + PEXTENDED_IO_REMOVE_LOCK Lock = (PEXTENDED_IO_REMOVE_LOCK)RemoveLock; + + DPRINT("%s(%p %p %u)\n", __FUNCTION__, RemoveLock, Tag, RemlockSize); + + /* Check what kind of lock this is */ + if (RemlockSize == (sizeof(IO_REMOVE_LOCK_DBG_BLOCK) + sizeof(IO_REMOVE_LOCK_COMMON_BLOCK))) + { + /* Acquire blocks queue */ + KeAcquireSpinLock(&(Lock->Dbg.Spin), &OldIrql); + + /* Get the release moment */ + KeQueryTickCount(&CurrentMoment); + + /* Start browsing tracking blocks to find a block that would match given tag */ + TagFound = FALSE; + TrackingBlock = Lock->Dbg.Blocks; + TrackingBlockLink = &(Lock->Dbg.Blocks); + while (TrackingBlock != NULL) + { + /* First of all, check if the lock was locked for too long */ + if (Lock->Dbg.MaxLockedTicks && + CurrentMoment.QuadPart - TrackingBlock->LockMoment.QuadPart > Lock->Dbg.MaxLockedTicks) + { + DPRINT("Lock %#08lx (with tag %#08lx) was supposed to be held at max %I64d ticks but lasted longer\n", + Lock, TrackingBlock->Tag, Lock->Dbg.MaxLockedTicks); + DPRINT("Lock was acquired in file %s at line %lu\n", TrackingBlock->File, TrackingBlock->Line); + ASSERT(FALSE); + } + + /* Check if this is the first matching tracking block */ + if ((TagFound == FALSE) && (TrackingBlock->Tag == Tag)) + { + /* Unlink this tracking block, and free it */ + TagFound = TRUE; + *TrackingBlockLink = TrackingBlock->Next; + ExFreePoolWithTag(TrackingBlock, Lock->Dbg.AllocateTag); + TrackingBlock = *TrackingBlockLink; + } + else + { + /* Go to the next tracking block */ + TrackingBlockLink = &(TrackingBlock->Next); + TrackingBlock = TrackingBlock->Next; + } + } + + /* We're done, release queue lock */ + KeReleaseSpinLock(&(Lock->Dbg.Spin), OldIrql); + + /* If we didn't find any matching block */ + if (TagFound == FALSE) + { + /* Check if it was because we were low in memory + * If yes, then ignore, that's normal + */ + if (InterlockedDecrement(&(Lock->Dbg.LowMemoryCount)) < 0) + { + /* Otherwise signal the issue, it shouldn't happen */ + InterlockedIncrement(&(Lock->Dbg.LowMemoryCount)); + DPRINT("Failed finding block for tag: %#08lx\n", Tag); + ASSERT(FALSE); + } + } + } + + /* Decrement the lock count */ + LockValue = InterlockedDecrement(&(Lock->Common.IoCount)); + ASSERT(LockValue >= 0); + + if (!LockValue) + { + /* Someone should be waiting... */ + ASSERT(Lock->Common.Removed); + + /* Signal the event */ + KeSetEvent(&(Lock->Common.RemoveEvent), IO_NO_INCREMENT, FALSE); + } +} + +/* + * @implemented + */ +VOID +NTAPI +IoReleaseRemoveLockAndWaitEx(IN PIO_REMOVE_LOCK RemoveLock, + IN PVOID Tag, + IN ULONG RemlockSize) +{ + LONG LockValue; + PIO_REMOVE_LOCK_TRACKING_BLOCK TrackingBlock; + PEXTENDED_IO_REMOVE_LOCK Lock = (PEXTENDED_IO_REMOVE_LOCK)RemoveLock; + PAGED_CODE(); + + DPRINT("%s(%p %p %u)\n", __FUNCTION__, RemoveLock, Tag, RemlockSize); + + /* Remove the lock and decrement the count */ + Lock->Common.Removed = TRUE; + LockValue = InterlockedDecrement(&Lock->Common.IoCount); + ASSERT(LockValue > 0); + + /* If we are still > 0, then wait for the others to remove lock */ + if (InterlockedDecrement(&Lock->Common.IoCount) > 0) + { + /* Wait for it */ + KeWaitForSingleObject(&(Lock->Common.RemoveEvent), + Executive, + KernelMode, + FALSE, + NULL); + } + + /* Check what kind of lock this is */ + if (RemlockSize == (sizeof(IO_REMOVE_LOCK_DBG_BLOCK) + sizeof(IO_REMOVE_LOCK_COMMON_BLOCK))) + { + /* A block must be remaining */ + ASSERT(Lock->Dbg.Blocks); + + /* Get it */ + TrackingBlock = Lock->Dbg.Blocks; + /* Tag should match */ + if (TrackingBlock->Tag != Tag) + { + DPRINT("Last tracking block tag invalid! Expected: %p, having: %p\n", Tag, TrackingBlock->Tag); + ASSERT(TrackingBlock->Tag != Tag); + } + + /* Release block */ + ExFreePoolWithTag(Lock->Dbg.Blocks, Lock->Dbg.AllocateTag); + } +} + +/* EOF */ diff --git a/pool/shard006/C/0119257_Msaltpepper.c b/pool/shard006/C/0119257_Msaltpepper.c new file mode 100644 index 0000000000000000000000000000000000000000..997147b9ffef193c69525af114472f8cc5ae0def --- /dev/null +++ b/pool/shard006/C/0119257_Msaltpepper.c @@ -0,0 +1,132 @@ +/* Add salt and pepper noise to the data.*/ +/* + Copyright (C) 2004 University of Texas at Austin + + 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 +#include + +#include + +int main (int argc, char* argv[]) +{ + float den, inten, max, *dat; + int n1, n2, point, i, j, seed; + bool rep, noise, allpos; + sf_file in, out; + + sf_init (argc,argv); + in = sf_input ("in"); + out = sf_output("out"); + + if (!sf_histint(in,"n1",&n1)) sf_error("No n1= in input"); + n2 = sf_leftsize(in,1); + + if (SF_FLOAT != sf_gettype(in)) sf_error("Need float input"); + + + if (!sf_getfloat("den",&den)) den=10.; + /* noise density (percent, default=10, Min=0, Max=100) */ + if ( den < 0. ){ + den =0.; + } else { + if ( den > 100.) { + den = 100.; + } + } + den *= 0.01; + + if (!sf_getfloat("inten",&inten)) inten=0.1; + /* noise intensity (multiple peak value of data, default=0.1) */ + + if (!sf_getbool("rep",&rep)) rep=false; + /* if y, replace data with noise */ + + if (!sf_getbool("allpos",&allpos)) allpos=false; + /* if y, assume positive noise */ + + if (!sf_getbool("noise",&noise)) noise=false; + /* if y, output noise only */ + + dat = sf_floatalloc (n1*n2); + + if (!sf_getint("seed",&seed)) seed = time(NULL); + /* random seed */ + + srand((unsigned long) seed); + + if (noise) { + max=0.; + sf_floatread(dat,n1*n2,in); + for (i=0; i + * Copyright (C) 2008 Imre Kaloz + * + * 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 +#include +#include +#include + +#include + +#include + +#include "devices.h" +#include "dev-m25p80.h" +#include "dev-ar913x-wmac.h" + +#define MZK_W300NH_GPIO_LED_STATUS 1 +#define MZK_W300NH_GPIO_LED_WPS 3 +#define MZK_W300NH_GPIO_LED_WLAN 6 +#define MZK_W300NH_GPIO_LED_AP 15 +#define MZK_W300NH_GPIO_LED_ROUTER 16 + +#define MZK_W300NH_GPIO_BTN_APROUTER 5 +#define MZK_W300NH_GPIO_BTN_WPS 12 +#define MZK_W300NH_GPIO_BTN_RESET 21 + +#define MZK_W04NU_BUTTONS_POLL_INTERVAL 20 + +#ifdef CONFIG_MTD_PARTITIONS +static struct mtd_partition mzk_w300nh_partitions[] = { + { + .name = "u-boot", + .offset = 0, + .size = 0x040000, + .mask_flags = MTD_WRITEABLE, + } , { + .name = "u-boot-env", + .offset = 0x040000, + .size = 0x010000, + } , { + .name = "kernel", + .offset = 0x050000, + .size = 0x160000, + } , { + .name = "rootfs", + .offset = 0x1b0000, + .size = 0x610000, + } , { + .name = "config", + .offset = 0x7c0000, + .size = 0x020000, + } , { + .name = "art", + .offset = 0x7e0000, + .size = 0x020000, + .mask_flags = MTD_WRITEABLE, + } , { + .name = "firmware", + .offset = 0x050000, + .size = 0x770000, + } +}; +#endif /* CONFIG_MTD_PARTITIONS */ + +static struct flash_platform_data mzk_w300nh_flash_data = { +#ifdef CONFIG_MTD_PARTITIONS + .parts = mzk_w300nh_partitions, + .nr_parts = ARRAY_SIZE(mzk_w300nh_partitions), +#endif +}; + +static struct gpio_led mzk_w300nh_leds_gpio[] __initdata = { + { + .name = "mzk-w300nh:green:status", + .gpio = MZK_W300NH_GPIO_LED_STATUS, + .active_low = 1, + }, { + .name = "mzk-w300nh:blue:wps", + .gpio = MZK_W300NH_GPIO_LED_WPS, + .active_low = 1, + }, { + .name = "mzk-w300nh:green:wlan", + .gpio = MZK_W300NH_GPIO_LED_WLAN, + .active_low = 1, + }, { + .name = "mzk-w300nh:green:ap", + .gpio = MZK_W300NH_GPIO_LED_AP, + .active_low = 1, + }, { + .name = "mzk-w300nh:green:router", + .gpio = MZK_W300NH_GPIO_LED_ROUTER, + .active_low = 1, + } +}; + +static struct gpio_button mzk_w300nh_gpio_buttons[] __initdata = { + { + .desc = "reset", + .type = EV_KEY, + .code = BTN_0, + .threshold = 5, + .gpio = MZK_W300NH_GPIO_BTN_RESET, + .active_low = 1, + }, { + .desc = "wps", + .type = EV_KEY, + .code = BTN_1, + .threshold = 5, + .gpio = MZK_W300NH_GPIO_BTN_WPS, + .active_low = 1, + }, { + .desc = "aprouter", + .type = EV_KEY, + .code = BTN_2, + .threshold = 5, + .gpio = MZK_W300NH_GPIO_BTN_APROUTER, + .active_low = 0, + } +}; + +static void __init mzk_w300nh_setup(void) +{ + u8 *mac = (u8 *) KSEG1ADDR(0x1fff1000); + + ar71xx_set_mac_base(mac); + + ar71xx_add_device_mdio(0x0); + + ar71xx_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RMII; + ar71xx_eth0_data.phy_mask = 0xf; + ar71xx_eth0_data.speed = SPEED_100; + ar71xx_eth0_data.duplex = DUPLEX_FULL; + ar71xx_eth0_data.has_ar8216 = 1; + + ar71xx_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_RMII; + ar71xx_eth1_data.phy_mask = 0x10; + + ar71xx_add_device_eth(0); + ar71xx_add_device_eth(1); + + ar71xx_add_device_m25p80(&mzk_w300nh_flash_data); + + ar71xx_add_device_leds_gpio(-1, ARRAY_SIZE(mzk_w300nh_leds_gpio), + mzk_w300nh_leds_gpio); + + ar71xx_add_device_gpio_buttons(-1, MZK_W04NU_BUTTONS_POLL_INTERVAL, + ARRAY_SIZE(mzk_w300nh_gpio_buttons), + mzk_w300nh_gpio_buttons); + ar913x_add_device_wmac(); +} + +MIPS_MACHINE(AR71XX_MACH_MZK_W300NH, "Planex MZK-W300NH", mzk_w300nh_setup); diff --git a/pool/shard006/C/0119267_main-cubehash-test.c b/pool/shard006/C/0119267_main-cubehash-test.c new file mode 100644 index 0000000000000000000000000000000000000000..0d22e07a2e2632d04f8359999bf04f9ab6e20d17 --- /dev/null +++ b/pool/shard006/C/0119267_main-cubehash-test.c @@ -0,0 +1,103 @@ +/* main-cubehash-test.c */ +/* + This file is part of the AVR-Crypto-Lib. + Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) + + 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 . +*/ +/* + * CubeHash test-suit + * +*/ + +#include "main-test-common.h" + +#include "cubehash.h" +#include "hfal_cubehash.h" +#include "shavs.h" +#include "nessie_hash_test.h" +#include "performance_test.h" +#include "hfal-nessie.h" +#include "hfal-performance.h" +#include "hfal-test.h" + +char *algo_name = "CubeHash"; + + +const hfdesc_t *const algolist[] PROGMEM = { + (hfdesc_t*)&cubehash224_desc, + (hfdesc_t*)&cubehash256_desc, + (hfdesc_t*)&cubehash384_desc, + (hfdesc_t*)&cubehash512_desc, + NULL +}; + +/***************************************************************************** + * additional validation-functions * + *****************************************************************************/ + +void cubehash256_test0(void){ + cubehash_ctx_t ctx; + uint8_t hash[32]; + cubehash256_init(&ctx); + cli_putstr_P(PSTR("\r\ninit done ")); + cubehash_lastBlock(&ctx, NULL, 0); + cli_putstr_P(PSTR("\r\nlastblock done ")); + cubehash256_ctx2hash(hash, &ctx); + cli_putstr_P(PSTR("\r\nhash = ")); + cli_hexdump(hash, 32); +} + +void performance_cubehash(void){ + hfal_performance_multiple(algolist); +} + +void testrun_nessie_cubehash(void){ + hfal_nessie_multiple(algolist); +} +/***************************************************************************** + * main * + *****************************************************************************/ + +const char nessie_str[] PROGMEM = "nessie"; +const char test256_str[] PROGMEM = "test256"; +const char performance_str[] PROGMEM = "performance"; +const char echo_str[] PROGMEM = "echo"; +const char shavs_list_str[] PROGMEM = "shavs_list"; +const char shavs_set_str[] PROGMEM = "shavs_set"; +const char shavs_test1_str[] PROGMEM = "shavs_test1"; +const char shavs_test3_str[] PROGMEM = "shavs_test3"; + +const cmdlist_entry_t cmdlist[] PROGMEM = { + { nessie_str, NULL, testrun_nessie_cubehash }, + { test256_str, NULL, cubehash256_test0 }, + { performance_str, NULL, performance_cubehash }, + { shavs_list_str, NULL, shavs_listalgos }, + { shavs_set_str, (void*)1, (void_fpt)shavs_setalgo }, + { shavs_test1_str, NULL, shavs_test1 }, + { shavs_test3_str, NULL, shavs_test3 }, + { echo_str, (void*)1, (void_fpt)echo_ctrl }, + { NULL, NULL, NULL } +}; + +int main (void){ + main_setup(); + + shavs_algolist=(hfdesc_t**)algolist; + shavs_algo=(hfdesc_t*)&cubehash256_desc; + for(;;){ + welcome_msg(algo_name); + cmd_interface(cmdlist); + } +} diff --git a/pool/shard006/C/0119269_bb_ble_periodiclist.c b/pool/shard006/C/0119269_bb_ble_periodiclist.c new file mode 100644 index 0000000000000000000000000000000000000000..e821ec924f43da14f7e6c8872a1dd1e8326b95ea --- /dev/null +++ b/pool/shard006/C/0119269_bb_ble_periodiclist.c @@ -0,0 +1,220 @@ +/*************************************************************************************************/ +/*! + * \file + * + * \brief Generic BLE whitelist implementation file. + * + * Copyright (c) 2013-2018 Arm Ltd. All Rights Reserved. + * + * Copyright (c) 2019-2020 Packetcraft, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/*************************************************************************************************/ + +#include "bb_ble_api.h" +#include "wsf_assert.h" +#include "util/bda.h" +#include "util/bstream.h" +#include + +/************************************************************************************************** + Data Types +**************************************************************************************************/ + +/*! \brief Periodic list filter table entry. */ +typedef struct +{ + uint64_t addr; /*!< Address. */ + uint8_t addrType; /*!< Address type. */ + uint8_t SID; /*!< Set ID. */ +} bbBlePeriodicListEntry_t; + +/************************************************************************************************** + Globals +**************************************************************************************************/ + +static bbBlePeriodicListEntry_t *pBbBlePeriodicListFilt; /*!< Periodic list filter. */ +static uint8_t bbBlePeriodicListNumEntries; /*!< Number of valid periodic list entries. */ +static uint8_t bbBlePeriodicListNumEntriesMax; /*!< Maximum number of periodic list entries. */ + +/*************************************************************************************************/ +/*! + * \brief Initialize periodic list. + * + * \param numEntries Number of periodic list entries to provide. + * \param pFreeMem Pointer to free memory. + * \param freeMemSize Size of pFreeMem. + * + * \return Amount of free memory consumed. + * + * This function initializes the white list. + * + * \note This function must be called once before initializing the LL. + */ +/*************************************************************************************************/ +uint16_t BbBleInitPeriodicList(uint8_t numEntries, uint8_t *pFreeMem, uint32_t freeMemSize) +{ + uint8_t *pAvailMem = pFreeMem; + + bbBlePeriodicListNumEntries = 0; + bbBlePeriodicListNumEntriesMax = 0; + + /* Allocate memory. */ + if (((uint32_t)pAvailMem) & 3) + { + /* Align to next word. */ + pAvailMem = (uint8_t *)(((uint32_t)pAvailMem & ~3) + sizeof(uint32_t)); + } + pBbBlePeriodicListFilt = (bbBlePeriodicListEntry_t *)pAvailMem; + pAvailMem += sizeof(bbBlePeriodicListEntry_t) * numEntries; + + /* Check memory allocation. */ + if (((uint32_t)(pAvailMem - pFreeMem)) > freeMemSize) + { + WSF_ASSERT(FALSE); + return 0; + } + + bbBlePeriodicListNumEntriesMax = numEntries; + return (pAvailMem - pFreeMem); +} + +/*************************************************************************************************/ +/*! + * \brief Check if address is periodic listed. + * + * \param addrType Address type. + * \param addr Bluetooth device address. + * \param SID Set ID. + * + * \return TRUE if periodic listed, FALSE otherwise. + */ +/*************************************************************************************************/ +bool_t BbBlePeriodicListCheckAddr(uint8_t addrType, uint64_t addr, uint8_t SID) +{ + for (unsigned int i = 0; i < bbBlePeriodicListNumEntries; i++) + { + if ((pBbBlePeriodicListFilt[i].addrType == addrType) && + (pBbBlePeriodicListFilt[i].addr == addr) && + (pBbBlePeriodicListFilt[i].SID == SID)) + { + /* Peer is in periodic list, allow PDU to pass through the filter. */ + return TRUE; + } + } + + /* Peer is not in periodic list, filter out PDU. */ + return FALSE; +} + +/*************************************************************************************************/ +/*! + * \brief Get periodic list size. + * + * \return Total number of periodic list entries. + * + * Read the periodic list capacity supported by the BB. + */ +/*************************************************************************************************/ +uint8_t BbBlePeriodicListGetSize(void) +{ + return bbBlePeriodicListNumEntriesMax; +} + +/*************************************************************************************************/ +/*! + * \brief Clear all periodic list entries. + * + * Clear all periodic list entries stored in the BB. + * + * \note No resource synchronization is required to modify the periodic list resource as + * the LL modifies the periodic list only when advertising events are disabled. + */ +/*************************************************************************************************/ +void BbBlePeriodicListClear(void) +{ + bbBlePeriodicListNumEntries = 0; +} + +/*************************************************************************************************/ +/*! + * \brief Add device to the periodic list. + * + * \param addrType Address type. + * \param addr Bluetooth device address. + * \param SID Set ID. + * + * \return TRUE if successful, FALSE if list full. + * + * Adds the given address to the periodic list stored in the BB. + * + * \note No resource synchronization is required to modify the periodic list resource as + * the LL modifies the periodic list only when advertising events are disabled. + */ +/*************************************************************************************************/ +bool_t BbBlePeriodicListAdd(uint8_t addrType, uint64_t addr, uint8_t SID) +{ + if (bbBlePeriodicListNumEntries < bbBlePeriodicListNumEntriesMax) + { + pBbBlePeriodicListFilt[bbBlePeriodicListNumEntries].addrType = addrType; + pBbBlePeriodicListFilt[bbBlePeriodicListNumEntries].addr = addr; + pBbBlePeriodicListFilt[bbBlePeriodicListNumEntries].SID = SID; + + bbBlePeriodicListNumEntries++; + return TRUE; + } + + /* List full. */ + return FALSE; +} + +/*************************************************************************************************/ +/*! + * \brief Remove device from the periodic list. + * + * \param addrType Address type. + * \param addr Bluetooth device address. + * \param SID Set ID. + * + * + * \return TRUE if successful, FALSE if address not in the list. + * + * Removes the given address from the periodic list stored in the BB. + * + * \note No resource synchronization is required to modify the white list resource as + * the LL modifies the white list only when advertising events are disabled. + */ +/*************************************************************************************************/ +bool_t BbBlePeriodicListRemove(uint8_t addrType, uint64_t addr, uint8_t SID) +{ + for (uint8_t i = 0; i < bbBlePeriodicListNumEntries; i++) + { + if ((pBbBlePeriodicListFilt[i].addrType == addrType) && + (pBbBlePeriodicListFilt[i].addr == addr) && + (pBbBlePeriodicListFilt[i].SID == SID)) + { + /* If there is more than one entry, move the last entry into this slot. */ + if ((bbBlePeriodicListNumEntries > 1) && (i != bbBlePeriodicListNumEntries - 1)) + { + pBbBlePeriodicListFilt[i].addrType = pBbBlePeriodicListFilt[bbBlePeriodicListNumEntries - 1].addrType; + pBbBlePeriodicListFilt[i].addr = pBbBlePeriodicListFilt[bbBlePeriodicListNumEntries - 1].addr; + pBbBlePeriodicListFilt[i].SID = pBbBlePeriodicListFilt[bbBlePeriodicListNumEntries - 1].SID; + } + bbBlePeriodicListNumEntries--; + return TRUE; + } + } + + return FALSE; +} diff --git a/pool/shard006/C/0119271_elf_memory.c b/pool/shard006/C/0119271_elf_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..c7990cc0ce557adf6eccd2f6eac1f90fde949416 --- /dev/null +++ b/pool/shard006/C/0119271_elf_memory.c @@ -0,0 +1,92 @@ +/*- + * Copyright (c) 2006,2008 Joseph Koshy + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include + +#include +#include +#include + +#include "_libelf.h" + +LIBELF_VCSID("$Id$"); + +Elf * +elf_memory(char *image, size_t sz) +{ + Elf *e; + + if (LIBELF_PRIVATE(version) == EV_NONE) { + LIBELF_SET_ERROR(SEQUENCE, 0); + return (NULL); + } + + if (image == NULL || sz == 0) { + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + } + + if ((e = _libelf_allocate_elf()) == NULL) + return (NULL); + + e->e_cmd = ELF_C_READ; + e->e_rawfile = image; + e->e_rawsize = sz; + +#undef LIBELF_IS_ELF +#define LIBELF_IS_ELF(P) ((P)[EI_MAG0] == ELFMAG0 && \ + (P)[EI_MAG1] == ELFMAG1 && (P)[EI_MAG2] == ELFMAG2 && \ + (P)[EI_MAG3] == ELFMAG3) + + if (sz > EI_NIDENT && LIBELF_IS_ELF(image)) { + _libelf_init_elf(e, ELF_K_ELF); + e->e_class = image[EI_CLASS]; + e->e_byteorder = image[EI_DATA]; + e->e_version = image[EI_VERSION]; + + if (e->e_version > EV_CURRENT) { + e = _libelf_release_elf(e); + LIBELF_SET_ERROR(VERSION, 0); + return (NULL); + } + + if ((e->e_byteorder != ELFDATA2LSB && e->e_byteorder != + ELFDATA2MSB) || (e->e_class != ELFCLASS32 && e->e_class != + ELFCLASS64)) { + e = _libelf_release_elf(e); + LIBELF_SET_ERROR(HEADER, 0); + return (NULL); + } + + } else if (sz >= SARMAG && + strncmp(image, ARMAG, (size_t) SARMAG) == 0) { + _libelf_init_elf(e, ELF_K_AR); + e = _libelf_ar_open(e); + } else + _libelf_init_elf(e, ELF_K_NONE); + + return (e); +} diff --git a/pool/shard006/C/0119272_virtio_blk.c b/pool/shard006/C/0119272_virtio_blk.c new file mode 100644 index 0000000000000000000000000000000000000000..0fa9a729119bf738d26859fb307a1ed919ac46e8 --- /dev/null +++ b/pool/shard006/C/0119272_virtio_blk.c @@ -0,0 +1,269 @@ +/* + * Copyright (c) 2015-2019 Contributors as noted in the AUTHORS file + * + * This file is part of Solo5, a sandboxed execution environment. + * + * Permission to use, copy, modify, and/or distribute this software + * for any purpose with or without fee is hereby granted, provided + * that the above copyright notice and this permission notice appear + * in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "bindings.h" +#include "virtio_ring.h" +#include "virtio_pci.h" + +#define VIRTIO_BLK_ID_BYTES 20 +#define VIRTIO_BLK_T_IN 0 /* read */ +#define VIRTIO_BLK_T_OUT 1 /* write */ +#define VIRTIO_BLK_T_SCSI_CMD 2 +#define VIRTIO_BLK_T_SCSI_CMD_OUT 3 +#define VIRTIO_BLK_T_FLUSH 4 +#define VIRTIO_BLK_T_FLUSH_OUT 5 +#define VIRTIO_BLK_T_GET_ID 8 +#define VIRTIO_BLK_T_BARRIER 0x80000000 + +#define VIRTIO_BLK_S_OK 0 +#define VIRTIO_BLK_S_IOERR 1 +#define VIRTIO_BLK_S_UNSUPP 2 + +static uint64_t virtio_blk_sectors; + +#define VIRTIO_BLK_SECTOR_SIZE 512 + +struct virtio_blk_hdr { + uint32_t type; + uint32_t ioprio; + uint64_t sector; +}; + +static struct virtq blkq; +#define VIRTQ_BLK 0 + +static uint16_t virtio_blk_pci_base; /* base in PCI config space */ + +static bool blk_configured; +static bool blk_acquired; +static solo5_handle_t blk_handle; +extern struct mft *virtio_manifest; + +/* Returns the index to the head of the buffers chain. */ +static uint16_t virtio_blk_op(uint32_t type, + uint64_t sector, + void *data, size_t len) +{ + uint16_t mask = blkq.num - 1; + struct virtio_blk_hdr hdr; + struct io_buffer *head_buf, *data_buf, *status_buf; + uint16_t head = blkq.next_avail & mask; + + assert(len <= VIRTIO_BLK_SECTOR_SIZE); + + head_buf = &blkq.bufs[head]; + data_buf = &blkq.bufs[(head + 1) & mask]; + status_buf = &blkq.bufs[(head + 2) & mask]; + + hdr.type = type; + hdr.ioprio = 0; + hdr.sector = sector; + + /* The header buf */ + memcpy(head_buf->data, &hdr, sizeof(struct virtio_blk_hdr)); + head_buf->len = sizeof(struct virtio_blk_hdr); + head_buf->extra_flags = 0; + + /* The data buf */ + if (type == VIRTIO_BLK_T_OUT) /* write */ { + memcpy(data_buf->data, data, len); + data_buf->extra_flags = 0; + } else + data_buf->extra_flags = VIRTQ_DESC_F_WRITE; + data_buf->len = len; + + /* The status buf */ + status_buf->len = sizeof(uint8_t); + status_buf->extra_flags = VIRTQ_DESC_F_WRITE; + + assert(virtq_add_descriptor_chain(&blkq, head, 3) == 0); + + outw(virtio_blk_pci_base + VIRTIO_PCI_QUEUE_NOTIFY, VIRTQ_BLK); + + return head; +} + +/* + * Returns the status (0 is OK, -1 is not) + * + * This function assumes that no other pending IO is submitted at the same + * time. That is true as long as we use only synchronous IO calls, and if + * there is just a sync call at a time (which is true for solo5). + */ +static int virtio_blk_op_sync(uint32_t type, + uint64_t sector, + void *data, size_t len) +{ + uint16_t mask = blkq.num - 1; + uint16_t head; + struct io_buffer *data_buf, *status_buf; + uint8_t status; + + head = virtio_blk_op(type, sector, data, len); + data_buf = &blkq.bufs[(head + 1) & mask]; + status_buf = &blkq.bufs[(head + 2) & mask]; + + /* Loop until the device used all of our descriptors. */ + while (blkq.used->idx != blkq.avail->idx) + ; + + /* Consume all the recently used descriptors. */ + for (; blkq.used->idx != blkq.last_used; blkq.last_used++) { + struct virtq_used_elem *e; + + /* Assert that the used descriptor matches the descriptor of the + * IO we started at the start of this function. */ + e = &(blkq.used->ring[blkq.last_used & mask]); + assert(head == e->id); + + blkq.num_avail += 3; /* 3 descriptors per chain */ + } + + status = (*(uint8_t *)status_buf); + if (status != VIRTIO_BLK_S_OK) + return -1; + + if (type == VIRTIO_BLK_T_IN) /* read */ + memcpy(data, data_buf->data, len); + + return 0; +} + +void virtio_config_block(struct pci_config_info *pci) +{ + uint8_t ready_for_init = VIRTIO_PCI_STATUS_ACK | VIRTIO_PCI_STATUS_DRIVER; + uint32_t host_features, guest_features; + size_t pgs; + + outb(pci->base + VIRTIO_PCI_STATUS, 0); + outb(pci->base + VIRTIO_PCI_STATUS, ready_for_init); + + host_features = inl(pci->base + VIRTIO_PCI_HOST_FEATURES); + + /* don't negotiate anything for now */ + guest_features = 0; + outl(pci->base + VIRTIO_PCI_GUEST_FEATURES, guest_features); + + virtio_blk_sectors = inq(pci->base + VIRTIO_PCI_CONFIG_OFF); + log(INFO, "Solo5: PCI:%02x:%02x: configured, capacity=%llu sectors, " + "features=0x%x\n", + pci->bus, pci->dev, (unsigned long long)virtio_blk_sectors, + host_features); + + virtq_init_rings(pci->base, &blkq, 0); + + pgs = (((blkq.num * sizeof (struct io_buffer)) - 1) >> PAGE_SHIFT) + 1; + blkq.bufs = mem_ialloc_pages(pgs); + assert(blkq.bufs); + memset(blkq.bufs, 0, pgs << PAGE_SHIFT); + + virtio_blk_pci_base = pci->base; + blk_configured = 1; + + /* + * We don't need to get interrupts every time the device uses our + * descriptors. + */ + + blkq.avail->flags |= VIRTQ_AVAIL_F_NO_INTERRUPT; + + outb(pci->base + VIRTIO_PCI_STATUS, VIRTIO_PCI_STATUS_DRIVER_OK); +} + +/* + * FIXME: This is a single-device implementation of the new manifest-based + * APIs. On virtio, this call has the following semantics: + * + * 1. The first call to solo5_block_acquire() asking for a handle to a valid + * block device (one specified in the application manifest) will succeed, + * and return a handle for the sole virtio block device. + * 2. All subsequent calls will return an error. + * + * Note that the presence of a virtio block device is registered during boot + * in (blk_configured), and the initial acquisition by solo5_block_acquire() is + * registered in (blk_acquired). + */ +solo5_result_t solo5_block_acquire(const char *name, solo5_handle_t *h, + struct solo5_block_info *info) +{ + if (!blk_configured || blk_acquired) + return SOLO5_R_EUNSPEC; + + unsigned mft_index; + struct mft_entry *mft_e = mft_get_by_name(virtio_manifest, name, + MFT_DEV_BLOCK_BASIC, &mft_index); + if (mft_e == NULL) + return SOLO5_R_EINVAL; + blk_handle = mft_index; + blk_acquired = true; + + info->block_size = VIRTIO_BLK_SECTOR_SIZE; + info->capacity = virtio_blk_sectors * VIRTIO_BLK_SECTOR_SIZE; + *h = mft_index; + log(INFO, "Solo5: Application acquired '%s' as block device\n", name); + return SOLO5_R_OK; +} + +solo5_result_t solo5_block_write(solo5_handle_t h, solo5_off_t offset, + const uint8_t *buf, size_t size) +{ + if (!blk_acquired || h != blk_handle) + return SOLO5_R_EINVAL; + + /* + * XXX: This does not check for writes ending past the end of the device, + * virtio_blk_op_sync() will return -1 (translated to SOLO5_R_EUNSPEC) + * below. + */ + uint64_t sector = offset / VIRTIO_BLK_SECTOR_SIZE; + if ((offset % VIRTIO_BLK_SECTOR_SIZE != 0) || + (sector >= virtio_blk_sectors) || + (size != VIRTIO_BLK_SECTOR_SIZE)) + return SOLO5_R_EINVAL; + + /* + * XXX: removing the const qualifier from buf here is fine with the current + * implementation which does a memcpy() on VIRTIO_BLK_T_OUT, however the + * internal interfaces should be refactored to reflect this. + */ + int rv = virtio_blk_op_sync(VIRTIO_BLK_T_OUT, sector, (uint8_t *)buf, size); + return (rv == 0) ? SOLO5_R_OK : SOLO5_R_EUNSPEC; +} + +solo5_result_t solo5_block_read(solo5_handle_t h, solo5_off_t offset, + uint8_t *buf, size_t size) +{ + if (!blk_acquired || h != blk_handle) + return SOLO5_R_EINVAL; + + /* + * XXX: This does not check for reads ending past the end of the device, + * virtio_blk_op_sync() will return -1 (translated to SOLO5_R_EUNSPEC) + * below. + */ + uint64_t sector = offset / VIRTIO_BLK_SECTOR_SIZE; + if ((offset % VIRTIO_BLK_SECTOR_SIZE != 0) || + (sector >= virtio_blk_sectors) || + (size != VIRTIO_BLK_SECTOR_SIZE)) + return SOLO5_R_EINVAL; + + int rv = virtio_blk_op_sync(VIRTIO_BLK_T_IN, sector, buf, size); + return (rv == 0) ? SOLO5_R_OK : SOLO5_R_EUNSPEC; +} diff --git a/pool/shard006/C/0119274_CWE126_Buffer_Overread__char_alloca_loop_67b.c b/pool/shard006/C/0119274_CWE126_Buffer_Overread__char_alloca_loop_67b.c new file mode 100644 index 0000000000000000000000000000000000000000..96fcd7949902dae3158a919e135f39ac32659cf5 --- /dev/null +++ b/pool/shard006/C/0119274_CWE126_Buffer_Overread__char_alloca_loop_67b.c @@ -0,0 +1,73 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE126_Buffer_Overread__char_alloca_loop_67b.c +Label Definition File: CWE126_Buffer_Overread.stack.label.xml +Template File: sources-sink-67b.tmpl.c +*/ +/* + * @description + * CWE: 126 Buffer Over-read + * BadSource: Set data pointer to a small buffer + * GoodSource: Set data pointer to a large buffer + * Sinks: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +typedef struct _CWE126_Buffer_Overread__char_alloca_loop_67_structType +{ + char * structFirst; +} CWE126_Buffer_Overread__char_alloca_loop_67_structType; + +#ifndef OMITBAD + +void CWE126_Buffer_Overread__char_alloca_loop_67b_badSink(CWE126_Buffer_Overread__char_alloca_loop_67_structType myStruct) +{ + char * data = myStruct.structFirst; + { + size_t i, destLen; + char dest[100]; + memset(dest, 'C', 100-1); + dest[100-1] = '\0'; /* null terminate */ + destLen = strlen(dest); + /* POTENTIAL FLAW: using length of the dest where data + * could be smaller than dest causing buffer overread */ + for (i = 0; i < destLen; i++) + { + dest[i] = data[i]; + } + dest[100-1] = '\0'; + printLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE126_Buffer_Overread__char_alloca_loop_67b_goodG2BSink(CWE126_Buffer_Overread__char_alloca_loop_67_structType myStruct) +{ + char * data = myStruct.structFirst; + { + size_t i, destLen; + char dest[100]; + memset(dest, 'C', 100-1); + dest[100-1] = '\0'; /* null terminate */ + destLen = strlen(dest); + /* POTENTIAL FLAW: using length of the dest where data + * could be smaller than dest causing buffer overread */ + for (i = 0; i < destLen; i++) + { + dest[i] = data[i]; + } + dest[100-1] = '\0'; + printLine(dest); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard006/C/0119280_main.c b/pool/shard006/C/0119280_main.c new file mode 100644 index 0000000000000000000000000000000000000000..9fdf4c82bf0408cc72cbe4d39674f520a784bad3 --- /dev/null +++ b/pool/shard006/C/0119280_main.c @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include +#include + +file_t* stdout = NULL; +file_t* stdin = NULL; + +int main(int argc, char** argv) +{ + int pid = system_pid(); + trui_window_t window = trui_create_window("Hello World!"); + trui_syslog_writeline("Got WINID: %d", window); + + trui_create_label(2, 2, 50, "This is a simple label!"); + trui_create_button(2, 4, 20, "Close application"); + + trui_servermessage_t responce; + while(mq_recv(&responce, sizeof(trui_servermessage_t), MQ_NOFLAGS)) + { + if(responce.message == TRUI_BUTTON_PRESSED) + { + trui_syslog_writeline("Button %d was pressed. Exiting PID %d", responce.param, pid); + break; + } + } + trui_close(); + return 0; +} diff --git a/pool/shard006/C/0119281_keymap-android.c b/pool/shard006/C/0119281_keymap-android.c new file mode 100644 index 0000000000000000000000000000000000000000..adcc3229476adc7704ce534f96d4df9103319814 --- /dev/null +++ b/pool/shard006/C/0119281_keymap-android.c @@ -0,0 +1,184 @@ +/*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id: keymap-android.c 29333 2011-02-19 01:13:38Z kugel $ + * + * Copyright (C) 2010 Maurus Cuelenaere + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ + +/* Button Code Definitions for Android targets */ + +#include +#include +#include + +#include "config.h" +#include "action.h" +#include "button.h" +#include "settings.h" + +/* + * The format of the list is as follows + * { Action Code, Button code, Prereq button code } + * if there's no need to check the previous button's value, use BUTTON_NONE + * Insert LAST_ITEM_IN_LIST at the end of each mapping + */ + +static const struct button_mapping button_context_standard[] = { + { ACTION_STD_PREV, BUTTON_DPAD_UP|BUTTON_REL, BUTTON_NONE }, + { ACTION_STD_NEXT, BUTTON_DPAD_DOWN|BUTTON_REL, BUTTON_NONE }, + + { ACTION_STD_OK, BUTTON_DPAD_CENTER, BUTTON_NONE }, + { ACTION_STD_OK, BUTTON_DPAD_RIGHT|BUTTON_REL, BUTTON_NONE }, + { ACTION_STD_CANCEL, BUTTON_BACK, BUTTON_NONE }, + { ACTION_STD_CANCEL, BUTTON_BACK|BUTTON_REPEAT, BUTTON_BACK }, + { ACTION_STD_CANCEL, BUTTON_DPAD_LEFT|BUTTON_REL, BUTTON_NONE }, + + { ACTION_STD_MENU, BUTTON_MENU|BUTTON_REL, BUTTON_MENU }, + { ACTION_STD_CONTEXT, BUTTON_MENU|BUTTON_REPEAT, BUTTON_MENU }, + + /* special hack to get a redraw on activity resume, see lcd-android.c */ + { ACTION_REDRAW, BUTTON_FORCE_REDRAW, BUTTON_NONE }, + + LAST_ITEM_IN_LIST +}; /* button_context_standard */ + +static const struct button_mapping button_context_wps[] = { + { ACTION_WPS_BROWSE, BUTTON_BACK, BUTTON_NONE }, + { ACTION_WPS_MENU, BUTTON_MENU|BUTTON_REL, BUTTON_MENU }, + { ACTION_WPS_CONTEXT, BUTTON_MENU|BUTTON_REPEAT, BUTTON_MENU }, + + LAST_ITEM_IN_LIST +}; /* button_context_wps */ + +static const struct button_mapping button_context_list[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD) +}; /* button_context_list */ + +static const struct button_mapping button_context_tree[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_LIST) +}; /* button_context_tree */ + +static const struct button_mapping button_context_listtree_scroll_with_combo[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_CUSTOM|CONTEXT_TREE), +}; + +static const struct button_mapping button_context_listtree_scroll_without_combo[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_CUSTOM|CONTEXT_TREE), +}; + +static const struct button_mapping button_context_settings[] = { + { ACTION_SETTINGS_INC, BUTTON_DPAD_RIGHT|BUTTON_REL, BUTTON_NONE }, + { ACTION_SETTINGS_DEC, BUTTON_DPAD_LEFT|BUTTON_REL, BUTTON_NONE }, + { ACTION_STD_OK, BUTTON_DPAD_CENTER, BUTTON_NONE }, + { ACTION_STD_CANCEL, BUTTON_BACK, BUTTON_NONE }, + + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD) +}; /* button_context_settings */ + +static const struct button_mapping button_context_settings_right_is_inc[] = { + + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD) +}; /* button_context_settingsgraphical */ + +static const struct button_mapping button_context_yesno[] = { + { ACTION_YESNO_ACCEPT, BUTTON_DPAD_CENTER, BUTTON_NONE }, + + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD) +}; /* button_context_settings_yesno */ + +static const struct button_mapping button_context_colorchooser[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_CUSTOM|CONTEXT_SETTINGS), +}; /* button_context_colorchooser */ + +static const struct button_mapping button_context_eq[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_CUSTOM|CONTEXT_SETTINGS), +}; /* button_context_eq */ + +/** Bookmark Screen **/ +static const struct button_mapping button_context_bmark[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_LIST), +}; /* button_context_bmark */ + +static const struct button_mapping button_context_time[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_SETTINGS), +}; /* button_context_time */ + +static const struct button_mapping button_context_quickscreen[] = { + { ACTION_STD_CANCEL, BUTTON_BACK|BUTTON_REL, BUTTON_NONE }, + + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD) +}; /* button_context_quickscreen */ + +static const struct button_mapping button_context_pitchscreen[] = { + + { ACTION_PS_INC_SMALL, BUTTON_DPAD_RIGHT|BUTTON_REL, BUTTON_NONE }, + { ACTION_PS_DEC_SMALL, BUTTON_DPAD_LEFT|BUTTON_REL, BUTTON_NONE }, + { ACTION_PS_EXIT, BUTTON_BACK, BUTTON_NONE }, + + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_STD) +}; /* button_context_pitchcreen */ + + +static const struct button_mapping button_context_radio[] = { + LAST_ITEM_IN_LIST__NEXTLIST(CONTEXT_SETTINGS) +}; /* button_context_radio */ + +const struct button_mapping* target_get_context_mapping(int context) +{ + switch (context) + { + case CONTEXT_STD: + return button_context_standard; + case CONTEXT_WPS: + return button_context_wps; + + case CONTEXT_LIST: + return button_context_list; + case CONTEXT_MAINMENU: + case CONTEXT_TREE: + if (global_settings.hold_lr_for_scroll_in_list) + return button_context_listtree_scroll_without_combo; + else + return button_context_listtree_scroll_with_combo; + case CONTEXT_CUSTOM|CONTEXT_TREE: + return button_context_tree; + + case CONTEXT_SETTINGS: + return button_context_settings; + case CONTEXT_CUSTOM|CONTEXT_SETTINGS: + case CONTEXT_SETTINGS_RECTRIGGER: + return button_context_settings_right_is_inc; + + case CONTEXT_SETTINGS_COLOURCHOOSER: + return button_context_colorchooser; + case CONTEXT_SETTINGS_EQ: + return button_context_eq; + + case CONTEXT_SETTINGS_TIME: + return button_context_time; + + case CONTEXT_FM: + return button_context_radio; + case CONTEXT_BOOKMARKSCREEN: + return button_context_bmark; + case CONTEXT_QUICKSCREEN: + return button_context_quickscreen; + case CONTEXT_PITCHSCREEN: + return button_context_pitchscreen; + } + return button_context_standard; +} diff --git a/pool/shard006/C/0119282_server_tcpforward.c b/pool/shard006/C/0119282_server_tcpforward.c new file mode 100644 index 0000000000000000000000000000000000000000..a424ab8d75fcc9f15b4499ab9e2117e47c281dae --- /dev/null +++ b/pool/shard006/C/0119282_server_tcpforward.c @@ -0,0 +1,218 @@ +/* server_tcpforward.c + * + * Server side of tcpip forwarding. + * + */ + +/* lsh, an implementation of the ssh protocol + * + * Copyright (C) 1998, 2005 Balázs Scheidler, Niels Möller + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA + */ + +#if HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include "tcpforward.h" + +#include "channel_forward.h" +#include "format.h" +#include "io.h" +#include "lsh_string.h" +#include "ssh.h" +#include "werror.h" +#include "xalloc.h" + +#include "server_tcpforward.c.x" + + +/* Handling of tcpip-forward */ + +/* GABA: + (class + (name server_forward) + (super forwarded_port) + (vars + (port object resource))) +*/ + +static struct server_forward * +make_server_forward(struct ssh_connection *connection, + const struct address_info *address) +{ + struct resource *port + = tcpforward_listen(connection, ATOM_FORWARDED_TCPIP, + address, address); + if (!port) + return NULL; + else + { + NEW(server_forward, self); + + self->super.address = address; + self->port = port; + + remember_resource(connection->resources, self->port); + + return self; + } +} + +static void +do_tcpip_forward_handler(struct global_request *s UNUSED, + struct ssh_connection *connection, + const struct request_info *info, + struct simple_buffer *args) +{ + uint32_t bind_host_length; + const uint8_t *bind_host; + uint32_t bind_port; + + if (parse_string(args, &bind_host_length, &bind_host) + && parse_uint32(args, &bind_port) + && parse_eod(args)) + { + struct address_info *a; + struct server_forward *forward; + + trace("forward-tcpip request for port %i.\n", bind_port); + + if (bind_port < 1024) + { + werror("Denying forwarding of privileged port %i.\n", bind_port); + global_request_reply(connection, info, 0); + return; + } + + if (tcpforward_lookup(&connection->forwarded_ports, + bind_host_length, bind_host, bind_port)) + { + global_request_reply(connection, info, 0); + return; + } + + a = make_address_info(ssh_format("%ls", bind_host_length, bind_host), + bind_port); + forward = make_server_forward(connection, a); + + if (forward) + { + object_queue_add_head(&connection->forwarded_ports, + &forward->super.super); + + global_request_reply(connection, info, 1); + } + else + global_request_reply(connection, info, 0); + } + else + { + werror("Incorrectly formatted tcpip-forward request\n"); + SSH_CONNECTION_ERROR(connection, "Invalid tcpip-forward message."); + } +} + +struct global_request +tcpip_forward_handler = + { STATIC_HEADER, do_tcpip_forward_handler }; + +static void +do_tcpip_cancel_forward(struct global_request *s UNUSED, + struct ssh_connection *connection, + const struct request_info *info, + struct simple_buffer *args) +{ + uint32_t bind_host_length; + const uint8_t *bind_host; + uint32_t bind_port; + + if (parse_string(args, &bind_host_length, &bind_host) && + parse_uint32(args, &bind_port) && + parse_eod(args)) + { + CAST(server_forward, forward, + tcpforward_remove(&connection->forwarded_ports, + bind_host_length, + bind_host, + bind_port)); + + if (forward) + { + assert(forward->port); + verbose("Cancelling a requested tcpip-forward.\n"); + + KILL_RESOURCE(forward->port); + forward->port = NULL; + + global_request_reply(connection, info, 1); + } + else + { + verbose("Could not find tcpip-forward to cancel\n"); + + global_request_reply(connection, info, 0); + } + } + else + { + werror("Incorrectly formatted cancel-tcpip-forward request\n"); + SSH_CONNECTION_ERROR(connection, "Invalid cancel-tcpip-forward message."); + } +} + +struct global_request tcpip_cancel_forward_handler = +{ STATIC_HEADER, do_tcpip_cancel_forward }; + + +/* Handling of direct-tcpip */ + +DEFINE_CHANNEL_OPEN(channel_open_direct_tcpip) + (struct channel_open *s UNUSED, + const struct channel_open_info *info, + struct simple_buffer *args) +{ + struct lsh_string *dest_host = NULL; + uint32_t dest_port; + const uint8_t *orig_host; + uint32_t orig_host_length; + uint32_t orig_port; + + if ( (dest_host = parse_string_copy(args)) + && parse_uint32(args, &dest_port) + && parse_string(args, &orig_host_length, &orig_host) + && parse_uint32(args, &orig_port) + && parse_eod(args)) + { + struct resource *r; + + verbose("direct-tcpip to %pS:%i.\n", dest_host, dest_port); + + r = tcpforward_connect(make_address_info(dest_host, dest_port), + info); + if (r) + remember_resource(info->connection->resources, r); + } + else + { + lsh_string_free(dest_host); + + werror("do_channel_open_direct_tcpip: Invalid message!\n"); + SSH_CONNECTION_ERROR(info->connection, "Invalid CHANNEL_OPEN direct-tcpip message."); + } +} diff --git a/pool/shard006/C/0119284_evcon-test-ev.c b/pool/shard006/C/0119284_evcon-test-ev.c new file mode 100644 index 0000000000000000000000000000000000000000..c17fb28ab70e39119fe394dd91419dbd35adc25a --- /dev/null +++ b/pool/shard006/C/0119284_evcon-test-ev.c @@ -0,0 +1,45 @@ + +#include "evcon-echo.h" +#include +#include + +#define UNUSED(x) ((void)(x)) + +static void test_ev_client_finished_cb(EchoClient* client, void *user_data) { + struct ev_loop *loop = (struct ev_loop*) user_data; + UNUSED(client); + + ev_break(loop, EVBREAK_ONE); +} + + +static void test_ev(void) { + struct ev_loop *l = ev_loop_new(0); + evcon_allocator *alloc = evcon_glib_allocator(); + evcon_loop *loop = evcon_loop_from_ev(l, alloc); + EchoClient *client; + EchoServer *srv; + + srv = echo_server_new(loop); + g_debug("Listening on port %i\n", srv->port); + + client = echo_client_new(srv, 5, test_ev_client_finished_cb, l); + + ev_run(l, 0); + + echo_client_free(client); + echo_server_free(srv); + + evcon_loop_unref(loop); + + ev_loop_destroy(l); +} + + +int main(int argc, char** argv) { + g_test_init(&argc, &argv, NULL); + + g_test_add_func("/evcon-echo/test-ev", test_ev); + + return g_test_run(); +} diff --git a/pool/shard006/C/0119288_boxes.c b/pool/shard006/C/0119288_boxes.c new file mode 100644 index 0000000000000000000000000000000000000000..6d4438b2d4d2d4f2396c68cdfa5e1655497d3208 --- /dev/null +++ b/pool/shard006/C/0119288_boxes.c @@ -0,0 +1,88 @@ +/* +** Implémentation des fonctions +*/ +#include +#include +#include +#include + +#include "boxes.h" + +void *init_box(unsigned int myeltsize, unsigned int nombre_initial, void (*fct_print)(void *)) { + new_box(myeltsize, nombre_initial, BOX_TYPE_LINEAR, fct_print); +} + +void *new_box(unsigned int myeltsize, unsigned int nombre_initial, unsigned int box_type, void (*fct_print)(void *)) { + struct box *pbox; + if( (myeltsize <= 0) || (nombre_initial <= 0) ) { + return NULL; + } + //if(nombre_initial < BOX_SIZE_INITIAL) { + //nombre_initial = BOX_SIZE_INITIAL; + //} + if( (pbox = (struct box *)calloc(1, sizeof(struct box))) == NULL ) { + fprintf(stderr, "[init_box] calloc box error\n"); + return NULL; + } + pbox->index = 0; + pbox->type = box_type; + pbox->maxindex = nombre_initial-1; + pbox->eltsize = myeltsize; + pbox->print = fct_print; + if( (pbox->ptr = (void *)calloc(nombre_initial, myeltsize)) == NULL ) { + fprintf(stderr, "[init_box] calloc box->ptr error\n"); + free(pbox); + return NULL; + } + return pbox; +} + +int put_box(struct box *pbox, void * pdata) { +//*(pbox->ptr+pbox->index*pbox->eltsize) = *pdata; + if(pbox->index == pbox->maxindex ) { + void *ptmp; + if( ( ptmp = realloc( pbox->ptr, pbox->eltsize*(pbox->maxindex+1+BOX_SIZE_INCREMENT)) ) == NULL ) { + return BOX_ERROR_REALLOC; + } + pbox->ptr = ptmp; + pbox->maxindex += BOX_SIZE_INCREMENT; + fprintf(stderr, "Size: %8x\r", pbox->maxindex); + //sleep(1); + } + memcpy(pbox->ptr+pbox->index*pbox->eltsize, pdata, pbox->eltsize); + (pbox->index)++; + return BOX_SUCCESS; +} + +void extend_box(struct box *pbox) { + return; +} + +void release_box(struct box *pbox) { + fprintf(stderr, "[free] pbox->ptr\n"); + free(pbox->ptr); + fprintf(stderr, "[free] pbox\n"); + free(pbox); + return; +} + +void info_box(struct box *pbox) { + fprintf(stdout, "struct box %p\n", pbox); + fprintf(stdout, "\tindex %d\n", pbox->index); + fprintf(stdout, "\tmaxindex %d\n", pbox->maxindex); + fprintf(stdout, "\teltsize %d\n", pbox->eltsize); + fprintf(stdout, "\tprint %p\n", pbox->print); + fprintf(stdout, "\tptr %p\n", pbox->ptr); + return; +} + +void display_box(struct box *pbox) { + unsigned int i; + while( i < pbox->index ) { + pbox->print(pbox->ptr + i*pbox->eltsize); + i++; + } +return; +} + +/* EOF */ diff --git a/pool/shard006/C/0119296_ft_qsort.c b/pool/shard006/C/0119296_ft_qsort.c new file mode 100644 index 0000000000000000000000000000000000000000..931293324926cd2493ca3fed619abdf26d485a08 --- /dev/null +++ b/pool/shard006/C/0119296_ft_qsort.c @@ -0,0 +1,39 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_qsort.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: jgroc-de +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2017/11/11 18:17:23 by jgroc-de #+# #+# */ +/* Updated: 2017/11/15 13:07:06 by jgroc-de ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +void ft_qsort(int *tab, int start, int end) +{ + int left; + int right; + int pivot; + + left = start; + right = end; + pivot = tab[start]; + if (start >= end) + return ; + while (1) + { + while (tab[right] > pivot) + right--; + while (tab[left] < pivot) + left--; + if (left < right) + ft_swap(tab + left, tab + right); + else + break ; + } + ft_qsort(tab, start, right); + ft_qsort(tab, right + 1, end); +} diff --git a/pool/shard006/C/0119305_XelixProcessList.c b/pool/shard006/C/0119305_XelixProcessList.c new file mode 100644 index 0000000000000000000000000000000000000000..72b542399425852208d658768c3002827e637724 --- /dev/null +++ b/pool/shard006/C/0119305_XelixProcessList.c @@ -0,0 +1,116 @@ +/* +htop - XelixProcessList.c +(C) 2014 Hisham H. Muhammad +(C) 2019-2020 Lukas Martini +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + +#include "ProcessList.h" +#include "XelixProcess.h" + +#include +#include +#include + +ProcessList* ProcessList_new(UsersTable* usersTable, Hashtable* pidWhiteList, uid_t userId) { + ProcessList* this = xCalloc(1, sizeof(ProcessList)); + ProcessList_init(this, Class(Process), usersTable, pidWhiteList, userId); + + return this; +} + +void ProcessList_delete(ProcessList* this) { + ProcessList_done(this); + free(this); +} + +void ProcessList_goThroughEntries(ProcessList* super, bool pauseProcessUpdate) { + if (pauseProcessUpdate) { + return; + } + + FILE* fp = fopen("/sys/tasks", "r"); + if(!fp) { + return; + } + + super->totalTasks = 0; + super->runningTasks = 0; + + // Drop first line + char* data = malloc(1024); + fgets(data, 1024, fp); + free(data); + + while(true) { + if(feof(fp)) { + break; + } + + int pid; + int uid; + int gid; + int ppid; + char cstate; + char name[500]; + int mem; + char _tty[30]; + char* tty = _tty; + + if(fscanf(fp, "%d %d %d %d %c \"%500[^\"]\" %d %s\n", &pid, &uid, &gid, &ppid, &cstate, name, &mem, tty) != 8) { + continue; + } + + bool preExisting = false; + Process *proc = ProcessList_getProcess(super, pid, &preExisting, XelixProcess_new); + + super->totalTasks++; + if(cstate == 'R' || cstate == 'C') { + super->runningTasks++; + proc->state = 'R'; + } else { + proc->state = 'S'; + } + + proc->time = proc->time + 10; + proc->pid = pid; + proc->ppid = ppid; + proc->tgid = pid; + proc->comm = strdup(name); + proc->basenameOffset = 0; + proc->updated = true; + + proc->show = true; + proc->pgrp = super->totalTasks; + proc->session = super->totalTasks; + proc->tty_nr = super->totalTasks; + proc->tpgid = 0; + proc->st_uid = uid; + proc->flags = 0; + proc->processor = 0; + + proc->percent_cpu = 42.23; + proc->percent_mem = 20.0; + + struct passwd* pwd = getpwuid(uid); + proc->user = calloc(1, 100); + if(pwd) { + strncpy(proc->user, pwd->pw_name, 100); + } else { + itoa(uid, proc->user, 100); + } + + proc->priority = 1; + proc->nice = 1; + proc->nlwp = 1; + strncpy(proc->starttime_show, "Jun 01 ", sizeof(proc->starttime_show)); + proc->starttime_ctime = 1433116800; // Jun 01, 2015 + + if(!preExisting) { + ProcessList_add(super, proc); + } + } + + fclose(fp); +} diff --git a/pool/shard006/C/0119307_Printf2.c b/pool/shard006/C/0119307_Printf2.c new file mode 100644 index 0000000000000000000000000000000000000000..93be3a1a08f942d0cd59c5170895439468652df0 --- /dev/null +++ b/pool/shard006/C/0119307_Printf2.c @@ -0,0 +1,65 @@ +/** + @version 1.10 1997-07-01 + @author Cay Horstmann +*/ + +#include "Printf2.h" +#include +#include +#include + +/** + @param format a string containing a printf format specifier + (such as "%8.2f"). Substrings "%%" are skipped. + @return a pointer to the format specifier (skipping the '%') + or NULL if there wasn't a unique format specifier +*/ +char* find_format(const char format[]) +{ + char* p; + char* q; + + p = strchr(format, '%'); + while (p != NULL && *(p + 1) == '%') /* skip %% */ + p = strchr(p + 2, '%'); + if (p == NULL) return NULL; + /* now check that % is unique */ + p++; + q = strchr(p, '%'); + while (q != NULL && *(q + 1) == '%') /* skip %% */ + q = strchr(q + 2, '%'); + if (q != NULL) return NULL; /* % not unique */ + q = p + strspn(p, " -0+#"); /* skip past flags */ + q += strspn(q, "0123456789"); /* skip past field width */ + if (*q == '.') { q++; q += strspn(q, "0123456789"); } + /* skip past precision */ + if (strchr("eEfFgG", *q) == NULL) return NULL; + /* not a floating-point format */ + return p; +} + +JNIEXPORT jstring JNICALL Java_Printf2_sprint(JNIEnv* env, jclass cl, + jstring format, jdouble x) +{ + const char* cformat; + char* fmt; + jstring ret; + + cformat = (*env)->GetStringUTFChars(env, format, NULL); + fmt = find_format(cformat); + if (fmt == NULL) + ret = format; + else + { + char* cret; + int width = atoi(fmt); + if (width == 0) width = DBL_DIG + 10; + cret = (char*) malloc(strlen(cformat) + width); + sprintf(cret, cformat, x); + ret = (*env)->NewStringUTF(env, cret); + free(cret); + } + (*env)->ReleaseStringUTFChars(env, format, cformat); + return ret; +} + diff --git a/pool/shard006/C/0119312_pixbuf-thumbnailer.c b/pool/shard006/C/0119312_pixbuf-thumbnailer.c new file mode 100644 index 0000000000000000000000000000000000000000..8ee8364e6e5958e80babafed1a0ae6b2535ead74 --- /dev/null +++ b/pool/shard006/C/0119312_pixbuf-thumbnailer.c @@ -0,0 +1,277 @@ +/* vi:set et ai sw=2 sts=2 ts=2: */ +/*- + * Copyright (c) 2009 Jannis Pohlmann + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 Library General Public License for more details. + * + * You should have received a copy of the GNU Library General + * Public License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include + +#include + +#include + + + +/* + * A buffer size of 1 MiB makes it possible to load a lot of current images in only + * a few iterations, which can significantly improve performance for some formats + * like GIF, without being too big, which on the contrary would degrade performance. + * On the other hand, it ensures that a cancelled load will end fairly quickly at + * the end of the current iteration, instead of continuing almost indefinitely as + * can be the case for some images, again in GIF format. + * See https://gitlab.xfce.org/apps/ristretto/-/issues/16 for an example of such an + * image. + */ +#define LOADER_BUFFER_SIZE 1048576 + + + +static void pixbuf_thumbnailer_create (TumblerAbstractThumbnailer *thumbnailer, + GCancellable *cancellable, + TumblerFileInfo *info); + + + +struct _PixbufThumbnailerClass +{ + TumblerAbstractThumbnailerClass __parent__; +}; + +struct _PixbufThumbnailer +{ + TumblerAbstractThumbnailer __parent__; +}; + + + +G_DEFINE_DYNAMIC_TYPE (PixbufThumbnailer, + pixbuf_thumbnailer, + TUMBLER_TYPE_ABSTRACT_THUMBNAILER); + + + +void +pixbuf_thumbnailer_register (TumblerProviderPlugin *plugin) +{ + pixbuf_thumbnailer_register_type (G_TYPE_MODULE (plugin)); +} + + + +static void +pixbuf_thumbnailer_class_init (PixbufThumbnailerClass *klass) +{ + TumblerAbstractThumbnailerClass *abstractthumbnailer_class; + + abstractthumbnailer_class = TUMBLER_ABSTRACT_THUMBNAILER_CLASS (klass); + abstractthumbnailer_class->create = pixbuf_thumbnailer_create; +} + + + +static void +pixbuf_thumbnailer_class_finalize (PixbufThumbnailerClass *klass) +{ +} + + + +static void +pixbuf_thumbnailer_init (PixbufThumbnailer *thumbnailer) +{ +} + + + +static GdkPixbuf * +pixbuf_thumbnailer_new_from_stream (GInputStream *stream, + TumblerThumbnail *thumbnail, + const gchar *mime_type, + GCancellable *cancellable, + GError **error) +{ + GdkPixbufLoader *loader; + GdkPixbufAnimation *animation; + GdkPixbufAnimationIter *iter; + gssize n_read; + GdkPixbuf *pixbuf = NULL; + guchar *buffer; + GError *err = NULL; + gboolean has_frame; + + g_return_val_if_fail (G_IS_INPUT_STREAM (stream), NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* try to use a pixbuf loader specific to the mime type, falling back on the + * generic loader in case of error */ + loader = gdk_pixbuf_loader_new_with_mime_type (mime_type, NULL); + if (loader == NULL) + loader = gdk_pixbuf_loader_new (); + + g_signal_connect (loader, "size-prepared", + G_CALLBACK (tumbler_util_size_prepared), thumbnail); + + buffer = g_new (guchar, LOADER_BUFFER_SIZE); + for (;;) + { + n_read = g_input_stream_read (stream, buffer, LOADER_BUFFER_SIZE, + cancellable, &err); + + /* read error (< 0), read finished (== 0) or write error */ + if (n_read <= 0 || ! gdk_pixbuf_loader_write (loader, buffer, n_read, &err)) + break; + + /* we only need the first frame to generate a thumbnail in case of an animation */ + animation = gdk_pixbuf_loader_get_animation (loader); + if (animation != NULL) + { + iter = gdk_pixbuf_animation_get_iter (animation, NULL); + has_frame = ! gdk_pixbuf_animation_iter_on_currently_loading_frame (iter); + g_object_unref (iter); + + if (has_frame) + break; + } + } + + /* close the pixbuf loader, ignoring errors if there has been one before */ + gdk_pixbuf_loader_close (loader, err == NULL ? &err : NULL); + + /* some images reported as corrupt are still displayable and we don't care about + * the rest of the animation */ + if (err == NULL || g_error_matches (err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_CORRUPT_IMAGE) + || g_error_matches (err, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_INCOMPLETE_ANIMATION)) + { + pixbuf = gdk_pixbuf_loader_get_pixbuf (loader); + if (G_LIKELY (pixbuf != NULL)) + { + g_clear_error (&err); + pixbuf = gdk_pixbuf_apply_embedded_orientation (pixbuf); + } + /* should not happend, just in case */ + else if (err == NULL) + g_set_error (&err, TUMBLER_ERROR, TUMBLER_ERROR_NO_CONTENT, + TUMBLER_ERROR_MESSAGE_CREATION_FAILED); + } + + g_object_unref (loader); + g_free (buffer); + if (err != NULL) + g_propagate_error (error, err); + + return pixbuf; +} + + + +static void +pixbuf_thumbnailer_create (TumblerAbstractThumbnailer *thumbnailer, + GCancellable *cancellable, + TumblerFileInfo *info) +{ + + GFileInputStream *stream; + TumblerImageData data; + TumblerThumbnail *thumbnail; + const gchar *uri; + GdkPixbuf *pixbuf; + GError *error = NULL; + GFile *file; + + g_return_if_fail (IS_PIXBUF_THUMBNAILER (thumbnailer)); + g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable)); + g_return_if_fail (TUMBLER_IS_FILE_INFO (info)); + + /* do nothing if cancelled */ + if (g_cancellable_is_cancelled (cancellable)) + return; + + uri = tumbler_file_info_get_uri (info); + g_debug ("Handling URI '%s'", uri); + + /* try to open the source file for reading */ + file = g_file_new_for_uri (uri); + stream = g_file_read (file, cancellable, &error); + g_object_unref (file); + + if (stream == NULL) + { + g_signal_emit_by_name (thumbnailer, "error", uri, + error->domain, error->code, error->message); + g_error_free (error); + + return; + } + + thumbnail = tumbler_file_info_get_thumbnail (info); + g_assert (thumbnail != NULL); + + /* load the scaled pixbuf from the stream. this works like + * gdk_pixbuf_new_from_file_at_scale(), but without increasing the + * pixbuf size. */ + pixbuf = pixbuf_thumbnailer_new_from_stream (G_INPUT_STREAM (stream), thumbnail, + tumbler_file_info_get_mime_type (info), + cancellable, &error); + + g_object_unref (stream); + + if (pixbuf == NULL) + { + g_signal_emit_by_name (thumbnailer, "error", uri, + error->domain, error->code, error->message); + g_error_free (error); + g_object_unref (thumbnail); + + return; + } + + g_assert (pixbuf != NULL); + + data.data = gdk_pixbuf_get_pixels (pixbuf); + data.has_alpha = gdk_pixbuf_get_has_alpha (pixbuf); + data.bits_per_sample = gdk_pixbuf_get_bits_per_sample (pixbuf); + data.width = gdk_pixbuf_get_width (pixbuf); + data.height = gdk_pixbuf_get_height (pixbuf); + data.rowstride = gdk_pixbuf_get_rowstride (pixbuf); + data.colorspace = (TumblerColorspace) gdk_pixbuf_get_colorspace (pixbuf); + + tumbler_thumbnail_save_image_data (thumbnail, &data, + tumbler_file_info_get_mtime (info), + NULL, &error); + + if (error != NULL) + { + g_signal_emit_by_name (thumbnailer, "error", uri, + error->domain, error->code, error->message); + g_error_free (error); + } + else + { + g_signal_emit_by_name (thumbnailer, "ready", uri); + } + + g_object_unref (pixbuf); + g_object_unref (thumbnail); +} diff --git a/pool/shard006/C/0119313_at91-gpio.c b/pool/shard006/C/0119313_at91-gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..12f99bf2279296f4da948397b67825c47114a00d --- /dev/null +++ b/pool/shard006/C/0119313_at91-gpio.c @@ -0,0 +1,71 @@ +/* + * smemlcd - Sharp Memory LCDs library + * + * Copyright (C) 2014-2017 by Artur Wroblewski + * + * 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 . + */ + +#include +#include +#include +#include + +#define BLOCK_SIZE 4096UL +#define MAP_MASK (BLOCK_SIZE - 1) +#define GPIO_A_BASE 0xfffff400 + +static void *PIO_PER; /* 0x0000 */ +static void *PIO_OER; /* 0x0010 */ +static void *PIO_SODR; /* 0x0030 */ +static void *PIO_CODR; /* 0x0034 */ + +#define GPIO_IN(pin) *(unsigned int *) PIO_PER = 1 << pin +#define GPIO_OUT(pin) *(unsigned int *) PIO_OER = 1 << pin + +#define GPIO_SET(pin) *(unsigned int *) PIO_SODR = 1 << pin +#define GPIO_CLR(pin) *(unsigned int *) PIO_CODR = 1 << pin + +int gpio_init() { + int mem_fd; + void *gpio_map; + + if ((mem_fd = open("/dev/mem", O_RDWR | O_SYNC)) < 0) { + fprintf(stderr, "Cannot open /dev/mem\n"); + return -1; + } + + gpio_map = mmap( + 0, BLOCK_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd, + GPIO_A_BASE & ~MAP_MASK + ); + + close(mem_fd); + + if (gpio_map == MAP_FAILED) { + fprintf(stderr, "mmap error %d\n", gpio_map); + return -1; + } + + PIO_PER = gpio_map + (GPIO_A_BASE & MAP_MASK); + PIO_OER = gpio_map + ((GPIO_A_BASE + 0x10) & MAP_MASK); + PIO_SODR = gpio_map + ((GPIO_A_BASE + 0x30) & MAP_MASK); + PIO_CODR = gpio_map + ((GPIO_A_BASE + 0x34) & MAP_MASK); + + return 0; +} + +/* + * vim: sw=4:et:ai + */ diff --git a/pool/shard006/C/0119317_download.c b/pool/shard006/C/0119317_download.c new file mode 100644 index 0000000000000000000000000000000000000000..0f24b86b9ca67c32c33dcfd1a84f78c45563f7cc --- /dev/null +++ b/pool/shard006/C/0119317_download.c @@ -0,0 +1,151 @@ +/* + * This file is part of the Soletta Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * 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 +#include +#include +#include + +#include "sol-mainloop.h" +#include "sol-http.h" +#include "sol-http-client.h" +#include "sol-log.h" + +static FILE *fd; +struct sol_http_client_connection *pending; + +static ssize_t +recv_func(void *userdata, const struct sol_http_client_connection *connection, + struct sol_buffer *buffer) +{ + ssize_t ret; + + ret = fwrite(buffer->data, buffer->used, 1, fd); + if (!ret || ferror(fd)) { + fprintf(stderr, "ERROR: Failed to write\n"); + return -1; + } + + return ret * buffer->used; +} + +static void +response_func(void *userdata, const struct sol_http_client_connection *connection, + struct sol_http_response *response) +{ + fclose(fd); + fd = NULL; + pending = NULL; + + SOL_HTTP_RESPONSE_CHECK_API(response); + + if (response->response_code != SOL_HTTP_STATUS_OK) { + fprintf(stderr, "ERROR: Finished with error, response code: %d\n", response->response_code); + sol_quit_with_code(EXIT_FAILURE); + return; + } + + printf("Download concluded successfully\n"); + sol_quit_with_code(EXIT_SUCCESS); +} + +static const struct sol_http_request_interface iface = { + SOL_SET_API_VERSION(.api_version = SOL_HTTP_REQUEST_INTERFACE_API_VERSION, ) + .recv_cb = recv_func, + .response_cb = response_func +}; + +static void +startup(void) +{ + char **argv = sol_argv(); + char *output = NULL, *url = NULL; + int c, opt_idx, argc = sol_argc(); + static const struct option opts[] = { + { "output", required_argument, NULL, 'o' }, + { "help", no_argument, NULL, 'h' }, + { 0, 0, 0, 0 } + }; + + while ((c = getopt_long(argc, argv, "o:h", opts, &opt_idx)) != -1) { + switch (c) { + case 'o': + output = optarg; + break; + case 'h': + default: + fprintf(stderr, + "Usage:\n\t%s [-o ] \n", argv[0]); + sol_quit_with_code(EXIT_SUCCESS); + return; + } + } + + url = argv[optind]; + if (!url) { + fprintf(stderr, "ERROR: missing url.\n"); + sol_quit_with_code(EXIT_FAILURE); + return; + } + + if (output) { + fd = fopen(output, "w"); + if (fd == NULL) { + fprintf(stderr, "ERROR: Failed to create the file: %s\n", output); + sol_quit_with_code(EXIT_FAILURE); + return; + } + } else { + fd = stdout; + } + + pending = sol_http_client_request_with_interface(SOL_HTTP_METHOD_GET, + url, NULL, &iface, NULL); + if (!pending) { + fprintf(stderr, "ERROR: Failed to create the request\n"); + fclose(fd); + sol_quit_with_code(EXIT_FAILURE); + return; + } +} + + +static void +shutdown(void) +{ + if (pending) + sol_http_client_connection_cancel(pending); + if (fd) + fclose(fd); +} + +SOL_MAIN_DEFAULT(startup, shutdown); diff --git a/pool/shard006/C/0119321_neut_multim.c b/pool/shard006/C/0119321_neut_multim.c new file mode 100644 index 0000000000000000000000000000000000000000..98ffea973a99a5608c7b20358877c82d13d540fa --- /dev/null +++ b/pool/shard006/C/0119321_neut_multim.c @@ -0,0 +1,95 @@ +/* This file is part of the Neper software package. */ +/* Copyright (C) 2003-2022, Romain Quey. */ +/* See the COPYING file in the top-level directory. */ + +#include "neut_multim_.h" + +void +neut_multim_set_zero (struct MULTIM *pMultim) +{ + (*pMultim).algoqty = 0; + (*pMultim).algos = NULL; + (*pMultim).algohit = NULL; + + (*pMultim).mOdis = NULL; + (*pMultim).mOsize = NULL; + (*pMultim).mO = NULL; + + (*pMultim).Oalgo = NULL; + + (*pMultim).Odis = NULL; + (*pMultim).Osize = NULL; + (*pMultim).O = NULL; + + return; +} + +void +neut_multim_free (struct MULTIM *pMultim, int PolyQty) +{ + + ut_free_3d_char (&(*pMultim).algos, (*pMultim).algoqty, 2); + ut_free_1d_int (&(*pMultim).algohit); + + ut_free_2d (&(*pMultim).mOdis, PolyQty + 1); + ut_free_2d (&(*pMultim).mOsize, PolyQty + 1); + ut_free_2d (&(*pMultim).mO, PolyQty + 1); + + ut_free_1d_int (&(*pMultim).Oalgo); + + ut_free_1d (&(*pMultim).Odis); + ut_free_1d (&(*pMultim).Osize); + ut_free_1d (&(*pMultim).O); + + return; +} + +void +neut_multim_init (int dim, char *list, int cellqty, struct MULTIM *pMultim) +{ + int i, qty; + char **ind_algo = NULL; + char **ind_algo2 = NULL; + char *deflist = ut_alloc_1d_char (100); + + if (dim == 3) + sprintf (deflist, "netg%sgmsh%snetg%snetg%snetg%sgmne", NEUT_SEP_DEP, + NEUT_SEP_NODEP, NEUT_SEP_DEP, NEUT_SEP_NODEP, NEUT_SEP_DEP); + else if (dim == 2) + sprintf (deflist, "mead%sdela%sfron", NEUT_SEP_NODEP, NEUT_SEP_NODEP); + else + ut_print_neperbug (); + + ut_list_break ((!strcmp (list, "default")) ? deflist : list, NEUT_SEP_NODEP, + &ind_algo, &(*pMultim).algoqty); + + (*pMultim).algos = ut_alloc_3d_char ((*pMultim).algoqty, 2, 5); + + for (i = 0; i < (*pMultim).algoqty; i++) + { + ut_list_break (ind_algo[i], NEUT_SEP_DEP, &ind_algo2, &qty); + sprintf ((*pMultim).algos[i][0], "%s", ind_algo2[0]); + if (qty == 2) + sprintf ((*pMultim).algos[i][1], "%s", ind_algo2[1]); + else + ut_free_1d_char (&(*pMultim).algos[i][1]); + ut_free_2d_char (&ind_algo2, qty); + } + ut_free_2d_char (&ind_algo, (*pMultim).algoqty); + + // Alloc + + (*pMultim).mOdis = ut_alloc_2d (cellqty + 1, (*pMultim).algoqty); + (*pMultim).mOsize = ut_alloc_2d (cellqty + 1, (*pMultim).algoqty); + (*pMultim).mO = ut_alloc_2d (cellqty + 1, (*pMultim).algoqty); + (*pMultim).Oalgo = ut_alloc_1d_int (cellqty + 1); + (*pMultim).algohit = ut_alloc_1d_int ((*pMultim).algoqty); + + (*pMultim).Odis = ut_alloc_1d (cellqty + 1); + (*pMultim).Osize = ut_alloc_1d (cellqty + 1); + (*pMultim).O = ut_alloc_1d (cellqty + 1); + + ut_free_1d_char (&deflist); + + return; +} diff --git a/pool/shard006/C/0119322_drawpos.c b/pool/shard006/C/0119322_drawpos.c new file mode 100644 index 0000000000000000000000000000000000000000..ed59f2ce7fd0fc08b20992e5e583a15b649b648d --- /dev/null +++ b/pool/shard006/C/0119322_drawpos.c @@ -0,0 +1,95 @@ + +#include "game.h" +#include "window.h" +#include "config/map.h" +#include "utility/vector.h" +#include "components/physics.h" +#include "components/drawpos.h" + +#include +#include +#include + +struct _drawpos { + SDL_Rect pos; + Vector offset; + int phys_id; + bool active; +}; + +static DrawPos DRAWPOS[DRAWPOS_POOL_SIZE]; + +static void DrawPos_alignWithoutPhysics(int id, Vector* position) { + DRAWPOS[id].pos.x = Map_getUnitX() * (position->x + Map_getWidth()/2) - DRAWPOS[id].offset.x; + DRAWPOS[id].pos.y = Map_getUnitY() * (position->y + Map_getHeight()/2) - DRAWPOS[id].offset.y; +} + +static void DrawPos_align(int id) { + Vector *position; + + if (DRAWPOS[id].phys_id != -1) { + position = Physics_getPos(DRAWPOS[id].phys_id); + DrawPos_alignWithoutPhysics(id, position); + } + +} + +void DrawPos_init() { + int id; + + for (id = 0; id < DRAWPOS_POOL_SIZE; ++id) { + DRAWPOS[id].active = false; + } +} + +int DrawPos_new(int body_id, int qw, int qh, float ox, float oy) { + int id; + + for (id = 0; id < DRAWPOS_POOL_SIZE; ++id) { + if (!DRAWPOS[id].active) { + DRAWPOS[id].phys_id = body_id; + DRAWPOS[id].active = true; + DRAWPOS[id].pos.w = qw; + DRAWPOS[id].pos.h = qh; + Vector_set(&DRAWPOS[id].offset, ox, oy); + DrawPos_align(id); + return id; + } + } + POOL_OVERFLOW(DrawPos); +} + +void DrawPos_kill(int id) { + if (id == -1 || !DRAWPOS[id].active) return; + DRAWPOS[id].active = false; +} + +void DrawPos_update() { + int id; + + for (id = 0; id < DRAWPOS_POOL_SIZE; ++id) + if (DRAWPOS[id].active) + DrawPos_align(id); +} + +SDL_Rect* DrawPos_getPos(int id) { + if (id == -1 || !DRAWPOS[id].active) return NULL; + return &DRAWPOS[id].pos; +} + +void DrawPos_setPos(int id, Vector *pos) { + if (id == -1 || !DRAWPOS[id].active) return; + DrawPos_alignWithoutPhysics(id, pos); +} + +Vector* DrawPos_getOffset(int id) { + if (id == -1 || !DRAWPOS[id].active) return NULL; + return &DRAWPOS[id].offset; +} + +void DrawPos_print(int id) { + if (id == -1 || !DRAWPOS[id].active) return; + logprint(">> DRAWPOS INFO: #%d\n", id); + logprint(">> RECT [ x: %d, y: %d, w: %d, h: %d ]\n", DRAWPOS[id].pos.x, DRAWPOS[id].pos.y, DRAWPOS[id].pos.w, DRAWPOS[id].pos.h); + logprint(">> OFFSET [ ox: %f, oy: %f ]\n", DRAWPOS[id].offset.x, DRAWPOS[id].offset.y); +} diff --git a/pool/shard006/C/0119325_notify.c b/pool/shard006/C/0119325_notify.c new file mode 100644 index 0000000000000000000000000000000000000000..0898c3155292c54453df568921e546d59bb3db4f --- /dev/null +++ b/pool/shard006/C/0119325_notify.c @@ -0,0 +1,248 @@ +/* + * Copyright 2014 Red Hat Inc. + * + * 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. + * + * Authors: Ben Skeggs + */ + +#include +#include +#include +#include +#include +#include + +static inline int +nvif_notify_put_(struct nvif_notify *notify) +{ + struct nvif_object *object = notify->object; + struct { + struct nvif_ioctl_v0 ioctl; + struct nvif_ioctl_ntfy_put_v0 ntfy; + } args = { + .ioctl.type = NVIF_IOCTL_V0_NTFY_PUT, + .ntfy.index = notify->index, + }; + + if (atomic_inc_return(¬ify->putcnt) != 1) + return 0; + + return nvif_object_ioctl(object, &args, sizeof(args), NULL); +} + +int +nvif_notify_put(struct nvif_notify *notify) +{ + if (likely(notify->object) && + test_and_clear_bit(NVIF_NOTIFY_USER, ¬ify->flags)) { + int ret = nvif_notify_put_(notify); + if (test_bit(NVIF_NOTIFY_WORK, ¬ify->flags)) + flush_work(¬ify->work); + return ret; + } + return 0; +} + +static inline int +nvif_notify_get_(struct nvif_notify *notify) +{ + struct nvif_object *object = notify->object; + struct { + struct nvif_ioctl_v0 ioctl; + struct nvif_ioctl_ntfy_get_v0 ntfy; + } args = { + .ioctl.type = NVIF_IOCTL_V0_NTFY_GET, + .ntfy.index = notify->index, + }; + + if (atomic_dec_return(¬ify->putcnt) != 0) + return 0; + + return nvif_object_ioctl(object, &args, sizeof(args), NULL); +} + +int +nvif_notify_get(struct nvif_notify *notify) +{ + if (likely(notify->object) && + !test_and_set_bit(NVIF_NOTIFY_USER, ¬ify->flags)) + return nvif_notify_get_(notify); + return 0; +} + +static inline int +nvif_notify_func(struct nvif_notify *notify, bool keep) +{ + int ret = notify->func(notify); + if (ret == NVIF_NOTIFY_KEEP || + !test_and_clear_bit(NVKM_NOTIFY_USER, ¬ify->flags)) { + if (!keep) + atomic_dec(¬ify->putcnt); + else + nvif_notify_get_(notify); + } + return ret; +} + +static void +nvif_notify_work(struct work_struct *work) +{ + struct nvif_notify *notify = container_of(work, typeof(*notify), work); + nvif_notify_func(notify, true); +} + +int +nvif_notify(const void *header, u32 length, const void *data, u32 size) +{ + struct nvif_notify *notify = NULL; + const union { + struct nvif_notify_rep_v0 v0; + } *args = header; + int ret = NVIF_NOTIFY_DROP; + + if (length == sizeof(args->v0) && args->v0.version == 0) { + if (WARN_ON(args->v0.route)) + return NVIF_NOTIFY_DROP; + notify = (void *)(unsigned long)args->v0.token; + } + + if (!WARN_ON(notify == NULL)) { + struct nvif_client *client = nvif_client(notify->object); + if (!WARN_ON(notify->size != size)) { + atomic_inc(¬ify->putcnt); + if (test_bit(NVIF_NOTIFY_WORK, ¬ify->flags)) { + memcpy((void *)notify->data, data, size); + schedule_work(¬ify->work); + return NVIF_NOTIFY_DROP; + } + notify->data = data; + ret = nvif_notify_func(notify, client->driver->keep); + notify->data = NULL; + } + } + + return ret; +} + +int +nvif_notify_fini(struct nvif_notify *notify) +{ + struct nvif_object *object = notify->object; + struct { + struct nvif_ioctl_v0 ioctl; + struct nvif_ioctl_ntfy_del_v0 ntfy; + } args = { + .ioctl.type = NVIF_IOCTL_V0_NTFY_DEL, + .ntfy.index = notify->index, + }; + int ret = nvif_notify_put(notify); + if (ret >= 0 && object) { + ret = nvif_object_ioctl(object, &args, sizeof(args), NULL); + if (ret == 0) { + nvif_object_ref(NULL, ¬ify->object); + kfree((void *)notify->data); + } + } + return ret; +} + +int +nvif_notify_init(struct nvif_object *object, void (*dtor)(struct nvif_notify *), + int (*func)(struct nvif_notify *), bool work, u8 event, + void *data, u32 size, u32 reply, struct nvif_notify *notify) +{ + struct { + struct nvif_ioctl_v0 ioctl; + struct nvif_ioctl_ntfy_new_v0 ntfy; + struct nvif_notify_req_v0 req; + } *args; + int ret = -ENOMEM; + + notify->object = NULL; + nvif_object_ref(object, ¬ify->object); + notify->flags = 0; + atomic_set(¬ify->putcnt, 1); + notify->dtor = dtor; + notify->func = func; + notify->data = NULL; + notify->size = reply; + if (work) { + INIT_WORK(¬ify->work, nvif_notify_work); + set_bit(NVIF_NOTIFY_WORK, ¬ify->flags); + notify->data = kmalloc(notify->size, GFP_KERNEL); + if (!notify->data) + goto done; + } + + if (!(args = kmalloc(sizeof(*args) + size, GFP_KERNEL))) + goto done; + args->ioctl.version = 0; + args->ioctl.type = NVIF_IOCTL_V0_NTFY_NEW; + args->ntfy.version = 0; + args->ntfy.event = event; + args->req.version = 0; + args->req.reply = notify->size; + args->req.route = 0; + args->req.token = (unsigned long)(void *)notify; + + memcpy(args->req.data, data, size); + ret = nvif_object_ioctl(object, args, sizeof(*args) + size, NULL); + notify->index = args->ntfy.index; + kfree(args); +done: + if (ret) + nvif_notify_fini(notify); + return ret; +} + +static void +nvif_notify_del(struct nvif_notify *notify) +{ + nvif_notify_fini(notify); + kfree(notify); +} + +void +nvif_notify_ref(struct nvif_notify *notify, struct nvif_notify **pnotify) +{ + BUG_ON(notify != NULL); + if (*pnotify) + (*pnotify)->dtor(*pnotify); + *pnotify = notify; +} + +int +nvif_notify_new(struct nvif_object *object, int (*func)(struct nvif_notify *), + bool work, u8 type, void *data, u32 size, u32 reply, + struct nvif_notify **pnotify) +{ + struct nvif_notify *notify = kzalloc(sizeof(*notify), GFP_KERNEL); + if (notify) { + int ret = nvif_notify_init(object, nvif_notify_del, func, work, + type, data, size, reply, notify); + if (ret) { + kfree(notify); + notify = NULL; + } + *pnotify = notify; + return ret; + } + return -ENOMEM; +} diff --git a/pool/shard006/C/0119334_b_uname.c b/pool/shard006/C/0119334_b_uname.c new file mode 100644 index 0000000000000000000000000000000000000000..3d65505582a93a6a6cddbd393194c436c556d993 --- /dev/null +++ b/pool/shard006/C/0119334_b_uname.c @@ -0,0 +1,143 @@ +/* + * $Id: b_uname.c,v 1.9 2008/03/13 20:47:06 mbrey Exp $ + */ + +#include "bench.h" + +#define UNAMEFILE "NODENAME" + +static int b_uname_write_info __P((FILE *)); + +int +b_uname() +{ + FILE *fp; + int ret; + + if ((fp = fopen(UNAMEFILE, "w")) == NULL) + goto file_err; + + ret = b_uname_write_info(fp); + + if (fclose(fp) != 0) { +file_err: fprintf(stderr, + "%s: %s: %s\n", progname, UNAMEFILE, strerror(errno)); + return (1); + } + + return (ret); +} + +#ifdef DB_WIN32 +static int +b_uname_write_info(fp) + FILE *fp; +{ + OSVERSIONINFO osver; + SYSTEM_INFO sysinfo; + char *p; + +#ifdef DB_WINCE + p = "WinCE"; +#else + { + DWORD len; + char buf[1024]; + + len = sizeof(buf) - 1; + GetComputerName(buf, &len); + p = buf; + } +#endif + fprintf(fp, "

%s, ", p); + + GetSystemInfo(&sysinfo); + switch (sysinfo.wProcessorArchitecture) { + case PROCESSOR_ARCHITECTURE_ALPHA: + p = "alpha"; + break; + case PROCESSOR_ARCHITECTURE_INTEL: + p = "x86"; + break; + case PROCESSOR_ARCHITECTURE_MIPS: + p = "mips"; + break; + case PROCESSOR_ARCHITECTURE_PPC: + p = "ppc"; + break; + default: + p = "unknown"; + break; + } + fprintf(fp, "%s
\n", p); + memset(&osver, 0, sizeof(osver)); + osver.dwOSVersionInfoSize = sizeof(osver); + GetVersionEx(&osver); + switch (osver.dwPlatformId) { + case VER_PLATFORM_WIN32_NT: /* NT, Windows 2000 or Windows XP */ + if (osver.dwMajorVersion == 4) + p = "Windows NT4x"; + else if (osver.dwMajorVersion <= 3) + p = "Windows NT3x"; + else if (osver.dwMajorVersion == 5 && osver.dwMinorVersion < 1) + p = "Windows 2000"; + else if (osver.dwMajorVersion >= 5) + p = "Windows XP"; + else + p = "unknown"; + break; + case VER_PLATFORM_WIN32_WINDOWS: /* Win95, Win98 or WinME */ + if ((osver.dwMajorVersion > 4) || + ((osver.dwMajorVersion == 4) && (osver.dwMinorVersion > 0))) { + if (osver.dwMinorVersion >= 90) + p = "Windows ME"; + else + p = "Windows 98"; + } else + p = "Windows 95"; + break; + case VER_PLATFORM_WIN32s: /* Windows 3.x */ + p = "Windows"; + break; + default: + p = "unknown"; + break; + } + fprintf(fp, + "%s, %ld.%02ld", p, osver.dwMajorVersion, osver.dwMinorVersion); + return (0); +} + +#elif defined(HAVE_VXWORKS) +static int +b_uname_write_info(fp) + FILE *fp; +{ + fprintf(fp, "

VxWorks"); + return (0); +} + +#else /* POSIX */ +#include + +static int +b_uname_write_info(fp) + FILE *fp; +{ + struct utsname name; + + if (uname(&name) == 0) + fprintf(fp, "

%s, %s
\n%s, %s, %s

\n", name.nodename, + name.machine, name.sysname, name.release, name.version); + else { + /* + * We've seen random failures on some systems, complain and + * skip the call if it fails. + */ + fprintf(stderr, "%s: uname: %s\n", progname, strerror(errno)); + + fprintf(fp, "

POSIX"); + } + return (0); +} +#endif diff --git a/pool/shard006/C/0119336_101_The_Blocks_Problem.c b/pool/shard006/C/0119336_101_The_Blocks_Problem.c new file mode 100644 index 0000000000000000000000000000000000000000..f7140f493d577734bbb79d19e21dc9a6c3caf52e --- /dev/null +++ b/pool/shard006/C/0119336_101_The_Blocks_Problem.c @@ -0,0 +1,70 @@ +#include +#define MAXSTACKS 25 +#define MAXWORDLEN 5 + +int stacks[MAXSTACKS][MAXSTACKS]; +int where[MAXSTACKS]; +int stackTops[MAXSTACKS]; +char firstWord[MAXWORDLEN], secondWord[MAXWORDLEN]; + +// return blocks on top of s +void returnBlocks(int s){ + int stack = where[s]; + int i = stackTops[stack] - 1; + int element; + for (; stacks[stack][i] != s; --i){ + element = stacks[stack][i]; + stacks[element][stackTops[element]++] = element; + stackTops[stack]--; + where[element] = element; + } +} + +int main() +{ + // freopen("101_data", "r", stdin); + int i, from, to, top, n, stack, j; + scanf("%d", &n); + // initialize + for (i = 0;i < n; ++i){ + stacks[i][stackTops[i]++] = i; + where[i] = i; + } + while (scanf("%s", firstWord), *firstWord != 'q'){ + scanf("%d %s %d", &from, secondWord, &to); + if (from == to || where[from] == where[to]) + continue; + if (*firstWord == 'm'){ + // move a onto b + if (secondWord[1] == 'n') + returnBlocks(to); + returnBlocks(from); + // move [from] to top of [to] + stackTops[where[from]]--; + stacks[where[to]][stackTops[where[to]]++] = from; + where[from] = where[to]; + } + else{ + // pile a onto b + if (secondWord[1] == 'n') + returnBlocks(to); + stack = where[from]; + for (i = 0; i < stackTops[stack]; ++i) + if (stacks[stack][i] == from) + break; + top = i; + for (; i < stackTops[stack]; ++i) { + stacks[where[to]][stackTops[where[to]]++] = stacks[stack][i]; + where[stacks[stack][i]] = where[to]; + } + stackTops[stack] = top; + } + } + for (i = 0; i < n; ++i){ + printf("%d:", i); + for (j = 0; j < stackTops[i]; ++j) + printf(" %d", stacks[i][j]); + putchar('\n'); + } + return 0; +} diff --git a/pool/shard006/C/0119348_encode.c b/pool/shard006/C/0119348_encode.c new file mode 100644 index 0000000000000000000000000000000000000000..3e6061adbfd8d390c70720c88cccba5de9cfeaac --- /dev/null +++ b/pool/shard006/C/0119348_encode.c @@ -0,0 +1,121 @@ +/* + * encode.c + * + * CCITT ADPCM encoder + * + * Usage : encode [-3|4|5] [-a|u|l] < infile > outfile + */ +#include +#include +#include "g72x.h" + + +/* + * Pack output codes into bytes and write them to stdout. + * Returns 1 if there is residual output, else returns 0. + */ +int +pack_output( + unsigned code, + int bits) +{ + static unsigned int out_buffer = 0; + static int out_bits = 0; + unsigned char out_byte; + + out_buffer |= (code << out_bits); + out_bits += bits; + if (out_bits >= 8) { + out_byte = out_buffer & 0xff; + out_bits -= 8; + out_buffer >>= 8; + fwrite(&out_byte, sizeof (char), 1, stdout); + } + return (out_bits > 0); +} + + +main( + int argc, + char **argv) +{ + struct g72x_state state; + unsigned char sample_char; + short sample_short; + unsigned char code; + int resid; + int in_coding; + int in_size; + unsigned *in_buf; + int (*enc_routine)(); + int enc_bits; + + g72x_init_state(&state); + + /* Set defaults to u-law input, G.721 output */ + in_coding = AUDIO_ENCODING_ULAW; + in_size = sizeof (char); + in_buf = (unsigned *)&sample_char; + enc_routine = g721_encoder; + enc_bits = 4; + + /* Process encoding argument, if any */ + while ((argc > 1) && (argv[1][0] == '-')) { + switch (argv[1][1]) { + case '3': + enc_routine = g723_24_encoder; + enc_bits = 3; + break; + case '4': + enc_routine = g721_encoder; + enc_bits = 4; + break; + case '5': + enc_routine = g723_40_encoder; + enc_bits = 5; + break; + case 'u': + in_coding = AUDIO_ENCODING_ULAW; + in_size = sizeof (char); + in_buf = (unsigned *)&sample_char; + break; + case 'a': + in_coding = AUDIO_ENCODING_ALAW; + in_size = sizeof (char); + in_buf = (unsigned *)&sample_char; + break; + case 'l': + in_coding = AUDIO_ENCODING_LINEAR; + in_size = sizeof (short); + in_buf = (unsigned *)&sample_short; + break; + default: +fprintf(stderr, "CCITT ADPCM Encoder -- usage:\n"); +fprintf(stderr, "\tencode [-3|4|5] [-a|u|l] < infile > outfile\n"); +fprintf(stderr, "where:\n"); +fprintf(stderr, "\t-3\tGenerate G.723 24kbps (3-bit) data\n"); +fprintf(stderr, "\t-4\tGenerate G.721 32kbps (4-bit) data [default]\n"); +fprintf(stderr, "\t-5\tGenerate G.723 40kbps (5-bit) data\n"); +fprintf(stderr, "\t-a\tProcess 8-bit A-law input data\n"); +fprintf(stderr, "\t-u\tProcess 8-bit u-law input data [default]\n"); +fprintf(stderr, "\t-l\tProcess 16-bit linear PCM input data\n"); + exit(1); + } + argc--; + argv++; + } + + /* Read input file and process */ + while (fread(in_buf, in_size, 1, stdin) == 1) { + code = (*enc_routine)(in_size == 2 ? sample_short : sample_char, + in_coding, &state); + resid = pack_output(code, enc_bits); + } + + /* Write zero codes until all residual codes are written out */ + while (resid) { + resid = pack_output(0, enc_bits); + } + fclose(stdout); + return 0; +} diff --git a/pool/shard006/C/0119353_eth.c b/pool/shard006/C/0119353_eth.c new file mode 100644 index 0000000000000000000000000000000000000000..0ff05ec4fa73c461c84ce3d215f33c5c4f01db8a --- /dev/null +++ b/pool/shard006/C/0119353_eth.c @@ -0,0 +1,528 @@ +/* ============================================================================ + * @n (C) Copyright 2009, Texas Instruments, Inc. + * + * 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 Texas Instruments Incorporated 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. + * +*/ + +// Includes {{{ + +#include +#include +#include +#include +#include + +#include +#include "cpsw_singlecore.h" +#include "cppi_qmss_mgmt.h" + +extern volatile unsigned int cregister TSCL; + +//}}} + +// Definitions {{{ + +/* Addresses used to disable the PASS PDSP's */ +#define PASS_PDSP0 0x02001000 +#define PASS_PDSP1 0x02001100 +#define PASS_PDSP2 0x02001200 +#define PASS_PDSP3 0x02001300 +#define PASS_PDSP4 0x02001400 +#define PASS_PDSP5 0x02001500 + +/* Number of packets to be used for testing the example. */ +#define MAX_NUM_PACKETS 10u + +/* Counters to track number of packets sent/received by this application */ +extern volatile uint32_t gRxCounter, gTxCounter; + +void mdebugHaltPdsp (Int pdspNum); +volatile Int mdebugWait = 1; + +//}}} + +static void powerup(void) //{{{ +{ +// /* PASS power domain is turned OFF by default. It needs to be turned on before doing any +// * PASS device register access. This not required for the simulator. */ +// +// /* PASS Power domain cycle end on ON*/ +// +// /* power on and enable the clocks for PASS modules */ +// CSL_PSC_enablePowerDomain (CSL_PSC_PD_PASS); +// CSL_PSC_setModuleNextState (CSL_PSC_LPSC_PKTPROC, PSC_MODSTATE_ENABLE); +// /* Start the state transition */ +// CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); +// /* Wait until the state transition process is completed. */ +// while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)) +// +// CSL_PSC_enablePowerDomain (CSL_PSC_PD_PASS); +// CSL_PSC_setModuleNextState (CSL_PSC_LPSC_CPGMAC, PSC_MODSTATE_ENABLE); +// /* Start the state transition */ +// CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); +// /* Wait until the state transition process is completed. */ +// while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)) +// +// CSL_PSC_enablePowerDomain (CSL_PSC_PD_PASS); +// CSL_PSC_setModuleNextState (CSL_PSC_LPSC_Crypto, PSC_MODSTATE_ENABLE); +// /* Start the state transition */ +// CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); +// /* Wait until the state transition process is completed. */ +// while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); +// +// /* Disabling PA PDSP to prepare for power down */ +// volatile unsigned int *passPDSP; +// passPDSP = (unsigned int*)PASS_PDSP0; +// *passPDSP &= 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP1; +// *passPDSP &= 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP2; +// *passPDSP &= 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP3; +// *passPDSP &= 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP4; +// *passPDSP &= 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP5; +// *passPDSP &= 0xFFFFFFFD; +// +// /* Disable the clocks for PASS modules */ +// CSL_PSC_disablePowerDomain (CSL_PSC_PD_PASS); +// CSL_PSC_setModuleNextState (CSL_PSC_LPSC_PKTPROC, PSC_MODSTATE_SWRSTDISABLE); +// /* Start the state transition */ +// CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); +// /* Wait until the state transition process is completed. */ +// while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); +// +// CSL_PSC_disablePowerDomain (CSL_PSC_PD_PASS); +// CSL_PSC_setModuleNextState (CSL_PSC_LPSC_CPGMAC, PSC_MODSTATE_SWRSTDISABLE); +// /* Start the state transition */ +// CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); +// /* Wait until the state transition process is completed. */ +// while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); +// +// CSL_PSC_disablePowerDomain (CSL_PSC_PD_PASS); +// CSL_PSC_setModuleNextState (CSL_PSC_LPSC_Crypto, PSC_MODSTATE_SWRSTDISABLE); +// /* Start the state transition */ +// CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); +// /* Wait until the state transition process is completed. */ +// while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); + + /* Enable the clocks for PASS modules */ + CSL_PSC_enablePowerDomain (CSL_PSC_PD_PASS); + CSL_PSC_setModuleNextState (CSL_PSC_LPSC_PKTPROC, PSC_MODSTATE_ENABLE); + /* Start the state transition */ + CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); + /* Wait until the state transition process is completed. */ + while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); + + CSL_PSC_enablePowerDomain (CSL_PSC_PD_PASS); + CSL_PSC_setModuleNextState (CSL_PSC_LPSC_CPGMAC, PSC_MODSTATE_ENABLE); + /* Start the state transition */ + CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); + /* Wait until the state transition process is completed. */ + while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); + + CSL_PSC_enablePowerDomain (CSL_PSC_PD_PASS); + CSL_PSC_setModuleNextState (CSL_PSC_LPSC_Crypto, PSC_MODSTATE_ENABLE); + /* Start the state transition */ + CSL_PSC_startStateTransition (CSL_PSC_PD_PASS); + /* Wait until the state transition process is completed. */ + while (!CSL_PSC_isStateTransitionDone (CSL_PSC_PD_PASS)); + +// /* Enable PDSPs */ +// passPDSP = (unsigned int*)PASS_PDSP0; +// *passPDSP = 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP1; +// *passPDSP = 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP2; +// *passPDSP = 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP3; +// *passPDSP = 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP4; +// *passPDSP = 0xFFFFFFFD; +// +// passPDSP = (unsigned int*)PASS_PDSP5; +// *passPDSP = 0xFFFFFFFD; +} //}}} + +int32_t eth_init(uint8_t* host_mac, uint8_t* amc_mac, uint8_t* wire_mac) //{{{ +{ + uint8_t broadcast_mac[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; + + /* Power up */ + powerup(); + + /* Initialize the components + * (1) QMSS + * (2) CPPI + * (3) Ethernet switch subsystem + MDIO + SGMII + */ + /* Initialize QMSS */ + if (Init_Qmss () != 0) + { + printf ("QMSS init failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("QMSS successfully initialized \n"); +//End of commenting + } + + /* Initialize CPPI */ + if (Init_Cppi () != 0) + { + printf ("CPPI init failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("CPPI successfully initialized \n"); +//End of commenting + } + + /* Init PA LLD */ + if (Init_PASS () != 0) + { + printf ("PASS init failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("PASS successfully initialized \n"); +//End of commenting + } + + /* Initialize the CPSW switch */ + if (Init_Cpsw (host_mac, amc_mac, wire_mac) != 0) + { + printf ("Ethernet subsystem init failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("Ethernet subsystem successfully initialized \n"); +//End of commenting + } + + /* Setup Tx */ + if (Setup_Tx () != 0) + { + printf ("Tx setup failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("Tx setup successfully done \n"); +//End of commenting + } + + /* Setup Rx */ + if (Setup_Rx () != 0) + { + printf ("Rx setup failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("Rx setup successfully done \n"); +//End of commenting + } + + /* Setup PA */ + if (Setup_PASS (host_mac) != 0) + { + printf ("PASS setup failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("PASS setup successfully done \n"); +//End of commenting + } + + /* Setup PA for broadcast MAC address */ + if (Setup_PASS (broadcast_mac) != 0) + { + printf ("PASS setup failed \n"); + return -1; + } + else + { +//ADITYA : commenting out printfs +// printf ("PASS setup successfully done \n"); +//End of commenting + } + + return 0; +} //}}} + +int32_t eth_send(uint8_t* payload, uint32_t payload_len) //{{{ +{ + Cppi_Desc* pCppiDesc; + + /* Get a free descriptor from the global free queue we setup + * during initialization. + */ + if ((pCppiDesc = Qmss_queuePop(gTxFreeQHnd)) == NULL) + { + printf("No Tx free descriptor. Cant run send/rcv test \n"); + return -1; + } + + /* The descriptor address returned from the hardware has the + * descriptor size appended to the address in the last 4 bits. + * + * To get the true descriptor size, always mask off the last + * 4 bits of the address. + */ + pCppiDesc = (Ptr) ((uint32_t) pCppiDesc & 0xFFFFFFF0); + + Cppi_setData(Cppi_DescType_HOST, + (Cppi_Desc *) pCppiDesc, + (uint8_t*)OSL_Convert_CoreLocal2GlobalAddr((uint32_t)payload), + payload_len); + + Cppi_setPacketLen (Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, payload_len); + + //WARNING: ALE causes a severe performance drop in packet transmit rate + //Ref: https://e2e.ti.com/support/dsp/c6000_multi-core_dsps/f/639/t/397066 + + //Lookup ALE to decide outgoing port on on-board switch, add CRC + //Cppi_setPSFlags(Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, 0); + + //Skip ALE, send out eth port 1 on on-board switch, add CRC + //Cppi_setPSFlags(Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, 1); + + //Skip ALE, send out eth port 2 on on-board switch, add CRC + Cppi_setPSFlags(Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, 2); + + //Use ALE, skip CRC + //Cppi_setPSFlags(Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, 8); + + //Skip ALE, send out eth port 1 on on-board switch, skip CRC + //Cppi_setPSFlags(Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, 9); + + //Skip ALE, send out eth port 2 on on-board switch, skip CRC + //Cppi_setPSFlags(Cppi_DescType_HOST, (Cppi_Desc *)pCppiDesc, 10); + + + /* Send the packet out the mac */ + Qmss_queuePush (gPaTxQHnd[8], pCppiDesc, payload_len, SIZE_HOST_DESC, Qmss_Location_TAIL); + + /* Increment the application transmit counter */ + gTxCounter++; + + // TODO maybe we need a cycle delay to wait for the PA + + return 0; +} //}}} + +static int32_t eth_recv_from_queue(Cppi_Desc* pCppiDesc, uint8_t** payload, uint32_t* payload_len) //{{{ +{ + Cppi_HostDesc* pHostDesc; + + pHostDesc = (Cppi_HostDesc *)pCppiDesc; + + /* Verify the application software info we received is same + * as what we had sent earlier. + */ + if (pHostDesc->softwareInfo0 != 0xaaaaaaaa) + { + printf ("VerifyPacket: Found an entry in receive queue with swinfo0 = 0x%08x, expected 0x%08x\n", + pHostDesc->softwareInfo0, 0xaaaaaaaa); + + pHostDesc->buffLen = pHostDesc->origBufferLen; + Qmss_queuePush (gRxFreeQHnd, (Ptr)pHostDesc, pHostDesc->buffLen, SIZE_HOST_DESC, Qmss_Location_TAIL); + + return -1; + } + + /* Set the buffer to the packet */ + *payload = (uint8_t*)pHostDesc->buffPtr; + *payload_len = pHostDesc->buffLen; + + /* Increment Rx counter to indicate the number of successfully + * received packets by the example app. + */ + gRxCounter++; + + /* Reset the buffer length and put the descriptor back on the free queue */ + pHostDesc->buffLen = pHostDesc->origBufferLen; + Qmss_queuePush (gRxFreeQHnd, (Ptr)pHostDesc, pHostDesc->buffLen, SIZE_HOST_DESC, Qmss_Location_TAIL); + + /* Verify packet done. Return success. */ + return 0; +} //}}} + +int32_t eth_recv(uint8_t** payload, uint32_t* payload_len, uint8_t blocking) //{{{ +{ + static uint8_t sIsPingListUsed = 0; + Cppi_Desc* pCppiDesc; + uint32_t count, i; + + /* Wait for accumulator interrupt, configured to only interrupt when there is one packet */ + if (blocking) + { + while (qmssGblCfgParams.qmQueIntdReg->INTCNT_REG[PA_ACC_CHANNEL_NUM] <= 0); + } + else + { + if (qmssGblCfgParams.qmQueIntdReg->INTCNT_REG[PA_ACC_CHANNEL_NUM] <= 0) + { + return -1; + } + } + + /* Clear INTD and tell the accumulator it can move on to the ping or pong buffer */ + Qmss_ackInterrupt(PA_ACC_CHANNEL_NUM, 1); + Qmss_setEoiVector(Qmss_IntdInterruptType_HIGH, PA_ACC_CHANNEL_NUM); + + /* Get the number of entries in accumulator list. + * The hardware enqueues data alternatively to Ping/Pong buffer lists in + * the accumulator. Hence, we need to track which list (Ping/Pong) + * we serviced the last time and accordingly process the other one + * this time around. + */ + if (!sIsPingListUsed) + { + /* Serviced Pong list last time. So read off the Ping list now */ + count = gHiPriAccumList[0]; + } + else + { + /* Serviced Ping list last time. So read off the Pong list now */ + count = gHiPriAccumList[RX_INT_THRESHOLD + 1]; + } + + /* Process all the Results received + * + * Skip the first entry in the list that contains the + * entry count and proceed processing results. + */ + for (i = 1; i <= count; i ++) + { + /* Get the result descriptor. + * + * The hardware enqueues data alternatively to Ping/Pong buffer lists in + * the accumulator. Hence, we need to track which list (Ping/Pong) + * we serviced the last time and accordingly process the other one + * this time around. + */ + if (!sIsPingListUsed) + { + /* Serviced Pong list last time. So read off the Ping list now */ + pCppiDesc = (Cppi_Desc *) gHiPriAccumList[i]; + } + else + { + /* Serviced Ping list last time. So read off the Pong list now + * + * Skip over Ping list length to arrive at Pong list start. + */ + pCppiDesc = (Cppi_Desc *) gHiPriAccumList[i + RX_INT_THRESHOLD + 1]; + } + + /* Descriptor size appended to the address in the last 4 bits. + * + * To get the true descriptor size, always mask off the last + * 4 bits of the address. + */ + pCppiDesc = (Ptr) ((uint32_t) pCppiDesc & 0xFFFFFFF0); + eth_recv_from_queue(pCppiDesc, payload, payload_len); + } + + /* Clear the accumulator list and save whether we used Ping/Pong + * list information for next time around. + */ + if (count > 0) + { + if (!sIsPingListUsed) + { + /* Just processed Ping list */ + sIsPingListUsed = 1; + + /* Clear the accumulator list after processing */ + memset((void *) &gHiPriAccumList[0], 0, sizeof (uint32_t) * (RX_INT_THRESHOLD + 1)); + } + else + { + /* Just processed Pong list */ + sIsPingListUsed = 0; + + /* Clear the accumulator list after processing */ + memset((void *) &gHiPriAccumList[RX_INT_THRESHOLD + 1], 0, sizeof (uint32_t) * (RX_INT_THRESHOLD + 1)); + } + } + + /* Done processing interrupt. Return */ + return 0; +} //}}} + + +//void eth_getMACAddress(uint8_t* macAddress) { +// //Uint8 macAddress [6]; +// Uint8 portNum; +// portNum = 0; +// +// CSL_CPSW_3GF_getPortMACAddress (portNum, macAddress); +//} + +void eth_printMAC(uint8_t * mac) { + int i; + for (i = 0; i < 5; i++) + printf("%02x:", mac[i]); + printf("%02x", mac[i]); +} + +void eth_printUDPPayloadChars(NET_ip_packet * ip_pkt, Uint32 nChars) { + unsigned char * udp_payload = ip_pkt->data + sizeof(NET_udphdr); + int i; + for (i = 0; i < nChars; i++) { + //printf("%c", udp_payload[i]); + printf("%02x ", udp_payload[i]); + } +} diff --git a/pool/shard006/C/0119356_wsf_trace.c b/pool/shard006/C/0119356_wsf_trace.c new file mode 100644 index 0000000000000000000000000000000000000000..4a8f76deaa277b8141d9ea2264ae6ca345ad6da9 --- /dev/null +++ b/pool/shard006/C/0119356_wsf_trace.c @@ -0,0 +1,286 @@ +/*************************************************************************************************/ +/*! + * \file + * + * \brief Trace message implementation. + * + * Copyright (c) 2009-2018 Arm Ltd. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/*************************************************************************************************/ + +#include "wsf_types.h" +#include "wsf_trace.h" +#include "wsf_assert.h" +#include "wsf_cs.h" +#include "util/print.h" +#include + +/************************************************************************************************** + Macros +**************************************************************************************************/ + +/*! \brief Length of newline and carriage return suffix. */ +#define WSF_TRACE_SUFFIX_LEN 2 + +#ifndef WSF_PRINTF_MAX_LEN +/*! \brief Maximum length of a trace string. */ +#define WSF_PRINTF_MAX_LEN 128 +#endif + +#ifndef WSF_TOKEN_RING_BUF_SIZE +/*! \brief Size of token ring buffer (multiple of 2^N). */ +#define WSF_TOKEN_RING_BUF_SIZE 32 +#endif + +/*! \brief Ring buffer flow control condition detected. */ +#define WSF_TOKEN_FLAG_FLOW_CTRL (1 << 28) + +/************************************************************************************************** + Data types +**************************************************************************************************/ + +/*! \brief Trace control block. */ +struct +{ + WsfTraceHandler_t sendMsgCback; /*!< Send trace message callback. */ + WsfBt4TraceCback_t bt4cback; /*!< Platform trace callback for BT4. */ + uint32_t numDropMsg; /*!< Number of dropped messages since last successful. */ + bool_t enabled; /*!< Tracing state. */ + +#if WSF_TOKEN_ENABLED == TRUE + union + { + struct + { + uint32_t token; /*!< Token. */ + uint32_t param; /*!< Parameter. */ + } v; /*!< Value accessor. */ + /* Use native packing for speed. Host will resolve endian. */ + uint8_t buf[8]; /*!< Buffer accessor. */ + } ringBuf[WSF_TOKEN_RING_BUF_SIZE]; /*!< Token message ring buffer. */ + uint32_t prodIdx; /*!< Ring buffer producer index. */ + uint32_t consIdx; /*!< Ring buffer consumer index. */ +#endif +} wsfTraceCb; + +/*************************************************************************************************/ +/*! + * \brief Register BT4 platform trace callback function. + * + * \param cback Callback function + * + * \return None. + */ +/*************************************************************************************************/ +void WsfTraceRegister(WsfBt4TraceCback_t cback) +{ + wsfTraceCb.bt4cback = cback; +} + +#if WSF_TOKEN_ENABLED == TRUE +/*************************************************************************************************/ +/*! + * \brief Store tokenized message. + * + * \param tok Message token. + * \param param Message parameter. + * + * \return None. + */ +/*************************************************************************************************/ +void WsfToken(uint32_t tok, uint32_t param) +{ + static uint32_t flags = 0; + + if (!wsfTraceCb.enabled) + { + return; + } + + WSF_CS_INIT(cs); + WSF_CS_ENTER(cs); + + uint32_t prodIdx = (wsfTraceCb.prodIdx + 1) & (WSF_TOKEN_RING_BUF_SIZE - 1); + + if (prodIdx != wsfTraceCb.consIdx) + { + wsfTraceCb.ringBuf[wsfTraceCb.prodIdx].v.token = tok | flags; + wsfTraceCb.ringBuf[wsfTraceCb.prodIdx].v.param = param; + wsfTraceCb.prodIdx = prodIdx; + flags = 0; + } + else + { + flags = WSF_TOKEN_FLAG_FLOW_CTRL; + } + + WSF_CS_EXIT(cs); +} + +/*************************************************************************************************/ +/*! + * \brief Service the trace ring buffer. + * + * \return TRUE if trace messages pending, FALSE otherwise. + * + * This routine is called in the main loop for a "push" type trace systems. + */ +/*************************************************************************************************/ +bool_t WsfTokenService(void) +{ + WSF_ASSERT(wsfTraceCb.sendMsgCback); + + if (wsfTraceCb.consIdx != wsfTraceCb.prodIdx) + { + /* Advance consumer counter only if write successful. */ + if (wsfTraceCb.sendMsgCback((uint8_t *)&wsfTraceCb.ringBuf[wsfTraceCb.consIdx], sizeof(wsfTraceCb.ringBuf[0]))) + { + wsfTraceCb.consIdx = (wsfTraceCb.consIdx + 1) & (WSF_TOKEN_RING_BUF_SIZE - 1); + } + return TRUE; + } + + return FALSE; +} +#endif + +#if WSF_TRACE_ENABLED == TRUE +/*************************************************************************************************/ +/*! + * \brief Create overflow message. + * + * \param pBuf Buffer to store output in. + * \param pStr Format string. + * Addition parameters variable arguments to the format string. + * + * \return Length in bytes of overflow message. + */ +/*************************************************************************************************/ +uint8_t wsfTraceOverFlowMessage(char *pBuf, const char *pStr, ...) +{ + uint8_t len; + va_list args; + + va_start(args, pStr); + + len = PrintVsn(pBuf, WSF_PRINTF_MAX_LEN, pStr, args); + + va_end(args); + + return len; +} + +/*************************************************************************************************/ +/*! + * \brief Output trace message. + * + * \param pStr Format string + * Addition parameters variable arguments to the format string. + * + * \return None. + */ +/*************************************************************************************************/ +void WsfTrace(const char *pStr, ...) +{ + if (!wsfTraceCb.enabled) + { + /* Discard message when disabled. */ + return; + } + + if (wsfTraceCb.bt4cback != NULL) + { + va_list args; + + va_start(args, pStr); + if (wsfTraceCb.bt4cback) + { + (*wsfTraceCb.bt4cback)(pStr, args); + } + va_end(args); + } + else if (wsfTraceCb.sendMsgCback != NULL) + { + uint32_t len; + va_list args; + /* Use heap memory to ease stack utilization. */ + static char buf[WSF_PRINTF_MAX_LEN]; + + va_start(args, pStr); + + /* Dropped message notification. */ + if (wsfTraceCb.numDropMsg) + { + static char dropMsg[] = ">>> Trace buffer overflowed; %u message(s) lost <<<\r\n"; + + len = wsfTraceOverFlowMessage(buf, dropMsg, wsfTraceCb.numDropMsg); + + if (wsfTraceCb.sendMsgCback((uint8_t *)buf, len) == FALSE) + { + wsfTraceCb.numDropMsg++; + + /* Trace I/O flow control continues. */ + return; + } + + wsfTraceCb.numDropMsg = 0; + } + + /* Format message. */ + len = PrintVsn(buf, WSF_PRINTF_MAX_LEN - WSF_TRACE_SUFFIX_LEN, pStr, args); + buf[len++] = '\r'; + buf[len++] = '\n'; + + /* Deliver message. */ + if (wsfTraceCb.sendMsgCback((uint8_t *)buf, (uint8_t)len) == FALSE) + { + /* Trace I/O flow controlled; drop message. */ + wsfTraceCb.numDropMsg = 1; + } + } +} +#endif + +/*************************************************************************************************/ +/*! + * \brief Enable trace messages. + * + * \param enable TRUE to enable, FALSE to disable + * + * \return None. + */ +/*************************************************************************************************/ +void WsfTraceEnable(bool_t enable) +{ + WSF_ASSERT(wsfTraceCb.sendMsgCback); + wsfTraceCb.enabled = enable; +} + +/*************************************************************************************************/ +/*! + * \brief Register trace handler. + * + * \param traceCback Token event handler. + * + * \return None. + * + * This routine registers trace output handler. This callback is called when the trace data is + * ready for writing. + */ +/*************************************************************************************************/ +void WsfTraceRegisterHandler(WsfTraceHandler_t traceCback) +{ + wsfTraceCb.sendMsgCback = traceCback; +} diff --git a/pool/shard006/C/0119363_ngx_tcp_log.c b/pool/shard006/C/0119363_ngx_tcp_log.c new file mode 100644 index 0000000000000000000000000000000000000000..ee756352d9f2e7e1ed2f0e62384710f512ed1b61 --- /dev/null +++ b/pool/shard006/C/0119363_ngx_tcp_log.c @@ -0,0 +1,204 @@ + + +#include +#include +#include + + +static u_char * ngx_tcp_time(u_char *buf, time_t t); +static u_char *ngx_tcp_log_fill(ngx_tcp_session_t *s, u_char *buf); +static void ngx_tcp_log_write(ngx_tcp_session_t *s, ngx_tcp_log_t *log, + u_char *buf, size_t len); + + +ngx_int_t +ngx_tcp_log_handler(ngx_tcp_session_t *s) +{ + u_char *line, *p; + size_t len; + ngx_uint_t l; + ngx_connection_t *c; + ngx_tcp_log_t *log; + ngx_open_file_t *file; + ngx_tcp_log_srv_conf_t *lscf; + ngx_tcp_core_srv_conf_t *cscf; + + ngx_log_debug0(NGX_LOG_DEBUG_TCP, s->connection->log, 0, + "tcp access log handler"); + + cscf = ngx_tcp_get_module_srv_conf(s, ngx_tcp_core_module); + lscf = cscf->access_log; + + if (lscf->off) { + return NGX_OK; + } + + c = s->connection; + log = lscf->logs->elts; + for (l = 0; l < lscf->logs->nelts; l++) { + + if (ngx_time() == log[l].disk_full_time) { + + /* + * on FreeBSD writing to a full filesystem with enabled softupdates + * may block process for much longer time than writing to non-full + * filesystem, so we skip writing to a log for one second + */ + + continue; + } + + len = 0; + + /* Calculate the length */ + len += sizeof("1970/09/28 12:00:00"); /* log time */ + len += NGX_INT64_LEN + 2; /* [ngx_pid] */ + len += c->addr_text.len + 1; /* client address */ + len += s->addr_text->len + 1; /* this session address */ + len += sizeof("1970/09/28 12:00:00"); /* accept time */ + len += sizeof("255.255.255.255:65536"); /* upstream address */ + len += NGX_OFF_T_LEN + 1; /* read bytes from client */ + len += NGX_OFF_T_LEN + 1; /* write bytes to client */ + len += NGX_LINEFEED_SIZE; + + file = log[l].file; + + if (file && file->buffer) { + + if (len > (size_t) (file->last - file->pos)) { + + ngx_tcp_log_write(s, &log[l], file->buffer, + file->pos - file->buffer); + + file->pos = file->buffer; + } + + if (len <= (size_t) (file->last - file->pos)) { + + p = file->pos; + + p = ngx_tcp_log_fill(s, p); + + file->pos = p; + + continue; + } + } + + line = ngx_pnalloc(s->pool, len); + if (line == NULL) { + return NGX_ERROR; + } + + p = line; + + p = ngx_tcp_log_fill(s, p); + + ngx_tcp_log_write(s, &log[l], line, p - line); + } + + return NGX_OK; +} + + +static u_char * +ngx_tcp_time(u_char *buf, time_t t) +{ + ngx_tm_t tm; + + ngx_localtime(t, &tm); + + return ngx_sprintf(buf, "%4d/%02d/%02d %02d:%02d:%02d", + tm.ngx_tm_year, tm.ngx_tm_mon, + tm.ngx_tm_mday, tm.ngx_tm_hour, + tm.ngx_tm_min, tm.ngx_tm_sec); +} + + +static u_char * +ngx_tcp_log_fill(ngx_tcp_session_t *s, u_char *buf) +{ + u_char *last; + ngx_str_t *name; + ngx_connection_t *c; + ngx_tcp_upstream_t *u; + + c = s->connection; + + last = ngx_cpymem(buf, ngx_cached_err_log_time.data, + ngx_cached_err_log_time.len); + + last = ngx_sprintf(last, " [%P]", ngx_pid); + last = ngx_sprintf(last, " %V", &c->addr_text); + last = ngx_sprintf(last, " %V ", s->addr_text); + last = ngx_tcp_time(last, s->start_sec); + + name = NULL; + if (s->upstream) { + u = s->upstream; + if (u->peer.connection) { + name = u->peer.name; + } + } + + if (name) { + last = ngx_sprintf(last, " %V", name); + } + else { + last = ngx_sprintf(last, " -"); + } + + last = ngx_sprintf(last, " %O", s->bytes_read); + last = ngx_sprintf(last, " %O", s->bytes_write); + + ngx_linefeed(last); + + return last; +} + + +static void +ngx_tcp_log_write(ngx_tcp_session_t *s, ngx_tcp_log_t *log, u_char *buf, + size_t len) +{ + u_char *name; + time_t now; + ssize_t n; + ngx_err_t err; + + if(len == 0) return; + + name = log->file->name.data; + n = ngx_write_fd(log->file->fd, buf, len); + + if (n == (ssize_t) len) { + return; + } + + now = ngx_time(); + + if (n == -1) { + err = ngx_errno; + + if (err == NGX_ENOSPC) { + log->disk_full_time = now; + } + + if (now - log->error_log_time > 59) { + ngx_log_error(NGX_LOG_ALERT, s->connection->log, err, + ngx_write_fd_n " to \"%s\" failed", name); + + log->error_log_time = now; + } + + return; + } + + if (now - log->error_log_time > 59) { + ngx_log_error(NGX_LOG_ALERT, s->connection->log, 0, + ngx_write_fd_n " to \"%s\" was incomplete: %z of %uz", + name, n, len); + + log->error_log_time = now; + } +} diff --git a/pool/shard006/C/0119367_example1.c b/pool/shard006/C/0119367_example1.c new file mode 100644 index 0000000000000000000000000000000000000000..1b1f517e8a3719d7c96d0f3d6f5fd81178486152 --- /dev/null +++ b/pool/shard006/C/0119367_example1.c @@ -0,0 +1,75 @@ +#include +#include + +struct people{ +int no; +int pwd; +struct people *next; +}; + +int main(){ +struct people *head,*flag1,*flag2; +int i=0,j=0,k=1; + +printf("how many pople and the password:\n"); +scanf("%d %d",&i,&j); + +flag1=head=(struct people *)malloc(sizeof(struct people));//sizeof(struct people *)=4; +flag1->no=k; +scanf("%d",&(flag1->pwd)); + +while(++k<=i){ +flag2=(struct people *)malloc(sizeof(struct people)); +flag2->no=k; +scanf("%d",&(flag2->pwd)); +flag1->next=flag2; +flag1=flag2; +} + +flag1->next=head; + +/*while(i--){ + printf("%d %d\n",head->no,head->pwd); + head=head->next; +}*/ + + +k=j%i; +printf("%d %d %d ",i,j,k); +while(i!=1){ + +if(k==0){ + + flag1=head; + while(flag1->next->next!=head) + flag1=flag1->next; + printf("%d \n",flag1->next->no); + k=(flag1->next->pwd)%(--i); + printf("%d %d %d ",i,flag1->next->pwd,k); + flag1->next=head; + +} +else if(k==1){ + flag1=head; + while(flag1->next!=head) + flag1=flag1->next; + printf("%d \n",flag1->next->no); + k=(flag1->next->pwd)%(--i); + printf("%d %d %d ",i,flag1->next->pwd,k); + flag1->next=head->next; + head=flag1; +} +else{ + flag1=head; + while(k-->2) + flag1=flag1->next; + printf("%d \n",flag1->next->no); + k=(flag1->next->pwd)%(--i); + printf("%d %d %d ",i,flag1->next->pwd,k); + flag1->next=flag1->next->next; + head=flag1->next; +} +} +printf("%d\n",head->no); + +} diff --git a/pool/shard006/C/0119375_unix_local_server.c b/pool/shard006/C/0119375_unix_local_server.c new file mode 100644 index 0000000000000000000000000000000000000000..1311f21d1b181836e84def01e500fa7479348f99 --- /dev/null +++ b/pool/shard006/C/0119375_unix_local_server.c @@ -0,0 +1,154 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define MAX_RECV 1024 +#define SERVER_PATH "/tmp/sock_demo" + +int recvFunc(int rfd, std::string &msg) +{ + if (0 > rfd) return -1; + + char recv_buff[MAX_RECV] = {0}; + int recv_len, data_len, temp_len; + + /* recv msg header */ + recv_len = read(rfd, recv_buff, 8); + printf("step[1] >> recv_buff is \"%s\"\n", recv_buff); + if (8 == recv_len && 0 == strcmp(recv_buff, "vsec:")) { + /* recv msg length */ + recv_len = read(rfd, recv_buff, 10); + printf("step[2] >> recv_buff is \"%s\"\n", recv_buff); + if (10 == recv_len) { + temp_len = 0; + data_len = atoi(recv_buff); + if (0 >= data_len) return -2; + /* recv msg content */ + while(temp_len < data_len) { + int recv_max = data_len - temp_len; + recv_max = MAX_RECV < recv_max ? MAX_RECV : recv_max; + recv_len = read(rfd, recv_buff, recv_max); + if (0 > recv_len) break; + printf("step[3] date_len=%d, temp_len=%d, recv_len=%d, recv_buff is \"%s\"\n", data_len, temp_len, recv_len, recv_buff); + msg += recv_buff; + temp_len += recv_len; + } + if (temp_len >= data_len) return data_len; + } + } + + printf("recv failed date_len=%d temp_len=%d recv_len=%d\n", data_len, temp_len, recv_len); + return 0 == recv_len ? -3 : -4; +} + +int sendFunc(int wfd, const char *msg) +{ + int ret = 0, save_errno, send_len; + char head_buff[32]; + if (0 >= wfd) return -1; + if (NULL == msg || 0 == msg[0]) return -2; + + printf("pipe_send : %s\n", msg); + do { + send_len = strlen(msg); + + /* send head */ + snprintf(head_buff, 32, "vsec:"); + ret = write(wfd, head_buff, 8); + printf("step[1] >> send_buff is \"%s\" and ret is %d\n", head_buff, ret); + if (8 != ret) { + ret = -3; + break; + } + + /* send length */ + snprintf(head_buff, 32, "%010d", send_len+1); + ret = write(wfd, head_buff, 10); + printf("step[2] >> send_buff is \"%s\" and ret is %d\n", head_buff, ret); + if (10 != ret) { + ret = -4; + break; + } + + /* send message */ + ret = write(wfd, msg, strlen(msg)+1); + printf("step[3] >> send_buff is \"%s\" and ret is %d\n", msg, ret); + if (send_len+1 != ret) { + ret = -5; + break; + } + }while(0); + + printf("pipe_send : ret=%d\n", ret); + return ret; +} + +int main(int argc, char** argv) { + int server_sockfd, client_sockfd; + socklen_t server_len, client_len; + struct sockaddr_un server_address; + struct sockaddr_un client_address; + fd_set readfds, testfds; + int result; + + + // create socket + server_sockfd = socket(AF_LOCAL, SOCK_STREAM, 0); + if ( -1 == server_sockfd) { + perror("socket func fail "); + return -1; + } + + // init sockaddr + server_address.sun_family = AF_LOCAL; + strncpy(server_address.sun_path, SERVER_PATH, sizeof(server_address.sun_path)-1); + + + // bind sockaddr + unlink(SERVER_PATH); + server_len = sizeof(server_address); + bind(server_sockfd, (struct sockaddr*)&server_address, server_len); + + // listen + listen(server_sockfd, 5); + FD_ZERO(&readfds); + FD_SET(server_sockfd, &readfds); + + while(1) { + testfds = readfds; + printf("server waitting......\n"); + result = select(FD_SETSIZE, &testfds, NULL, NULL, NULL); + + if (result < 1) perror("select error : "); + + for (int fd = 0; fd < FD_SETSIZE; fd++) + { + if (!FD_ISSET(fd, &testfds)) continue; + + if (fd == server_sockfd) + { + client_len = sizeof(struct sockaddr_un); + client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); + FD_SET(client_sockfd, &readfds); + printf("adding client %d\n", client_sockfd); + }else + { + std::string msg; + recvFunc(fd, msg); + printf("==%s\n", msg.c_str()); + } + } + sleep(6); + } + close(server_sockfd); + return 0; +} + diff --git a/pool/shard006/C/0119379_softc-block.c b/pool/shard006/C/0119379_softc-block.c new file mode 100644 index 0000000000000000000000000000000000000000..8705c9d9c8537b91668ce22f8b477553aab3cb65 --- /dev/null +++ b/pool/shard006/C/0119379_softc-block.c @@ -0,0 +1,158 @@ +#include +#include +#include +#include +#include + +#include "softc-block-private.h" +#include "softc-block.h" + +/*! + * allocates a referenced memory + */ +static void *refmalloc(size_t size) +{ + void *ptr = malloc(sizeof(size_t) + size); + size_t *cnt = (size_t *)ptr; + *cnt = 0; + ptr += sizeof(size_t); + return ptr; +} + + +/*! + * reallocates a referenced memory + */ +static void *refrealloc(void *data, size_t size) +{ + void *ptr = data - sizeof(size_t); + ptr = realloc(ptr, sizeof(size_t) + size); + size_t *cnt = (size_t *)ptr; + *cnt = 0; + ptr += sizeof(size_t); + return ptr; +} + + +/*! + * returns number of references + */ +size_t softc_block_data_refs(const void *ptr) +{ + size_t *cnt = (size_t*)(ptr - sizeof(size_t)); + return *cnt; +} + +/*! + * increase the reference number and return its value + */ +static size_t inc(void **mem) +{ + size_t *cnt = (size_t*)((*mem) - sizeof(size_t)); + return ++(*cnt); +} + +/*! + * decrease the reference number and return its value. + * if all references are gone, the memory is freed. + */ +static size_t dec(void **mem) +{ + size_t *cnt = (size_t*)((*mem) - sizeof(size_t)); + if (*cnt > 0) + return --(*cnt); + + free((void*)(*mem)-sizeof(size_t)); + *mem = NULL; + return 0; +} + +softc_block_s *softc_block_shallow_copy(const softc_block_s *orig) +{ + softc_block_s *block = malloc(sizeof *block); + size_t size = sizeof(*block->dims)*orig->rank; + block->rank = orig->rank; + block->dims = malloc(size); + memcpy(block->dims, orig->dims, size); + inc((void**)&orig->data); + block->data = orig->data; + return block; +} + +softc_block_s *softc_block_create_type(size_t rank, const size_t dims[], size_t type_size) +{ + assert(rank > 0); + softc_block_s *block = malloc(sizeof *block); + size_t idx; + size_t tot = 1; + for (idx = 0; idx < rank; ++idx) { + tot *= dims[idx]; + } + block->rank = rank; + block->dims = malloc(sizeof(*dims)*rank); + memcpy(block->dims, (void*)dims, sizeof(*dims)*rank); + block->data = refmalloc(type_size * tot); + return block; +} + +void softc_block_free(softc_block_s *block) +{ + if(block != NULL) { + free(block->dims); + dec((void**)&block->data); + free(block); + } +} + +const void *softc_block_data(const softc_block_s *block) +{ + assert(block != NULL); + return block->data; +} + +const size_t *softc_block_dims(const softc_block_s *block) +{ + assert(block != NULL); + return block->dims; +} + +size_t softc_block_rank(const softc_block_s *block) +{ + assert(block != NULL); + return block->rank; +} + +void softc_block_reshape(softc_block_s *self, size_t rank, const size_t dims[]) +{ + size_t tot_orig = 1; + size_t tot_new = 1; + size_t idx; + for (idx = 0; idx < self->rank; ++idx) { + tot_orig *= self->dims[idx]; + } + for (idx = 0; idx < rank; ++idx) { + tot_new *= dims[idx]; + } + + /* Must reshape to the same size! */ + assert(tot_orig == tot_new); + + self->rank = rank; + self->dims = realloc(self->dims, sizeof(*dims)*rank); +} + +void softc_block_resize(softc_block_s *block, size_t rank, const size_t dims[], size_t type_size) +{ + /* warning! this command cannot be used if the block have multiple references*/ + assert(softc_block_data_refs(block->data) == 0); + + size_t idx; + size_t tot = 1; + for (idx = 0; idx < rank; ++idx) { + tot *= dims[idx]; + } + block->rank = rank; + block->dims = realloc(block->dims, sizeof(*dims)*rank); + memcpy(block->dims, (void*)dims, sizeof(*dims)*rank); + block->data = refrealloc(block->data, type_size * tot); +} diff --git a/pool/shard006/C/0119380_nx_event_source.c b/pool/shard006/C/0119380_nx_event_source.c new file mode 100644 index 0000000000000000000000000000000000000000..d9ce54911309d520da0f2d9239759c9d9e5c1977 --- /dev/null +++ b/pool/shard006/C/0119380_nx_event_source.c @@ -0,0 +1,116 @@ +/***************************************************************************\ + This file is part of the NxDragon Game Engine. + + Copyright 2013 Patrik Jeppsson + + NxDragon 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. + + NxDragon 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 NxDragon. If not, see . +\***************************************************************************/ + +#include "nx_event_source.h" +#include "nx_event_queue.h" +#include "nx_list.h" +#include "nx_mutex.h" + +#include "nx_memory.h" + +struct nx_event_source_t { + nx_list listeners; + nx_mutex *mutex; +}; + +/*************************************************************/ +nx_event_source* nx_event_source_create(void) +{ + struct nx_event_source_t *self = nx_malloc(sizeof(struct nx_event_source_t)); + nx_list_init(&self->listeners); + self->mutex = nx_mutex_create(); + + return self; +} + +/*************************************************************/ +void nx_event_source_delete(nx_event_source *self) +{ + nx_mutex_delete(self->mutex); + nx_list_delete(&self->listeners); + nx_free(self); +} + +/*************************************************************/ +nxbool nx_event_source_register(nx_event_source *self, nx_event_queue *event_queue) +{ + /* The event queue must be unique and valid object */ + if(event_queue == 0 || (nx_list_contains(&self->listeners,event_queue) == nxtrue)) + return nxfalse; + + nx_mutex_lock(self->mutex); + + nx_list_append(&self->listeners,event_queue); + + nx_mutex_unlock(self->mutex); + + return nxtrue; +} + +/*************************************************************/ +nxbool nx_event_source_unregister(nx_event_source *self, nx_event_queue *event_queue) +{ + int index = 0; + + nx_mutex_lock(self->mutex); + + if(event_queue == 0 || (nx_list_contains(&self->listeners,event_queue) == nxfalse)) + { + nx_mutex_unlock(self->mutex); + return nxfalse; + } + + while(index < nx_list_size(&self->listeners)) + { + if(nx_list_at(&self->listeners,index) == event_queue) + { + nx_list_remove_at(&self->listeners,index); + nx_mutex_unlock(self->mutex); + return nxtrue; + } + + ++index; + } + + nx_mutex_unlock(self->mutex); + return nxfalse; +} + +/*************************************************************/ +void nx_event_source_emit(nx_event_source *self, nx_event *event) +{ + int index = 0; + + nx_event_ref(event); + + /* Register the event source as the emitter of the event */ + event->event_source = self; + + nx_mutex_lock(self->mutex); + + while(index < nx_list_size(&self->listeners)) + { + nx_event_queue_insert(nx_list_at(&self->listeners,index),event); + ++index; + } + + nx_mutex_unlock(self->mutex); + + nx_event_release(event); +} diff --git a/pool/shard006/C/0119381_main.c b/pool/shard006/C/0119381_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f5c77ce44c3a7dfc8f4d2f89e23238da48f16942 --- /dev/null +++ b/pool/shard006/C/0119381_main.c @@ -0,0 +1,90 @@ + +// BUILD: $CC main.c -o $BUILD_DIR/versions.exe + +// RUN: ./versions.exe + +#include +#include +#include + +extern struct mach_header __dso_handle; + +int main() +{ + printf("[BEGIN] dyld_version_spi\n"); + dyld_platform_t active = dyld_get_active_platform(); + dyld_platform_t base = dyld_get_base_platform(active); + dyld_build_version_t absoluteMin = { .platform = base, .version = 0 }; + dyld_build_version_t absoluteMax = { .platform = base, .version = 0xffffffff }; + +#if TARGET_OS_OSX + if ( base != PLATFORM_MACOS ) { + printf("[FAIL] base.platform %u incorrect for macOS\n", base); + return 0; + } +#elif TARGET_OS_IOS + if ( base != PLATFORM_IOS ) { + printf("[FAIL] base.platform %u incorrect for iOS\n", base); + return 0; + } +#elif TARGET_OS_TV + if ( base != PLATFORM_TVOS ) { + printf("[FAIL] base.platform %u incorrect for tvOS\n", base); + return 0; + } +#elif TARGET_OS_BRIDGE + if ( base != PLATFORM_BRIDGEOS ) { + printf("[FAIL] base.platform %u incorrect for wacthOS\n", base); + return 0; + } +#elif TARGET_OS_WATCH + if ( base != PLATFORM_WATCHOS ) { + printf("[FAIL] base.platform %u incorrect for bridgeOS\n", base); + return 0; + } +#else + printf("[FAIL] Running on unknown platform\n"); + return 0; +#endif + +#if TARGET_OS_SIMULATOR + if (dyld_is_simulator_platform(active) != true) { + printf("[FAIL] active platform %u should be a simulator\n", active); + return 0; + } +#else + if (dyld_is_simulator_platform(active) == true) { + printf("[FAIL] active platform %u should not be a simulator\n", active); + return 0; + } +#endif + + if (dyld_is_simulator_platform(base) == true) { + printf("[FAIL] base platform %u should not be a simulator\n", base); + return 0; + } + + if (!dyld_sdk_at_least(&__dso_handle, absoluteMin)) { + printf("[FAIL] executable sdk version should not < 1.0.0\n"); + return 0; + } + + if (dyld_sdk_at_least(&__dso_handle, absoluteMax)) { + printf("[FAIL] executable sdk version should not > 65536.0.0\n"); + return 0; + } + + if (!dyld_minos_at_least(&__dso_handle, absoluteMin)) { + printf("[FAIL] executable min version should not < 1.0.0\n"); + return 0; + } + + if (dyld_minos_at_least(&__dso_handle, absoluteMax)) { + printf("[FAIL] executable min version should not > 65536.0.0\n"); + return 0; + } + + printf("[PASS] dyld_version_spi\n"); + return 0; +} + diff --git a/pool/shard006/C/0119383_best_cmod.c b/pool/shard006/C/0119383_best_cmod.c new file mode 100644 index 0000000000000000000000000000000000000000..b81da2dc1a9181c1f6561fe519fac9c215719d7c --- /dev/null +++ b/pool/shard006/C/0119383_best_cmod.c @@ -0,0 +1,99 @@ +/* + * best_cmod.c + * + * This program takes the output from the difmap modelfitting scripts for + * the lens monitoring program and finds the fluxes associated with the + * best fit models. The best fit models are written to model files. + * + * Usage: best_cmod [input date] [source_root] + * + * 02Apr97 CDF, A modification of the old getflux.c + * v14Apr97 CDF, Accounting for post 21Mar97 1635 models. + * v10May01 CDF, A big re-write to make more general. + * + */ + +#include +#include +#include +#include "dataio.h" +#include "modfuncs.h" + +/*....................................................................... + * + * Main program + * + */ + +int main(int argc, char *argv[]) +{ + int no_error=1; /* Flag set to 0 on error */ + float scal; /* Best-fit scale factor */ + char obsdate[MMAX]; /* Epoch of observation */ + char root[MMAX]; /* Source root name */ + char inmod[MMAX]; /* Input "scalmod" filename */ + char outmod[MMAX]; /* Output model filename */ + char basemod[MMAX]; /* Base model filename */ + FILE *mfp=NULL; /* Model output file */ + + /* + * Check command line format + */ + + if(argc != 3) { + fprintf(stderr,"\nUsage: best_cmod [obsdate] [source_root]\n\n"); + fprintf(stderr," e.g. For observations of 1633+741 on Feb 23, 1998\n"); + fprintf(stderr," type \"best_cmod 19980223 1633\"\n\n"); + return 1; + } + + /* + * Get relevant info from command line + */ + + strcpy(obsdate,argv[1]); + strcpy(root,argv[2]); + + /* + * Set filenames for input "scalmod" file and output model file. + */ + + sprintf(inmod,"%s_%s.scalmod",obsdate,root); + sprintf(outmod,"%s_%s.mod",obsdate,root); + + /* + * Get best-fit scale + */ + + if((cal_flux(inmod,&scal)) == 1) { + fprintf(stderr,"ERROR: best_cmod\n"); + return 1; + } + + /* + * Open base model file + */ + + + /* + * Create best-fit model + */ + + sprintf(basemod,"%s%s_mod_0",MODDIR,root); + if(scale_data(scal,scal,1.0,basemod)) + no_error = 0; + + /* + * Clean up and exit + */ + + if(mfp) + fclose(mfp); + + if(no_error) + return 0; + else { + fprintf(stderr,"ERROR: best_cmod\n"); + return 1; + } +} diff --git a/pool/shard006/C/0119385_eukrea_cpuimx25.c b/pool/shard006/C/0119385_eukrea_cpuimx25.c new file mode 100644 index 0000000000000000000000000000000000000000..98c9b435befb6680ce12d89dd85b000dcd7ee758 --- /dev/null +++ b/pool/shard006/C/0119385_eukrea_cpuimx25.c @@ -0,0 +1,237 @@ +/* + * (C) 2009 Pengutronix, Sascha Hauer + * (c) 2010 Eukrea Electromatique, Eric Bénard + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct fec_platform_data fec_info = { + .xcv_type = RMII, + .phy_addr = 0, +}; + +struct imx_nand_platform_data nand_info = { + .width = 1, + .hw_ecc = 1, +}; + +static struct imx_fb_videomode imxfb_mode = { + .mode = { + .name = "CMO-QVGA", + .refresh = 60, + .xres = 320, + .yres = 240, + .pixclock = KHZ2PICOS(6500), + .hsync_len = 30, + .left_margin = 38, + .right_margin = 20, + .vsync_len = 3, + .upper_margin = 15, + .lower_margin = 4, + }, + .pcr = 0xCAD08B80, + .bpp = 16, +}; + +static struct imx_fb_platform_data eukrea_cpuimx25_fb_data = { + .mode = &imxfb_mode, + .num_modes = 1, + .pwmr = 0x00A903FF, + .lscr1 = 0x00120300, + .dmacr = 0x80040060, +}; + +struct gpio_led led0 = { + .gpio = 2 * 32 + 19, + .active_low = 1, +}; + +#ifdef CONFIG_USB +static void imx25_usb_init(void) +{ + unsigned int tmp; + + /* Host 1 */ + tmp = readl(MX25_USB_OTG_BASE_ADDR + 0x600); + tmp &= ~(MX35_H1_SIC_MASK | MX35_H1_PM_BIT | MX35_H1_TLL_BIT | + MX35_H1_USBTE_BIT | MX35_H1_IPPUE_DOWN_BIT | MX35_H1_IPPUE_UP_BIT); + tmp |= (MXC_EHCI_INTERFACE_SINGLE_UNI) << MX35_H1_SIC_SHIFT; + tmp |= MX35_H1_USBTE_BIT; + tmp |= MX35_H1_IPPUE_DOWN_BIT; + writel(tmp, MX25_USB_OTG_BASE_ADDR + 0x600); + + tmp = readl(MX25_USB_OTG_BASE_ADDR + 0x584); + tmp |= 3 << 30; + writel(tmp, MX25_USB_OTG_BASE_ADDR + 0x584); + + /* Set to Host mode */ + tmp = readl(MX25_USB_OTG_BASE_ADDR + 0x5a8); + writel(tmp | 0x3, MX25_USB_OTG_BASE_ADDR + 0x5a8); +} + +#endif + +static struct fsl_usb2_platform_data usb_pdata = { + .operating_mode = FSL_USB2_DR_DEVICE, + .phy_mode = FSL_USB2_PHY_UTMI, +}; + +static iomux_v3_cfg_t eukrea_cpuimx25_pads[] = { + MX25_PAD_FEC_MDC__FEC_MDC, + MX25_PAD_FEC_MDIO__FEC_MDIO, + MX25_PAD_FEC_RDATA0__FEC_RDATA0, + MX25_PAD_FEC_RDATA1__FEC_RDATA1, + MX25_PAD_FEC_RX_DV__FEC_RX_DV, + MX25_PAD_FEC_TDATA0__FEC_TDATA0, + MX25_PAD_FEC_TDATA1__FEC_TDATA1, + MX25_PAD_FEC_TX_CLK__FEC_TX_CLK, + MX25_PAD_FEC_TX_EN__FEC_TX_EN, + /* UART1 */ + MX25_PAD_UART1_RXD__UART1_RXD, + MX25_PAD_UART1_TXD__UART1_TXD, + MX25_PAD_UART1_RTS__UART1_RTS, + MX25_PAD_UART1_CTS__UART1_CTS, + /* LCDC */ + MX25_PAD_LD0__LD0, + MX25_PAD_LD1__LD1, + MX25_PAD_LD2__LD2, + MX25_PAD_LD3__LD3, + MX25_PAD_LD4__LD4, + MX25_PAD_LD5__LD5, + MX25_PAD_LD6__LD6, + MX25_PAD_LD7__LD7, + MX25_PAD_LD8__LD8, + MX25_PAD_LD9__LD9, + MX25_PAD_LD10__LD10, + MX25_PAD_LD11__LD11, + MX25_PAD_LD12__LD12, + MX25_PAD_LD13__LD13, + MX25_PAD_LD14__LD14, + MX25_PAD_LD15__LD15, + MX25_PAD_GPIO_E__LD16, + MX25_PAD_GPIO_F__LD17, + MX25_PAD_LSCLK__LSCLK, + MX25_PAD_OE_ACD__OE_ACD, + MX25_PAD_VSYNC__VSYNC, + MX25_PAD_HSYNC__HSYNC, + /* BACKLIGHT CONTROL */ + MX25_PAD_PWM__GPIO_1_26, + /* I2C */ + MX25_PAD_I2C1_CLK__I2C1_CLK, + MX25_PAD_I2C1_DAT__I2C1_DAT, + /* SDCard */ + MX25_PAD_SD1_CLK__SD1_CLK, + MX25_PAD_SD1_CMD__SD1_CMD, + MX25_PAD_SD1_DATA0__SD1_DATA0, + MX25_PAD_SD1_DATA1__SD1_DATA1, + MX25_PAD_SD1_DATA2__SD1_DATA2, + MX25_PAD_SD1_DATA3__SD1_DATA3, + /* LED */ + MX25_PAD_POWER_FAIL__GPIO_3_19, + /* SWITCH */ + MX25_PAD_VSTBY_ACK__GPIO_3_18, +}; + +static int eukrea_cpuimx25_devices_init(void) +{ + mxc_iomux_v3_setup_multiple_pads(eukrea_cpuimx25_pads, + ARRAY_SIZE(eukrea_cpuimx25_pads)); + + led_gpio_register(&led0); + + imx25_iim_register_fec_ethaddr(); + imx25_add_fec(&fec_info); + + nand_info.width = 1; + imx25_add_nand(&nand_info); + + devfs_add_partition("nand0", 0x00000, 0x40000, + DEVFS_PARTITION_FIXED, "self_raw"); + dev_add_bb_dev("self_raw", "self0"); + + devfs_add_partition("nand0", 0x40000, 0x20000, + DEVFS_PARTITION_FIXED, "env_raw"); + dev_add_bb_dev("env_raw", "env0"); + + /* enable LCD */ + gpio_direction_output(26, 1); + gpio_set_value(26, 1); + + /* LED : default OFF */ + gpio_direction_output(2 * 32 + 19, 1); + + /* Switch : input */ + gpio_direction_input(2 * 32 + 18); + + imx25_add_fb(&eukrea_cpuimx25_fb_data); + + imx25_add_i2c0(NULL); + imx25_add_mmc0(NULL); + +#ifdef CONFIG_USB + imx25_usb_init(); + add_generic_usb_ehci_device(DEVICE_ID_DYNAMIC, MX25_USB_OTG_BASE_ADDR + 0x400, NULL); +#endif +#ifdef CONFIG_USB_GADGET + /* Workaround ENGcm09152 */ + writel(readl(MX25_USB_OTG_BASE_ADDR + 0x608) | (1 << 23), MX25_USB_OTG_BASE_ADDR + 0x608); + add_generic_device("fsl-udc", DEVICE_ID_DYNAMIC, NULL, MX25_USB_OTG_BASE_ADDR, 0x200, + IORESOURCE_MEM, &usb_pdata); +#endif + + armlinux_set_bootparams((void *)0x80000100); + armlinux_set_architecture(MACH_TYPE_EUKREA_CPUIMX25SD); + + return 0; +} + +device_initcall(eukrea_cpuimx25_devices_init); + +static int eukrea_cpuimx25_console_init(void) +{ + imx25_add_uart0(); + return 0; +} + +console_initcall(eukrea_cpuimx25_console_init); diff --git a/pool/shard006/C/0119389_GP2Y0A700K0F.c b/pool/shard006/C/0119389_GP2Y0A700K0F.c new file mode 100644 index 0000000000000000000000000000000000000000..adf868b4c8032345e0d0d42f529fff9fa38d85d3 --- /dev/null +++ b/pool/shard006/C/0119389_GP2Y0A700K0F.c @@ -0,0 +1,60 @@ + +/* + * $Id: GP2Y0A700K0F.c,v 1.3 2010/07/15 14:38:19 clivewebster Exp $ + * + * Revision History + * ================ + * $Log: GP2Y0A700K0F.c,v $ + * Revision 1.3 2010/07/15 14:38:19 clivewebster + * Allow variable ADC reference voltage + * + * Revision 1.2 2010/06/14 19:03:07 clivewebster + * Add copyright license info + * + * Revision 1.1 2010/01/30 21:21:49 clivewebster + * Added new sensors + * + * =========== + * + * Copyright (C) 2010 Clive Webster (webbot@webbot.org.uk) + * + * 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 . + * + * + * + * GP2Y0A700K0F.c + * + * Created on: 29-Jan-2010 + * Author: Clive Webster + */ + +#include "GP2.h" +// Requires the floating point library +#include + +#include "../../../a2d.h" + +// Read all the values and store into the device +static void __GP2Y0A700K0F_read(SENSOR* sensor){ + Sharp_GP2Y0A700K0F* device = (Sharp_GP2Y0A700K0F*)sensor; + +// uint16_t adc = a2dConvert10bit(device->adcPin); +// device->distance.cm = 94407.0 * pow(adc,-1.0891); + + uint16_t adc = a2dReadMv(device->adcPin); + device->distance.cm = 531492.0 * pow(adc,-1.0891); +} + +DISTANCE_CLASS const c_Sharp_GP2Y0A700K0F = MAKE_DISTANCE_CLASS(null,&__GP2Y0A700K0F_read,0,0); + diff --git a/pool/shard006/C/0119392_schedulercbscreateserver.c b/pool/shard006/C/0119392_schedulercbscreateserver.c new file mode 100644 index 0000000000000000000000000000000000000000..2780a71f2d5998a63fc5fef7e02a8a8005ebd54f --- /dev/null +++ b/pool/shard006/C/0119392_schedulercbscreateserver.c @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2011 Petr Benes. + * Copyright (C) 2011 On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#if HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +int _Scheduler_CBS_Create_server ( + Scheduler_CBS_Parameters *params, + Scheduler_CBS_Budget_overrun budget_overrun_callback, + rtems_id *server_id +) +{ + unsigned int i; + Scheduler_CBS_Server *the_server; + + if ( params->budget <= 0 || + params->deadline <= 0 || + params->budget >= SCHEDULER_EDF_PRIO_MSB || + params->deadline >= SCHEDULER_EDF_PRIO_MSB ) + return SCHEDULER_CBS_ERROR_INVALID_PARAMETER; + + for ( i = 0; i<_Scheduler_CBS_Maximum_servers; i++ ) { + if ( !_Scheduler_CBS_Server_list[i] ) + break; + } + + if ( i == _Scheduler_CBS_Maximum_servers ) + return SCHEDULER_CBS_ERROR_FULL; + + *server_id = i; + _Scheduler_CBS_Server_list[*server_id] = (Scheduler_CBS_Server *) + _Workspace_Allocate( sizeof(Scheduler_CBS_Server) ); + the_server = _Scheduler_CBS_Server_list[*server_id]; + if ( !the_server ) + return SCHEDULER_CBS_ERROR_NO_MEMORY; + + the_server->parameters = *params; + the_server->task_id = -1; + the_server->cbs_budget_overrun = budget_overrun_callback; + return SCHEDULER_CBS_OK; +} diff --git a/pool/shard006/C/0119393_mouse.c b/pool/shard006/C/0119393_mouse.c new file mode 100644 index 0000000000000000000000000000000000000000..3bf9c9393fa7c4a6cb8177301cf0e9cadeb0bf62 --- /dev/null +++ b/pool/shard006/C/0119393_mouse.c @@ -0,0 +1,307 @@ +/** + ****************************************************************************** + * @file USB_Host/DynamicSwitch_Standalone/Src/mouse.c + * @author MCD Application Team + * @version V1.4.0 + * @date 17-February-2017 + * @brief This file implements Functions for mouse menu + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2017 STMicroelectronics International N.V. + * 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. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + +/* Private typedef -----------------------------------------------------------*/ +extern USBH_HandleTypeDef hUSBHost; + +/* Private define ------------------------------------------------------------*/ + +/* Left Button Report data */ +#define HID_MOUSE_BUTTON1 0x01 +/* Right Button Report data */ +#define HID_MOUSE_BUTTON2 0x02 +/* Middle Button Report data */ +#define HID_MOUSE_BUTTON3 0x04 + +/* Mouse directions */ +#define MOUSE_TOP_DIR 0x80 +#define MOUSE_BOTTOM_DIR 0x00 +#define MOUSE_LEFT_DIR 0x80 +#define MOUSE_RIGHT_DIR 0x00 + +#define MOUSE_WINDOW_X 80 +#define MOUSE_WINDOW_Y 70 +#define MOUSE_WINDOW_X_MAX 181 +#define MOUSE_WINDOW_Y_MIN 101 +#define MOUSE_WINDOW_HEIGHT 70 +#define MOUSE_WINDOW_WIDTH 145 + +#define HID_MOUSE_BUTTON_HEIGHT 10 +#define HID_MOUSE_BUTTON_WIDTH 24 +#define HID_MOUSE_BUTTON1_XCHORD 80 +#define HID_MOUSE_BUTTON2_XCHORD 140 +#define HID_MOUSE_BUTTON3_XCHORD 200 +#define HID_MOUSE_BUTTON_YCHORD 150 + +#define MOUSE_LEFT_MOVE 1 +#define MOUSE_RIGHT_MOVE 2 +#define MOUSE_UP_MOVE 3 +#define MOUSE_DOWN_MOVE 4 + +#define HID_MOUSE_HEIGHTLSB 2 +#define HID_MOUSE_WIDTHLSB 2 +#define HID_MOUSE_RES_X 4 +#define HID_MOUSE_RES_Y 4 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void USR_MOUSE_Init(void); +static void HID_MOUSE_UpdatePosition(int8_t x, int8_t y); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Manages Mouse Menu Process. + * @param None + * @retval None + */ +void HID_MouseMenuProcess(void) +{ + switch(hid_demo.mouse_state) + { + case HID_MOUSE_IDLE: + hid_demo.mouse_state = HID_MOUSE_START; + HID_SelectItem(DEMO_MOUSE_menu, 0); + hid_demo.select = 0; + prev_select = 0; + break; + + case HID_MOUSE_WAIT: + if(hid_demo.select != prev_select) + { + prev_select = hid_demo.select; + HID_SelectItem(DEMO_MOUSE_menu, hid_demo.select & 0x7F); + + /* Handle select item */ + if(hid_demo.select & 0x80) + { + hid_demo.select &= 0x7F; + switch(hid_demo.select) + { + case 0: + hid_demo.mouse_state = HID_MOUSE_START; + break; + + case 1: /* Return */ + LCD_LOG_ClearTextZone(); + hid_demo.state = HID_DEMO_REENUMERATE; + hid_demo.select = 0; + break; + + default: + break; + } + } + } + break; + + case HID_MOUSE_START: + USR_MOUSE_Init(); + hid_demo.mouse_state = HID_MOUSE_WAIT; + HID_MOUSE_UpdatePosition(0,0); + break; + + default: + break; + } +} + +/** + * @brief Init Mouse window. + * @param None + * @retval None + */ +static void USR_MOUSE_Init(void) +{ + LCD_LOG_ClearTextZone(); + BSP_LCD_SetTextColor(LCD_COLOR_YELLOW); + BSP_LCD_DisplayStringAtLine(4, (uint8_t *)"USB HID Host Mouse Demo... "); + BSP_LCD_SetTextColor(LCD_LOG_DEFAULT_COLOR); + + /* Display Mouse Window */ + BSP_LCD_DrawRect(MOUSE_WINDOW_X, MOUSE_WINDOW_Y, MOUSE_WINDOW_WIDTH, MOUSE_WINDOW_HEIGHT); + + HID_MOUSE_ButtonReleased(0); + HID_MOUSE_ButtonReleased(1); + HID_MOUSE_ButtonReleased(2); + + BSP_LCD_SetTextColor(LCD_COLOR_GREEN); + BSP_LCD_SetBackColor(LCD_COLOR_BLACK); + + HID_MOUSE_UpdatePosition(0,0); +} + +/** + * @brief Processes Mouse data. + * @param data: Mouse data to be displayed + * @retval None + */ +void USR_MOUSE_ProcessData(HID_MOUSE_Info_TypeDef *data) +{ + if((data->x != 0) && (data->y != 0)) + { + HID_MOUSE_UpdatePosition(data->x , data->y); + } +} + +/** + * @brief Handles mouse scroll to update the mouse position on display window. + * @param x: USB HID Mouse X co-ordinate + * @param y: USB HID Mouse Y co-ordinate + * @retval None + */ +static void HID_MOUSE_UpdatePosition(int8_t x, int8_t y) +{ + static int16_t x_loc = 0, y_loc = 0; + static int16_t prev_x = 5, prev_y = 1; + + if((x != 0) || (y != 0)) + { + x_loc += x/2; + y_loc += y/10; + + if(y_loc > MOUSE_WINDOW_HEIGHT - 12) + { + y_loc = MOUSE_WINDOW_HEIGHT - 12; + } + if(x_loc > MOUSE_WINDOW_WIDTH - 10) + { + x_loc = MOUSE_WINDOW_WIDTH - 10; + } + + if(y_loc < 2) + { + y_loc = 2; + } + if(x_loc < 2) + { + x_loc = 2; + } + BSP_LCD_SetBackColor(LCD_COLOR_BLACK); + BSP_LCD_SetTextColor(LCD_COLOR_BLACK); + BSP_LCD_DisplayChar(MOUSE_WINDOW_X + prev_x, MOUSE_WINDOW_Y + prev_y, 'x'); + + BSP_LCD_SetTextColor(LCD_COLOR_GREEN); + BSP_LCD_DisplayChar(MOUSE_WINDOW_X + x_loc, MOUSE_WINDOW_Y + y_loc, 'x'); + + prev_x = x_loc; + prev_y = y_loc; + } +} + +/** + * @brief Handles mouse button press. + * @param button_idx: Mouse button pressed + * @retval None + */ +void HID_MOUSE_ButtonPressed(uint8_t button_idx) +{ + /* Set the color for button press status */ + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_SetBackColor(LCD_COLOR_BLUE); + + /* Change the color of button pressed to indicate button press */ + switch(button_idx) + { + /* Left Button Pressed */ + case 0: + BSP_LCD_FillRect(HID_MOUSE_BUTTON1_XCHORD, HID_MOUSE_BUTTON_YCHORD,\ + HID_MOUSE_BUTTON_WIDTH, HID_MOUSE_BUTTON_HEIGHT ); + break; + + /* Right Button Pressed */ + case 1: + BSP_LCD_FillRect(HID_MOUSE_BUTTON2_XCHORD,HID_MOUSE_BUTTON_YCHORD,\ + HID_MOUSE_BUTTON_WIDTH,HID_MOUSE_BUTTON_HEIGHT); + break; + + /* Middle button Pressed */ + case 2: + BSP_LCD_FillRect(HID_MOUSE_BUTTON3_XCHORD,HID_MOUSE_BUTTON_YCHORD,\ + HID_MOUSE_BUTTON_WIDTH,HID_MOUSE_BUTTON_HEIGHT); + break; + } +} + +/** + * @brief Handles mouse button release. + * @param button_idx: Mouse button released + * @retval None + */ +void HID_MOUSE_ButtonReleased(uint8_t button_idx) +{ + /* Set the color for release status */ + BSP_LCD_SetTextColor(LCD_COLOR_WHITE); + BSP_LCD_SetBackColor(LCD_COLOR_BLACK); + + /* Change the color of button released to default button color */ + switch(button_idx) + { + /* Left Button Released */ + case 0: + BSP_LCD_FillRect(HID_MOUSE_BUTTON1_XCHORD, HID_MOUSE_BUTTON_YCHORD,\ + HID_MOUSE_BUTTON_WIDTH, HID_MOUSE_BUTTON_HEIGHT); + break; + + /* Right Button Released */ + case 1: + BSP_LCD_FillRect(HID_MOUSE_BUTTON2_XCHORD, HID_MOUSE_BUTTON_YCHORD,\ + HID_MOUSE_BUTTON_WIDTH, HID_MOUSE_BUTTON_HEIGHT); + break; + + /* Middle Button Released */ + case 2: + BSP_LCD_FillRect(HID_MOUSE_BUTTON3_XCHORD, HID_MOUSE_BUTTON_YCHORD,\ + HID_MOUSE_BUTTON_WIDTH, HID_MOUSE_BUTTON_HEIGHT); + break; + } +} + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0119394_clk-s2mps11.c b/pool/shard006/C/0119394_clk-s2mps11.c new file mode 100644 index 0000000000000000000000000000000000000000..498304941338620e58e78195dfb37fb9a30683f7 --- /dev/null +++ b/pool/shard006/C/0119394_clk-s2mps11.c @@ -0,0 +1,275 @@ +/* + * clk-s2mps11.c - Clock driver for S2MPS11. + * + * Copyright (C) 2013,2014 Samsung Electornics + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum { + S2MPS11_CLK_AP = 0, + S2MPS11_CLK_CP, + S2MPS11_CLK_BT, + S2MPS11_CLKS_NUM, +}; + +struct s2mps11_clk { + struct sec_pmic_dev *iodev; + struct device_node *clk_np; + struct clk_hw hw; + struct clk *clk; + struct clk_lookup *lookup; + u32 mask; + unsigned int reg; +}; + +static struct s2mps11_clk *to_s2mps11_clk(struct clk_hw *hw) +{ + return container_of(hw, struct s2mps11_clk, hw); +} + +static int s2mps11_clk_prepare(struct clk_hw *hw) +{ + struct s2mps11_clk *s2mps11 = to_s2mps11_clk(hw); + + return regmap_update_bits(s2mps11->iodev->regmap_pmic, + s2mps11->reg, + s2mps11->mask, s2mps11->mask); +} + +static void s2mps11_clk_unprepare(struct clk_hw *hw) +{ + struct s2mps11_clk *s2mps11 = to_s2mps11_clk(hw); + + regmap_update_bits(s2mps11->iodev->regmap_pmic, s2mps11->reg, + s2mps11->mask, ~s2mps11->mask); +} + +static int s2mps11_clk_is_prepared(struct clk_hw *hw) +{ + int ret; + u32 val; + struct s2mps11_clk *s2mps11 = to_s2mps11_clk(hw); + + ret = regmap_read(s2mps11->iodev->regmap_pmic, + s2mps11->reg, &val); + if (ret < 0) + return -EINVAL; + + return val & s2mps11->mask; +} + +static unsigned long s2mps11_clk_recalc_rate(struct clk_hw *hw, + unsigned long parent_rate) +{ + return 32768; +} + +static struct clk_ops s2mps11_clk_ops = { + .prepare = s2mps11_clk_prepare, + .unprepare = s2mps11_clk_unprepare, + .is_prepared = s2mps11_clk_is_prepared, + .recalc_rate = s2mps11_clk_recalc_rate, +}; + +/* This s2mps11_clks_init tructure is common to s2mps11, s2mps13 and s2mps14 */ +static struct clk_init_data s2mps11_clks_init[S2MPS11_CLKS_NUM] = { + [S2MPS11_CLK_AP] = { + .name = "s2mps11_ap", + .ops = &s2mps11_clk_ops, + }, + [S2MPS11_CLK_CP] = { + .name = "s2mps11_cp", + .ops = &s2mps11_clk_ops, + }, + [S2MPS11_CLK_BT] = { + .name = "s2mps11_bt", + .ops = &s2mps11_clk_ops, +<<<<<<< HEAD + .flags = CLK_IS_ROOT, +======= +>>>>>>> upstream/master + }, +}; + +static struct device_node *s2mps11_clk_parse_dt(struct platform_device *pdev, + struct clk_init_data *clks_init) +{ + struct sec_pmic_dev *iodev = dev_get_drvdata(pdev->dev.parent); + struct device_node *clk_np; + int i; + + if (!iodev->dev->of_node) + return ERR_PTR(-EINVAL); + + clk_np = of_get_child_by_name(iodev->dev->of_node, "clocks"); + if (!clk_np) { + dev_err(&pdev->dev, "could not find clock sub-node\n"); + return ERR_PTR(-EINVAL); + } + + for (i = 0; i < S2MPS11_CLKS_NUM; i++) + of_property_read_string_index(clk_np, "clock-output-names", i, + &clks_init[i].name); + + return clk_np; +} + +static int s2mps11_clk_probe(struct platform_device *pdev) +{ + struct sec_pmic_dev *iodev = dev_get_drvdata(pdev->dev.parent); + struct s2mps11_clk *s2mps11_clks; + struct clk_hw_onecell_data *clk_data; + unsigned int s2mps11_reg; + int i, ret = 0; + enum sec_device_type hwid = platform_get_device_id(pdev)->driver_data; + + s2mps11_clks = devm_kcalloc(&pdev->dev, S2MPS11_CLKS_NUM, + sizeof(*s2mps11_clks), GFP_KERNEL); + if (!s2mps11_clks) + return -ENOMEM; + + clk_data = devm_kzalloc(&pdev->dev, sizeof(*clk_data) + + sizeof(*clk_data->hws) * S2MPS11_CLKS_NUM, + GFP_KERNEL); + if (!clk_data) + return -ENOMEM; + + switch (hwid) { + case S2MPS11X: + s2mps11_reg = S2MPS11_REG_RTC_CTRL; + break; + case S2MPS13X: + s2mps11_reg = S2MPS13_REG_RTCCTRL; + break; + case S2MPS14X: + s2mps11_reg = S2MPS14_REG_RTCCTRL; + break; + case S5M8767X: + s2mps11_reg = S5M8767_REG_CTRL1; + break; + default: + dev_err(&pdev->dev, "Invalid device type\n"); + return -EINVAL; + } + + /* Store clocks of_node in first element of s2mps11_clks array */ + s2mps11_clks->clk_np = s2mps11_clk_parse_dt(pdev, s2mps11_clks_init); + if (IS_ERR(s2mps11_clks->clk_np)) + return PTR_ERR(s2mps11_clks->clk_np); + + for (i = 0; i < S2MPS11_CLKS_NUM; i++) { + if (i == S2MPS11_CLK_CP && hwid == S2MPS14X) + continue; /* Skip clocks not present in some devices */ + s2mps11_clks[i].iodev = iodev; + s2mps11_clks[i].hw.init = &s2mps11_clks_init[i]; + s2mps11_clks[i].mask = 1 << i; + s2mps11_clks[i].reg = s2mps11_reg; + + s2mps11_clks[i].clk = devm_clk_register(&pdev->dev, + &s2mps11_clks[i].hw); + if (IS_ERR(s2mps11_clks[i].clk)) { + dev_err(&pdev->dev, "Fail to register : %s\n", + s2mps11_clks_init[i].name); + ret = PTR_ERR(s2mps11_clks[i].clk); + goto err_reg; + } + + s2mps11_clks[i].lookup = clkdev_hw_create(&s2mps11_clks[i].hw, + s2mps11_clks_init[i].name, NULL); + if (!s2mps11_clks[i].lookup) { + ret = -ENOMEM; + goto err_reg; + } + clk_data->hws[i] = &s2mps11_clks[i].hw; + } + + clk_data->num = S2MPS11_CLKS_NUM; + of_clk_add_hw_provider(s2mps11_clks->clk_np, of_clk_hw_onecell_get, + clk_data); + + platform_set_drvdata(pdev, s2mps11_clks); + + return ret; + +err_reg: + while (--i >= 0) + clkdev_drop(s2mps11_clks[i].lookup); + + return ret; +} + +static int s2mps11_clk_remove(struct platform_device *pdev) +{ + struct s2mps11_clk *s2mps11_clks = platform_get_drvdata(pdev); + int i; + + of_clk_del_provider(s2mps11_clks[0].clk_np); + /* Drop the reference obtained in s2mps11_clk_parse_dt */ + of_node_put(s2mps11_clks[0].clk_np); + + for (i = 0; i < S2MPS11_CLKS_NUM; i++) { + /* Skip clocks not present on S2MPS14 */ + if (!s2mps11_clks[i].lookup) + continue; + clkdev_drop(s2mps11_clks[i].lookup); + } + + return 0; +} + +static const struct platform_device_id s2mps11_clk_id[] = { + { "s2mps11-clk", S2MPS11X}, + { "s2mps13-clk", S2MPS13X}, + { "s2mps14-clk", S2MPS14X}, + { "s5m8767-clk", S5M8767X}, + { }, +}; +MODULE_DEVICE_TABLE(platform, s2mps11_clk_id); + +static struct platform_driver s2mps11_clk_driver = { + .driver = { + .name = "s2mps11-clk", + }, + .probe = s2mps11_clk_probe, + .remove = s2mps11_clk_remove, + .id_table = s2mps11_clk_id, +}; + +static int __init s2mps11_clk_init(void) +{ + return platform_driver_register(&s2mps11_clk_driver); +} +subsys_initcall(s2mps11_clk_init); + +static void __exit s2mps11_clk_cleanup(void) +{ + platform_driver_unregister(&s2mps11_clk_driver); +} +module_exit(s2mps11_clk_cleanup); + +MODULE_DESCRIPTION("S2MPS11 Clock Driver"); +MODULE_AUTHOR("Yadwinder Singh Brar "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0119395_pn532_mifare_ultralight.c b/pool/shard006/C/0119395_pn532_mifare_ultralight.c new file mode 100644 index 0000000000000000000000000000000000000000..5fb541461c380788b97ea051931be1c41c38723e --- /dev/null +++ b/pool/shard006/C/0119395_pn532_mifare_ultralight.c @@ -0,0 +1,326 @@ +/**************************************************************************/ +/*! + @file pn532_mifare_ultralight.c + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, K. Townsend (microBuilder.eu) + 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 copyright holders 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 ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. +*/ +/**************************************************************************/ + +/* MIFARE ULTRALIGHT DESCRIPTION + ============================= + + MIFARE Ultralight cards typically contain 512 bits (64 bytes) of + memory, including 4 bytes (32-bits) of OTP (One Time Programmable) + memory where the individual bits can be written but not erased. + + MF0ICU1 Mifare Ultralight Functional Specification: + http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf + + + Mifare Ultralight cards have a 7-byte UID + + EEPROM MEMORY + ============= + Mifare Ultralight cards have 512 bits (64 bytes) of EEPROM memory, + including 4 byte (32 bits) of OTP memory. Unlike Mifare Classic cards, + there is no authentication on a per block level, although the blocks + can be set to "read-only" mode using Lock Bytes (described below). + + EEPROM memory is organised into 16 pages of four bytes eachs, in + the following order + + Page Description + ---- ------------ + 0 Serial Number (4 bytes) + 1 Serial Number (4 bytes) + 2 Byte 0: Serial Number + Byte 1: Internal Memory + Byte 2..3: lock bytes + 3 One-time programmable memory (4 bytes) + 4..15 User memory (4 bytes) + + Lock Bytes (Page 2) + ------------------- + Bytes 2 and 3 of page 2 are referred to as "Lock Bytes". Each + page from 0x03 and higher can individually locked by setting the + corresponding locking bit to "1" to prevent further write access, + effectively making the memory read only. + + For information on the lock byte mechanism, refer to section 8.5.2 of + the datasheet (referenced above). + + OTP Bytes (Page 3) + ------------------ + Page 3 is the OTP memory, and by default all bits on this page are + set to 0. These bits can be bitwise modified using the Mifare WRITE + command, and individual bits can be set to 1, but can not be changed + back to 0. + + Data Pages (Pages 4..15) + ------------------------ + Pages 4 to 15 are can be freely read from and written to, + provided there is no conflict with the Lock Bytes described above. + + After production, the bytes have the following default values: + + Page Byte Values + ---- ---------------------- + 0 1 2 3 + 4 0xFF 0xFF 0xFF 0xFF + 5..15 0x00 0x00 0x00 0x00 + + ACCESSING DATA BLOCKS + ===================== + + Before you can access the cards, you must following two steps: + + 1.) 'Connect' to a Mifare Ultralight card and retrieve the 7 byte + UID of the card. + + 2.) Memory can be read and written directly once a passive mode + connection has been made. No authentication is required for + Mifare Ultralight cards. + +*/ +#include "projectconfig.h" + +#ifdef CFG_PN532 + +#include + +#include "../pn532.h" +#include "../pn532_bus.h" +#include "pn532_mifare_ultralight.h" + +#include "core/delay/delay.h" + +/**************************************************************************/ +/*! + Tries to detect MIFARE targets in passive mode. + + @param pbtCUID Pointer to the byte array where the card's 7 byte + UID will be stored once a card is detected + @param pszCUIDLen Pointer to the size of the card UID in bytes + + Response for a valid ISO14443A 106KBPS (Mifare Ultralight, etc.) + should be in the following format. See UM0701-02 section + 7.3.5 for more information + + byte Description + ------------- ------------------------------------------ + b0..6 Frame header and preamble + b7 Tags Found + b8 Tag Number (only one used in this example) + b9..10 SENS_RES + b11 SEL_RES + b12 NFCID Length + b13..NFCIDLen NFCID + + SENS_RES SEL_RES Manufacturer/Card Type NFCID Len + -------- ------- ----------------------- --------- + 00 44 00 NXP Mifare Ultralight 7 bytes + + @note Possible error messages are: + + - PN532_ERROR_WRONGCARDTYPE +*/ +/**************************************************************************/ +pn532_error_t pn532_mifareultralight_WaitForPassiveTarget (byte_t * pbtCUID, size_t * pszCUIDLen) +{ + byte_t abtResponse[PN532_RESPONSELEN_INLISTPASSIVETARGET]; + pn532_error_t error; + size_t szLen; + uint8_t i; + + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Waiting for an ISO14443A Card%s", CFG_PRINTF_NEWLINE); + #endif + + /* Try to initialise a single ISO14443A tag at 106KBPS */ + /* Note: To wait for a card with a known UID, append the four byte */ + /* UID to the end of the command. */ + byte_t abtCommand[] = { PN532_COMMAND_INLISTPASSIVETARGET, 0x01, PN532_MODULATION_ISO14443A_106KBPS}; + error = pn532Write(abtCommand, sizeof(abtCommand)); + if (error) + return error; + + /* Wait until we get a valid response or a timeout */ + do + { + delay(25); + error = pn532Read(abtResponse, &szLen); + } while (error == PN532_ERROR_RESPONSEBUFFEREMPTY); + if (error) + return error; + + /* Check szLen ... if it's 10 we've probably timed out via MaxRetries */ + /* ToDo: Properly parse and handle this error case! */ + if (szLen == 10) + { + return PN532_ERROR_TIMEOUTWAITINGFORCARD; + } + + /* Check SENS_RES to make sure this is a Mifare Ultralight card */ + /* Mifare Ultralight = 00 44 */ + if (abtResponse[10] == 0x44) + { + /* Card appears to be Mifare Ultralight */ + *pszCUIDLen = abtResponse[12]; + for (i=0; i < *pszCUIDLen; i++) + { + pbtCUID[i] = abtResponse[13+i]; + } + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Card Found: %s", CFG_PRINTF_NEWLINE); + PN532_DEBUG(" ATQA: "); + pn532PrintHex(abtResponse+9, 2); + PN532_DEBUG(" SAK: %02x%s", abtResponse[11], CFG_PRINTF_NEWLINE); + PN532_DEBUG(" UID: "); + pn532PrintHex(pbtCUID, *pszCUIDLen); + #endif + } + else + { + /* Card is ISO14443A but doesn't appear to be Mifare Ultralight */ + /* Mifare Classic = 0x0002, 0x0004, 0x0008 */ + /* Mifare DESFire = 0x0344 */ + /* Innovision Jewel = 0x0C00 */ + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Wrong Card Type (Expected ATQA 00 44) %s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE); + PN532_DEBUG(" ATQA : "); + pn532PrintHex(abtResponse+9, 2); + PN532_DEBUG(" SAK : %02x%s", abtResponse[11], CFG_PRINTF_NEWLINE); + PN532_DEBUG(" UID Length : %d%s", abtResponse[12], CFG_PRINTF_NEWLINE); + PN532_DEBUG(" UID : "); + size_t pos; + for (pos=0; pos < abtResponse[12]; pos++) + { + printf("%02x ", abtResponse[13 + pos]); + } + printf("%s%s", CFG_PRINTF_NEWLINE, CFG_PRINTF_NEWLINE); + #endif + return PN532_ERROR_WRONGCARDTYPE; + } + + return PN532_ERROR_NONE; +} + +/**************************************************************************/ +/*! + Tries to read an entire 4-byte page at the specified address. + + @param page The page number (0..63 in most cases) + @param pbtBuffer Pointer to the byte array that will hold the + retrieved data (if any) + + @note Possible error messages are: + + - PN532_ERROR_ADDRESSOUTOFRANGE + - PN532_ERROR_BLOCKREADFAILED +*/ +/**************************************************************************/ +pn532_error_t pn532_mifareultralight_ReadPage (uint8_t page, byte_t * pbtBuffer) +{ + pn532_error_t error; + byte_t abtCommand[4]; + byte_t abtResponse[PN532_RESPONSELEN_INDATAEXCHANGE]; + size_t szLen; + + if (page >= 64) + { + return PN532_ERROR_ADDRESSOUTOFRANGE; + } + + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Reading page %03d%s", page, CFG_PRINTF_NEWLINE); + #endif + + /* Prepare the command */ + abtCommand[0] = PN532_COMMAND_INDATAEXCHANGE; + abtCommand[1] = 1; /* Card number */ + abtCommand[2] = PN532_MIFARE_CMD_READ; /* Mifare Read command = 0x30 */ + abtCommand[3] = page; /* Page Number (0..63 in most cases) */ + + /* Send the commands */ + error = pn532Write(abtCommand, sizeof(abtCommand)); + if (error) + { + /* Bus error, etc. */ + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Read failed%s", CFG_PRINTF_NEWLINE); + #endif + return error; + } + + /* Read the response */ + memset(abtResponse, 0, PN532_RESPONSELEN_INDATAEXCHANGE); + do + { + delay(50); + error = pn532Read(abtResponse, &szLen); + } + while (error == PN532_ERROR_RESPONSEBUFFEREMPTY); + if (error) + { + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Read failed%s", CFG_PRINTF_NEWLINE); + #endif + return error; + } + + /* Make sure we have a valid response (should be 26 bytes long) */ + if (szLen == 26) + { + /* Copy the 4 data bytes to the output buffer */ + /* Block content starts at byte 9 of a valid response */ + /* Note that the command actually reads 16 byte or 4 */ + /* pages at a time ... we simply discard the last 12 */ + /* bytes */ + memcpy (pbtBuffer, abtResponse+8, 4); + } + else + { + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Unexpected response reading block %d. Bad key?%s", page, CFG_PRINTF_NEWLINE); + #endif + return PN532_ERROR_BLOCKREADFAILED; + } + + /* Display data for debug if requested */ + #ifdef PN532_DEBUGMODE + PN532_DEBUG("Page %02d: %s", page, CFG_PRINTF_NEWLINE); + pn532PrintHexChar(pbtBuffer, 4); + #endif + + // Return OK signal + return PN532_ERROR_NONE; +} + +#endif // #ifdef CFG_PN532 diff --git a/pool/shard006/C/0119398_CS_system.c b/pool/shard006/C/0119398_CS_system.c new file mode 100644 index 0000000000000000000000000000000000000000..bd46e11e60abab323e720b7ff4c79f38713a8719 --- /dev/null +++ b/pool/shard006/C/0119398_CS_system.c @@ -0,0 +1,287 @@ +/* + * Copyright (c) 2008, Autodesk, 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 the Autodesk, Inc. 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 Autodesk, Inc. ``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 Autodesk, Inc. 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. +*/ + +/* R E M A R K S + + This module carries several stub functions which are used to + insulate CS-MAP from system dependencies. +*/ + +#include "cs_map.h" + +int EXP_LVL1 CS_protect (int newValue) +{ + extern short cs_Protect; + + int rtnValue; + + rtnValue = cs_Protect; + cs_Protect = (short)newValue; + return rtnValue; +} +int EXP_LVL1 CS_unique (int newValue) +{ + extern char cs_Unique; + + int rtnValue; + + rtnValue = cs_Unique; + cs_Unique = (char)newValue; + return rtnValue; +} + +/* Establish definitions for all functions which the application programmer + did not provide. Application programmers are expected to make their + own definitions in the "cs_ClientBeg.h" or "cs_ClientEnd.h" header + files. */ + +void EXP_LVL5 *CS_malc (size_t blk_size) +{ +#ifndef _csMalloc +# define _csMalloc(_n) malloc(_n) +#endif + return (_csMalloc (blk_size)); +} + +void EXP_LVL5 *CS_ralc (void *ptr,size_t new_size) +{ +#ifndef _csRealloc +# define _csRealloc(_m,_n) realloc(_m,_n) +#endif + return (_csRealloc (ptr,new_size)); +} + +void EXP_LVL5 *CS_calc (size_t blk_count,size_t blk_size) +{ +#ifndef _csCalloc +# define _csCalloc(_n,_s) calloc(_n,_s) +#endif + return (_csCalloc (blk_count,blk_size)); +} + +void EXP_LVL5 CS_free (void *ptr) +{ +#ifndef _csFree +# define _csFree(_m) {if (_m) {free(_m); _m = 0;} } +#endif + + void *lclPtr; + + lclPtr = ptr; + _csFree (lclPtr); + return; +} +void EXP_LVL3 CS_dllFree (void *ptr) +{ + CS_free (ptr); + return; +} + +/****************************************************************************** + The following function is, essentially, a case insensitive file + open function. It was written by a CS-MAP user who distributes + product on a wide variety of platforms, specifically several + different flavors of UNIX. Thus, a case insensitive file open + is very useful. + + NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE + + The CS-MAP authors have no way of testing this function or verifying + its veracity. Use this function at your own risk. +******************************************************************************/ + +#if _FILE_SYSTEM == _fs_UNIX +#include +csFILE *CS_fopen(const char *filename, const char *mode) +{ + extern char cs_DirsepC; + struct stat statbuf; + csFILE *result = NULL; + char *fixed_filename = (char*) filename; + + /* If we are attempting to read from the file, and the file passed + * in does not exist, look for a different file in the same directory + * that has the same filename with a different case. + */ + + if ( (*mode == *_STRM_TXTRD) && stat(filename,&statbuf) ) + { + /* Make a copy of the filename passed in, and separate it into + * directory and path components. + */ + + char *last_path_sep; + + fixed_filename = (char*) malloc(strlen(filename)+1); + strcpy(fixed_filename,filename); + last_path_sep = strrchr(fixed_filename,cs_DirsepC); + if ( last_path_sep ) + { + /* Unless the directory is the current directory, we'd + * better make sure that at least the directory exists! + */ + char *filename_part = last_path_sep + 1; + *last_path_sep = '\0'; + if ( ! stat(fixed_filename,&statbuf) ) + { + /* Search the contents of the directory for a file which + * matches the one passed in, allowing for different + * case. + */ +#if 1 + DIR *directory = opendir(fixed_filename); + if ( directory ) + { + struct dirent *entry; + while ( (entry = readdir(directory)) != 0 ) + { + if ( ! CS_stricmp(entry->d_name,filename_part) ) + { + /* We have a match! It should be safe to assume that + * their lengths are the same, so we'll just copy it + * in-place. + */ + strcpy(filename_part,entry->d_name); + break; + } + } + closedir(directory); + } +#else + struct dirent *name_list = NULL; + int num_matches = scandir( fixed_filename, name_list, NULL, NULL); + if (num_matches > 0) + { + int ii; + for (ii=0;ii < num_matches;ii++ ) + { + if (!CS_stricmp (name_list[ii].d_name,filename_part)) + { + /* We have a match! It should be safe to assume that + * their lengths are the same, so we'll just copy it + * in-place. + */ + strcpy (filename_part,name_list[ii].d_name); + break; + } + } + free (name_list); + } +#endif + /* Replace the directory/path separator */ + *last_path_sep = cs_DirsepC; + } + } + } + result = (csFILE*) fopen(fixed_filename,mode); + if ( filename != fixed_filename ) + { + free(fixed_filename); + } + return result; +} +#endif + +#if _RUN_TIME == _rt_MOSXUNIX +/****************************************************************************** + Apple doesn't support findfirst or ftw. So, the following function + has been written to support use of CS-MAP on the Apple. It should be + noted, that the ftw functionality is no longer a part of the standard + library. + + Note: ftw is only used in the CS_swpal function in the CS_rlsUpdt module. + The CS_swpal function is only used in the CStestS.c function of the CS_Test + (console test) module. Since it is not used in the library portion of the product, + It should be moved to be a function in the CStestSupport.c source module, + With a prototype added to the cs_Test.h module. + + Alternatively, the ‘S’ test of the CS_Test module could be removed and + all references to CS_ftw could then be removed from the product. + + CS_rlsUpdt is used to update + older dictionary files to a newer format. Since the dictionary files + have not changed in many years, it's use is rather limited also. + + NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE + + The CS-MAP authors has no way of testing this function or verifying + its veracity. Use this function at your own risk. +*****************************************************************************/ + +int CS_ftw (const char *path,int (*fn)(const char*,const struct stat*,int),int depth) +{ + /* Apple doesn't include an "ftw" implementation, and the + * only one I could find is subject to the GNU license, + * so we'll go for a different implementation. [GEH 2000/11/30] + * + * This is a bit of a farce, really; the "depth" parameter is completely + * ignored. It would take very little work to make it call CS_ftw() + * recursively. + */ + extern char cs_DirsepC; + extern char *cs_DirP; + extern char cs_ExtsepC; + + char *cp; + char ctemp[MAXPATH]; + DIR *directory = NULL; + int st = 0; + + cp = CS_stcpy(ctemp,path); + + directory = opendir(ctemp); + if ( directory ) + { + struct dirent *entry; + *(cp - 1) = cs_DirsepC; + while ( entry = readdir(directory) ) + { + struct stat stat_buf; + CS_stcpy(cp,entry->d_name); + + st = stat (ctemp,&stat_buf); + if (st == 0) + { + if ( S_ISDIR(stat_buf.st_mode) ) /* Should really be smarter here */ + { + st = (*fn) (ctemp,&stat_buf,FTW_D); + } + else + { + st = (*fn) (ctemp,&stat_buf,FTW_F); + } + if (st != 0) + { + break; + } + } + } + closedir(directory); + } + return st; +} +#endif diff --git a/pool/shard006/C/0119400_output.c b/pool/shard006/C/0119400_output.c new file mode 100644 index 0000000000000000000000000000000000000000..739bbb8a6b4747fb992e7b5b50915082c91efb1a --- /dev/null +++ b/pool/shard006/C/0119400_output.c @@ -0,0 +1,188 @@ +/* +This file is part of mktorrent +Copyright (C) 2007, 2009 Emil Renner Berthing + +mktorrent 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. + +mktorrent is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA +*/ +#ifndef ALLINONE +#include /* off_t */ +#include /* printf() etc. */ +#include /* strlen() etc. */ +#include /* time() */ +#ifdef USE_OPENSSL +#include /* SHA_DIGEST_LENGTH */ +#else +#include +#include "sha1.h" +#endif + +#include "mktorrent.h" + +#define EXPORT +#endif /* ALLINONE */ + +/* + * write announce list + */ +static void write_announce_list(FILE *f, llist_t *list) +{ + /* the announce list is a list of lists of urls */ + fprintf(f, "13:announce-listl"); + /* go through them all.. */ + for (; list; list = list->next) { + slist_t *l; + + /* .. and print the lists */ + fprintf(f, "l"); + for (l = list->l; l; l = l->next) + fprintf(f, "%lu:%s", + (unsigned long)strlen(l->s), l->s); + fprintf(f, "e"); + } + fprintf(f, "e"); +} + +/* + * write file list + */ +static void write_file_list(FILE *f, flist_t *list) +{ + char *a, *b; + + fprintf(f, "5:filesl"); + + /* go through all the files */ + for (; list; list = list->next) { + /* the file list contains a dictionary for every file + with entries for the length and path + write the length first */ + fprintf(f, "d6:lengthi%" PRIoff "e4:pathl", list->size); + /* the file path is written as a list of subdirectories + and the last entry is the filename + sorry this code is even uglier than the rest */ + a = list->path; + /* while there are subdirectories before the filename.. */ + while ((b = strchr(a, DIRSEP_CHAR)) != NULL) { + /* set the next DIRSEP_CHAR to '\0' so fprintf + will only write the first subdirectory name */ + *b = '\0'; + /* print it bencoded */ + fprintf(f, "%lu:%s", (unsigned long)strlen(a), a); + /* undo our alteration to the string */ + *b = DIRSEP_CHAR; + /* and move a to the beginning of the next + subdir or filename */ + a = b + 1; + } + /* now print the filename bencoded and end the + path name list and file dictionary */ + fprintf(f, "%lu:%see", (unsigned long)strlen(a), a); + } + + /* whew, now end the file list */ + fprintf(f, "e"); +} + +/* + * write web seed list + */ +static void write_web_seed_list(FILE *f, slist_t *list) +{ + /* print the entry and start the list */ + fprintf(f, "8:url-listl"); + /* go through the list and write each URL */ + for (; list; list = list->next) + fprintf(f, "%lu:%s", (unsigned long)strlen(list->s), list->s); + /* end the list */ + fprintf(f, "e"); +} + +/* + * write metainfo to the file stream using all the information + * we've gathered so far and the hash string calculated + */ +EXPORT void write_metainfo(FILE *f, metafile_t *m, unsigned char *hash_string) +{ + /* let the user know we've started writing the metainfo file */ + printf("Writing metainfo file... "); + fflush(stdout); + + /* every metainfo file is one big dictonary */ + fprintf(f, "d"); + + if (m->announce_list != NULL) { + /* write the announce URL */ + fprintf(f, "8:announce%lu:%s", + (unsigned long)strlen(m->announce_list->l->s), + m->announce_list->l->s); + /* write the announce-list entry if we have + more than one announce URL */ + if (m->announce_list->next || m->announce_list->l->next) + write_announce_list(f, m->announce_list); + } + + /* add the comment if one is specified */ + if (m->comment != NULL) + fprintf(f, "7:comment%lu:%s", + (unsigned long)strlen(m->comment), + m->comment); + /* I made this! */ + fprintf(f, "10:created by13:mktorrent " VERSION); + /* add the creation date */ + if (!m->no_creation_date) + fprintf(f, "13:creation datei%lde", + (long)time(NULL)); + + /* now here comes the info section + it is yet another dictionary */ + fprintf(f, "4:infod"); + /* first entry is either 'length', which specifies the length of a + single file torrent, or a list of files and their respective sizes */ + if (!m->target_is_directory) + fprintf(f, "6:lengthi%" PRIoff "e", m->file_list->size); + else + write_file_list(f, m->file_list); + + /* the info section also contains the name of the torrent, + the piece length and the hash string */ + fprintf(f, "4:name%lu:%s12:piece lengthi%ue6:pieces%u:", + (unsigned long)strlen(m->torrent_name), m->torrent_name, + m->piece_length, m->pieces * SHA_DIGEST_LENGTH); + fwrite(hash_string, 1, m->pieces * SHA_DIGEST_LENGTH, f); + + /* set the private flag */ + if (m->private) + fprintf(f, "7:privatei1e"); + + /* end the info section */ + fprintf(f, "e"); + + /* add url-list if one is specified */ + if (m->web_seed_list != NULL) { + if (m->web_seed_list->next == NULL) + fprintf(f, "8:url-list%lu:%s", + (unsigned long)strlen(m->web_seed_list->s), + m->web_seed_list->s); + else + write_web_seed_list(f, m->web_seed_list); + } + + /* end the root dictionary */ + fprintf(f, "e"); + + /* let the user know we're done already */ + printf("done.\n"); + fflush(stdout); +} diff --git a/pool/shard006/C/0119402_wdt285.c b/pool/shard006/C/0119402_wdt285.c new file mode 100644 index 0000000000000000000000000000000000000000..1136217c81d8081a44da4df4be4533ffeaf35366 --- /dev/null +++ b/pool/shard006/C/0119402_wdt285.c @@ -0,0 +1,199 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + + +#undef ONLY_TESTING + +static unsigned int soft_margin = 60; +static unsigned int reload; +static unsigned long timer_alive; + +#ifdef ONLY_TESTING + +static void watchdog_fire(int irq, void *dev_id) +{ + printk(KERN_CRIT "Watchdog: Would Reboot.\n"); + *CSR_TIMER4_CNTL = 0; + *CSR_TIMER4_CLR = 0; +} +#endif + + +static void watchdog_ping(void) +{ + *CSR_TIMER4_LOAD = reload; +} + + +static int watchdog_open(struct inode *inode, struct file *file) +{ + int ret; + + if (*CSR_SA110_CNTL & (1 << 13)) + return -EBUSY; + + if (test_and_set_bit(1, &timer_alive)) + return -EBUSY; + + reload = soft_margin * (mem_fclk_21285 / 256); + + *CSR_TIMER4_CLR = 0; + watchdog_ping(); + *CSR_TIMER4_CNTL = TIMER_CNTL_ENABLE | TIMER_CNTL_AUTORELOAD + | TIMER_CNTL_DIV256; + +#ifdef ONLY_TESTING + ret = request_irq(IRQ_TIMER4, watchdog_fire, 0, "watchdog", NULL); + if (ret) { + *CSR_TIMER4_CNTL = 0; + clear_bit(1, &timer_alive); + } +#else + + *CSR_SA110_CNTL |= 1 << 13; + + ret = 0; +#endif + nonseekable_open(inode, file); + return ret; +} + + +static int watchdog_release(struct inode *inode, struct file *file) +{ +#ifdef ONLY_TESTING + free_irq(IRQ_TIMER4, NULL); + clear_bit(1, &timer_alive); +#endif + return 0; +} + +static ssize_t watchdog_write(struct file *file, const char __user *data, + size_t len, loff_t *ppos) +{ + + if (len) + watchdog_ping(); + + return len; +} + +static const struct watchdog_info ident = { + .options = WDIOF_SETTIMEOUT, + .identity = "Footbridge Watchdog", +}; + +static long watchdog_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + unsigned int new_margin; + int __user *int_arg = (int __user *)arg; + int ret = -ENOTTY; + + switch (cmd) { + case WDIOC_GETSUPPORT: + ret = 0; + if (copy_to_user((void __user *)arg, &ident, sizeof(ident))) + ret = -EFAULT; + break; + + case WDIOC_GETSTATUS: + case WDIOC_GETBOOTSTATUS: + ret = put_user(0, int_arg); + break; + + case WDIOC_KEEPALIVE: + watchdog_ping(); + ret = 0; + break; + + case WDIOC_SETTIMEOUT: + ret = get_user(new_margin, int_arg); + if (ret) + break; + + + if (new_margin < 0 || new_margin > 60) { + ret = -EINVAL; + break; + } + + soft_margin = new_margin; + reload = soft_margin * (mem_fclk_21285 / 256); + watchdog_ping(); + + case WDIOC_GETTIMEOUT: + ret = put_user(soft_margin, int_arg); + break; + } + return ret; +} + +static const struct file_operations watchdog_fops = { + .owner = THIS_MODULE, + .llseek = no_llseek, + .write = watchdog_write, + .unlocked_ioctl = watchdog_ioctl, + .open = watchdog_open, + .release = watchdog_release, +}; + +static struct miscdevice watchdog_miscdev = { + .minor = WATCHDOG_MINOR, + .name = "watchdog", + .fops = &watchdog_fops, +}; + +static int __init footbridge_watchdog_init(void) +{ + int retval; + + if (machine_is_netwinder()) + return -ENODEV; + + retval = misc_register(&watchdog_miscdev); + if (retval < 0) + return retval; + + printk(KERN_INFO + "Footbridge Watchdog Timer: 0.01, timer margin: %d sec\n", + soft_margin); + + if (machine_is_cats()) + printk(KERN_WARNING + "Warning: Watchdog reset may not work on this machine.\n"); + return 0; +} + +static void __exit footbridge_watchdog_exit(void) +{ + misc_deregister(&watchdog_miscdev); +} + +MODULE_AUTHOR("Phil Blundell "); +MODULE_DESCRIPTION("Footbridge watchdog driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); + +module_param(soft_margin, int, 0); +MODULE_PARM_DESC(soft_margin, "Watchdog timeout in seconds"); + +module_init(footbridge_watchdog_init); +module_exit(footbridge_watchdog_exit); diff --git a/pool/shard006/C/0119403_xps-outline.c b/pool/shard006/C/0119403_xps-outline.c new file mode 100644 index 0000000000000000000000000000000000000000..c4dda2a1dff36086a64cdca22161725799728dc7 --- /dev/null +++ b/pool/shard006/C/0119403_xps-outline.c @@ -0,0 +1,145 @@ +#include "mupdf/fitz.h" +#include "xps-imp.h" + +#include +#include + +/* + * Parse the document structure / outline parts referenced from fixdoc relationships. + */ + +static fz_outline * +xps_lookup_last_outline_at_level(fz_context *ctx, xps_document *doc, fz_outline *node, int level, int target_level) +{ + while (node->next) + node = node->next; + if (level == target_level || !node->down) + return node; + return xps_lookup_last_outline_at_level(ctx, doc, node->down, level + 1, target_level); +} + +static fz_outline * +xps_parse_document_outline(fz_context *ctx, xps_document *doc, fz_xml *root) +{ + fz_xml *node; + fz_outline *head = NULL, *entry, *tail; + int last_level = 1, this_level; + for (node = fz_xml_down(root); node; node = fz_xml_next(node)) + { + if (fz_xml_is_tag(node, "OutlineEntry")) + { + char *level = fz_xml_att(node, "OutlineLevel"); + char *target = fz_xml_att(node, "OutlineTarget"); + char *description = fz_xml_att(node, "Description"); + if (!target || !description) + continue; + + entry = fz_new_outline(ctx); + entry->title = Memento_label(fz_strdup(ctx, description), "outline_title"); + entry->uri = Memento_label(fz_strdup(ctx, target), "outline_uri"); + entry->page = xps_lookup_link_target(ctx, (fz_document*)doc, target, NULL, NULL).page; + entry->down = NULL; + entry->next = NULL; + + this_level = level ? atoi(level) : 1; + + if (!head) + { + head = entry; + } + else + { + tail = xps_lookup_last_outline_at_level(ctx, doc, head, 1, this_level); + if (this_level > last_level) + tail->down = entry; + else + tail->next = entry; + } + + last_level = this_level; + } + } + return head; +} + +static fz_outline * +xps_parse_document_structure(fz_context *ctx, xps_document *doc, fz_xml *root) +{ + fz_xml *node; + if (fz_xml_is_tag(root, "DocumentStructure")) + { + node = fz_xml_down(root); + if (node && fz_xml_is_tag(node, "DocumentStructure.Outline")) + { + node = fz_xml_down(node); + if (node && fz_xml_is_tag(node, "DocumentOutline")) + return xps_parse_document_outline(ctx, doc, node); + } + } + return NULL; +} + +static fz_outline * +xps_load_document_structure(fz_context *ctx, xps_document *doc, xps_fixdoc *fixdoc) +{ + xps_part *part; + fz_xml_doc *xml = NULL; + fz_outline *outline = NULL; + + fz_var(xml); + + part = xps_read_part(ctx, doc, fixdoc->outline); + fz_try(ctx) + { + xml = fz_parse_xml(ctx, part->data, 0, 0); + outline = xps_parse_document_structure(ctx, doc, fz_xml_root(xml)); + } + fz_always(ctx) + { + fz_drop_xml(ctx, xml); + xps_drop_part(ctx, doc, part); + } + fz_catch(ctx) + { + fz_rethrow(ctx); + } + + return outline; +} + +fz_outline * +xps_load_outline(fz_context *ctx, fz_document *doc_) +{ + xps_document *doc = (xps_document*)doc_; + xps_fixdoc *fixdoc; + fz_outline *head = NULL, *tail, *outline = NULL; + + for (fixdoc = doc->first_fixdoc; fixdoc; fixdoc = fixdoc->next) + { + if (fixdoc->outline) + { + fz_try(ctx) + { + outline = xps_load_document_structure(ctx, doc, fixdoc); + } + fz_catch(ctx) + { + fz_rethrow_if(ctx, FZ_ERROR_TRYLATER); + outline = NULL; + } + if (!outline) + continue; + + if (!head) + head = outline; + else + { + while (tail->next) + tail = tail->next; + tail->next = outline; + } + tail = outline; + } + } + return head; +} diff --git a/pool/shard006/C/0119404_timer0_configure.c b/pool/shard006/C/0119404_timer0_configure.c new file mode 100644 index 0000000000000000000000000000000000000000..6c1bfb201d57867ef4e4a425463410ae2c985c64 --- /dev/null +++ b/pool/shard006/C/0119404_timer0_configure.c @@ -0,0 +1,68 @@ +///////////////////////////////////////////////////////////////////////////// +// +// File: timer0_configure.c +// +// Copyright S. Brennen Ball, 2011 +// +// The author provides no guarantees, warantees, or promises, implied or +// otherwise. By using this software you agree to indemnify the author +// of any damages incurred by using it. +// +///////////////////////////////////////////////////////////////////////////// + +///////////////////////////////////////////////////////////////////////////// +// 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 Street, Fifth Floor, Boston, MA 02110-1301 USA +///////////////////////////////////////////////////////////////////////////// + +#include "timer0.h" + + +/////////////////////////////////////////// +// Internal defines +/////////////////////////////////////////// +#define TIMER0_CONFIG_OPTION_TMOD_MASK 0x0F //Mask for the options used for TMOD + + +///////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// void timer0_configure(uint8_t timer0_config_options, uint16_t t0_val) +// +// Description: +// Configures timer 0 +// +// Parameters: +// uint8_t timer0_config_options - timer 0 configuration options +// uint16_t t0_val - this is the auto-reload value in mode 2, and the TH0:TL0 (T0) value in other modes +// +// Return value: +// None +// +///////////////////////////////////////////////////////////////////////////////////////////////////////// +void timer0_configure(uint8_t timer0_config_options, uint16_t t0_val) +{ + //If timer 0 is being run as 2 8-bit timers with auto-reload, then set the reload value in TH0 and TL0 + if((timer0_config_options & TMOD_MODE0_MASK) == TIMER0_CONFIG_OPTION_MODE_2_8_BIT_AUTO_RLD_TMR) + { + TH0 = (uint8_t)t0_val; + TL0 = (uint8_t)t0_val; + } + else + { + timer0_set_t0_val(t0_val); + } + + //Set up TMOD register from timer0_config_options + TMOD = (TMOD & ~TIMER0_CONFIG_OPTION_TMOD_MASK) | (timer0_config_options & TIMER0_CONFIG_OPTION_TMOD_MASK); +} diff --git a/pool/shard006/C/0119405_configuration_attribute.c b/pool/shard006/C/0119405_configuration_attribute.c new file mode 100644 index 0000000000000000000000000000000000000000..e608497bd2c2f25eb401cace15ef10aac64f4560 --- /dev/null +++ b/pool/shard006/C/0119405_configuration_attribute.c @@ -0,0 +1,248 @@ +/* + * Copyright (C) 2005-2010 Martin Willi + * Copyright (C) 2010 revosec AG + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See . + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include + +#include "configuration_attribute.h" + +#include +#include +#include + +typedef struct private_configuration_attribute_t private_configuration_attribute_t; + +/** + * Private data of an configuration_attribute_t object. + */ +struct private_configuration_attribute_t { + + /** + * Public configuration_attribute_t interface. + */ + configuration_attribute_t public; + + /** + * Reserved bit + */ + bool reserved; + + /** + * Type of the attribute. + */ + u_int16_t type; + + /** + * Length of the attribute. + */ + u_int16_t length; + + /** + * Attribute value as chunk. + */ + chunk_t value; +}; + +/** + * Encoding rules to parse or generate a configuration attribute. + * + * The defined offsets are the positions in a object of type + * private_configuration_attribute_t. + */ +encoding_rule_t configuration_attribute_encodings[] = { + /* 1 reserved bit */ + { RESERVED_BIT, offsetof(private_configuration_attribute_t, reserved)}, + /* type of the attribute as 15 bit unsigned integer */ + { ATTRIBUTE_TYPE, offsetof(private_configuration_attribute_t, type) }, + /* Length of attribute value */ + { CONFIGURATION_ATTRIBUTE_LENGTH, offsetof(private_configuration_attribute_t, length) }, + /* Value of attribute if attribute format flag is zero */ + { CONFIGURATION_ATTRIBUTE_VALUE, offsetof(private_configuration_attribute_t, value) } +}; + +/* + 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + !R| Attribute Type ! Length | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + ~ Value ~ + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +*/ + +METHOD(payload_t, verify, status_t, + private_configuration_attribute_t *this) +{ + bool failed = FALSE; + + if (this->length != this->value.len) + { + DBG1(DBG_ENC, "invalid attribute length"); + return FAILED; + } + + switch (this->type) + { + case INTERNAL_IP4_ADDRESS: + case INTERNAL_IP4_NETMASK: + case INTERNAL_IP4_DNS: + case INTERNAL_IP4_NBNS: + case INTERNAL_ADDRESS_EXPIRY: + case INTERNAL_IP4_DHCP: + if (this->length != 0 && this->length != 4) + { + failed = TRUE; + } + break; + case INTERNAL_IP4_SUBNET: + if (this->length != 0 && this->length != 8) + { + failed = TRUE; + } + break; + case INTERNAL_IP6_ADDRESS: + case INTERNAL_IP6_SUBNET: + if (this->length != 0 && this->length != 17) + { + failed = TRUE; + } + break; + case INTERNAL_IP6_DNS: + case INTERNAL_IP6_NBNS: + case INTERNAL_IP6_DHCP: + if (this->length != 0 && this->length != 16) + { + failed = TRUE; + } + break; + case SUPPORTED_ATTRIBUTES: + if (this->length % 2) + { + failed = TRUE; + } + break; + case APPLICATION_VERSION: + /* any length acceptable */ + break; + default: + DBG1(DBG_ENC, "unknown attribute type %N", + configuration_attribute_type_names, this->type); + break; + } + + if (failed) + { + DBG1(DBG_ENC, "invalid attribute length %d for %N", + this->length, configuration_attribute_type_names, this->type); + return FAILED; + } + return SUCCESS; +} + +METHOD(payload_t, get_encoding_rules, void, + private_configuration_attribute_t *this, encoding_rule_t **rules, + size_t *rule_count) +{ + *rules = configuration_attribute_encodings; + *rule_count = countof(configuration_attribute_encodings); +} + +METHOD(payload_t, get_type, payload_type_t, + private_configuration_attribute_t *this) +{ + return CONFIGURATION_ATTRIBUTE; +} + +METHOD(payload_t, get_next_type, payload_type_t, + private_configuration_attribute_t *this) +{ + return NO_PAYLOAD; +} + +METHOD(payload_t, set_next_type, void, + private_configuration_attribute_t *this, payload_type_t type) +{ +} + +METHOD(payload_t, get_length, size_t, + private_configuration_attribute_t *this) +{ + return this->value.len + CONFIGURATION_ATTRIBUTE_HEADER_LENGTH; +} + +METHOD(configuration_attribute_t, get_cattr_type, configuration_attribute_type_t, + private_configuration_attribute_t *this) +{ + return this->type; +} + +METHOD(configuration_attribute_t, get_value, chunk_t, + private_configuration_attribute_t *this) +{ + return this->value; +} + +METHOD2(payload_t, configuration_attribute_t, destroy, void, + private_configuration_attribute_t *this) +{ + free(this->value.ptr); + free(this); +} + +/* + * Described in header. + */ +configuration_attribute_t *configuration_attribute_create() +{ + private_configuration_attribute_t *this; + + INIT(this, + .public = { + .payload_interface = { + .verify = _verify, + .get_encoding_rules = _get_encoding_rules, + .get_length = _get_length, + .get_next_type = _get_next_type, + .set_next_type = _set_next_type, + .get_type = _get_type, + .destroy = _destroy, + }, + .get_value = _get_value, + .get_type = _get_cattr_type, + .destroy = _destroy, + }, + ); + return &this->public; +} + +/* + * Described in header. + */ +configuration_attribute_t *configuration_attribute_create_value( + configuration_attribute_type_t type, chunk_t value) +{ + private_configuration_attribute_t *this; + + this = (private_configuration_attribute_t*)configuration_attribute_create(); + this->type = ((u_int16_t)type) & 0x7FFF; + this->value = chunk_clone(value); + this->length = value.len; + + return &this->public; +} + diff --git a/pool/shard006/C/0119408_idList.c b/pool/shard006/C/0119408_idList.c new file mode 100644 index 0000000000000000000000000000000000000000..f3b4af2911227b116b71be20e7fa6c67da26dbaf --- /dev/null +++ b/pool/shard006/C/0119408_idList.c @@ -0,0 +1,277 @@ +/** + * Copyright (C) 2008-2014, Marvell International Ltd. + * + * This software file (the "File") is distributed by Marvell International + * Ltd. under the terms of the GNU General Public License Version 2, June 1991 + * (the "License"). You may use, redistribute and/or modify this File in + * accordance with the terms and conditions of the License, a copy of which + * is available by writing to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the + * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE + * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE + * ARE EXPRESSLY DISCLAIMED. The License provides additional details about + * this warranty disclaimer. + * + */ + + +/*! + * \file idList.c + * \brief station id and 802.11 aid management + */ + +/*============================================================================= + * INCLUDE FILES + *============================================================================= + */ + +#include "wltypes.h" +#include "List.h" +#include "osif.h" +#include "buildModes.h" +#include "ap8xLnxIntf.h" +UINT32 AssocStationsCnt= 0; +/*============================================================================= + * DEFINITIONS + *============================================================================= +*/ + + +typedef struct IdListElem_t + +{ + struct IdListElem_t *nxt; + struct IdListElem_t *prv; + UINT16 Id; +} +IdListElem_t; + + +/*============================================================================= + * IMPORTED PUBLIC VARIABLES + *============================================================================= + */ +/*============================================================================= + * MODULE LEVEL VARIABLES + *============================================================================= + */ +DECLARE_LOCK(idLock); /*used to protect aid and stnid*/ + +IdListElem_t AidList[MAX_AID + 1]; + +IdListElem_t *StnIdList= NULL; + + +static List FreeStaIdList; +static List StaIdList; + +static List FreeAIDList; +static List AIDList; + +extern void ListPutItemFILO(List *me, ListItem *Item); +/*============================================================================= + * PRIVATE PROCEDURES (ANSI Prototypes) + *============================================================================= + */ + +/*============================================================================= + * CODED PROCEDURES + *============================================================================= + */ + +/* + *Function Name:InitAidList + * + *Parameters: + * + *Description: + * + *Returns: + * + */ +void InitAidList(void) +{ + UINT32 i; + SPIN_LOCK_INIT(&idLock); + + ListInit(&FreeAIDList); + ListInit(&AIDList); + for (i = 0; i < MAX_AID; i++) + { + AidList[i].nxt = NULL; + AidList[i].prv = NULL; + AidList[i].Id = MAX_AID - i; + ListPutItemFILO(&FreeAIDList, (ListItem*)(AidList+i)); + } +} + +/* + *Function Name:AssignAid + * + *Parameters: + * + *Description: + * + *Returns: + * + */ +UINT32 AssignAid(void) +{ + ListItem *tmp; + IdListElem_t *tmp1; + unsigned long idflags; + SPIN_LOCK_IRQSAVE(&idLock, idflags); + tmp = ListGetItem(&FreeAIDList); + if (tmp) + { + tmp1 = (IdListElem_t *)tmp; + ListPutItemFILO(&AIDList,tmp); + AssocStationsCnt++; + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); + return tmp1->Id; + } + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); + return 0; /* List is empty */ +} + +/* + *Function Name:FreeAid + * + *Parameters: + * + *Description: + * + *Returns: + * + */ + +void FreeAid(UINT32 Aid) +{ + ListItem *search; + IdListElem_t *search1; + unsigned long idflags; + SPIN_LOCK_IRQSAVE(&idLock, idflags); + search = AIDList.head; + while (search) + { + search1 = (IdListElem_t *)search; + if ((search1->Id == Aid)) + { + ListPutItemFILO(&FreeAIDList,ListRmvItem(&AIDList,search)); + AssocStationsCnt--; + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); + return ; + } + search = search->nxt; + } + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); +} +Status_e ResetAid(UINT16 StnId, UINT16 Aid) +{ + return FAIL; +} +/* + *Function Name:InitStnId + * + *Parameters: + * + *Description: + * + *Returns: + * + */ + +WL_STATUS InitStnIdList(int max_stns) +{ + UINT32 i; + ListInit(&FreeStaIdList); + ListInit(&StaIdList); + if (StnIdList == NULL) + { + StnIdList = malloc((max_stns + 1)*sizeof(IdListElem_t)); + if (StnIdList == NULL) + return (OS_FAIL); + memset(StnIdList, 0, (max_stns + 1)*sizeof(IdListElem_t)); + } + for (i = 0; i < max_stns; i++) + { + StnIdList[i].nxt = NULL; + StnIdList[i].prv = NULL; + StnIdList[i].Id = max_stns - i; + ListPutItemFILO(&FreeStaIdList, (ListItem*)(StnIdList+i)); + } + return(OS_SUCCESS); +} + +void StnIdListCleanup(void) +{ + if (StnIdList){ + free(StnIdList); + StnIdList = 0; + } +} + +/* + *Function Name:AssignStnId + * + *Parameters: + * + *Description: + * + *Returns: + * + */ + +UINT32 AssignStnId(void) +{ + ListItem *tmp; + IdListElem_t *tmp1; + unsigned long idflags; + SPIN_LOCK_IRQSAVE(&idLock, idflags); + tmp = ListGetItem(&FreeStaIdList); + if (tmp) + { + tmp1 = (IdListElem_t *)tmp; + ListPutItemFILO(&StaIdList,tmp); + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); + return tmp1->Id; + } + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); + return 0; /* List is empty */ +} + +/* + *Function Name:FreeStnId + * + *Parameters: + * + *Description: + * + *Returns: + * + */ + +void FreeStnId(UINT32 StnId) +{ + ListItem *search; + IdListElem_t *search1; + unsigned long idflags; + SPIN_LOCK_IRQSAVE(&idLock, idflags); + + search = StaIdList.head; + while (search) + { + search1 = (IdListElem_t *)search; + if ((search1->Id == StnId)) + { + ListPutItemFILO(&FreeStaIdList,ListRmvItem(&StaIdList,search)); + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); + return ; + } + search = search->nxt; + } + SPIN_UNLOCK_IRQRESTORE(&idLock, idflags); +} + diff --git a/pool/shard006/C/0119411_mt.c b/pool/shard006/C/0119411_mt.c new file mode 100644 index 0000000000000000000000000000000000000000..0a426328e6672aede428ccb751b1cc900db97de7 --- /dev/null +++ b/pool/shard006/C/0119411_mt.c @@ -0,0 +1,47 @@ +/* Mersenne twister implementation from Michael Brundage. Public Domain. + MT is a very fast pseudo random number generator. This version works + on 32bit words. Changes by AK. */ +#include +#include "mt.h" + +int mt_index; +unsigned int mt_buffer[MT_LEN]; + +void mt_init(void) +{ + int i; + srand(1); + for (i = 0; i < MT_LEN; i++) + mt_buffer[i] = rand(); + mt_index = 0; +} + +#define MT_IA 397 +#define MT_IB (MT_LEN - MT_IA) +#define UPPER_MASK 0x80000000 +#define LOWER_MASK 0x7FFFFFFF +#define MATRIX_A 0x9908B0DF +#define TWIST(b,i,j) ((b)[i] & UPPER_MASK) | ((b)[j] & LOWER_MASK) +#define MAGIC(s) (((s)&1)*MATRIX_A) + +void mt_refill(void) +{ + int i; + unsigned int s; + unsigned int * b = mt_buffer; + + mt_index = 0; + i = 0; + for (; i < MT_IB; i++) { + s = TWIST(b, i, i+1); + b[i] = b[i + MT_IA] ^ (s >> 1) ^ MAGIC(s); + } + for (; i < MT_LEN-1; i++) { + s = TWIST(b, i, i+1); + b[i] = b[i - MT_IB] ^ (s >> 1) ^ MAGIC(s); + } + + s = TWIST(b, MT_LEN-1, 0); + b[MT_LEN-1] = b[MT_IA-1] ^ (s >> 1) ^ MAGIC(s); +} + diff --git a/pool/shard006/C/0119413_cat.c b/pool/shard006/C/0119413_cat.c new file mode 100644 index 0000000000000000000000000000000000000000..ba6935a48cc5a830147278177f264dad02d7a598 --- /dev/null +++ b/pool/shard006/C/0119413_cat.c @@ -0,0 +1,34 @@ +#include + +int main(int argc, char *argv[]) +{ + FILE *fp; + int ret; + + if (argv[1] == NULL) { + printf("please input src file\n"); + return -1; + } + + fp = fopen(argv[1], "r"); + + if (fp == NULL) { + printf("open file %s failure\n", argv[1]); + return -2; + } + + while (1) { + + ret = fgetc(fp); // 放在feof判断前, 否则输出结尾出现乱码 + + if (feof(fp)) { + break; + } + + fputc(ret, stdout); + } + + fclose(fp); + + return 0; +} diff --git a/pool/shard006/C/0119414_ssp.c b/pool/shard006/C/0119414_ssp.c new file mode 100644 index 0000000000000000000000000000000000000000..93096befd0173a3ed767f1c48550dcedc0b66fa3 --- /dev/null +++ b/pool/shard006/C/0119414_ssp.c @@ -0,0 +1,316 @@ +/* + * linux/arch/arm/mach-pxa/ssp.c + * + * based on linux/arch/arm/mach-sa1100/ssp.c by Russell King + * + * Copyright (C) 2003 Russell King. + * Copyright (C) 2003 Wolfson Microelectronics PLC + * + * 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. + * + * PXA2xx SSP driver. This provides the generic core for simple + * IO-based SSP applications and allows easy port setup for DMA access. + * + * Author: Liam Girdwood + * + * Revision history: + * 22nd Aug 2003 Initial version. + * 20th Dec 2004 Added ssp_config for changing port config without + * closing the port. + * 4th Aug 2005 Added option to disable irq handler registration and + * cleaned up irq and clock detection. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PXA_SSP_PORTS 3 + +struct ssp_info_ { + int irq; + u32 clock; +}; + +/* + * SSP port clock and IRQ settings + */ +static const struct ssp_info_ ssp_info[PXA_SSP_PORTS] = { +#if defined (CONFIG_PXA27x) + {IRQ_SSP, CKEN23_SSP1}, + {IRQ_SSP2, CKEN3_SSP2}, + {IRQ_SSP3, CKEN4_SSP3}, +#else + {IRQ_SSP, CKEN3_SSP}, + {IRQ_NSSP, CKEN9_NSSP}, + {IRQ_ASSP, CKEN10_ASSP}, +#endif +}; + +static DEFINE_MUTEX(mutex); +static int use_count[PXA_SSP_PORTS] = {0, 0, 0}; + +static irqreturn_t ssp_interrupt(int irq, void *dev_id, struct pt_regs *regs) +{ + struct ssp_dev *dev = (struct ssp_dev*) dev_id; + unsigned int status = SSSR_P(dev->port); + + SSSR_P(dev->port) = status; /* clear status bits */ + + if (status & SSSR_ROR) + printk(KERN_WARNING "SSP(%d): receiver overrun\n", dev->port); + + if (status & SSSR_TUR) + printk(KERN_WARNING "SSP(%d): transmitter underrun\n", dev->port); + + if (status & SSSR_BCE) + printk(KERN_WARNING "SSP(%d): bit count error\n", dev->port); + + return IRQ_HANDLED; +} + +/** + * ssp_write_word - write a word to the SSP port + * @data: 32-bit, MSB justified data to write. + * + * Wait for a free entry in the SSP transmit FIFO, and write a data + * word to the SSP port. + * + * The caller is expected to perform the necessary locking. + * + * Returns: + * %-ETIMEDOUT timeout occurred (for future) + * 0 success + */ +int ssp_write_word(struct ssp_dev *dev, u32 data) +{ + while (!(SSSR_P(dev->port) & SSSR_TNF)) + cpu_relax(); + + SSDR_P(dev->port) = data; + + return 0; +} + +/** + * ssp_read_word - read a word from the SSP port + * + * Wait for a data word in the SSP receive FIFO, and return the + * received data. Data is LSB justified. + * + * Note: Currently, if data is not expected to be received, this + * function will wait for ever. + * + * The caller is expected to perform the necessary locking. + * + * Returns: + * %-ETIMEDOUT timeout occurred (for future) + * 32-bit data success + */ +int ssp_read_word(struct ssp_dev *dev) +{ + while (!(SSSR_P(dev->port) & SSSR_RNE)) + cpu_relax(); + + return SSDR_P(dev->port); +} + +/** + * ssp_flush - flush the transmit and receive FIFOs + * + * Wait for the SSP to idle, and ensure that the receive FIFO + * is empty. + * + * The caller is expected to perform the necessary locking. + */ +void ssp_flush(struct ssp_dev *dev) +{ + do { + while (SSSR_P(dev->port) & SSSR_RNE) { + (void) SSDR_P(dev->port); + } + } while (SSSR_P(dev->port) & SSSR_BSY); +} + +/** + * ssp_enable - enable the SSP port + * + * Turn on the SSP port. + */ +void ssp_enable(struct ssp_dev *dev) +{ + SSCR0_P(dev->port) |= SSCR0_SSE; +} + +/** + * ssp_disable - shut down the SSP port + * + * Turn off the SSP port, optionally powering it down. + */ +void ssp_disable(struct ssp_dev *dev) +{ + SSCR0_P(dev->port) &= ~SSCR0_SSE; +} + +/** + * ssp_save_state - save the SSP configuration + * @ssp: pointer to structure to save SSP configuration + * + * Save the configured SSP state for suspend. + */ +void ssp_save_state(struct ssp_dev *dev, struct ssp_state *ssp) +{ + ssp->cr0 = SSCR0_P(dev->port); + ssp->cr1 = SSCR1_P(dev->port); + ssp->to = SSTO_P(dev->port); + ssp->psp = SSPSP_P(dev->port); + + SSCR0_P(dev->port) &= ~SSCR0_SSE; +} + +/** + * ssp_restore_state - restore a previously saved SSP configuration + * @ssp: pointer to configuration saved by ssp_save_state + * + * Restore the SSP configuration saved previously by ssp_save_state. + */ +void ssp_restore_state(struct ssp_dev *dev, struct ssp_state *ssp) +{ + SSSR_P(dev->port) = SSSR_ROR | SSSR_TUR | SSSR_BCE; + + SSCR0_P(dev->port) = ssp->cr0 & ~SSCR0_SSE; + SSCR1_P(dev->port) = ssp->cr1; + SSTO_P(dev->port) = ssp->to; + SSPSP_P(dev->port) = ssp->psp; + + SSCR0_P(dev->port) = ssp->cr0; +} + +/** + * ssp_config - configure SSP port settings + * @mode: port operating mode + * @flags: port config flags + * @psp_flags: port PSP config flags + * @speed: port speed + * + * Port MUST be disabled by ssp_disable before making any config changes. + */ +int ssp_config(struct ssp_dev *dev, u32 mode, u32 flags, u32 psp_flags, u32 speed) +{ + dev->mode = mode; + dev->flags = flags; + dev->psp_flags = psp_flags; + dev->speed = speed; + + /* set up port type, speed, port settings */ + SSCR0_P(dev->port) = (dev->speed | dev->mode); + SSCR1_P(dev->port) = dev->flags; + SSPSP_P(dev->port) = dev->psp_flags; + + return 0; +} + +/** + * ssp_init - setup the SSP port + * + * initialise and claim resources for the SSP port. + * + * Returns: + * %-ENODEV if the SSP port is unavailable + * %-EBUSY if the resources are already in use + * %0 on success + */ +int ssp_init(struct ssp_dev *dev, u32 port, u32 init_flags) +{ + int ret; + + if (port > PXA_SSP_PORTS || port == 0) + return -ENODEV; + + mutex_lock(&mutex); + if (use_count[port - 1]) { + mutex_unlock(&mutex); + return -EBUSY; + } + use_count[port - 1]++; + + if (!request_mem_region(__PREG(SSCR0_P(port)), 0x2c, "SSP")) { + use_count[port - 1]--; + mutex_unlock(&mutex); + return -EBUSY; + } + dev->port = port; + + /* do we need to get irq */ + if (!(init_flags & SSP_NO_IRQ)) { + ret = request_irq(ssp_info[port-1].irq, ssp_interrupt, + 0, "SSP", dev); + if (ret) + goto out_region; + dev->irq = ssp_info[port-1].irq; + } else + dev->irq = 0; + + /* turn on SSP port clock */ + pxa_set_cken(ssp_info[port-1].clock, 1); + mutex_unlock(&mutex); + return 0; + +out_region: + release_mem_region(__PREG(SSCR0_P(port)), 0x2c); + use_count[port - 1]--; + mutex_unlock(&mutex); + return ret; +} + +/** + * ssp_exit - undo the effects of ssp_init + * + * release and free resources for the SSP port. + */ +void ssp_exit(struct ssp_dev *dev) +{ + mutex_lock(&mutex); + SSCR0_P(dev->port) &= ~SSCR0_SSE; + + if (dev->port > PXA_SSP_PORTS || dev->port == 0) { + printk(KERN_WARNING "SSP: tried to close invalid port\n"); + return; + } + + pxa_set_cken(ssp_info[dev->port-1].clock, 0); + if (dev->irq) + free_irq(dev->irq, dev); + release_mem_region(__PREG(SSCR0_P(dev->port)), 0x2c); + use_count[dev->port - 1]--; + mutex_unlock(&mutex); +} + +EXPORT_SYMBOL(ssp_write_word); +EXPORT_SYMBOL(ssp_read_word); +EXPORT_SYMBOL(ssp_flush); +EXPORT_SYMBOL(ssp_enable); +EXPORT_SYMBOL(ssp_disable); +EXPORT_SYMBOL(ssp_save_state); +EXPORT_SYMBOL(ssp_restore_state); +EXPORT_SYMBOL(ssp_init); +EXPORT_SYMBOL(ssp_exit); +EXPORT_SYMBOL(ssp_config); + +MODULE_DESCRIPTION("PXA SSP driver"); +MODULE_AUTHOR("Liam Girdwood"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard006/C/0119422_expandeddatum.c b/pool/shard006/C/0119422_expandeddatum.c new file mode 100644 index 0000000000000000000000000000000000000000..bc30150dde974d7486a21ae23e5b5ab066cc0ed8 --- /dev/null +++ b/pool/shard006/C/0119422_expandeddatum.c @@ -0,0 +1,145 @@ +/*------------------------------------------------------------------------- + * + * expandeddatum.c + * Support functions for "expanded" value representations. + * + * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group + * Portions Copyright (c) 1994, Regents of the University of California + * + * + * IDENTIFICATION + * src/backend/utils/adt/expandeddatum.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#include "utils/expandeddatum.h" +#include "utils/memutils.h" + +/* + * DatumGetEOHP + * + * Given a Datum that is an expanded-object reference, extract the pointer. + * + * This is a bit tedious since the pointer may not be properly aligned; + * compare VARATT_EXTERNAL_GET_POINTER(). + */ +ExpandedObjectHeader * +DatumGetEOHP(Datum d) +{ + varattrib_1b_e *datum = (varattrib_1b_e *) DatumGetPointer(d); + varatt_expanded ptr; + + Assert(VARATT_IS_EXTERNAL_EXPANDED(datum)); + memcpy(&ptr, VARDATA_EXTERNAL(datum), sizeof(ptr)); + Assert(VARATT_IS_EXPANDED_HEADER(ptr.eohptr)); + return ptr.eohptr; +} + +/* + * EOH_init_header + * + * Initialize the common header of an expanded object. + * + * The main thing this encapsulates is initializing the TOAST pointers. + */ +void +EOH_init_header(ExpandedObjectHeader *eohptr, + const ExpandedObjectMethods *methods, + MemoryContext obj_context) +{ + varatt_expanded ptr; + + eohptr->vl_len_ = EOH_HEADER_MAGIC; + eohptr->eoh_methods = methods; + eohptr->eoh_context = obj_context; + + ptr.eohptr = eohptr; + + SET_VARTAG_EXTERNAL(eohptr->eoh_rw_ptr, VARTAG_EXPANDED_RW); + memcpy(VARDATA_EXTERNAL(eohptr->eoh_rw_ptr), &ptr, sizeof(ptr)); + + SET_VARTAG_EXTERNAL(eohptr->eoh_ro_ptr, VARTAG_EXPANDED_RO); + memcpy(VARDATA_EXTERNAL(eohptr->eoh_ro_ptr), &ptr, sizeof(ptr)); +} + +/* + * EOH_get_flat_size + * EOH_flatten_into + * + * Convenience functions for invoking the "methods" of an expanded object. + */ + +Size +EOH_get_flat_size(ExpandedObjectHeader *eohptr) +{ + return (*eohptr->eoh_methods->get_flat_size) (eohptr); +} + +void +EOH_flatten_into(ExpandedObjectHeader *eohptr, + void *result, Size allocated_size) +{ + (*eohptr->eoh_methods->flatten_into) (eohptr, result, allocated_size); +} + +/* + * If the Datum represents a R/W expanded object, change it to R/O. + * Otherwise return the original Datum. + * + * Caller must ensure that the datum is a non-null varlena value. Typically + * this is invoked via MakeExpandedObjectReadOnly(), which checks that. + */ +Datum +MakeExpandedObjectReadOnlyInternal(Datum d) +{ + ExpandedObjectHeader *eohptr; + + /* Nothing to do if not a read-write expanded-object pointer */ + if (!VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(d))) + return d; + + /* Now safe to extract the object pointer */ + eohptr = DatumGetEOHP(d); + + /* Return the built-in read-only pointer instead of given pointer */ + return EOHPGetRODatum(eohptr); +} + +/* + * Transfer ownership of an expanded object to a new parent memory context. + * The object must be referenced by a R/W pointer, and what we return is + * always its "standard" R/W pointer, which is certain to have the same + * lifespan as the object itself. (The passed-in pointer might not, and + * in any case wouldn't provide a unique identifier if it's not that one.) + */ +Datum +TransferExpandedObject(Datum d, MemoryContext new_parent) +{ + ExpandedObjectHeader *eohptr = DatumGetEOHP(d); + + /* Assert caller gave a R/W pointer */ + Assert(VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(d))); + + /* Transfer ownership */ + MemoryContextSetParent(eohptr->eoh_context, new_parent); + + /* Return the object's standard read-write pointer */ + return EOHPGetRWDatum(eohptr); +} + +/* + * Delete an expanded object (must be referenced by a R/W pointer). + */ +void +DeleteExpandedObject(Datum d) +{ + ExpandedObjectHeader *eohptr = DatumGetEOHP(d); + + /* Assert caller gave a R/W pointer */ + Assert(VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(d))); + + /* Kill it */ + MemoryContextDelete(eohptr->eoh_context); +} diff --git a/pool/shard006/C/0119426_net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder.c b/pool/shard006/C/0119426_net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder.c new file mode 100644 index 0000000000000000000000000000000000000000..5ae1eafd3b8b72663cc7aad7482257e2df46942a --- /dev/null +++ b/pool/shard006/C/0119426_net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder.c @@ -0,0 +1,58 @@ +/* + * Jitsi, the OpenSource Java VoIP and Instant Messaging client. + * + * Distributable under LGPL license. + * See terms of license at gnu.org. + */ +#include "net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder.h" + +#include +#include "telephony.h" +#include "g722.h" + +JNIEXPORT void JNICALL +Java_net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder_g722_1encoder_1close + (JNIEnv *jniEnv, jclass clazz, jlong encoder) +{ + g722_encode_state_t *e = (g722_encode_state_t *) (intptr_t) encoder; + + g722_encode_release(e); + g722_encode_free(e); +} + +JNIEXPORT jlong JNICALL +Java_net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder_g722_1encoder_1open + (JNIEnv *jniEnv, jclass clazz) +{ + return (jlong) (intptr_t) g722_encode_init(NULL, 64000, 0); +} + +JNIEXPORT void JNICALL +Java_net_java_sip_communicator_impl_neomedia_codec_audio_g722_JNIEncoder_g722_1encoder_1process + (JNIEnv *jniEnv, jclass clazz, + jlong encoder, + jbyteArray input, jint inputOffset, + jbyteArray output, jint outputOffset, jint outputLength) +{ + jbyte *outputPtr = (*jniEnv)->GetByteArrayElements(jniEnv, output, NULL); + + if (outputPtr) + { + jbyte *inputPtr + = (*jniEnv)->GetPrimitiveArrayCritical(jniEnv, input, NULL); + + if (inputPtr) + { + g722_encode( + (g722_encode_state_t *) (intptr_t) encoder, + (uint8_t *) (outputPtr + outputOffset), + (const int16_t *) (inputPtr + inputOffset), + 2 * (outputLength / sizeof(uint8_t))); + (*jniEnv)->ReleasePrimitiveArrayCritical( + jniEnv, + input, inputPtr, + JNI_ABORT); + } + (*jniEnv)->ReleaseByteArrayElements(jniEnv, output, outputPtr, 0); + } +} diff --git a/pool/shard006/C/0119436_dev.c b/pool/shard006/C/0119436_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..89cd5c65f22c3f3b4c9010a22e1f03e3ba852890 --- /dev/null +++ b/pool/shard006/C/0119436_dev.c @@ -0,0 +1,170 @@ +/* + * Generic Scope + * + * License: GNU/GPL, see COPYING + * Authors: Antti Partanen + */ + +#include +#include +#include +#include +#include +#include + +const double device_frequency = 1000.0; /* Hz */ +const long double device_intervals[] = { 0.001, 0.0001, 0.00001, 0.000001, 0.0 }; +struct device *device_first = NULL; +struct device *device_last = NULL; + + +int dev_init() +{ + return 0; +} + +void dev_quit() +{ +} + +int dev_scan(void *lib) +{ + devlib_add_device(lib, "Digital 1 kHz", "ES1111-0", DEV_TYPE_IO_READ, DEV_FORMAT_DIGITAL, 8); + devlib_add_device(lib, "Sine 1 kHz", "ES1111-1", DEV_TYPE_IO_READ, DEV_FORMAT_INT8, 1); + devlib_add_device(lib, "Sawtooth 1 kHz", "ES1111-2", DEV_TYPE_IO_READ, DEV_FORMAT_INT8, 1); + return 3; +} + +int dev_open(struct device *dev) +{ + /* "open" device */ + dev->io.timestamp = -1.0; + dev->data = malloc(sizeof(double)); + *((double *)dev->data) = 0; + return 0; +} + +int dev_close(struct device *dev) +{ + /* release resources */ + free(dev->data); + return 0; +} + +int dev_reset(struct device *dev) +{ + dev->io.timestamp = -1.0; + *((double *)dev->data) = 0; + return 0; +} + +int dev_manipulate(struct device *dev, uint8_t *data, int count, int format, int stride) +{ + int i; + + /* wait until there actually should be samples available: + * this should not be needed with real hardware as real hardware + * should feed samples in timely manner i.e. in sync + */ + do + { +#ifndef _WIN32 + /* only in linux, window has a timer that is not ACCURATE */ + os_sleep(0.000001); +#endif + } + while (dev->io.timestamp > os_time()); + + if (strcmp(dev->serial, "ES1111-0") == 0) + { + double value = *((double *)dev->data); + for (i = 0; i < count; i++) + { + int x = (int)(value * device_frequency * dev->io.interval); + if (x > 255) + { + value = 0; + x = 0; + } + *data = (uint8_t)x; + data += stride; + value += 2.0; + } + *((double *)dev->data) = value; + } + else if (strcmp(dev->serial, "ES1111-1") == 0) + { + double fraction = *((double *)dev->data); + double integral; + int8_t *samples = (int8_t *)data; + for (i = 0; i < count; i++) + { + *samples = (int8_t)(sin(2 * M_PI * fraction) * 127.0); + samples += stride; + fraction += device_frequency * dev->io.interval; + } + *((double *)dev->data) = modf(fraction, &integral); + } + else if (strcmp(dev->serial, "ES1111-2") == 0) + { + double value = *((double *)dev->data); + int8_t *samples = (int8_t *)data; + for (i = 0; i < count; i++) + { + *samples = (int8_t)((int)value - 128); + samples += stride; + value += 256.0 * device_frequency * dev->io.interval; + } + *((double *)dev->data) = value; + } + + /* update timestamp */ + if (dev->io.timestamp < 0.0) + { + /* + * normally you should only add, but this is a test device + * so it needs to start from current time to able to sync. + */ + dev->io.timestamp = os_time(); + } + else + { + dev->io.timestamp += dev->io.interval * count; + } + + return 0; +} + +void *dev_ioctl(struct device *dev, int request, va_list argv) +{ + if (request == DEV_IOCTL_GET_INTERVAL) + { + return &dev->io.interval; + } + else if (request == DEV_IOCTL_SET_INTERVAL) + { + int i; + long double interval = va_arg(argv, long double); + + /* check interval */ + for (i = 0; device_intervals[i] > 0.0; i++) + { + if (device_intervals[i] != interval) + { + continue; + } + dev->io.interval = interval; + return DEV_IOCTL_OK; + } + + return DEV_IOCTL_ERROR; + } + else if (request == DEV_IOCTL_INTERVALS) + { + return (void *)device_intervals; + } + + return DEV_IOCTL_UNKNOWN; +} + + diff --git a/pool/shard006/C/0119440_afs.c b/pool/shard006/C/0119440_afs.c new file mode 100644 index 0000000000000000000000000000000000000000..b092354da045dd422512bb09fec5c1d8063375bd --- /dev/null +++ b/pool/shard006/C/0119440_afs.c @@ -0,0 +1,283 @@ +/*====================================================================== + + drivers/mtd/afs.c: ARM Flash Layout/Partitioning + + Copyright (C) 2000 ARM Limited + + 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 + + This is access code for flashes using ARM's flash partitioning + standards. + + $Id: afs.c,v 1.1.1.1 2007-05-25 06:50:07 bruce Exp $ + +======================================================================*/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +struct footer_struct { + u32 image_info_base; /* Address of first word of ImageFooter */ + u32 image_start; /* Start of area reserved by this footer */ + u32 signature; /* 'Magic' number proves it's a footer */ + u32 type; /* Area type: ARM Image, SIB, customer */ + u32 checksum; /* Just this structure */ +}; + +struct image_info_struct { + u32 bootFlags; /* Boot flags, compression etc. */ + u32 imageNumber; /* Unique number, selects for boot etc. */ + u32 loadAddress; /* Address program should be loaded to */ + u32 length; /* Actual size of image */ + u32 address; /* Image is executed from here */ + char name[16]; /* Null terminated */ + u32 headerBase; /* Flash Address of any stripped header */ + u32 header_length; /* Length of header in memory */ + u32 headerType; /* AIF, RLF, s-record etc. */ + u32 checksum; /* Image checksum (inc. this struct) */ +}; + +static u32 word_sum(void *words, int num) +{ + u32 *p = words; + u32 sum = 0; + + while (num--) + sum += *p++; + + return sum; +} + +static int +afs_read_footer(struct mtd_info *mtd, u_int *img_start, u_int *iis_start, + u_int off, u_int mask) +{ + struct footer_struct fs; + u_int ptr = off + mtd->erasesize - sizeof(fs); + size_t sz; + int ret; + + ret = mtd->read(mtd, ptr, sizeof(fs), &sz, (u_char *) &fs); + if (ret >= 0 && sz != sizeof(fs)) + ret = -EINVAL; + + if (ret < 0) { + printk(KERN_ERR "AFS: mtd read failed at 0x%x: %d\n", + ptr, ret); + return ret; + } + + ret = 1; + + /* + * Does it contain the magic number? + */ + if (fs.signature != 0xa0ffff9f) + ret = 0; + + /* + * Check the checksum. + */ + if (word_sum(&fs, sizeof(fs) / sizeof(u32)) != 0xffffffff) + ret = 0; + + /* + * Don't touch the SIB. + */ + if (fs.type == 2) + ret = 0; + + *iis_start = fs.image_info_base & mask; + *img_start = fs.image_start & mask; + + /* + * Check the image info base. This can not + * be located after the footer structure. + */ + if (*iis_start >= ptr) + ret = 0; + + /* + * Check the start of this image. The image + * data can not be located after this block. + */ + if (*img_start > off) + ret = 0; + + return ret; +} + +static int +afs_read_iis(struct mtd_info *mtd, struct image_info_struct *iis, u_int ptr) +{ + size_t sz; + int ret, i; + + memset(iis, 0, sizeof(*iis)); + ret = mtd->read(mtd, ptr, sizeof(*iis), &sz, (u_char *) iis); + if (ret < 0) + goto failed; + + if (sz != sizeof(*iis)) { + ret = -EINVAL; + goto failed; + } + + ret = 0; + + /* + * Validate the name - it must be NUL terminated. + */ + for (i = 0; i < sizeof(iis->name); i++) + if (iis->name[i] == '\0') + break; + + if (i < sizeof(iis->name)) + ret = 1; + + return ret; + + failed: + printk(KERN_ERR "AFS: mtd read failed at 0x%x: %d\n", + ptr, ret); + return ret; +} + +static int parse_afs_partitions(struct mtd_info *mtd, + struct mtd_partition **pparts, + unsigned long origin) +{ + struct mtd_partition *parts; + u_int mask, off, idx, sz; + int ret = 0; + char *str; + + /* + * This is the address mask; we use this to mask off out of + * range address bits. + */ + mask = mtd->size - 1; + + /* + * First, calculate the size of the array we need for the + * partition information. We include in this the size of + * the strings. + */ + for (idx = off = sz = 0; off < mtd->size; off += mtd->erasesize) { + struct image_info_struct iis; + u_int iis_ptr, img_ptr; + + ret = afs_read_footer(mtd, &img_ptr, &iis_ptr, off, mask); + if (ret < 0) + break; + if (ret == 0) + continue; + + ret = afs_read_iis(mtd, &iis, iis_ptr); + if (ret < 0) + break; + if (ret == 0) + continue; + + sz += sizeof(struct mtd_partition); + sz += strlen(iis.name) + 1; + idx += 1; + } + + if (!sz) + return ret; + + parts = kzalloc(sz, GFP_KERNEL); + if (!parts) + return -ENOMEM; + + str = (char *)(parts + idx); + + /* + * Identify the partitions + */ + for (idx = off = 0; off < mtd->size; off += mtd->erasesize) { + struct image_info_struct iis; + u_int iis_ptr, img_ptr; + + /* Read the footer. */ + ret = afs_read_footer(mtd, &img_ptr, &iis_ptr, off, mask); + if (ret < 0) + break; + if (ret == 0) + continue; + + /* Read the image info block */ + ret = afs_read_iis(mtd, &iis, iis_ptr); + if (ret < 0) + break; + if (ret == 0) + continue; + + strcpy(str, iis.name); + + parts[idx].name = str; + parts[idx].size = (iis.length + mtd->erasesize - 1) & ~(mtd->erasesize - 1); + parts[idx].offset = img_ptr; + parts[idx].mask_flags = 0; + + printk(" mtd%d: at 0x%08x, %5dKB, %8u, %s\n", + idx, img_ptr, parts[idx].size / 1024, + iis.imageNumber, str); + + idx += 1; + str = str + strlen(iis.name) + 1; + } + + if (!idx) { + kfree(parts); + parts = NULL; + } + + *pparts = parts; + return idx ? idx : ret; +} + +static struct mtd_part_parser afs_parser = { + .owner = THIS_MODULE, + .parse_fn = parse_afs_partitions, + .name = "afs", +}; + +static int __init afs_parser_init(void) +{ + return register_mtd_parser(&afs_parser); +} + +static void __exit afs_parser_exit(void) +{ + deregister_mtd_parser(&afs_parser); +} + +module_init(afs_parser_init); +module_exit(afs_parser_exit); + + +MODULE_AUTHOR("ARM Ltd"); +MODULE_DESCRIPTION("ARM Firmware Suite partition parser"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0119444_testSerial.c b/pool/shard006/C/0119444_testSerial.c new file mode 100644 index 0000000000000000000000000000000000000000..f18506c1a612e0186d2ed30e765ca0159194f1d6 --- /dev/null +++ b/pool/shard006/C/0119444_testSerial.c @@ -0,0 +1,63 @@ +/*------------------------------------------------------------------------- +| rxtx is a native interface to serial ports in java. +| Copyright 1997-2004 by Trent Jarvi taj@www.linux.org.uk +| +| This library is free software; you can redistribute it and/or +| modify it under the terms of the GNU Library General Public +| License as published by the Free Software Foundation; either +| version 2 of the License, or (at your option) any later version. +| +| 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 +| Library General Public License for more details. +| +| You should have received a copy of the GNU Library General Public +| License along with this library; if not, write to the Free +| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +--------------------------------------------------------------------------*/ +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + int i, fd ; + struct termios ttyset; + + if (argc < 1 ) + { + printf("usage ./testSerial /dev/ttyS0\n"); + exit(1); + } + fd = open (argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK ); + + // wait for minicom/rxtx to start and user to press a key + // You can set up the port in minicom/rxtx now. Dont + // exit minicom until you have hit a key to continue. + + fgetc(stdin); + + // get the attributes. + + tcgetattr( fd, &ttyset ); + + /* print the attributes */ + + fprintf(stderr, "c_iflag=%#x\n", ttyset.c_iflag); + + fprintf(stderr, "c_lflag=%#x\n", ttyset.c_lflag); + fprintf(stderr, "c_oflag=%#x\n", ttyset.c_oflag); + fprintf(stderr, "c_cflag=%#x\n", ttyset.c_cflag); + fprintf(stderr, "c_cc[]: "); + for(i=0; i, 1997. + + 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 + . */ + +#include +#include +#include + +__complex__ float +__casinhf (__complex__ float x) +{ + __complex__ float res; + int rcls = fpclassify (__real__ x); + int icls = fpclassify (__imag__ x); + + if (rcls <= FP_INFINITE || icls <= FP_INFINITE) + { + if (icls == FP_INFINITE) + { + __real__ res = __copysignf (HUGE_VALF, __real__ x); + + if (rcls == FP_NAN) + __imag__ res = __nanf (""); + else + __imag__ res = __copysignf (rcls >= FP_ZERO ? M_PI_2 : M_PI_4, + __imag__ x); + } + else if (rcls <= FP_INFINITE) + { + __real__ res = __real__ x; + if ((rcls == FP_INFINITE && icls >= FP_ZERO) + || (rcls == FP_NAN && icls == FP_ZERO)) + __imag__ res = __copysignf (0.0, __imag__ x); + else + __imag__ res = __nanf (""); + } + else + { + __real__ res = __nanf (""); + __imag__ res = __nanf (""); + } + } + else if (rcls == FP_ZERO && icls == FP_ZERO) + { + res = x; + } + else + { + res = __kernel_casinhf (x, 0); + } + + return res; +} +#ifndef __casinhf +weak_alias (__casinhf, casinhf) +#endif diff --git a/pool/shard006/C/0119448_evas_soft16_polygon.c b/pool/shard006/C/0119448_evas_soft16_polygon.c new file mode 100644 index 0000000000000000000000000000000000000000..ca18bef49065fae907b9c1959335e06f5749b119 --- /dev/null +++ b/pool/shard006/C/0119448_evas_soft16_polygon.c @@ -0,0 +1,231 @@ +#include +#include +#include "evas_soft16_scanline_fill.c" + +typedef struct _RGBA_Edge RGBA_Edge; +typedef struct _RGBA_Vertex RGBA_Vertex; + +struct _RGBA_Edge +{ + float x, dx; + int i; +}; + +struct _RGBA_Vertex +{ + float x, y; + int i; +}; + +#define POLY_EDGE_DEL(_i) \ +{ \ + int _j; \ + \ + for (_j = 0; (_j < num_active_edges) && (edges[_j].i != _i); _j++); \ + if (_j < num_active_edges) \ + { \ + num_active_edges--; \ + memmove(&(edges[_j]), &(edges[_j + 1]), \ + (num_active_edges - _j) * sizeof(RGBA_Edge)); \ + } \ +} + +#define POLY_EDGE_ADD(_i, _y) \ +{ \ + int _j; \ + float _dx; \ + RGBA_Vertex *_p, *_q; \ + if (_i < (n - 1)) _j = _i + 1; \ + else _j = 0; \ + if (point[_i].y < point[_j].y) \ + { \ + _p = &(point[_i]); \ + _q = &(point[_j]); \ + } \ + else \ + { \ + _p = &(point[_j]); \ + _q = &(point[_i]); \ + } \ + edges[num_active_edges].dx = _dx = (_q->x - _p->x) / (_q->y - _p->y); \ + edges[num_active_edges].x = (_dx * ((float)_y + 0.5 - _p->y)) + _p->x; \ + edges[num_active_edges].i = _i; \ + num_active_edges++; \ +} + +static int +polygon_point_sorter(const void *a, const void *b) +{ + RGBA_Vertex *p, *q; + + p = (RGBA_Vertex *)a; + q = (RGBA_Vertex *)b; + if (p->y <= q->y) return -1; + return 1; +} + +static int +polygon_edge_sorter(const void *a, const void *b) +{ + RGBA_Edge *p, *q; + + p = (RGBA_Edge *)a; + q = (RGBA_Edge *)b; + if (p->x <= q->x) return -1; + return 1; +} + +void +evas_common_soft16_polygon_draw(Soft16_Image *dst, RGBA_Draw_Context *dc, RGBA_Polygon_Point *points, int x, int y) +{ + RGBA_Polygon_Point *pt; + RGBA_Vertex *point; + RGBA_Edge *edges; + int num_active_edges; + int n; + int i, j, k; + int y0, y1, yi; + int ext_x, ext_y, ext_w, ext_h; + int *sorted_index; + DATA8 alpha; + DATA16 rgb565; + DATA32 rgb565_unpack; + + alpha = A_VAL(&dc->col.col) >> 3; + if (alpha == 0) + return; + alpha++; + + rgb565 = RGB_565_FROM_COMPONENTS(R_VAL(&dc->col.col), + G_VAL(&dc->col.col), + B_VAL(&dc->col.col)); + rgb565_unpack = RGB_565_UNPACK(rgb565); + + ext_x = 0; + ext_y = 0; + ext_w = dst->cache_entry.w; + ext_h = dst->cache_entry.h; + if (dc->clip.use) + RECTS_CLIP_TO_RECT(ext_x, ext_y, ext_w, ext_h, + dc->clip.x, dc->clip.y, dc->clip.w, dc->clip.h); + + if ((ext_w <= 0) || (ext_h <= 0)) + return; + + n = 0; + EINA_INLIST_FOREACH(points, pt) n++; + + if (n < 3) + return; + + edges = malloc(sizeof(RGBA_Edge) * n); + if (!edges) + return; + + point = malloc(sizeof(RGBA_Vertex) * n); + if (!point) + { + free(edges); + return; + } + + sorted_index = malloc(sizeof(int) * n); + if (!sorted_index) + { + free(edges); + free(point); + return; + } + + k = 0; + EINA_INLIST_FOREACH(points, pt) + { + point[k].x = pt->x + x; + point[k].y = pt->y + y; + point[k].i = k; + k++; + } + qsort(point, n, sizeof(RGBA_Vertex), polygon_point_sorter); + + for (k = 0; k < n; k++) + sorted_index[k] = point[k].i; + + k = 0; + EINA_INLIST_FOREACH(points, pt) + { + point[k].x = pt->x + x; + point[k].y = pt->y + y; + point[k].i = k; + k++; + } + + y0 = MAX(ext_y, ceil(point[sorted_index[0]].y - 0.5)); + y1 = MIN(ext_y + ext_h - 1, floor(point[sorted_index[n - 1]].y - 0.5)); + + k = 0; + num_active_edges = 0; + + for (yi = y0; yi <= y1; yi++) + { + for (; (k < n) && (point[sorted_index[k]].y <= ((float)yi + 0.5)); k++) + { + i = sorted_index[k]; + + if (i > 0) j = i - 1; + else j = n - 1; + if (point[j].y <= ((float)yi - 0.5)) + { + POLY_EDGE_DEL(j) + } + else if (point[j].y > ((float)yi + 0.5)) + { + POLY_EDGE_ADD(j, yi) + } + if (i < (n - 1)) j = i + 1; + else j = 0; + if (point[j].y <= ((float)yi - 0.5)) + { + POLY_EDGE_DEL(i) + } + else if (point[j].y > ((float)yi + 0.5)) + { + POLY_EDGE_ADD(i, yi) + } + } + + qsort(edges, num_active_edges, sizeof(RGBA_Edge), polygon_edge_sorter); + + for (j = 0; j < num_active_edges; j += 2) + { + int x0, x1; + + x0 = ceil(edges[j].x - 0.5); + if (j < (num_active_edges - 1)) + x1 = floor(edges[j + 1].x - 0.5); + else + x1 = x0; + if ((x1 >= ext_x) && (x0 < (ext_x + ext_w)) && (x0 <= x1)) + { + DATA16 *dst_itr; + int w; + + if (x0 < ext_x) x0 = ext_x; + if (x1 >= (ext_x + ext_w)) x1 = ext_x + ext_w - 1; + + w = (x1 - x0) + 1; + dst_itr = dst->pixels + (yi * dst->stride) + x0; + + if (alpha == 32) + _soft16_scanline_fill_solid_solid(dst_itr, w, rgb565); + else + _soft16_scanline_fill_transp_solid(dst_itr, w, rgb565_unpack, alpha); + } + edges[j].x += edges[j].dx; + edges[j + 1].x += edges[j + 1].dx; + } + } + + free(edges); + free(point); + free(sorted_index); +} diff --git a/pool/shard006/C/0119449_dumpkeys.c b/pool/shard006/C/0119449_dumpkeys.c new file mode 100644 index 0000000000000000000000000000000000000000..736ca35e6015f2fb23e4b57f8963edad7ab29840 --- /dev/null +++ b/pool/shard006/C/0119449_dumpkeys.c @@ -0,0 +1,196 @@ +/* + * dumpkeys.c + * + * derived from version 0.81 - aeb@cwi.nl + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ksyms.h" +#include "getfd.h" +#include "modifiers.h" +#include "nls.h" +#include "version.h" + +static int fd; + +static void __attribute__ ((noreturn)) +usage(void) { + fprintf(stderr, _("dumpkeys version %s"), PACKAGE_VERSION); + fprintf(stderr, _("\ +\n\ +usage: dumpkeys [options...]\n\ +\n\ +valid options are:\n\ +\n\ + -h --help display this help text\n\ + -i --short-info display information about keyboard driver\n\ + -l --long-info display above and symbols known to loadkeys\n\ + -n --numeric display keytable in hexadecimal notation\n\ + -f --full-table don't use short-hand notations, one row per keycode\n\ + -1 --separate-lines one line per (modifier,keycode) pair\n\ + --funcs-only display only the function key strings\n\ + --keys-only display only key bindings\n\ + --compose-only display only compose key combinations\n\ + -c --charset=")); + lk_list_charsets(stderr); + fprintf(stderr, _("\ + interpret character action codes to be from the\n\ + specified character set\n\ +")); + exit(1); +} + +int +main (int argc, char *argv[]) { + const char *short_opts = "hilvsnf1tkdS:c:V"; + const struct option long_opts[] = { + { "help", no_argument, NULL, 'h' }, + { "short-info", no_argument, NULL, 'i' }, + { "long-info", no_argument, NULL, 'l' }, + { "numeric", no_argument, NULL, 'n' }, + { "full-table", no_argument, NULL, 'f' }, + { "separate-lines",no_argument, NULL, '1' }, + { "shape", required_argument, NULL, 'S' }, + { "funcs-only", no_argument, NULL, 't' }, + { "keys-only", no_argument, NULL, 'k' }, + { "compose-only",no_argument, NULL, 'd' }, + { "charset", required_argument, NULL, 'c' }, + { "verbose", no_argument, NULL, 'v' }, + { "version", no_argument, NULL, 'V' }, + { NULL, 0, NULL, 0 } + }; + int c, rc; + int kbd_mode; + + char long_info = 0; + char short_info = 0; + char numeric = 0; + lk_table_shape table = LK_SHAPE_DEFAULT; + char funcs_only = 0; + char keys_only = 0; + char diac_only = 0; + + struct lk_ctx *ctx; + + set_progname(argv[0]); + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE_NAME, LOCALEDIR); + textdomain(PACKAGE_NAME); + + ctx = lk_init(); + if (!ctx) { + exit(EXIT_FAILURE); + } + + while ((c = getopt_long(argc, argv, + short_opts, long_opts, NULL)) != -1) { + switch (c) { + case 'i': + short_info = 1; + break; + case 's': + case 'l': + long_info = 1; + break; + case 'n': + numeric = 1; + break; + case 'f': + table = LK_SHAPE_FULL_TABLE; + break; + case '1': + table = LK_SHAPE_SEPARATE_LINES; + break; + case 'S': + table = atoi(optarg); + break; + case 't': + funcs_only = 1; + break; + case 'k': + keys_only = 1; + break; + case 'd': + diac_only = 1; + break; + case 'v': + lk_set_log_priority(ctx, LOG_INFO); + break; + case 'c': + if ((lk_set_charset(ctx, optarg)) != 0) { + fprintf(stderr, _("unknown charset %s - ignoring charset request\n"), + optarg); + usage(); + } + printf("charset \"%s\"\n", optarg); + break; + case 'V': + print_version_and_exit(); + case 'h': + case '?': + usage(); + } + } + + if (optind < argc) + usage(); + + fd = getfd(NULL); + + /* check whether the keyboard is in Unicode mode */ + if (ioctl(fd, KDGKBMODE, &kbd_mode)) { + fprintf(stderr, _("%s: error reading keyboard mode: %m\n"), + progname); + exit(EXIT_FAILURE); + } + + if (kbd_mode == K_UNICODE) { + lk_set_parser_flags(ctx, LK_FLAG_PREFER_UNICODE); + } + + if ((rc = lk_kernel_keymap(ctx, fd)) < 0) + goto fail; + + if (short_info || long_info) { + lk_dump_summary(ctx, stdout, fd); + + if (long_info) { + printf(_("Symbols recognized by %s:\n(numeric value, symbol)\n\n"), + progname); + lk_dump_symbols(ctx, stdout); + } + exit(EXIT_SUCCESS); + } + +#ifdef KDGKBDIACR + if (!diac_only) { +#endif + if (!funcs_only) { + lk_dump_keymap(ctx, stdout, table, numeric); + } +#ifdef KDGKBDIACR + } + + if (!funcs_only && !keys_only) + lk_dump_diacs(ctx, stdout); +#endif + + fail: lk_free(ctx); + close(fd); + + if (rc < 0) + exit(EXIT_FAILURE); + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard006/C/0119452_clipboard.c b/pool/shard006/C/0119452_clipboard.c new file mode 100644 index 0000000000000000000000000000000000000000..d7831433235f023bb28e3cac7a650b77ec24ea81 --- /dev/null +++ b/pool/shard006/C/0119452_clipboard.c @@ -0,0 +1,258 @@ +/* + * gretl -- Gnu Regression, Econometrics and Time-series Library + * Copyright (C) 2001 Allin Cottrell and Riccardo "Jack" Lucchetti + * + * 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 . + * + */ + +#include +#include + +#define CLIPDEBUG 0 + +static gchar *clipboard_buf; + +GtkTargetEntry text_targets[] = { + { "UTF8_STRING", 0, TARGET_UTF8_STRING }, + { "STRING", 0, TARGET_STRING }, + { "TEXT", 0, TARGET_TEXT }, + { "COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT } +}; + +GtkTargetEntry rtf_targets[] = { + { "application/rtf", 0, TARGET_RTF }, + { "application/x-rtf", 0, TARGET_RTF }, + { "text/rtf", 0, TARGET_RTF }, + { "text/richtext", 0, TARGET_RTF }, + { "STRING", 0, TARGET_STRING }, + { "TEXT", 0, TARGET_TEXT } +}; + +static int n_text = sizeof text_targets / sizeof text_targets[0]; +static int n_rtf = sizeof rtf_targets / sizeof rtf_targets[0]; + +static void gretl_clipboard_set (int copycode); + +static void gretl_clipboard_free (void) +{ + free(clipboard_buf); + clipboard_buf = NULL; +} + +int buf_to_clipboard (const char *buf) +{ + int err = 0; + + if (buf == NULL || *buf == '\0') { + return 0; + } + + gretl_clipboard_free(); + clipboard_buf = gretl_strdup(buf); + if (clipboard_buf == NULL) { + err = 1; + } else { + gretl_clipboard_set(GRETL_FORMAT_TXT); + } + + return err; +} + +#if CLIPDEBUG + +static const char *fmt_label (int f) +{ + if (f == TARGET_UTF8_STRING) { + return "TARGET_UTF8_STRING"; + } else if (f == TARGET_STRING) { + return "TARGET_STRING"; + } else if (f == TARGET_TEXT) { + return "TARGET_STRING"; + } else if (f == TARGET_COMPOUND_TEXT) { + return "TARGET_COMPOUND_STRING"; + } else if (f == TARGET_RTF) { + return "TARGET_RTF"; + } else { + return "unknown"; + } +} + +#endif + +static void gretl_clipboard_get (GtkClipboard *clip, + GtkSelectionData *selection_data, + guint info, + gpointer p) +{ + gchar *str = clipboard_buf; /* global */ + +#if CLIPDEBUG + fprintf(stderr, "gretl_clipboard_get: info = %d (%s)\n", + (int) info, fmt_label(info)); +#endif + + if (str == NULL || *str == '\0') { + return; + } + + if (info != TARGET_UTF8_STRING) { + /* remove any Unicode minuses */ + strip_unicode_minus(str); + } + + if (info == TARGET_RTF) { + gtk_selection_data_set(selection_data, + GDK_SELECTION_TYPE_STRING, + 8, (guchar *) str, + strlen(str)); + } else { + gtk_selection_data_set_text(selection_data, str, -1); + } +} + +static void gretl_clipboard_clear (GtkClipboard *clip, gpointer p) +{ + gretl_clipboard_free(); +} + +#ifdef OS_OSX + +static void pasteboard_set (int fmt) +{ + FILE *fp = popen("/usr/bin/pbcopy", "w"); + + if (fp == NULL) { + errbox("Couldn't open pbcopy"); + } else { + fputs(clipboard_buf, fp); + pclose(fp); + } +} + +#endif + +static void gretl_clipboard_set (int fmt) +{ + static GtkClipboard *clip; + GtkTargetEntry *targs; + gint n_targs; + +#ifdef OS_OSX + if (fmt == GRETL_FORMAT_RTF || fmt == GRETL_FORMAT_RTF_TXT) { + pasteboard_set(fmt); + return; + } +#endif + + if (clip == NULL) { + clip = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); + } + + if (fmt == GRETL_FORMAT_RTF || fmt == GRETL_FORMAT_RTF_TXT) { + targs = rtf_targets; + n_targs = n_rtf; + } else { + targs = text_targets; + n_targs = n_text; + } + +#if CLIPDEBUG + fprintf(stderr, "gretl_clipboard_set: fmt = %d\n", fmt); +#endif + + if (!gtk_clipboard_set_with_owner(clip, targs, n_targs, + gretl_clipboard_get, + gretl_clipboard_clear, + G_OBJECT(mdata->main))) { + fprintf(stderr, "Failed to initialize clipboard\n"); + } +} + +/* We call this when a buffer to be copied as RTF contains + non-ASCII characters but validates as UTF-8. Note that the + UTF-8 minus sign does not recode correctly into Windows + codepages, so if it's present we have to remove it first, + then see if there's anything non-ASCII left to handle. +*/ + +static char *strip_utf8 (char *buf) +{ + strip_unicode_minus(buf); + + if (string_is_utf8((const unsigned char *) buf)) { +#if CLIPDEBUG + fprintf(stderr, "strip_utf8: stage 2, recoding\n"); +#endif + return utf8_to_cp(buf); + } else { + return buf; + } +} + +/* note: there's a Windows-specific counterpart to this + in gretlwin32.c +*/ + +int prn_to_clipboard (PRN *prn, int fmt) +{ + char *buf = gretl_print_steal_buffer(prn); + const char *cset = NULL; + gchar *trbuf = NULL; + int utf8_ok = 1; + int err = 0; + + if (buf == NULL || *buf == '\0') { + return 0; + } + + gretl_clipboard_free(); + + if (fmt == GRETL_FORMAT_RTF || fmt == GRETL_FORMAT_RTF_TXT) { + /* UTF-8 will never work in RTF */ + utf8_ok = 0; + } else if (fmt == GRETL_FORMAT_TXT && !g_get_charset(&cset)) { + utf8_ok = 0; + } + +#if CLIPDEBUG + fprintf(stderr, "prn_to_clipboard, fmt = %d, utf8_ok = %d\n", fmt, utf8_ok); +#endif + + if (!utf8_ok && string_is_utf8((const unsigned char *) buf)) { + trbuf = strip_utf8(buf); + } else { + trbuf = buf; + } + + if (fmt == GRETL_FORMAT_RTF_TXT) { + clipboard_buf = dosify_buffer(trbuf, fmt); + } else { + clipboard_buf = gretl_strdup(trbuf); + } + + if (trbuf != buf) { + g_free(trbuf); + } + + if (clipboard_buf == NULL) { + err = 1; + } else { + gretl_clipboard_set(fmt); + } + + return err; +} + + diff --git a/pool/shard006/C/0119454_action-create_file.c b/pool/shard006/C/0119454_action-create_file.c new file mode 100644 index 0000000000000000000000000000000000000000..bc6c9d38893256a2c1352f14bbae0dec2b611c3b --- /dev/null +++ b/pool/shard006/C/0119454_action-create_file.c @@ -0,0 +1,105 @@ +/** + * ${project-name} - a GNU/Linux console-based file manager + * + * Implementation of action `Create file` + * + * Copyright 2008 Sergey I. Sharybin + * Copyright 2008 Alex A. Smirnov + * + * This program can be distributed under the terms of the GNU GPL. + * See the file COPYING. + */ + +#include "actions.h" +#include "i18n.h" + +#include +#include + +/** + * Show dialog to get name of file to create + * + * @return pointer to a buffer where new file name is stored + * @sideeffect allocate memory for output value + */ +static wchar_t* +get_file_name (void) +{ + wchar_t *res = NULL; + w_window_t *wnd = widget_create_window (NULL, _(L"Create file"), 0, 0, + MIN (50, SCREEN_WIDTH * 0.8), 6, + WMS_CENTERED); + w_edit_t *edt; + + widget_create_text (NULL, WIDGET_CONTAINER (wnd), + _(L"Name of file to create:"), 1, 1); + + edt = widget_create_edit (NULL, WIDGET_CONTAINER (wnd), 1, 2, + WIDGET_POSITION (wnd).width - 2); + + action_create_ok_cancel_btns (wnd); + + if (w_window_show_modal (wnd) == MR_OK) + { + res = wcsdup (w_edit_get_text (edt)); + } + + widget_destroy (WIDGET (wnd)); + + return res; +} + +/** + * Create file with specified name + * + * @param __file_name - name of file to create + * @return non-zero if file created, zero otherwise + */ +static BOOL +create_file (const wchar_t *__file_name) +{ + int res; + vfs_file_t fd; + + ACTION_REPEAT (fd = vfs_open (__file_name, O_CREAT, &res, 0), + action_error_retrycancel, + return FALSE, + _(L"Cannot create file \"%ls\":\n%ls"), __file_name, + vfs_get_error (res)); + + vfs_close (fd); + + return TRUE; +} + +/** + * Create file operation + * + * @param __panel - descriptor of file panel where file will be created + * @return zero on success, non-zero otherwise + */ +int +action_create_file (file_panel_t *__panel) +{ + wchar_t *file_name; + + file_name = get_file_name (); + + if (file_name) + { + wchar_t *cwd = file_panel_get_full_cwd (__panel); + wchar_t *full_name = vfs_abs_path (file_name, cwd); + + create_file (full_name); + + /* Rescan panel and set cursor to created item */ + file_panel_rescan (__panel); + action_centre_to_item (__panel, full_name); + + free (file_name); + free (cwd); + free (full_name); + } + + return 0; +} diff --git a/pool/shard006/C/0119460_nouveau_dma.c b/pool/shard006/C/0119460_nouveau_dma.c new file mode 100644 index 0000000000000000000000000000000000000000..2634a1a798885229caae7b2c4353f4955fb91046 --- /dev/null +++ b/pool/shard006/C/0119460_nouveau_dma.c @@ -0,0 +1,261 @@ +/* + * Copyright (C) 2007 Ben Skeggs. + * 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 (including the + * next paragraph) shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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 "nouveau_drv.h" +#include "nouveau_dma.h" + +void +OUT_RINGp(struct nouveau_channel *chan, const void *data, unsigned nr_dwords) +{ + bool is_iomem; + u32 *mem = ttm_kmap_obj_virtual(&chan->push.buffer->kmap, &is_iomem); + mem = &mem[chan->dma.cur]; + if (is_iomem) + memcpy_toio((void __force __iomem *)mem, data, nr_dwords * 4); + else + memcpy(mem, data, nr_dwords * 4); + chan->dma.cur += nr_dwords; +} + +/* Fetch and adjust GPU GET pointer + * + * Returns: + * value >= 0, the adjusted GET pointer + * -EINVAL if GET pointer currently outside main push buffer + * -EBUSY if timeout exceeded + */ +static inline int +READ_GET(struct nouveau_channel *chan, uint64_t *prev_get, int *timeout) +{ + uint64_t val; + + val = nvif_rd32(&chan->user, chan->user_get); + if (chan->user_get_hi) + val |= (uint64_t)nvif_rd32(&chan->user, chan->user_get_hi) << 32; + + /* reset counter as long as GET is still advancing, this is + * to avoid misdetecting a GPU lockup if the GPU happens to + * just be processing an operation that takes a long time + */ + if (val != *prev_get) { + *prev_get = val; + *timeout = 0; + } + + if ((++*timeout & 0xff) == 0) { + udelay(1); + if (*timeout > 100000) + return -EBUSY; + } + + if (val < chan->push.vma.offset || + val > chan->push.vma.offset + (chan->dma.max << 2)) + return -EINVAL; + + return (val - chan->push.vma.offset) >> 2; +} + +void +nv50_dma_push(struct nouveau_channel *chan, struct nouveau_bo *bo, + int delta, int length) +{ + struct nouveau_cli *cli = (void *)chan->user.client; + struct nouveau_bo *pb = chan->push.buffer; + struct nvkm_vma *vma; + int ip = (chan->dma.ib_put * 2) + chan->dma.ib_base; + u64 offset; + + vma = nouveau_bo_vma_find(bo, cli->vm); + BUG_ON(!vma); + offset = vma->offset + delta; + + BUG_ON(chan->dma.ib_free < 1); + + nouveau_bo_wr32(pb, ip++, lower_32_bits(offset)); + nouveau_bo_wr32(pb, ip++, upper_32_bits(offset) | length << 8); + + chan->dma.ib_put = (chan->dma.ib_put + 1) & chan->dma.ib_max; + + mb(); + /* Flush writes. */ + nouveau_bo_rd32(pb, 0); + + nvif_wr32(&chan->user, 0x8c, chan->dma.ib_put); + chan->dma.ib_free--; +} + +static int +nv50_dma_push_wait(struct nouveau_channel *chan, int count) +{ + uint32_t cnt = 0, prev_get = 0; + + while (chan->dma.ib_free < count) { + uint32_t get = nvif_rd32(&chan->user, 0x88); + if (get != prev_get) { + prev_get = get; + cnt = 0; + } + + if ((++cnt & 0xff) == 0) { + DRM_UDELAY(1); + if (cnt > 100000) + return -EBUSY; + } + + chan->dma.ib_free = get - chan->dma.ib_put; + if (chan->dma.ib_free <= 0) + chan->dma.ib_free += chan->dma.ib_max; + } + + return 0; +} + +static int +nv50_dma_wait(struct nouveau_channel *chan, int slots, int count) +{ + uint64_t prev_get = 0; + int ret, cnt = 0; + + ret = nv50_dma_push_wait(chan, slots + 1); + if (unlikely(ret)) + return ret; + + while (chan->dma.free < count) { + int get = READ_GET(chan, &prev_get, &cnt); + if (unlikely(get < 0)) { + if (get == -EINVAL) + continue; + + return get; + } + + if (get <= chan->dma.cur) { + chan->dma.free = chan->dma.max - chan->dma.cur; + if (chan->dma.free >= count) + break; + + FIRE_RING(chan); + do { + get = READ_GET(chan, &prev_get, &cnt); + if (unlikely(get < 0)) { + if (get == -EINVAL) + continue; + return get; + } + } while (get == 0); + chan->dma.cur = 0; + chan->dma.put = 0; + } + + chan->dma.free = get - chan->dma.cur - 1; + } + + return 0; +} + +int +nouveau_dma_wait(struct nouveau_channel *chan, int slots, int size) +{ + uint64_t prev_get = 0; + int cnt = 0, get; + + if (chan->dma.ib_max) + return nv50_dma_wait(chan, slots, size); + + while (chan->dma.free < size) { + get = READ_GET(chan, &prev_get, &cnt); + if (unlikely(get == -EBUSY)) + return -EBUSY; + + /* loop until we have a usable GET pointer. the value + * we read from the GPU may be outside the main ring if + * PFIFO is processing a buffer called from the main ring, + * discard these values until something sensible is seen. + * + * the other case we discard GET is while the GPU is fetching + * from the SKIPS area, so the code below doesn't have to deal + * with some fun corner cases. + */ + if (unlikely(get == -EINVAL) || get < NOUVEAU_DMA_SKIPS) + continue; + + if (get <= chan->dma.cur) { + /* engine is fetching behind us, or is completely + * idle (GET == PUT) so we have free space up until + * the end of the push buffer + * + * we can only hit that path once per call due to + * looping back to the beginning of the push buffer, + * we'll hit the fetching-ahead-of-us path from that + * point on. + * + * the *one* exception to that rule is if we read + * GET==PUT, in which case the below conditional will + * always succeed and break us out of the wait loop. + */ + chan->dma.free = chan->dma.max - chan->dma.cur; + if (chan->dma.free >= size) + break; + + /* not enough space left at the end of the push buffer, + * instruct the GPU to jump back to the start right + * after processing the currently pending commands. + */ + OUT_RING(chan, chan->push.vma.offset | 0x20000000); + + /* wait for GET to depart from the skips area. + * prevents writing GET==PUT and causing a race + * condition that causes us to think the GPU is + * idle when it's not. + */ + do { + get = READ_GET(chan, &prev_get, &cnt); + if (unlikely(get == -EBUSY)) + return -EBUSY; + if (unlikely(get == -EINVAL)) + continue; + } while (get <= NOUVEAU_DMA_SKIPS); + WRITE_PUT(NOUVEAU_DMA_SKIPS); + + /* we're now submitting commands at the start of + * the push buffer. + */ + chan->dma.cur = + chan->dma.put = NOUVEAU_DMA_SKIPS; + } + + /* engine fetching ahead of us, we have space up until the + * current GET pointer. the "- 1" is to ensure there's + * space left to emit a jump back to the beginning of the + * push buffer if we require it. we can never get GET == PUT + * here, so this is safe. + */ + chan->dma.free = get - chan->dma.cur - 1; + } + + return 0; +} + diff --git a/pool/shard006/C/0119461_AudDrv_Ana.c b/pool/shard006/C/0119461_AudDrv_Ana.c new file mode 100644 index 0000000000000000000000000000000000000000..253bf79849c6c9fe1e0f048f2e650c7fd012d201 --- /dev/null +++ b/pool/shard006/C/0119461_AudDrv_Ana.c @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2007 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. + */ +/******************************************************************************* + * + * Filename: + * --------- + * AudDrv_Ana.c + * + * Project: + * -------- + * MT6583 Audio Driver ana Register setting + * + * Description: + * ------------ + * Audio register + * + * Author: + * ------- + * Chipeng Chang + * + *------------------------------------------------------------------------------ + * $Revision: #1 $ + * $Modtime:$ + * $Log:$ + * + * + *******************************************************************************/ + + +/***************************************************************************** + * C O M P I L E R F L A G S + *****************************************************************************/ + + +/***************************************************************************** + * E X T E R N A L R E F E R E N C E S + *****************************************************************************/ + +#include "AudDrv_Common.h" +#include "AudDrv_Ana.h" +#include "AudDrv_Clk.h" + +// define this to use wrapper to control +#define AUDIO_USING_WRAP_DRIVER +#ifdef AUDIO_USING_WRAP_DRIVER +#include +#endif + +/***************************************************************************** + * D A T A T Y P E S + *****************************************************************************/ + +void Ana_Set_Reg(uint32 offset, uint32 value, uint32 mask) +{ + // set pmic register or analog CONTROL_IFACE_PATH + int ret = 0; + PRINTK_ANA_REG("Ana_Set_Reg offset= 0x%x , value = 0x%x mask = 0x%x\n", offset, value, mask); +#ifdef AUDIO_USING_WRAP_DRIVER + uint32 Reg_Value = Ana_Get_Reg(offset); + Reg_Value &= (~mask); + Reg_Value |= (value & mask); + ret = pwrap_write(offset, Reg_Value); + Reg_Value = Ana_Get_Reg(offset); + if ((Reg_Value & mask) != (value & mask)) + { + printk("Ana_Set_Reg offset= 0x%x , value = 0x%x mask = 0x%x ret = %d Reg_Value = 0x%x\n", offset, value, mask, ret, Reg_Value); + } +#endif +} + +uint32 Ana_Get_Reg(uint32 offset) +{ + // get pmic register + int ret = 0; + uint32 Rdata = 0; +#ifdef AUDIO_USING_WRAP_DRIVER + ret = pwrap_read(offset, &Rdata); +#endif + //PRINTK_ANA_REG ("Ana_Get_Reg offset= 0x%x Rdata = 0x%x ret = %d\n",offset,Rdata,ret); + return Rdata; +} + +void Ana_Log_Print(void) +{ + AudDrv_ANA_Clk_On(); + + printk("SPK_CON0 = 0x%x\n", Ana_Get_Reg(SPK_CON0)); + printk("SPK_CON1 = 0x%x\n", Ana_Get_Reg(SPK_CON1)); + printk("SPK_CON2 = 0x%x\n", Ana_Get_Reg(SPK_CON2)); + printk("SPK_CON6 = 0x%x\n", Ana_Get_Reg(SPK_CON6)); + printk("SPK_CON7 = 0x%x\n", Ana_Get_Reg(SPK_CON7)); + printk("SPK_CON8 = 0x%x\n", Ana_Get_Reg(SPK_CON8)); + printk("SPK_CON9 = 0x%x\n", Ana_Get_Reg(SPK_CON9)); + printk("SPK_CON10 = 0x%x\n", Ana_Get_Reg(SPK_CON10)); + printk("SPK_CON11 = 0x%x\n", Ana_Get_Reg(SPK_CON11)); + printk("SPK_CON12 = 0x%x\n", Ana_Get_Reg(SPK_CON12)); + + printk("CID = 0x%x\n", Ana_Get_Reg(CID)); + printk("TOP_CKPDN0 = 0x%x\n", Ana_Get_Reg(TOP_CKPDN0)); + printk("TOP_CKPDN0_SET = 0x%x\n", Ana_Get_Reg(TOP_CKPDN0_SET)); + printk("TOP_CKPDN0_CLR = 0x%x\n", Ana_Get_Reg(TOP_CKPDN0_CLR)); + printk("TOP_CKPDN1 = 0x%x\n", Ana_Get_Reg(TOP_CKPDN1)); + printk("TOP_CKPDN1_SET = 0x%x\n", Ana_Get_Reg(TOP_CKPDN1_SET)); + printk("TOP_CKPDN1_CLR = 0x%x\n", Ana_Get_Reg(TOP_CKPDN1_CLR)); + printk("TOP_CKPDN2 = 0x%x\n", Ana_Get_Reg(TOP_CKPDN2)); + printk("TOP_CKPDN2_SET = 0x%x\n", Ana_Get_Reg(TOP_CKPDN2_SET)); + printk("TOP_CKPDN2_CLR = 0x%x\n", Ana_Get_Reg(TOP_CKPDN2_CLR)); + printk("TOP_CKCON1 = 0x%x\n", Ana_Get_Reg(TOP_CKCON1)); + + printk("AUDTOP_CON0 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON0)); + printk("AUDTOP_CON1 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON1)); + printk("AUDTOP_CON2 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON2)); + printk("AUDTOP_CON3 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON3)); + printk("AUDTOP_CON4 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON4)); + printk("AUDTOP_CON5 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON5)); + printk("AUDTOP_CON6 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON6)); + printk("AUDTOP_CON7 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON7)); + printk("AUDTOP_CON8 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON8)); + printk("AUDTOP_CON9 = 0x%x\n", Ana_Get_Reg(AUDTOP_CON9)); + AudDrv_ANA_Clk_Off(); + printk("-Ana_Log_Print \n"); +} + + +// export symbols for other module using +EXPORT_SYMBOL(Ana_Log_Print); +EXPORT_SYMBOL(Ana_Set_Reg); +EXPORT_SYMBOL(Ana_Get_Reg); + + diff --git a/pool/shard006/C/0119463_help-unknown-cmd.c b/pool/shard006/C/0119463_help-unknown-cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..714c65c9a5a37daf15da559c3cc719aa38c29331 --- /dev/null +++ b/pool/shard006/C/0119463_help-unknown-cmd.c @@ -0,0 +1,153 @@ +#include "cache.h" +#include "config.h" +#include +#include +#include "../builtin.h" +#include "levenshtein.h" + +static int autocorrect; +static struct cmdnames aliases; + +static int perf_unknown_cmd_config(const char *var, const char *value, + void *cb __maybe_unused) +{ + if (!strcmp(var, "help.autocorrect")) + { + autocorrect = perf_config_int(var, value); + } + + /* Also use aliases for command lookup */ + if (!prefixcmp(var, "alias.")) + { + add_cmdname(&aliases, var + 6, strlen(var + 6)); + } + + return 0; +} + +static int levenshtein_compare(const void *p1, const void *p2) +{ + const struct cmdname *const *c1 = p1, *const * c2 = p2; + const char *s1 = (*c1)->name, *s2 = (*c2)->name; + int l1 = (*c1)->len; + int l2 = (*c2)->len; + return l1 != l2 ? l1 - l2 : strcmp(s1, s2); +} + +static int add_cmd_list(struct cmdnames *cmds, struct cmdnames *old) +{ + unsigned int i, nr = cmds->cnt + old->cnt; + void *tmp; + + if (nr > cmds->alloc) + { + /* Choose bigger one to alloc */ + if (alloc_nr(cmds->alloc) < nr) + { + cmds->alloc = nr; + } + else + { + cmds->alloc = alloc_nr(cmds->alloc); + } + + tmp = realloc(cmds->names, cmds->alloc * sizeof(*cmds->names)); + + if (!tmp) + { + return -1; + } + + cmds->names = tmp; + } + + for (i = 0; i < old->cnt; i++) + { + cmds->names[cmds->cnt++] = old->names[i]; + } + + zfree(&old->names); + old->cnt = 0; + return 0; +} + +const char *help_unknown_cmd(const char *cmd) +{ + unsigned int i, n = 0, best_similarity = 0; + struct cmdnames main_cmds, other_cmds; + + memset(&main_cmds, 0, sizeof(main_cmds)); + memset(&other_cmds, 0, sizeof(main_cmds)); + memset(&aliases, 0, sizeof(aliases)); + + perf_config(perf_unknown_cmd_config, NULL); + + load_command_list("perf-", &main_cmds, &other_cmds); + + if (add_cmd_list(&main_cmds, &aliases) < 0 || + add_cmd_list(&main_cmds, &other_cmds) < 0) + { + fprintf(stderr, "ERROR: Failed to allocate command list for unknown command.\n"); + goto end; + } + + qsort(main_cmds.names, main_cmds.cnt, + sizeof(main_cmds.names), cmdname_compare); + uniq(&main_cmds); + + if (main_cmds.cnt) + { + /* This reuses cmdname->len for similarity index */ + for (i = 0; i < main_cmds.cnt; ++i) + main_cmds.names[i]->len = + levenshtein(cmd, main_cmds.names[i]->name, 0, 2, 1, 4); + + qsort(main_cmds.names, main_cmds.cnt, + sizeof(*main_cmds.names), levenshtein_compare); + + best_similarity = main_cmds.names[0]->len; + n = 1; + + while (n < main_cmds.cnt && best_similarity == main_cmds.names[n]->len) + { + ++n; + } + } + + if (autocorrect && n == 1) + { + const char *assumed = main_cmds.names[0]->name; + + main_cmds.names[0] = NULL; + clean_cmdnames(&main_cmds); + fprintf(stderr, "WARNING: You called a perf program named '%s', " + "which does not exist.\n" + "Continuing under the assumption that you meant '%s'\n", + cmd, assumed); + + if (autocorrect > 0) + { + fprintf(stderr, "in %0.1f seconds automatically...\n", + (float)autocorrect / 10.0); + poll(NULL, 0, autocorrect * 100); + } + + return assumed; + } + + fprintf(stderr, "perf: '%s' is not a perf-command. See 'perf --help'.\n", cmd); + + if (main_cmds.cnt && best_similarity < 6) + { + fprintf(stderr, "\nDid you mean %s?\n", + n < 2 ? "this" : "one of these"); + + for (i = 0; i < n; i++) + { + fprintf(stderr, "\t%s\n", main_cmds.names[i]->name); + } + } + +end: + exit(1); +} diff --git a/pool/shard006/C/0119464_gpio.c b/pool/shard006/C/0119464_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..f94560ddec9607024eb468fe2fb603bb3527b26d --- /dev/null +++ b/pool/shard006/C/0119464_gpio.c @@ -0,0 +1,171 @@ +/* + * gpio.c + * + * Linux GPIO userspace utility (character interface) + * + * Copyright (C) 2015, 2016 QWERTY Embedded Design + * Michael Welling + * + * Based on gpio-hammer.c + * Copyright (C) 2016 Linus Walleij + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include + +void print_usage() +{ + printf("USAGE:\tgpio -n NAME -o OFF [-d DIR] [-v VAL]\n"); + printf("\t-n, --name NAME\tGPIO device name.\n"); + printf("\t-o, --offset OFF\tGPIO device offset.\n"); + printf("\t-d, --direction DIR\tSet GPIO direction. { in, out }\n"); + printf("\t-v, --value VAL\tSet GPIO values in binary.\n"); + printf("\nEXAMPLE: gpio -n gpiochip0 -o0 -o1 -o2 -d out -v 001\n"); +} + +int main(int argc, char **argv) +{ + int fd; + char *gpio_name = NULL; + unsigned int lines[GPIOHANDLES_MAX]; + char *value = NULL; + char *direction = NULL; + int nlines = 0; + char *chrdev_name; + struct gpiohandle_request req; + struct gpiohandle_data data; + int ret; + int opt_i = 0; + int c; + int i; + + static struct option long_opts[]= + { + { "direction", required_argument, 0, 'd' }, + { "name", required_argument, 0, 'n' }, + { "offset", required_argument, 0, 'o' }, + { "value", required_argument, 0, 'v' }, + { 0, 0, 0, 0 }, + }; + + while((c = getopt_long(argc, argv, "d:n:o:v:", + long_opts, &opt_i)) != -1) + { + switch(c) + { + case 'd': + direction = optarg; + break; + case 'n': + gpio_name = optarg; + break; + case 'o': + lines[nlines] = strtoul(optarg, NULL, 10); + nlines++; + break; + case 'v': + value = optarg; + break; + case '?': + print_usage(); + return 0; + break; + } + } + + if (!gpio_name || !nlines) { + print_usage(); + return -EINVAL; + } + + ret = asprintf(&chrdev_name, "/dev/%s", gpio_name); + if (ret < 0) { + fprintf(stderr, "Out of memory\n", chrdev_name); + return -ENOMEM; + } + + fd = open(chrdev_name, 0); + if (fd < 0) { + ret = -errno; + fprintf(stderr, "Failed to open %s\n", chrdev_name); + goto exit_free_error; + } + + for (i = 0; i < nlines; i++) + req.lineoffsets[i] = lines[i]; + + if (direction) { + if (strcmp(direction, "out") == 0) + req.flags = GPIOHANDLE_REQUEST_OUTPUT; + else if (strcmp(direction, "in") == 0) + req.flags = GPIOHANDLE_REQUEST_INPUT; + else { + fprintf(stderr, "Invalid direction %s\n", direction); + ret = -EINVAL; + goto exit_close_error; + } + } + else { + req.flags = GPIOHANDLE_REQUEST_INPUT; + } + + strcpy(req.consumer_label, "gpio-util"); + req.lines = nlines; + + ret = ioctl(fd, GPIO_GET_LINEHANDLE_IOCTL, &req); + if (ret == -1) { + ret = -errno; + fprintf(stderr, "Failed to issue GET LINEHANDLE " + "IOCTL (%d)\n", + ret); + goto exit_close_error; + } + + if (value && (req.flags == GPIOHANDLE_REQUEST_OUTPUT)) { + for(i = 0; i < nlines; i++) + data.values[i] = value[i % strlen(value)] - '0'; + + ret = ioctl(req.fd, GPIOHANDLE_SET_LINE_VALUES_IOCTL, &data); + if (ret == -1) { + ret = -errno; + fprintf(stderr, "Failed to issue GPIOHANDLE SET LINE " + "VALUES IOCTL (%d)\n", + ret); + goto exit_close_error; + } + } + + ret = ioctl(req.fd, GPIOHANDLE_GET_LINE_VALUES_IOCTL, &data); + if (ret == -1) { + ret = -errno; + fprintf(stderr, "Failed to issue GPIOHANDLE GET LINE " + "VALUES IOCTL (%d)\n", + ret); + goto exit_close_error; + } + + for (i = 0; i < nlines; i++) { + printf("%s[%d] = %d\n", gpio_name, lines[i], data.values[i]); + } + +exit_close_error: + if (close(fd) == -1) + perror("Failed to close GPIO character device file"); +exit_free_error: + free(chrdev_name); + + return ret; +} diff --git a/pool/shard006/C/0119465_qnx_joypad.c b/pool/shard006/C/0119465_qnx_joypad.c new file mode 100644 index 0000000000000000000000000000000000000000..4833a8a80b0f4836ac399b1f3cc0721c53c58b76 --- /dev/null +++ b/pool/shard006/C/0119465_qnx_joypad.c @@ -0,0 +1,140 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2014 - Hans-Kristian Arntzen + * Copyright (C) 2011-2016 - Daniel De Matteis + * Copyright (C) 2013-2014 - CatalystG + * + * RetroArch 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 Found- + * ation, either version 3 of the License, or (at your option) any later version. + * + * RetroArch 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 RetroArch. + * If not, see . + */ + +#include "../../tasks/tasks_internal.h" +#include "../../configuration.h" + +static const char *qnx_joypad_name(unsigned pad) +{ + settings_t *settings = config_get_ptr(); + return settings ? settings->input.device_names[pad] : NULL; +} + +static bool qnx_joypad_init(void *data) +{ + unsigned autoconf_pad; + + (void)data; + + for (autoconf_pad = 0; autoconf_pad < MAX_USERS; autoconf_pad++) + { + if (!input_autoconfigure_connect( + qnx_joypad_name(autoconf_pad), + NULL, + qnx_joypad.ident, + autoconf_pad, + 0, + 0 + )) + input_config_set_device_name(autoconf_pad, qnx_joypad_name(autoconf_pad)); + } + + return true; +} + +static bool qnx_joypad_button(unsigned port_num, uint16_t joykey) +{ + qnx_input_t *qnx = (qnx_input_t*)input_driver_get_data(); + if (!qnx || port_num >= MAX_PADS) + return 0; + + qnx_input_device_t* controller = NULL; + controller = (qnx_input_device_t*)&qnx->devices[port_num]; + + if(port_num < MAX_USERS && joykey <= 19) + { + return (controller->buttons & (1 << joykey)) != 0; + } + + return false; +} + +static int16_t qnx_joypad_axis(unsigned port_num, uint32_t joyaxis) +{ + int val = 0; + int axis = -1; + bool is_neg = false; + bool is_pos = false; + qnx_input_t *qnx = (qnx_input_t*)input_driver_get_data(); + + if (!qnx || joyaxis == AXIS_NONE || port_num >= MAX_PADS) + return 0; + + if (AXIS_NEG_GET(joyaxis) < 4) + { + axis = AXIS_NEG_GET(joyaxis); + is_neg = true; + } + else if (AXIS_POS_GET(joyaxis) < 4) + { + axis = AXIS_POS_GET(joyaxis); + is_pos = true; + } + + qnx_input_device_t* controller = NULL; + controller = (qnx_input_device_t*)&qnx->devices[port_num]; + + switch (axis) + { + case 0: + val = controller->analog0[0]; + break; + case 1: + val = controller->analog0[1]; + break; + case 2: + val = controller->analog1[0]; + break; + case 3: + val = controller->analog1[1]; + break; + } + + if (is_neg && val > 0) + val = 0; + else if (is_pos && val < 0) + val = 0; + + return val; +} + +static void qnx_joypad_poll(void) +{ +} + +static bool qnx_joypad_query_pad(unsigned pad) +{ + return (pad < MAX_USERS); +} + + +static void qnx_joypad_destroy(void) +{ +} + +input_device_driver_t qnx_joypad = { + qnx_joypad_init, + qnx_joypad_query_pad, + qnx_joypad_destroy, + qnx_joypad_button, + NULL, + qnx_joypad_axis, + qnx_joypad_poll, + NULL, + qnx_joypad_name, + "qnx", +}; diff --git a/pool/shard006/C/0119467_avx512f-vpermi2d-2.c b/pool/shard006/C/0119467_avx512f-vpermi2d-2.c new file mode 100644 index 0000000000000000000000000000000000000000..6205cc53004d6068904eebd0a008b185d858b4e4 --- /dev/null +++ b/pool/shard006/C/0119467_avx512f-vpermi2d-2.c @@ -0,0 +1,53 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -mavx512f" } */ +/* { dg-require-effective-target avx512f } */ + +#define AVX512F + +#include "avx512f-helper.h" + +#define SIZE (AVX512F_LEN / 32) +#include "avx512f-mask-type.h" +#include "math.h" + +static void +CALC (int *dst, int *src1, int *ind, int *src2) +{ + int i; + + for (i = 0; i < SIZE; i++) + { + unsigned long long offset = ind[i] & (SIZE - 1); + unsigned long long cond = ind[i] & SIZE; + + dst[i] = cond ? src2[offset] : src1[offset]; + } +} + +void static +TEST (void) +{ + int i; + UNION_TYPE (AVX512F_LEN, i_d) s1, s2, res, ind; + int res_ref[SIZE]; + + MASK_TYPE mask = MASK_VALUE; + + for (i = 0; i < SIZE; i++) + { + ind.a[i] = DEFAULT_VALUE; + s1.a[i] = 34 * i + 1; + s2.a[i] = 34 * i; + + res.a[i] = DEFAULT_VALUE; + } + + CALC (res_ref, s1.a, ind.a, s2.a); + + res.x = + INTRINSIC (_mask2_permutex2var_epi32) (s1.x, ind.x, mask, s2.x); + + MASK_MERGE (i_d) (res_ref, mask, SIZE); + if (UNION_CHECK (AVX512F_LEN, i_d) (res, res_ref)) + abort (); +} diff --git a/pool/shard006/C/0119471_exemplo.c b/pool/shard006/C/0119471_exemplo.c new file mode 100644 index 0000000000000000000000000000000000000000..46b4c9cdb5bbe47630e312bd0fb5077cfa4ff7a4 --- /dev/null +++ b/pool/shard006/C/0119471_exemplo.c @@ -0,0 +1,29 @@ +#include +#include + +struct Aluno +{ + int codigo; + double notas[3]; + double media; +}; + +int main() +{ + int i; + struct Aluno jose; + jose.codigo=1; + + for ( i = 0; i < 3; i++ ){ + printf("Digite a %d nota do Aluno %d: ", ( i + 1 ), jose.codigo ); + scanf("%lf", &jose.notas[i]); + } + + jose.media = (jose.notas[0]+jose.notas[1]+jose.notas[2])/3; + + printf("\nMatrícula: %d.", jose.codigo); + printf("\nMédia: %.2lf.\n\n", jose.media); + + system ("pause"); + return (0); +} diff --git a/pool/shard006/C/0119472_traps.c b/pool/shard006/C/0119472_traps.c new file mode 100644 index 0000000000000000000000000000000000000000..7001beda716c2c86077df3dc224d470244152965 --- /dev/null +++ b/pool/shard006/C/0119472_traps.c @@ -0,0 +1,131 @@ +/* + * Helper functions for trap handlers + * + * Copyright (C) 2000-2007, Axis Communications AB. + * + * Authors: Bjorn Wesen + * Hans-Peter Nilsson + * + */ + +#include +#include +#include +#include + +void +show_registers(struct pt_regs *regs) +{ + /* + * It's possible to use either the USP register or current->thread.usp. + * USP might not correspond to the current process for all cases this + * function is called, and current->thread.usp isn't up to date for the + * current process. Experience shows that using USP is the way to go. + */ + unsigned long usp = rdusp(); + + printk("IRP: %08lx SRP: %08lx DCCR: %08lx USP: %08lx MOF: %08lx\n", + regs->irp, regs->srp, regs->dccr, usp, regs->mof); + + printk(" r0: %08lx r1: %08lx r2: %08lx r3: %08lx\n", + regs->r0, regs->r1, regs->r2, regs->r3); + + printk(" r4: %08lx r5: %08lx r6: %08lx r7: %08lx\n", + regs->r4, regs->r5, regs->r6, regs->r7); + + printk(" r8: %08lx r9: %08lx r10: %08lx r11: %08lx\n", + regs->r8, regs->r9, regs->r10, regs->r11); + + printk("r12: %08lx r13: %08lx oR10: %08lx sp: %08lx\n", + regs->r12, regs->r13, regs->orig_r10, (long unsigned)regs); + + printk("R_MMU_CAUSE: %08lx\n", (unsigned long)*R_MMU_CAUSE); + + printk("Process %s (pid: %d, stackpage=%08lx)\n", + current->comm, current->pid, (unsigned long)current); + + /* + * When in-kernel, we also print out the stack and code at the + * time of the fault.. + */ + if (!user_mode(regs)) { + int i; + + show_stack(NULL, (unsigned long *)usp); + + /* + * If the previous stack-dump wasn't a kernel one, dump the + * kernel stack now. + */ + if (usp != 0) + show_stack(NULL, NULL); + + printk("\nCode: "); + + if (regs->irp < PAGE_OFFSET) + goto bad_value; + + /* + * Quite often the value at regs->irp doesn't point to the + * interesting instruction, which often is the previous + * instruction. So dump at an offset large enough that the + * instruction decoding should be in sync at the interesting + * point, but small enough to fit on a row. The regs->irp + * location is pointed out in a ksymoops-friendly way by + * wrapping the byte for that address in parenthesises. + */ + for (i = -12; i < 12; i++) { + unsigned char c; + + if (__get_user(c, &((unsigned char *)regs->irp)[i])) { +bad_value: + printk(" Bad IP value."); + break; + } + + if (i == 0) + printk("(%02x) ", c); + else + printk("%02x ", c); + } + printk("\n"); + } +} + +void +arch_enable_nmi(void) +{ + asm volatile ("setf m"); +} + +extern void (*nmi_handler)(struct pt_regs *); +void handle_nmi(struct pt_regs *regs) +{ + if (nmi_handler) + nmi_handler(regs); + + /* Wait until nmi is no longer active. (We enable NMI immediately after + returning from this function, and we don't want it happening while + exiting from the NMI interrupt handler.) */ + while (*R_IRQ_MASK0_RD & IO_STATE(R_IRQ_MASK0_RD, nmi_pin, active)) + ; +} + +#ifdef CONFIG_DEBUG_BUGVERBOSE +void +handle_BUG(struct pt_regs *regs) +{ + struct bug_frame f; + unsigned char c; + unsigned long irp = regs->irp; + + if (__copy_from_user(&f, (const void __user *)(irp - 8), sizeof f)) + return; + if (f.prefix != BUG_PREFIX || f.magic != BUG_MAGIC) + return; + if (__get_user(c, f.filename)) + f.filename = ""; + + printk("kernel BUG at %s:%d!\n", f.filename, f.line); +} +#endif diff --git a/pool/shard006/C/0119473_ftps.c b/pool/shard006/C/0119473_ftps.c new file mode 100644 index 0000000000000000000000000000000000000000..82420b86af44d2818aa560542b155f13a709340c --- /dev/null +++ b/pool/shard006/C/0119473_ftps.c @@ -0,0 +1,161 @@ +/*****************************************************************************/ +/* ftps.c - General purpose routines for the FTPS protocol */ +/* Copyright (C) 1998-2007 Brian Masney */ +/* */ +/* 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 USA */ +/*****************************************************************************/ + +#include "gftp.h" +#include "ftpcommon.h" + +static const char cvsid[] = "$Id$"; + +#ifdef USE_SSL +static int +ftps_get_next_file (gftp_request * request, gftp_file * fle, int fd) +{ + rfc959_parms * params; + int resetptr; + size_t ret; + + params = request->protocol_data; + if (request->cached) + { + request->read_function = gftp_fd_read; + request->write_function = gftp_fd_write; + resetptr = 1; + } + else + resetptr = 0; + + ret = rfc959_get_next_file (request, fle, fd); + + if (resetptr) + { + request->read_function = gftp_ssl_read; + request->write_function = gftp_ssl_write; + } + + return (ret); +} + + +static int +ftps_auth_tls_start (gftp_request * request) +{ + rfc959_parms * params; + int ret; + + params = request->protocol_data; + + ret = rfc959_send_command (request, "AUTH TLS\r\n", -1, 1, 0); + if (ret < 0) + return (ret); + else if (ret != '2') + return (GFTP_EFATAL); + + if ((ret = gftp_ssl_session_setup (request)) < 0) + return (ret); + + request->read_function = gftp_ssl_read; + request->write_function = gftp_ssl_write; + + ret = rfc959_send_command (request, "PBSZ 0\r\n", -1, 1, 0); + if (ret < 0) + return (ret); + + ret = rfc959_send_command (request, "PROT P\r\n", -1, 1, 0); + if (ret < 0) + return (ret); + else if (ret == '2') + { + params->data_conn_read = gftp_ssl_read; + params->data_conn_write = gftp_ssl_write; + } + else + { + ret = rfc959_send_command (request, "PROT C\r\n", -1, 1, 0); + if (ret < 0) + return (ret); + else if (ret != '2') + { + gftp_disconnect (request); + return (GFTP_ERETRYABLE); + } + + params->data_conn_read = gftp_fd_read; + params->data_conn_write = gftp_fd_write; + } + + return (0); +} + +/*@unused@*/ static int +ftps_connect (gftp_request * request) +{ + if (request->datafd > 0) + return (0); + + request->read_function = gftp_fd_read; + request->write_function = gftp_fd_write; + + return (rfc959_connect (request)); +} + +#endif + + +void +ftps_register_module (void) +{ +#ifdef USE_SSL + ssl_register_module (); +#endif +} + + +int +ftps_init (gftp_request * request) +{ +#ifdef USE_SSL + rfc959_parms * params; + int ret; + + g_return_val_if_fail (request != NULL, GFTP_EFATAL); + + if ((ret = gftp_protocols[GFTP_FTP_NUM].init (request)) < 0) + return (ret); + + params = request->protocol_data; + request->protonum = GFTP_FTPS_NUM; + request->init = ftps_init; + request->connect = ftps_connect; + params->auth_tls_start = ftps_auth_tls_start; + request->get_next_file = ftps_get_next_file; + request->post_connect = NULL; + request->url_prefix = g_strdup ("ftps"); + + if ((ret = gftp_ssl_startup (NULL)) < 0) + return (ret); + + return (0); +#else + request->logging_function (gftp_logging_error, request, + _("FTPS Support unavailable since SSL support was not compiled in. Aborting connection.\n")); + + return (GFTP_EFATAL); +#endif +} + diff --git a/pool/shard006/C/0119474_nv_of.c b/pool/shard006/C/0119474_nv_of.c new file mode 100644 index 0000000000000000000000000000000000000000..181875fe35c662899e5964d52da76d7ca6a483ce --- /dev/null +++ b/pool/shard006/C/0119474_nv_of.c @@ -0,0 +1,82 @@ +/* + * linux/drivers/video/nvidia/nv_of.c + * + * Copyright 2004 Antonino A. Daplas + * + * Based on rivafb-i2c.c + * + * 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. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include "nv_type.h" +#include "nv_local.h" +#include "nv_proto.h" + +#include "../edid.h" + +int nvidia_probe_of_connector(struct fb_info *info, int conn, u8 **out_edid) +{ + struct nvidia_par *par = info->par; + struct device_node *parent, *dp; + const unsigned char *pedid = NULL; + static char *propnames[] = { + "DFP,EDID", "LCD,EDID", "EDID", "EDID1", + "EDID,B", "EDID,A", NULL }; + int i; + + parent = pci_device_to_OF_node(par->pci_dev); + if (parent == NULL) + return -1; + if (par->twoHeads) { + const char *pname; + int len; + + for (dp = NULL; + (dp = of_get_next_child(parent, dp)) != NULL;) { + pname = get_property(dp, "name", NULL); + if (!pname) + continue; + len = strlen(pname); + if ((pname[len-1] == 'A' && conn == 1) || + (pname[len-1] == 'B' && conn == 2)) { + for (i = 0; propnames[i] != NULL; ++i) { + pedid = get_property(dp, propnames[i], + NULL); + if (pedid != NULL) + break; + } + of_node_put(dp); + break; + } + } + } + if (pedid == NULL) { + for (i = 0; propnames[i] != NULL; ++i) { + pedid = get_property(parent, propnames[i], NULL); + if (pedid != NULL) + break; + } + } + if (pedid) { + *out_edid = kmemdup(pedid, EDID_LENGTH, GFP_KERNEL); + if (*out_edid == NULL) + return -1; + printk(KERN_DEBUG "nvidiafb: Found OF EDID for head %d\n", conn); + return 0; + } + return -1; +} diff --git a/pool/shard006/C/0119476_ehci-pci.c b/pool/shard006/C/0119476_ehci-pci.c new file mode 100644 index 0000000000000000000000000000000000000000..dceba4bd7aa1eb230567b9bcbfaa9b4bef167d9a --- /dev/null +++ b/pool/shard006/C/0119476_ehci-pci.c @@ -0,0 +1,154 @@ +/*- + * Copyright (c) 2007-2008, Juniper Networks, Inc. + * All rights reserved. + * + * SPDX-License-Identifier: GPL-2.0 + */ + +#include +#include +#include +#include +#include +#include + +#include "ehci.h" + +/* Information about a USB port */ +struct ehci_pci_priv { + struct ehci_ctrl ehci; +}; + +#ifdef CONFIG_DM_USB + +static void ehci_pci_init(struct udevice *dev, struct ehci_hccr **ret_hccr, + struct ehci_hcor **ret_hcor) +{ + struct ehci_hccr *hccr; + struct ehci_hcor *hcor; + u32 cmd; + + hccr = (struct ehci_hccr *)dm_pci_map_bar(dev, + PCI_BASE_ADDRESS_0, PCI_REGION_MEM); + hcor = (struct ehci_hcor *)((uintptr_t) hccr + + HC_LENGTH(ehci_readl(&hccr->cr_capbase))); + + debug("EHCI-PCI init hccr %#lx and hcor %#lx hc_length %d\n", + (ulong)hccr, (ulong)hcor, + (u32)HC_LENGTH(ehci_readl(&hccr->cr_capbase))); + + *ret_hccr = hccr; + *ret_hcor = hcor; + + /* enable busmaster */ + dm_pci_read_config32(dev, PCI_COMMAND, &cmd); + cmd |= PCI_COMMAND_MASTER; + dm_pci_write_config32(dev, PCI_COMMAND, cmd); +} + +#else + +#ifdef CONFIG_PCI_EHCI_DEVICE +static struct pci_device_id ehci_pci_ids[] = { + /* Please add supported PCI EHCI controller ids here */ + {0x1033, 0x00E0}, /* NEC */ + {0x10B9, 0x5239}, /* ULI1575 PCI EHCI module ids */ + {0x12D8, 0x400F}, /* Pericom */ + {0, 0} +}; +#endif + +static void ehci_pci_legacy_init(pci_dev_t pdev, struct ehci_hccr **ret_hccr, + struct ehci_hcor **ret_hcor) +{ + struct ehci_hccr *hccr; + struct ehci_hcor *hcor; + u32 cmd; + + hccr = (struct ehci_hccr *)pci_map_bar(pdev, + PCI_BASE_ADDRESS_0, PCI_REGION_MEM); + hcor = (struct ehci_hcor *)((uintptr_t) hccr + + HC_LENGTH(ehci_readl(&hccr->cr_capbase))); + + debug("EHCI-PCI init hccr 0x%x and hcor 0x%x hc_length %d\n", + (u32)hccr, (u32)hcor, + (u32)HC_LENGTH(ehci_readl(&hccr->cr_capbase))); + + *ret_hccr = hccr; + *ret_hcor = hcor; + + /* enable busmaster */ + pci_read_config_dword(pdev, PCI_COMMAND, &cmd); + cmd |= PCI_COMMAND_MASTER; + pci_write_config_dword(pdev, PCI_COMMAND, cmd); +} + +/* + * Create the appropriate control structures to manage + * a new EHCI host controller. + */ +int ehci_hcd_init(int index, enum usb_init_type init, + struct ehci_hccr **ret_hccr, struct ehci_hcor **ret_hcor) +{ + pci_dev_t pdev; + +#ifdef CONFIG_PCI_EHCI_DEVICE + pdev = pci_find_devices(ehci_pci_ids, CONFIG_PCI_EHCI_DEVICE); +#else + pdev = pci_find_class(PCI_CLASS_SERIAL_USB_EHCI, index); +#endif + if (pdev < 0) { + printf("EHCI host controller not found\n"); + return -1; + } + ehci_pci_legacy_init(pdev, ret_hccr, ret_hcor); + + return 0; +} + +/* + * Destroy the appropriate control structures corresponding + * the the EHCI host controller. + */ +int ehci_hcd_stop(int index) +{ + return 0; +} +#endif /* nCONFIG_DM_USB */ + +#ifdef CONFIG_DM_USB +static int ehci_pci_probe(struct udevice *dev) +{ + struct ehci_hccr *hccr; + struct ehci_hcor *hcor; + + ehci_pci_init(dev, &hccr, &hcor); + + return ehci_register(dev, hccr, hcor, NULL, 0, USB_INIT_HOST); +} + +static const struct udevice_id ehci_pci_ids[] = { + { .compatible = "ehci-pci" }, + { } +}; + +U_BOOT_DRIVER(ehci_pci) = { + .name = "ehci_pci", + .id = UCLASS_USB, + .probe = ehci_pci_probe, + .remove = ehci_deregister, + .of_match = ehci_pci_ids, + .ops = &ehci_usb_ops, + .platdata_auto_alloc_size = sizeof(struct usb_platdata), + .priv_auto_alloc_size = sizeof(struct ehci_pci_priv), + .flags = DM_FLAG_ALLOC_PRIV_DMA, +}; + +static struct pci_device_id ehci_pci_supported[] = { + { PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_EHCI, ~0) }, + {}, +}; + +U_BOOT_PCI_DEVICE(ehci_pci, ehci_pci_supported); + +#endif /* CONFIG_DM_USB */ diff --git a/pool/shard006/C/0119478_gus_instr.c b/pool/shard006/C/0119478_gus_instr.c new file mode 100644 index 0000000000000000000000000000000000000000..031a779785734720a4bd404d185a15e32852d0d9 --- /dev/null +++ b/pool/shard006/C/0119478_gus_instr.c @@ -0,0 +1,173 @@ +/* + * Routines for Gravis UltraSound soundcards - Synthesizer + * Copyright (c) by Jaroslav Kysela + * + * + * 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 +#include +#include +#include + +/* + * + */ + +int snd_gus_iwffff_put_sample(void *private_data, iwffff_wave_t *wave, + char *data, long len, int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + snd_gf1_mem_block_t *block; + int err; + + if (wave->format & IWFFFF_WAVE_ROM) + return 0; /* it's probably ok - verify the address? */ + if (wave->format & IWFFFF_WAVE_STEREO) + return -EINVAL; /* not supported */ + block = snd_gf1_mem_alloc(&gus->gf1.mem_alloc, + SNDRV_GF1_MEM_OWNER_WAVE_IWFFFF, + NULL, wave->size, + wave->format & IWFFFF_WAVE_16BIT, 1, + wave->share_id); + if (block == NULL) + return -ENOMEM; + err = snd_gus_dram_write(gus, data, + block->ptr, wave->size); + if (err < 0) { + snd_gf1_mem_lock(&gus->gf1.mem_alloc, 0); + snd_gf1_mem_xfree(&gus->gf1.mem_alloc, block); + snd_gf1_mem_lock(&gus->gf1.mem_alloc, 1); + return err; + } + wave->address.memory = block->ptr; + return 0; +} + +int snd_gus_iwffff_get_sample(void *private_data, iwffff_wave_t *wave, + char *data, long len, int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + + return snd_gus_dram_read(gus, data, wave->address.memory, wave->size, + wave->format & IWFFFF_WAVE_ROM ? 1 : 0); +} + +int snd_gus_iwffff_remove_sample(void *private_data, iwffff_wave_t *wave, + int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + + if (wave->format & IWFFFF_WAVE_ROM) + return 0; /* it's probably ok - verify the address? */ + return snd_gf1_mem_free(&gus->gf1.mem_alloc, wave->address.memory); +} + +/* + * + */ + +int snd_gus_gf1_put_sample(void *private_data, gf1_wave_t *wave, + char *data, long len, int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + snd_gf1_mem_block_t *block; + int err; + + if (wave->format & GF1_WAVE_STEREO) + return -EINVAL; /* not supported */ + block = snd_gf1_mem_alloc(&gus->gf1.mem_alloc, + SNDRV_GF1_MEM_OWNER_WAVE_GF1, + NULL, wave->size, + wave->format & GF1_WAVE_16BIT, 1, + wave->share_id); + if (block == NULL) + return -ENOMEM; + err = snd_gus_dram_write(gus, data, + block->ptr, wave->size); + if (err < 0) { + snd_gf1_mem_lock(&gus->gf1.mem_alloc, 0); + snd_gf1_mem_xfree(&gus->gf1.mem_alloc, block); + snd_gf1_mem_lock(&gus->gf1.mem_alloc, 1); + return err; + } + wave->address.memory = block->ptr; + return 0; +} + +int snd_gus_gf1_get_sample(void *private_data, gf1_wave_t *wave, + char *data, long len, int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + + return snd_gus_dram_read(gus, data, wave->address.memory, wave->size, 0); +} + +int snd_gus_gf1_remove_sample(void *private_data, gf1_wave_t *wave, + int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + + return snd_gf1_mem_free(&gus->gf1.mem_alloc, wave->address.memory); +} + +/* + * + */ + +int snd_gus_simple_put_sample(void *private_data, simple_instrument_t *instr, + char *data, long len, int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + snd_gf1_mem_block_t *block; + int err; + + if (instr->format & SIMPLE_WAVE_STEREO) + return -EINVAL; /* not supported */ + block = snd_gf1_mem_alloc(&gus->gf1.mem_alloc, + SNDRV_GF1_MEM_OWNER_WAVE_SIMPLE, + NULL, instr->size, + instr->format & SIMPLE_WAVE_16BIT, 1, + instr->share_id); + if (block == NULL) + return -ENOMEM; + err = snd_gus_dram_write(gus, data, block->ptr, instr->size); + if (err < 0) { + snd_gf1_mem_lock(&gus->gf1.mem_alloc, 0); + snd_gf1_mem_xfree(&gus->gf1.mem_alloc, block); + snd_gf1_mem_lock(&gus->gf1.mem_alloc, 1); + return err; + } + instr->address.memory = block->ptr; + return 0; +} + +int snd_gus_simple_get_sample(void *private_data, simple_instrument_t *instr, + char *data, long len, int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + + return snd_gus_dram_read(gus, data, instr->address.memory, instr->size, 0); +} + +int snd_gus_simple_remove_sample(void *private_data, simple_instrument_t *instr, + int atomic) +{ + snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, return -ENXIO); + + return snd_gf1_mem_free(&gus->gf1.mem_alloc, instr->address.memory); +} diff --git a/pool/shard006/C/0119481_div_main.c b/pool/shard006/C/0119481_div_main.c new file mode 100644 index 0000000000000000000000000000000000000000..39f35581e053db3514d3d4cb78b838937a57c3f2 --- /dev/null +++ b/pool/shard006/C/0119481_div_main.c @@ -0,0 +1,21 @@ +#include +#include "div_str.h" + +int main(int argc, char *argv[]) +{ + char str[50]; + char **ws; + int i; + printf("Input the line pls:"); + + fgets(str, 50, stdin); + ws = div_str(str); + + for (i = 0; ws[i]; i++) { + printf("%s\n", ws[i]); + } + + free_list(ws); + + return 0; +} diff --git a/pool/shard006/C/0119483_box_sys_vrb.c b/pool/shard006/C/0119483_box_sys_vrb.c new file mode 100644 index 0000000000000000000000000000000000000000..9e0f1e50d698c7893a4ba8bb47dea5997a1afc2d --- /dev/null +++ b/pool/shard006/C/0119483_box_sys_vrb.c @@ -0,0 +1,73 @@ +/* + * box_sys_vrb.c + * + * Created on: 06.12.2012 + * Author: montesas + */ + +#include "box_sys_vrb.h" +#include "box_sys.h" +#include "hdoipd.h" +#include "rtsp_client.h" + +#define TICK_SEND_ALIVE (hdoipd.eth_alive) + +static int box_sys_vrb_describe(t_rtsp_media *media, void *_data, t_rtsp_connection *con) +{ + t_rtsp_req_describe *data = _data; + int ret; + + if (!data) + return -1; + + ret = rtsp_handle_describe_generic(media, data, con); + if (ret) + return ret; + + /* VRB offers no streams */ //wrong + + + msgprintf(con, "m=audio 0 RTP/AVP 97\r\n"); + msgprintf(con, "a=control:/device/1/audio/1/\r\n"); + + + rtsp_send(con); + + return 0; +} + +static int box_sys_vrb_event(t_rtsp_media *media, uint32_t event) +{ + t_rtsp_client *client = NULL; + + if (media == NULL || media->creator == NULL) { + return RTSP_NULL_POINTER; + } + + client = (t_rtsp_client*)media->creator; + + switch (event) + { + case EVENT_TICK: + if (client->timeout.alive_ping > 0) + client->timeout.alive_ping--; + else { + client->timeout.alive_ping = TICK_SEND_ALIVE; + return rtsp_client_get_parameter(client, NULL); + } + break; + } + + return RTSP_SUCCESS; +} + +t_rtsp_media box_sys_vrb = { + .name = "", + .owner = 0, + .cookie = NULL, + .options = box_sys_options, + .describe = box_sys_vrb_describe, + .get_parameter = box_sys_get_parameter, + .set_parameter = box_sys_set_parameter, + .event = box_sys_vrb_event +}; diff --git a/pool/shard006/C/0119490_grammar.c b/pool/shard006/C/0119490_grammar.c new file mode 100644 index 0000000000000000000000000000000000000000..659a1511345396ee3ff9bdd8096d8b4ecf210db9 --- /dev/null +++ b/pool/shard006/C/0119490_grammar.c @@ -0,0 +1,246 @@ + +/* Grammar implementation */ + +#include "Python.h" +#include "pgenheaders.h" + +#include + +#include "token.h" +#include "grammar.h" + +#ifdef RISCOS +#include +#endif + +extern int Py_DebugFlag; + +grammar * +newgrammar(int start) +{ + grammar *g; + + g = PyMem_NEW(grammar, 1); + if (g == NULL) + Py_FatalError("no mem for new grammar"); + g->g_ndfas = 0; + g->g_dfa = NULL; + g->g_start = start; + g->g_ll.ll_nlabels = 0; + g->g_ll.ll_label = NULL; + g->g_accel = 0; + return g; +} + +dfa * +adddfa(grammar *g, int type, char *name) +{ + dfa *d; + + PyMem_RESIZE(g->g_dfa, dfa, g->g_ndfas + 1); + if (g->g_dfa == NULL) + Py_FatalError("no mem to resize dfa in adddfa"); + d = &g->g_dfa[g->g_ndfas++]; + d->d_type = type; + d->d_name = strdup(name); + d->d_nstates = 0; + d->d_state = NULL; + d->d_initial = -1; + d->d_first = NULL; + return d; /* Only use while fresh! */ +} + +int +addstate(dfa *d) +{ + state *s; + + PyMem_RESIZE(d->d_state, state, d->d_nstates + 1); + if (d->d_state == NULL) + Py_FatalError("no mem to resize state in addstate"); + s = &d->d_state[d->d_nstates++]; + s->s_narcs = 0; + s->s_arc = NULL; + s->s_lower = 0; + s->s_upper = 0; + s->s_accel = NULL; + s->s_accept = 0; + return s - d->d_state; +} + +void +addarc(dfa *d, int from, int to, int lbl) +{ + state *s; + arc *a; + + assert(0 <= from && from < d->d_nstates); + assert(0 <= to && to < d->d_nstates); + + s = &d->d_state[from]; + PyMem_RESIZE(s->s_arc, arc, s->s_narcs + 1); + if (s->s_arc == NULL) + Py_FatalError("no mem to resize arc list in addarc"); + a = &s->s_arc[s->s_narcs++]; + a->a_lbl = lbl; + a->a_arrow = to; +} + +int +addlabel(labellist *ll, int type, char *str) +{ + int i; + label *lb; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type && + strcmp(ll->ll_label[i].lb_str, str) == 0) + return i; + } + PyMem_RESIZE(ll->ll_label, label, ll->ll_nlabels + 1); + if (ll->ll_label == NULL) + Py_FatalError("no mem to resize labellist in addlabel"); + lb = &ll->ll_label[ll->ll_nlabels++]; + lb->lb_type = type; + lb->lb_str = strdup(str); + if (Py_DebugFlag) + printf("Label @ %08x, %d: %s\n", (unsigned)ll, ll->ll_nlabels, + PyGrammar_LabelRepr(lb)); + return lb - ll->ll_label; +} + +/* Same, but rather dies than adds */ + +int +findlabel(labellist *ll, int type, char *str) +{ + int i; + + for (i = 0; i < ll->ll_nlabels; i++) { + if (ll->ll_label[i].lb_type == type /*&& + strcmp(ll->ll_label[i].lb_str, str) == 0*/) + return i; + } + fprintf(stderr, "Label %d/'%s' not found\n", type, str); + Py_FatalError("grammar.c:findlabel()"); + return 0; /* Make gcc -Wall happy */ +} + +/* Forward */ +static void translabel(grammar *, label *); + +void +translatelabels(grammar *g) +{ + int i; + +#ifdef Py_DEBUG + printf("Translating labels ...\n"); +#endif + /* Don't translate EMPTY */ + for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) + translabel(g, &g->g_ll.ll_label[i]); +} + +static void +translabel(grammar *g, label *lb) +{ + int i; + + if (Py_DebugFlag) + printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); + + if (lb->lb_type == NAME) { + for (i = 0; i < g->g_ndfas; i++) { + if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { + if (Py_DebugFlag) + printf( + "Label %s is non-terminal %d.\n", + lb->lb_str, + g->g_dfa[i].d_type); + lb->lb_type = g->g_dfa[i].d_type; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + for (i = 0; i < (int)N_TOKENS; i++) { + if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { + if (Py_DebugFlag) + printf("Label %s is terminal %d.\n", + lb->lb_str, i); + lb->lb_type = i; + free(lb->lb_str); + lb->lb_str = NULL; + return; + } + } + printf("Can't translate NAME label '%s'\n", lb->lb_str); + return; + } + + if (lb->lb_type == STRING) { + if (isalpha((int)(lb->lb_str[1])) || lb->lb_str[1] == '_') { + char *p; + char *src; + char *dest; + size_t name_len; + if (Py_DebugFlag) + printf("Label %s is a keyword\n", lb->lb_str); + lb->lb_type = NAME; + src = lb->lb_str + 1; + p = strchr(src, '\''); + if (p) + name_len = p - src; + else + name_len = strlen(src); + dest = malloc(name_len + 1); + strncpy(dest, src, name_len); + dest[name_len] = '\0'; + free(lb->lb_str); + lb->lb_str = dest; + } + else if (lb->lb_str[2] == lb->lb_str[0]) { + int type = (int) PyToken_OneChar(lb->lb_str[1]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { + int type = (int) PyToken_TwoChars(lb->lb_str[1], + lb->lb_str[2]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { + int type = (int) PyToken_ThreeChars(lb->lb_str[1], + lb->lb_str[2], + lb->lb_str[3]); + if (type != OP) { + lb->lb_type = type; + free(lb->lb_str); + lb->lb_str = NULL; + } + else + printf("Unknown OP label %s\n", + lb->lb_str); + } + else + printf("Can't translate STRING label %s\n", + lb->lb_str); + } + else + printf("Can't translate label '%s'\n", + PyGrammar_LabelRepr(lb)); +} diff --git a/pool/shard006/C/0119493_vsf_malfs.c b/pool/shard006/C/0119493_vsf_malfs.c new file mode 100644 index 0000000000000000000000000000000000000000..227e828bf23c3c51f706dbb867c63f1db95fbb3b --- /dev/null +++ b/pool/shard006/C/0119493_vsf_malfs.c @@ -0,0 +1,95 @@ +/*************************************************************************** + * Copyright (C) 2009 - 2010 by Simon Qian * + * * + * 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 "vsf.h" +#include "vsf_malfs.h" + +static void vsf_malfs_finish(void *param) +{ + struct vsf_malfs_t *malfs = (struct vsf_malfs_t *)param; + struct vsf_malstream_t *malstream = &malfs->malstream; + vsfsm_evt_t evt = malstream->offset < malstream->size ? + VSF_MALFS_EVT_IOFAIL : VSF_MALFS_EVT_IODONE; + + vsfsm_post_evt_pending(malfs->notifier_sm, evt); +} + +vsf_err_t vsf_malfs_init(struct vsf_malfs_t *malfs) +{ + uint32_t bs = malfs->malstream.mal->cap.block_size; + + malfs->malstream.mbufstream = &malfs->mbufstream; + malfs->malstream.cb.param = malfs; + malfs->malstream.cb.on_finish = vsf_malfs_finish; + malfs->mbufstream.stream.op = &mbufstream_op; + malfs->mbufstream.mem.multibuf.size = malfs->malstream.mal->cap.block_size; + malfs->mbufstream.mem.multibuf.buffer_list = malfs->mbufstream_buffer; + malfs->mbufstream.mem.multibuf.count = 1; + + vsfsm_crit_init(&malfs->crit, VSF_MALFS_EVT_CRIT); + malfs->sector_buffer = vsf_bufmgr_malloc(bs); + return (NULL == malfs->sector_buffer) ? + VSFERR_NOT_ENOUGH_RESOURCES : VSFERR_NONE; +} + +void vsf_malfs_fini(struct vsf_malfs_t *malfs) +{ + if (malfs->sector_buffer != NULL) + { + vsf_bufmgr_free(malfs->sector_buffer); + malfs->sector_buffer = NULL; + } + if (malfs->volume_name != NULL) + { + vsf_bufmgr_free(malfs->volume_name); + malfs->volume_name = NULL; + } +} + +vsf_err_t vsf_malfs_read(struct vsf_malfs_t *malfs, uint32_t sector, + uint8_t *buff, uint32_t num) +{ + uint32_t bs = malfs->malstream.mal->cap.block_size; + uint32_t bn = malfs->malstream.mal->cap.block_num; + + if ((sector >= bn) || ((sector + num) >= bn)) + { + return VSFERR_INVALID_PARAMETER; + } + + malfs->mbufstream_buffer[0] = buff; + STREAM_INIT(&malfs->mbufstream); + return vsf_malstream_read(&malfs->malstream, sector * bs, num * bs); +} + +vsf_err_t vsf_malfs_write(struct vsf_malfs_t *malfs, uint32_t sector, + uint8_t *buff, uint32_t num) +{ + uint32_t bs = malfs->malstream.mal->cap.block_size; + uint32_t bn = malfs->malstream.mal->cap.block_num; + + if ((sector >= bn) || ((sector + num) >= bn)) + { + return VSFERR_INVALID_PARAMETER; + } + + malfs->mbufstream_buffer[0] = buff; + STREAM_INIT(&malfs->mbufstream); + return vsf_malstream_write(&malfs->malstream, sector * bs, num * bs); +} diff --git a/pool/shard006/C/0119494_mpegpsmux_aac.c b/pool/shard006/C/0119494_mpegpsmux_aac.c new file mode 100644 index 0000000000000000000000000000000000000000..177d3e56c57fcef1d27ecff649d7754c5bef311c --- /dev/null +++ b/pool/shard006/C/0119494_mpegpsmux_aac.c @@ -0,0 +1,152 @@ +/* + * Copyright 2006, 2007, 2008 Fluendo S.A. + * Authors: Jan Schmidt + * Kapil Agrawal + * Julien Moutte + * + * Copyright 2008 Lin YANG + * + * This library is licensed under 4 different licenses and you + * can choose to use it under the terms of any one of them. The + * four licenses are the MPL 1.1, the LGPL, the GPL and the MIT + * license. + * + * MPL: + * + * The contents of this file are subject to the Mozilla Public License + * Version 1.1 (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.mozilla.org/MPL/. + * + * Software distributed under the License is distributed on an "AS IS" + * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + * License for the specific language governing rights and limitations + * under the License. + * + * LGPL: + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + * + * GPL: + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. + * + * MIT: + * + * Unless otherwise indicated, Source Code is licensed under MIT license. + * See further explanation attached in License Statement (distributed in the file + * LICENSE). + * + * 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. + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "mpegpsmux_aac.h" +#include + +GST_DEBUG_CATEGORY_EXTERN (mpegpsmux_debug); +#define GST_CAT_DEFAULT mpegpsmux_debug + +GstBuffer * +mpegpsmux_prepare_aac (GstBuffer * buf, MpegPsPadData * data, MpegPsMux * mux) +{ + guint8 adts_header[7] = { 0, }; + GstBuffer *out_buf = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (buf) + 7); + gsize out_offset = 0; + guint8 rate_idx = 0, channels = 0, obj_type = 0; + + GST_DEBUG_OBJECT (mux, "Preparing AAC buffer for output"); + + /* We want the same metadata */ + gst_buffer_copy_metadata (out_buf, buf, GST_BUFFER_COPY_ALL); + + /* Generate ADTS header */ + obj_type = (GST_READ_UINT8 (GST_BUFFER_DATA (data->codec_data)) & 0xC) >> 2; + obj_type++; + rate_idx = (GST_READ_UINT8 (GST_BUFFER_DATA (data->codec_data)) & 0x3) << 1; + rate_idx |= + (GST_READ_UINT8 (GST_BUFFER_DATA (data->codec_data) + 1) & 0x80) >> 7; + channels = + (GST_READ_UINT8 (GST_BUFFER_DATA (data->codec_data) + 1) & 0x78) >> 3; + GST_DEBUG_OBJECT (mux, "Rate index %u, channels %u, object type %u", rate_idx, + channels, obj_type); + /* Sync point over a full byte */ + adts_header[0] = 0xFF; + /* Sync point continued over first 4 bits + static 4 bits + * (ID, layer, protection)*/ + adts_header[1] = 0xF1; + /* Object type over first 2 bits */ + adts_header[2] = obj_type << 6; + /* rate index over next 4 bits */ + adts_header[2] |= (rate_idx << 2); + /* channels over last 2 bits */ + adts_header[2] |= (channels & 0x4) >> 2; + /* channels continued over next 2 bits + 4 bits at zero */ + adts_header[3] = (channels & 0x3) << 6; + /* frame size over last 2 bits */ + adts_header[3] |= (GST_BUFFER_SIZE (out_buf) & 0x1800) >> 11; + /* frame size continued over full byte */ + adts_header[4] = (GST_BUFFER_SIZE (out_buf) & 0x1FF8) >> 3; + /* frame size continued first 3 bits */ + adts_header[5] = (GST_BUFFER_SIZE (out_buf) & 0x7) << 5; + /* buffer fullness (0x7FF for VBR) over 5 last bits */ + adts_header[5] |= 0x1F; + /* buffer fullness (0x7FF for VBR) continued over 6 first bits + 2 zeros for + * number of raw data blocks */ + adts_header[6] = 0xFC; + + /* Insert ADTS header */ + memcpy (GST_BUFFER_DATA (out_buf) + out_offset, adts_header, 7); + out_offset += 7; + + /* Now copy complete frame */ + memcpy (GST_BUFFER_DATA (out_buf) + out_offset, GST_BUFFER_DATA (buf), + GST_BUFFER_SIZE (buf)); + + return out_buf; +} diff --git a/pool/shard006/C/0119499_trinity.c b/pool/shard006/C/0119499_trinity.c new file mode 100644 index 0000000000000000000000000000000000000000..dd32418411beda47bc25652f169bf0629424675d --- /dev/null +++ b/pool/shard006/C/0119499_trinity.c @@ -0,0 +1,183 @@ +#include +#include +#include +#include +#include +#include + +#include "arch.h" +#include "trinity.h" +#include "files.h" +#include "log.h" +#include "maps.h" +#include "pids.h" +#include "params.h" +#include "random.h" +#include "signals.h" +#include "shm.h" +#include "tables.h" +#include "ioctls.h" +#include "protocols.h" +#include "uid.h" +#include "config.h" // for VERSION +#include "taint.h" + +char *progname = NULL; + +unsigned int page_size; +unsigned int num_online_cpus; +unsigned int max_children; + +/* + * just in case we're not using the test.sh harness, we + * change to the tmp dir if it exists. + */ +static void change_tmp_dir(void) +{ + struct stat sb; + const char tmpdir[]="tmp/"; + int ret; + + /* Check if it exists, bail early if it doesn't */ + ret = (lstat(tmpdir, &sb)); + if (ret == -1) + return; + + /* Just in case a previous run screwed the perms. */ + ret = chmod(tmpdir, 0777); + if (ret == -1) + output(0, "Couldn't chmod %s to 0777.\n", tmpdir); + + ret = chdir(tmpdir); + if (ret == -1) + output(0, "Couldn't change to %s\n", tmpdir); +} + +int main(int argc, char* argv[]) +{ + int ret = EXIT_SUCCESS; + int childstatus; + pid_t pid; + const char taskname[13]="trinity-main"; + + outputstd("Trinity v" __stringify(VERSION) " Dave Jones \n"); + + progname = argv[0]; + + initpid = getpid(); + + init_uids(); + + page_size = getpagesize(); + num_online_cpus = sysconf(_SC_NPROCESSORS_ONLN); + max_children = num_online_cpus; /* possibly overridden in params. */ + + select_syscall_tables(); + + create_shm(); + + parse_args(argc, argv); + + create_shm_arrays(); + + if (logging == TRUE) + open_logfiles(); + + init_shm(); + + kernel_taint_initial = check_tainted(); + if (kernel_taint_initial != 0) + output(0, "Kernel was tainted on startup. Will ignore flags that are already set.\n"); + + if (munge_tables() == FALSE) { + ret = EXIT_FAILURE; + goto out; + } + + if (show_syscall_list == TRUE) { + dump_syscall_tables(); + goto out; + } + + init_syscalls(); + + if (show_ioctl_list == TRUE) { + dump_ioctls(); + goto out; + } + + do_uid0_check(); + + if (do_specific_proto == TRUE) + find_specific_proto(specific_proto_optarg); + + init_shared_pages(); + + parse_devices(); + + pids_init(); + + setup_main_signals(); + + change_tmp_dir(); + + /* check if we ctrl'c or something went wrong during init. */ + if (shm->exit_reason != STILL_RUNNING) + goto cleanup_fds; + + init_watchdog(); + + /* do an extra fork so that the watchdog and the children don't share a common parent */ + fflush(stdout); + pid = fork(); + if (pid == 0) { + shm->mainpid = getpid(); + + setup_main_signals(); + + output(0, "Main thread is alive.\n"); + prctl(PR_SET_NAME, (unsigned long) &taskname); + set_seed(0); + + if (setup_fds() == FALSE) { + shm->exit_reason = EXIT_FD_INIT_FAILURE; // FIXME: Later, push this down to multiple EXIT's. + _exit(EXIT_FAILURE); + } + + if (no_files == FALSE) { + if (files_in_index == 0) { + shm->exit_reason = EXIT_NO_FILES; + _exit(EXIT_FAILURE); + } + } + + if (dropprivs == TRUE) //FIXME: Push down into child processes later. + drop_privs(); + + main_loop(); + + _exit(EXIT_SUCCESS); + } + + /* wait for main loop process to exit. */ + (void)waitpid(pid, &childstatus, 0); + + /* wait for watchdog to exit. */ + waitpid(watchdog_pid, &childstatus, 0); + + output(0, "\nRan %ld syscalls. Successes: %ld Failures: %ld\n", + shm->total_syscalls_done - 1, shm->successes, shm->failures); + +cleanup_fds: + + close_sockets(); + + destroy_shared_mappings(); + + if (logging == TRUE) + close_logfiles(); + +out: + + exit(ret); +} diff --git a/pool/shard006/C/0119500_jogball_key.c b/pool/shard006/C/0119500_jogball_key.c new file mode 100644 index 0000000000000000000000000000000000000000..a107e165ae34a75034c5024c481222b589e9cc71 --- /dev/null +++ b/pool/shard006/C/0119500_jogball_key.c @@ -0,0 +1,336 @@ +/* + * Jogball driver for MSM platform. + * + * Copyright (c) 2008 QUALCOMM USA, INC. + * + * All source code in this file is licensed under the following license + * except where indicated. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, you can find it at http://www.fsf.org + * +*/ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Android Jogball KEY driver"); + +struct jogball_driver_data { + struct input_dev *jogball_input_dev; + int gpio_irq_up; + int gpio_irq_down; + int gpio_irq_left; + int gpio_irq_right; +//ZTE_XYC_PM_20100803 +#ifdef CONFIG_HAS_EARLYSUSPEND + struct early_suspend earlysuspend; +#endif +}; + +#define GPIO_JOGBALL_UP_INT MSM_GPIO_TO_INT(30) +#define GPIO_JOGBALL_DOWN_INT MSM_GPIO_TO_INT(38) +#define GPIO_JOGBALL_LEFT_INT MSM_GPIO_TO_INT(76) +#define GPIO_JOGBALL_RIGHT_INT MSM_GPIO_TO_INT(88) + +//#define TraceBall_TAG "ZL:[TraceBall]--" + +#define MAX_NUM 6 + +static irqreturn_t jogball_key_interrupt(int irq, void *dev_id) +{ + static int num_up_irq = 0; + static int num_down_irq = 0; + static int num_left_irq = 0; + static int num_right_irq = 0; + + bool report_key = 0; /* 1 ±íʾÐèÒªÉϱ¨Öµ*/ + + struct jogball_driver_data *dd_jogball = dev_id; + + struct input_dev *jogball_input_dev = dd_jogball->jogball_input_dev; + //pr_info(TraceBall_TAG"Enter into jogball_key_interrupt()"); + + //disable all the gpio irq + //disable_irq(GPIO_JOGBALL_UP_INT); + //disable_irq(GPIO_JOGBALL_LEFT_INT); + //disable_irq(GPIO_JOGBALL_DOWN_INT); + //disable_irq(GPIO_JOGBALL_RIGHT_INT); + + switch (irq) { + case GPIO_JOGBALL_UP_INT: + num_up_irq+=1; + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--GPIO_JOGBALL_UP_INT\n"); + break; + case GPIO_JOGBALL_DOWN_INT: + num_down_irq+=1; + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--GPIO_JOGBALL_DOWN_INT\n"); + break; + case GPIO_JOGBALL_LEFT_INT: + num_left_irq+=1; + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--GPIO_JOGBALL_LEFT_INT\n"); + break; + case GPIO_JOGBALL_RIGHT_INT: + num_right_irq+=1; + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--GPIO_JOGBALL_RIGHT_INT\n"); + break; + default: + break; + } + + //×îÏÈ´ïµ½MAX_NUM ´ÎÖжϵÄÉϱ¨¸Ã¼üÖµ( ¿ÉÒÔ¸ù¾ÝÇé¿öÉèÖøÃÖµ) + + if((MAX_NUM == num_up_irq)&&(0 == report_key)) + { + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report UP Key--Begin\n"); + report_key = 1; + /* µ÷ÓÃϵͳapi Éϱ¨( ·½Ïò: ÉÏ) */ + input_report_key(jogball_input_dev, KEY_UP, 1);/* °´ÏÂ*/ + input_report_key(jogball_input_dev, KEY_UP, 0);/* µ¯Æð*/ /* ϵͳֻÓÐÊÕµ½°´Ïº͵¯ÆðÁ½¸öʼþºó²Å»á´¦Àí£¬Ö»ÊÕµ½°´Ï£¬ÊDz»»á´¦ÀíµÄ*/ + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report UP Key--End\n"); + + } + else if((MAX_NUM == num_down_irq)&&(0 == report_key)) + { + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report DOWN Key--Begin\n"); + report_key = 1; + /* µ÷ÓÃϵͳapi Éϱ¨( ·½Ïò: ÏÂ) */ + input_report_key(jogball_input_dev, KEY_DOWN, 1); + input_report_key(jogball_input_dev, KEY_DOWN, 0); + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report DOWN Key--End\n"); + + } + else if((MAX_NUM == num_left_irq)&&(0 == report_key)) + { + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report LEFT Key--Begin\n"); + report_key = 1; + /* µ÷ÓÃϵͳapi Éϱ¨( ·½Ïò: ×ó) */ + input_report_key(jogball_input_dev, KEY_LEFT, 1); + input_report_key(jogball_input_dev, KEY_LEFT, 0); + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report LEFT Key--End\n"); + + } + else if((MAX_NUM == num_right_irq)&&(0 == report_key)) + { + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report RIGHT Key--Begin\n"); + report_key = 1; + /* µ÷ÓÃϵͳapi Éϱ¨( ·½Ïò: ÓÒ) */ + input_report_key(jogball_input_dev, KEY_RIGHT, 1); + input_report_key(jogball_input_dev, KEY_RIGHT, 0); + //pr_info(TraceBall_TAG "Enter into jogball_key_interrupt()--Report RIGHT Key--End\n"); + + } + + if(report_key) + { + num_up_irq = 0; + num_down_irq = 0; + num_left_irq = 0; + num_right_irq = 0; + report_key = 0; + } + + //enable all the gpio irq + //enable_irq(GPIO_JOGBALL_UP_INT); + //enable_irq(GPIO_JOGBALL_LEFT_INT); + //enable_irq(GPIO_JOGBALL_DOWN_INT); + //enable_irq(GPIO_JOGBALL_RIGHT_INT); + + return IRQ_HANDLED; + +} + +//ZTE_XYC_PM_20100803 +#ifdef CONFIG_HAS_EARLYSUSPEND +static void msmjb_early_suspend(struct early_suspend *h) +{ + disable_irq(GPIO_JOGBALL_UP_INT); + disable_irq(GPIO_JOGBALL_DOWN_INT); + disable_irq(GPIO_JOGBALL_LEFT_INT); + disable_irq(GPIO_JOGBALL_RIGHT_INT); +} + +static void msmjb_early_resume(struct early_suspend *h) +{ + enable_irq(GPIO_JOGBALL_UP_INT); + enable_irq(GPIO_JOGBALL_DOWN_INT); + enable_irq(GPIO_JOGBALL_LEFT_INT); + enable_irq(GPIO_JOGBALL_RIGHT_INT); +} +#endif + +static int __devinit jogball_key_probe(struct platform_device *pdev) +{ + int result; + struct input_dev *input_dev; + struct jogball_driver_data *dd_jogball; + struct jogball_key_platform_data *pd_jogball = pdev->dev.platform_data; + //pr_info(TraceBall_TAG "Enter into jogball_key_probe()\n"); + dd_jogball = kzalloc(sizeof(struct jogball_driver_data), GFP_KERNEL); + + input_dev = input_allocate_device(); + + if (!input_dev || !dd_jogball) { + result = -ENOMEM; + goto fail_alloc_mem; + } + + platform_set_drvdata(pdev,dd_jogball); + + dd_jogball->gpio_irq_up = pd_jogball->gpio_irq_up; + dd_jogball->gpio_irq_down = pd_jogball->gpio_irq_down; + dd_jogball->gpio_irq_left = pd_jogball->gpio_irq_left; + dd_jogball->gpio_irq_right = pd_jogball->gpio_irq_right; + + input_dev->name = "jogball_key"; + //input_dev->id.bustype = BUS_HOST; + //input_dev->id.vendor = 0x0001; + //input_dev->id.product = 0x0002; + //input_dev->id.version = 0x0100; + + //__set_bit(EV_KEY, input_dev->keybit); + + input_set_capability(input_dev,EV_KEY,KEY_UP); + input_set_capability(input_dev,EV_KEY,KEY_DOWN); + input_set_capability(input_dev,EV_KEY,KEY_LEFT); + input_set_capability(input_dev,EV_KEY,KEY_RIGHT); + + result = input_register_device(input_dev); + + if (result) { + goto fail_ip_reg; + } + + dd_jogball->jogball_input_dev = input_dev; + + result = request_irq(GPIO_JOGBALL_UP_INT, jogball_key_interrupt, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,"jogball_key", dd_jogball); + if (result) + goto fail_req_irq; + + result = request_irq(GPIO_JOGBALL_DOWN_INT, jogball_key_interrupt, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,"jogball_key", dd_jogball); + if (result) + goto fail_req_irq; + + result = request_irq(GPIO_JOGBALL_LEFT_INT, jogball_key_interrupt, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,"jogball_key", dd_jogball); + if (result) + goto fail_req_irq; + + result = request_irq(GPIO_JOGBALL_RIGHT_INT, jogball_key_interrupt, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,"jogball_key", dd_jogball); + if (result) + goto fail_req_irq; + + //platform_set_drvdata(pdev,dd_jogball); + +//ZTE_XYC_PM_20100803 +#ifdef CONFIG_HAS_EARLYSUSPEND + dd_jogball->earlysuspend.suspend = msmjb_early_suspend; + dd_jogball->earlysuspend.resume = msmjb_early_resume; + dd_jogball->earlysuspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 2; + register_early_suspend(&dd_jogball->earlysuspend); +#endif + + return 0; + +fail_req_irq: + +fail_ip_reg: + //pr_info(TraceBall_TAG "Enter into jogball_key_probe()--fail_ip_reg\n"); + input_unregister_device(input_dev); + input_dev = NULL; +fail_alloc_mem: + //pr_info(TraceBall_TAG "Enter into jogball_key_probe()--fail_alloc_mem\n"); + input_free_device(input_dev); + kfree(dd_jogball); + return result; + +} + +static int __devexit jogball_key_remove(struct platform_device *pdev) +{ + struct jogball_driver_data *dd_jogball = platform_get_drvdata(pdev); + + free_irq(GPIO_JOGBALL_UP_INT, dd_jogball); + free_irq(GPIO_JOGBALL_DOWN_INT, dd_jogball); + free_irq(GPIO_JOGBALL_LEFT_INT, dd_jogball); + free_irq(GPIO_JOGBALL_RIGHT_INT, dd_jogball); + + input_unregister_device(dd_jogball->jogball_input_dev); + + platform_set_drvdata(pdev, NULL); + + kfree(dd_jogball); + + return 0; +} +/*ZTE_HYJ_PM_20100524 begin*/ +#ifdef CONFIG_PM +int jogball_suspend(struct platform_device *pdev, pm_message_t state) +{ + disable_irq(GPIO_JOGBALL_UP_INT); + disable_irq(GPIO_JOGBALL_DOWN_INT); + disable_irq(GPIO_JOGBALL_LEFT_INT); + disable_irq(GPIO_JOGBALL_RIGHT_INT); + return 0; +} + +int jogball_resume(struct platform_device *pdev) +{ + enable_irq(GPIO_JOGBALL_UP_INT); + enable_irq(GPIO_JOGBALL_DOWN_INT); + enable_irq(GPIO_JOGBALL_LEFT_INT); + enable_irq(GPIO_JOGBALL_RIGHT_INT); + return 0; +} +#endif /* CONFIG_PM */ +/*ZTE_HYJ_PM_20100524 end*/ + +static struct platform_driver jogball_key_driver = { + .probe = jogball_key_probe, + .remove = __devexit_p(jogball_key_remove), +//ZTE_XYC_PM_20100803 +/* +#ifdef CONFIG_PM + .suspend = jogball_suspend, + .resume = jogball_resume, +#endif *//* CONFIG_PM */ + + .driver = { + .name = "jogball_key", + .owner = THIS_MODULE, + }, +}; + +static int __init jogball_key_init(void) +{ + return platform_driver_register(&jogball_key_driver); +} + +static void __exit jogball_key_exit(void) +{ + platform_driver_unregister(&jogball_key_driver); +} + +module_init(jogball_key_init); +module_exit(jogball_key_exit); + diff --git a/pool/shard006/C/0119502_anjay_dynamic.c b/pool/shard006/C/0119502_anjay_dynamic.c new file mode 100644 index 0000000000000000000000000000000000000000..d2d51747d82490f4bcf5dfae96755b623be63068 --- /dev/null +++ b/pool/shard006/C/0119502_anjay_dynamic.c @@ -0,0 +1,194 @@ +/* + * Copyright 2017-2021 AVSystem + * + * 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 + +#include +#include +#include + +#include + +#include "../anjay_core.h" +#include "../anjay_dm_core.h" +#include "../anjay_io_core.h" +#include "../coap/anjay_content_format.h" + +#include "anjay_vtable.h" + +VISIBILITY_SOURCE_BEGIN + +/////////////////////////////////////////////////////////////////////// ENCODING + +static anjay_unlocked_output_ctx_t *spawn_opaque(avs_stream_t *stream, + const anjay_uri_path_t *uri) { + (void) uri; + return _anjay_output_opaque_create(stream); +} + +#ifndef ANJAY_WITHOUT_PLAINTEXT +static anjay_unlocked_output_ctx_t *spawn_text(avs_stream_t *stream, + const anjay_uri_path_t *uri) { + (void) uri; + return _anjay_output_text_create(stream); +} +#endif // ANJAY_WITHOUT_PLAINTEXT + +#ifndef ANJAY_WITHOUT_TLV +static anjay_unlocked_output_ctx_t *spawn_tlv(avs_stream_t *stream, + const anjay_uri_path_t *uri) { + return _anjay_output_tlv_create(stream, uri); +} +#endif // ANJAY_WITHOUT_TLV + +#ifdef ANJAY_WITH_LWM2M_JSON +static anjay_unlocked_output_ctx_t *spawn_json(avs_stream_t *stream, + const anjay_uri_path_t *uri) { + return _anjay_output_senml_like_create(stream, uri, + AVS_COAP_FORMAT_OMA_LWM2M_JSON); +} +#endif // ANJAY_WITH_LWM2M_JSON + +typedef struct { + uint16_t format; + anjay_input_ctx_constructor_t *input_ctx_constructor; + anjay_unlocked_output_ctx_t *(*output_ctx_spawn_func)( + avs_stream_t *stream, const anjay_uri_path_t *uri); +} dynamic_format_def_t; + +static const dynamic_format_def_t SUPPORTED_SIMPLE_FORMATS[] = { + { AVS_COAP_FORMAT_OCTET_STREAM, _anjay_input_opaque_create, spawn_opaque }, +#ifndef ANJAY_WITHOUT_PLAINTEXT + { AVS_COAP_FORMAT_PLAINTEXT, _anjay_input_text_create, spawn_text }, +#endif // ANJAY_WITHOUT_PLAINTEXT + { AVS_COAP_FORMAT_NONE, NULL, NULL } +}; + +static const dynamic_format_def_t SUPPORTED_HIERARCHICAL_FORMATS[] = { +#ifndef ANJAY_WITHOUT_TLV + { AVS_COAP_FORMAT_OMA_LWM2M_TLV, _anjay_input_tlv_create, spawn_tlv }, +#endif // ANJAY_WITHOUT_TLV +#ifdef ANJAY_WITH_LWM2M_JSON + { AVS_COAP_FORMAT_OMA_LWM2M_JSON, NULL, spawn_json }, +#endif // ANJAY_WITH_LWM2M_JSON + { AVS_COAP_FORMAT_NONE, NULL, NULL } +}; + +AVS_STATIC_ASSERT(AVS_ARRAY_SIZE(SUPPORTED_HIERARCHICAL_FORMATS) > 1, + at_least_one_hierarchical_format_must_be_enabled); + +static const dynamic_format_def_t * +find_format(const dynamic_format_def_t *supported_formats, uint16_t format) { + for (const dynamic_format_def_t *candidate = supported_formats; + candidate->format != AVS_COAP_FORMAT_NONE; + ++candidate) { + if (_anjay_translate_legacy_content_format(format) + == candidate->format) { + return candidate; + } + } + return NULL; +} + +uint16_t _anjay_default_hierarchical_format(anjay_lwm2m_version_t version) { + (void) version; + return AVS_COAP_FORMAT_OMA_LWM2M_TLV; +} + +uint16_t _anjay_default_simple_format(anjay_unlocked_t *anjay, + anjay_lwm2m_version_t version) { + if (anjay->prefer_hierarchical_formats) { + return _anjay_default_hierarchical_format(version); + } + +#ifdef ANJAY_WITHOUT_PLAINTEXT + return _anjay_default_hierarchical_format(version); +#else // ANJAY_WITHOUT_PLAINTEXT + return AVS_COAP_FORMAT_PLAINTEXT; +#endif // ANJAY_WITHOUT_PLAINTEXT +} + +int _anjay_output_dynamic_construct(anjay_unlocked_output_ctx_t **out_ctx, + avs_stream_t *stream, + const anjay_uri_path_t *uri, + uint16_t format, + anjay_request_action_t action) { + if (format == AVS_COAP_FORMAT_NONE) { + return -1; + } + + const dynamic_format_def_t *def = NULL; + switch (action) { + case ANJAY_ACTION_READ: + (void) ((def = find_format(SUPPORTED_SIMPLE_FORMATS, format)) + || (def = find_format(SUPPORTED_HIERARCHICAL_FORMATS, format))); + break; + default: + break; + } + + if (!def || !def->output_ctx_spawn_func) { + anjay_log(DEBUG, + _("Could not find an appropriate output context for " + "format: ") "%" PRIu16, + format); + return ANJAY_ERR_NOT_ACCEPTABLE; + } + + if (!(*out_ctx = def->output_ctx_spawn_func(stream, uri))) { + return ANJAY_ERR_INTERNAL; + } + return 0; +} + +/////////////////////////////////////////////////////////////////////// DECODING + +int _anjay_input_dynamic_construct(anjay_unlocked_input_ctx_t **out, + avs_stream_t *stream, + const anjay_request_t *request) { + uint16_t format = request->content_format; + if (request->content_format == AVS_COAP_FORMAT_NONE) { + format = AVS_COAP_FORMAT_PLAINTEXT; + } + anjay_input_ctx_constructor_t *constructor = NULL; + const dynamic_format_def_t *def; + switch (request->action) { + case ANJAY_ACTION_WRITE: + case ANJAY_ACTION_WRITE_UPDATE: + case ANJAY_ACTION_CREATE: { + if ((def = find_format(SUPPORTED_SIMPLE_FORMATS, format)) + || (def = find_format(SUPPORTED_HIERARCHICAL_FORMATS, + format))) { + constructor = def->input_ctx_constructor; + } + break; + } + case ANJAY_ACTION_EXECUTE: + *out = NULL; + return 0; + default: + // Nothing to prepare - the action does not need an input context. + return 0; + } + if (constructor) { + return constructor(out, &stream, &request->uri); + } + return ANJAY_ERR_UNSUPPORTED_CONTENT_FORMAT; +} + +#ifdef ANJAY_TEST +# include "tests/core/io/dynamic.c" +#endif diff --git a/pool/shard006/C/0119512_printf_test.c b/pool/shard006/C/0119512_printf_test.c new file mode 100644 index 0000000000000000000000000000000000000000..c4476ca901877178a0c9a5e5243d38fc50dae1d4 --- /dev/null +++ b/pool/shard006/C/0119512_printf_test.c @@ -0,0 +1,41 @@ +#include +#include +#include + +static void test_printf() +{ + float a = -0.33947753; + float b = 0.93957519; + + sleep(2); + printf("%x %#x %#08x %#8x %-#8x %-#08x\n", &a, &a, &a, &a, &a, &a); + printf("%x %#x %#06x %#6x %-#6x %-#06x\n", &a, &a, &a, &a, &a, &a); + printf("f {x: %f, y: %f}\n", (float)123456789, (float)123456789); + printf("10f {x: %10f, y: %10f}\n", (float)123456789, (float)123456789); + printf("010f{x: %010f, y: %010f}\n", (float)123456789, (float)123456789); + printf("f {x: %f, y: %f}\n", (float)1234, (float)1234); + printf("8f {x: %8f, y: %-8f}\n", (float)1234, (float)1234); + printf("08f {x: %08f, y: %-08f}\n", (float)1234, (float)1234); + printf("f {x: %f, y: %f}\n", (float)-1234, (float)-1234); + printf("8f {x: %8f, y: %-8f}\n", (float)-1234, (float)-1234); + printf("08f {x: %08f, y: %-08f}\n", (float)-1234, (float)-1234); + printf(".2 {x: %.2f, y: %.2f}\n", (float)1234, (float)1234); + printf(".2 {x: %.2f, y: %.2f}\n", (float)0, (float)0); + printf("f {x: %f, y: %f}\n", a, b); + printf("8.2 {x: %8.2f, y: %8.2f}\n", a, b); + printf("8. {x: %8.f, y: %8.f}\n", a, b); + printf("08f {x: %08f, y: %08f}\n", a, b); + printf("08.2{x: %08.2f, y: %08.2f}\n", a, b); + printf(".2 {x: %.2f, y: %.2f}\n", a, b); + printf(".8 {x: %.8f, y: %.8f}\n", a, b); + printf(".08 {x: %.08f, y: %.08f}\n", a, b); + printf("-8.2{x: %-8.2f, y: %-8.2f}\n", a, b); + printf("-8. {x: %-8.f, y: %-8.f}\n", a, b); + printf("-08f{x: %-08f, y: %-08f}\n", a, b); + printf("08.2{x: %-08.2f, y: %-08.2f}\n", a, b); + printf("-.2 {x: %-.2f, y: %-.2f}\n", a, b); + printf("-08f{x: %-08f, y: %-08f}\n", (float)1234, (float)1234); + printf("-8f {x: %-8f, y: %-8f}\n", (float)1234, (float)1234); + printf("-8.2{x: %-8.2f, y: %-8.2f}\n", (float)1234, (float)1234); +} +//REGISTER_TASK(test_printf, 0, DEFAULT_PRIORITY); diff --git a/pool/shard006/C/0119513_ll.c b/pool/shard006/C/0119513_ll.c new file mode 100644 index 0000000000000000000000000000000000000000..b122ae96799425d610cd1383fae9cb9bf42ca671 --- /dev/null +++ b/pool/shard006/C/0119513_ll.c @@ -0,0 +1,159 @@ +#include +#include + +struct node +{ + int data; + struct node * link; +}; + +void prepend(struct node **, int); +void append(struct node **, int); +int count(struct node *); +void delete(struct node **, int); +void display(struct node *); +void insert_after(struct node *, int, int); + +int main(void) +{ + struct node *list; + list = NULL; + + printf("No of elements in linked list = %d\n", count(list) ); + + append(&list, 14); + append(&list, 30); + append(&list, 25); + append(&list, 42); + append(&list, 17); + printf("No of elements in linked list = %d\n", count(list) ); + display(list); + + prepend(&list, 999); + prepend(&list, 888); + prepend(&list, 777); + printf("No of elements in linked list = %d\n", count(list) ); + display(list); + + insert_after(list, 1, 0); + insert_after(list, 2, 1); + insert_after(list, 5, 99); + printf("No of elements in linked list = %d\n", count(list) ); + display(list); + + insert_after(list, 99, 10); + printf("No of elements in linked list = %d\n", count(list) ); + display(list); + + delete(&list, 99); + delete(&list, 1); + printf("No of elements in linked list = %d\n", count(list) ); + display(list); + + delete(&list, 10); + printf("No of elements in linked list = %d\n", count(list) ); + display(list); + + return 0; +} + +void prepend(struct node ** list, int num) +{ + struct node *temp; + temp = (struct node *) malloc(sizeof(struct node)); + temp -> data = num; + temp -> link = *list; + *list = temp; +} + +void append(struct node **list, int num) +{ + struct node *temp, *r; + if(*list == NULL) + { + temp = (struct node *) malloc (sizeof(struct node)); + temp -> data = num; + temp -> link = NULL; + *list = temp; + } + else + { + temp = *list; + while(temp -> link != NULL) + temp = temp -> link; + + r = (struct node *) malloc(sizeof(struct node)); + r -> data = num; + r -> link = NULL; + temp -> link = r; + } +} + +int count(struct node * list) +{ + int count = 0; + while(list != NULL) + { + list = list -> link; + count++; + } + return count; +} + +void delete(struct node ** list, int num) +{ + struct node *old, *temp; + temp = *list; + + while(temp != NULL) + { + if(temp -> data == num) + { + if (temp == *list) + { + *list = temp -> link; + } + else + old -> link = temp -> link; + free(temp); + return; + } + else + { + old = temp; + temp = temp -> link; + } + } + printf("Element %d not found in the supplied list\n", num); +} + +void display(struct node * list) +{ + while(list != NULL) + { + printf("%d ", list -> data); + list = list -> link; + } + printf("\n"); +} + +void insert_after(struct node * list, int location, int num) +{ + struct node *temp, *r; + int i; + temp = list; + for(i=0; i link; + if(temp == NULL) + { + printf("Length of list is %d but supplied location is %d\n", i, location); + return; + } + } + r = (struct node *) malloc (sizeof(struct node)); + r -> data = num; + r -> link = temp -> link; + temp -> link = r; +} + diff --git a/pool/shard006/C/0119515_highmem.c b/pool/shard006/C/0119515_highmem.c new file mode 100644 index 0000000000000000000000000000000000000000..c6d423dea1ae08380f40de5d435b09d34ac05737 --- /dev/null +++ b/pool/shard006/C/0119515_highmem.c @@ -0,0 +1,51 @@ + + +#include +#include + +void *kmap_atomic_prot(struct page *page, enum km_type type, pgprot_t prot) +{ + unsigned int idx; + unsigned long vaddr; + + /* even !CONFIG_PREEMPT needs this, for in_atomic in do_page_fault */ + pagefault_disable(); + if (!PageHighMem(page)) + return page_address(page); + + debug_kmap_atomic(type); + idx = type + KM_TYPE_NR*smp_processor_id(); + vaddr = __fix_to_virt(FIX_KMAP_BEGIN + idx); +#ifdef CONFIG_DEBUG_HIGHMEM + BUG_ON(!pte_none(*(kmap_pte-idx))); +#endif + __set_pte_at(&init_mm, vaddr, kmap_pte-idx, mk_pte(page, prot), 1); + local_flush_tlb_page(NULL, vaddr); + + return (void*) vaddr; +} +EXPORT_SYMBOL(kmap_atomic_prot); + +void kunmap_atomic(void *kvaddr, enum km_type type) +{ +#ifdef CONFIG_DEBUG_HIGHMEM + unsigned long vaddr = (unsigned long) kvaddr & PAGE_MASK; + enum fixed_addresses idx = type + KM_TYPE_NR*smp_processor_id(); + + if (vaddr < __fix_to_virt(FIX_KMAP_END)) { + pagefault_enable(); + return; + } + + BUG_ON(vaddr != __fix_to_virt(FIX_KMAP_BEGIN + idx)); + + /* + * force other mappings to Oops if they'll try to access + * this pte without first remap it + */ + pte_clear(&init_mm, vaddr, kmap_pte-idx); + local_flush_tlb_page(NULL, vaddr); +#endif + pagefault_enable(); +} +EXPORT_SYMBOL(kunmap_atomic); diff --git a/pool/shard006/C/0119517_jiq.c b/pool/shard006/C/0119517_jiq.c new file mode 100644 index 0000000000000000000000000000000000000000..6063697f390ab78d91de2983d588bd2111378dbb --- /dev/null +++ b/pool/shard006/C/0119517_jiq.c @@ -0,0 +1,265 @@ +/* + * jiq.c -- the just-in-queue module + * + * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet + * Copyright (C) 2001 O'Reilly & Associates + * + * The source code in this file can be freely used, adapted, + * and redistributed in source or binary form, so long as an + * acknowledgment appears in derived source files. The citation + * should list that the code comes from the book "Linux Device + * Drivers" by Alessandro Rubini and Jonathan Corbet, published + * by O'Reilly & Associates. No warranty is attached; + * we cannot take responsibility for errors or fitness for use. + * + */ + +#include +#include +#include + +#include +#include +#include /* everything... */ +#include +#include /* error codes */ +#include +#include +#include /* tasklets */ + +MODULE_LICENSE("Dual BSD/GPL"); + +/* + * The delay for the delayed workqueue timer file. + */ +static long delay = 1; +module_param(delay, long, 0); + + +/* + * This module is a silly one: it only embeds short code fragments + * that show how enqueued tasks `feel' the environment + */ + +#define LIMIT (PAGE_SIZE-128) /* don't print any more after this size */ + +/* + * Print information about the current environment. This is called from + * within the task queues. If the limit is reched, awake the reading + * process. + */ +static DECLARE_WAIT_QUEUE_HEAD (jiq_wait); + +/* + * Keep track of info we need between task queue runs. + */ +static struct clientdata { + struct work_struct jiq_work; + struct delayed_work jiq_delayed_work; + int len; + char *buf; + unsigned long jiffies; + long delay; +} jiq_data; + +#define SCHEDULER_QUEUE ((task_queue *) 1) + + + +static void jiq_print_tasklet(unsigned long); +static DECLARE_TASKLET(jiq_tasklet, jiq_print_tasklet, (unsigned long)&jiq_data); + + +/* + * Do the printing; return non-zero if the task should be rescheduled. + */ +static int jiq_print(void *ptr) +{ + struct clientdata *data = ptr; + int len = data->len; + char *buf = data->buf; + unsigned long j = jiffies; + + if (len > LIMIT) { + wake_up_interruptible(&jiq_wait); + return 0; + } + + if (len == 0) + len = sprintf(buf," time delta preempt pid cpu command\n"); + else + len =0; + + /* intr_count is only exported since 1.3.5, but 1.99.4 is needed anyways */ + len += sprintf(buf+len, "%9li %4li %3i %5i %3i %s\n", + j, j - data->jiffies, + preempt_count(), current->pid, smp_processor_id(), + current->comm); + + data->len += len; + data->buf += len; + data->jiffies = j; + return 1; +} + + +/* + * Call jiq_print from a work queue + */ +static void jiq_print_wq(struct work_struct *work) +{ + struct clientdata *data = container_of(work, struct clientdata, jiq_work); + + if (! jiq_print(data)) + return; + + schedule_work(&jiq_data.jiq_work); +} + +static void jiq_print_wq_delayed(struct work_struct *work) +{ + struct clientdata *data = container_of(work, struct clientdata, jiq_delayed_work.work); + + if (! jiq_print(data)) + return; + + schedule_delayed_work(&jiq_data.jiq_delayed_work, data->delay); +} + +static int jiq_read_wq(char *buf, char **start, off_t offset, + int len, int *eof, void *data) +{ + DEFINE_WAIT(wait); + + jiq_data.len = 0; /* nothing printed, yet */ + jiq_data.buf = buf; /* print in this place */ + jiq_data.jiffies = jiffies; /* initial time */ + jiq_data.delay = 0; + + prepare_to_wait(&jiq_wait, &wait, TASK_INTERRUPTIBLE); + schedule_work(&jiq_data.jiq_work); + schedule(); + finish_wait(&jiq_wait, &wait); + + *eof = 1; + return jiq_data.len; +} + + +static int jiq_read_wq_delayed(char *buf, char **start, off_t offset, + int len, int *eof, void *data) +{ + DEFINE_WAIT(wait); + + jiq_data.len = 0; /* nothing printed, yet */ + jiq_data.buf = buf; /* print in this place */ + jiq_data.jiffies = jiffies; /* initial time */ + jiq_data.delay = delay; + + prepare_to_wait(&jiq_wait, &wait, TASK_INTERRUPTIBLE); + schedule_delayed_work(&jiq_data.jiq_delayed_work, delay); + schedule(); + finish_wait(&jiq_wait, &wait); + + *eof = 1; + return jiq_data.len; +} + + + + +/* + * Call jiq_print from a tasklet + */ +static void jiq_print_tasklet(unsigned long ptr) +{ + if (jiq_print ((void *) ptr)) + tasklet_schedule (&jiq_tasklet); +} + + + +static int jiq_read_tasklet(char *buf, char **start, off_t offset, int len, + int *eof, void *data) +{ + jiq_data.len = 0; /* nothing printed, yet */ + jiq_data.buf = buf; /* print in this place */ + jiq_data.jiffies = jiffies; /* initial time */ + + tasklet_schedule(&jiq_tasklet); + interruptible_sleep_on(&jiq_wait); /* sleep till completion */ + + *eof = 1; + return jiq_data.len; +} + + + + +/* + * This one, instead, tests out the timers. + */ + +static struct timer_list jiq_timer; + +static void jiq_timedout(unsigned long ptr) +{ + jiq_print((void *)ptr); /* print a line */ + wake_up_interruptible(&jiq_wait); /* awake the process */ +} + + +static int jiq_read_run_timer(char *buf, char **start, off_t offset, + int len, int *eof, void *data) +{ + + jiq_data.len = 0; /* prepare the argument for jiq_print() */ + jiq_data.buf = buf; + jiq_data.jiffies = jiffies; + + init_timer(&jiq_timer); /* init the timer structure */ + jiq_timer.function = jiq_timedout; + jiq_timer.data = (unsigned long)&jiq_data; + jiq_timer.expires = jiffies + HZ; /* one second */ + + jiq_print(&jiq_data); /* print and go to sleep */ + add_timer(&jiq_timer); + interruptible_sleep_on(&jiq_wait); /* RACE */ + del_timer_sync(&jiq_timer); /* in case a signal woke us up */ + + *eof = 1; + return jiq_data.len; +} + + + +/* + * the init/clean material + */ + +static int jiq_init(void) +{ + + /* this line is in jiq_init() */ + INIT_WORK(&jiq_data.jiq_work, jiq_print_wq); + INIT_DELAYED_WORK(&jiq_data.jiq_delayed_work, jiq_print_wq_delayed); + + create_proc_read_entry("jiqwq", 0, NULL, jiq_read_wq, NULL); + create_proc_read_entry("jiqwqdelay", 0, NULL, jiq_read_wq_delayed, NULL); + create_proc_read_entry("jiqtimer", 0, NULL, jiq_read_run_timer, NULL); + create_proc_read_entry("jiqtasklet", 0, NULL, jiq_read_tasklet, NULL); + + return 0; /* succeed */ +} + +static void jiq_cleanup(void) +{ + remove_proc_entry("jiqwq", NULL); + remove_proc_entry("jiqwqdelay", NULL); + remove_proc_entry("jiqtimer", NULL); + remove_proc_entry("jiqtasklet", NULL); +} + + +module_init(jiq_init); +module_exit(jiq_cleanup); diff --git a/pool/shard006/C/0119518_extF80_to_f64.c b/pool/shard006/C/0119518_extF80_to_f64.c new file mode 100644 index 0000000000000000000000000000000000000000..3170870cf62ba5719d30fe1ef9170886ad622db9 --- /dev/null +++ b/pool/shard006/C/0119518_extF80_to_f64.c @@ -0,0 +1,83 @@ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California +(Regents). 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 two paragraphs of disclaimer. +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions, and the following two paragraphs of disclaimer in the +documentation and/or other materials provided with the distribution. Neither +the name of the Regents nor the names of its contributors may be used to +endorse or promote products derived from this software without specific prior +written permission. + +IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, +SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING +OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS +BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED +HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE +MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + +=============================================================================*/ + +#include +#include +#include "platform.h" +#include "internals.h" +#include "specialize.h" +#include "softfloat.h" + +float64_t extF80_to_f64( extFloat80_t a ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + bool sign; + int_fast32_t exp; + uint_fast64_t sig; + struct commonNaN commonNaN; + uint_fast64_t uiZ; + union ui64_f64 uZ; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + sign = signExtF80UI64( uiA64 ); + exp = expExtF80UI64( uiA64 ); + sig = uiA0; + if ( ! (exp | sig) ) { + uiZ = packToF64UI( sign, 0, 0 ); + goto uiZ; + } + if ( exp == 0x7FFF ) { + if ( sig & UINT64_C( 0x7FFFFFFFFFFFFFFF ) ) { + softfloat_extF80UIToCommonNaN( uiA64, uiA0, &commonNaN ); + uiZ = softfloat_commonNaNToF64UI( &commonNaN ); + } else { + uiZ = packToF64UI( sign, 0x7FF, 0 ); + } + goto uiZ; + } + sig = softfloat_shortShiftRightJam64( sig, 1 ); + exp -= 0x3C01; + if ( sizeof (int_fast16_t) < sizeof (int_fast32_t) ) { + if ( exp < -0x1000 ) exp = -0x1000; + } + return softfloat_roundPackToF64( sign, exp, sig ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + diff --git a/pool/shard006/C/0119519_qo1.c b/pool/shard006/C/0119519_qo1.c new file mode 100644 index 0000000000000000000000000000000000000000..b64dcb96577c40cfccfd10257b0e80a1f8e6db85 --- /dev/null +++ b/pool/shard006/C/0119519_qo1.c @@ -0,0 +1,206 @@ +/* + Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved. + + File: qo1.c + + Purpose: To demonstrate how to solve a quadratic optimization + problem using the MOSEK API. + */ + +#include + +#include "mosek.h" /* Include the MOSEK definition file. */ + +#define NUMCON 1 /* Number of constraints. */ +#define NUMVAR 3 /* Number of variables. */ +#define NUMANZ 3 /* Number of non-zeros in A. */ +#define NUMQNZ 4 /* Number of non-zeros in Q. */ + +static void MSKAPI printstr(void *handle, + MSKCONST char str[]) +{ + printf("%s",str); +} /* printstr */ + +int main(int argc,char *argv[]) +{ + + double c[] = {0.0,-1.0,0.0}; + + MSKboundkeye bkc[] = {MSK_BK_LO}; + double blc[] = {1.0}; + double buc[] = {+MSK_INFINITY}; + + MSKboundkeye bkx[] = {MSK_BK_LO, + MSK_BK_LO, + MSK_BK_LO}; + double blx[] = {0.0, + 0.0, + 0.0}; + double bux[] = {+MSK_INFINITY, + +MSK_INFINITY, + +MSK_INFINITY}; + + MSKint32t aptrb[] = {0, 1, 2}, + aptre[] = {1, 2, 3}, + asub[] = {0, 0, 0}; + double aval[] = {1.0, 1.0, 1.0}; + + MSKint32t qsubi[NUMQNZ]; + MSKint32t qsubj[NUMQNZ]; + double qval[NUMQNZ]; + + MSKint32t i,j; + double xx[NUMVAR]; + + MSKenv_t env = NULL; + MSKtask_t task = NULL; + MSKrescodee r; + + /* Create the mosek environment. */ + r = MSK_makeenv(&env,NULL); + + if ( r==MSK_RES_OK ) + { + /* Create the optimization task. */ + r = MSK_maketask(env,NUMCON,NUMVAR,&task); + + if ( r==MSK_RES_OK ) + { + r = MSK_linkfunctotaskstream(task,MSK_STREAM_LOG,NULL,printstr); + + /* Append 'NUMCON' empty constraints. + The constraints will initially have no bounds. */ + if ( r == MSK_RES_OK ) + r = MSK_appendcons(task,NUMCON); + + /* Append 'NUMVAR' variables. + The variables will initially be fixed at zero (x=0). */ + if ( r == MSK_RES_OK ) + r = MSK_appendvars(task,NUMVAR); + + /* Optionally add a constant term to the objective. */ + if ( r ==MSK_RES_OK ) + r = MSK_putcfix(task,0.0); + for(j=0; j. + */ +#include "enesim_private.h" + +#ifdef _WIN32 +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# undef WIN32_LEAN_AND_MEAN +#elif (defined (__MACH__) && defined (__APPLE__)) || defined (__FreeBSD__) +# include +#elif defined (__linux__) +# include +# include +#endif + +#if !defined(_WIN32) && !defined(HAVE_POSIX_MEMALIGN) +#include +#endif + +#include "enesim_mempool_aligned_private.h" +/*============================================================================* + * Local * + *============================================================================*/ +/** @cond internal */ +typedef struct _Enesim_Mempool_Aligned +{ + size_t alignment; +} Enesim_Mempool_Aligned; + +static int _init = 0; + +/* TODO parse the options */ +static void * _enesim_mempool_aligned_init(const char *context EINA_UNUSED, const char *options EINA_UNUSED, va_list args EINA_UNUSED) +{ + Enesim_Mempool_Aligned *thiz; + + thiz = calloc(1, sizeof(Enesim_Mempool_Aligned)); + /* TODO try to get the cache line size automatically */ + /* Remains Solaris and BSD* */ + /* TODO: Merge in Eina later */ +#ifdef _WIN32 + { + DWORD buffer_size = 0; + DWORD i; + SYSTEM_LOGICAL_PROCESSOR_INFORMATION *buffer = NULL; + + if (!GetLogicalProcessorInformation(NULL, &buffer_size)) + { + free(thiz); + return NULL; + } + buffer = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION *)malloc(buffer_size); + if (!buffer) + { + free(thiz); + return NULL; + } + if (!GetLogicalProcessorInformation(&buffer[0], &buffer_size)) + { + free(buffer); + free(thiz); + return NULL; + } + for (i = 0; i != buffer_size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); ++i) + { + if ((buffer[i].Relationship == RelationCache) && (buffer[i].Cache.Level == 1)) + { + thiz->alignment = buffer[i].Cache.LineSize; + break; + } + } + free(buffer); + if (thiz->alignment == 0) + { + free(thiz); + return NULL; + } + } +#elif (defined (__MACH__) && defined (__APPLE__)) || defined (__FreeBSD__) + { + size_t sizeof_line_size = sizeof(thiz->alignment); + + sysctlbyname("hw.cachelinesize", &thiz->alignment, &sizeof_line_size, 0, 0); + if (thiz->alignment == 0) + { + free(thiz); + return NULL; + } + } +#elif defined (__linux__) + { +# ifdef _SC_LEVEL1_DCACHE_LINESIZE + thiz->alignment = sysconf(_SC_LEVEL1_DCACHE_LINESIZE); +# else + FILE *p = NULL; + + p = fopen("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size", "rb"); + if (p) + { + fscanf(p, "%d", &thiz->alignment); + fclose(p); + } + if (thiz->alignment == 0) + { + free(thiz); + return NULL; + } +# endif + } +#else + thiz->alignment = 64; +#endif + return thiz; +} + +static void _enesim_mempool_aligned_free(void *data EINA_UNUSED, void *element) +{ + free(element); +} + +static void * _enesim_mempool_aligned_alloc(void *data, unsigned int size) +{ + Enesim_Mempool_Aligned *thiz = (Enesim_Mempool_Aligned *)data; + int ret; + +#ifdef HAVE_POSIX_MEMALIGN +#endif + void *element = NULL; + +#ifdef _WIN32 + element = _aligned_malloc(size, thiz->alignment); + if (!element) + return NULL; +#else +# ifdef HAVE_POSIX_MEMALIGN + ret = posix_memalign(&element, thiz->alignment, size); + if (ret) + return NULL; +# else + element = memalign(thiz->alignment, size); + if (!element) ret = -EINVAL; +# endif +#endif + return element; +} + +static void _enesim_mempool_aligned_shutdown(void *data) +{ + Enesim_Mempool_Aligned *thiz = data; + free(thiz); +} + +static Eina_Mempool_Backend _mempool_aligned = { + /* .name = */ "aligned", + /* .init = */ _enesim_mempool_aligned_init, + /* .free = */ _enesim_mempool_aligned_free, + /* .alloc = */ _enesim_mempool_aligned_alloc, + /* .realloc = */ NULL, + /* .garbage_collect = */ NULL, + /* .statistics = */ NULL, + /* .shutdown = */ _enesim_mempool_aligned_shutdown, + /* .repack = */ NULL, +}; +/*============================================================================* + * Global * + *============================================================================*/ +int enesim_mempool_aligned_init(void) +{ + if (!_init++) + { + eina_mempool_register(&_mempool_aligned); + } + return _init; +} + +int enesim_mempool_aligned_shutdown(void) +{ + if (--_init != 0) + return _init; + eina_mempool_unregister(&_mempool_aligned); + return _init; +} + +Eina_Mempool * enesim_mempool_aligned_get(void) +{ + static Eina_Mempool *m = NULL; + + if (!m) + { + m = eina_mempool_add("aligned", NULL, NULL); + } + return m; +} +/** @endcond */ diff --git a/pool/shard006/C/0119521_JpegDecode.c b/pool/shard006/C/0119521_JpegDecode.c new file mode 100644 index 0000000000000000000000000000000000000000..4bb929b6a5097c21b7f3937a9bc31e165a0965d2 --- /dev/null +++ b/pool/shard006/C/0119521_JpegDecode.c @@ -0,0 +1,282 @@ +/* + * The Python Imaging Library. + * $Id$ + * + * decoder for JPEG image data. + * + * history: + * 1996-05-02 fl Created + * 1996-05-05 fl Handle small JPEG files correctly + * 1996-05-28 fl Added "draft mode" support + * 1997-01-25 fl Added colour conversion override + * 1998-01-31 fl Adapted to libjpeg 6a + * 1998-07-12 fl Extended YCbCr support + * 1998-12-29 fl Added new state to handle suspension in multipass modes + * 2000-10-12 fl Suppress warnings + * 2000-12-04 fl Suppress errors beyond end of image data + * + * Copyright (c) 1998-2000 Secret Labs AB + * Copyright (c) 1996-2000 Fredrik Lundh + * + * See the README file for details on usage and redistribution. + */ + + +#include "Imaging.h" + +#ifdef HAVE_LIBJPEG + +#undef HAVE_PROTOTYPES +#undef HAVE_STDLIB_H +#undef HAVE_STDDEF_H +#undef UINT8 +#undef UINT16 +#undef UINT32 +#undef INT16 +#undef INT32 + +#include "Jpeg.h" + + +/* -------------------------------------------------------------------- */ +/* Suspending input handler */ +/* -------------------------------------------------------------------- */ + +METHODDEF(void) +stub(j_decompress_ptr cinfo) +{ + /* empty */ +} + +METHODDEF(boolean) +fill_input_buffer(j_decompress_ptr cinfo) +{ + /* Suspension */ + return FALSE; +} + +METHODDEF(void) +skip_input_data(j_decompress_ptr cinfo, long num_bytes) +{ + JPEGSOURCE* source = (JPEGSOURCE*) cinfo->src; + + if (num_bytes > (long) source->pub.bytes_in_buffer) { + /* We need to skip more data than we have in the buffer. + This will force the JPEG library to suspend decoding. */ + source->skip = num_bytes - source->pub.bytes_in_buffer; + source->pub.next_input_byte += source->pub.bytes_in_buffer; + source->pub.bytes_in_buffer = 0; + } else { + /* Skip portion of the buffer */ + source->pub.bytes_in_buffer -= num_bytes; + source->pub.next_input_byte += num_bytes; + source->skip = 0; + } +} + + +GLOBAL(void) +jpeg_buffer_src(j_decompress_ptr cinfo, JPEGSOURCE* source) +{ + cinfo->src = (void*) source; + + /* Prepare for suspending reader */ + source->pub.init_source = stub; + source->pub.fill_input_buffer = fill_input_buffer; + source->pub.skip_input_data = skip_input_data; + source->pub.resync_to_restart = jpeg_resync_to_restart; + source->pub.term_source = stub; + source->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ + + source->skip = 0; +} + + +/* -------------------------------------------------------------------- */ +/* Error handler */ +/* -------------------------------------------------------------------- */ + +METHODDEF(void) +error(j_common_ptr cinfo) +{ + JPEGERROR* error; + error = (JPEGERROR*) cinfo->err; + longjmp(error->setjmp_buffer, 1); +} + +METHODDEF(void) +output(j_common_ptr cinfo) +{ + /* nothing */ +} + +/* -------------------------------------------------------------------- */ +/* Decoder */ +/* -------------------------------------------------------------------- */ + +int +ImagingJpegDecode(Imaging im, ImagingCodecState state, UINT8* buf, int bytes) +{ + JPEGSTATE* context = (JPEGSTATE*) state->context; + int ok; + + if (setjmp(context->error.setjmp_buffer)) { + /* JPEG error handler */ + jpeg_destroy_decompress(&context->cinfo); + state->errcode = IMAGING_CODEC_BROKEN; + return -1; + } + + if (!state->state) { + + /* Setup decompression context */ + context->cinfo.err = jpeg_std_error(&context->error.pub); + context->error.pub.error_exit = error; + context->error.pub.output_message = output; + jpeg_create_decompress(&context->cinfo); + jpeg_buffer_src(&context->cinfo, &context->source); + + /* Ready to decode */ + state->state = 1; + + } + + /* Load the source buffer */ + context->source.pub.next_input_byte = buf; + context->source.pub.bytes_in_buffer = bytes; + + if (context->source.skip > 0) { + skip_input_data(&context->cinfo, context->source.skip); + if (context->source.skip > 0) + return context->source.pub.next_input_byte - buf; + } + + switch (state->state) { + + case 1: + + /* Read JPEG header, until we find an image body. */ + do { + + /* Note that we cannot return unless we have decoded + as much data as possible. */ + ok = jpeg_read_header(&context->cinfo, FALSE); + + } while (ok == JPEG_HEADER_TABLES_ONLY); + + if (ok == JPEG_SUSPENDED) + break; + + /* Decoder settings */ + + /* jpegmode indicates whats in the file; if not set, we'll + trust the decoder */ + if (strcmp(context->jpegmode, "L") == 0) + context->cinfo.jpeg_color_space = JCS_GRAYSCALE; + else if (strcmp(context->jpegmode, "RGB") == 0) + context->cinfo.jpeg_color_space = JCS_RGB; + else if (strcmp(context->jpegmode, "CMYK") == 0) + context->cinfo.jpeg_color_space = JCS_CMYK; + else if (strcmp(context->jpegmode, "YCbCr") == 0) + context->cinfo.jpeg_color_space = JCS_YCbCr; + else if (strcmp(context->jpegmode, "YCbCrK") == 0) { + context->cinfo.jpeg_color_space = JCS_YCCK; + } + + /* rawmode indicates what we want from the decoder. if not + set, conversions are disabled */ + if (strcmp(context->rawmode, "L") == 0) + context->cinfo.out_color_space = JCS_GRAYSCALE; + else if (strcmp(context->rawmode, "RGB") == 0) + context->cinfo.out_color_space = JCS_RGB; + else if (strcmp(context->rawmode, "CMYK") == 0 || + strcmp(context->rawmode, "CMYK;I") == 0) + context->cinfo.out_color_space = JCS_CMYK; + else if (strcmp(context->rawmode, "YCbCr") == 0) + context->cinfo.out_color_space = JCS_YCbCr; + else if (strcmp(context->rawmode, "YCbCrK") == 0) + context->cinfo.out_color_space = JCS_YCCK; + else { + /* Disable decoder conversions */ + context->cinfo.jpeg_color_space = JCS_UNKNOWN; + context->cinfo.out_color_space = JCS_UNKNOWN; + } + + if (context->scale > 1) { + context->cinfo.scale_num = 1; + context->cinfo.scale_denom = context->scale; + } + if (context->draft) { + context->cinfo.do_fancy_upsampling = FALSE; + context->cinfo.dct_method = JDCT_FASTEST; + } + + state->state++; + /* fall through */ + + case 2: + + /* Set things up for decompression (this processes the entire + file if necessary to return data line by line) */ + if (!jpeg_start_decompress(&context->cinfo)) + break; + + state->state++; + /* fall through */ + + case 3: + + /* Decompress a single line of data */ + ok = 1; + while (state->y < state->ysize) { + ok = jpeg_read_scanlines(&context->cinfo, &state->buffer, 1); + if (ok != 1) + break; + state->shuffle((UINT8*) im->image[state->y + state->yoff] + + state->xoff * im->pixelsize, state->buffer, + state->xsize); + state->y++; + } + if (ok != 1) + break; + state->state++; + /* fall through */ + + case 4: + + /* Finish decompression */ + if (!jpeg_finish_decompress(&context->cinfo)) { + /* FIXME: add strictness mode test */ + if (state->y < state->ysize) + break; + } + + /* Clean up */ + jpeg_destroy_decompress(&context->cinfo); + /* if (jerr.pub.num_warnings) return BROKEN; */ + return -1; + + } + + /* Return number of bytes consumed */ + return context->source.pub.next_input_byte - buf; + +} + +/* -------------------------------------------------------------------- */ +/* Cleanup */ +/* -------------------------------------------------------------------- */ + +int ImagingJpegDecodeCleanup(ImagingCodecState state){ + /* called to free the decompression engine when the decode terminates + due to a corrupt or truncated image + */ + JPEGSTATE* context = (JPEGSTATE*) state->context; + + /* Clean up */ + jpeg_destroy_decompress(&context->cinfo); + return -1; +} + +#endif + diff --git a/pool/shard006/C/0119525_interrupt.c b/pool/shard006/C/0119525_interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..88c8a67472b3db55c09762cb8341aadcb5de0001 --- /dev/null +++ b/pool/shard006/C/0119525_interrupt.c @@ -0,0 +1,56 @@ +#include + +static funcptr isr[32] = {[0 ... 31] = NULL}; + +/* +interrupt management routines +*/ +void _irq_register(uint32_t mask, funcptr ptr) +{ + int32_t i; + + for (i = 0; i < 32; ++i) + if (mask & (1 << i)) + isr[i] = ptr; +} + +void _irq_handler(uint32_t cause, uint32_t *stack) +{ + int32_t i = 0; + +#if KERNEL_LOG >= 1 + dprintf("irq%x %d ", cause, (uint32_t)_read_us()); +#endif + krnl_pcb.interrupts++; + do { + if (cause & 0x1){ + if(isr[i]){ + isr[i](stack); + } + } + cause >>= 1; + ++i; + } while(cause); +} + +void _irq_mask_set(uint32_t mask) +{ + uint32_t m; + + m = IRQ_MASK; + m |= mask; + IRQ_MASK = m; +} + +void _irq_mask_clr(uint32_t mask) +{ + uint32_t m; + + m = IRQ_MASK; + m &= ~mask; + IRQ_MASK = m; +} + +void _exception_handler(uint32_t epc, uint32_t opcode) +{ +} diff --git a/pool/shard006/C/0119528_panel-s-wqxga-10-1.c b/pool/shard006/C/0119528_panel-s-wqxga-10-1.c new file mode 100644 index 0000000000000000000000000000000000000000..c5a1a23ab3a9d1ec967d16baa571b0a538286680 --- /dev/null +++ b/pool/shard006/C/0119528_panel-s-wqxga-10-1.c @@ -0,0 +1,220 @@ +/* + * arch/arm/mach-tegra/panel-s-wqxga-10-1.c + * + * Copyright (c) 2012-2014, NVIDIA CORPORATION. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include + +#include "board.h" +#include "board-panel.h" +#include "devices.h" +#include "gpio-names.h" + +#define DSI_PANEL_RESET 1 + +static bool reg_requested; +static struct regulator *avdd_lcd_3v3; +static struct regulator *vdd_lcd_bl; +static struct regulator *vdd_lcd_bl_en; +static struct regulator *dvdd_lcd_1v8; +static u16 en_panel_rst; + +static int dalmore_dsi_regulator_get(struct device *dev) +{ + int err = 0; + + if (reg_requested) + return 0; + dvdd_lcd_1v8 = regulator_get(dev, "dvdd_lcd"); + if (IS_ERR(dvdd_lcd_1v8)) { + pr_err("dvdd_lcd regulator get failed\n"); + err = PTR_ERR(dvdd_lcd_1v8); + dvdd_lcd_1v8 = NULL; + goto fail; + } + avdd_lcd_3v3 = regulator_get(dev, "avdd_lcd"); + if (IS_ERR(avdd_lcd_3v3)) { + pr_err("avdd_lcd regulator get failed\n"); + err = PTR_ERR(avdd_lcd_3v3); + avdd_lcd_3v3 = NULL; + goto fail; + } + + vdd_lcd_bl = regulator_get(dev, "vdd_lcd_bl"); + if (IS_ERR(vdd_lcd_bl)) { + pr_err("vdd_lcd_bl regulator get failed\n"); + err = PTR_ERR(vdd_lcd_bl); + vdd_lcd_bl = NULL; + goto fail; + } + + vdd_lcd_bl_en = regulator_get(dev, "vdd_lcd_bl_en"); + if (IS_ERR(vdd_lcd_bl_en)) { + pr_err("vdd_lcd_bl_en regulator get failed\n"); + err = PTR_ERR(vdd_lcd_bl_en); + vdd_lcd_bl_en = NULL; + goto fail; + } + reg_requested = true; + return 0; +fail: + return err; +} + +static int dsi_s_wqxga_10_1_postpoweron(struct device *dev) +{ + int err = 0; + + err = dalmore_dsi_regulator_get(dev); + if (err < 0) { + pr_err("dsi regulator get failed\n"); + goto fail; + } + + err = tegra_panel_gpio_get_dt("s,wqxga-10-1", &panel_of); + if (err < 0) { + pr_err("dsi gpio request failed\n"); + goto fail; + } + + /* If panel rst gpio is specified in device tree, + * use that. + */ + if (gpio_is_valid(panel_of.panel_gpio[TEGRA_GPIO_RESET])) + en_panel_rst = panel_of.panel_gpio[TEGRA_GPIO_RESET]; + + if (dvdd_lcd_1v8) { + err = regulator_enable(dvdd_lcd_1v8); + if (err < 0) { + pr_err("dvdd_lcd regulator enable failed\n"); + goto fail; + } + } + + if (avdd_lcd_3v3) { + err = regulator_enable(avdd_lcd_3v3); + if (err < 0) { + pr_err("avdd_lcd regulator enable failed\n"); + goto fail; + } + } + + /* panel ic requirement after vcc enable */ + msleep(260); + + if (vdd_lcd_bl) { + err = regulator_enable(vdd_lcd_bl); + if (err < 0) { + pr_err("vdd_lcd_bl regulator enable failed\n"); + goto fail; + } + } + + if (vdd_lcd_bl_en) { + err = regulator_enable(vdd_lcd_bl_en); + if (err < 0) { + pr_err("vdd_lcd_bl_en regulator enable failed\n"); + goto fail; + } + } + + msleep(20); +#if DSI_PANEL_RESET + /* use platform data */ + gpio_direction_output(en_panel_rst, 1); + usleep_range(1000, 5000); + gpio_set_value(en_panel_rst, 0); + usleep_range(1000, 5000); + gpio_set_value(en_panel_rst, 1); + msleep(20); +#endif + + return 0; +fail: + return err; +} + +static int dsi_s_wqxga_10_1_enable(struct device *dev) +{ + return 0; +} + +static int dsi_s_wqxga_10_1_disable(struct device *dev) +{ + if (vdd_lcd_bl) + regulator_disable(vdd_lcd_bl); + + if (vdd_lcd_bl_en) + regulator_disable(vdd_lcd_bl_en); + + if (avdd_lcd_3v3) + regulator_disable(avdd_lcd_3v3); + + if (dvdd_lcd_1v8) + regulator_disable(dvdd_lcd_1v8); + + return 0; +} + +static int dsi_s_wqxga_10_1_postsuspend(void) +{ + return 0; +} + +static int dsi_s_wqxga_10_1_bl_notify(struct device *dev, int brightness) +{ + struct backlight_device *bl = NULL; + struct pwm_bl_data *pb = NULL; + int cur_sd_brightness = atomic_read(&sd_brightness); + bl = (struct backlight_device *)dev_get_drvdata(dev); + pb = (struct pwm_bl_data *)dev_get_drvdata(&bl->dev); + + /* SD brightness is a percentage */ + brightness = (brightness * cur_sd_brightness) / 255; + + /* Apply any backlight response curve */ + if (brightness > 255) + pr_info("Error: Brightness > 255!\n"); + else if (pb->bl_measured) + brightness = pb->bl_measured[brightness]; + + return brightness; +} + +static int dsi_s_wqxga_10_1_check_fb(struct device *dev, struct fb_info *info) +{ + struct platform_device *pdev = NULL; + pdev = to_platform_device(bus_find_device_by_name( + &platform_bus_type, NULL, "tegradc.0")); + return info->device == &pdev->dev; +} + +static struct pwm_bl_data_dt_ops dsi_s_wqxga_10_1_pwm_bl_ops = { + .notify = dsi_s_wqxga_10_1_bl_notify, + .check_fb = dsi_s_wqxga_10_1_check_fb, + .blnode_compatible = "s,wqxga-10-1-bl", +}; + +struct tegra_panel_ops dsi_s_wqxga_10_1_ops = { + .enable = dsi_s_wqxga_10_1_enable, + .disable = dsi_s_wqxga_10_1_disable, + .postpoweron = dsi_s_wqxga_10_1_postpoweron, + .postsuspend = dsi_s_wqxga_10_1_postsuspend, + .pwm_bl_ops = &dsi_s_wqxga_10_1_pwm_bl_ops, +}; diff --git a/pool/shard006/C/0119532_csrc-rlx.c b/pool/shard006/C/0119532_csrc-rlx.c new file mode 100644 index 0000000000000000000000000000000000000000..f727df8980005124777588200a909a3d7f501cdf --- /dev/null +++ b/pool/shard006/C/0119532_csrc-rlx.c @@ -0,0 +1,36 @@ +/* + * 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. + * + * Copyright (C) 2007 by Ralf Baechle + * + * Modified for RLX Linux for RLX + * Copyright (C) 2008-2012 Tony Wu (tonywu@realtek.com) + */ +#include +#include + +#include + +static cycle_t c0_hpt_read(struct clocksource *cs) +{ + return read_c0_count(); +} + +static struct clocksource clocksource_rlx = { + .name = "RLX", + .read = c0_hpt_read, + .mask = CLOCKSOURCE_MASK(32), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, +}; + +int __init rlx_clocksource_init(void) +{ + /* Calculate a somewhat reasonable rating value */ + clocksource_rlx.rating = 200 + rlx_hpt_frequency / 10000000; + + clocksource_register_hz(&clocksource_rlx, rlx_hpt_frequency); + + return 0; +} diff --git a/pool/shard006/C/0119533_mydump.c b/pool/shard006/C/0119533_mydump.c new file mode 100644 index 0000000000000000000000000000000000000000..0d08e2ed124da21367ef95967bede76de1459fef --- /dev/null +++ b/pool/shard006/C/0119533_mydump.c @@ -0,0 +1,77 @@ +/* + This file is part of RIBS2.0 (Robust Infrastructure for Backend Systems). + RIBS is an infrastructure for building great SaaS applications (but not + limited to). + + Copyright (C) 2013,2014 Adap.tv, Inc. + + RIBS 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, version 2.1 of the License. + + RIBS 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 RIBS. If not, see . +*/ +#include "ribs.h" +#include "mydump_data.h" + +int main(void){ + + /* initialize and load the dump data */ + if (0 > mydump_data_init() || + 0 > mydump_data_load()) + exit(EXIT_FAILURE); + + int id = 1; + + /* get values from index where id = {1, 2, 3, 4} */ + for(id=1; id <= 4; id++) + { + /* the other table columns */ + int32_t age; + char *name; + + /* location of data from index lookup */ + uint32_t loc = 0; + + /* char pointer to beginning of name in data */ + char *result = ""; + + /* size of name data, since variable size */ + size_t result_size = 0; + + /* index lookup will return -1 if key not found */ + if( 0> IDX_CONTAINER_O2O_LOOKUP(int32_t, + &data[active].test_test_table_id_idx, id, &loc)) + { + printf("index key [%d] not found\n", id); + } + + /* else retrieve results */ + else { + /* get age at loc */ + age = DS_FIELD_GET_VAL(&data[active].test_test_table_age, loc); + + /* get char pointer at beginning of data at loc */ + ds_var_field_get(&data[active].test_test_table_name, + loc, &result, &result_size); + + /* allocate memory to name according to result size */ + name = ribs_malloc(result_size + 1); + + /* copy over 'result_size' number of characters from result + into name */ + strncpy(name, result, result_size); + + /* print result */ + printf("| %d | %s | %d |\n", id, name, age); + } + } + + return 0; +} diff --git a/pool/shard006/C/0119534_superio.c b/pool/shard006/C/0119534_superio.c new file mode 100644 index 0000000000000000000000000000000000000000..f89607857e4ec90b4a74d28b2472cdb94db705b9 --- /dev/null +++ b/pool/shard006/C/0119534_superio.c @@ -0,0 +1,103 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2008 Sean Nelson + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "chip.h" +#include "w83697hf.h" + +static void hwmon_set_fan_divisor(unsigned int base, int num, unsigned int divisor) { + unsigned char enc, buf; + + if (divisor) { + enc = log2(divisor); + if (1 << enc != divisor || enc > 7) + die("invalid fan divisor"); + outb(0x4e, base + 5); + outb(0x00, base + 6); + outb(0x47, base + 5); + outb((inb(base + 6) & ~(0x30 << (num * 2))) | ((enc & 3) << (4 + num * 2)), base + 6); + outb(0x5d, base + 5); + buf = inb(base + 6); + /* the above inb() auto-increments the address pointer ... */ + outb(0x5d, base + 5); + outb((buf & ~(0x20 << num)) | ((enc & 4) << (3 + num)), base + 6); + } +} + +static void w83697hf_init(device_t dev) +{ + struct resource *res0; + struct superio_winbond_w83697hf_config *cfg; + + if (!dev->enabled) + return; + + cfg = dev->chip_info; + + switch (dev->path.pnp.device) { + case W83697HF_HWM: + if (cfg) { + res0 = find_resource(dev, PNP_IDX_IO0); + hwmon_set_fan_divisor(res0->base, 0, cfg->hwmon_fan1_divisor); + hwmon_set_fan_divisor(res0->base, 1, cfg->hwmon_fan2_divisor); + } + break; + } +} + +static struct device_operations ops = { + .read_resources = pnp_read_resources, + .set_resources = pnp_set_resources, + .enable_resources = pnp_enable_resources, + .enable = pnp_alt_enable, + .init = w83697hf_init, + .ops_pnp_mode = &pnp_conf_mode_8787_aa, +}; + +static struct pnp_info pnp_dev_info[] = { + { &ops, W83697HF_FDC, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0, {0x07f8, 0}, }, + { &ops, W83697HF_PP, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0, {0x07f8, 0}, }, + { &ops, W83697HF_SP1, PNP_IO0 | PNP_IRQ0, {0x07f8, 0}, }, + { &ops, W83697HF_SP2, PNP_IO0 | PNP_IRQ0, {0x07f8, 0}, }, + { &ops, W83697HF_CIR, PNP_IO0 | PNP_IRQ0, {0x07f8, 0}, }, + { &ops, W83697HF_GAME_GPIO1, PNP_IO0 | PNP_IO1 | PNP_IRQ0, {0x07ff, 0}, {0x07fe, 4}, }, + { &ops, W83697HF_MIDI_GPIO5, }, + { &ops, W83697HF_GPIO234, }, + { &ops, W83697HF_ACPI, }, + { &ops, W83697HF_HWM, PNP_IO0 | PNP_IRQ0, {0x0ff8, 0}, }, +}; + +static void enable_dev(struct device *dev) +{ + pnp_enable_devices(dev, &ops, ARRAY_SIZE(pnp_dev_info), pnp_dev_info); +} + +struct chip_operations superio_winbond_w83697hf_ops = { + CHIP_NAME("Winbond W83697HF Super I/O") + .enable_dev = enable_dev, +}; diff --git a/pool/shard006/C/0119543_ClockMeter.c b/pool/shard006/C/0119543_ClockMeter.c new file mode 100644 index 0000000000000000000000000000000000000000..8d42b24b5112e871165b3c860b8e82b370dc0514 --- /dev/null +++ b/pool/shard006/C/0119543_ClockMeter.c @@ -0,0 +1,36 @@ +/* +htop +(C) 2004-2006 Hisham H. Muhammad +Released under the GNU GPL, see the COPYING file +in the source distribution for its full text. +*/ + +#include "ClockMeter.h" +#include "Meter.h" + +#include + +#include "debug.h" + +int ClockMeter_attributes[] = { + CLOCK +}; + +static void ClockMeter_setValues(Meter* this, char* buffer, int size) { + time_t t = time(NULL); + struct tm *lt = localtime(&t); + this->values[0] = lt->tm_hour * 60 + lt->tm_min; + strftime(buffer, size, "%H:%M:%S", lt); +} + +MeterType ClockMeter = { + .setValues = ClockMeter_setValues, + .display = NULL, + .mode = TEXT_METERMODE, + .total = 100.0, + .items = 1, + .attributes = ClockMeter_attributes, + .name = "Clock", + .uiName = "Clock", + .caption = "Time: ", +}; diff --git a/pool/shard006/C/0119548_sandbox_rtc.c b/pool/shard006/C/0119548_sandbox_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..b08d758a74ef596222512ac32ecd7e459660a7f1 --- /dev/null +++ b/pool/shard006/C/0119548_sandbox_rtc.c @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * (C) Copyright 2015 Google, Inc + * Written by Simon Glass + */ + +#include +#include +#include +#include +#include + +#define REG_COUNT 0x80 + +static int sandbox_rtc_get(struct udevice *dev, struct rtc_time *time) +{ + time->tm_sec = dm_i2c_reg_read(dev, REG_SEC); + if (time->tm_sec < 0) + return time->tm_sec; + time->tm_min = dm_i2c_reg_read(dev, REG_MIN); + if (time->tm_min < 0) + return time->tm_min; + time->tm_hour = dm_i2c_reg_read(dev, REG_HOUR); + if (time->tm_hour < 0) + return time->tm_hour; + time->tm_mday = dm_i2c_reg_read(dev, REG_MDAY); + if (time->tm_mday < 0) + return time->tm_mday; + time->tm_mon = dm_i2c_reg_read(dev, REG_MON); + if (time->tm_mon < 0) + return time->tm_mon; + time->tm_year = dm_i2c_reg_read(dev, REG_YEAR); + if (time->tm_year < 0) + return time->tm_year; + time->tm_year += 1900; + time->tm_wday = dm_i2c_reg_read(dev, REG_WDAY); + if (time->tm_wday < 0) + return time->tm_wday; + + return 0; +} + +static int sandbox_rtc_set(struct udevice *dev, const struct rtc_time *time) +{ + int ret; + + ret = dm_i2c_reg_write(dev, REG_SEC, time->tm_sec); + if (ret < 0) + return ret; + ret = dm_i2c_reg_write(dev, REG_MIN, time->tm_min); + if (ret < 0) + return ret; + ret = dm_i2c_reg_write(dev, REG_HOUR, time->tm_hour); + if (ret < 0) + return ret; + ret = dm_i2c_reg_write(dev, REG_MDAY, time->tm_mday); + if (ret < 0) + return ret; + ret = dm_i2c_reg_write(dev, REG_MON, time->tm_mon); + if (ret < 0) + return ret; + ret = dm_i2c_reg_write(dev, REG_YEAR, time->tm_year - 1900); + if (ret < 0) + return ret; + ret = dm_i2c_reg_write(dev, REG_WDAY, time->tm_wday); + if (ret < 0) + return ret; + + return 0; +} + +static int sandbox_rtc_reset(struct udevice *dev) +{ + return dm_i2c_reg_write(dev, REG_RESET, 0); +} + +static int sandbox_rtc_read8(struct udevice *dev, unsigned int reg) +{ + return dm_i2c_reg_read(dev, reg); +} + +static int sandbox_rtc_write8(struct udevice *dev, unsigned int reg, int val) +{ + return dm_i2c_reg_write(dev, reg, val); +} + +static const struct rtc_ops sandbox_rtc_ops = { + .get = sandbox_rtc_get, + .set = sandbox_rtc_set, + .reset = sandbox_rtc_reset, + .read8 = sandbox_rtc_read8, + .write8 = sandbox_rtc_write8, +}; + +static const struct udevice_id sandbox_rtc_ids[] = { + { .compatible = "sandbox-rtc" }, + { } +}; + +U_BOOT_DRIVER(rtc_sandbox) = { + .name = "rtc-sandbox", + .id = UCLASS_RTC, + .of_match = sandbox_rtc_ids, + .ops = &sandbox_rtc_ops, +}; diff --git a/pool/shard006/C/0119552_skypeweb_util.c b/pool/shard006/C/0119552_skypeweb_util.c new file mode 100644 index 0000000000000000000000000000000000000000..12b2e397a92c7ad6a86882039f03f58a9b82a70d --- /dev/null +++ b/pool/shard006/C/0119552_skypeweb_util.c @@ -0,0 +1,248 @@ +/* + * SkypeWeb Plugin for libpurple/Pidgin + * Copyright (c) 2014-2015 Eion Robb + * + * 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 . + */ + +#include "skypeweb_util.h" + +#include + +gchar * +skypeweb_string_get_chunk(const gchar *haystack, gsize len, const gchar *start, const gchar *end) +{ + const gchar *chunk_start, *chunk_end; + g_return_val_if_fail(haystack && start && end, NULL); + + if (len > 0) { + chunk_start = g_strstr_len(haystack, len, start); + } else { + chunk_start = strstr(haystack, start); + } + g_return_val_if_fail(chunk_start, NULL); + chunk_start += strlen(start); + + if (len > 0) { + chunk_end = g_strstr_len(chunk_start, len - (chunk_start - haystack), end); + } else { + chunk_end = strstr(chunk_start, end); + } + g_return_val_if_fail(chunk_end, NULL); + + return g_strndup(chunk_start, chunk_end - chunk_start); +} + +gchar * +skypeweb_jsonobj_to_string(JsonObject *jsonobj) +{ + JsonGenerator *generator; + JsonNode *root; + gchar *string; + + root = json_node_new(JSON_NODE_OBJECT); + json_node_set_object(root, jsonobj); + + generator = json_generator_new(); + json_generator_set_root(generator, root); + + string = json_generator_to_data(generator, NULL); + + g_object_unref(generator); + json_node_free(root); + + return string; +} + +/** turn https://bay-client-s.gateway.messenger.live.com/v1/users/ME/contacts/8:eionrobb + or https://bay-client-s.gateway.messenger.live.com/v1/users/8:eionrobb/presenceDocs/messagingService + into eionrobb +*/ +const gchar * +skypeweb_contact_url_to_name(const gchar *url) +{ + static gchar *tempname = NULL; + const gchar *start, *end; + + start = g_strrstr(url, "/8:"); + if (!start) return NULL; + start = start + 3; + + if ((end = strchr(start, '/'))) { + g_free(tempname); + tempname = g_strndup(start, end - start); + return tempname; + } + + g_free(tempname); + tempname = g_strdup(start); + return tempname; +} + +/** turn https://bay-client-s.gateway.messenger.live.com/v1/users/ME/conversations/19:blah@thread.skype + into 19:blah@thread.skype +*/ +const gchar * +skypeweb_thread_url_to_name(const gchar *url) +{ + static gchar *tempname = NULL; + const gchar *start, *end; + + start = g_strrstr(url, "/19:"); + if (!start) return NULL; + start = start + 1; + + if ((end = strchr(start, '/'))) { + g_free(tempname); + tempname = g_strndup(start, end - start); + return tempname; + } + + return start; +} + +/** Blatantly stolen from MSN prpl, with super-secret SHA256 change! */ +#define BUFSIZE 256 +char * +skypeweb_hmac_sha256(char *input) +{ + PurpleCipher *cipher; + PurpleCipherContext *context; + const guchar productKey[] = SKYPEWEB_LOCKANDKEY_SECRET; + const guchar productID[] = SKYPEWEB_LOCKANDKEY_APPID; + const char hexChars[] = "0123456789abcdef"; + char buf[BUFSIZE]; + unsigned char sha256Hash[32]; + unsigned char *newHash; + unsigned int *sha256Parts; + unsigned int *chlStringParts; + unsigned int newHashParts[5]; + gchar *output; + + long long nHigh = 0, nLow = 0; + + int len; + int i; + + /* Create the SHA256 hash by using Purple SHA256 algorithm */ + cipher = purple_ciphers_find_cipher("sha256"); + context = purple_cipher_context_new(cipher, NULL); + + purple_cipher_context_append(context, (guchar *)input, strlen(input)); + purple_cipher_context_append(context, productKey, sizeof(productKey) - 1); + purple_cipher_context_digest(context, sizeof(sha256Hash), sha256Hash, NULL); + purple_cipher_context_destroy(context); + + /* Split it into four integers */ + sha256Parts = (unsigned int *)sha256Hash; + for (i = 0; i < 4; i++) { + /* adjust endianess */ + sha256Parts[i] = GUINT_TO_LE(sha256Parts[i]); + + /* & each integer with 0x7FFFFFFF */ + /* and save one unmodified array for later */ + newHashParts[i] = sha256Parts[i]; + sha256Parts[i] &= 0x7FFFFFFF; + } + + /* make a new string and pad with '0' to length that's a multiple of 8 */ + snprintf(buf, BUFSIZE - 5, "%s%s", input, productID); + len = strlen(buf); + if ((len % 8) != 0) { + int fix = 8 - (len % 8); + memset(&buf[len], '0', fix); + buf[len + fix] = '\0'; + len += fix; + } + + /* split into integers */ + chlStringParts = (unsigned int *)buf; + + /* this is magic */ + for (i = 0; i < (len / 4); i += 2) { + long long temp; + + chlStringParts[i] = GUINT_TO_LE(chlStringParts[i]); + chlStringParts[i + 1] = GUINT_TO_LE(chlStringParts[i + 1]); + + temp = (0x0E79A9C1 * (long long)chlStringParts[i]) % 0x7FFFFFFF; + temp = (sha256Parts[0] * (temp + nLow) + sha256Parts[1]) % 0x7FFFFFFF; + nHigh += temp; + + temp = ((long long)chlStringParts[i + 1] + temp) % 0x7FFFFFFF; + nLow = (sha256Parts[2] * temp + sha256Parts[3]) % 0x7FFFFFFF; + nHigh += nLow; + } + nLow = (nLow + sha256Parts[1]) % 0x7FFFFFFF; + nHigh = (nHigh + sha256Parts[3]) % 0x7FFFFFFF; + + newHashParts[0] ^= nLow; + newHashParts[1] ^= nHigh; + newHashParts[2] ^= nLow; + newHashParts[3] ^= nHigh; + + /* adjust endianness */ + for(i = 0; i < 4; i++) + newHashParts[i] = GUINT_TO_LE(newHashParts[i]); + + /* make a string of the parts */ + newHash = (unsigned char *)newHashParts; + + /* convert to hexadecimal */ + output = g_new0(gchar, 33); + for (i = 0; i < 16; i++) + { + output[i * 2] = hexChars[(newHash[i] >> 4) & 0xF]; + output[(i * 2) + 1] = hexChars[newHash[i] & 0xF]; + } + output[32] = '\0'; + + return output; +} + +gint64 +skypeweb_get_js_time() +{ + GTimeVal val; + + g_get_current_time (&val); + + return (((gint64) val.tv_sec) * 1000) + (val.tv_usec / 1000); +} + +/* copied from oscar.c to be libpurple 2.1 compatible */ +PurpleAccount * +find_acct(const char *prpl, const char *acct_id) +{ + PurpleAccount *acct = NULL; + + /* If we have a specific acct, use it */ + if (acct_id && *acct_id) { + acct = purple_accounts_find(acct_id, prpl); + if (acct && !purple_account_is_connected(acct)) + acct = NULL; + } else { /* Otherwise find an active account for the protocol */ + GList *l = purple_accounts_get_all(); + while (l) { + if (!strcmp(prpl, purple_account_get_protocol_id(l->data)) + && purple_account_is_connected(l->data)) { + acct = l->data; + break; + } + l = l->next; + } + } + + return acct; +} diff --git a/pool/shard006/C/0119553_byteswap64.c b/pool/shard006/C/0119553_byteswap64.c new file mode 100644 index 0000000000000000000000000000000000000000..11726f4a06a84cd0d39c7b46c75b3b6092fb39f2 --- /dev/null +++ b/pool/shard006/C/0119553_byteswap64.c @@ -0,0 +1,80 @@ +/* byteswap64.c + Copyright (C) 2017, 2018 Eric Herman + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation, either version 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. + + https://www.gnu.org/licenses/lgpl-3.0.txt + https://www.gnu.org/licenses/gpl-3.0.txt + */ +/* byteswap64.c */ + +/* +Some systems which have bswap_32 do not have bswap_64 +This defines a Bswap_64 which uses two bswap_32 calls + +gcc -DHAVE_BYTESWAP_H -DHAVE_BSWAP_32 -DHAVE_BSWAP_64 byteswap64.c +*/ + +#include +#include + +#if HAVE_BYTESWAP_H +#include +#endif + +#if HAVE_BSWAP_32 +#define Bswap_32(x) bswap_32(x) +#endif + +#if HAVE_BSWAP_64 +#define Bswap_64 bswap_64 +#endif + +#define Bswap_32_constant(x) \ + ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \ + (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24)) + +#ifndef Bswap_32 +#define Bswap_32 Bswap_32_constant +#endif + +#define Bswap_64_32x2(x) \ + ((((uint64_t)Bswap_32((uint32_t)x) << 32) | \ + ((uint64_t)Bswap_32((uint32_t)(x >> 32))))) + +#ifndef Bswap_64 +#define Bswap_64 Bswap_64_32x2 +#endif + +int main(int argc, char *argv[]) +{ + uint64_t original, expected; + uint64_t actual1, actual2, actual3; + + original = 0x554E49584C4f5645; + expected = 0x45564f4c58494e55; + + printf(" original: %0llx\n", (unsigned long long) original); + printf(" expected: %0llx\n", (unsigned long long) expected); + +#if HAVE_BSWAP_64 + actual1 = bswap_64(original); + printf(" bswap_64: %0llx\n", (unsigned long long) actual1); +#endif + + actual2 = Bswap_64_32x2(original); + printf("bswap_64_32x2: %0llx\n", (unsigned long long) actual2); + + actual3 = Bswap_64(original); + printf(" Bswap_64: %0llx\n", (unsigned long long) actual3); + + return actual2 == expected ? 0 : 1; +} diff --git a/pool/shard006/C/0119555_at91sam926x_time.c b/pool/shard006/C/0119555_at91sam926x_time.c new file mode 100644 index 0000000000000000000000000000000000000000..06d3e3276e09014fe18b7fa84f30ee60aa76a304 --- /dev/null +++ b/pool/shard006/C/0119555_at91sam926x_time.c @@ -0,0 +1,116 @@ +/* + * (C) Copyright 2002 + * Sysgo Real-Time Solutions, GmbH + * Marius Groeger + * + * (C) Copyright 2002 + * Sysgo Real-Time Solutions, GmbH + * Alex Zuepke + * + * (C) Copyright 2002 + * Gary Jennejohn, DENX Software Engineering, + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PIT_CPIV(x) ((x) & AT91_PIT_CPIV) +#define pit_write(reg, val) __raw_writel(val, pit_base + reg) +#define pit_read(reg) __raw_readl(pit_base + reg) + +static __iomem void *pit_base; + +uint64_t at91sam9_clocksource_read(void) +{ + return pit_read(AT91_PIT_PIIR); +} + +static struct clocksource cs = { + .read = at91sam9_clocksource_read, + .mask = CLOCKSOURCE_MASK(32), + .shift = 10, +}; + +static void at91_pit_stop(void) +{ + /* Disable timer and irqs */ + pit_write(AT91_PIT_MR, 0); + + /* Clear any pending interrupts, wait for PIT to stop counting */ + while (PIT_CPIV(pit_read(AT91_PIT_PIVR)) != 0); +} + +static void at91sam926x_pit_reset(void) +{ + at91_pit_stop(); + + /* Start PIT but don't enable IRQ */ + pit_write(AT91_PIT_MR, 0xfffff | AT91_PIT_PITEN); +} + +static int at91_pit_probe(struct device_d *dev) +{ + struct clk *clk; + u32 pit_rate; + int ret; + + clk = clk_get(dev, NULL); + if (IS_ERR(clk)) { + ret = PTR_ERR(clk); + dev_err(dev, "clock not found: %d\n", ret); + return ret; + } + + ret = clk_enable(clk); + if (ret < 0) { + dev_err(dev, "clock failed to enable: %d\n", ret); + clk_put(clk); + return ret; + } + + pit_base = dev_request_mem_region(dev, 0); + if (IS_ERR(pit_base)) + return PTR_ERR(pit_base); + + pit_rate = clk_get_rate(clk) / 16; + + at91sam926x_pit_reset(); + + cs.mult = clocksource_hz2mult(pit_rate, cs.shift); + + init_clock(&cs); + + return 0; +} + +static struct driver_d at91_pit_driver = { + .name = "at91-pit", + .probe = at91_pit_probe, +}; + +static int at91_pit_init(void) +{ + return platform_driver_register(&at91_pit_driver); +} +postcore_initcall(at91_pit_init); diff --git a/pool/shard006/C/0119556_winwaveoutopen.c b/pool/shard006/C/0119556_winwaveoutopen.c new file mode 100644 index 0000000000000000000000000000000000000000..ce86314a960a69ebc5f29cd55bb493db74688756 --- /dev/null +++ b/pool/shard006/C/0119556_winwaveoutopen.c @@ -0,0 +1,53 @@ +// 2 september 2014 +#define UNICODE +#define _UNICODE +#define STRICT +#define STRICT_TYPED_ITEMIDS +// get Windows version right; right now Windows XP +#define WINVER 0x0501 +#define _WIN32_WINNT 0x0501 +#define _WIN32_WINDOWS 0x0501 /* according to Microsoft's winperf.h */ +#define _WIN32_IE 0x0600 /* according to Microsoft's sdkddkver.h */ +#define NTDDI_VERSION 0x05010000 /* according to Microsoft's sdkddkver.h */ +#include +#include + +int main(void) +{ + HWAVEOUT wo; + HANDLE event; + WAVEFORMATEX fmt; + MMRESULT err; + + event = CreateEvent(NULL, TRUE, TRUE, NULL); // start off signaled just in case + if (event == NULL) { + fprintf(stderr, "CreateEvent() failed (last error %d)\n", GetLastError()); + return 3; + } + + ZeroMemory(&fmt, sizeof (WAVEFORMATEX)); + fmt.wFormatTag = WAVE_FORMAT_PCM; + fmt.nChannels = 1; + fmt.nSamplesPerSec = 44100; + fmt.wBitsPerSample = 8; + fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample; + fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; + fmt.cbSize = 0; + err = waveOutOpen(&wo, WAVE_MAPPER, &fmt, + (DWORD_PTR) event, 0, + CALLBACK_EVENT | WAVE_FORMAT_DIRECT); + if (err != MMSYSERR_NOERROR) { + WCHAR errmsg[MAXERRORLENGTH + 1]; + MMRESULT converr; + + converr = waveOutGetErrorTextW(err, errmsg, MAXERRORLENGTH + 1); + if (converr != MMSYSERR_NOERROR) { + fprintf(stderr, "open error %x (message conversion error %x)\n", err, converr); + return 2; + } + fwprintf(stderr, L"open error: %s\n", errmsg); + return 1; + } + fprintf(stderr, "open successful\n"); + return 0; +} diff --git a/pool/shard006/C/0119557_syscall_tp_kern.c b/pool/shard006/C/0119557_syscall_tp_kern.c new file mode 100644 index 0000000000000000000000000000000000000000..630ce8c4d5a23c25406de1724b0ba53fb5867259 --- /dev/null +++ b/pool/shard006/C/0119557_syscall_tp_kern.c @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* Copyright (c) 2017 Facebook + */ +#include +#include "bpf_helpers.h" + +struct syscalls_enter_open_args { + unsigned long long unused; + long syscall_nr; + long filename_ptr; + long flags; + long mode; +}; + +struct syscalls_exit_open_args { + unsigned long long unused; + long syscall_nr; + long ret; +}; + +struct bpf_map_def SEC("maps") enter_open_map = { + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(u32), + .value_size = sizeof(u32), + .max_entries = 1, +}; + +struct bpf_map_def SEC("maps") exit_open_map = { + .type = BPF_MAP_TYPE_ARRAY, + .key_size = sizeof(u32), + .value_size = sizeof(u32), + .max_entries = 1, +}; + +static __always_inline void count(void *map) +{ + u32 key = 0; + u32 *value, init_val = 1; + + value = bpf_map_lookup_elem(map, &key); + if (value) + *value += 1; + else + bpf_map_update_elem(map, &key, &init_val, BPF_NOEXIST); +} + +SEC("tracepoint/syscalls/sys_enter_open") +int trace_enter_open(struct syscalls_enter_open_args *ctx) +{ + count(&enter_open_map); + return 0; +} + +SEC("tracepoint/syscalls/sys_enter_openat") +int trace_enter_open_at(struct syscalls_enter_open_args *ctx) +{ + count(&enter_open_map); + return 0; +} + +SEC("tracepoint/syscalls/sys_exit_open") +int trace_enter_exit(struct syscalls_exit_open_args *ctx) +{ + count(&exit_open_map); + return 0; +} + +SEC("tracepoint/syscalls/sys_exit_openat") +int trace_enter_exit_at(struct syscalls_exit_open_args *ctx) +{ + count(&exit_open_map); + return 0; +} diff --git a/pool/shard006/C/0119560_graphics.c b/pool/shard006/C/0119560_graphics.c new file mode 100644 index 0000000000000000000000000000000000000000..b2aadd493623620dfcf38f701d4724f2aca63088 --- /dev/null +++ b/pool/shard006/C/0119560_graphics.c @@ -0,0 +1,97 @@ +#include "graphics.h" +#include +#include + +#define IS_ALPHA(color) (((color)&0xff000000)==0xff000000?0:1) +#define FRAMEBUFFER_SIZE (PSP_LINE_SIZE*SCREEN_HEIGHT*4) +#define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) + +Color* g_vram_base = (Color*) (0x40000000 | 0x04000000); + +typedef union +{ + int rgba; + struct + { + char r; + char g; + char b; + char a; + } c; +} color_t; + +extern u8 msx[]; + +Color* getVramDrawBuffer() +{ + Color* vram = (Color*) g_vram_base; + return vram; +} + +Color* getVramDisplayBuffer() +{ + Color* vram = (Color*) g_vram_base; + return vram; +} + +void putPixelScreen(Color color, int x, int y) +{ + Color* vram = getVramDrawBuffer(); + vram[PSP_LINE_SIZE * y + x] = color; +} + +Color getPixelScreen(int x, int y) +{ + Color* vram = getVramDrawBuffer(); + return vram[PSP_LINE_SIZE * y + x]; +} + +Color getPixelImage(int x, int y, Image* image) +{ + return image->data[x + y * image->textureWidth]; +} + +int gY = 0; + +void SetColor(int col) +{ + gY = 0; + int i; + color_t *pixel = (color_t *)0x44000000; + for(i = 0; i < 512*272; i++) { + pixel->rgba = col; + pixel++; + } +} + +void cls() +{ + sceDisplaySetFrameBuf((void *)0x44000000, 512, PSP_DISPLAY_PIXEL_FORMAT_8888, 1); + SetColor(0); + gY = 0; +} + +void printTextScreen(int x, int y, const char * text, u32 color) +{ + int c, i, j, l; + u8 *font; + Color *vram_ptr; + Color *vram; + + for (c = 0; c < strlen(text); c++) { + if (x < 0 || x + 8 > SCREEN_WIDTH || y < 0 || y + 8 > SCREEN_HEIGHT) break; + char ch = text[c]; + vram = getVramDrawBuffer() + x + y * PSP_LINE_SIZE; + + font = &msx[ (int)ch * 8]; + for (i = l = 0; i < 8; i++, l += 8, font++) { + vram_ptr = vram; + for (j = 0; j < 8; j++) { + if ((*font & (128 >> j))) *vram_ptr = color; + vram_ptr++; + } + vram += PSP_LINE_SIZE; + } + x += 8; + } +} \ No newline at end of file diff --git a/pool/shard006/C/0119561_vnormg_c.c b/pool/shard006/C/0119561_vnormg_c.c new file mode 100644 index 0000000000000000000000000000000000000000..d785dff1a6738cc3ee715af9789f21a87a7afd8c --- /dev/null +++ b/pool/shard006/C/0119561_vnormg_c.c @@ -0,0 +1,212 @@ +/* + +-Procedure vnormg_c ( Vector norm, general dimension ) + +-Abstract + + Compute the magnitude of a double precision vector of arbitrary + dimension. + +-Disclaimer + + THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE + CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. + GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE + ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE + PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" + TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY + WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A + PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC + SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE + SOFTWARE AND RELATED MATERIALS, HOWEVER USED. + + IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA + BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT + LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, + INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, + REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE + REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. + + RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF + THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY + CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE + ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. + +-Required_Reading + + None. + +-Keywords + + VECTOR + +*/ + + #include "SpiceUsr.h" + #include "SpiceZmc.h" + #undef vnormg_c + + + SpiceDouble vnormg_c ( ConstSpiceDouble * v1, + SpiceInt ndim ) + +/* + +-Brief_I/O + + VARIABLE I/O DESCRIPTION + -------- --- -------------------------------------------------- + v1 I Vector whose magnitude is to be found. + ndim I Dimension of v1. + +-Detailed_Input + + v1 This may be any double precision vector or arbitrary + size. + +-Detailed_Output + + vnormg_c is the magnitude of v1 calculated in a numerically stable + way. + +-Parameters + + None. + +-Exceptions + + 1) If ndim is not physically realistic, greater than zero, a + BADDIMENSION error is signaled. The value 0. is returned. + +-Files + + None. + +-Particulars + + vnormg_c finds the component of v1 whose magnitude is the largest. + If the absolute magnitude of that component indicates that a + numeric overflow would occur when it is squared, or if it + indicates that an underflow would occur when squared (falsely + giving a magnitude of zero) then the following expression is + used: + + vnormg_c = v1max * MAGNITUDE OF [ (1/v1max)*v1 ] + + therwise a simpler expression is used: + + vnormg_c = MAGNITUDE OF [ v1 ] + + Beyond the logic described above, no further checking of the + validity of the input is performed. + +-Examples + + The following table show the correlation between various input + vectors v1 and vnormg_c: + + ndim v1 ndim vnormg_c + ----------------------------------------------------------------- + 1 (-7.0D20) 1 7.D20 + 3 (1., 2., 2.) 3 3. + 4 (3., 3., 3., 3.) 4 6. + 5 (5., 12., 0., 0., 0.) 5 13. + 3 (-5.D-17, 0.0, 12.D-17) 3 13.D-17 + +-Restrictions + + None. + +-Author_and_Institution + + W.M. Owen (JPL) + +-Literature_References + + None. + +-Version + + -CSPICE Version 1.1.0, 22-OCT-1998 (NJB) + + Made input vector const. + + -CSPICE Version 1.0.0, 1-APR-1998 (EDW) + +-Index_Entries + + norm of n-dimensional vector + +-& +*/ + +{ /* Begin vnormg_c */ + + /* + Local variables + */ + + SpiceInt i; + SpiceDouble norm; + SpiceDouble scale; + + + /* + Use discovery check-in. + */ + + /* Initialize norm and scale to zero. */ + + norm = 0.; + scale = 0.; + + + /* Check ndim is cool. Dimension is positive definite. */ + + if ( ndim <= 0 ) + { + + chkin_c ( "vnormg_c" ); + SpiceError ( "Vector dimension less than or equal to zero", + "BADDIMENSION" ); + chkout_c ( "vnormg_c" ); + return ( 0. ); + + } + + + /* + Determine an appropriate scale factor to prevent numerical + overflow. Overflow would be bad! + */ + + for ( i = 0; i < ndim; i++ ) + { + scale = MaxAbs( scale, v1[i] ); + } + + + /* If the vector is zero, return zero. */ + + if ( scale == 0. ) + { + return 0.; + } + + + /* Do the calculation. Not very involved. */ + + for ( i = 0; i < ndim; i++ ) + { + norm += pow( v1[i] / scale, 2 ); + } + + + + /* Return the value. */ + + + return ( scale * sqrt( norm ) ); + + +} /* End vnormg_c */ diff --git a/pool/shard006/C/0119562_DETOUR0836.c b/pool/shard006/C/0119562_DETOUR0836.c new file mode 100644 index 0000000000000000000000000000000000000000..f22a3662fc0d7dac072d83a3f4b5bbe1a345c834 --- /dev/null +++ b/pool/shard006/C/0119562_DETOUR0836.c @@ -0,0 +1,58 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[2]; +atomic_int atom_1_r3_2; +atomic_int atom_1_r6_0; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + int v2_r3 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v4_r4 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v5_r5 = v4_r4 ^ v4_r4; + int v8_r6 = atomic_load_explicit(&vars[0+v5_r5], memory_order_seq_cst); + int v15 = (v2_r3 == 2); + atomic_store_explicit(&atom_1_r3_2, v15, memory_order_seq_cst); + int v16 = (v8_r6 == 0); + atomic_store_explicit(&atom_1_r6_0, v16, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[0], 0); + atomic_init(&vars[1], 0); + atomic_init(&atom_1_r3_2, 0); + atomic_init(&atom_1_r6_0, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v9 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v10 = (v9 == 2); + int v11 = atomic_load_explicit(&atom_1_r3_2, memory_order_seq_cst); + int v12 = atomic_load_explicit(&atom_1_r6_0, memory_order_seq_cst); + int v13_conj = v11 & v12; + int v14_conj = v10 & v13_conj; + if (v14_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard006/C/0119565_mipsnbsd-nat.c b/pool/shard006/C/0119565_mipsnbsd-nat.c new file mode 100644 index 0000000000000000000000000000000000000000..c8ad11bba46c38ca38f9eb24701d14ae8ba0c460 --- /dev/null +++ b/pool/shard006/C/0119565_mipsnbsd-nat.c @@ -0,0 +1,126 @@ +/* Native-dependent code for MIPS systems running NetBSD. + + Copyright (C) 2000-2002, 2004, 2007-2012 Free Software Foundation, + Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include "defs.h" +#include "inferior.h" +#include "regcache.h" +#include "target.h" + +#include +#include +#include + +#include "mips-tdep.h" +#include "mipsnbsd-tdep.h" +#include "inf-ptrace.h" + +/* Determine if PT_GETREGS fetches this register. */ +static int +getregs_supplies (struct gdbarch *gdbarch, int regno) +{ + return ((regno) >= MIPS_ZERO_REGNUM + && (regno) <= gdbarch_pc_regnum (gdbarch)); +} + +static void +mipsnbsd_fetch_inferior_registers (struct target_ops *ops, + struct regcache *regcache, int regno) +{ + struct gdbarch *gdbarch = get_regcache_arch (regcache); + if (regno == -1 || getregs_supplies (gdbarch, regno)) + { + struct reg regs; + + if (ptrace (PT_GETREGS, PIDGET (inferior_ptid), + (PTRACE_TYPE_ARG3) ®s, 0) == -1) + perror_with_name (_("Couldn't get registers")); + + mipsnbsd_supply_reg (regcache, (char *) ®s, regno); + if (regno != -1) + return; + } + + if (regno == -1 + || regno >= gdbarch_fp0_regnum (get_regcache_arch (regcache))) + { + struct fpreg fpregs; + + if (ptrace (PT_GETFPREGS, PIDGET (inferior_ptid), + (PTRACE_TYPE_ARG3) &fpregs, 0) == -1) + perror_with_name (_("Couldn't get floating point status")); + + mipsnbsd_supply_fpreg (regcache, (char *) &fpregs, regno); + } +} + +static void +mipsnbsd_store_inferior_registers (struct target_ops *ops, + struct regcache *regcache, int regno) +{ + struct gdbarch *gdbarch = get_regcache_arch (regcache); + if (regno == -1 || getregs_supplies (gdbarch, regno)) + { + struct reg regs; + + if (ptrace (PT_GETREGS, PIDGET (inferior_ptid), + (PTRACE_TYPE_ARG3) ®s, 0) == -1) + perror_with_name (_("Couldn't get registers")); + + mipsnbsd_fill_reg (regcache, (char *) ®s, regno); + + if (ptrace (PT_SETREGS, PIDGET (inferior_ptid), + (PTRACE_TYPE_ARG3) ®s, 0) == -1) + perror_with_name (_("Couldn't write registers")); + + if (regno != -1) + return; + } + + if (regno == -1 + || regno >= gdbarch_fp0_regnum (get_regcache_arch (regcache))) + { + struct fpreg fpregs; + + if (ptrace (PT_GETFPREGS, PIDGET (inferior_ptid), + (PTRACE_TYPE_ARG3) &fpregs, 0) == -1) + perror_with_name (_("Couldn't get floating point status")); + + mipsnbsd_fill_fpreg (regcache, (char *) &fpregs, regno); + + if (ptrace (PT_SETFPREGS, PIDGET (inferior_ptid), + (PTRACE_TYPE_ARG3) &fpregs, 0) == -1) + perror_with_name (_("Couldn't write floating point status")); + } +} + + +/* Provide a prototype to silence -Wmissing-prototypes. */ +void _initialize_mipsnbsd_nat (void); + +void +_initialize_mipsnbsd_nat (void) +{ + struct target_ops *t; + + t = inf_ptrace_target (); + t->to_fetch_registers = mipsnbsd_fetch_inferior_registers; + t->to_store_registers = mipsnbsd_store_inferior_registers; + add_target (t); +} diff --git a/pool/shard006/C/0119570_get_stackid_cannot_attach.c b/pool/shard006/C/0119570_get_stackid_cannot_attach.c new file mode 100644 index 0000000000000000000000000000000000000000..d884b2ed5bc5897f346fe5d0de584e6ac021c71d --- /dev/null +++ b/pool/shard006/C/0119570_get_stackid_cannot_attach.c @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: GPL-2.0 +// Copyright (c) 2020 Facebook +#include +#include "test_stacktrace_build_id.skel.h" + +void test_get_stackid_cannot_attach(void) +{ + struct perf_event_attr attr = { + /* .type = PERF_TYPE_SOFTWARE, */ + .type = PERF_TYPE_HARDWARE, + .config = PERF_COUNT_HW_CPU_CYCLES, + .precise_ip = 1, + .sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_BRANCH_STACK, + .branch_sample_type = PERF_SAMPLE_BRANCH_USER | + PERF_SAMPLE_BRANCH_NO_FLAGS | + PERF_SAMPLE_BRANCH_NO_CYCLES | + PERF_SAMPLE_BRANCH_CALL_STACK, + .sample_period = 5000, + .size = sizeof(struct perf_event_attr), + }; + struct test_stacktrace_build_id *skel; + __u32 duration = 0; + int pmu_fd, err; + + skel = test_stacktrace_build_id__open(); + if (CHECK(!skel, "skel_open", "skeleton open failed\n")) + return; + + /* override program type */ + bpf_program__set_perf_event(skel->progs.oncpu); + + err = test_stacktrace_build_id__load(skel); + if (CHECK(err, "skel_load", "skeleton load failed: %d\n", err)) + goto cleanup; + + pmu_fd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, + 0 /* cpu 0 */, -1 /* group id */, + 0 /* flags */); + if (pmu_fd < 0 && (errno == ENOENT || errno == EOPNOTSUPP)) { + printf("%s:SKIP:cannot open PERF_COUNT_HW_CPU_CYCLES with precise_ip > 0\n", + __func__); + test__skip(); + goto cleanup; + } + if (CHECK(pmu_fd < 0, "perf_event_open", "err %d errno %d\n", + pmu_fd, errno)) + goto cleanup; + + skel->links.oncpu = bpf_program__attach_perf_event(skel->progs.oncpu, + pmu_fd); + CHECK(!IS_ERR(skel->links.oncpu), "attach_perf_event_no_callchain", + "should have failed\n"); + close(pmu_fd); + + /* add PERF_SAMPLE_CALLCHAIN, attach should succeed */ + attr.sample_type |= PERF_SAMPLE_CALLCHAIN; + + pmu_fd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, + 0 /* cpu 0 */, -1 /* group id */, + 0 /* flags */); + + if (CHECK(pmu_fd < 0, "perf_event_open", "err %d errno %d\n", + pmu_fd, errno)) + goto cleanup; + + skel->links.oncpu = bpf_program__attach_perf_event(skel->progs.oncpu, + pmu_fd); + CHECK(IS_ERR(skel->links.oncpu), "attach_perf_event_callchain", + "err: %ld\n", PTR_ERR(skel->links.oncpu)); + close(pmu_fd); + + /* add exclude_callchain_kernel, attach should fail */ + attr.exclude_callchain_kernel = 1; + + pmu_fd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, + 0 /* cpu 0 */, -1 /* group id */, + 0 /* flags */); + + if (CHECK(pmu_fd < 0, "perf_event_open", "err %d errno %d\n", + pmu_fd, errno)) + goto cleanup; + + skel->links.oncpu = bpf_program__attach_perf_event(skel->progs.oncpu, + pmu_fd); + CHECK(!IS_ERR(skel->links.oncpu), "attach_perf_event_exclude_callchain_kernel", + "should have failed\n"); + close(pmu_fd); + +cleanup: + test_stacktrace_build_id__destroy(skel); +} diff --git a/pool/shard006/C/0119571_execinfo_testfunc1.c b/pool/shard006/C/0119571_execinfo_testfunc1.c new file mode 100644 index 0000000000000000000000000000000000000000..6fdd471bbe01ee6ea738f7617bc591eb2aa217fa --- /dev/null +++ b/pool/shard006/C/0119571_execinfo_testfunc1.c @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2019 Sippy Software, 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: + * 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. + * + */ + +#define _BSD_SOURCE +#include + +#include "execinfo_testfunc1.h" +#include "execinfo_testfunc.h" + +int +testfunc1(const void *caller, int rlev) +{ + int rval, rnd; + + rnd = random() % 1024; + if (rlev > 0) { + rval = testfunc1(testfunc1, rlev - 1); + } else { + rval = testfunc(testfunc1, rnd); + } + return (rval & 0x000000ff); +} diff --git a/pool/shard006/C/0119572_CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06.c b/pool/shard006/C/0119572_CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06.c new file mode 100644 index 0000000000000000000000000000000000000000..b1edd382e626ab14944b15fa8e2a52b1de30d3a9 --- /dev/null +++ b/pool/shard006/C/0119572_CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06.c @@ -0,0 +1,292 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06.c +Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml +Template File: sources-vasinks-06.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: file Read input from a file + * GoodSource: Copy a fixed string into data + * Sinks: w32_vsnprintf + * GoodSink: vsnprintf with a format string + * BadSink : vsnprintf without a format string + * Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5) + * + * */ + +#include +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +/* The variable below is declared "const", so a tool should be able + to identify that reads of this will always give its initialized + value. */ +static const int STATIC_CONST_FIVE = 5; + +#ifndef OMITBAD + +static void badVaSinkB(char * data, ...) +{ + { + char dest[100] = ""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vsnprintf(dest, 100-1, data, args); + va_end(args); + printLine(dest); + } +} + +void CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_FIVE==5) + { + { + /* Read input from a file */ + size_t dataLen = strlen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (100-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + fclose(pFile); + } + } + } + } + if(STATIC_CONST_FIVE==5) + { + badVaSinkB(data, data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static void goodB2G1VaSinkG(char * data, ...) +{ + { + char dest[100] = ""; + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + vsnprintf(dest, 100-1, "%s", args); + va_end(args); + printLine(dest); + } +} + +/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */ +static void goodB2G1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_FIVE==5) + { + { + /* Read input from a file */ + size_t dataLen = strlen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (100-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + fclose(pFile); + } + } + } + } + if(STATIC_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + goodB2G1VaSinkG(data, data); + } +} + +static void goodB2G2VaSinkG(char * data, ...) +{ + { + char dest[100] = ""; + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + vsnprintf(dest, 100-1, "%s", args); + va_end(args); + printLine(dest); + } +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ +static void goodB2G2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_FIVE==5) + { + { + /* Read input from a file */ + size_t dataLen = strlen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (100-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + fclose(pFile); + } + } + } + } + if(STATIC_CONST_FIVE==5) + { + goodB2G2VaSinkG(data, data); + } +} + +static void goodG2B1VaSinkB(char * data, ...) +{ + { + char dest[100] = ""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vsnprintf(dest, 100-1, data, args); + va_end(args); + printLine(dest); + } +} + +/* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + } + if(STATIC_CONST_FIVE==5) + { + goodG2B1VaSinkB(data, data); + } +} + +static void goodG2B2VaSinkB(char * data, ...) +{ + { + char dest[100] = ""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vsnprintf(dest, 100-1, data, args); + va_end(args); + printLine(dest); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ +static void goodG2B2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_FIVE==5) + { + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + } + if(STATIC_CONST_FIVE==5) + { + goodG2B2VaSinkB(data, data); + } +} + +void CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06_good() +{ + goodG2B1(); + goodG2B2(); + goodB2G1(); + goodB2G2(); +} + +#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()..."); + CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__char_file_w32_vsnprintf_06_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0119575_ft_strjoinch.c b/pool/shard006/C/0119575_ft_strjoinch.c new file mode 100644 index 0000000000000000000000000000000000000000..0d83eaa16d96c0b62edd27132915b576f209bf45 --- /dev/null +++ b/pool/shard006/C/0119575_ft_strjoinch.c @@ -0,0 +1,32 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_strjoin.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: jrameau +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/09/27 00:08:20 by jrameau #+# #+# */ +/* Updated: 2016/09/27 00:08:21 by jrameau ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +char *ft_strjoinch(char const *s1, char c) +{ + char *new_str; + size_t i; + size_t s1_len; + + if (!s1 || !c) + return (NULL); + s1_len = ft_strlen(s1); + new_str = ft_strnew(s1_len + 1); + if (!new_str) + return (NULL); + i = -1; + while (++i < s1_len) + *(new_str + i) = *(s1 + i); + *(new_str + i) = c; + return (new_str); +} diff --git a/pool/shard006/C/0119576_snmp_pdu.c b/pool/shard006/C/0119576_snmp_pdu.c new file mode 100644 index 0000000000000000000000000000000000000000..8c4b51d0a66591be797ed0dfcae95e4e80400535 --- /dev/null +++ b/pool/shard006/C/0119576_snmp_pdu.c @@ -0,0 +1,121 @@ +/* + This file is part of GNU Radius SNMP Library. + Copyright (C) 2001,2003,2004,2007 Free Software Foundation, Inc. + + Written by Sergey Poznyakoff + + 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 3 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; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +struct snmp_pdu * +snmp_pdu_create(int type) +{ + struct snmp_pdu *pdu; + + pdu = snmp_alloc(sizeof(*pdu)); + + pdu->type = type; + pdu->req_id = 0; + pdu->err_stat = 0; + pdu->err_ind = 0; + pdu->var = NULL; + return pdu; +} + +void +snmp_pdu_free(struct snmp_pdu *pdu) +{ + if (!pdu) + return; + snmp_var_free_list(pdu->var); + snmp_free(pdu); +} + +void +snmp_pdu_add_var(struct snmp_pdu *pdu, struct snmp_var *var) +{ + var->next = pdu->var; + pdu->var = var; +} + +u_char * +snmp_pdu_decode(u_char *data, int *length, struct snmp_pdu *pdu) +{ + u_char *buf = data; + u_char type; + + buf = asn_decode_header(buf, length, &pdu->type); + if (!buf) + return NULL; + + switch (pdu->type) { + case SNMP_PDU_RESPONSE: + case SNMP_PDU_GET: + case SNMP_PDU_GETNEXT: + case SNMP_PDU_SET: + buf = asn_decode_int(buf, length, &type, + &pdu->req_id, sizeof(pdu->req_id)); + if (!buf) + break; + + buf = asn_decode_int(buf, length, &type, + &pdu->err_stat, sizeof(pdu->err_stat)); + if (!buf) + break; + + buf = asn_decode_int(buf, length, &type, + &pdu->err_ind, sizeof(pdu->err_ind)); + break; + default: + SNMP_SET_ERRNO(E_SNMP_UNKNOWN_REQ); + buf = NULL; + } + return buf; +} + + +u_char * +snmp_pdu_encode(u_char *data, int *length, struct snmp_pdu *pdu) +{ + u_char *buf = data; + +#define BAIL_OUT if (!buf) return NULL; + + /*FIXME: No support for trap and bulk PDUs */ + buf = asn_encode_int(buf, length, + (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + pdu->req_id); + BAIL_OUT; + + buf = asn_encode_int(buf, length, + (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + pdu->err_stat); + BAIL_OUT; + + buf = asn_encode_int(buf, length, + (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), + pdu->err_ind); + BAIL_OUT; + + return buf; +} diff --git a/pool/shard006/C/0119580_fft.c b/pool/shard006/C/0119580_fft.c new file mode 100644 index 0000000000000000000000000000000000000000..ecf9f3dd9dabd390e091dc858678db93649ff778 --- /dev/null +++ b/pool/shard006/C/0119580_fft.c @@ -0,0 +1,111 @@ +/* + * fft.c + * + * Fast Fourier transform + * + * Copyright (C) 2012 Thomas Tsou + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program; if not, see . + * See the COPYING file in the main directory for details. + */ + +#include +#include +#include +#include + +#include "sigvec.h" +#include "fft.h" + +struct fft_hdl { + struct cxvec *fft_in; + struct cxvec *fft_out; + fftwf_plan fft_plan; +}; + +/*! \brief Initialize FFT backend + * \param[in] reverse FFT direction + * \param[in] m FFT length + * \param[in] istride input stride count + * \param[in] ostride output stride count + * \param[in] in input buffer (FFTW aligned) + * \param[in] out output buffer (FFTW aligned) + * \param[in] ooffset initial offset into output buffer + * + * If the reverse is non-NULL, then an inverse FFT will be used. This is a + * wrapper for advanced non-contiguous FFTW usage. See FFTW documentation for + * further details. + * + * http://www.fftw.org/doc/Advanced-Complex-DFTs.html + * + * It is currently unknown how the offset of the output buffer affects FFTW + * memory alignment. + */ +struct fft_hdl *init_fft(int reverse, int m, int istride, int ostride, + struct cxvec *in, struct cxvec *out, int ooffset) +{ + int rank = 1; + int n[] = { m }; + int howmany = istride; + int idist = 1; + int odist = 1; + int *inembed = n; + int *onembed = n; + fftwf_complex *obuffer, *ibuffer; + + struct fft_hdl *hdl = (struct fft_hdl *) malloc(sizeof(struct fft_hdl)); + if (!hdl) + return NULL; + + int direction = FFTW_FORWARD; + if (reverse) + direction = FFTW_BACKWARD; + + ibuffer = (fftwf_complex *) in->data; + obuffer = (fftwf_complex *) out->data + ooffset; + + hdl->fft_in = in; + hdl->fft_out = out; + hdl->fft_plan = fftwf_plan_many_dft(rank, n, howmany, + ibuffer, inembed, istride, idist, + obuffer, onembed, ostride, odist, + direction, FFTW_MEASURE); + return hdl; +} + +void *fft_malloc(size_t size) +{ + return fftwf_malloc(size); +} + +/*! \brief Free FFT backend resources + */ +void free_fft(struct fft_hdl *hdl) +{ + cxvec_free(hdl->fft_in); + cxvec_free(hdl->fft_out); + fftwf_destroy_plan(hdl->fft_plan); + free(hdl); +} + +/*! \brief Run multiple DFT operations with the initialized plan + * \param[in] hdl handle to an intitialized fft struct + * + * Input and output buffers are configured with init_fft(). + */ +int cxvec_fft(struct fft_hdl *hdl) +{ + fftwf_execute(hdl->fft_plan); + return 0; +} diff --git a/pool/shard006/C/0119583_clock-sh7780.c b/pool/shard006/C/0119583_clock-sh7780.c new file mode 100644 index 0000000000000000000000000000000000000000..93ad367342c9c6a715a4ea96f22b987a007f967b --- /dev/null +++ b/pool/shard006/C/0119583_clock-sh7780.c @@ -0,0 +1,126 @@ +/* + * arch/sh/kernel/cpu/sh4/clock-sh7780.c + * + * SH7780 support for the clock framework + * + * Copyright (C) 2005 Paul Mundt + * + * 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. + */ +#include +#include +#include +#include +#include + +static int ifc_divisors[] = { 2, 4 }; +static int bfc_divisors[] = { 1, 1, 1, 8, 12, 16, 24, 1 }; +static int pfc_divisors[] = { 1, 24, 24, 1 }; +static int cfc_divisors[] = { 1, 1, 4, 1, 6, 1, 1, 1 }; + +static void master_clk_init(struct clk *clk) +{ + clk->rate *= pfc_divisors[ctrl_inl(FRQCR) & 0x0003]; +} + +static struct clk_ops sh7780_master_clk_ops = { + .init = master_clk_init, +}; + +static void module_clk_recalc(struct clk *clk) +{ + int idx = (ctrl_inl(FRQCR) & 0x0003); + clk->rate = clk->parent->rate / pfc_divisors[idx]; +} + +static struct clk_ops sh7780_module_clk_ops = { + .recalc = module_clk_recalc, +}; + +static void bus_clk_recalc(struct clk *clk) +{ + int idx = ((ctrl_inl(FRQCR) >> 16) & 0x0007); + clk->rate = clk->parent->rate / bfc_divisors[idx]; +} + +static struct clk_ops sh7780_bus_clk_ops = { + .recalc = bus_clk_recalc, +}; + +static void cpu_clk_recalc(struct clk *clk) +{ + int idx = ((ctrl_inl(FRQCR) >> 24) & 0x0001); + clk->rate = clk->parent->rate / ifc_divisors[idx]; +} + +static struct clk_ops sh7780_cpu_clk_ops = { + .recalc = cpu_clk_recalc, +}; + +static struct clk_ops *sh7780_clk_ops[] = { + &sh7780_master_clk_ops, + &sh7780_module_clk_ops, + &sh7780_bus_clk_ops, + &sh7780_cpu_clk_ops, +}; + +void __init arch_init_clk_ops(struct clk_ops **ops, int idx) +{ + if (idx < ARRAY_SIZE(sh7780_clk_ops)) + *ops = sh7780_clk_ops[idx]; +} + +static void shyway_clk_recalc(struct clk *clk) +{ + int idx = ((ctrl_inl(FRQCR) >> 20) & 0x0007); + clk->rate = clk->parent->rate / cfc_divisors[idx]; +} + +static struct clk_ops sh7780_shyway_clk_ops = { + .recalc = shyway_clk_recalc, +}; + +static struct clk sh7780_shyway_clk = { + .name = "shyway_clk", + .flags = CLK_ALWAYS_ENABLED, + .ops = &sh7780_shyway_clk_ops, +}; + +/* + * Additional SH7780-specific on-chip clocks that aren't already part of the + * clock framework + */ +static struct clk *sh7780_onchip_clocks[] = { + &sh7780_shyway_clk, +}; + +static int __init sh7780_clk_init(void) +{ + struct clk *clk = clk_get("master_clk"); + int i; + + for (i = 0; i < ARRAY_SIZE(sh7780_onchip_clocks); i++) { + struct clk *clkp = sh7780_onchip_clocks[i]; + + clkp->parent = clk; + clk_register(clkp); + clk_enable(clkp); + } + + /* + * Now that we have the rest of the clocks registered, we need to + * force the parent clock to propagate so that these clocks will + * automatically figure out their rate. We cheat by handing the + * parent clock its current rate and forcing child propagation. + */ + clk_set_rate(clk, clk_get_rate(clk)); + + clk_put(clk); + + return 0; +} + +arch_initcall(sh7780_clk_init); + diff --git a/pool/shard006/C/0119587_loading-plugins.c b/pool/shard006/C/0119587_loading-plugins.c new file mode 100644 index 0000000000000000000000000000000000000000..263be23f84d6b17b18f2432ef8e8dbbb797767e4 --- /dev/null +++ b/pool/shard006/C/0119587_loading-plugins.c @@ -0,0 +1,73 @@ + +/* + * Loading plugins in Grilo. + * Tracks sources adding and removing + */ + +#include + +#define GRL_LOG_DOMAIN_DEFAULT example_log_domain +GRL_LOG_DOMAIN_STATIC(example_log_domain); + +static void +source_added_cb (GrlRegistry *registry, GrlSource *source, gpointer user_data) +{ + g_debug ("Detected new source available: '%s'", + grl_source_get_name (source)); + + /* Usually you may add the new service to the user interface so the user + can interact with it (browse, search, etc) */ +} + +static void +source_removed_cb (GrlRegistry *registry, GrlSource *source, gpointer user_data) +{ + g_debug ("Source '%s' is gone", + grl_source_get_name (source)); + + /* Usually you would inform the user that this service is no longer + available (for example a UPnP server was shutdown) and remove it + from the user interface. */ +} + +static void +load_plugins (void) +{ + GrlRegistry *registry; + GError *error = NULL; + + registry = grl_registry_get_default (); + + /* These callback will be invoked when media providers + are loaded/unloaded */ + g_signal_connect (registry, "source-added", + G_CALLBACK (source_added_cb), NULL); + g_signal_connect (registry, "source-removed", + G_CALLBACK (source_removed_cb), NULL); + + /* Command the registry to load all available plugins. + The registry will look for plugins in the default + plugin path and directories specified using the + GRL_PLUGIN_PATH environment variable */ + if (!grl_registry_load_all_plugins (registry, &error)) { + g_error ("Failed to load plugins: %s", error->message); + } +} + +gint +main (int argc, gchar *argv[]) +{ + GMainLoop *loop; + + grl_init (&argc, &argv); + GRL_LOG_DOMAIN_INIT (example_log_domain, "example"); + load_plugins (); /* Load Grilo plugins */ + + /* Run the main loop */ + loop = g_main_loop_new (NULL, FALSE); + g_main_loop_run (loop); + + grl_deinit (); + + return 0; +} diff --git a/pool/shard006/C/0119590_realview_mpcore.c b/pool/shard006/C/0119590_realview_mpcore.c new file mode 100644 index 0000000000000000000000000000000000000000..39d4ebeb1d98bf32e10dc7fb793f400450195186 --- /dev/null +++ b/pool/shard006/C/0119590_realview_mpcore.c @@ -0,0 +1,141 @@ +/* + * RealView ARM11MPCore internal peripheral emulation + * + * Copyright (c) 2006-2007 CodeSourcery. + * Copyright (c) 2013 SUSE LINUX Products GmbH + * Written by Paul Brook and Andreas Färber + * + * This code is licensed under the GPL. + */ + +#include "qemu/osdep.h" +#include "qapi/error.h" +#include "hw/cpu/arm11mpcore.h" +#include "hw/intc/realview_gic.h" + +#define TYPE_REALVIEW_MPCORE_RIRQ "realview_mpcore" +#define REALVIEW_MPCORE_RIRQ(obj) \ + OBJECT_CHECK(mpcore_rirq_state, (obj), TYPE_REALVIEW_MPCORE_RIRQ) + +/* Dummy PIC to route IRQ lines. The baseboard has 4 independent IRQ + controllers. The output of these, plus some of the raw input lines + are fed into a single SMP-aware interrupt controller on the CPU. */ +typedef struct { + SysBusDevice parent_obj; + + qemu_irq cpuic[32]; + qemu_irq rvic[4][64]; + uint32_t num_cpu; + + ARM11MPCorePriveState priv; + RealViewGICState gic[4]; +} mpcore_rirq_state; + +/* Map baseboard IRQs onto CPU IRQ lines. */ +static const int mpcore_irq_map[32] = { + -1, -1, -1, -1, 1, 2, -1, -1, + -1, -1, 6, -1, 4, 5, -1, -1, + -1, 14, 15, 0, 7, 8, -1, -1, + -1, -1, -1, -1, 9, 3, -1, -1, +}; + +static void mpcore_rirq_set_irq(void *opaque, int irq, int level) +{ + mpcore_rirq_state *s = (mpcore_rirq_state *)opaque; + int i; + + for (i = 0; i < 4; i++) { + qemu_set_irq(s->rvic[i][irq], level); + } + if (irq < 32) { + irq = mpcore_irq_map[irq]; + if (irq >= 0) { + qemu_set_irq(s->cpuic[irq], level); + } + } +} + +static void realview_mpcore_realize(DeviceState *dev, Error **errp) +{ + SysBusDevice *sbd = SYS_BUS_DEVICE(dev); + mpcore_rirq_state *s = REALVIEW_MPCORE_RIRQ(dev); + DeviceState *priv = DEVICE(&s->priv); + DeviceState *gic; + SysBusDevice *gicbusdev; + Error *err = NULL; + int n; + int i; + + qdev_prop_set_uint32(priv, "num-cpu", s->num_cpu); + object_property_set_bool(OBJECT(&s->priv), true, "realized", &err); + if (err != NULL) { + error_propagate(errp, err); + return; + } + sysbus_pass_irq(sbd, SYS_BUS_DEVICE(&s->priv)); + for (i = 0; i < 32; i++) { + s->cpuic[i] = qdev_get_gpio_in(priv, i); + } + /* ??? IRQ routing is hardcoded to "normal" mode. */ + for (n = 0; n < 4; n++) { + object_property_set_bool(OBJECT(&s->gic[n]), true, "realized", &err); + if (err != NULL) { + error_propagate(errp, err); + return; + } + gic = DEVICE(&s->gic[n]); + gicbusdev = SYS_BUS_DEVICE(&s->gic[n]); + sysbus_mmio_map(gicbusdev, 0, 0x10040000 + n * 0x10000); + sysbus_connect_irq(gicbusdev, 0, s->cpuic[10 + n]); + for (i = 0; i < 64; i++) { + s->rvic[n][i] = qdev_get_gpio_in(gic, i); + } + } + qdev_init_gpio_in(dev, mpcore_rirq_set_irq, 64); +} + +static void mpcore_rirq_init(Object *obj) +{ + SysBusDevice *sbd = SYS_BUS_DEVICE(obj); + mpcore_rirq_state *s = REALVIEW_MPCORE_RIRQ(obj); + SysBusDevice *privbusdev; + int i; + + object_initialize(&s->priv, sizeof(s->priv), TYPE_ARM11MPCORE_PRIV); + qdev_set_parent_bus(DEVICE(&s->priv), sysbus_get_default()); + privbusdev = SYS_BUS_DEVICE(&s->priv); + sysbus_init_mmio(sbd, sysbus_mmio_get_region(privbusdev, 0)); + + for (i = 0; i < 4; i++) { + object_initialize(&s->gic[i], sizeof(s->gic[i]), TYPE_REALVIEW_GIC); + qdev_set_parent_bus(DEVICE(&s->gic[i]), sysbus_get_default()); + } +} + +static Property mpcore_rirq_properties[] = { + DEFINE_PROP_UINT32("num-cpu", mpcore_rirq_state, num_cpu, 1), + DEFINE_PROP_END_OF_LIST(), +}; + +static void mpcore_rirq_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + + dc->realize = realview_mpcore_realize; + dc->props = mpcore_rirq_properties; +} + +static const TypeInfo mpcore_rirq_info = { + .name = TYPE_REALVIEW_MPCORE_RIRQ, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(mpcore_rirq_state), + .instance_init = mpcore_rirq_init, + .class_init = mpcore_rirq_class_init, +}; + +static void realview_mpcore_register_types(void) +{ + type_register_static(&mpcore_rirq_info); +} + +type_init(realview_mpcore_register_types) diff --git a/pool/shard006/C/0119596_s2box.c b/pool/shard006/C/0119596_s2box.c new file mode 100644 index 0000000000000000000000000000000000000000..7dc192a34b0cbae7e7879b988c60057e56b9cbb2 --- /dev/null +++ b/pool/shard006/C/0119596_s2box.c @@ -0,0 +1,50 @@ +/* s2box.c + * + * Copyright 2006-2012 David G. Barnes, Paul Bourke, Christopher Fluke + * + * This file is part of S2PLOT. + * + * S2PLOT 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. + * + * S2PLOT 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 S2PLOT. If not, see . + * + * We would appreciate it if research outcomes using S2PLOT would + * provide the following acknowledgement: + * + * "Three-dimensional visualisation was conducted with the S2PLOT + * progamming library" + * + * and a reference to + * + * D.G.Barnes, C.J.Fluke, P.D.Bourke & O.T.Parry, 2006, Publications + * of the Astronomical Society of Australia, 23(2), 82-93. + * + */ + +#include +#include +#include "s2plot.h" + +int main(int argc, char *argv[]) +{ + char xopt[] = "BCDETMNOPQ"; + char yopt[] = "BCDETMNOPQ"; + char zopt[] = "BCDETMNOPQ"; + + s2opend("/?",argc, argv); /* Open the display */ + s2swin(-1.,1., -1.,1., -1.,1.); /* Set the window coordinates */ + s2box(xopt, 0,0, yopt, 0,0, zopt, 0,0); /* Draw the coordinate box */ + s2lab("X-axis","Y-axis","Z-axis","Plot"); /* Write some labels */ + s2show(1); /* Open the s2plot window */ + + return 1; +} diff --git a/pool/shard006/C/0119600_init_decoder.c b/pool/shard006/C/0119600_init_decoder.c new file mode 100644 index 0000000000000000000000000000000000000000..8833c5a551e8aa0605fe5c6fc69019bbf9f7095b --- /dev/null +++ b/pool/shard006/C/0119600_init_decoder.c @@ -0,0 +1,57 @@ +/*********************************************************************** +Copyright (c) 2006-2011, Skype Limited. 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 Internet Society, IETF or IETF Trust, nor the +names of specific 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. +***********************************************************************/ + +//#ifdef HAVE_CONFIG_H +#include "opus__config.h" +//#endif + +#include "main.h" + +/************************/ +/* Init Decoder State */ +/************************/ +opus_int silk_init_decoder( + silk_decoder_state *psDec /* I/O Decoder state pointer */ +) +{ + /* Clear the entire encoder state, except anything copied */ + silk_memset( psDec, 0, sizeof( silk_decoder_state ) ); + + /* Used to deactivate LSF interpolation */ + psDec->first_frame_after_reset = 1; + psDec->prev_gain_Q16 = 65536; + psDec->arch = opus_select_arch(); + + /* Reset CNG state */ + silk_CNG_Reset( psDec ); + + /* Reset PLC state */ + silk_PLC_Reset( psDec ); + + return(0); +} + diff --git a/pool/shard006/C/0119602_cmdline.c b/pool/shard006/C/0119602_cmdline.c new file mode 100644 index 0000000000000000000000000000000000000000..668e407973571935889ae4d5afdd59e93d1e12dd --- /dev/null +++ b/pool/shard006/C/0119602_cmdline.c @@ -0,0 +1,104 @@ +/* + * 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. + * + * cmdline.c: Kernel command line creation using ARCS argc/argv. + * + * Copyright (C) 1996 David S. Miller (davem@davemloft.net) + */ +#include +#include +#include +#include + +#include +#include + +#undef DEBUG_CMDLINE + +static char *ignored[] = { + "ConsoleIn=", + "ConsoleOut=", + "SystemPartition=", + "OSLoader=", + "OSLoadPartition=", + "OSLoadFilename=", + "OSLoadOptions=" +}; + +static char *used_arc[][2] = { + { "OSLoadPartition=", "root=" }, + { "OSLoadOptions=", "" } +}; + +static char * __init move_firmware_args(char* cp) +{ + char *s; + int actr, i; + + actr = 1; /* */ + + while (actr < prom_argc) { + for(i = 0; i < ARRAY_SIZE(used_arc); i++) { + int len = strlen(used_arc[i][0]); + + if (!strncmp(prom_argv(actr), used_arc[i][0], len)) { + /* */ + strcat(cp, used_arc[i][1]); + cp += strlen(used_arc[i][1]); + /* */ + s = strchr(prom_argv(actr), '='); + if (s) { + s++; + strcpy(cp, s); + cp += strlen(s); + } + *cp++ = ' '; + break; + } + } + actr++; + } + + return cp; +} + +void __init prom_init_cmdline(void) +{ + char *cp; + int actr, i; + + actr = 1; /* */ + + cp = arcs_cmdline; + /* + + + */ + cp = move_firmware_args(cp); + + while (actr < prom_argc) { + for (i = 0; i < ARRAY_SIZE(ignored); i++) { + int len = strlen(ignored[i]); + + if (!strncmp(prom_argv(actr), ignored[i], len)) + goto pic_cont; + } + /* */ + strcpy(cp, prom_argv(actr)); + cp += strlen(prom_argv(actr)); + *cp++ = ' '; + + pic_cont: + actr++; + } + + if (cp != arcs_cmdline) /* */ + --cp; + *cp = '\0'; + +#ifdef DEBUG_CMDLINE + printk(KERN_DEBUG "prom cmdline: %s\n", arcs_cmdline); +#endif +} diff --git a/pool/shard006/C/0119611_ip6table_raw.c b/pool/shard006/C/0119611_ip6table_raw.c new file mode 100644 index 0000000000000000000000000000000000000000..8f7109f991e6032b7c2f671f8678ebb14a3f06dd --- /dev/null +++ b/pool/shard006/C/0119611_ip6table_raw.c @@ -0,0 +1,103 @@ +/* + * IPv6 raw table, a port of the IPv4 raw table to IPv6 + * + * Copyright (C) 2003 Jozsef Kadlecsik + */ +#include +#include + +#define RAW_VALID_HOOKS ((1 << NF_IP6_PRE_ROUTING) | (1 << NF_IP6_LOCAL_OUT)) + +static struct +{ + struct ip6t_replace repl; + struct ip6t_standard entries[2]; + struct ip6t_error term; +} initial_table __initdata = { + .repl = { + .name = "raw", + .valid_hooks = RAW_VALID_HOOKS, + .num_entries = 3, + .size = sizeof(struct ip6t_standard) * 2 + sizeof(struct ip6t_error), + .hook_entry = { + [NF_IP6_PRE_ROUTING] = 0, + [NF_IP6_LOCAL_OUT] = sizeof(struct ip6t_standard) + }, + .underflow = { + [NF_IP6_PRE_ROUTING] = 0, + [NF_IP6_LOCAL_OUT] = sizeof(struct ip6t_standard) + }, + }, + .entries = { + IP6T_STANDARD_INIT(NF_ACCEPT), /* PRE_ROUTING */ + IP6T_STANDARD_INIT(NF_ACCEPT), /* LOCAL_OUT */ + }, + .term = IP6T_ERROR_INIT, /* ERROR */ +}; + +static struct xt_table packet_raw = { + .name = "raw", + .valid_hooks = RAW_VALID_HOOKS, + .lock = RW_LOCK_UNLOCKED, + .me = THIS_MODULE, + .af = AF_INET6, +}; + +/* The work comes in here from netfilter.c. */ +static unsigned int +ip6t_hook(unsigned int hook, + struct sk_buff *skb, + const struct net_device *in, + const struct net_device *out, + int (*okfn)(struct sk_buff *)) +{ + return ip6t_do_table(skb, hook, in, out, &packet_raw); +} + +static struct nf_hook_ops ip6t_ops[] = { + { + .hook = ip6t_hook, + .pf = PF_INET6, + .hooknum = NF_IP6_PRE_ROUTING, + .priority = NF_IP6_PRI_FIRST, + .owner = THIS_MODULE, + }, + { + .hook = ip6t_hook, + .pf = PF_INET6, + .hooknum = NF_IP6_LOCAL_OUT, + .priority = NF_IP6_PRI_FIRST, + .owner = THIS_MODULE, + }, +}; + +static int __init ip6table_raw_init(void) +{ + int ret; + + /* Register table */ + ret = ip6t_register_table(&packet_raw, &initial_table.repl); + if (ret < 0) + return ret; + + /* Register hooks */ + ret = nf_register_hooks(ip6t_ops, ARRAY_SIZE(ip6t_ops)); + if (ret < 0) + goto cleanup_table; + + return ret; + + cleanup_table: + ip6t_unregister_table(&packet_raw); + return ret; +} + +static void __exit ip6table_raw_fini(void) +{ + nf_unregister_hooks(ip6t_ops, ARRAY_SIZE(ip6t_ops)); + ip6t_unregister_table(&packet_raw); +} + +module_init(ip6table_raw_init); +module_exit(ip6table_raw_fini); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0119615_drv_sram.c b/pool/shard006/C/0119615_drv_sram.c new file mode 100644 index 0000000000000000000000000000000000000000..416e6863a7f357eb70a2b78ae5763aa1059d7c18 --- /dev/null +++ b/pool/shard006/C/0119615_drv_sram.c @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2006-2021, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2018-12-04 zylx first version + */ + +#include +#include +#include + +#ifdef BSP_USING_SRAM +#include + +#define DRV_DEBUG +#define LOG_TAG "drv.sram" +#include + +static SRAM_HandleTypeDef hsram; +static FMC_NORSRAM_TimingTypeDef SRAM_Timing; +#ifdef RT_USING_MEMHEAP_AS_HEAP +static struct rt_memheap system_heap; +#endif + +static int SRAM_Init(void) +{ + int result = RT_EOK; + + /* SRAM device configuration */ + hsram.Instance = FMC_NORSRAM_DEVICE; + hsram.Extended = FMC_NORSRAM_EXTENDED_DEVICE; + + /* SRAM device configuration */ + SRAM_Timing.AddressSetupTime = ADDRESSSETUPTIME; + SRAM_Timing.AddressHoldTime = ADDRESSHOLDTIME; /* Min value, Don't care on SRAM Access mode A */ + SRAM_Timing.DataSetupTime = DATASETUPTIME; + SRAM_Timing.DataHoldTime = DATAHOLDTIME; + SRAM_Timing.BusTurnAroundDuration = BUSTURNAROUNDDURATION; + SRAM_Timing.CLKDivision = CLKDIVISION; /* Min value, Don't care on SRAM Access mode A */ + SRAM_Timing.DataLatency = DATALATENCY; /* Min value, Don't care on SRAM Access mode A */ + SRAM_Timing.AccessMode = ACCESSMODE; + + hsram.Init.NSBank = FMC_NORSRAM_BANK1; + hsram.Init.DataAddressMux = FMC_DATA_ADDRESS_MUX_DISABLE; + hsram.Init.MemoryType = FMC_MEMORY_TYPE_SRAM; +#if SRAM_DATA_WIDTH == 8 + hsram.Init.MemoryDataWidth = FMC_NORSRAM_MEM_BUS_WIDTH_8; +#elif SRAM_DATA_WIDTH == 16 + hsram.Init.MemoryDataWidth = FMC_NORSRAM_MEM_BUS_WIDTH_16; +#else + hsram.Init.MemoryDataWidth = FMC_NORSRAM_MEM_BUS_WIDTH_32; +#endif + hsram.Init.BurstAccessMode = FMC_BURST_ACCESS_MODE_DISABLE; + hsram.Init.WriteOperation = FMC_WRITE_OPERATION_ENABLE; + hsram.Init.WaitSignal = FMC_WAIT_SIGNAL_DISABLE; + hsram.Init.WaitSignalActive = FMC_WAIT_TIMING_BEFORE_WS; + hsram.Init.WaitSignalPolarity = FMC_WAIT_SIGNAL_POLARITY_LOW; + hsram.Init.ExtendedMode = FMC_EXTENDED_MODE_DISABLE; + hsram.Init.AsynchronousWait = FMC_ASYNCHRONOUS_WAIT_DISABLE; + hsram.Init.WriteBurst = FMC_WRITE_BURST_DISABLE; + hsram.Init.ContinuousClock = FMC_CONTINUOUS_CLOCK_SYNC_ONLY; + hsram.Init.WriteFifo = FMC_WRITE_FIFO_DISABLE; + hsram.Init.NBLSetupTime = 0; + hsram.Init.PageSize = FMC_PAGE_SIZE_NONE; + + /* Initialize the SRAM controller */ + if (HAL_SRAM_Init(&hsram, &SRAM_Timing, &SRAM_Timing) != HAL_OK) + { + LOG_E("SRAM init failed!"); + result = -RT_ERROR; + } + else + { + LOG_D("sram init success, mapped at 0x%X, size is %d bytes, data width is %d", SRAM_BANK_ADDR, SRAM_SIZE, SRAM_DATA_WIDTH); +#ifdef RT_USING_MEMHEAP_AS_HEAP + /* If RT_USING_MEMHEAP_AS_HEAP is enabled, SRAM is initialized to the heap */ + rt_memheap_init(&system_heap, "sram", (void *)SRAM_BANK_ADDR, SRAM_SIZE); +#endif + } + + return result; +} +INIT_BOARD_EXPORT(SRAM_Init); + +#ifdef DRV_DEBUG +#ifdef FINSH_USING_MSH +int sram_test(void) +{ + int i = 0; + uint32_t start_time = 0, time_cast = 0; +#if SRAM_DATA_WIDTH == 8 + char data_width = 1; + uint8_t data = 0; + uint8_t *ptr = (uint8_t *)SRAM_BANK_ADDR; +#elif SRAM_DATA_WIDTH == 16 + char data_width = 2; + uint16_t data = 0; + uint16_t *ptr = (uint16_t *)SRAM_BANK_ADDR; +#else + char data_width = 4; + uint32_t data = 0; + uint32_t *ptr = (uint32_t *)SRAM_BANK_ADDR; +#endif + + /* write data */ + LOG_D("Writing the %ld bytes data, waiting....", SRAM_SIZE); + start_time = rt_tick_get(); + for (i = 0; i < SRAM_SIZE / data_width; i++) + { +#if SRAM_DATA_WIDTH == 8 + ((__IO uint8_t *)ptr)[i] = (uint8_t)0x55; +#elif SRAM_DATA_WIDTH == 16 + ((__IO uint16_t *)ptr)[i] = (uint16_t)0x5555; +#else + ((__IO uint32_t *)ptr)[i] = (uint32_t)0x55555555; +#endif + } + time_cast = rt_tick_get() - start_time; + LOG_D("Write data success, total time: %d.%03dS.", time_cast / RT_TICK_PER_SECOND, + time_cast % RT_TICK_PER_SECOND / ((RT_TICK_PER_SECOND * 1 + 999) / 1000)); + + /* read data */ + LOG_D("start Reading and verifying data, waiting...."); + for (i = 0; i < SRAM_SIZE / data_width; i++) + { +#if SRAM_DATA_WIDTH == 8 + data = ((__IO uint8_t *)ptr)[i]; + if (data != 0x55) + { + LOG_E("SRAM test failed!"); + break; + } +#elif SRAM_DATA_WIDTH == 16 + data = ((__IO uint16_t *)ptr)[i]; + if (data != 0x5555) + { + LOG_E("SRAM test failed!"); + break; + } +#else + data = ((__IO uint32_t *)ptr)[i]; + if (data != 0x55555555) + { + LOG_E("SRAM test failed!"); + break; + } +#endif + } + + if (i >= SRAM_SIZE / data_width) + { + LOG_D("SRAM test success!"); + } + + return RT_EOK; +} +MSH_CMD_EXPORT(sram_test, sram test); +#endif /* FINSH_USING_MSH */ +#endif /* DRV_DEBUG */ +#endif /* BSP_USING_SRAM */ diff --git a/pool/shard006/C/0119616_kdebug.c b/pool/shard006/C/0119616_kdebug.c new file mode 100644 index 0000000000000000000000000000000000000000..b790c0f5e9d706ed113ca9e0b6832d5e6646b0a6 --- /dev/null +++ b/pool/shard006/C/0119616_kdebug.c @@ -0,0 +1,209 @@ +#include +#include +#include +#include + +#include + +extern const struct Stab __STAB_BEGIN__[]; // Beginning of stabs table +extern const struct Stab __STAB_END__[]; // End of stabs table +extern const char __STABSTR_BEGIN__[]; // Beginning of string table +extern const char __STABSTR_END__[]; // End of string table + + +// stab_binsearch(stabs, region_left, region_right, type, addr) +// +// Some stab types are arranged in increasing order by instruction +// address. For example, N_FUN stabs (stab entries with n_type == +// N_FUN), which mark functions, and N_SO stabs, which mark source files. +// +// Given an instruction address, this function finds the single stab +// entry of type 'type' that contains that address. +// +// The search takes place within the range [*region_left, *region_right]. +// Thus, to search an entire set of N stabs, you might do: +// +// left = 0; +// right = N - 1; /* rightmost stab */ +// stab_binsearch(stabs, &left, &right, type, addr); +// +// The search modifies *region_left and *region_right to bracket the +// 'addr'. *region_left points to the matching stab that contains +// 'addr', and *region_right points just before the next stab. If +// *region_left > *region_right, then 'addr' is not contained in any +// matching stab. +// +// For example, given these N_SO stabs: +// Index Type Address +// 0 SO f0100000 +// 13 SO f0100040 +// 117 SO f0100176 +// 118 SO f0100178 +// 555 SO f0100652 +// 556 SO f0100654 +// 657 SO f0100849 +// this code: +// left = 0, right = 657; +// stab_binsearch(stabs, &left, &right, N_SO, 0xf0100184); +// will exit setting left = 118, right = 554. +// +static void +stab_binsearch(const struct Stab *stabs, int *region_left, int *region_right, + int type, uintptr_t addr) +{ + int l = *region_left, r = *region_right, any_matches = 0; + + while (l <= r) { + int true_m = (l + r) / 2, m = true_m; + + // search for earliest stab with right type + while (m >= l && stabs[m].n_type != type) + m--; + if (m < l) { // no match in [l, m] + l = true_m + 1; + continue; + } + + // actual binary search + any_matches = 1; + if (stabs[m].n_value < addr) { + *region_left = m; + l = true_m + 1; + } else if (stabs[m].n_value > addr) { + *region_right = m - 1; + r = m - 1; + } else { + // exact match for 'addr', but continue loop to find + // *region_right + *region_left = m; + l = m; + addr++; + } + } + + if (!any_matches) + *region_right = *region_left - 1; + else { + // find rightmost region containing 'addr' + for (l = *region_right; + l > *region_left && stabs[l].n_type != type; + l--) + /* do nothing */; + *region_left = l; + } +} + + +// debuginfo_eip(addr, info) +// +// Fill in the 'info' structure with information about the specified +// instruction address, 'addr'. Returns 0 if information was found, and +// negative if not. But even if it returns negative it has stored some +// information into '*info'. +// +int +debuginfo_eip(uintptr_t addr, struct Eipdebuginfo *info) +{ + const struct Stab *stabs, *stab_end; + const char *stabstr, *stabstr_end; + int lfile, rfile, lfun, rfun, lline, rline; + + // Initialize *info + info->eip_file = ""; + info->eip_line = 0; + info->eip_fn_name = ""; + info->eip_fn_namelen = 9; + info->eip_fn_addr = addr; + info->eip_fn_narg = 0; + + // Find the relevant set of stabs + if (addr >= ULIM) { + stabs = __STAB_BEGIN__; + stab_end = __STAB_END__; + stabstr = __STABSTR_BEGIN__; + stabstr_end = __STABSTR_END__; + } else { + // Can't search for user-level addresses yet! + panic("User address"); + } + + // String table validity checks + if (stabstr_end <= stabstr || stabstr_end[-1] != 0) + return -1; + + // Now we find the right stabs that define the function containing + // 'eip'. First, we find the basic source file containing 'eip'. + // Then, we look in that source file for the function. Then we look + // for the line number. + + // Search the entire set of stabs for the source file (type N_SO). + lfile = 0; + rfile = (stab_end - stabs) - 1; + stab_binsearch(stabs, &lfile, &rfile, N_SO, addr); + if (lfile == 0) + return -1; + + // Search within that file's stabs for the function definition + // (N_FUN). + lfun = lfile; + rfun = rfile; + stab_binsearch(stabs, &lfun, &rfun, N_FUN, addr); + + if (lfun <= rfun) { + // stabs[lfun] points to the function name + // in the string table, but check bounds just in case. + if (stabs[lfun].n_strx < stabstr_end - stabstr) + info->eip_fn_name = stabstr + stabs[lfun].n_strx; + info->eip_fn_addr = stabs[lfun].n_value; + addr -= info->eip_fn_addr; + // Search within the function definition for the line number. + lline = lfun; + rline = rfun; + } else { + // Couldn't find function stab! Maybe we're in an assembly + // file. Search the whole file for the line number. + info->eip_fn_addr = addr; + lline = lfile; + rline = rfile; + } + // Ignore stuff after the colon. + info->eip_fn_namelen = strfind(info->eip_fn_name, ':') - info->eip_fn_name; + + + // Search within [lline, rline] for the line number stab. + // If found, set info->eip_line to the right line number. + // If not found, return -1. + // + // Hint: + // There's a particular stabs type used for line numbers. + // Look at the STABS documentation and to find + // which one. + stab_binsearch(stabs, &lline, &rline, N_SLINE, addr); + if (lline == 0) + return -1; + else + info->eip_line = stabs[lline].n_desc; + + // Search backwards from the line number for the relevant filename + // stab. + // We can't just use the "lfile" stab because inlined functions + // can interpolate code from a different file! + // Such included source files use the N_SOL stab type. + while (lline >= lfile + && stabs[lline].n_type != N_SOL + && (stabs[lline].n_type != N_SO || !stabs[lline].n_value)) + lline--; + if (lline >= lfile && stabs[lline].n_strx < stabstr_end - stabstr) + info->eip_file = stabstr + stabs[lline].n_strx; + + + // Set eip_fn_narg to the number of arguments taken by the function, + // or 0 if there was no containing function. + if (lfun < rfun) + for (lline = lfun + 1; + lline < rfun && stabs[lline].n_type == N_PSYM; + lline++) + info->eip_fn_narg++; + + return 0; +} diff --git a/pool/shard006/C/0119619_add_recursive-test.c b/pool/shard006/C/0119619_add_recursive-test.c new file mode 100644 index 0000000000000000000000000000000000000000..cd29b790ffc727716031226b500e8126c06b3be9 --- /dev/null +++ b/pool/shard006/C/0119619_add_recursive-test.c @@ -0,0 +1,27 @@ +#include + +#ifdef _MSC_VER +# define DLLIMPORT __declspec(dllimport) +#else +# define DLLIMPORT extern +#endif + +DLLIMPORT int add_rec(int, int); +DLLIMPORT int (*my_callback)(int); + +static int some_callback(int x) +{ + printf("some_callback(%d)\n", x); + fflush(stdout); + return add_rec(x, 9); +} + +int main(void) +{ + int x, y; + my_callback = some_callback; + x = add_rec(40, 2); + y = add_rec(100, -5); + printf("got: %d %d\n", x, y); + return 0; +} diff --git a/pool/shard006/C/0119623_sha.c b/pool/shard006/C/0119623_sha.c new file mode 100644 index 0000000000000000000000000000000000000000..61ead904a967452fc79fe993641bd6dace3a34d2 --- /dev/null +++ b/pool/shard006/C/0119623_sha.c @@ -0,0 +1,28 @@ +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "../demo.h" + +static tb_void_t tb_test_sha(tb_size_t mode, tb_char_t const* data) +{ + tb_byte_t ob[32]; + tb_size_t on = tb_sha_make(mode, (tb_byte_t const*)data, tb_strlen(data), ob, 32); + tb_assert_and_check_return((on << 3) == mode); + + tb_size_t i = 0; + tb_char_t sha[256] = {0}; + for (i = 0; i < on; ++i) tb_snprintf(sha + (i << 1), 3, "%02X", ob[i]); + tb_printf("[sha]: %d = %s\n", mode, sha); +} + +/* ////////////////////////////////////////////////////////////////////////////////////// + * main + */ +tb_int_t tb_demo_hash_sha_main(tb_int_t argc, tb_char_t** argv) +{ + tb_test_sha(TB_SHA_MODE_SHA1_160, argv[1]); + tb_test_sha(TB_SHA_MODE_SHA2_224, argv[1]); + tb_test_sha(TB_SHA_MODE_SHA2_256, argv[1]); + + return 0; +} diff --git a/pool/shard006/C/0119624_crypto.c b/pool/shard006/C/0119624_crypto.c new file mode 100644 index 0000000000000000000000000000000000000000..8c080dc025c393ec7dade6cac2ff231a8cf8884c --- /dev/null +++ b/pool/shard006/C/0119624_crypto.c @@ -0,0 +1,223 @@ +/* Copyright (C) 2013 CZ.NIC, z.s.p.o. + + 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 . +*/ + +#include +#include +#include +#include +#include +#include + +#include "libknot/common.h" +#include "libknot/dnssec/config.h" +#include "libknot/dnssec/crypto.h" + +/*- thread safety -----------------------------------------------------------*/ + +/*! + * \brief Mutexes to be used by OpenSSL. + */ +static pthread_mutex_t *openssl_mutex = NULL; +static int openssl_mutex_count = 0; + +/*! + * \brief Callback for OpenSSL mutex locking and unlocking. + * + * \see CRYPTO_set_locking_callback() in OpenSSL documentation. + * + * \param mode Locking mode. + * \param n Mutex number. + * \param file Source file where locking occurs (for debugging). + * \param line Line number where locking occurs (for debugging). + */ +static void openssl_mutex_cb(int mode, int n, const char *file, int line) +{ + UNUSED(file); + UNUSED(line); + + assert(openssl_mutex); + assert(n < openssl_mutex_count); + + pthread_mutex_t *mutex = &openssl_mutex[n]; + + if (mode & CRYPTO_LOCK) { + pthread_mutex_lock(mutex); + } else { + pthread_mutex_unlock(mutex); + } +} + +/*! + * \brief Initialize mutexes for OpenSSL usage. + */ +static void openssl_mutexes_init(void) +{ + assert(openssl_mutex_count == 0); + assert(openssl_mutex == NULL); + + openssl_mutex_count = CRYPTO_num_locks(); + if (openssl_mutex_count == 0) { + return; + } + + openssl_mutex = calloc(openssl_mutex_count, sizeof(pthread_mutex_t)); + for (int i = 0; i < openssl_mutex_count; i++) { + pthread_mutex_init(&openssl_mutex[i], NULL); + } + + CRYPTO_set_locking_callback(openssl_mutex_cb); +} + +/*! + * \brief Destroy mutexes for OpenSSL usage. + */ +static void openssl_mutexes_destroy(void) +{ + assert(openssl_mutex); + + for (int i = 0; i < openssl_mutex_count; i++) { + pthread_mutex_destroy(&openssl_mutex[i]); + } + + free(openssl_mutex); + + openssl_mutex_count = 0; + openssl_mutex = NULL; +} + +/*! + * \brief Callback for thread identification for purpose of OpenSSL. + * + * \see CRYPTO_THREADID_set_callback() in OpenSSL documentation. + * + * \param openssl_id Thread identifier in OpenSSL. + */ +#if OPENSSL_VERSION_NUMBER >= 0x1000001fL +static void openssl_threadid_cb(CRYPTO_THREADID *openssl_id) +{ + pthread_t id = pthread_self(); + CRYPTO_THREADID_set_pointer(openssl_id, (void *)id); +} +#else +static unsigned long openssl_threadid_cb(void) +{ + unsigned long ret; + ret = (unsigned long)pthread_self(); + return(ret); +} +#endif + +/*- pluggable engines -------------------------------------------------------*/ + +#if KNOT_ENABLE_GOST + +static ENGINE *gost_engine = NULL; + +static void init_gost_engine(void) +{ + assert(gost_engine == NULL); + +#ifndef OPENSSL_NO_STATIC_ENGINE + ENGINE_load_gost(); +#else + ENGINE_load_dynamic(); +#endif + + gost_engine = ENGINE_by_id("gost"); + if (!gost_engine) { + return; + } + + ENGINE_init(gost_engine); + ENGINE_register_pkey_asn1_meths(gost_engine); + ENGINE_ctrl_cmd_string(gost_engine, "CRYPT_PARAMS", + "id-Gost28147-89-CryptoPro-A-ParamSet", 0); +} + +static void deinit_gost_engine(void) +{ + assert(gost_engine); + + ENGINE_finish(gost_engine); + ENGINE_free(gost_engine); + + gost_engine = NULL; +} + +#endif + +/*- public API --------------------------------------------------------------*/ + +void knot_crypto_init(void) +{ + OpenSSL_add_all_digests(); +} + +void knot_crypto_cleanup(void) +{ + knot_crypto_unload_engines(); + + EVP_cleanup(); + CRYPTO_cleanup_all_ex_data(); + ERR_free_strings(); + + knot_crypto_cleanup_thread(); +} + +void knot_crypto_cleanup_thread(void) +{ + ERR_remove_state(0); +} + +void knot_crypto_init_threads(void) +{ + // locking + if (!openssl_mutex) { + openssl_mutexes_init(); + } + + // thread identification +#if OPENSSL_VERSION_NUMBER >= 0x1000001fL + CRYPTO_THREADID_set_callback(openssl_threadid_cb); +#else + CRYPTO_set_id_callback((unsigned long (*)())openssl_threadid_cb); +#endif +} + +void knot_crypto_cleanup_threads(void) +{ + if (openssl_mutex) { + openssl_mutexes_destroy(); + } +} + +void knot_crypto_load_engines(void) +{ +#if KNOT_ENABLE_GOST + if (!gost_engine) { + init_gost_engine(); + } +#endif +} + +void knot_crypto_unload_engines(void) +{ +#if KNOT_ENABLE_GOST + if (gost_engine) { + deinit_gost_engine(); + } +#endif +} diff --git a/pool/shard006/C/0119625_lab1.fork2.c b/pool/shard006/C/0119625_lab1.fork2.c new file mode 100644 index 0000000000000000000000000000000000000000..b6d1e4cbdfc5aaac84db7cb7751183e96876bd29 --- /dev/null +++ b/pool/shard006/C/0119625_lab1.fork2.c @@ -0,0 +1,37 @@ +// ОС. Лаб. 1.2 +// Общение родительского и дочернего процесса. +// Родительский пишет дочернему. + +#include +#include +#include + +int main (void) +{ + int fd[2]; + int id; + char string[] = "Jaaasooon!\n"; + char readbuffer[64]; + pipe(fd); + id = fork(); + + if(id == 0) + { + printf("+Start child work\n"); + close(fd[1]); + read(fd[0], readbuffer, sizeof(readbuffer)); + printf("Received string: %s", readbuffer); + printf("+Finish child work\n"); + return 0; + } + else + { + printf("+Start parent work\n"); + printf("Parent ID %d\n", id); + close(fd[0]); + write(fd[1], string, (strlen(string) + 1)); + printf("+Finish parent work\n"); + return 0; + } + return 0; +} diff --git a/pool/shard006/C/0119630_alter_crecip.c b/pool/shard006/C/0119630_alter_crecip.c new file mode 100644 index 0000000000000000000000000000000000000000..e5490db24657505e86bcbc2dc760d3106bad3b97 --- /dev/null +++ b/pool/shard006/C/0119630_alter_crecip.c @@ -0,0 +1,83 @@ +/* Copyright (C) 2010-2011 D. V. Wiebe + * + *************************************************************************** + * + * This file is part of the GetData project. + * + * GetData 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. + * + * GetData 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 GetData; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +/* Test field modifying */ +#include "test.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +int main(void) +{ + const char *filedir = "dirfile"; + const char *format = "dirfile/format"; + const char *data = "dirfile/data"; + const char *format_data = "data RAW INT32 8\nphase PHASE data 1\n" + "div RECIP data 230.\n"; + int32_t data_data[256]; + double c[8]; +#ifdef GD_NO_C99_API + double v[2] = {1093, 3290}; +#else + double complex v = 1093 + _Complex_I * 3290; +#endif + int fd, i, ret, error, n, r = 0; + DIRFILE *D; + + rmdirfile(); + mkdir(filedir, 0777); + + for (fd = 0; fd < 256; ++fd) + data_data[fd] = (int32_t)fd; + + fd = open(format, O_CREAT | O_EXCL | O_WRONLY, 0666); + write(fd, format_data, strlen(format_data)); + close(fd); + + fd = open(data, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0666); + write(fd, data_data, 256 * sizeof(int32_t)); + close(fd); + + D = gd_open(filedir, GD_RDWR | GD_VERBOSE); + ret = gd_alter_crecip(D, "div", "phase", v); + error = gd_error(D); + n = gd_getdata(D, "div", 5, 0, 1, 0, GD_FLOAT64, c); + + gd_close(D); + + for (i = 0; i < 8; ++i) + CHECKFi(i,c[i], creal(v) / (i + 41.)); + + unlink(data); + unlink(format); + rmdir(filedir); + + CHECKI(error,0); + CHECKI(n,8); + CHECKI(ret,0); + + return r; +} diff --git a/pool/shard006/C/0119638_xml_namespace.c b/pool/shard006/C/0119638_xml_namespace.c new file mode 100644 index 0000000000000000000000000000000000000000..d7803fc1e91fabc0f47d22462989280928e8a0e1 --- /dev/null +++ b/pool/shard006/C/0119638_xml_namespace.c @@ -0,0 +1,84 @@ +#include + +VALUE cNokogiriXmlNamespace ; + +/* + * call-seq: + * prefix + * + * Get the prefix for this namespace. Returns +nil+ if there is no prefix. + */ +static VALUE prefix(VALUE self) +{ + xmlNsPtr ns; + xmlDocPtr doc; + + Data_Get_Struct(self, xmlNs, ns); + if(!ns->prefix) return Qnil; + + Data_Get_Struct(rb_iv_get(self, "@document"), xmlDoc, doc); + + return NOKOGIRI_STR_NEW2(ns->prefix); +} + +/* + * call-seq: + * href + * + * Get the href for this namespace + */ +static VALUE href(VALUE self) +{ + xmlNsPtr ns; + xmlDocPtr doc; + + Data_Get_Struct(self, xmlNs, ns); + if(!ns->href) return Qnil; + + Data_Get_Struct(rb_iv_get(self, "@document"), xmlDoc, doc); + + return NOKOGIRI_STR_NEW2(ns->href); +} + +VALUE Nokogiri_wrap_xml_namespace(xmlDocPtr doc, xmlNsPtr node) +{ + VALUE ns, document, node_cache; + + assert(doc->_private); + + if(node->_private) + return (VALUE)node->_private; + + ns = Data_Wrap_Struct(cNokogiriXmlNamespace, 0, 0, node); + + document = DOC_RUBY_OBJECT(doc); + + node_cache = rb_iv_get(document, "@node_cache"); + rb_ary_push(node_cache, ns); + + rb_iv_set(ns, "@document", DOC_RUBY_OBJECT(doc)); + + node->_private = (void *)ns; + + return ns; +} + +VALUE Nokogiri_wrap_xml_namespace2(VALUE document, xmlNsPtr node) +{ + xmlDocPtr doc; + Data_Get_Struct(document, xmlDoc, doc) ; + return Nokogiri_wrap_xml_namespace(doc, node); +} + + +void init_xml_namespace() +{ + VALUE nokogiri = rb_define_module("Nokogiri"); + VALUE xml = rb_define_module_under(nokogiri, "XML"); + VALUE klass = rb_define_class_under(xml, "Namespace", rb_cObject); + + cNokogiriXmlNamespace = klass; + + rb_define_method(klass, "prefix", prefix, 0); + rb_define_method(klass, "href", href, 0); +} diff --git a/pool/shard006/C/0119653_ompss-codelocation.c b/pool/shard006/C/0119653_ompss-codelocation.c new file mode 100644 index 0000000000000000000000000000000000000000..2fde7b0548e270a4d58531d756670f027b84632d --- /dev/null +++ b/pool/shard006/C/0119653_ompss-codelocation.c @@ -0,0 +1,129 @@ +/*****************************************************************************\ + * ANALYSIS PERFORMANCE TOOLS * + * Extrae * + * Instrumentation package for parallel applications * + ***************************************************************************** + * ___ This library is free software; you can redistribute it and/or * + * / __ modify it under the terms of the GNU LGPL as published * + * / / _____ by the Free Software Foundation; either version 2.1 * + * / / / \ of the License, or (at your option) any later version. * + * ( ( ( B S C ) * + * \ \ \_____/ This library is distributed in 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 LGPL 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 Street, Fifth Floor, Boston, MA 02110-1301 USA * + * The GNU LEsser General Public License is contained in the file COPYING. * + * --------- * + * Barcelona Supercomputing Center - Centro Nacional de Supercomputacion * +\*****************************************************************************/ + +#include +#include + +#include "extrae_user_events.h" + +#define UNREFERENCED(x) ((x)=(x)) + +double pi_kernel (int n, double h) +{ + double tmp = 0; + double x; + int i; + extrae_combined_events_t evt; + + extrae_type_t type = 2020; + extrae_value_t enter = (extrae_value_t) pi_kernel, leave = 0; + + Extrae_register_function_address ((void*)1234 /* pi_kernel */, (char*)__FUNCTION__, (char*)__FILE__, __LINE__); + + Extrae_init_CombinedEvents (&evt); + evt.nEvents = 1; + evt.Types = &type; + evt.Values = &enter; + Extrae_emit_CombinedEvents (&evt); + + for (i = 1; i <= n; i++) + { + x = h * ((double)i - 0.5); + tmp += (4.0 / (1.0 + x*x)); + } + + evt.nEvents = 1; + evt.Types = &type; + evt.Values = &leave; + Extrae_emit_CombinedEvents (&evt); + + return tmp; +} + +void sleep_kernel (int n) +{ + extrae_combined_events_t evt; + extrae_type_t type = 2020; + extrae_value_t enter = (extrae_value_t) sleep_kernel, leave = 0; + + Extrae_register_function_address ((void*)2345 /* sleep_kernel */, (char*)__FUNCTION__, (char*)__FILE__, __LINE__); + + Extrae_init_CombinedEvents (&evt); + evt.nEvents = 1; + evt.Types = &type; + evt.Values = &enter; + Extrae_emit_CombinedEvents (&evt); + + printf ("in sleep_kernel (%d)\n", n); + + evt.nEvents = 1; + evt.Types = &type; + evt.Values = &leave; + Extrae_emit_CombinedEvents (&evt); +} + +void fake_kernel (void) +{ + extrae_combined_events_t evt; + extrae_type_t type = 2020; + extrae_value_t enter = (extrae_value_t) fake_kernel, leave = 0; + + Extrae_register_function_address ((void*)3456 /* fake_kernel */, "my_function", "my_file.c", 10); + + Extrae_init_CombinedEvents (&evt); + evt.nEvents = 1; + evt.Types = &type; + evt.Values = &enter; + Extrae_emit_CombinedEvents (&evt); + + printf ("in fake_kernel ()\n"); + + evt.nEvents = 1; + evt.Types = &type; + evt.Values = &leave; + Extrae_emit_CombinedEvents (&evt); +} + +int main(int argc, char **argv) +{ + int n = 1000; + double PI25DT = 3.141592653589793238462643; + double pi, h, area; + + UNREFERENCED(argc); + UNREFERENCED(argv); + + Extrae_register_codelocation_type (2000, 2020, "Function-F", "Line-Source-F"); + + h = 1.0 / (double) n; + + area = pi_kernel (n, h); + pi = h * area; + printf("pi is approximately %.16f, Error is %.16f\n",pi,fabs(pi - PI25DT)); + + sleep_kernel (2); + + fake_kernel (); + + return 0; +} diff --git a/pool/shard006/C/0119661_strconv.c b/pool/shard006/C/0119661_strconv.c new file mode 100644 index 0000000000000000000000000000000000000000..c3563b9d022f78593d81d771a52d03327b054f91 --- /dev/null +++ b/pool/shard006/C/0119661_strconv.c @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +#include "jansson_private.h" +#include "strbuffer.h" + +/* need jansson_private_config.h to get the correct snprintf */ +#ifdef HAVE_CONFIG_H +#include +#endif + +#if JSON_HAVE_LOCALECONV +#include + +/* + - This code assumes that the decimal separator is exactly one + character. + + - If setlocale() is called by another thread between the call to + localeconv() and the call to sprintf() or strtod(), the result may + be wrong. setlocale() is not thread-safe and should not be used + this way. Multi-threaded programs should use uselocale() instead. +*/ + +static void to_locale(strbuffer_t *strbuffer) +{ + const char *point; + char *pos; + + point = localeconv()->decimal_point; + if(*point == '.') { + /* No conversion needed */ + return; + } + + pos = strchr(strbuffer->value, '.'); + if(pos) + *pos = *point; +} + +static void from_locale(char *buffer) +{ + const char *point; + char *pos; + + point = localeconv()->decimal_point; + if(*point == '.') { + /* No conversion needed */ + return; + } + + pos = strchr(buffer, *point); + if(pos) + *pos = '.'; +} +#endif + +int jsonp_strtod(strbuffer_t *strbuffer, double *out) +{ + double value; + char *end; + +#if JSON_HAVE_LOCALECONV + to_locale(strbuffer); +#endif + + errno = 0; + value = strtod(strbuffer->value, &end); + assert(end == strbuffer->value + strbuffer->length); + + if((value == HUGE_VAL || value == -HUGE_VAL) && errno == ERANGE) { + /* Overflow */ + return -1; + } + + *out = value; + return 0; +} + +int jsonp_dtostr(char *buffer, size_t size, double value, int precision) +{ + int ret; + char *start, *end; + size_t length; + + if (precision == 0) + precision = 17; + + ret = snprintf(buffer, size, "%.*g", precision, value); + if(ret < 0) + return -1; + + length = (size_t)ret; + if(length >= size) + return -1; + +#if JSON_HAVE_LOCALECONV + from_locale(buffer); +#endif + + /* Make sure there's a dot or 'e' in the output. Otherwise + a real is converted to an integer when decoding */ + if(strchr(buffer, '.') == NULL && + strchr(buffer, 'e') == NULL) + { + if(length + 3 >= size) { + /* No space to append ".0" */ + return -1; + } + buffer[length] = '.'; + buffer[length + 1] = '0'; + buffer[length + 2] = '\0'; + length += 2; + } + + /* Remove leading '+' from positive exponent. Also remove leading + zeros from exponents (added by some printf() implementations) */ + start = strchr(buffer, 'e'); + if(start) { + start++; + end = start + 1; + + if(*start == '-') + start++; + + while(*end == '0') + end++; + + if(end != start) { + memmove(start, end, length - (size_t)(end - buffer)); + length -= (size_t)(end - start); + } + } + + return (int)length; +} diff --git a/pool/shard006/C/0119665_s5p_mfc_intr.c b/pool/shard006/C/0119665_s5p_mfc_intr.c new file mode 100644 index 0000000000000000000000000000000000000000..1edfeb17ada8b4e2b76c965abc39bdd54a29dc62 --- /dev/null +++ b/pool/shard006/C/0119665_s5p_mfc_intr.c @@ -0,0 +1,129 @@ +/* + * drivers/media/platform/exynos/mfc/s5p_mfc_intr.c + * + * Copyright (c) 2010 Samsung Electronics Co., Ltd. + * http://www.samsung.com/ + * + * C file for Samsung MFC (Multi Function Codec - FIMV) driver + * This file contains functions used to wait for command completion. + * + * 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 +#include +#include +#include +#include + +#include "s5p_mfc_intr.h" + +#define wait_condition(x, c) (x->int_cond && \ + (R2H_BIT(x->int_type) & r2h_bits(c))) +#define is_err_cond(x) ((x->int_cond) && (x->int_type == S5P_FIMV_R2H_CMD_ERR_RET)) + +int s5p_mfc_wait_for_done_dev(struct s5p_mfc_dev *dev, int command) +{ + int ret; + + ret = wait_event_timeout(dev->queue, + wait_condition(dev, command), + msecs_to_jiffies(MFC_INT_TIMEOUT)); + if (ret == 0) { + mfc_err_dev("Interrupt (dev->int_type:%d, command:%d) timed out.\n", + dev->int_type, command); + return 1; + } + mfc_debug(1, "Finished waiting (dev->int_type:%d, command: %d).\n", + dev->int_type, command); + return 0; +} + +int s5p_mfc_wait_for_done_ctx(struct s5p_mfc_ctx *ctx, int command) +{ + int ret; + unsigned int timeout = MFC_INT_TIMEOUT; + + if (command == S5P_FIMV_R2H_CMD_CLOSE_INSTANCE_RET) + timeout = MFC_INT_SHORT_TIMEOUT; + + ret = wait_event_timeout(ctx->queue, + wait_condition(ctx, command), + msecs_to_jiffies(timeout)); + if (ret == 0) { + mfc_err_ctx("Interrupt (ctx->int_type:%d, command:%d) timed out.\n", + ctx->int_type, command); + return 1; + } else if (ret > 0) { + if (is_err_cond(ctx)) { + mfc_err_ctx("Finished (ctx->int_type:%d, command: %d).\n", + ctx->int_type, command); + mfc_err_ctx("But error (ctx->int_err:%d).\n", ctx->int_err); + return -1; + } + } + mfc_debug(1, "Finished waiting (ctx->int_type:%d, command: %d).\n", + ctx->int_type, command); + return 0; +} + +void s5p_mfc_cleanup_timeout(struct s5p_mfc_ctx *ctx) +{ + struct s5p_mfc_dev *dev = ctx->dev; + + spin_lock_irq(&dev->condlock); + clear_bit(ctx->num, &dev->ctx_work_bits); + spin_unlock_irq(&dev->condlock); +} + + +int s5p_mfc_get_new_ctx(struct s5p_mfc_dev *dev) +{ + struct s5p_mfc_ctx *ctx; + int new_ctx = 0; + int cnt = 0; + int find_ctx = 0; + + if (!dev) { + mfc_err("no mfc device to run\n"); + return -EINVAL; + } + mfc_debug(2, "Previous context: %d (bits %08lx)\n", dev->curr_ctx, + dev->ctx_work_bits); + + if (dev->preempt_ctx > MFC_NO_INSTANCE_SET) { + new_ctx = dev->preempt_ctx; + mfc_debug(2, "preempt_ctx is : %d\n", new_ctx); + } else if (dev->continue_ctx > MFC_NO_INSTANCE_SET) { + new_ctx = dev->continue_ctx; + ctx = dev->ctx[new_ctx]; + if (!ctx) { + dev->continue_ctx = MFC_NO_INSTANCE_SET; + mfc_err("no mfc context to run\n"); + return -EINVAL; + } else if (test_bit(new_ctx, &dev->ctx_stop_bits) && need_to_continue(ctx) == 0) { + dev->continue_ctx = MFC_NO_INSTANCE_SET; + mfc_debug(2, "continue_ctx is : %d, but it has ctx_stop_bits\n", new_ctx); + return -EAGAIN; + } else { + mfc_debug(2, "continue_ctx is : %d\n", new_ctx); + } + } else { + find_ctx = 1; + } + + if (find_ctx) { + new_ctx = (dev->curr_ctx + 1) % MFC_NUM_CONTEXTS; + while (!test_bit(new_ctx, &dev->ctx_work_bits)) { + new_ctx = (new_ctx + 1) % MFC_NUM_CONTEXTS; + cnt++; + if (cnt > MFC_NUM_CONTEXTS) { + /* No contexts to run */ + return -EAGAIN; + } + } + } + return new_ctx; +} diff --git a/pool/shard006/C/0119669_gssh-channel-input-stream.c b/pool/shard006/C/0119669_gssh-channel-input-stream.c new file mode 100644 index 0000000000000000000000000000000000000000..b01bb40d92eaec1b57a73e2d0b0f8fe1be0bdd16 --- /dev/null +++ b/pool/shard006/C/0119669_gssh-channel-input-stream.c @@ -0,0 +1,257 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- + * + * Copyright (C) 2013 Colin Walters + * + * 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 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#include "gssh-channel-input-stream.h" +#include "gssh-connection-private.h" +#include "gssh-channel-private.h" + +struct _GSshChannelInputStream +{ + GInputStream parent; + + GSshChannel *channel; + + gboolean is_closed; + + GTask *read_task; + GTask *close_task; + + void *buf; + gsize count; + + /* For synchronous operations */ + gboolean sync_running; + gssize sync_bytes_read; + GMainContext *sync_context; + GError *sync_error; +}; + +struct _GSshChannelInputStreamClass +{ + GInputStreamClass parent; +}; + +G_DEFINE_TYPE(GSshChannelInputStream, _gssh_channel_input_stream, G_TYPE_INPUT_STREAM); + +static void +_gssh_channel_input_stream_init (GSshChannelInputStream *self) +{ +} + +static void +_gssh_channel_input_stream_dispose (GObject *object) +{ + G_GNUC_UNUSED GSshChannelInputStream *self = (GSshChannelInputStream*)object; + + G_OBJECT_CLASS (_gssh_channel_input_stream_parent_class)->dispose (object); +} + +static gboolean +gssh_channel_input_stream_close (GInputStream *stream, + GCancellable *cancellable, + GError **error) +{ + GSshChannelInputStream *self = GSSH_CHANNEL_INPUT_STREAM (stream); + + g_return_val_if_fail (!self->is_closed, FALSE); + + self->is_closed = TRUE; + + return TRUE; +} + +static void +gssh_channel_input_stream_close_async (GInputStream *stream, + int io_priority, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer data) +{ + GSshChannelInputStream *self = GSSH_CHANNEL_INPUT_STREAM (stream); + GTask *task; + + g_return_if_fail (!self->is_closed); + + task = g_task_new (stream, cancellable, callback, data); + gssh_channel_input_stream_close (stream, cancellable, NULL); + g_task_return_boolean (task, TRUE); + g_object_unref (task); +} + +static gboolean +gssh_channel_input_stream_close_finish (GInputStream *stream, + GAsyncResult *result, + GError **error) +{ + g_return_val_if_fail (g_task_is_valid (result, stream), FALSE); + + return g_task_propagate_boolean (G_TASK (result), error); +} + +static void +gssh_channel_input_stream_read_async (GInputStream *stream, + void *buffer, + gsize count, + int io_priority, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + GSshChannelInputStream *self = GSSH_CHANNEL_INPUT_STREAM (stream); + + g_return_if_fail (!self->is_closed); + + g_assert (self->read_task == NULL); + self->read_task = g_task_new (self, cancellable, callback, user_data); + g_task_set_priority (self->read_task, io_priority); + + self->buf = buffer; + self->count = count; + + _gssh_channel_input_stream_iteration (self); +} + +static gssize +gssh_channel_input_stream_read_finish (GInputStream *stream, + GAsyncResult *result, + GError **error) +{ + g_return_val_if_fail (g_task_is_valid (result, stream), FALSE); + + return g_task_propagate_int (G_TASK (result), error); +} + +static void +on_sync_read_done (GObject *src, + GAsyncResult *result, + gpointer user_data) +{ + GSshChannelInputStream *self = GSSH_CHANNEL_INPUT_STREAM (user_data); + + self->sync_bytes_read = gssh_channel_input_stream_read_finish ((GInputStream*)self, result, &self->sync_error); + self->sync_running = FALSE; + g_main_context_wakeup (self->sync_context); +} + +static gssize +gssh_channel_input_stream_read (GInputStream *stream, + void *buffer, + gsize count, + GCancellable *cancellable, + GError **error) +{ + GSshChannelInputStream *self = GSSH_CHANNEL_INPUT_STREAM (stream); + + g_return_val_if_fail (!self->is_closed, -1); + + self->sync_context = g_main_context_new (); + g_main_context_push_thread_default (self->sync_context); + self->sync_error = NULL; + self->sync_running = TRUE; + + gssh_channel_input_stream_read_async (stream, buffer, count, + G_PRIORITY_DEFAULT, cancellable, + on_sync_read_done, self); + + while (self->sync_running) + g_main_context_iteration (self->sync_context, TRUE); + + g_main_context_pop_thread_default (self->sync_context); + + if (self->sync_error) + { + g_propagate_error (error, self->sync_error); + return -1; + } + return self->sync_bytes_read; +} + +void +_gssh_channel_input_stream_iteration (GSshChannelInputStream *self) +{ + int rc; + GError *local_error = NULL; + GTask *prev_task = self->read_task; + gboolean is_eof = FALSE; + + if (!prev_task) + return; + + g_assert (!self->is_closed); + rc = ssh_channel_read_nonblocking (self->channel->libsshchannel, + self->buf, self->count, 0); + if (rc == 0) + { + is_eof = ssh_channel_is_eof (self->channel->libsshchannel); + if (!is_eof) + { + /* We'll get 0 but !is_eof when we hit the libssh equivalent + * of EAGAIN. We need to wait for poll(). + */ + return; + } + } + + /* This special dance is required because we may have reentered via + g_task_return() */ + self->read_task = NULL; + + if (is_eof) + { + g_debug ("channel eof"); + g_task_return_int (prev_task, 0); + } + else if (rc > 0) + { + g_debug ("channel read %" G_GSSIZE_FORMAT " bytes", (gssize)rc); + g_task_return_int (prev_task, rc); + } + else + { + _gssh_set_error_from_libssh (&local_error, "Failed to read", + self->channel->connection->session); + g_task_return_error (prev_task, local_error); + } + g_object_unref (prev_task); +} + +GSshChannelInputStream * +_gssh_channel_input_stream_new (GSshChannel *channel) +{ + GSshChannelInputStream *ret = g_object_new (GSSH_TYPE_CHANNEL_INPUT_STREAM, NULL); + ret->channel = channel; + return ret; +} + +static void +_gssh_channel_input_stream_class_init (GSshChannelInputStreamClass *class) +{ + GInputStreamClass *istream_class; + + G_OBJECT_CLASS (class)->dispose = _gssh_channel_input_stream_dispose; + + istream_class = G_INPUT_STREAM_CLASS (class); + istream_class->read_fn = gssh_channel_input_stream_read; + istream_class->read_async = gssh_channel_input_stream_read_async; + istream_class->read_finish = gssh_channel_input_stream_read_finish; + istream_class->close_fn = gssh_channel_input_stream_close; + istream_class->close_async = gssh_channel_input_stream_close_async; + istream_class->close_finish = gssh_channel_input_stream_close_finish; +} diff --git a/pool/shard006/C/0119672_get_iface.c b/pool/shard006/C/0119672_get_iface.c new file mode 100644 index 0000000000000000000000000000000000000000..529b0f751d58f866736066cfa77ffc991a73f429 --- /dev/null +++ b/pool/shard006/C/0119672_get_iface.c @@ -0,0 +1,118 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +ERRTAG("get_iface"); + +char txbuf[128]; +char rxbuf[8*1024-256]; + +struct nrbuf nr; +struct ncbuf nc; + +static int open_socket(void) +{ + int domain = PF_NETLINK; + int type = SOCK_RAW; + int protocol = NETLINK_GENERIC; + struct sockaddr_nl nls = { + .family = AF_NETLINK, + .pid = sys_getpid(), + .groups = 0 + }; + int fd, ret; + + if((fd = sys_socket(domain, type, protocol)) < 0) + fail("socket", "NETLINK", fd); + if((ret = sys_bind(fd, (struct sockaddr*)&nls, sizeof(nls))) < 0) + fail("bind", "NETLINK", ret); + + return fd; +} + +static struct nlgen* send_recv(int fd) +{ + int ret; + struct nlmsg* msg; + struct nlerr* err; + struct nlgen* gen; + + if((ret = nc_send(fd, &nc)) < 0) + fail("send", NULL, ret); + if((ret = nr_recv(fd, &nr)) < 0) + fail("recv", NULL, ret); + + if(!(msg = nr_next(&nr))) + fail("recv", NULL, -EAGAIN); + + if((err = nl_err(msg))) { + if((ret = err->errno) < 0) + fail(NULL, NULL, ret); + else + fail(NULL, NULL, -EBADMSG); + } else if(!(gen = nl_gen(msg))) { + fail(NULL, NULL, -EBADMSG); + } + + return gen; +} + +static int query_group(int fd, char* name) +{ + nc_header(&nc, GENL_ID_CTRL, 0, 0); + nc_gencmd(&nc, CTRL_CMD_GETFAMILY, 1); + nc_put_str(&nc, CTRL_ATTR_FAMILY_NAME, name); + + struct nlgen* msg = send_recv(fd); + + uint16_t* grpid = nl_get_u16(msg, CTRL_ATTR_FAMILY_ID); + + if(!grpid) + fail(NULL, NULL, -ENOENT); + + return *grpid; +} + +int main(int argc, char** argv) +{ + int ifi; + char* p; + + if(argc != 2) + fail("bad call", NULL, 0); + + if(!(p = parseint(argv[1], &ifi)) || *p) + fail("bad ifindex:", argv[1], 0); + + nc_buf_set(&nc, txbuf, sizeof(txbuf)); + nr_buf_set(&nr, rxbuf, sizeof(rxbuf)); + + int fd = open_socket(); + int nl80211 = query_group(fd, "nl80211"); + + nc_header(&nc, nl80211, 0, 0); + nc_gencmd(&nc, NL80211_CMD_GET_INTERFACE, 0); + nc_put_int(&nc, NL80211_ATTR_IFINDEX, ifi); + + struct nlgen* msg = send_recv(fd); + + nl_dump_gen(msg); + + return 0; +} diff --git a/pool/shard006/C/0119673_access.c b/pool/shard006/C/0119673_access.c new file mode 100644 index 0000000000000000000000000000000000000000..10d156a19f36027c72f6f716821975b825725761 --- /dev/null +++ b/pool/shard006/C/0119673_access.c @@ -0,0 +1,224 @@ +/* + * ======================================================================================= + * + * Filename: access.c + * + * Description: Interface for the different register access modules. + * + * Version: + * Released: + * + * Author: Thomas Roehl (tr), thomas.roehl@googlemail.com + * Project: likwid + * + * Copyright (C) 2015 RRZE, University Erlangen-Nuremberg + * + * 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 . + * + * ======================================================================================= + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include + + +static int globalSocket = -1; +static int cpuSockets[MAX_NUM_THREADS] = { [0 ... MAX_NUM_THREADS-1] = -1}; +static int registeredCpus = 0; + +int _HPMinit(int cpu_id) +{ + int ret = 0; + if (accessClient_mode == ACCESSMODE_DIRECT) + { + ret = msr_init(0); + if (ret == 0) + { + if (cpuid_info.supportUncore) + { + ret = pci_init(0); + } + } + } + else if (accessClient_mode == ACCESSMODE_DAEMON) + { + accessClient_init(&cpuSockets[cpu_id]); + if (globalSocket == -1) + { + globalSocket = cpuSockets[cpu_id]; + ret = msr_init(globalSocket); + if (ret == 0) + { + if (cpuid_info.supportUncore) + { + ret = pci_init(globalSocket); + } + } + } + } + if (ret == 0) + { + registeredCpus++; + } + return 0; +} + +int HPMinit(void) +{ + return _HPMinit(0); +} + +int HPMinitialized(void) +{ + return registeredCpus; +} + +int HPMaddThread(int cpu_id) +{ + if (((cpuSockets[cpu_id] == -1) && (accessClient_mode == ACCESSMODE_DAEMON)) || + (accessClient_mode == ACCESSMODE_DIRECT)) + { + return _HPMinit(cpu_id); + } + return 0; +} + +void HPMfinalize(void) +{ + msr_finalize(); + pci_finalize(); + if (accessClient_mode == ACCESSMODE_DAEMON) + { + for (int i=0;i= MAX_NUM_PCI_DEVICES) || (data == NULL)) + { + return -EFAULT; + } + if ((cpu_id < 0) || (cpu_id >= cpuid_topology.numHWThreads)) + { + return -ERANGE; + } + if (accessClient_mode == ACCESSMODE_DAEMON) + { + if ((cpuSockets[cpu_id] >= 0) && (cpuSockets[cpu_id] != socket)) + { + socket = cpuSockets[cpu_id]; + } + else if (socket < 0) + { + return -ENOENT; + } + } + *data = 0x0ULL; + DEBUG_PRINT(DEBUGLEV_DEVELOP, READ S[%d] C[%d] DEV[%d] R 0x%X, socket, cpu_id, dev, reg); + if (dev == MSR_DEV) + { + err = msr_tread(socket, cpu_id, reg, &tmp); + *data = tmp; + } + else if (pci_checkDevice(dev, cpu_id)) + { + err = pci_tread(socket, cpu_id, dev, reg, (uint32_t*)&tmp); + *data = tmp; + } + DEBUG_PRINT(DEBUGLEV_DEVELOP, READ S[%d] C[%d] DEV[%d] R 0x%X = 0x%llX ERR[%d], socket, cpu_id, dev, reg, LLU_CAST tmp, err); + return err; +} + +int HPMwrite(int cpu_id, PciDeviceIndex dev, uint32_t reg, uint64_t data) +{ + int socket = globalSocket; + int err = 0; + uint64_t tmp; + if (dev >= MAX_NUM_PCI_DEVICES) + { + ERROR_PRINT(MSR WRITE D %d NOT VALID, dev); + return -EFAULT; + } + if ((cpu_id < 0) || (cpu_id >= cpuid_topology.numHWThreads)) + { + ERROR_PRINT(MSR WRITE C %d OUT OF RANGE, cpu_id); + return -ERANGE; + } + if (accessClient_mode == ACCESSMODE_DAEMON) + { + if ((cpuSockets[cpu_id] >= 0) && (cpuSockets[cpu_id] != socket)) + { + socket = cpuSockets[cpu_id]; + } + if (socket < 0) + { + ERROR_PRINT(MSR WRITE S %d INVALID, socket); + return -ENOENT; + } + } + DEBUG_PRINT(DEBUGLEV_DEVELOP, WRITE S[%d] C[%d] DEV[%d] R 0x%X D 0x%llX, socket, cpu_id, dev, reg, LLU_CAST data); + if (dev == MSR_DEV) + { + err = msr_twrite(socket, cpu_id, reg, data); + DEBUG_PRINT(DEBUGLEV_DEVELOP, WRITE S[%d] C[%d] DEV[%d] R 0x%X D 0x%llX ERR[%d], socket, cpu_id, dev, reg, LLU_CAST data, err); + if (perfmon_verbosity == DEBUGLEV_DEVELOP) + { + int err2 = msr_tread(socket, cpu_id, reg, &tmp); + DEBUG_PRINT(DEBUGLEV_DEVELOP, VERIFY S[%d] C[%d] DEV[%d] R 0x%X D 0x%llX ERR[%d] CMP %d, socket, cpu_id, dev, reg, LLU_CAST tmp, err2, (data == tmp)); + } + } + else if (pci_checkDevice(dev, cpu_id)) + { + err = pci_twrite(socket, cpu_id, dev, reg, data); + DEBUG_PRINT(DEBUGLEV_DEVELOP, WRITE S[%d] C[%d] DEV[%d] R 0x%X D 0x%llX ERR[%d], socket, cpu_id, dev, reg, LLU_CAST data, err); + if (perfmon_verbosity == DEBUGLEV_DEVELOP) + { + int err2 = pci_tread(socket, cpu_id, dev, reg, (uint32_t*)&tmp); + DEBUG_PRINT(DEBUGLEV_DEVELOP, VERIFY S[%d] C[%d] DEV[%d] R 0x%X D 0x%llX ERR[%d] CMP %d, socket, cpu_id, dev, reg, LLU_CAST tmp, err2, (data == tmp)); + } + } + return err; +} diff --git a/pool/shard006/C/0119677_lapacke_sgetri.c b/pool/shard006/C/0119677_lapacke_sgetri.c new file mode 100644 index 0000000000000000000000000000000000000000..21cef74e20cbb52fc4d17b8011724444c27440ce --- /dev/null +++ b/pool/shard006/C/0119677_lapacke_sgetri.c @@ -0,0 +1,75 @@ +/***************************************************************************** + Copyright (c) 2014, 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: + + * 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. +***************************************************************************** +* Contents: Native high-level C interface to LAPACK function sgetri +* Author: Intel Corporation +* Generated November 2015 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_sgetri( int matrix_layout, lapack_int n, float* a, + lapack_int lda, const lapack_int* ipiv ) +{ + lapack_int info = 0; + lapack_int lwork = -1; + float* work = NULL; + float work_query; + if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_sgetri", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + /* Optionally check input matrices for NaNs */ + if( LAPACKE_sge_nancheck( matrix_layout, n, n, a, lda ) ) { + return -3; + } +#endif + /* Query optimal working array(s) size */ + info = LAPACKE_sgetri_work( matrix_layout, n, a, lda, ipiv, &work_query, + lwork ); + if( info != 0 ) { + goto exit_level_0; + } + lwork = (lapack_int)work_query; + /* Allocate memory for work arrays */ + work = (float*)LAPACKE_malloc( sizeof(float) * lwork ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + /* Call middle-level interface */ + info = LAPACKE_sgetri_work( matrix_layout, n, a, lda, ipiv, work, lwork ); + /* Release memory and exit */ + LAPACKE_free( work ); +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_sgetri", info ); + } + return info; +} diff --git a/pool/shard006/C/0119683_xattr_security.c b/pool/shard006/C/0119683_xattr_security.c new file mode 100644 index 0000000000000000000000000000000000000000..7b9e9c1842d5232ceb20f2aeebda31cacb5855fd --- /dev/null +++ b/pool/shard006/C/0119683_xattr_security.c @@ -0,0 +1,57 @@ +/* + * linux/fs/ext2/xattr_security.c + * Handler for storing security labels as extended attributes. + */ + +#include "ext2.h" +#include +#include "xattr.h" + +static int +ext2_xattr_security_get(const struct xattr_handler *handler, + struct dentry *unused, struct inode *inode, + const char *name, void *buffer, size_t size) +{ + return ext2_xattr_get(inode, EXT2_XATTR_INDEX_SECURITY, name, + buffer, size); +} + +static int +ext2_xattr_security_set(const struct xattr_handler *handler, + struct dentry *unused, struct inode *inode, + const char *name, const void *value, + size_t size, int flags) +{ + return ext2_xattr_set(inode, EXT2_XATTR_INDEX_SECURITY, name, + value, size, flags); +} + +static int ext2_initxattrs(struct inode *inode, const struct xattr *xattr_array, + void *fs_info) +{ + const struct xattr *xattr; + int err = 0; + + for (xattr = xattr_array; xattr->name != NULL; xattr++) { + err = ext2_xattr_set(inode, EXT2_XATTR_INDEX_SECURITY, + xattr->name, xattr->value, + xattr->value_len, 0); + if (err < 0) + break; + } + return err; +} + +int +ext2_init_security(struct inode *inode, struct inode *dir, + const struct qstr *qstr) +{ + return security_inode_init_security(inode, dir, qstr, + &ext2_initxattrs, NULL); +} + +const struct xattr_handler ext2_xattr_security_handler = { + .prefix = XATTR_SECURITY_PREFIX, + .get = ext2_xattr_security_get, + .set = ext2_xattr_security_set, +}; diff --git a/pool/shard006/C/0119684_main.c b/pool/shard006/C/0119684_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6d49611b8b66c35c1ffb7b38cb0c21944cecfeab --- /dev/null +++ b/pool/shard006/C/0119684_main.c @@ -0,0 +1,44 @@ +#include +#include "setup.h" + +int irqcount = 0; +uint8_t buffer[100]; + +void my_callback_rx_notify(uint8_t port) +{ + LED_Toggle(LED0); + irqcount++; + int length = udi_cdc_get_nb_received_data(); + printf("IRQ:%d:length=%d ",irqcount, length); + /*while (udi_cdc_is_rx_ready()) + printf(" 0x%X", udi_cdc_getc()); + printf("\n\r");*/ + + udi_cdc_read_buf(buffer,length); + for (int i=0;i +#include + +#define STACK_SIZE 512 +#define NUM_THREAD 4 +static K_THREAD_STACK_ARRAY_DEFINE(tstack, NUM_THREAD, STACK_SIZE); +static struct k_thread tdata[NUM_THREAD]; +/*for those not supporting tickless idle*/ +#ifndef CONFIG_TICKLESS_IDLE +#define CONFIG_TICKLESS_IDLE_THRESH 20 +#endif +/*sleep duration tickless*/ +#define SLEEP_TICKLESS __ticks_to_ms(CONFIG_TICKLESS_IDLE_THRESH) + +/*sleep duration with tick*/ +#define SLEEP_TICKFUL __ticks_to_ms(CONFIG_TICKLESS_IDLE_THRESH - 1) + +/*slice size is set as half of the sleep duration*/ +#define SLICE_SIZE __ticks_to_ms(CONFIG_TICKLESS_IDLE_THRESH >> 1) + +/*maximum slice duration accepted by the test*/ +#define SLICE_SIZE_LIMIT __ticks_to_ms((CONFIG_TICKLESS_IDLE_THRESH >> 1) + 1) + +/*align to millisecond boundary*/ +#if defined(CONFIG_ARCH_POSIX) +#define ALIGN_MS_BOUNDARY() \ + do { \ + u32_t t = k_uptime_get_32(); \ + while (t == k_uptime_get_32()) \ + posix_halt_cpu(); \ + } while (0) +#else +#define ALIGN_MS_BOUNDARY() \ + do { \ + u32_t t = k_uptime_get_32(); \ + while (t == k_uptime_get_32()) \ + ; \ + } while (0) +#endif +K_SEM_DEFINE(sema, 0, NUM_THREAD); +static s64_t elapsed_slice; + +static void thread_tslice(void *p1, void *p2, void *p3) +{ + s64_t t = k_uptime_delta(&elapsed_slice); + + TC_PRINT("elapsed slice %lld, expected: <%lld, %lld>\n", + t, SLICE_SIZE, SLICE_SIZE_LIMIT); + + /**TESTPOINT: verify slicing scheduler behaves as expected*/ + zassert_true(t >= SLICE_SIZE, NULL); + /*less than one tick delay*/ + zassert_true(t <= SLICE_SIZE_LIMIT, NULL); + + u32_t t32 = k_uptime_get_32(); + + /*keep the current thread busy for more than one slice*/ + while (k_uptime_get_32() - t32 < SLEEP_TICKLESS) +#if defined(CONFIG_ARCH_POSIX) + posix_halt_cpu(); +#else + ; +#endif + k_sem_give(&sema); +} +/** + * @addtogroup kernel_tickless_tests + * @{ + */ + +/** + * @brief Verify system clock with and without tickless idle + * + * @details Check if system clock recovers and works as expected + * when tickless idle is enabled and disabled. + */ +void test_tickless_sysclock(void) +{ + volatile u32_t t0, t1; + + ALIGN_MS_BOUNDARY(); + t0 = k_uptime_get_32(); + k_sleep(SLEEP_TICKLESS); + t1 = k_uptime_get_32(); + TC_PRINT("time %d, %d\n", t0, t1); + /**TESTPOINT: verify system clock recovery after exiting tickless idle*/ + zassert_true((t1 - t0) >= SLEEP_TICKLESS, NULL); + + ALIGN_MS_BOUNDARY(); + t0 = k_uptime_get_32(); + k_sem_take(&sema, SLEEP_TICKFUL); + t1 = k_uptime_get_32(); + TC_PRINT("time %d, %d\n", t0, t1); + /**TESTPOINT: verify system clock recovery after exiting tickful idle*/ + zassert_true((t1 - t0) >= SLEEP_TICKFUL, NULL); +} + +/** + * @brief Verify tickless functionality with time slice + * + * @details Create threads of equal priority and enable time + * slice. Check if the threads execute more than a tick. + */ +void test_tickless_slice(void) +{ + k_tid_t tid[NUM_THREAD]; + + k_sem_reset(&sema); + /*enable time slice*/ + k_sched_time_slice_set(SLICE_SIZE, K_PRIO_PREEMPT(0)); + + /*create delayed threads with equal preemptive priority*/ + for (int i = 0; i < NUM_THREAD; i++) { + tid[i] = k_thread_create(&tdata[i], tstack[i], STACK_SIZE, + thread_tslice, NULL, NULL, NULL, + K_PRIO_PREEMPT(0), 0, SLICE_SIZE); + } + k_uptime_delta(&elapsed_slice); + /*relinquish CPU and wait for each thread to complete*/ + for (int i = 0; i < NUM_THREAD; i++) { + k_sem_take(&sema, K_FOREVER); + } + + /*test case teardown*/ + for (int i = 0; i < NUM_THREAD; i++) { + k_thread_abort(tid[i]); + } + /*disable time slice*/ + k_sched_time_slice_set(0, K_PRIO_PREEMPT(0)); +} + +/** + * @} + */ +void test_main(void) +{ + ztest_test_suite(tickless_concept, + ztest_unit_test(test_tickless_sysclock), + ztest_unit_test(test_tickless_slice)); + ztest_run_test_suite(tickless_concept); +} diff --git a/pool/shard006/C/0119690_mr.c b/pool/shard006/C/0119690_mr.c new file mode 100644 index 0000000000000000000000000000000000000000..42cc3c7ac5b6802fb6b4ccf15f4717e14d4d74f5 --- /dev/null +++ b/pool/shard006/C/0119690_mr.c @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved. + * + * This software is available to you under a choice of one of two + * licenses. You may choose to be licensed under the terms of the GNU + * General Public License (GPL) Version 2, available from the file + * COPYING in the main directory of this source tree, or the + * OpenIB.org BSD license below: + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * - Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * + * - Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THE 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 +#include +#include +#include +#include "mlx5_core.h" + +int mlx5_core_create_mkey_cb(struct mlx5_core_dev *dev, + struct mlx5_core_mkey *mkey, + struct mlx5_async_ctx *async_ctx, u32 *in, + int inlen, u32 *out, int outlen, + mlx5_async_cbk_t callback, + struct mlx5_async_work *context) +{ + u32 lout[MLX5_ST_SZ_DW(create_mkey_out)] = {0}; + u32 mkey_index; + void *mkc; + int err; + u8 key; + + spin_lock_irq(&dev->priv.mkey_lock); + key = dev->priv.mkey_key++; + spin_unlock_irq(&dev->priv.mkey_lock); + mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry); + + MLX5_SET(create_mkey_in, in, opcode, MLX5_CMD_OP_CREATE_MKEY); + MLX5_SET(mkc, mkc, mkey_7_0, key); + + if (callback) + return mlx5_cmd_exec_cb(async_ctx, in, inlen, out, outlen, + callback, context); + + err = mlx5_cmd_exec(dev, in, inlen, lout, sizeof(lout)); + if (err) + return err; + + mkey_index = MLX5_GET(create_mkey_out, lout, mkey_index); + mkey->iova = MLX5_GET64(mkc, mkc, start_addr); + mkey->size = MLX5_GET64(mkc, mkc, len); + mkey->key = mlx5_idx_to_mkey(mkey_index) | key; + mkey->pd = MLX5_GET(mkc, mkc, pd); + + mlx5_core_dbg(dev, "out 0x%x, key 0x%x, mkey 0x%x\n", + mkey_index, key, mkey->key); + return 0; +} +EXPORT_SYMBOL(mlx5_core_create_mkey_cb); + +int mlx5_core_create_mkey(struct mlx5_core_dev *dev, + struct mlx5_core_mkey *mkey, + u32 *in, int inlen) +{ + return mlx5_core_create_mkey_cb(dev, mkey, NULL, in, inlen, + NULL, 0, NULL, NULL); +} +EXPORT_SYMBOL(mlx5_core_create_mkey); + +int mlx5_core_destroy_mkey(struct mlx5_core_dev *dev, + struct mlx5_core_mkey *mkey) +{ + u32 out[MLX5_ST_SZ_DW(destroy_mkey_out)] = {0}; + u32 in[MLX5_ST_SZ_DW(destroy_mkey_in)] = {0}; + + MLX5_SET(destroy_mkey_in, in, opcode, MLX5_CMD_OP_DESTROY_MKEY); + MLX5_SET(destroy_mkey_in, in, mkey_index, mlx5_mkey_to_idx(mkey->key)); + return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out)); +} +EXPORT_SYMBOL(mlx5_core_destroy_mkey); + +int mlx5_core_query_mkey(struct mlx5_core_dev *dev, struct mlx5_core_mkey *mkey, + u32 *out, int outlen) +{ + u32 in[MLX5_ST_SZ_DW(query_mkey_in)] = {0}; + + memset(out, 0, outlen); + MLX5_SET(query_mkey_in, in, opcode, MLX5_CMD_OP_QUERY_MKEY); + MLX5_SET(query_mkey_in, in, mkey_index, mlx5_mkey_to_idx(mkey->key)); + return mlx5_cmd_exec(dev, in, sizeof(in), out, outlen); +} +EXPORT_SYMBOL(mlx5_core_query_mkey); + +static inline u32 mlx5_get_psv(u32 *out, int psv_index) +{ + switch (psv_index) { + case 1: return MLX5_GET(create_psv_out, out, psv1_index); + case 2: return MLX5_GET(create_psv_out, out, psv2_index); + case 3: return MLX5_GET(create_psv_out, out, psv3_index); + default: return MLX5_GET(create_psv_out, out, psv0_index); + } +} + +int mlx5_core_create_psv(struct mlx5_core_dev *dev, u32 pdn, + int npsvs, u32 *sig_index) +{ + u32 out[MLX5_ST_SZ_DW(create_psv_out)] = {0}; + u32 in[MLX5_ST_SZ_DW(create_psv_in)] = {0}; + int i, err; + + if (npsvs > MLX5_MAX_PSVS) + return -EINVAL; + + MLX5_SET(create_psv_in, in, opcode, MLX5_CMD_OP_CREATE_PSV); + MLX5_SET(create_psv_in, in, pd, pdn); + MLX5_SET(create_psv_in, in, num_psv, npsvs); + + err = mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out)); + if (err) + return err; + + for (i = 0; i < npsvs; i++) + sig_index[i] = mlx5_get_psv(out, i); + + return err; +} +EXPORT_SYMBOL(mlx5_core_create_psv); + +int mlx5_core_destroy_psv(struct mlx5_core_dev *dev, int psv_num) +{ + u32 out[MLX5_ST_SZ_DW(destroy_psv_out)] = {0}; + u32 in[MLX5_ST_SZ_DW(destroy_psv_in)] = {0}; + + MLX5_SET(destroy_psv_in, in, opcode, MLX5_CMD_OP_DESTROY_PSV); + MLX5_SET(destroy_psv_in, in, psvn, psv_num); + return mlx5_cmd_exec(dev, in, sizeof(in), out, sizeof(out)); +} +EXPORT_SYMBOL(mlx5_core_destroy_psv); diff --git a/pool/shard006/C/0119691_cblas_zsyr2k.c b/pool/shard006/C/0119691_cblas_zsyr2k.c new file mode 100644 index 0000000000000000000000000000000000000000..c275cc69342e7f6c67384eb9fb2a60b176cf8c66 --- /dev/null +++ b/pool/shard006/C/0119691_cblas_zsyr2k.c @@ -0,0 +1,111 @@ +#include "blis.h" +#ifdef BLIS_ENABLE_CBLAS +/* + * + * cblas_zsyr2k.c + * This program is a C interface to zsyr2k. + * Written by Keita Teranishi + * 4/8/1998 + * + */ + +#include "cblas.h" +#include "cblas_f77.h" +void cblas_zsyr2k(enum CBLAS_ORDER Order, enum CBLAS_UPLO Uplo, + enum CBLAS_TRANSPOSE Trans, f77_int N, f77_int K, + const void *alpha, const void *A, f77_int lda, + const void *B, f77_int ldb, const void *beta, + void *C, f77_int ldc) +{ + char UL, TR; +#ifdef F77_CHAR + F77_CHAR F77_TR, F77_UL; +#else + #define F77_TR &TR + #define F77_UL &UL +#endif + +#ifdef F77_INT + F77_INT F77_N=N, F77_K=K, F77_lda=lda, F77_ldb=ldb; + F77_INT F77_ldc=ldc; +#else + #define F77_N N + #define F77_K K + #define F77_lda lda + #define F77_ldb ldb + #define F77_ldc ldc +#endif + + extern int CBLAS_CallFromC; + extern int RowMajorStrg; + RowMajorStrg = 0; + CBLAS_CallFromC = 1; + + if( Order == CblasColMajor ) + { + + if( Uplo == CblasUpper) UL='U'; + else if ( Uplo == CblasLower ) UL='L'; + else + { + cblas_xerbla(2, "cblas_zsyr2k", "Illegal Uplo setting, %d\n", Uplo); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + + if( Trans == CblasTrans) TR ='T'; + else if ( Trans == CblasConjTrans ) TR='C'; + else if ( Trans == CblasNoTrans ) TR='N'; + else + { + cblas_xerbla(3, "cblas_zsyr2k", "Illegal Trans setting, %d\n", Trans); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + + + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + F77_TR = C2F_CHAR(&TR); + #endif + + F77_zsyr2k(F77_UL, F77_TR, &F77_N, &F77_K, (dcomplex*)alpha, (dcomplex*)A, &F77_lda, + (dcomplex*)B, &F77_ldb, (dcomplex*)beta, (dcomplex*)C, &F77_ldc); + } else if (Order == CblasRowMajor) + { + RowMajorStrg = 1; + if( Uplo == CblasUpper) UL='L'; + else if ( Uplo == CblasLower ) UL='U'; + else + { + cblas_xerbla(3, "cblas_zsyr2k", "Illegal Uplo setting, %d\n", Uplo); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + if( Trans == CblasTrans) TR ='N'; + else if ( Trans == CblasConjTrans ) TR='N'; + else if ( Trans == CblasNoTrans ) TR='T'; + else + { + cblas_xerbla(3, "cblas_zsyr2k", "Illegal Trans setting, %d\n", Trans); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + F77_TR = C2F_CHAR(&TR); + #endif + + F77_zsyr2k(F77_UL, F77_TR, &F77_N, &F77_K, (dcomplex*)alpha, (dcomplex*)A, &F77_lda, (dcomplex*)B, &F77_ldb, (dcomplex*)beta, (dcomplex*)C, &F77_ldc); + } + else cblas_xerbla(1, "cblas_zsyr2k", "Illegal Order setting, %d\n", Order); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; +} +#endif diff --git a/pool/shard006/C/0119700_mix_listener.c b/pool/shard006/C/0119700_mix_listener.c new file mode 100644 index 0000000000000000000000000000000000000000..59cd02b4e9af6688a8d1523d359419655b3b4ce2 --- /dev/null +++ b/pool/shard006/C/0119700_mix_listener.c @@ -0,0 +1,99 @@ +/* + Copyright (c) 2013-2014 Dong Fang. 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 +#include +#include +#include +#include +#include +#include "../global.h" + +static int mix_listener_bind (struct sockbase *sb, const char *sock) +{ + int i; + int child_fd; + struct sockbase *child_sb = 0; + struct sockbase *tmp = 0; + struct str_array sock_arr = {}; + + str_array_init (&sock_arr); + str_split (sock, &sock_arr, "+"); + for (i = 0; i < sock_arr.size; i++) { + if ((child_fd = xlisten (sock_arr.at[i])) < 0) + goto BAD; + if (!(child_sb = xget (child_fd))) + goto BAD; + list_add_tail (&child_sb->sib_link, &sb->sub_socks); + child_sb->owner = sb; + while (acceptq_rm_nohup (child_sb, &tmp) == 0) + acceptq_add (sb, tmp); + xput (child_fd); + } + return 0; + BAD: + walk_sub_sock (child_sb, tmp, &sb->sub_socks) { + list_del_init (&child_sb->sib_link); + xclose (child_sb->fd); + } + return -1; +} + +static void mix_listener_close (struct sockbase *sb) +{ + struct sockbase *child_sb, *tmp; + + walk_sub_sock (child_sb, tmp, &sb->sub_socks) { + child_sb->owner = 0; + list_del_init (&child_sb->sib_link); + xclose (child_sb->fd); + } + + /* Destroy acceptq's connection */ + while (acceptq_rm_nohup (sb, &tmp) == 0) { + xclose (tmp->fd); + } + + sockbase_exit (sb); + mem_free (sb, sizeof (*sb) ); +} + +static struct sockbase *mix_alloc() { + struct sockbase *sb = TNEW (struct sockbase); + + if (sb) + sockbase_init (sb); + return sb; +} + +struct sockbase_vfptr mix_listener_spec[4] = { + { + .type = XLISTENER, + .pf = TP_MIX, + .alloc = mix_alloc, + .bind = mix_listener_bind, + .close = mix_listener_close, + .setopt = 0, + .getopt = 0, + .notify = 0, + }, +}; diff --git a/pool/shard006/C/0119703_e-cell-renderer-color.c b/pool/shard006/C/0119703_e-cell-renderer-color.c new file mode 100644 index 0000000000000000000000000000000000000000..a262fa16dac719e6f5c68dbe30c458af9326b174 --- /dev/null +++ b/pool/shard006/C/0119703_e-cell-renderer-color.c @@ -0,0 +1,233 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* e-cell-renderer-color.c + * + * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com) + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU Lesser General Public + * License as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, see . + */ + +#include + +#include "e-cell-renderer-color.h" + +#include +#include + +#define E_CELL_RENDERER_COLOR_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE \ + ((obj), E_TYPE_CELL_RENDERER_COLOR, ECellRendererColorPrivate)) + +enum { + PROP_0, + PROP_COLOR +}; + +struct _ECellRendererColorPrivate { + GdkRGBA *color; +}; + +G_DEFINE_TYPE ( + ECellRendererColor, + e_cell_renderer_color, + GTK_TYPE_CELL_RENDERER) + +static void +cell_renderer_color_get_size (GtkCellRenderer *cell, + GtkWidget *widget, + const GdkRectangle *cell_area, + gint *x_offset, + gint *y_offset, + gint *width, + gint *height) +{ + gint color_width = 16; + gint color_height = 16; + gint calc_width; + gint calc_height; + gfloat xalign; + gfloat yalign; + guint xpad; + guint ypad; + + g_object_get ( + cell, "xalign", &xalign, "yalign", &yalign, + "xpad", &xpad, "ypad", &ypad, NULL); + + calc_width = (gint) xpad * 2 + color_width; + calc_height = (gint) ypad * 2 + color_height; + + if (cell_area && color_width > 0 && color_height > 0) { + if (x_offset) { + *x_offset = (((gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL) ? + (1.0 - xalign) : xalign) * + (cell_area->width - calc_width)); + *x_offset = MAX (*x_offset, 0); + } + + if (y_offset) { + *y_offset =(yalign * + (cell_area->height - calc_height)); + *y_offset = MAX (*y_offset, 0); + } + } else { + if (x_offset) *x_offset = 0; + if (y_offset) *y_offset = 0; + } + + if (width) + *width = calc_width; + + if (height) + *height = calc_height; +} + +static void +cell_renderer_color_render (GtkCellRenderer *cell, + cairo_t *cr, + GtkWidget *widget, + const GdkRectangle *background_area, + const GdkRectangle *cell_area, + GtkCellRendererState flags) +{ + ECellRendererColorPrivate *priv; + GdkRectangle pix_rect; + GdkRectangle draw_rect; + guint xpad; + guint ypad; + + priv = E_CELL_RENDERER_COLOR_GET_PRIVATE (cell); + + if (priv->color == NULL) + return; + + cell_renderer_color_get_size ( + cell, widget, cell_area, + &pix_rect.x, &pix_rect.y, + &pix_rect.width, &pix_rect.height); + + g_object_get (cell, "xpad", &xpad, "ypad", &ypad, NULL); + + pix_rect.x += cell_area->x + xpad; + pix_rect.y += cell_area->y + ypad; + pix_rect.width -= xpad * 2; + pix_rect.height -= ypad * 2; + + if (!gdk_rectangle_intersect (cell_area, &pix_rect, &draw_rect)) + return; + + gdk_cairo_set_source_rgba (cr, priv->color); + cairo_rectangle (cr, pix_rect.x, pix_rect.y, draw_rect.width, draw_rect.height); + + cairo_fill (cr); +} + +static void +cell_renderer_color_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + ECellRendererColorPrivate *priv; + + priv = E_CELL_RENDERER_COLOR_GET_PRIVATE (object); + + switch (property_id) { + case PROP_COLOR: + if (priv->color != NULL) + gdk_rgba_free (priv->color); + priv->color = g_value_dup_boxed (value); + return; + } + + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); +} + +static void +cell_renderer_color_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + ECellRendererColorPrivate *priv; + + priv = E_CELL_RENDERER_COLOR_GET_PRIVATE (object); + + switch (property_id) { + case PROP_COLOR: + g_value_set_boxed (value, priv->color); + return; + } + + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); +} + +static void +cell_renderer_color_finalize (GObject *object) +{ + ECellRendererColorPrivate *priv; + + priv = E_CELL_RENDERER_COLOR_GET_PRIVATE (object); + + if (priv->color != NULL) + gdk_rgba_free (priv->color); + + /* Chain up to parent's finalize() method. */ + G_OBJECT_CLASS (e_cell_renderer_color_parent_class)->finalize (object); +} + +static void +e_cell_renderer_color_class_init (ECellRendererColorClass *class) +{ + GObjectClass *object_class; + GtkCellRendererClass *cell_class; + + g_type_class_add_private (class, sizeof (ECellRendererColorPrivate)); + + object_class = G_OBJECT_CLASS (class); + object_class->set_property = cell_renderer_color_set_property; + object_class->get_property = cell_renderer_color_get_property; + object_class->finalize = cell_renderer_color_finalize; + + cell_class = GTK_CELL_RENDERER_CLASS (class); + cell_class->get_size = cell_renderer_color_get_size; + cell_class->render = cell_renderer_color_render; + + g_object_class_install_property ( + object_class, + PROP_COLOR, + g_param_spec_boxed ( + "color", + "Color Info", + "The color to render", + GDK_TYPE_COLOR, + G_PARAM_READWRITE)); +} + +static void +e_cell_renderer_color_init (ECellRendererColor *cellcolor) +{ + cellcolor->priv = E_CELL_RENDERER_COLOR_GET_PRIVATE (cellcolor); + + g_object_set (cellcolor, "xpad", 4, NULL); +} + +/** + * e_cell_renderer_color_new: + * + * Since: 2.22 + **/ +GtkCellRenderer * +e_cell_renderer_color_new (void) +{ + return g_object_new (E_TYPE_CELL_RENDERER_COLOR, NULL); +} diff --git a/pool/shard006/C/0119704_jerror.c b/pool/shard006/C/0119704_jerror.c new file mode 100644 index 0000000000000000000000000000000000000000..d3d1dd97b3b489c2468b30bc0bd2f2d69c3c7711 --- /dev/null +++ b/pool/shard006/C/0119704_jerror.c @@ -0,0 +1,240 @@ +/* + * jerror.c + * + * Copyright (C) 1991-1998, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains simple error-reporting and trace-message routines. + * These are suitable for Unix-like systems and others where writing to + * stderr is the right thing to do. Many applications will want to replace + * some or all of these routines. + * + * If you define USE_WINDOWS_MESSAGEBOX in jconfig.h or in the makefile, + * you get a Windows-specific hack to display error messages in a dialog box. + * It ain't much, but it beats dropping error messages into the bit bucket, + * which is what happens to output to stderr under most Windows C compilers. + * + * These routines are used by both the compression and decompression code. + */ + +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ +#include "jinclude.h" +#include "jpeglib.h" +#include "jversion.h" +#include "jerror.h" + +#ifdef USE_WINDOWS_MESSAGEBOX +#include +#endif + +#ifndef EXIT_FAILURE /* define exit() codes if not provided */ +#define EXIT_FAILURE 1 +#endif + + +/* + * Create the message string table. + * We do this from the master message list in jerror.h by re-reading + * jerror.h with a suitable definition for macro JMESSAGE. + * The message table is made an external symbol just in case any applications + * want to refer to it directly. + */ + + +#define JMESSAGE(code,string) string , + +const char * const jpeg_std_message_table[] = { +#include "jerror.h" + NULL +}; + + +/* + * Error exit handler: must not return to caller. + * + * Applications may override this if they want to get control back after + * an error. Typically one would longjmp somewhere instead of exiting. + * The setjmp buffer can be made a private field within an expanded error + * handler object. Note that the info needed to generate an error message + * is stored in the error object, so you can generate the message now or + * later, at your convenience. + * You should make sure that the JPEG object is cleaned up (with jpeg_abort + * or jpeg_destroy) at some point. + */ + +METHODDEF(void) +error_exit (j_common_ptr cinfo) +{ + /* Always display the message */ + (*cinfo->err->output_message) (cinfo); + + /* Let the memory manager delete any temp files before we die */ + jpeg_destroy(cinfo); + + exit(EXIT_FAILURE); +} + + +/* + * Actual output of an error or trace message. + * Applications may override this method to send JPEG messages somewhere + * other than stderr. + * + * On Windows, printing to stderr is generally completely useless, + * so we provide optional code to produce an error-dialog popup. + * Most Windows applications will still prefer to override this routine, + * but if they don't, it'll do something at least marginally useful. + * + * NOTE: to use the library in an environment that doesn't support the + * C stdio library, you may have to delete the call to fprintf() entirely, + * not just not use this routine. + */ + +METHODDEF(void) +output_message (j_common_ptr cinfo) +{ + char buffer[JMSG_LENGTH_MAX]; + + /* Create the message */ + (*cinfo->err->format_message) (cinfo, buffer); + +#ifdef USE_WINDOWS_MESSAGEBOX + /* Display it in a message dialog box */ + MessageBox(GetActiveWindow(), buffer, "JPEG Library Error", + MB_OK | MB_ICONERROR); +#else + /* Send it to stderr, adding a newline */ + /* RS fprintf(stderr, "%s\n", buffer); */ +#endif +} + + +/* + * Decide whether to emit a trace or warning message. + * msg_level is one of: + * -1: recoverable corrupt-data warning, may want to abort. + * 0: important advisory messages (always display to user). + * 1: first level of tracing detail. + * 2,3,...: successively more detailed tracing messages. + * An application might override this method if it wanted to abort on warnings + * or change the policy about which messages to display. + */ + +METHODDEF(void) emit_message (j_common_ptr cinfo, int msg_level) { + struct jpeg_error_mgr * err = cinfo->err; + if (msg_level < 0) { + /* It's a warning message. Since corrupt files may generate many warnings, + * the policy implemented here is to show only the first warning, + * unless trace_level >= 3. + */ + if (err->num_warnings == 0 || err->trace_level >= 3) + (*err->output_message) (cinfo); + /* Always count warnings in num_warnings. */ + err->num_warnings++; + } else { + /* It's a trace message. Show it if trace_level >= msg_level. */ + if (err->trace_level >= msg_level) + (*err->output_message) (cinfo); + } +} + + +/* + * Format a message string for the most recent JPEG error or message. + * The message is stored into buffer, which should be at least JMSG_LENGTH_MAX + * characters. Note that no '\n' character is added to the string. + * Few applications should need to override this method. + */ + +METHODDEF(void) format_message (j_common_ptr cinfo, char * buffer) { + struct jpeg_error_mgr * err = cinfo->err; + int msg_code = err->msg_code; + const char * msgtext = NULL; + const char * msgptr; + char ch; + boolean isstring; + + /* Look up message string in proper table */ + if (msg_code > 0 && msg_code <= err->last_jpeg_message) { + msgtext = err->jpeg_message_table[msg_code]; + } else if (err->addon_message_table != NULL && + msg_code >= err->first_addon_message && + msg_code <= err->last_addon_message) { + msgtext = err->addon_message_table[msg_code - err->first_addon_message]; + } + + /* Defend against bogus message number */ + if (msgtext == NULL) { + err->msg_parm.i[0] = msg_code; + msgtext = err->jpeg_message_table[0]; + } + + /* Check for string parameter, as indicated by %s in the message text */ + isstring = FALSE; + msgptr = msgtext; + while ((ch = *msgptr++) != '\0') { + if (ch == '%') { + if (*msgptr == 's') isstring = TRUE; + break; + } + } + + /* Format the message into the passed buffer */ + if (isstring) + sprintf(buffer, msgtext, err->msg_parm.s); + else + sprintf(buffer, msgtext, + err->msg_parm.i[0], err->msg_parm.i[1], + err->msg_parm.i[2], err->msg_parm.i[3], + err->msg_parm.i[4], err->msg_parm.i[5], + err->msg_parm.i[6], err->msg_parm.i[7]); +} + + +/* + * Reset error state variables at start of a new image. + * This is called during compression startup to reset trace/error + * processing to default state, without losing any application-specific + * method pointers. An application might possibly want to override + * this method if it has additional error processing state. + */ + +METHODDEF(void) reset_error_mgr (j_common_ptr cinfo) { + cinfo->err->num_warnings = 0; + /* trace_level is not reset since it is an application-supplied parameter */ + cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */ +} + + +/* + * Fill in the standard error-handling methods in a jpeg_error_mgr object. + * Typical call is: + * struct jpeg_compress_struct cinfo; + * struct jpeg_error_mgr err; + * + * cinfo.err = jpeg_std_error(&err); + * after which the application may override some of the methods. + */ + +GLOBAL(struct jpeg_error_mgr *) jpeg_std_error (struct jpeg_error_mgr * err) { + err->error_exit = error_exit; + err->emit_message = emit_message; + err->output_message = output_message; + err->format_message = format_message; + err->reset_error_mgr = reset_error_mgr; + + err->trace_level = 0; /* default = no tracing */ + err->num_warnings = 0; /* no warnings emitted yet */ + err->msg_code = 0; /* may be useful as a flag for "no error" */ + + /* Initialize message table pointers */ + err->jpeg_message_table = jpeg_std_message_table; + err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1; + + err->addon_message_table = NULL; + err->first_addon_message = 0; /* for safety */ + err->last_addon_message = 0; + + return err; +} diff --git a/pool/shard006/C/0119705_config.c b/pool/shard006/C/0119705_config.c new file mode 100644 index 0000000000000000000000000000000000000000..76cf39f4da94279a5316cc0f063ad1823b9fb354 --- /dev/null +++ b/pool/shard006/C/0119705_config.c @@ -0,0 +1,119 @@ +/***************************************************************************/ + +/* + * linux/arch/m68knommu/platform/5407/config.c + * + * Copyright (C) 1999-2002, Greg Ungerer (gerg@snapgear.com) + * Copyright (C) 2000, Lineo (www.lineo.com) + */ + +/***************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/***************************************************************************/ + +void coldfire_tick(void); +void coldfire_timer_init(void (*handler)(int, void *, struct pt_regs *)); +unsigned long coldfire_timer_offset(void); +void coldfire_trap_init(void); +void coldfire_reset(void); + +extern unsigned int mcf_timervector; +extern unsigned int mcf_profilevector; +extern unsigned int mcf_timerlevel; + +/***************************************************************************/ + +/* + * DMA channel base address table. + */ +unsigned int dma_base_addr[MAX_M68K_DMA_CHANNELS] = { + MCF_MBAR + MCFDMA_BASE0, + MCF_MBAR + MCFDMA_BASE1, + MCF_MBAR + MCFDMA_BASE2, + MCF_MBAR + MCFDMA_BASE3, +}; + +/***************************************************************************/ + +void mcf_autovector(unsigned int vec) +{ + volatile unsigned char *mbar; + + if ((vec >= 25) && (vec <= 31)) { + mbar = (volatile unsigned char *) MCF_MBAR; + vec = 0x1 << (vec - 24); + *(mbar + MCFSIM_AVR) |= vec; + mcf_setimr(mcf_getimr() & ~vec); + } +} + +/***************************************************************************/ + +void mcf_settimericr(unsigned int timer, unsigned int level) +{ + volatile unsigned char *icrp; + unsigned int icr, imr; + + if (timer <= 2) { + switch (timer) { + case 2: icr = MCFSIM_TIMER2ICR; imr = MCFSIM_IMR_TIMER2; break; + default: icr = MCFSIM_TIMER1ICR; imr = MCFSIM_IMR_TIMER1; break; + } + + icrp = (volatile unsigned char *) (MCF_MBAR + icr); + *icrp = MCFSIM_ICR_AUTOVEC | (level << 2) | MCFSIM_ICR_PRI3; + mcf_setimr(mcf_getimr() & ~imr); + } +} + +/***************************************************************************/ + +int mcf_timerirqpending(int timer) +{ + unsigned int imr = 0; + + switch (timer) { + case 1: imr = MCFSIM_IMR_TIMER1; break; + case 2: imr = MCFSIM_IMR_TIMER2; break; + default: break; + } + return (mcf_getipr() & imr); +} + +/***************************************************************************/ + +void config_BSP(char *commandp, int size) +{ + mcf_setimr(MCFSIM_IMR_MASKALL); + memset(commandp, 0, size); + +#if defined(CONFIG_CLEOPATRA) + /* Different timer setup - to prevent device clash */ + mcf_timervector = 30; + mcf_profilevector = 31; + mcf_timerlevel = 6; +#endif + + mach_sched_init = coldfire_timer_init; + mach_tick = coldfire_tick; + mach_gettimeoffset = coldfire_timer_offset; + mach_trap_init = coldfire_trap_init; + mach_reset = coldfire_reset; +} + +/***************************************************************************/ diff --git a/pool/shard006/C/0119706_board-macallan-kbc.c b/pool/shard006/C/0119706_board-macallan-kbc.c new file mode 100644 index 0000000000000000000000000000000000000000..37e387e553ace468f8cd291e1beed7580da4724d --- /dev/null +++ b/pool/shard006/C/0119706_board-macallan-kbc.c @@ -0,0 +1,94 @@ +/* + * arch/arm/mach-tegra/board-macallan-kbc.c + * Keys configuration for Nvidia t114 macallan platform. + * + * Copyright (C) 2013 NVIDIA, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + * 02111-1307, USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tegra-board-id.h" +#include "board.h" +#include "board-macallan.h" +#include "devices.h" +#include "iomap.h" +#include "wakeups-t11x.h" + +#define GPIO_KEY(_id, _gpio, _iswake) \ + { \ + .code = _id, \ + .gpio = TEGRA_GPIO_##_gpio, \ + .active_low = 1, \ + .desc = #_id, \ + .type = EV_KEY, \ + .wakeup = _iswake, \ + .debounce_interval = 10, \ + } + +static struct gpio_keys_button macallan_e1545_keys[] = { + [0] = GPIO_KEY(KEY_POWER, PQ0, 1), + [1] = GPIO_KEY(KEY_VOLUMEUP, PR2, 0), + [2] = GPIO_KEY(KEY_VOLUMEDOWN, PR1, 0), + [3] = GPIO_KEY(KEY_HOME, PI5, 0), + [4] = GPIO_KEY(KEY_BACK, PQ2, 0), /* Todo : CAMF */ + [5] = GPIO_KEY(KEY_MENU, PR0, 0), /* Todo : CAMS */ +}; + +static int macallan_wakeup_key(void) +{ + int wakeup_key; + u64 status = readl(IO_ADDRESS(TEGRA_PMC_BASE) + PMC_WAKE_STATUS) + | (u64)readl(IO_ADDRESS(TEGRA_PMC_BASE) + + PMC_WAKE2_STATUS) << 32; + if (status & ((u64)1 << TEGRA_WAKE_GPIO_PQ0)) + wakeup_key = KEY_POWER; + else if (status & ((u64)1 << TEGRA_WAKE_GPIO_PS0)) + wakeup_key = SW_LID; + else + wakeup_key = KEY_RESERVED; + + return wakeup_key; +} + +static struct gpio_keys_platform_data macallan_e1545_keys_pdata = { + .buttons = macallan_e1545_keys, + .nbuttons = ARRAY_SIZE(macallan_e1545_keys), + .wakeup_key = macallan_wakeup_key, +}; + +static struct platform_device macallan_e1545_keys_device = { + .name = "gpio-keys", + .id = 0, + .dev = { + .platform_data = &macallan_e1545_keys_pdata, + }, +}; + +int __init macallan_kbc_init(void) +{ + platform_device_register(&macallan_e1545_keys_device); + + return 0; +} + diff --git a/pool/shard006/C/0119709_sspgst.c b/pool/shard006/C/0119709_sspgst.c new file mode 100644 index 0000000000000000000000000000000000000000..a86622ab234c560ccff19fff97730d9bf715eadd --- /dev/null +++ b/pool/shard006/C/0119709_sspgst.c @@ -0,0 +1,281 @@ +/* sspgst.f -- translated by f2c (version 20061008). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" +#include "blaswrap.h" + +/* Table of constant values */ + +static integer c__1 = 1; +static real c_b9 = -1.f; +static real c_b11 = 1.f; + +/* Subroutine */ int sspgst_(integer *itype, char *uplo, integer *n, real *ap, + real *bp, integer *info) +{ + /* System generated locals */ + integer i__1, i__2; + real r__1; + + /* Local variables */ + integer j, k, j1, k1, jj, kk; + real ct, ajj; + integer j1j1; + real akk; + integer k1k1; + real bjj, bkk; + extern doublereal sdot_(integer *, real *, integer *, real *, integer *); + extern /* Subroutine */ int sspr2_(char *, integer *, real *, real *, + integer *, real *, integer *, real *); + extern logical lsame_(char *, char *); + extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *); + logical upper; + extern /* Subroutine */ int saxpy_(integer *, real *, real *, integer *, + real *, integer *), sspmv_(char *, integer *, real *, real *, + real *, integer *, real *, real *, integer *), stpmv_( + char *, char *, char *, integer *, real *, real *, integer *), stpsv_(char *, char *, char *, integer *, + real *, real *, integer *), xerbla_(char + *, integer *); + + +/* -- LAPACK routine (version 3.2) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* SSPGST reduces a real symmetric-definite generalized eigenproblem */ +/* to standard form, using packed storage. */ + +/* If ITYPE = 1, the problem is A*x = lambda*B*x, */ +/* and A is overwritten by inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T) */ + +/* If ITYPE = 2 or 3, the problem is A*B*x = lambda*x or */ +/* B*A*x = lambda*x, and A is overwritten by U*A*U**T or L**T*A*L. */ + +/* B must have been previously factorized as U**T*U or L*L**T by SPPTRF. */ + +/* Arguments */ +/* ========= */ + +/* ITYPE (input) INTEGER */ +/* = 1: compute inv(U**T)*A*inv(U) or inv(L)*A*inv(L**T); */ +/* = 2 or 3: compute U*A*U**T or L**T*A*L. */ + +/* UPLO (input) CHARACTER*1 */ +/* = 'U': Upper triangle of A is stored and B is factored as */ +/* U**T*U; */ +/* = 'L': Lower triangle of A is stored and B is factored as */ +/* L*L**T. */ + +/* N (input) INTEGER */ +/* The order of the matrices A and B. N >= 0. */ + +/* AP (input/output) REAL array, dimension (N*(N+1)/2) */ +/* On entry, the upper or lower triangle of the symmetric matrix */ +/* A, packed columnwise in a linear array. The j-th column of A */ +/* is stored in the array AP as follows: */ +/* if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; */ +/* if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = A(i,j) for j<=i<=n. */ + +/* On exit, if INFO = 0, the transformed matrix, stored in the */ +/* same format as A. */ + +/* BP (input) REAL array, dimension (N*(N+1)/2) */ +/* The triangular factor from the Cholesky factorization of B, */ +/* stored in the same format as A, as returned by SPPTRF. */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit */ +/* < 0: if INFO = -i, the i-th argument had an illegal value */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* Test the input parameters. */ + + /* Parameter adjustments */ + --bp; + --ap; + + /* Function Body */ + *info = 0; + upper = lsame_(uplo, "U"); + if (*itype < 1 || *itype > 3) { + *info = -1; + } else if (! upper && ! lsame_(uplo, "L")) { + *info = -2; + } else if (*n < 0) { + *info = -3; + } + if (*info != 0) { + i__1 = -(*info); + xerbla_("SSPGST", &i__1); + return 0; + } + + if (*itype == 1) { + if (upper) { + +/* Compute inv(U')*A*inv(U) */ + +/* J1 and JJ are the indices of A(1,j) and A(j,j) */ + + jj = 0; + i__1 = *n; + for (j = 1; j <= i__1; ++j) { + j1 = jj + 1; + jj += j; + +/* Compute the j-th column of the upper triangle of A */ + + bjj = bp[jj]; + stpsv_(uplo, "Transpose", "Nonunit", &j, &bp[1], &ap[j1], & + c__1); + i__2 = j - 1; + sspmv_(uplo, &i__2, &c_b9, &ap[1], &bp[j1], &c__1, &c_b11, & + ap[j1], &c__1); + i__2 = j - 1; + r__1 = 1.f / bjj; + sscal_(&i__2, &r__1, &ap[j1], &c__1); + i__2 = j - 1; + ap[jj] = (ap[jj] - sdot_(&i__2, &ap[j1], &c__1, &bp[j1], & + c__1)) / bjj; +/* L10: */ + } + } else { + +/* Compute inv(L)*A*inv(L') */ + +/* KK and K1K1 are the indices of A(k,k) and A(k+1,k+1) */ + + kk = 1; + i__1 = *n; + for (k = 1; k <= i__1; ++k) { + k1k1 = kk + *n - k + 1; + +/* Update the lower triangle of A(k:n,k:n) */ + + akk = ap[kk]; + bkk = bp[kk]; +/* Computing 2nd power */ + r__1 = bkk; + akk /= r__1 * r__1; + ap[kk] = akk; + if (k < *n) { + i__2 = *n - k; + r__1 = 1.f / bkk; + sscal_(&i__2, &r__1, &ap[kk + 1], &c__1); + ct = akk * -.5f; + i__2 = *n - k; + saxpy_(&i__2, &ct, &bp[kk + 1], &c__1, &ap[kk + 1], &c__1) + ; + i__2 = *n - k; + sspr2_(uplo, &i__2, &c_b9, &ap[kk + 1], &c__1, &bp[kk + 1] +, &c__1, &ap[k1k1]); + i__2 = *n - k; + saxpy_(&i__2, &ct, &bp[kk + 1], &c__1, &ap[kk + 1], &c__1) + ; + i__2 = *n - k; + stpsv_(uplo, "No transpose", "Non-unit", &i__2, &bp[k1k1], + &ap[kk + 1], &c__1); + } + kk = k1k1; +/* L20: */ + } + } + } else { + if (upper) { + +/* Compute U*A*U' */ + +/* K1 and KK are the indices of A(1,k) and A(k,k) */ + + kk = 0; + i__1 = *n; + for (k = 1; k <= i__1; ++k) { + k1 = kk + 1; + kk += k; + +/* Update the upper triangle of A(1:k,1:k) */ + + akk = ap[kk]; + bkk = bp[kk]; + i__2 = k - 1; + stpmv_(uplo, "No transpose", "Non-unit", &i__2, &bp[1], &ap[ + k1], &c__1); + ct = akk * .5f; + i__2 = k - 1; + saxpy_(&i__2, &ct, &bp[k1], &c__1, &ap[k1], &c__1); + i__2 = k - 1; + sspr2_(uplo, &i__2, &c_b11, &ap[k1], &c__1, &bp[k1], &c__1, & + ap[1]); + i__2 = k - 1; + saxpy_(&i__2, &ct, &bp[k1], &c__1, &ap[k1], &c__1); + i__2 = k - 1; + sscal_(&i__2, &bkk, &ap[k1], &c__1); +/* Computing 2nd power */ + r__1 = bkk; + ap[kk] = akk * (r__1 * r__1); +/* L30: */ + } + } else { + +/* Compute L'*A*L */ + +/* JJ and J1J1 are the indices of A(j,j) and A(j+1,j+1) */ + + jj = 1; + i__1 = *n; + for (j = 1; j <= i__1; ++j) { + j1j1 = jj + *n - j + 1; + +/* Compute the j-th column of the lower triangle of A */ + + ajj = ap[jj]; + bjj = bp[jj]; + i__2 = *n - j; + ap[jj] = ajj * bjj + sdot_(&i__2, &ap[jj + 1], &c__1, &bp[jj + + 1], &c__1); + i__2 = *n - j; + sscal_(&i__2, &bjj, &ap[jj + 1], &c__1); + i__2 = *n - j; + sspmv_(uplo, &i__2, &c_b11, &ap[j1j1], &bp[jj + 1], &c__1, & + c_b11, &ap[jj + 1], &c__1); + i__2 = *n - j + 1; + stpmv_(uplo, "Transpose", "Non-unit", &i__2, &bp[jj], &ap[jj], + &c__1); + jj = j1j1; +/* L40: */ + } + } + } + return 0; + +/* End of SSPGST */ + +} /* sspgst_ */ diff --git a/pool/shard006/C/0119710_stm32f1xx_hal_spi_ex.c b/pool/shard006/C/0119710_stm32f1xx_hal_spi_ex.c new file mode 100644 index 0000000000000000000000000000000000000000..e5e90e7c5a56277ac9e79ff6133ce2827de8887f --- /dev/null +++ b/pool/shard006/C/0119710_stm32f1xx_hal_spi_ex.c @@ -0,0 +1,233 @@ +/** + ****************************************************************************** + * @file stm32f1xx_hal_spi_ex.c + * @author MCD Application Team + * @version V1.1.0 + * @date 14-April-2017 + * @brief Extended SPI HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities SPI extension peripheral: + * + Extended Peripheral Control functions + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f1xx_hal.h" + +/** @addtogroup STM32F1xx_HAL_Driver + * @{ + */ + +/** @addtogroup SPI + * @{ + */ +#ifdef HAL_SPI_MODULE_ENABLED + +/** @defgroup SPI_Private_Variables SPI Private Variables + * @{ + */ +#if (USE_SPI_CRC != 0U) +/* Variable used to determine if device is impacted by implementation of workaround + related to wrong CRC errors detection on SPI2. Conditions in which this workaround has to be applied, are: + - STM32F101CDE/STM32F103CDE + - Revision ID : Z + - SPI2 + - In receive only mode, with CRC calculation enabled, at the end of the CRC reception, + the software needs to check the CRCERR flag. If it is found set, read back the SPI_RXCRC: + + If the value is 0, the complete data transfer is successful. + + Otherwise, one or more errors have been detected during the data transfer by CPU or DMA. + If CRCERR is found reset, the complete data transfer is considered successful. +*/ +uint8_t uCRCErrorWorkaroundCheck = 0U; +#endif /* USE_SPI_CRC */ +/** + * @} + */ + + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @addtogroup SPI_Exported_Functions + * @{ + */ + +/** @addtogroup SPI_Exported_Functions_Group1 + * + * @{ + */ + +/** + * @brief Initializes the SPI according to the specified parameters + * in the SPI_InitTypeDef and create the associated handle. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if(hspi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); + assert_param(IS_SPI_MODE(hspi->Init.Mode)); + assert_param(IS_SPI_DIRECTION(hspi->Init.Direction)); + assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); + assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); + assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); + assert_param(IS_SPI_NSS(hspi->Init.NSS)); + assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); + assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit)); + +#if (USE_SPI_CRC != 0U) + assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) + { + assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); + } +#else + hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; +#endif /* USE_SPI_CRC */ + + if(hspi->State == HAL_SPI_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_SPI_MspInit(hspi); + } + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Disble the selected SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/ + /* Configure : SPI Mode, Communication Mode, Data size, Clock polarity and phase, NSS management, + Communication speed, First bit and CRC calculation state */ + WRITE_REG(hspi->Instance->CR1, (hspi->Init.Mode | hspi->Init.Direction | hspi->Init.DataSize | + hspi->Init.CLKPolarity | hspi->Init.CLKPhase | (hspi->Init.NSS & SPI_CR1_SSM) | + hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation) ); + + /* Configure : NSS management */ + WRITE_REG(hspi->Instance->CR2, (((hspi->Init.NSS >> 16U) & SPI_CR2_SSOE) | hspi->Init.TIMode)); + + /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ + /* Configure : CRC Polynomial */ + WRITE_REG(hspi->Instance->CRCPR, hspi->Init.CRCPolynomial); + +#if defined(SPI_I2SCFGR_I2SMOD) + /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ + CLEAR_BIT(hspi->Instance->I2SCFGR, SPI_I2SCFGR_I2SMOD); +#endif /* SPI_I2SCFGR_I2SMOD */ + +#if (USE_SPI_CRC != 0U) +#if defined (STM32F101xE) || defined (STM32F103xE) + /* Check RevisionID value for identifying if Device is Rev Z (0x0001) in order to enable workaround for + CRC errors wrongly detected */ + /* Pb is that ES_STM32F10xxCDE also identify an issue in Debug registers access while not in Debug mode. + Revision ID information is only available in Debug mode, so Workaround could not be implemented + to distinguish Rev Z devices (issue present) from more recent version (issue fixed). + So, in case of Revison Z F101 or F103 devices, below variable should be assigned to 1 */ + uCRCErrorWorkaroundCheck = 0U; +#else + uCRCErrorWorkaroundCheck = 0U; +#endif /* STM32F101xE || STM32F103xE */ +#endif /* USE_SPI_CRC */ + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State = HAL_SPI_STATE_READY; + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** @addtogroup SPI_Private_Functions + * @{ + */ +#if (USE_SPI_CRC != 0U) +/** + * @brief Checks if encountered CRC error could be corresponding to wrongly detected errors + * according to SPI instance, Device type, and revision ID. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval CRC error validity (SPI_INVALID_CRC_ERROR or SPI_VALID_CRC_ERROR). +*/ +uint8_t SPI_ISCRCErrorValid(SPI_HandleTypeDef *hspi) +{ +#if defined(STM32F101xE) || defined(STM32F103xE) + /* Check how to handle this CRC error (workaround to be applied or not) */ + /* If CRC errors could be wrongly detected (issue 2.15.2 in STM32F10xxC/D/E silicon limitations ES (DocID14732 Rev 13) */ + if((uCRCErrorWorkaroundCheck != 0U) && (hspi->Instance == SPI2)) + { + if(hspi->Instance->RXCRCR == 0U) + { + return (SPI_INVALID_CRC_ERROR); + } + } + return (SPI_VALID_CRC_ERROR); +#else + /* Prevent unused argument(s) compilation warning */ + UNUSED(hspi); + + return (SPI_VALID_CRC_ERROR); +#endif +} +#endif /* USE_SPI_CRC */ + +/** + * @} + */ + +#endif /* HAL_SPI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0119712_send_v6.c b/pool/shard006/C/0119712_send_v6.c new file mode 100644 index 0000000000000000000000000000000000000000..8f8b2ea19fb8325e79e1ac9faf61902e8fbe79e6 --- /dev/null +++ b/pool/shard006/C/0119712_send_v6.c @@ -0,0 +1,22 @@ +#include "ping.h" + +void +send_v6() +{ +#ifdef IPV6 + int len; + struct icmp6_hdr *icmp6; + + icmp6 = (struct icmp6_hdr *) sendbuf; + icmp6->icmp6_type = ICMP6_ECHO_REQUEST; + icmp6->icmp6_code = 0; + icmp6->icmp6_id = pid; + icmp6->icmp6_seq = nsent++; + Gettimeofday((struct timeval *) (icmp6 + 1), NULL); + + len = 8 + datalen; /* 8-byte ICMPv6 header */ + + Sendto(sockfd, sendbuf, len, 0, pr->sasend, pr->salen); + /* 4kernel calculates and stores checksum for us */ +#endif /* IPV6 */ +} diff --git a/pool/shard006/C/0119714_lixad.c b/pool/shard006/C/0119714_lixad.c new file mode 100644 index 0000000000000000000000000000000000000000..98cf4363a1266fd406dda83e44a6c49af7ef13d5 --- /dev/null +++ b/pool/shard006/C/0119714_lixad.c @@ -0,0 +1,293 @@ +/* + * Copyright (c) 2009-2021, Christian Ferrari + * All rights reserved. + * + * This file is part of LIXA. + * + * LIXA 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. + * + * LIXA 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 LIXA. If not, see . + */ +#include + + + +#ifdef HAVE_GLIB_H +# include +#endif +#ifdef HAVE_ERRNO_H +# include +#endif +#ifdef HAVE_STDIO_H +# include +#endif +#ifdef HAVE_SIGNAL_H +# include +#endif +#ifdef HAVE_STDLIB_H +# include +#endif +#ifdef HAVE_SYSLOG_H +# include +#endif +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef HAVE_FCNTL_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_LIBXML_XMLVERSION_H +# include +#endif +#ifdef HAVE_LIBXML_PARSER_H +# include +#endif + + + +#include "lixa_crash.h" +#include "lixa_errors.h" +#include "lixa_trace.h" +#include "lixa_utils.h" +#include "lixa_syslog.h" +#include "server_config.h" +#include "server_listener.h" +#include "server_manager.h" +#include "server_recovery.h" +#include "server_status.h" + + + +/* set module trace flag */ +#ifdef LIXA_TRACE_MODULE +# undef LIXA_TRACE_MODULE +#endif /* LIXA_TRACE_MODULE */ +#define LIXA_TRACE_MODULE LIXA_TRACE_MOD_SERVER + +/** + * Transform the current process in a daemon, detaching terminals and + * changing parent group + * This function is copied from an example showed by Richard Stevens in + * UNIX network programming book + */ +void daemonize(void); + +/* default command line options */ +gboolean run_as_daemon = FALSE; +static gboolean maintenance = FALSE; +static char *dump_specs = NULL; +static char *config_file = NULL; +static char *trace_file = NULL; +static gboolean clean_failed = FALSE; +static gboolean print_version = FALSE; +/* command line options */ +static GOptionEntry entries[] = +{ + {"daemon", 'd', 0, G_OPTION_ARG_NONE, &run_as_daemon, "Run the process as a daemon", NULL}, + {"maintenance", 'm', 0, G_OPTION_ARG_NONE, &maintenance, "Start the server in maintenance mode only", NULL}, + {"dump", 'u', 0, G_OPTION_ARG_STRING, &dump_specs, "Dump the content of status files using order [ufs] (u=used, f=free, s=sequential)", NULL}, + {"config-file", 'c', 0, G_OPTION_ARG_STRING, &config_file, "Specify an alternate configuration file", NULL}, + {"trace-file", 't', 0, G_OPTION_ARG_STRING, &trace_file, "Specify trace file name", NULL}, + {"clean-failed", 'l', 0, G_OPTION_ARG_NONE, &clean_failed, "Clean recovery failed transactions at start-up", NULL}, + {"version", 'v', 0, G_OPTION_ARG_NONE, &print_version, "Print package info and exit", NULL}, + {NULL} +}; + + + +int main(int argc, char *argv[]) +{ + int rc = LIXA_RC_OK; + struct server_config_s sc; + struct listener_status_array_s lsa; + struct thread_status_array_s tsa; + srvr_rcvr_tbl_t srt; + server_trans_tbl_t stt; + GError *error = NULL; + GOptionContext *option_context; + struct ts_dump_spec_s tsds; + struct ts_recovery_spec_s tsrs; + int pid_fd; + + LIXA_TRACE_INIT; + LIXA_CRASH_INIT; + + openlog("lixad", LOG_PID, LOG_DAEMON); + LIXA_SYSLOG((LOG_NOTICE, LIXA_SYSLOG_LXD000N, + LIXA_PACKAGE_NAME, LIXA_PACKAGE_VERSION)); + + option_context = g_option_context_new("- LIXA server"); + g_option_context_add_main_entries(option_context, entries, NULL); + if (!g_option_context_parse(option_context, &argc, &argv, &error)) { + LIXA_SYSLOG((LOG_ERR, LIXA_SYSLOG_LXD001E, error->message)); + g_print("option parsing failed: %s\n", error->message); + exit(1); + } + g_option_context_free(option_context); + + if (NULL != trace_file) { + FILE *dummy; + dummy = freopen(trace_file, "w", stderr); +#ifdef LIXA_DEBUG + /* remove buffering: it's the default behavior before freopen, but it + changes calling it */ + setbuf(dummy, NULL); +#endif /* LIXA_DEBUG */ + } + + if (print_version) { + lixa_print_version(stdout); + exit(0); + } + if (run_as_daemon && NULL != dump_specs) { + LIXA_SYSLOG((LOG_WARNING, LIXA_SYSLOG_LXD002W)); + LIXA_TRACE(("main: dump option overrides daemon option\n")); + g_print("Warning: dump option overrides daemon option\n"); + run_as_daemon = FALSE; + } + + if (maintenance) + LIXA_SYSLOG((LOG_WARNING, LIXA_SYSLOG_LXD020N)); + + /* daemonize the server process */ + if (run_as_daemon) + daemonize(); + + /* initialize libxml2 library */ + LIBXML_TEST_VERSION; + + /* initialize configuration structure */ + server_config_init(&sc, &tpa); + if (LIXA_RC_OK != (rc = server_config(&sc, &tpa, config_file))) { + LIXA_TRACE(("main/server_config: rc=%d\n", rc)); + LIXA_SYSLOG((LOG_ERR, LIXA_SYSLOG_LXD003E, lixa_strerror(rc))); + return rc; + } + + /* write pid file */ + if (!dump_specs) { + if (-1 == (pid_fd = open(sc.pid_file, O_CREAT | O_WRONLY, + S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH))) + LIXA_SYSLOG((LOG_WARNING, LIXA_SYSLOG_LXD015W, sc.pid_file, + errno, strerror(errno))); + else { + char array[100]; + ssize_t written_bytes; + snprintf(array, sizeof(array), PID_T_FORMAT + "\n", getpid()); + written_bytes = write(pid_fd, array, strlen(array)); + close(pid_fd); + } + } + + if (LIXA_RC_OK != (rc = server_pipes_init(&tpa))) { + LIXA_TRACE(("main/server_pipes_init: rc=%d\n", rc)); + LIXA_SYSLOG((LOG_ERR, LIXA_SYSLOG_LXD017E)); + return rc; + } + + /* start configured manager(s) */ + tsds.dump = NULL != dump_specs; + if (tsds.dump) { + tsds.free = NULL != strchr(dump_specs, 'f'); + tsds.used = NULL != strchr(dump_specs, 'u'); + tsds.seq = NULL != strchr(dump_specs, 's'); + } + tsrs.clean_failed = clean_failed; + if (tsrs.clean_failed) + LIXA_SYSLOG((LOG_NOTICE, LIXA_SYSLOG_LXD022N)); + LIXA_TRACE(("lixad/main: starting\n")); + if (LIXA_RC_OK != (rc = server_manager( + &sc, &tpa, &tsa, &srt, &stt, &tsds, &tsrs, + maintenance))) { + LIXA_TRACE(("main/server_manager: rc=%d\n", rc)); + LIXA_SYSLOG((LOG_ERR, LIXA_SYSLOG_LXD004E, lixa_strerror(rc))); + return rc; + } + + /* start configured listener(s) */ + if (NULL == dump_specs && + LIXA_RC_OK != (rc = server_listener(&sc, &lsa, &tsa))) { + LIXA_TRACE(("main/server_listener: rc=%d\n", rc)); + LIXA_SYSLOG((LOG_ERR, LIXA_SYSLOG_LXD005E, lixa_strerror(rc))); + return rc; + } + + /* removing pid file */ + if (!dump_specs) { + if (0 != (unlink(sc.pid_file))) { + LIXA_TRACE(("main/unlink: errno=%d ('%s')\n", + errno, strerror(errno))); + LIXA_SYSLOG((LOG_NOTICE, LIXA_SYSLOG_LXD024N, sc.pid_file, errno, + strerror(errno))); + } + } + + /* clean-up memory to enhance memory leak detection */ + server_cleanup(&sc, &tpa, &tsa, &srt, &stt); + + /* it's time to exit */ + LIXA_SYSLOG((LOG_NOTICE, LIXA_SYSLOG_LXD006N)); + + LIXA_TRACE(("lixad/main: exiting\n")); + return 0; +} + + +/** + * Courtesy of Mr. Richard Stevens, UNIX Network Programming + */ +void daemonize(void) +{ + pid_t pid; + int i; + FILE *dummy; + + LIXA_TRACE(("lixad/daemonize: fork()\n")); + if (0 != (pid = fork())) + exit(0); + + LIXA_TRACE(("lixad/daemonize: setsid()\n")); + setsid(); + + LIXA_TRACE(("lixad/daemonize: signal()\n")); + signal(SIGHUP, SIG_IGN); + + LIXA_TRACE(("lixad/daemonize: fork()\n")); + if (0 != (pid = fork())) + exit(0); + + LIXA_TRACE(("lixad/daemonize: chdir()\n")); + i = chdir("/"); + + LIXA_TRACE(("lixad/daemonize: umask()\n")); + umask(0); + + for (i = 0; i < 64; ++i) + close(i); + + if (NULL != trace_file) + dummy = freopen(trace_file, "a", stderr); + else + dummy = freopen("/dev/null", "a", stderr); + + LIXA_SYSLOG((LOG_NOTICE, LIXA_SYSLOG_LXD014N)); + + LIXA_TRACE(("lixad/daemonize: now daemonized!\n")); + + return; +} diff --git a/pool/shard006/C/0119716_hikmeans.c b/pool/shard006/C/0119716_hikmeans.c new file mode 100644 index 0000000000000000000000000000000000000000..d212fb7a75bd29c185064c197376a986f088d2e7 --- /dev/null +++ b/pool/shard006/C/0119716_hikmeans.c @@ -0,0 +1,298 @@ +/** @file hikmeans.c + ** @author Brian Fulkerson + ** @author Andrea Vedaldi + ** @brief Hierarchical Integer K-Means Clustering - Declaration + **/ + +/* AUTORIGHTS +Copyright (C) 2007-10 Andrea Vedaldi and Brian Fulkerson + +This file is part of VLFeat, available under the terms of the +GNU GPLv2, or (at your option) any later version. +*/ + +/** @file hikmeans.h + ** @brief Hierarchical integer K-Means clustering + ** + ** Hierarchical integer K-Means clustering (HIKM) is a simple + ** hierarchical version of integer K-Means (@ref ikmeans.h + ** "IKM"). The algorithm recursively applies integer K-means to create + ** more refined partitions of the data. + ** + ** Create a tree with ::vl_hikm_new() and delete it with + ** ::vl_hikm_delete(). Use ::vl_hikm_train() to build the tree + ** from training data and ::vl_hikm_push() to project new data down + ** a HIKM tree. + ** + ** @section hikm-tree HIKM tree + ** + ** The HIKM tree is represented by a ::VlHIKMTree structure, which + ** contains a tree composed of ::VlHIKMNode. Each node is an + ** integer K-means filter which partitions the data into @c K + ** clusters. + **/ + +#include +#include +#include +#include + +#include "hikmeans.h" + +/** ------------------------------------------------------------------ + ** @internal + ** @brief Copy a subset of the data to a buffer + ** + ** @param data Data + ** @param ids Data labels + ** @param N Number of indices + ** @param M Data dimensionality + ** @param id Label of data to copy + ** @param N2 Number of data copied (out) + ** + ** @return a new buffer with a copy of the selected data. + **/ + +vl_uint8* +vl_hikm_copy_subset (vl_uint8 const * data, + vl_uint * ids, + int N, int M, + vl_uint id, int *N2) +{ + int i ; + int count = 0; + + /* count how many data points with this label there are */ + for (i = 0 ; i < N ; i++) + if (ids[i] == id) + count ++ ; + *N2 = count ; + + /* copy each datum to the buffer */ + { + vl_uint8 * new_data = vl_malloc (sizeof(vl_uint8) * M * count); + count = 0; + for (i = 0 ; i < N ; i ++) + if (ids[i] == id) + { + memcpy(new_data + count * M, + data + i * M, + sizeof(vl_uint8) * M); + count ++ ; + } + *N2 = count ; + return new_data ; + } +} + +/** ------------------------------------------------------------------ + ** @brief Compute HIKM clustering. + ** + ** @param tree HIKM tree to initialize. + ** @param data Data to cluster. + ** @param N Number of data points. + ** @param K Number of clusters for this node. + ** @param height Tree height. + ** + ** @remark height cannot be smaller than 1. + ** + ** @return a new HIKM node representing a sub-clustering. + **/ + +static VlHIKMNode * +xmeans (VlHIKMTree *tree, + vl_uint8 const *data, + int N, int K, int height) +{ + VlHIKMNode *node = vl_malloc (sizeof(VlHIKMNode)) ; + vl_uint *ids = vl_malloc (sizeof(vl_uint) * N) ; + + node-> filter = vl_ikm_new (tree -> method) ; + node-> children = (height == 1) ? 0 : vl_malloc (sizeof(VlHIKMNode*) * K) ; + + vl_ikm_set_max_niters (node->filter, tree->max_niters) ; + vl_ikm_set_verbosity (node->filter, tree->verb - 1 ) ; + vl_ikm_init_rand_data (node->filter, data, tree->M, N, K) ; + vl_ikm_train (node->filter, data, N) ; + vl_ikm_push (node->filter, ids, data, N) ; + + /* recurse for each child */ + if (height > 1) { + int k ; + for (k = 0 ; k < K ; k ++) { + int partition_N ; + int partition_K ; + vl_uint8 *partition ; + + partition = vl_hikm_copy_subset + (data, ids, N, tree->M, k, &partition_N) ; + + partition_K = VL_MIN (K, partition_N) ; + + node->children [k] = xmeans + (tree, partition, partition_N, partition_K, height - 1) ; + + vl_free (partition) ; + + if (tree->verb > tree->depth - height) { + VL_PRINTF("hikmeans: branch at depth %d: %6.1f %% completed\n", + tree->depth - height, + (double) (k+1) / K * 100) ; + } + } + } + + vl_free (ids) ; + return node ; +} + +/** ------------------------------------------------------------------ + ** @internal + ** @brief Delete node + ** + ** @param node to delete. + ** + ** The function deletes recursively @a node and all its descendent. + **/ + +static void +xdelete (VlHIKMNode *node) +{ + if(node) { + int k ; + if (node->children) { + for(k = 0 ; k < vl_ikm_get_K (node->filter) ; ++k) + xdelete (node->children[k]) ; + vl_free (node->children) ; + } + if (node->filter) + vl_ikm_delete (node->filter) ; + vl_free(node); + } +} + +/** ------------------------------------------------------------------ + ** @brief New HIKM tree + ** @param method clustering method. + ** @return new HIKM tree. + **/ + +VL_EXPORT +VlHIKMTree * +vl_hikm_new (int method) +{ + VlHIKMTree *f = vl_malloc (sizeof(VlHIKMTree)) ; + f -> M = 0 ; + f -> K = 0 ; + f -> max_niters = 200 ; + f -> method = method ; + f -> verb = 0 ; + f -> depth = 0 ; + f -> root = 0 ; + return f ; +} + +/** ------------------------------------------------------------------ + ** @brief Delete HIKM tree + ** @param f HIKM tree. + **/ + +VL_EXPORT +void +vl_hikm_delete (VlHIKMTree *f) +{ + if (f) { + xdelete (f -> root) ; + vl_free (f) ; + } +} + +/** ------------------------------------------------------------------ + ** @brief Initialize HIKM tree + ** + ** @param f HIKM tree. + ** @param M Data dimensionality. + ** @param K Number of clusters per node. + ** @param depth Tree depth. + ** + ** @remark @a depth cannot be smaller than 1. + ** + ** @return a new HIKM tree representing the clustering. + **/ + +VL_EXPORT +void +vl_hikm_init (VlHIKMTree *f, int M, int K, int depth) +{ + assert(depth > 0) ; + assert(M > 0) ; + assert(K > 0) ; + + xdelete (f -> root) ; + f -> root = 0; + + f -> M = M ; + f -> K = K ; + f -> depth = depth ; +} + +/** ------------------------------------------------------------------ + ** @brief Train HIKM tree + ** @param f HIKM tree. + ** @param data Data to cluster. + ** @param N Number of data. + **/ + +VL_EXPORT +void +vl_hikm_train (VlHIKMTree *f, vl_uint8 const *data, int N) +{ + f -> root = xmeans (f, data, N, VL_MIN(f->K, N), f->depth) ; +} + +/** ------------------------------------------------------------------ + ** @brief Project data down HIKM tree + ** + ** @param f HIKM tree. + ** @param asgn Path down the tree (out). + ** @param data Data to project. + ** @param N Number of data. + ** + ** The function writes to @a asgn the path of the data @a data + ** down the HIKM tree @a f. The parameter @a asgn must point to + ** an array of @c M by @c N elements, where @c M is the depth of + ** the HIKM tree and @c N is the number of data point to process. + **/ + +VL_EXPORT +void +vl_hikm_push (VlHIKMTree *f, vl_uint *asgn, vl_uint8 const *data, int N) +{ + int i, d, + M = vl_hikm_get_ndims (f), + depth = vl_hikm_get_depth (f) ; + + /* for each datum */ + for(i = 0 ; i < N ; i++) { + VlHIKMNode *node = f->root ; + d = 0 ; + while (node) { + /* + vl_uint best = + vl_ikm_push_one (vl_ikm_get_centers (node->filter), + data + i * M, + M, + vl_ikm_get_K (node->filter)) ; + */ + + vl_uint best ; + vl_ikm_push (node->filter, &best, data + i * M, 1) ; + + asgn [i*depth + d] = best ; + ++ d ; + + if (!node->children) break ; + node = node->children [best] ; + } + } +} diff --git a/pool/shard006/C/0119721_ohci.c b/pool/shard006/C/0119721_ohci.c new file mode 100644 index 0000000000000000000000000000000000000000..0a1ccbae68ea223aed36257b06a875ad2e443eed --- /dev/null +++ b/pool/shard006/C/0119721_ohci.c @@ -0,0 +1,35 @@ + +#include "ohci.h" +#include "../usb.h" + +static uint16_t ohci_descriptors; +static uint16_t ohci_communication; + +static ohci_controller_t* _ohci_controllers; +static ohci_controller_t* ohci_controllers[MAX_USB_CONTROLLER_COUNT]; + +static ohci_controller_t single_ohci_controller_init(uint8_t id, pci_driver_descriptor_t controller) { + uint16_t status = pci_read_dword(controller.device.bus, controller.device.device, controller.device.function, PCI_STATUS_COMMAND); + pci_write_dword(controller.device.bus, controller.device.device, controller.device.function, PCI_STATUS_COMMAND, status | 0x406); + + ohci_controller_t result = { + .device_addresses = (uint8_t*) kmalloc(USB_MAX_ADDRESSES), + + }; + + return result; + +} + +void ohci_controller_init(void) { + ohci_communication = 0; + _ohci_controllers = (ohci_controller_t*) kmalloc(ohci_controller_count * sizeof(ohci_controller_t)); + + int i; + for (i = 0; i < ohci_controller_count; i++) { + _ohci_controllers[i] = single_ohci_controller_init(i, ohci_controller[i]); + ohci_controllers[i] = (ohci_controller_t*) &_ohci_controllers[i]; + + } + +} diff --git a/pool/shard006/C/0119722_utils.c b/pool/shard006/C/0119722_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..b2441e847cc9b0ae1294c441873935839da3cbd2 --- /dev/null +++ b/pool/shard006/C/0119722_utils.c @@ -0,0 +1,280 @@ +/* + * This file is distributed as part of the MariaDB Corporation MaxScale. It 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, + * version 2. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Copyright MariaDB Corporation Ab 2013-2014 + * + */ + +/** + * @file utils.c - General utility functions + * + * @verbatim + * Revision History + * + * Date Who Description + * 10-06-2013 Massimiliano Pinto Initial implementation + * 12-06-2013 Massimiliano Pinto Read function trought + * the gwbuff strategy + * 13-06-2013 Massimiliano Pinto MaxScale local authentication + * basics + * 02-09-2014 Martin Brampton Replaced C++ comments by C comments + * + * @endverbatim + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* used in the hex2bin function */ +#define char_val(X) (X >= '0' && X <= '9' ? X-'0' : \ + X >= 'A' && X <= 'Z' ? X-'A'+10 : \ + X >= 'a' && X <= 'z' ? X-'a'+10 : \ + '\177') + +/* used in the bin2hex function */ +char hex_upper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; +char hex_lower[] = "0123456789abcdefghijklmnopqrstuvwxyz"; + +/***************************************** + * backend read event triggered by EPOLLIN + *****************************************/ + +int setnonblocking(int fd) +{ + int fl; + + if ((fl = fcntl(fd, F_GETFL, 0)) == -1) + { + char errbuf[STRERROR_BUFLEN]; + MXS_ERROR("Can't GET fcntl for %i, errno = %d, %s.", + fd, + errno, + strerror_r(errno, errbuf, sizeof(errbuf))); + return 1; + } + + if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) == -1) + { + char errbuf[STRERROR_BUFLEN]; + MXS_ERROR("Can't SET fcntl for %i, errno = %d, %s", + fd, + errno, + strerror_r(errno, errbuf, sizeof(errbuf))); + return 1; + } + return 0; +} + + +char *gw_strend(register const char *s) +{ + while (*s++) + { + ; + } + return (char*) (s - 1); +} + +/***************************************** + * generate a random char + *****************************************/ +static char gw_randomchar() +{ + return (char)((random_jkiss() % 78) + 30); +} + +/***************************************** + * generate a random string + * output must be pre allocated + *****************************************/ +int gw_generate_random_str(char *output, int len) +{ + int i; + + for (i = 0; i < len; ++i ) + { + output[i] = gw_randomchar(); + } + + output[len] = '\0'; + + return 0; +} + +/***************************************** + * hex string to binary data + * output must be pre allocated + *****************************************/ +int gw_hex2bin(uint8_t *out, const char *in, unsigned int len) +{ + const char *in_end= in + len; + + if (len == 0 || in == NULL) + { + return 1; + } + + while (in < in_end) + { + register unsigned char b1 = char_val(*in); + uint8_t b2 = 0; + in++; + b2 = (b1 << 4) | char_val(*in); + *out++ = b2; + + in++; + } + + return 0; +} + +/***************************************** + * binary data to hex string + * output must be pre allocated + *****************************************/ +char *gw_bin2hex(char *out, const uint8_t *in, unsigned int len) +{ + const uint8_t *in_end = in + len; + if (len == 0 || in == NULL) + { + return NULL; + } + + for (; in != in_end; ++in) + { + *out++ = hex_upper[((uint8_t) *in) >> 4]; + *out++ = hex_upper[((uint8_t) *in) & 0x0F]; + } + *out= '\0'; + + return out; +} + +/**************************************************** + * fill a preallocated buffer with XOR(str1, str2) + * XOR between 2 equal len strings + * note that XOR(str1, XOR(str1 CONCAT str2)) == str2 + * and that XOR(str1, str2) == XOR(str2, str1) + *****************************************************/ +void gw_str_xor(uint8_t *output, const uint8_t *input1, const uint8_t *input2, unsigned int len) +{ + const uint8_t *input1_end = NULL; + input1_end = input1 + len; + + while (input1 < input1_end) + { + *output++ = *input1++ ^ *input2++; + } + + *output = '\0'; +} + +/********************************************************** + * fill a 20 bytes preallocated with SHA1 digest (160 bits) + * for one input on in_len bytes + **********************************************************/ +void gw_sha1_str(const uint8_t *in, int in_len, uint8_t *out) +{ + unsigned char hash[SHA_DIGEST_LENGTH]; + + SHA1(in, in_len, hash); + memcpy(out, hash, SHA_DIGEST_LENGTH); +} + +/******************************************************** + * fill 20 bytes preallocated with SHA1 digest (160 bits) + * for two inputs, in_len and in2_len bytes + ********************************************************/ +void gw_sha1_2_str(const uint8_t *in, int in_len, const uint8_t *in2, int in2_len, uint8_t *out) +{ + SHA_CTX context; + unsigned char hash[SHA_DIGEST_LENGTH]; + + SHA1_Init(&context); + SHA1_Update(&context, in, in_len); + SHA1_Update(&context, in2, in2_len); + SHA1_Final(hash, &context); + + memcpy(out, hash, SHA_DIGEST_LENGTH); +} + + +/** + * node Gets errno corresponding to latest socket error + * + * Parameters: + * @param fd - in, use + * socket to examine + * + * @return errno + * + * + */ +int gw_getsockerrno(int fd) +{ + int eno = 0; + socklen_t elen = sizeof(eno); + + if (fd <= 0) + { + goto return_eno; + } + + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&eno, &elen) != 0) + { + eno = 0; + } + +return_eno: + return eno; +} + +/** + * Create a HEX(SHA1(SHA1(password))) + * + * @param password The password to encrypt + * @return The new allocated encrypted password, that the caller must free + * + */ +char *create_hex_sha1_sha1_passwd(char *passwd) +{ + uint8_t hash1[SHA_DIGEST_LENGTH] = ""; + uint8_t hash2[SHA_DIGEST_LENGTH] = ""; + char *hexpasswd = NULL; + + if ((hexpasswd = (char *)calloc(SHA_DIGEST_LENGTH * 2 + 1, 1)) == NULL) + { + return NULL; + } + + /* hash1 is SHA1(real_password) */ + gw_sha1_str((uint8_t *)passwd, strlen(passwd), hash1); + + /* hash2 is the SHA1(input data), where input_data = SHA1(real_password) */ + gw_sha1_str(hash1, SHA_DIGEST_LENGTH, hash2); + + /* dbpass is the HEX form of SHA1(SHA1(real_password)) */ + gw_bin2hex(hexpasswd, hash2, SHA_DIGEST_LENGTH); + + return hexpasswd; +} diff --git a/pool/shard006/C/0119723_return_address.c b/pool/shard006/C/0119723_return_address.c new file mode 100644 index 0000000000000000000000000000000000000000..1261eb17c97dbf3ff9c9a130319bfa007d10eca9 --- /dev/null +++ b/pool/shard006/C/0119723_return_address.c @@ -0,0 +1,68 @@ +/* + * arch/arm/kernel/return_address.c + * + * Copyright (C) 2009 Uwe Kleine-Koenig + * for Pengutronix + * + * 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 +#include + +#if defined(CONFIG_FRAME_POINTER) || !defined(CONFIG_ARM_UNWIND) +#include + +#include + +struct return_address_data { + unsigned int level; + void *addr; +}; + +static int save_return_addr(struct stackframe *frame, void *d) +{ + struct return_address_data *data = d; + + if (!data->level) { + data->addr = (void *)frame->lr; + + return 1; + } else { + --data->level; + return 0; + } +} + +void *return_address(unsigned int level) +{ + struct return_address_data data; + struct stackframe frame; + register unsigned long current_sp asm ("sp"); + + data.level = level + 1; + + frame.fp = (unsigned long)__builtin_frame_address(0); + frame.sp = current_sp; + frame.lr = (unsigned long)__builtin_return_address(0); + frame.pc = (unsigned long)return_address; + + walk_stackframe(&frame, save_return_addr, &data); + + if (!data.level) + return data.addr; + else + return NULL; +} + +#else /* CONFIG_FRAME_POINTER || CONFIG_ARM_UNWIND */ + +void *return_address(unsigned int level) +{ + return NULL; +} + +#endif /* CONFIG_FRAME_POINTER || CONFIG_ARM_UNWIND */ + +EXPORT_SYMBOL_GPL(return_address); diff --git a/pool/shard006/C/0119725_io_delegating.c b/pool/shard006/C/0119725_io_delegating.c new file mode 100644 index 0000000000000000000000000000000000000000..aae1df560f71bcb4dfbfcfd4cd9925b7226280df --- /dev/null +++ b/pool/shard006/C/0119725_io_delegating.c @@ -0,0 +1,344 @@ +/* + * Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER + * + * This code is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 + * only, as published by the Free Software Foundation. + * + * This code 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 version 2 for more details (a copy is + * included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this work; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + * Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo + * Park, CA 94025 or visit www.sun.com if you need additional + * information or have any questions. + */ + + +/*************** NOTE: this file is included when PLATFORM_TYPE_DELEGATING=true **************************/ + +/*---------------------------------------------------------------------------*\ + * Channel I/O * +\*---------------------------------------------------------------------------*/ + +#define ptrForJni(addr) ((signed char *)addr) +#define freeJVMObject(jobject) (*JNI_env)->DeleteGlobalRef(JNI_env, jobject) + + +/** + * Asserts a given condition. + * + * @param condition the condition to test + * @param msg the optional message that will be passed to 'fatalVMError' + * if 'condition' is false + */ +static void jni_assume(int condition, char *msg) { + if (!condition) { + if (msg == null) { + msg = "JNI assume failure"; + } + if (JNI_env != null && (*JNI_env)->ExceptionOccurred(JNI_env)) { + (*JNI_env)->ExceptionDescribe(JNI_env); + } + JNI_env = null; + fatalVMError(msg); + } +} + +/** + * Check the last jni call worked + * + * @param msg the optional message that will be passed to 'fatalVMError' + * if the last JNI call failed + */ +static void jni_check(char *msg) { + jni_assume(!(*JNI_env)->ExceptionOccurred(JNI_env), msg); +} + +/** + * Creates a string in the embedded JVM whose value is initialized from a given string in Squawk memory. + * + * @param string the address of an array of bytes or chars implementing the body of a Squawk string + * @param classID the identifier of the String class (CID_STRING or CID_STRING_OF_BYTES) + * @return the corresponding String object in the embedded JVM + */ +static Address createJVMString(Address string, int classID, int length) { + Address jvmString; + + jni_assume(string != null, "must not be a null string"); + jni_assume(classID == CID_STRING || classID == CID_STRING_OF_BYTES, "invalid string classID"); + if (classID == CID_STRING) { + jvmString = (*JNI_env)->NewString(JNI_env, (const jchar*)string, length); + } else { + /* + * Make a null-terminated copy of the string that conforms to the format expected by NewStringUTF + */ + void *newBuffer(UWord size, const char *desc, boolean fatalIfFail); + void freeBuffer(Address buffer); + char* asciiString = (char *)newBuffer(length + 1, "createJVMString", true); + memcpy(asciiString, string, length); + asciiString[length] = 0; + jvmString = (*JNI_env)->NewStringUTF(JNI_env, asciiString); + freeBuffer(asciiString); + } + jni_assume(jvmString != null, "String allocation failed"); + return jvmString; +} + +/** + * Creates a byte array in the embedded JVM whose contents are initialized from a given byte array in Squawk memory. + * + * @param array the address of a byte array + * @param fill true if the elements of the returned JVM array should be filled from 'array' + * @return the corresponding byte array object in the embedded JVM + */ +static Address createJVMByteArray(Address array, int length, boolean fill) { + Address jvmByteArray; + assume(array != 0); // This test should be done in Java code so that a NullPointerException can be thrown + jvmByteArray = (*JNI_env)->NewByteArray(JNI_env, length); + jni_assume(jvmByteArray != null, "Byte array allocation failed"); + if (fill) { + (*JNI_env)->SetByteArrayRegion(JNI_env, jvmByteArray, 0, length, ptrForJni(array)); + jni_check("Byte array copy failed"); + } + return jvmByteArray; +} + +/** + * Creates a char array in the embedded JVM whose contents are initialized from a given char array in Squawk memory. + * + * @param array the address of a char array in Squawk memory + * @param fill true if the elements of the returned JVM array should be filled from 'array' + * @return the corresponding char array object in the embedded JVM + */ +static Address createJVMCharArray(Address array, int length, boolean fill) { + Address jvmCharArray; + assume(array != 0); // This test should be done in Java code so that a NullPointerException can be thrown + jvmCharArray = (*JNI_env)->NewCharArray(JNI_env, length); + jni_assume(jvmCharArray != null, "Char array allocation failed"); + if (fill) { + (*JNI_env)->SetCharArrayRegion(JNI_env, jvmCharArray, 0, length, (jchar *)ptrForJni(array)); + jni_check("Char array copy failed"); + } + return jvmCharArray; +} + +/** + * Creates an int array in the embedded JVM whose contents are initialized from a given int array in Squawk memory. + * + * @param array the address of an int array in Squawk memory + * @param fill true if the elements of the returned JVM array should be filled from 'array' + * @return the corresponding int array object in the embedded JVM + */ +static Address createJVMIntArray(Address array, int length, boolean fill) { + Address jvmIntArray; + assume(array != 0); // This test should be done in Java code so that a NullPointerException can be thrown + jvmIntArray = (*JNI_env)->NewIntArray(JNI_env, length); + jni_assume(jvmIntArray != null, "Int array allocation failed"); + if (fill) { + (*JNI_env)->SetIntArrayRegion(JNI_env, jvmIntArray, 0, length, (jint*)ptrForJni(array)); + jni_check("Int array copy failed"); + } + return jvmIntArray; +} + +/** + * Creates an object in the embedded JVM whose contents are initialized from a given object in Squawk memory. + * This routine only handles Strings, byte arrays, char arrays and int arrays. + * + * @param object the address of an object in Squawk memory + * @param fill true if the return object should be initialized from the Squawk object + * @return the corresponding object in the embedded JVM + */ +static Address createJVMObject(Address object, boolean fill) { + if (object != 0) { + Address cls = getClass(object); + int id = com_sun_squawk_Klass_id(cls); + Address jvmObject; + if (id == CID_STRING || id == CID_STRING_OF_BYTES) { + jvmObject = createJVMString(object, id, getArrayLength(object)); + } else if (id == CID_BYTE_ARRAY) { + jvmObject = createJVMByteArray(object, getArrayLength(object), fill); + } else if (id == CID_CHAR_ARRAY) { + jvmObject = createJVMCharArray(object, getArrayLength(object), fill); + } else if (id == CID_INT_ARRAY) { + jvmObject = createJVMIntArray(object, getArrayLength(object), fill); + } else { + fatalVMError("createJVMObject:: Invalid reference type"); + } + return jvmObject; + } + return null; +} + +/** + * Updates the contents of a byte array from the contents of a byte array in the embedded JVM. + * + * @param array the address of a byte array + * @param jvmArray a handle to a byte array in the embedded JVM + * @param offset the starting index + * @param length the number of bytes to copy + */ +static void updateFromJVMByteArray(Address array, Address jvmArray, int offset, int length) { + assume(array != 0 && jvmArray != null); // This test should be done in Java code so that a NullPointerException can be thrown + (*JNI_env)->GetByteArrayRegion(JNI_env, jvmArray, offset, length, ptrForJni(array+offset)); + jni_check("Byte array copy back failed"); +} + +/** + * Initializes the IO subsystem. + * + * @param classPath the class path with which to start the embedded JVM + * @param args extra arguments to pass to the embedded JVM + * @param argc the number of extra arguments in 'args + */ +void CIO_initialize(char *classPath, char** args, int argc) { + /* + * Create the embedded Java VM now + */ + jint createJVM(JavaVM **, void **env, void *args); + JavaVMInitArgs vm_args; + JavaVMOption options[MAX_JVM_ARGS + 1]; + + char *buf = (char *)malloc(strlen("-Djava.class.path=")+strlen(classPath)+strlen(":hosted-support/classes")+1); + sprintf(buf, "-Djava.class.path=%s%chosted-support%cclasses", classPath, (char)pathSeparatorChar, (char)fileSeparatorChar); + + // A version 1.4 Java VM is required + vm_args.version = JNI_VERSION_1_4; + + vm_args.options = options; + options[0].optionString = buf; + vm_args.nOptions = 1; + + /* + * Disable the JIT as it has stability problems on at least one platform (Solaris) + * and the slow down is not noticeable anyway. + * + * Try it on again. It makes a 20% difference with the suite creator. + * if there is trouble, users can disable from command line: + * -J-Djava.compiler=NONE + */ + /* options[vm_args.nOptions++].optionString = "-Djava.compiler=NONE";*/ + + /* + * Add command line oprtions. + */ + while (argc-- != 0) { + options[vm_args.nOptions++].optionString = *args; + args++; + } +/* +{ +int i; +fprintf(stderr, "Starting embedded JVM with options \""); +for (i = 0; i != vm_args.nOptions; i++) { + fprintf(stderr, "%s ", vm_args.options[i].optionString); +} +fprintf(stderr, "\"\n"); +} +*/ + createJVM(&jvm, (void**)&JNI_env, &vm_args); + + if (JNI_env != null) { + channelIO_clazz = (*JNI_env)->FindClass(JNI_env, "com/sun/squawk/vm/ChannelIO"); + jni_assume(channelIO_clazz != null, "Can't find com.sun.squawk.vm.ChannelIO"); + + channelIO_execute = (*JNI_env)->GetStaticMethodID(JNI_env, channelIO_clazz, "execute", "(IIIIIIIIILjava/lang/Object;Ljava/lang/Object;)I"); + jni_assume(channelIO_execute != null, "Couldn't find method: channelIO_execute()"); + + } else { + fprintf(stderr, "Warning: Error creating Java VM -- I/O subsystem will be disabled\n"); + } +} + +/** + * Shuts down the IO subsystem. + */ +//void CIO_finalize() { +// if (jvm != 0) { +// (*jvm)->DestroyJavaVM(jvm); +// jvm = 0; +// } +//} + +/** + * Executes an operation on a given channel for an isolate. + * + * @param context the I/O context + * @param op the operation to perform + * @param channel the identifier of the channel to execute the operation on + * @param i1 + * @param i2 + * @param i3 + * @param i4 + * @param i5 + * @param i6 + * @param send + * @param receive + * @return the operation result + */ + static void ioExecute(void) { + int context = com_sun_squawk_ServiceOperation_context; + int op = com_sun_squawk_ServiceOperation_op; + int channel = com_sun_squawk_ServiceOperation_channel; + int i1 = com_sun_squawk_ServiceOperation_i1; + int i2 = com_sun_squawk_ServiceOperation_i2; + int i3 = com_sun_squawk_ServiceOperation_i3; + int i4 = com_sun_squawk_ServiceOperation_i4; + int i5 = com_sun_squawk_ServiceOperation_i5; + int i6 = com_sun_squawk_ServiceOperation_i6; + Address send = com_sun_squawk_ServiceOperation_o1; + Address receive = com_sun_squawk_ServiceOperation_o2; + + Address s1; + Address r1; + int res; + + { + /* + * Always return 0 if there is no embedded JVM. + */ + if (JNI_env == null) { + res = 0; + } else { + s1 = createJVMObject(send, true); + r1 = createJVMObject(receive, false); +//fprintf(stderr, ">>> %d %d %d\n", cio, op, channelID); + res = (*JNI_env)->CallStaticIntMethod(JNI_env, channelIO_clazz, channelIO_execute, context, op, channel, i1, i2, i3, i4, i5, i6, s1, r1); + jni_check("CIO_execute failure"); +//fprintf(stderr, " = %d\n", res); + if (s1 != null) freeJVMObject(s1); + if (r1 != null) { + updateFromJVMByteArray(receive, r1, i1, i2); + freeJVMObject(r1); + } + } + } + com_sun_squawk_ServiceOperation_result = res; +} + +#if KERNEL_SQUAWK +/** + * Posts an event via ChannelIO to wake up any waiters. + */ +static void ioPostEvent(void) { + + { + /* + * Check if there is no embedded JVM. + */ + if (JNI_env != null) { + void os_postEvent(boolean notify); + os_postEvent(true); + } + } +} +#endif diff --git a/pool/shard006/C/0119726_message_queue.c b/pool/shard006/C/0119726_message_queue.c new file mode 100644 index 0000000000000000000000000000000000000000..9ea7e4ce11ad54ce6e5c5dbcc95b45ce63c1068f --- /dev/null +++ b/pool/shard006/C/0119726_message_queue.c @@ -0,0 +1,240 @@ +/* Copyright (C) 2010-2016 The RetroArch team + * + * --------------------------------------------------------------------------------------- + * The following license statement only applies to this file (message_queue.c). + * --------------------------------------------------------------------------------------- + * + * 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 +#include + +#include +#include +#include +#include + +struct queue_elem +{ + unsigned duration; + unsigned prio; + char *msg; +}; + +struct msg_queue +{ + struct queue_elem **elems; + size_t ptr; + size_t size; + char *tmp_msg; +}; + +/** + * msg_queue_new: + * @size : maximum size of message + * + * Creates a message queue with maximum size different messages. + * + * Returns: NULL if allocation error, pointer to a message queue + * if successful. Has to be freed manually. + **/ +msg_queue_t *msg_queue_new(size_t size) +{ + struct queue_elem **elems = NULL; + msg_queue_t *queue = (msg_queue_t*)calloc(1, sizeof(*queue)); + + if (!queue) + return NULL; + + queue->size = size + 1; + + elems = (struct queue_elem**)calloc(queue->size, + sizeof(struct queue_elem*)); + + if (!elems) + { + free(queue); + return NULL; + } + + queue->elems = elems; + queue->ptr = 1; + + return queue; +} + +/** + * msg_queue_free: + * @queue : pointer to queue object + * + * Frees message queue.. + **/ +void msg_queue_free(msg_queue_t *queue) +{ + if (queue) + { + msg_queue_clear(queue); + free(queue->elems); + } + free(queue); +} + + +/** + * msg_queue_push: + * @queue : pointer to queue object + * @msg : message to add to the queue + * @prio : priority level of the message + * @duration : how many times the message can be pulled + * before it vanishes (E.g. show a message for + * 3 seconds @ 60fps = 180 duration). + * + * Push a new message onto the queue. + **/ +void msg_queue_push(msg_queue_t *queue, const char *msg, + unsigned prio, unsigned duration) +{ + size_t tmp_ptr = 0; + struct queue_elem *new_elem = NULL; + + if (!queue || queue->ptr >= queue->size) + return; + + new_elem = (struct queue_elem*) + calloc(1, sizeof(struct queue_elem)); + if (!new_elem) + return; + + new_elem->prio = prio; + new_elem->duration = duration; + new_elem->msg = msg ? strdup(msg) : NULL; + + queue->elems[queue->ptr] = new_elem; + + tmp_ptr = queue->ptr++; + + while (tmp_ptr > 1) + { + struct queue_elem *parent = queue->elems[tmp_ptr >> 1]; + struct queue_elem *child = queue->elems[tmp_ptr]; + + if (child->prio <= parent->prio) + break; + + queue->elems[tmp_ptr >> 1] = child; + queue->elems[tmp_ptr] = parent; + + tmp_ptr >>= 1; + } +} + +/** + * msg_queue_clear: + * @queue : pointer to queue object + * + * Clears out everything in the queue. + **/ +void msg_queue_clear(msg_queue_t *queue) +{ + size_t i; + + if (!queue) + return; + + for (i = 1; i < queue->ptr; i++) + { + if (queue->elems[i]) + { + free(queue->elems[i]->msg); + free(queue->elems[i]); + queue->elems[i] = NULL; + } + } + queue->ptr = 1; + free(queue->tmp_msg); + queue->tmp_msg = NULL; +} + +/** + * msg_queue_pull: + * @queue : pointer to queue object + * + * Pulls highest priority message in queue. + * + * Returns: NULL if no message in queue, otherwise a string + * containing the message. + **/ +const char *msg_queue_pull(msg_queue_t *queue) +{ + struct queue_elem *front = NULL, *last = NULL; + size_t tmp_ptr = 1; + + (void)tmp_ptr; + + /* Nothing in queue. */ + if (!queue || queue->ptr == 1) + return NULL; + + front = (struct queue_elem*)queue->elems[1]; + front->duration--; + if (front->duration > 0) + return front->msg; + + free(queue->tmp_msg); + queue->tmp_msg = front->msg; + front->msg = NULL; + + front = (struct queue_elem*)queue->elems[1]; + last = (struct queue_elem*)queue->elems[--queue->ptr]; + queue->elems[1] = last; + free(front); + + for (;;) + { + struct queue_elem *parent = NULL; + struct queue_elem *child = NULL; + size_t switch_index = tmp_ptr; + bool left = (tmp_ptr * 2 <= queue->ptr) + && (queue->elems[tmp_ptr] < queue->elems[tmp_ptr * 2]); + bool right = (tmp_ptr * 2 + 1 <= queue->ptr) + && (queue->elems[tmp_ptr] < queue->elems[tmp_ptr * 2 + 1]); + + if (!left && !right) + break; + + if (left && !right) + switch_index <<= 1; + else if (right && !left) + switch_index += switch_index + 1; + else + { + if (queue->elems[tmp_ptr * 2] + >= queue->elems[tmp_ptr * 2 + 1]) + switch_index <<= 1; + else + switch_index += switch_index + 1; + } + + parent = (struct queue_elem*)queue->elems[tmp_ptr]; + child = (struct queue_elem*)queue->elems[switch_index]; + queue->elems[tmp_ptr] = child; + queue->elems[switch_index] = parent; + tmp_ptr = switch_index; + } + + return queue->tmp_msg; +} diff --git a/pool/shard006/C/0119728_mme_user_init.c b/pool/shard006/C/0119728_mme_user_init.c new file mode 100644 index 0000000000000000000000000000000000000000..8a1a436687a7a79c5fe00d2b653677881a6f05c5 --- /dev/null +++ b/pool/shard006/C/0119728_mme_user_init.c @@ -0,0 +1,70 @@ +/************************************************************** + * Copyright (C) 2010 STMicroelectronics. All Rights Reserved. + * This file is part of the latest release of the Multicom4 project. This release + * is fully functional and provides all of the original MME functionality.This + * release is now considered stable and ready for integration with other software + * components. + + * Multicom4 is a 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 + * version 2. + + * Multicom4 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 Multicom4; + * see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - + * Suite 330, Boston, MA 02111-1307, USA. + + * Written by Multicom team at STMicroelectronics in November 2010. + * Contact multicom.support@st.com. +**************************************************************/ + +/* + * + */ + +#include /* External defines and prototypes */ + +#include "_mme_sys.h" /* Internal defines and prototypes */ + +#include /* External ioctl interface */ + +#include "_mme_user.h" /* Internal definitions */ + +#include + +/* + * Userspace->Kernel wrappers for MME calls + */ + +int mme_user_mmeinit(mme_user_t *instance, void *arg) +{ + int res = -ENODEV; + MME_ERROR status = MME_INTERNAL_ERROR; + + mme_userinit_t *user_mmeinit = (mme_userinit_t *) arg; + + /* Init MME */ + status = MME_Init(); + if (put_user(status,&(user_mmeinit->status))) { + res = -EFAULT; + } + return res; +} + +int mme_user_mmeterm(mme_user_t *instance, void *arg) +{ + int res = -ENODEV; + MME_ERROR status = MME_INTERNAL_ERROR; + + mme_userterm_t *user_mmeterm = (mme_userterm_t *) arg; + + /* Init MME */ + status = MME_Term(); + if (put_user(status,&(user_mmeterm->status))) { + res = -EFAULT; + } + return res; +} diff --git a/pool/shard006/C/0119732_gststreak.c b/pool/shard006/C/0119732_gststreak.c new file mode 100644 index 0000000000000000000000000000000000000000..3feb1f4a950d946ca7d2b21736d2b60ac7421f48 --- /dev/null +++ b/pool/shard006/C/0119732_gststreak.c @@ -0,0 +1,279 @@ +/* GStreamer + * Copyright (C) <2009> Sebastian Dröge + * + * EffecTV - Realtime Digital Video Effector + * Copyright (C) 2001-2006 FUKUCHI Kentaro + * + * StreakTV - afterimage effector. + * Copyright (C) 2001-2002 FUKUCHI Kentaro + * + * This combines the StreakTV and BaltanTV effects, which are + * very similar. BaltanTV is used if the feedback property is set + * to TRUE, otherwise StreakTV is used. + * + * EffecTV is free software. This library is free software; + * you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + +/** + * SECTION:element-streaktv + * + * StreakTV makes after images of moving objects. + * + * + * Example launch line + * |[ + * gst-launch -v videotestsrc ! streaktv ! ffmpegcolorspace ! autovideosink + * ]| This pipeline shows the effect of streaktv on a test stream. + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "gststreak.h" +#include "gsteffectv.h" + +#include + +#define DEFAULT_FEEDBACK FALSE + +enum +{ + PROP_0, + PROP_FEEDBACK +}; + +GST_BOILERPLATE (GstStreakTV, gst_streaktv, GstVideoFilter, + GST_TYPE_VIDEO_FILTER); + +static GstStaticPadTemplate gst_streaktv_src_template = + GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS (GST_VIDEO_CAPS_BGRx "; " GST_VIDEO_CAPS_RGBx ";" + GST_VIDEO_CAPS_xBGR "; " GST_VIDEO_CAPS_xRGB) + ); + +static GstStaticPadTemplate gst_streaktv_sink_template = + GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS (GST_VIDEO_CAPS_BGRx "; " GST_VIDEO_CAPS_RGBx ";" + GST_VIDEO_CAPS_xBGR "; " GST_VIDEO_CAPS_xRGB) + ); + + + +static GstFlowReturn +gst_streaktv_transform (GstBaseTransform * trans, GstBuffer * in, + GstBuffer * out) +{ + GstStreakTV *filter = GST_STREAKTV (trans); + guint32 *src, *dest; + GstFlowReturn ret = GST_FLOW_OK; + gint i, cf; + gint video_area = filter->width * filter->height; + guint32 **planetable = filter->planetable; + gint plane = filter->plane; + guint stride_mask, stride_shift, stride; + + GST_OBJECT_LOCK (filter); + if (filter->feedback) { + stride_mask = 0xfcfcfcfc; + stride = 8; + stride_shift = 2; + } else { + stride_mask = 0xf8f8f8f8; + stride = 4; + stride_shift = 3; + } + + src = (guint32 *) GST_BUFFER_DATA (in); + dest = (guint32 *) GST_BUFFER_DATA (out); + + for (i = 0; i < video_area; i++) { + planetable[plane][i] = (src[i] & stride_mask) >> stride_shift; + } + + cf = plane & (stride - 1); + if (filter->feedback) { + for (i = 0; i < video_area; i++) { + dest[i] = planetable[cf][i] + + planetable[cf + stride][i] + + planetable[cf + stride * 2][i] + + planetable[cf + stride * 3][i]; + planetable[plane][i] = (dest[i] & stride_mask) >> stride_shift; + } + } else { + for (i = 0; i < video_area; i++) { + dest[i] = planetable[cf][i] + + planetable[cf + stride][i] + + planetable[cf + stride * 2][i] + + planetable[cf + stride * 3][i] + + planetable[cf + stride * 4][i] + + planetable[cf + stride * 5][i] + + planetable[cf + stride * 6][i] + + planetable[cf + stride * 7][i]; + } + } + + plane++; + filter->plane = plane & (PLANES - 1); + GST_OBJECT_UNLOCK (filter); + + return ret; +} + +static gboolean +gst_streaktv_set_caps (GstBaseTransform * btrans, GstCaps * incaps, + GstCaps * outcaps) +{ + GstStreakTV *filter = GST_STREAKTV (btrans); + GstStructure *structure; + gboolean ret = FALSE; + + structure = gst_caps_get_structure (incaps, 0); + + GST_OBJECT_LOCK (filter); + if (gst_structure_get_int (structure, "width", &filter->width) && + gst_structure_get_int (structure, "height", &filter->height)) { + gint i; + + if (filter->planebuffer) + g_free (filter->planebuffer); + + filter->planebuffer = + g_new0 (guint32, filter->width * filter->height * 4 * PLANES); + for (i = 0; i < PLANES; i++) + filter->planetable[i] = + &filter->planebuffer[filter->width * filter->height * i]; + + ret = TRUE; + } + GST_OBJECT_UNLOCK (filter); + + return ret; +} + +static gboolean +gst_streaktv_start (GstBaseTransform * trans) +{ + GstStreakTV *filter = GST_STREAKTV (trans); + + filter->plane = 0; + + return TRUE; +} + +static void +gst_streaktv_finalize (GObject * object) +{ + GstStreakTV *filter = GST_STREAKTV (object); + + if (filter->planebuffer) { + g_free (filter->planebuffer); + filter->planebuffer = NULL; + } + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +static void +gst_streaktv_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstStreakTV *filter = GST_STREAKTV (object); + + switch (prop_id) { + case PROP_FEEDBACK: + if (G_UNLIKELY (GST_STATE (filter) >= GST_STATE_PAUSED)) { + g_warning ("Changing the \"feedback\" property only allowed " + "in state < PLAYING"); + return; + } + + filter->feedback = g_value_get_boolean (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_streaktv_get_property (GObject * object, guint prop_id, GValue * value, + GParamSpec * pspec) +{ + GstStreakTV *filter = GST_STREAKTV (object); + + switch (prop_id) { + case PROP_FEEDBACK: + g_value_set_boolean (value, filter->feedback); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_streaktv_base_init (gpointer g_class) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); + + gst_element_class_set_details_simple (element_class, "StreakTV effect", + "Filter/Effect/Video", + "StreakTV makes after images of moving objects", + "FUKUCHI, Kentarou , " + "Sebastian Dröge "); + + gst_element_class_add_static_pad_template (element_class, + &gst_streaktv_sink_template); + gst_element_class_add_static_pad_template (element_class, + &gst_streaktv_src_template); +} + +static void +gst_streaktv_class_init (GstStreakTVClass * klass) +{ + GObjectClass *gobject_class = (GObjectClass *) klass; + GstBaseTransformClass *trans_class = (GstBaseTransformClass *) klass; + + gobject_class->set_property = gst_streaktv_set_property; + gobject_class->get_property = gst_streaktv_get_property; + + gobject_class->finalize = gst_streaktv_finalize; + + g_object_class_install_property (gobject_class, PROP_FEEDBACK, + g_param_spec_boolean ("feedback", "Feedback", + "Feedback", DEFAULT_FEEDBACK, + G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); + + trans_class->set_caps = GST_DEBUG_FUNCPTR (gst_streaktv_set_caps); + trans_class->transform = GST_DEBUG_FUNCPTR (gst_streaktv_transform); + trans_class->start = GST_DEBUG_FUNCPTR (gst_streaktv_start); +} + +static void +gst_streaktv_init (GstStreakTV * filter, GstStreakTVClass * klass) +{ + filter->feedback = DEFAULT_FEEDBACK; +} diff --git a/pool/shard006/C/0119734_avx512f-vpsravq-2.c b/pool/shard006/C/0119734_avx512f-vpsravq-2.c new file mode 100644 index 0000000000000000000000000000000000000000..57d2a94011829001cdf3b26cf44ccb6e9dc88a70 --- /dev/null +++ b/pool/shard006/C/0119734_avx512f-vpsravq-2.c @@ -0,0 +1,59 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -mavx512f" } */ +/* { dg-require-effective-target avx512f } */ + +#define AVX512F + +#include "avx512f-helper.h" + +#define SIZE (AVX512F_LEN / 64) +#include "avx512f-mask-type.h" + +static void +CALC (long long *r, long long *s1, long long *s2) +{ + int i; + for (i = 0; i < SIZE; i++) + { + r[i] = + s2[i] < 64 ? (s1[i] >> s2[i]) : (s1[i] > + 0 ? 0 : 0xFFFFFFFFFFFFFFFFLL); + } +} + +void +TEST (void) +{ + int i, sign; + UNION_TYPE (AVX512F_LEN, i_q) res1, res2, res3, src1, src2; + MASK_TYPE mask = MASK_VALUE; + long long res_ref[SIZE]; + + sign = -1; + for (i = 0; i < SIZE; i++) + { + src1.a[i] = 2 + sign * 7 * i % 291; + src2.a[i] = 1 + 17 * i % 71; + sign = sign * -1; + } + + for (i = 0; i < SIZE; i++) + res2.a[i] = DEFAULT_VALUE; + + res1.x = INTRINSIC (_srav_epi64) (src1.x, src2.x); + res2.x = INTRINSIC (_mask_srav_epi64) (res2.x, mask, src1.x, src2.x); + res3.x = INTRINSIC (_maskz_srav_epi64) (mask, src1.x, src2.x); + + CALC (res_ref, src1.a, src2.a); + + if (UNION_CHECK (AVX512F_LEN, i_q) (res1, res_ref)) + abort (); + + MASK_MERGE (i_q) (res_ref, mask, SIZE); + if (UNION_CHECK (AVX512F_LEN, i_q) (res2, res_ref)) + abort (); + + MASK_ZERO (i_q) (res_ref, mask, SIZE); + if (UNION_CHECK (AVX512F_LEN, i_q) (res3, res_ref)) + abort (); +} diff --git a/pool/shard006/C/0119737_rpm_actions.c b/pool/shard006/C/0119737_rpm_actions.c new file mode 100644 index 0000000000000000000000000000000000000000..a352fd2d0aefbcac728d46a6ea22738cd12b965f --- /dev/null +++ b/pool/shard006/C/0119737_rpm_actions.c @@ -0,0 +1,45 @@ +// Copyright (C) 2004-2005 Ryan Powell + +// This file is part of RPM. + +// RPM 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. + +// RPM 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 RPM; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// + +#include "g_local.h" + +void RPM_ReadyCheck (gentity_t *ent) +{ +#ifdef _SOF2_BOTS + if (ent->r.svFlags & SVF_BOT) + { + if(!ent->client->pers.ready) + { + ent->client->pers.ready = 1; + } + return; + } +#endif + if(level.time < ent->client->pers.readyMessageTime + 3000) + { + return; + } + + if(g_doWarmup.integer == 2 && !ent->client->pers.ready) + { + //trap_SendServerCommand( ent-g_entities, va("cp \"@You are not ready for the match\nPlease type ^1/ready ^7in console\n^7or\n^1!r ^7in chat!\n\"")); + trap_SendServerCommand( ent-g_entities, va("cp \"@You are not ready for the match\nPlease type ^1!r ^7in chat!\n\"")); + ent->client->pers.readyMessageTime = level.time; + } +} diff --git a/pool/shard006/C/0119743_VariationalInequality_driver.c b/pool/shard006/C/0119743_VariationalInequality_driver.c new file mode 100644 index 0000000000000000000000000000000000000000..6903cd6dce7a53246e741bb5e96b472e3d6fdcf6 --- /dev/null +++ b/pool/shard006/C/0119743_VariationalInequality_driver.c @@ -0,0 +1,166 @@ +/* Siconos is a program dedicated to modeling, simulation and control + * of non smooth dynamical systems. + * + * Copyright 2016 INRIA. + * + * 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 +#include +#include +#include +#include +#include + +#include "NumericsOptions.h" +#include "VariationalInequality_Solvers.h" +#include "VariationalInequality_computeError.h" + +#include "NonSmoothDrivers.h" +#include "SiconosBlas.h" +#include "SiconosSets.h" + +char * SICONOS_VI_EG_STR = "VI_EG"; +char * SICONOS_VI_FPP_STR = "VI_FPP"; +char * SICONOS_VI_HP_STR = "VI_HP"; +char * SICONOS_VI_BOX_QI_STR = "Box VI solver based on Qi C-function"; +char * SICONOS_VI_BOX_AVI_LSA_STR = "Box VI solver based on the Newton-Josephy method"; +char * SICONOS_VI_BOX_PATH_STR = "Box VI solver based on PATH solver"; + +/* #define DEBUG_MESSAGES */ +/* #define DEBUT_STDOUT */ +#include "debug.h" + + +void snPrintf(int level, SolverOptions* opts, const char *fmt, ...); + +int variationalInequality_driver(VariationalInequality* problem, + double *x, double *w, + SolverOptions* options, + NumericsOptions* global_options) +{ + if (options == NULL) + numericsError("variationalInequality_driver", "null input for solver and/or global options"); + /* Set global options */ + if (global_options) + { + setNumericsOptions(global_options); + options->numericsOptions = global_options; + } + + /* If the options for solver have not been set, read default values in .opt file */ + int NoDefaultOptions = options->isSet; /* true(1) if the SolverOptions structure has been filled in else false(0) */ + + if (!NoDefaultOptions) + readSolverOptions(3, options); + + if (verbose > 0) + printSolverOptions(options); + + /* Solver name */ + /*char * name = options->solverName;*/ + + int info = -1 ; + + /* Check for trivial case */ + info = checkTrivialCase_vi(problem, x, w, options); + if (info == 0){ + double error; + variationalInequality_computeError(problem, x , w, options->dparam[0], options, &error); + printf("variationalInequality_driver. error = %8.4e\n", error); + return info; + } + + switch (options->solverId) + { + /* Non Smooth Gauss Seidel (NSGS) */ + /* Extra Gradient algorithm */ + case SICONOS_VI_EG: + { + snPrintf(1, options, + " ========================== Call ExtraGradient (EG) solver for VI problem ==========================\n"); + variationalInequality_ExtraGradient(problem, x , w , &info , options); + break; + } + case SICONOS_VI_FPP: + { + snPrintf(1, options, + " ========================== Call Fixed Point Projection (FPP) solver for VI problem ==========================\n"); + variationalInequality_FixedPointProjection(problem, x , w , &info , options); + break; + } + case SICONOS_VI_HP: + { + snPrintf(1, options, + " ========================== Call Hyperplane Projection (HP) solver for VI problem ==========================\n"); + variationalInequality_HyperplaneProjection(problem, x , w , &info , options); + break; + } + case SICONOS_VI_BOX_QI: + { + variationalInequality_box_newton_QiLSA(problem, x, w, &info, options); + break; + } + case SICONOS_VI_BOX_AVI_LSA: + { + vi_box_AVI_LSA(problem, x, w, &info, options); + break; + } + case SICONOS_VI_BOX_PATH: + { + vi_box_path(problem, x, w, &info, options); + break; + } + default: + { + fprintf(stderr, "Numerics, variationalInequality_driver failed. Unknown solver.\n"); + exit(EXIT_FAILURE); + + } + } + + return info; + +} + +int checkTrivialCase_vi(VariationalInequality* problem, double* x, + double* w, SolverOptions* options) +{ + int n = problem->size; + if (problem->ProjectionOnX) + { + problem->ProjectionOnX(problem,x,w); + } + else + { + cblas_dcopy(problem->size, x, 1, w, 1); + project_on_set(problem->size, w, problem->set); + } + cblas_daxpy(n, -1.0,x, 1, w , 1); + double nnorm = cblas_dnrm2(n,w,1); + DEBUG_PRINTF("checkTrivialCase_vi, nnorm = %6.4e\n",nnorm); + + if (nnorm > fmin(options->dparam[0], 1e-12)) + return 1; + + problem->F(problem,n,x,w); + nnorm = cblas_dnrm2(n,w,1); + DEBUG_PRINTF("checkTrivialCase_vi, nnorm = %6.4e\n",nnorm); + + if (nnorm > fmin(options->dparam[0], 1e-12)) + return 1; + + if (verbose == 1) + printf("variationalInequality driver, trivial solution F(x) = 0, x in X.\n"); + return 0; +} diff --git a/pool/shard006/C/0119747_buf_string.c b/pool/shard006/C/0119747_buf_string.c new file mode 100644 index 0000000000000000000000000000000000000000..1865c3ce10a727a84406bb148a8564d13bc026a8 --- /dev/null +++ b/pool/shard006/C/0119747_buf_string.c @@ -0,0 +1,55 @@ +#include +#include +#include + +#include "buf_string.h" + +int buffer_add(StringBuf *buf, char *collected) { + int new_size = strlen(collected); + + /* DONT Resize just hope that it has enough memory */ + assert((buf->size + new_size +1) <= buf->max_buf_size); + + strncpy(&buf->str[buf->size], collected, new_size); + buf->size += new_size; + + return buf->size; +} + +/* optimized collecte for single char */ +int buffer_addc(StringBuf *buf, char collected_c) { + /* DONT Resize just hope that it has enough memory */ + assert((buf->size + 1) <= buf->max_buf_size); + + buf->str[buf->size] = collected_c; + buf->str[buf->size + 1] = '\0'; + return ++buf->size; +} + +StringBuf *StringBuf_create(int size) { + StringBuf *p; + p = (StringBuf * ) malloc(sizeof(StringBuf)); + p->size = 0; + p->max_buf_size = size; + p->str = (char *) malloc(sizeof(char) * size); + + return p; +} + +void StringBuf_destroy(StringBuf *p) { + free(p->str); + free(p); +} + +#ifdef DEBUG_BUF_STRING +int main(int argc, char **argv) { + StringBuf s; + s.size = 0; + int i; + + for(i = 1; i + +#include "TestSuite.h" +#include "test-libmongoc.h" +#include "mongoc-tests.h" + +static char *gTestUri; + + +static void +test_has_collection (void) +{ + mongoc_collection_t *collection; + mongoc_database_t *database; + mongoc_client_t *client; + bson_error_t error; + char *name; + bool r; + bson_oid_t oid; + bson_t b; + + client = mongoc_client_new (gTestUri); + assert (client); + + name = gen_collection_name ("has_collection"); + collection = mongoc_client_get_collection (client, "test", name); + assert (collection); + + database = mongoc_client_get_database (client, "test"); + assert (database); + + bson_init (&b); + bson_oid_init (&oid, NULL); + bson_append_oid (&b, "_id", 3, &oid); + bson_append_utf8 (&b, "hello", 5, "world", 5); + r = mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &b, NULL, + &error); + if (!r) { + MONGOC_WARNING ("%s\n", error.message); + } + assert (r); + bson_destroy (&b); + + r = mongoc_database_has_collection (database, name, &error); + assert (!error.domain); + assert (r); + + bson_free (name); + mongoc_database_destroy (database); + mongoc_collection_destroy (collection); + mongoc_client_destroy (client); +} + + +static void +test_command (void) +{ + mongoc_database_t *database; + mongoc_client_t *client; + mongoc_cursor_t *cursor; + bson_error_t error; + const bson_t *doc; + bool r; + bson_t cmd = BSON_INITIALIZER; + bson_t reply; + + client = mongoc_client_new (gTestUri); + assert (client); + + database = mongoc_client_get_database (client, "admin"); + + /* + * Test a known working command, "ping". + */ + bson_append_int32 (&cmd, "ping", 4, 1); + + cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL); + assert (cursor); + + r = mongoc_cursor_next (cursor, &doc); + assert (r); + assert (doc); + + r = mongoc_cursor_next (cursor, &doc); + assert (!r); + assert (!doc); + + mongoc_cursor_destroy (cursor); + + + /* + * Test a non-existing command to ensure we get the failure. + */ + bson_reinit (&cmd); + bson_append_int32 (&cmd, "a_non_existing_command", -1, 1); + + r = mongoc_database_command_simple (database, &cmd, NULL, &reply, &error); + assert (!r); + assert (error.domain == MONGOC_ERROR_QUERY); + assert (error.code == MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND); + assert (!strcmp ("no such cmd: a_non_existing_command", error.message)); + + mongoc_database_destroy (database); + mongoc_client_destroy (client); + bson_destroy (&cmd); +} + + +static void +test_drop (void) +{ + mongoc_database_t *database; + mongoc_client_t *client; + bson_error_t error = { 0 }; + char *dbname; + bool r; + + client = mongoc_client_new (gTestUri); + assert (client); + + dbname = gen_collection_name ("db_drop_test"); + database = mongoc_client_get_database (client, dbname); + bson_free (dbname); + + r = mongoc_database_drop (database, &error); + assert (r); + assert (!error.domain); + assert (!error.code); + + mongoc_database_destroy (database); + mongoc_client_destroy (client); +} + + +static void +test_create_collection (void) +{ + mongoc_database_t *database; + mongoc_collection_t *collection; + mongoc_client_t *client; + bson_error_t error = { 0 }; + bson_t options; + char *dbname; + char *name; + bool r; + + client = mongoc_client_new (gTestUri); + assert (client); + + dbname = gen_collection_name ("dbtest"); + database = mongoc_client_get_database (client, dbname); + assert (database); + bson_free (dbname); + + bson_init (&options); + BSON_APPEND_INT32 (&options, "size", 1234); + BSON_APPEND_INT32 (&options, "max", 4567); + BSON_APPEND_BOOL (&options, "capped", true); + BSON_APPEND_BOOL (&options, "autoIndexId", true); + + name = gen_collection_name ("create_collection"); + collection = mongoc_database_create_collection (database, name, &options, &error); + assert (collection); + bson_free (name); + + r = mongoc_collection_drop (collection, &error); + assert (r); + + r = mongoc_database_drop (database, &error); + assert (r); + + mongoc_collection_destroy (collection); + mongoc_database_destroy (database); + mongoc_client_destroy (client); +} + + +static void +cleanup_globals (void) +{ + bson_free (gTestUri); +} + + +void +test_database_install (TestSuite *suite) +{ + gTestUri = bson_strdup_printf ("mongodb://%s/", MONGOC_TEST_HOST); + + TestSuite_Add (suite, "/Database/has_collection", test_has_collection); + TestSuite_Add (suite, "/Database/command", test_command); + TestSuite_Add (suite, "/Database/drop", test_drop); + TestSuite_Add (suite, "/Database/create_collection", test_create_collection); + + atexit (cleanup_globals); +} diff --git a/pool/shard006/C/0119755_platform_pcal9555a.c b/pool/shard006/C/0119755_platform_pcal9555a.c new file mode 100644 index 0000000000000000000000000000000000000000..6625edc7285deb71090ba6bec19644fb334df8ca --- /dev/null +++ b/pool/shard006/C/0119755_platform_pcal9555a.c @@ -0,0 +1,68 @@ +/* + * platform_pcal9555a.c: pcal9555a platform data initilization file + * + * (C) Copyright 2014 Intel Corporation + * Author: Dan O'Donovan + * + * 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; version 2 + * of the License. + */ + +#include +#include +#include +#include +#include +#include "platform_pcal9555a.h" + + +void __init *pcal9555a_platform_data(void *info) +{ + static struct pca953x_platform_data pcal9555a_pdata[PCAL9555A_NUM]; + static int nr; + struct pca953x_platform_data *pcal9555a; + struct i2c_board_info *i2c_info = info; + int gpio_base, intr; + char base_pin_name[SFI_NAME_LEN + 1]; + char intr_pin_name[SFI_NAME_LEN + 1]; + + if (!info) { + pr_err("%s: invalid info pointer\n", __func__); + return NULL; + } + + if (nr >= PCAL9555A_NUM) { + pr_err("%s: too many pcal9555a, we only support %d\n", + __func__, PCAL9555A_NUM); + return NULL; + } + pcal9555a = &pcal9555a_pdata[nr++]; + + /* we have several pcal9555a on the board, we only need load several + * instances of the same pca953x driver to cover them + */ + + snprintf(base_pin_name, sizeof(base_pin_name), + "%s_base", i2c_info->type); + snprintf(intr_pin_name, sizeof(intr_pin_name), + "%s_int", i2c_info->type); + + strcpy(i2c_info->type, "pcal9555a"); + + gpio_base = get_gpio_by_name(base_pin_name); + intr = get_gpio_by_name(intr_pin_name); + + if (gpio_base == -1) + return NULL; + pcal9555a->gpio_base = gpio_base; + if (intr != -1) { + i2c_info->irq = intr + INTEL_MID_IRQ_OFFSET; + pcal9555a->irq_base = gpio_base + INTEL_MID_IRQ_OFFSET; + } else { + i2c_info->irq = -1; + pcal9555a->irq_base = -1; + } + return pcal9555a; +} diff --git a/pool/shard006/C/0119758_pthread_once.c b/pool/shard006/C/0119758_pthread_once.c new file mode 100644 index 0000000000000000000000000000000000000000..86b062804e71e453ec3456264900b6a0e89f8f4e --- /dev/null +++ b/pool/shard006/C/0119758_pthread_once.c @@ -0,0 +1,97 @@ +/* Copyright (C) 2003, 2004, 2007 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. */ + +#include "pthreadP.h" +#include + + +unsigned long int __fork_generation attribute_hidden; + +static void +clear_once_control (void *arg) +{ + pthread_once_t *once_control = (pthread_once_t *) arg; + + *once_control = 0; + lll_futex_wake (once_control, INT_MAX, LLL_PRIVATE); +} + +int +attribute_protected +__pthread_once (pthread_once_t *once_control, void (*init_routine) (void)) +{ + for (;;) + { + int oldval; + int newval; + int tmp; + + /* Pseudo code: + newval = __fork_generation | 1; + oldval = *once_control; + if ((oldval & 2) == 0) + *once_control = newval; + Do this atomically. + */ + newval = __fork_generation | 1; + __asm__ __volatile__ ( + "1: ldl_l %0, %2\n" + " and %0, 2, %1\n" + " bne %1, 2f\n" + " mov %3, %1\n" + " stl_c %1, %2\n" + " beq %1, 1b\n" + "2: mb" + : "=&r" (oldval), "=&r" (tmp), "=m" (*once_control) + : "r" (newval), "m" (*once_control)); + + /* Check if the initializer has already been done. */ + if ((oldval & 2) != 0) + return 0; + + /* Check if another thread already runs the initializer. */ + if ((oldval & 1) == 0) + break; + + /* Check whether the initializer execution was interrupted by a fork. */ + if (oldval != newval) + break; + + /* Same generation, some other thread was faster. Wait. */ + lll_futex_wait (once_control, oldval, LLL_PRIVATE); + } + + /* This thread is the first here. Do the initialization. + Register a cleanup handler so that in case the thread gets + interrupted the initialization can be restarted. */ + pthread_cleanup_push (clear_once_control, once_control); + + init_routine (); + + pthread_cleanup_pop (0); + + /* Add one to *once_control to take the bottom 2 bits from 01 to 10. */ + atomic_increment (once_control); + + /* Wake up all other threads. */ + lll_futex_wake (once_control, INT_MAX, LLL_PRIVATE); + + return 0; +} +weak_alias (__pthread_once, pthread_once) +strong_alias (__pthread_once, __pthread_once_internal) diff --git a/pool/shard006/C/0119761_fu-cros-ec-firmware.c b/pool/shard006/C/0119761_fu-cros-ec-firmware.c new file mode 100644 index 0000000000000000000000000000000000000000..39283286361e9ca9c77f862169e3a203697997e0 --- /dev/null +++ b/pool/shard006/C/0119761_fu-cros-ec-firmware.c @@ -0,0 +1,190 @@ +/* + * Copyright (C) 2020 Benson Leung + * + * SPDX-License-Identifier: LGPL-2.1+ + */ + +#include "config.h" + +#include + +#include "fu-cros-ec-common.h" +#include "fu-cros-ec-firmware.h" + +#define MAXSECTIONS 2 + +struct _FuCrosEcFirmware { + FuFmapFirmware parent_instance; + struct cros_ec_version version; + GPtrArray *sections; +}; + +G_DEFINE_TYPE(FuCrosEcFirmware, fu_cros_ec_firmware, FU_TYPE_FMAP_FIRMWARE) + +gboolean +fu_cros_ec_firmware_pick_sections(FuCrosEcFirmware *self, guint32 writeable_offset, GError **error) +{ + gboolean found = FALSE; + + for (gsize i = 0; i < self->sections->len; i++) { + FuCrosEcFirmwareSection *section = g_ptr_array_index(self->sections, i); + guint32 offset = section->offset; + + if (offset != writeable_offset) + continue; + + section->ustatus = FU_CROS_EC_FW_NEEDED; + found = TRUE; + } + + if (!found) { + g_set_error(error, + G_IO_ERROR, + G_IO_ERROR_INVALID_DATA, + "no writeable section found with offset: 0x%x", + writeable_offset); + return FALSE; + } + + /* success */ + return TRUE; +} + +GPtrArray * +fu_cros_ec_firmware_get_sections(FuCrosEcFirmware *self) +{ + return self->sections; +} + +static gboolean +fu_cros_ec_firmware_parse(FuFirmware *firmware, + GBytes *fw, + guint64 addr_start, + guint64 addr_end, + FwupdInstallFlags flags, + GError **error) +{ + FuCrosEcFirmware *self = FU_CROS_EC_FIRMWARE(firmware); + FuFirmware *fmap_firmware = FU_FIRMWARE(firmware); + + for (gsize i = 0; i < self->sections->len; i++) { + gboolean rw = FALSE; + FuCrosEcFirmwareSection *section = g_ptr_array_index(self->sections, i); + const gchar *fmap_name; + const gchar *fmap_fwid_name; + g_autoptr(FuFirmware) img = NULL; + g_autoptr(FuFirmware) fwid_img = NULL; + g_autoptr(GBytes) payload_bytes = NULL; + g_autoptr(GBytes) fwid_bytes = NULL; + + if (g_strcmp0(section->name, "RO") == 0) { + fmap_name = "EC_RO"; + fmap_fwid_name = "RO_FRID"; + } else if (g_strcmp0(section->name, "RW") == 0) { + rw = TRUE; + fmap_name = "EC_RW"; + fmap_fwid_name = "RW_FWID"; + } else { + g_set_error_literal(error, + G_IO_ERROR, + G_IO_ERROR_INVALID_DATA, + "incorrect section name"); + return FALSE; + } + + img = fu_firmware_get_image_by_id(fmap_firmware, fmap_name, error); + if (img == NULL) { + g_prefix_error(error, "%s image not found: ", fmap_name); + return FALSE; + } + + fwid_img = fu_firmware_get_image_by_id(fmap_firmware, fmap_fwid_name, error); + if (fwid_img == NULL) { + g_prefix_error(error, "%s image not found: ", fmap_fwid_name); + return FALSE; + } + fwid_bytes = fu_firmware_write(fwid_img, error); + if (fwid_bytes == NULL) { + g_prefix_error(error, "unable to get bytes from %s: ", fmap_fwid_name); + return FALSE; + } + if (!fu_memcpy_safe((guint8 *)section->raw_version, + FU_FMAP_FIRMWARE_STRLEN, + 0x0, + g_bytes_get_data(fwid_bytes, NULL), + g_bytes_get_size(fwid_bytes), + 0x0, + g_bytes_get_size(fwid_bytes), + error)) + return FALSE; + + payload_bytes = fu_firmware_write(img, error); + if (payload_bytes == NULL) { + g_prefix_error(error, "unable to get bytes from %s: ", fmap_name); + return FALSE; + } + section->offset = fu_firmware_get_addr(img); + section->size = g_bytes_get_size(payload_bytes); + fu_firmware_set_version(img, section->raw_version); + section->image_idx = fu_firmware_get_idx(img); + + if (!fu_cros_ec_parse_version(section->raw_version, §ion->version, error)) { + g_prefix_error(error, + "failed parsing firmware's version: %32s: ", + section->raw_version); + return FALSE; + } + + if (rw) { + if (!fu_cros_ec_parse_version(section->raw_version, + &self->version, + error)) { + g_prefix_error(error, + "failed parsing firmware's version: %32s: ", + section->raw_version); + return FALSE; + } + fu_firmware_set_version(firmware, self->version.triplet); + } + } + + /* success */ + return TRUE; +} + +static void +fu_cros_ec_firmware_init(FuCrosEcFirmware *self) +{ + FuCrosEcFirmwareSection *section; + + self->sections = g_ptr_array_new_with_free_func(g_free); + section = g_new0(FuCrosEcFirmwareSection, 1); + section->name = "RO"; + g_ptr_array_add(self->sections, section); + section = g_new0(FuCrosEcFirmwareSection, 1); + section->name = "RW"; + g_ptr_array_add(self->sections, section); +} + +static void +fu_cros_ec_firmware_finalize(GObject *object) +{ + FuCrosEcFirmware *self = FU_CROS_EC_FIRMWARE(object); + g_ptr_array_free(self->sections, TRUE); + G_OBJECT_CLASS(fu_cros_ec_firmware_parent_class)->finalize(object); +} + +static void +fu_cros_ec_firmware_class_init(FuCrosEcFirmwareClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS(klass); + FuFmapFirmwareClass *klass_firmware = FU_FMAP_FIRMWARE_CLASS(klass); + klass_firmware->parse = fu_cros_ec_firmware_parse; + object_class->finalize = fu_cros_ec_firmware_finalize; +} + +FuFirmware * +fu_cros_ec_firmware_new(void) +{ + return g_object_new(FU_TYPE_CROS_EC_FIRMWARE, NULL); +} diff --git a/pool/shard006/C/0119762_osal.c b/pool/shard006/C/0119762_osal.c new file mode 100644 index 0000000000000000000000000000000000000000..2c500f4b6cc63c9158c52ef48174ee34bc083e8b --- /dev/null +++ b/pool/shard006/C/0119762_osal.c @@ -0,0 +1,114 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio + + 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. +*/ + +/** + * @file osal.c + * @brief OSAL module code. + * + * @addtogroup OSAL + * @{ + */ + +#include "osal.h" + +/*===========================================================================*/ +/* Module local definitions. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module exported variables. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module local types. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module local variables. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module local functions. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Module exported functions. */ +/*===========================================================================*/ + +/** + * @brief Dequeues and wakes up one thread from the queue, if any. + * + * @param[in] tqp pointer to the threads queue object + * @param[in] msg the message code + * + * @iclass + */ +void osalThreadDequeueNextI(threads_queue_t *tqp, msg_t msg) { + semaphore_t *sp = &tqp->sem; + + if (chSemGetCounterI(&tqp->sem) < (cnt_t)0) { + thread_reference_t tr = nil.threads; + while (true) { + /* Is this thread waiting on this semaphore?*/ + if (tr->u1.semp == sp) { + sp->cnt++; + + chDbgAssert(NIL_THD_IS_WTSEM(tr), "not waiting"); + + (void) chSchReadyI(tr, msg); + return; + } + tr++; + + chDbgAssert(tr < &nil.threads[NIL_CFG_NUM_THREADS], + "pointer out of range"); + } + } +} + +/** + * @brief Dequeues and wakes up all threads from the queue. + * + * @param[in] tqp pointer to the threads queue object + * @param[in] msg the message code + * + * @iclass + */ +void osalThreadDequeueAllI(threads_queue_t *tqp, msg_t msg) { + semaphore_t *sp = &tqp->sem; + thread_reference_t tr; + cnt_t cnt; + + cnt = sp->cnt; + sp->cnt = (cnt_t)0; + tr = nil.threads; + while (cnt < (cnt_t)0) { + /* Is this thread waiting on this semaphore?*/ + if (tr->u1.semp == sp) { + + chDbgAssert(NIL_THD_IS_WTSEM(tr), "not waiting"); + + cnt++; + (void) chSchReadyI(tr, msg); + } + tr++; + + chDbgAssert(tr < &nil.threads[NIL_CFG_NUM_THREADS], + "pointer out of range"); + } +} + +/** @} */ diff --git a/pool/shard006/C/0119766_max8998_charger.c b/pool/shard006/C/0119766_max8998_charger.c new file mode 100644 index 0000000000000000000000000000000000000000..c5d5158fbc08770ef8bffec383fe75a4c9f60f13 --- /dev/null +++ b/pool/shard006/C/0119766_max8998_charger.c @@ -0,0 +1,211 @@ +/* + * max8998_charger.c - Power supply consumer driver for the Maxim 8998/LP3974 + * + * Copyright (C) 2009-2010 Samsung Electronics + * MyungJoo Ham + * + * 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 +#include +#include +#include +#include +#include +#include + +struct max8998_battery_data { + struct device *dev; + struct max8998_dev *iodev; + struct power_supply battery; +}; + +static enum power_supply_property max8998_battery_props[] = { + POWER_SUPPLY_PROP_PRESENT, /* the presence of battery */ + POWER_SUPPLY_PROP_ONLINE, /* charger is active or not */ +}; + +/* Note that the charger control is done by a current regulator "CHARGER" */ +static int max8998_battery_get_property(struct power_supply *psy, + enum power_supply_property psp, + union power_supply_propval *val) +{ + struct max8998_battery_data *max8998 = container_of(psy, + struct max8998_battery_data, battery); + struct i2c_client *i2c = max8998->iodev->i2c; + int ret; + u8 reg; + + switch (psp) { + case POWER_SUPPLY_PROP_PRESENT: + ret = max8998_read_reg(i2c, MAX8998_REG_STATUS2, ®); + if (ret) + return ret; + if (reg & (1 << 4)) + val->intval = 0; + else + val->intval = 1; + break; + case POWER_SUPPLY_PROP_ONLINE: + ret = max8998_read_reg(i2c, MAX8998_REG_STATUS2, ®); + if (ret) + return ret; + if (reg & (1 << 3)) + val->intval = 0; + else + val->intval = 1; + break; + default: + return -EINVAL; + } + + return 0; +} + +static __devinit int max8998_battery_probe(struct platform_device *pdev) +{ + struct max8998_dev *iodev = dev_get_drvdata(pdev->dev.parent); + struct max8998_platform_data *pdata = dev_get_platdata(iodev->dev); + struct max8998_battery_data *max8998; + struct i2c_client *i2c; + int ret = 0; + + if (!pdata) { + dev_err(pdev->dev.parent, "No platform init data supplied\n"); + return -ENODEV; + } + + max8998 = kzalloc(sizeof(struct max8998_battery_data), GFP_KERNEL); + if (!max8998) + return -ENOMEM; + + max8998->dev = &pdev->dev; + max8998->iodev = iodev; + platform_set_drvdata(pdev, max8998); + i2c = max8998->iodev->i2c; + + /* Setup "End of Charge" */ + /* If EOC value equals 0, + * remain value set from bootloader or default value */ + if (pdata->eoc >= 10 && pdata->eoc <= 45) { + max8998_update_reg(i2c, MAX8998_REG_CHGR1, + (pdata->eoc / 5 - 2) << 5, 0x7 << 5); + } else if (pdata->eoc == 0) { + dev_dbg(max8998->dev, + "EOC value not set: leave it unchanged.\n"); + } else { + dev_err(max8998->dev, "Invalid EOC value\n"); + ret = -EINVAL; + goto err; + } + + /* Setup Charge Restart Level */ + switch (pdata->restart) { + case 100: + max8998_update_reg(i2c, MAX8998_REG_CHGR1, 0x1 << 3, 0x3 << 3); + break; + case 150: + max8998_update_reg(i2c, MAX8998_REG_CHGR1, 0x0 << 3, 0x3 << 3); + break; + case 200: + max8998_update_reg(i2c, MAX8998_REG_CHGR1, 0x2 << 3, 0x3 << 3); + break; + case -1: + max8998_update_reg(i2c, MAX8998_REG_CHGR1, 0x3 << 3, 0x3 << 3); + break; + case 0: + dev_dbg(max8998->dev, + "Restart Level not set: leave it unchanged.\n"); + break; + default: + dev_err(max8998->dev, "Invalid Restart Level\n"); + ret = -EINVAL; + goto err; + } + + /* Setup Charge Full Timeout */ + switch (pdata->timeout) { + case 5: + max8998_update_reg(i2c, MAX8998_REG_CHGR2, 0x0 << 4, 0x3 << 4); + break; + case 6: + max8998_update_reg(i2c, MAX8998_REG_CHGR2, 0x1 << 4, 0x3 << 4); + break; + case 7: + max8998_update_reg(i2c, MAX8998_REG_CHGR2, 0x2 << 4, 0x3 << 4); + break; + case -1: + max8998_update_reg(i2c, MAX8998_REG_CHGR2, 0x3 << 4, 0x3 << 4); + break; + case 0: + dev_dbg(max8998->dev, + "Full Timeout not set: leave it unchanged.\n"); + break; + default: + dev_err(max8998->dev, "Invalid Full Timeout value\n"); + ret = -EINVAL; + goto err; + } + + max8998->battery.name = "max8998_pmic"; + max8998->battery.type = POWER_SUPPLY_TYPE_BATTERY; + max8998->battery.get_property = max8998_battery_get_property; + max8998->battery.properties = max8998_battery_props; + max8998->battery.num_properties = ARRAY_SIZE(max8998_battery_props); + + ret = power_supply_register(max8998->dev, &max8998->battery); + if (ret) { + dev_err(max8998->dev, "failed: power supply register\n"); + goto err; + } + + return 0; +err: + kfree(max8998); + return ret; +} + +static int __devexit max8998_battery_remove(struct platform_device *pdev) +{ + struct max8998_battery_data *max8998 = platform_get_drvdata(pdev); + + power_supply_unregister(&max8998->battery); + kfree(max8998); + + return 0; +} + +static const struct platform_device_id max8998_battery_id[] = { + { "max8998-battery", TYPE_MAX8998 }, + { } +}; + +static struct platform_driver max8998_battery_driver = { + .driver = { + .name = "max8998-battery", + .owner = THIS_MODULE, + }, + .probe = max8998_battery_probe, + .remove = __devexit_p(max8998_battery_remove), + .id_table = max8998_battery_id, +}; + +module_platform_driver(max8998_battery_driver); + +MODULE_DESCRIPTION("MAXIM 8998 battery control driver"); +MODULE_AUTHOR("MyungJoo Ham "); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:max8998-battery"); diff --git a/pool/shard006/C/0119769_LoaderLibrary.c b/pool/shard006/C/0119769_LoaderLibrary.c new file mode 100644 index 0000000000000000000000000000000000000000..531e0bae3ffbaa6115c80aa1f5972f5ecd4922c4 --- /dev/null +++ b/pool/shard006/C/0119769_LoaderLibrary.c @@ -0,0 +1,300 @@ +/****************************************************************\ +* * +* Copyright (C) 2007 by Markus Duft * +* * +* This file is part of parity. * +* * +* parity 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 3 of * +* the License, or (at your option) any later version. * +* * +* parity 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 parity. If not, * +* see . * +* * +\****************************************************************/ + +#include "LoaderLibrary.h" +#include "LoaderInit.h" +#include "LoaderLog.h" +#include "LoaderHelper.h" + +#include + +#define LOADER_MAX_ERRORS 64 +#define LOADER_PATHFIELD_LEN 50 + +typedef struct { + const char* path; +} LoaderPathCacheNode; + +typedef struct { + const char* path; + unsigned long error; +} LoaderErrorList; + +static LoaderPathCacheNode* gPathCache = 0; + +static unsigned int gPathCacheCount = 0; + +static void* LibLoad(const char* name, unsigned int strict) +{ + HMODULE handle = 0; + unsigned int i; + LoaderErrorList lst[LOADER_MAX_ERRORS+1]; + unsigned int longest = 0; + + if(!name) { + if (!GetModuleHandleEx(0, NULL, &handle) && LogGetLevel() > LevelWarning) { + unsigned long lastError = GetLastError(); + char* tmp = LoaderFormatErrorMessage(lastError); + LogDebug("error %d querying main module handle (%s)\n", lastError, tmp); + LocalFree(tmp); + SetLastError(lastError); + } + return handle; + } + + for(i = 0; i < gPathCacheCount; ++i) + { + char * ptrTry = HeapAlloc(GetProcessHeap(), 0, lstrlen(name) + lstrlen(gPathCache[i].path) + 2); + + lstrcpyn(ptrTry, gPathCache[i].path, lstrlen(gPathCache[i].path) + 1); + ptrTry[lstrlen(gPathCache[i].path)] = '\\'; + lstrcpyn(&ptrTry[lstrlen(gPathCache[i].path)+1], name, lstrlen(name) + 1); + + handle = LoadLibrary(ptrTry); + + if(!handle && LogGetLevel() > LevelWarning) { + unsigned long lastError = GetLastError(); + char* tmp = LoaderFormatErrorMessage(lastError); + LogDebug("error %d loading '%s' (%s)\n", lastError, ptrTry, tmp); + LocalFree(tmp); + } else + if(!handle && i < LOADER_MAX_ERRORS) { + register int len; + + lst[i].error = GetLastError(); + lst[i].path = gPathCache[i].path; + + len = strlen(lst[i].path); + if(len > longest) + longest = len; + } + + HeapFree(GetProcessHeap(), 0, ptrTry); + + if(handle) { + LogDebug("loaded %s through path cache.\n", name); + return handle; + } + } + + // + // try default lookup + // + handle = LoadLibrary(name); + + if(!handle && LogGetLevel() > LevelWarning) { + unsigned long lastError = GetLastError(); + char* tmp = LoaderFormatErrorMessage(lastError); + LogDebug("error %d loading '%s' (%s)\n", lastError, name, tmp); + LocalFree(tmp); + } else + if(!handle && i < LOADER_MAX_ERRORS) { + lst[i].error = GetLastError(); + lst[i].path = name; + } + + if(handle) + { + LogDebug("loaded %s through windows default lookup or absolute name\n", name); + return handle; + } + + if(strict && LogGetLevel() <= LevelWarning) { + unsigned int y = 0; + char spaces[MAX_PATH]; + + FillMemory(spaces, sizeof(spaces), ' '); + + LogWarning("failed to load %s from following paths (%d in cache):\n", name, gPathCacheCount); + + lst[LOADER_MAX_ERRORS].error = ERROR_MORE_DATA; + lst[LOADER_MAX_ERRORS].path = "..."; + + for(y = 0; y <= i && y <= LOADER_MAX_ERRORS; ++y) { + char* tmp = LoaderFormatErrorMessage(lst[y].error); + register int index = longest - strlen(lst[y].path); + + spaces[index] = 0; + + LogWarning(" * [%s%d] %s%s (%s)\n", + ( lst[y].error < 10000 ? ( lst[y].error < 1000 ? ( lst[y].error < 100 ? ( lst[y].error < 10 ? " " : " " ) : " ") : " ") : ""), + lst[y].error, lst[y].path, spaces, tmp); + + spaces[index] = ' '; + + LocalFree(tmp); + } + } + + return 0; +} + +static const char* LibStrChr(const char* ptr, char c) +{ + while(*ptr != '\0' && *ptr != c) ++ptr; + + if(*ptr == c) + return ptr; + + return 0; +} + +static void LibCreatePathCache() +{ + unsigned int szLdLib = 0; + const char* ptrRPath = ParityLoaderGetGeneratedRunPath(); + + // + // first lookup from LD_LIBRARY_PATH! + // this has the effect, that LD_LIBRARY_PATH + // is searched before the runpaths. (for libtool: + // shlibpath_overrides_runpath = yes!). This saves + // us from relinking all the time. + // + szLdLib = GetEnvironmentVariable("LD_LIBRARY_PATH", 0, 0); + + if(szLdLib > 1) + { + char* ptrLdLib = HeapAlloc(GetProcessHeap(), 0, szLdLib); + char* start = 0; + char* end = 0; + + if(!GetEnvironmentVariable("LD_LIBRARY_PATH", ptrLdLib, szLdLib)) + { + LogWarning("cannot get environment variable LD_LIBRARY_PATH!\n"); + } else { + char pSep = ':'; + start = ptrLdLib; + end = ptrLdLib; + + if(LibStrChr(ptrLdLib, ';') || LibStrChr(ptrLdLib, '\\')) + pSep = ';'; + + LogDebug("adding LD_LIBRARY_PATH to path cache (sep: %c)\n", pSep); + + while(end && *end != '\0') + { + int isSep = 0; + + while(*end != pSep && *end != '\0') + ++end; + + if(*end == pSep) { + *end = '\0'; + isSep = 1; + ++end; + } + + if(gPathCache == 0) + gPathCache = HeapAlloc(GetProcessHeap(), 0, sizeof(LoaderPathCacheNode)); + else + gPathCache = HeapReAlloc(GetProcessHeap(), 0, gPathCache, sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + + if(!gPathCache) + { + LogWarning("cannot allocate %d bytes for the path cache, this will break library loading!\n", sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + LoaderWriteLastWindowsError(); + gPathCacheCount = 0; + } else { + // + // buffer2 is never freed, this is intentionally! + // + const char * buffer1 = LoaderConvertPathToNative(start); + char * buffer2 = HeapAlloc(GetProcessHeap(), 0, sizeof(char) * (lstrlen(buffer1) + 1)); + lstrcpy(buffer2, buffer1); + gPathCache[gPathCacheCount].path = buffer2; + + LogDebug(" * %s\n", gPathCache[gPathCacheCount].path); + + ++gPathCacheCount; + } + + if(!isSep) + break; + + start = end; + } + } + } + + // + // second lookup runpaths, pointers can be stored directly. + // + LogDebug("adding runpaths to path cache\n"); + + while(ptrRPath && *ptrRPath != '\0') + { + if(gPathCache == 0) + gPathCache = HeapAlloc(GetProcessHeap(), 0, sizeof(LoaderPathCacheNode)); + else + gPathCache = HeapReAlloc(GetProcessHeap(), 0, gPathCache, sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + + if(!gPathCache) + { + LogWarning("cannot allocate %d bytes for the path cache, this will break library loading!\n", sizeof(LoaderPathCacheNode) * (gPathCacheCount + 1)); + LoaderWriteLastWindowsError(); + gPathCacheCount = 0; + } else { + gPathCache[gPathCacheCount].path = ptrRPath; + ++gPathCacheCount; + + LogDebug(" * %s\n", ptrRPath); + } + + while(*ptrRPath != '\0') + ++ptrRPath; + + ++ptrRPath; + } +} + +void* LoaderLibraryGetHandle(const char* name, int strict) +{ + void* handle = 0; + unsigned int errormode = 0; + + if(gPathCache == 0) + LibCreatePathCache(); + + errormode = SetErrorMode(SEM_FAILCRITICALERRORS); + SetErrorMode(errormode | SEM_FAILCRITICALERRORS); + + handle = LibLoad(name, strict); + + SetErrorMode(errormode); + + if(handle) { + return handle; + } else if(strict) { + /* + * Don't issue a warning here, since LibLoad does this already. + */ + ExitProcess(1); + } + + return 0; +} + +int LoaderLibraryReleaseHandle(void *handle) +{ + return FreeLibrary(handle); +} diff --git a/pool/shard006/C/0119772_obio.c b/pool/shard006/C/0119772_obio.c new file mode 100644 index 0000000000000000000000000000000000000000..e69fc42e86797412e4193bd3eb421b981359afe5 --- /dev/null +++ b/pool/shard006/C/0119772_obio.c @@ -0,0 +1,183 @@ +/* $NetBSD: obio.c,v 1.11 2003/07/15 00:25:05 lukem Exp $ */ + +/*- + * Copyright (c) 2001, 2002, 2003 Wasabi Systems, Inc. + * All rights reserved. + * + * Written by Jason R. Thorpe for Wasabi Systems, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed for the NetBSD Project by + * Wasabi Systems, Inc. + * 4. The name of Wasabi Systems, Inc. may not be used to endorse + * or promote products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``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 WASABI SYSTEMS, INC + * 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. + */ + +/* + * On-board device autoconfiguration support for Broadcom Sentry5 + * based boards. + * XXX This is totally bogus and is just enough to get the console hopefully + * running on the sentry5. + */ + +#include +__FBSDID("$FreeBSD: release/9.1.0/sys/mips/sentry5/obio.c 202175 2010-01-12 21:36:08Z imp $"); + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +int obio_probe(device_t); +int obio_attach(device_t); + +/* + * A bit tricky and hackish. Since we need OBIO to rely + * on PCI we make it pseudo-pci device. But there should + * be only one such device, so we use this static flag + * to prevent false positives on every realPCI device probe. + */ +static int have_one = 0; + +int +obio_probe(device_t dev) +{ + if (!have_one) { + have_one = 1; + return 0; + } + return (ENXIO); +} + +int +obio_attach(device_t dev) +{ + struct obio_softc *sc = device_get_softc(dev); + + sc->oba_st = MIPS_BUS_SPACE_IO; + sc->oba_addr = MIPS_PHYS_TO_KSEG1(SENTRY5_UART1ADR); + sc->oba_size = 0x03FFFFFF; /* XXX sb pci bus 0 aperture size? */ + sc->oba_rman.rm_type = RMAN_ARRAY; + sc->oba_rman.rm_descr = "OBIO I/O"; + if (rman_init(&sc->oba_rman) != 0 || + rman_manage_region(&sc->oba_rman, + sc->oba_addr, sc->oba_addr + sc->oba_size) != 0) + panic("obio_attach: failed to set up I/O rman"); + sc->oba_irq_rman.rm_type = RMAN_ARRAY; + sc->oba_irq_rman.rm_descr = "OBIO IRQ"; + + /* + * This module is intended for UART purposes only and + * it's IRQ is 4 + */ + if (rman_init(&sc->oba_irq_rman) != 0 || + rman_manage_region(&sc->oba_irq_rman, 4, 4) != 0) + panic("obio_attach: failed to set up IRQ rman"); + + device_add_child(dev, "uart", 0); + bus_generic_probe(dev); + bus_generic_attach(dev); + + return (0); +} + +static struct resource * +obio_alloc_resource(device_t bus, device_t child, int type, int *rid, + u_long start, u_long end, u_long count, u_int flags) +{ + struct resource *rv; + struct rman *rm; + bus_space_handle_t bh = 0; + struct obio_softc *sc = device_get_softc(bus); + + switch (type) { + case SYS_RES_IRQ: + rm = &sc->oba_irq_rman; + break; + case SYS_RES_MEMORY: + return (NULL); + case SYS_RES_IOPORT: + rm = &sc->oba_rman; + bh = sc->oba_addr; + start = bh; + break; + default: + return (NULL); + } + + + rv = rman_reserve_resource(rm, start, end, count, flags, child); + if (rv == NULL) + return (NULL); + if (type == SYS_RES_IRQ) + return (rv); + rman_set_rid(rv, *rid); + rman_set_bustag(rv, mips_bus_space_generic); + rman_set_bushandle(rv, bh); + + if (0) { + if (bus_activate_resource(child, type, *rid, rv)) { + rman_release_resource(rv); + return (NULL); + } + } + return (rv); + +} + +static int +obio_activate_resource(device_t bus, device_t child, int type, int rid, + struct resource *r) +{ + return (0); +} +static device_method_t obio_methods[] = { + DEVMETHOD(device_probe, obio_probe), + DEVMETHOD(device_attach, obio_attach), + + DEVMETHOD(bus_alloc_resource, obio_alloc_resource), + DEVMETHOD(bus_activate_resource, obio_activate_resource), + DEVMETHOD(bus_setup_intr, bus_generic_setup_intr), + DEVMETHOD(bus_teardown_intr, bus_generic_teardown_intr), + + {0, 0}, +}; + +static driver_t obio_driver = { + "obio", + obio_methods, + sizeof(struct obio_softc), +}; +static devclass_t obio_devclass; + +DRIVER_MODULE(obio, pci, obio_driver, obio_devclass, 0, 0); diff --git a/pool/shard006/C/0119778_interrupt.c b/pool/shard006/C/0119778_interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..dc86fe5466f3a6dfbf4f7198d6152894cf2e5b8b --- /dev/null +++ b/pool/shard006/C/0119778_interrupt.c @@ -0,0 +1,148 @@ +/* + * File : interrupt.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006, RT-Thread Development Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Change Logs: + * Date Author Notes + */ + +#include +#include "gk7101.h" + +#define MAX_HANDLERS (64) + +extern rt_uint32_t rt_interrupt_nest; + +/* exception and interrupt handler table */ +struct rt_irq_desc irq_desc[MAX_HANDLERS]; + +rt_uint32_t rt_interrupt_from_thread, rt_interrupt_to_thread; +rt_uint32_t rt_thread_switch_interrupt_flag; + + +/* -------------------------------------------------------------------- + * Interrupt initialization + * -------------------------------------------------------------------- */ + + + +void rt_hw_interrupt_mask(int irq); +void rt_hw_interrupt_umask(int irq); + +rt_isr_handler_t rt_hw_interrupt_handle(rt_uint32_t vector, void *param) +{ + rt_kprintf("Unhandled interrupt %d occured!!!\n", vector); + return RT_NULL; +} + + + +/** + * This function will initialize hardware interrupt + */ +void rt_hw_interrupt_init(void) +{ + //rt_int32_t i; + //register rt_uint32_t idx; + + + /* init interrupt nest, and context in thread sp */ + rt_interrupt_nest = 0; + rt_interrupt_from_thread = 0; + rt_interrupt_to_thread = 0; + rt_thread_switch_interrupt_flag = 0; +} + + +/** + * This function will mask a interrupt. + * @param vector the interrupt number + */ +void rt_hw_interrupt_mask(int irq) +{ + +} + + +/** + * This function will un-mask a interrupt. + * @param vector the interrupt number + */ +void rt_hw_interrupt_umask(int irq) +{ + +} + +/** + * This function will install a interrupt service routine to a interrupt. + * @param vector the interrupt number + * @param handler the interrupt service routine to be installed + * @param param the interrupt service function parameter + * @param name the interrupt name + * @return old handler + */ +rt_isr_handler_t rt_hw_interrupt_install(int vector, rt_isr_handler_t handler, + void *param, char *name) +{ + rt_isr_handler_t old_handler = RT_NULL; + + if(vector < MAX_HANDLERS) + { + old_handler = irq_desc[vector].handler; + if (handler != RT_NULL) + { + +#ifdef RT_USING_INTERRUPT_INFO + rt_snprintf(irq_desc[vector].name, RT_NAME_MAX - 1, "%s", name); + irq_desc[vector].counter = 0; +#endif + irq_desc[vector].handler = (rt_isr_handler_t)handler; + irq_desc[vector].param = param; + } + } + + return old_handler; +} + +/*@}*/ + + + +#ifdef RT_USING_FINSH +void list_irq(void) +{ + int irq; + +#ifdef RT_USING_INTERRUPT_INFO + rt_kprintf("number\tcount\tname\n"); + for (irq = 0; irq < MAX_HANDLERS; irq++) + { + if (rt_strncmp(irq_desc[irq].name, "default", sizeof("default"))) + { + rt_kprintf("%02ld: %10ld %s\n", irq, irq_desc[irq].counter, irq_desc[irq].name); + } + } +#endif +} + +#include +FINSH_FUNCTION_EXPORT(list_irq, list system irq); + +#endif + + diff --git a/pool/shard006/C/0119780_aquarius.c b/pool/shard006/C/0119780_aquarius.c new file mode 100644 index 0000000000000000000000000000000000000000..7c9e5c6e29f55dbaf22c2cee0b63091b41913e6c --- /dev/null +++ b/pool/shard006/C/0119780_aquarius.c @@ -0,0 +1,255 @@ +/* + * Mattel Aquarius + * This tool creates a BASIC loader file + * and a binary file stored in "variable array" format + * + * The machine code starts at 14712. + * The original Mattel loader (now commented out) permitted + * little changes in the BASIC loader, but we don't need it. + * + * Stefano Bodrato - December 2001: first release + * + * $Id: aquarius.c,v 1.2 2009/06/13 19:16:42 dom Exp $ + */ + +#include "appmake.h" + +static char *binname = NULL; +static char *outfile = NULL; +static char help = 0; + + +/* Options that are available for this module */ +option_t aquarius_options[] = { + { 'h', "help", "Display this help", OPT_BOOL, &help}, + { 'b', "binfile", "Linked binary file", OPT_STR, &binname }, + { 'o', "output", "Name of output file", OPT_STR, &outfile }, + { 0, NULL, NULL, OPT_NONE, NULL } +}; + + + + +int aquarius_exec(char *target) +{ + char filename[FILENAME_MAX+1]; + char ldr_name[FILENAME_MAX+1]; + char mybuf[20]; + FILE *fpin, *fpout; + int c; + int i; + int len; + int dlen; + + strcpy(ldr_name,"_"); + + + if ( help || binname == NULL ) + return -1; + + if ( outfile == NULL ) { + strcpy(filename,binname); + suffix_change(filename,".caq"); + } else { + strcpy(filename,outfile); + } + + + if ( (fpin=fopen(binname,"rb") ) == NULL ) { + printf("Can't open input file\n"); + exit(1); + } + + +/* + * Now we try to determine the size of the file + * to be converted + */ + + if (fseek(fpin,0,SEEK_END)) { + printf("Couldn't determine size of file\n"); + fclose(fpin); + exit(1); + } + + len=ftell(fpin); + dlen=(len)/4; + + fseek(fpin,0L,SEEK_SET); + +/****************/ +/* BASIC loader */ +/****************/ + + strcat(ldr_name,filename); + + if ( (fpout=fopen(ldr_name,"wb") ) == NULL ) { + printf("Can't create the loader file\n"); + exit(1); + } + +/* Write out the header */ + for (i=1;i<=12;i++) + writebyte(255,fpout); + writebyte(0,fpout); + writestring("LOADR",fpout); + writebyte(0,fpout); + for (i=1;i<=12;i++) + writebyte(255,fpout); + + writebyte(0,fpout); + writeword(14601,fpout); /* points to line 10 */ + + writeword(5,fpout); /* 5 U=0 */ + writebyte('U',fpout); + writebyte(0xB0,fpout); + writebyte('0',fpout); + + writebyte(0,fpout); + writeword(14609,fpout); /* points to line 20 */ + + writeword(10,fpout); /* 10 X=0 */ + writebyte('X',fpout); + writebyte(0xB0,fpout); + writebyte('0',fpout); + + writebyte(0,fpout); + writeword(14621+2,fpout); /* points to line 30 */ + + writeword(20,fpout); /* 20 DIMA(xxxxx) */ + writebyte(0x85,fpout); + writebyte('A',fpout); + writebyte('(',fpout); + sprintf(mybuf,"%i",dlen); + for (i=1;i<=(5-strlen(mybuf));i++) + writebyte('0',fpout); + writestring(mybuf,fpout); + writebyte(')',fpout); + + writebyte(0,fpout); + writeword(14629+2,fpout); /* points to line 40 */ + + writeword(30,fpout); /* 30 CLOAD*A */ + writebyte(0x9A,fpout); + writebyte(0xAA,fpout); + writebyte('A',fpout); + + writebyte(0,fpout); + writeword(14651+2,fpout); /* points to line 50 */ + + writeword(40,fpout); /* 40 POKE14340,PEEK(14552)+7 */ + writebyte(0x94,fpout); + writestring("14340,",fpout); + writebyte(0xC1,fpout); + writestring("(14552)",fpout); + writebyte(0xA8,fpout); + writebyte('7',fpout); + + writebyte(0,fpout); + writeword(14671+2,fpout); /* points to line 60 */ + + writeword(50,fpout); /* 50 POKE14341,PEEK(14553) */ + writebyte(0x94,fpout); + writestring("14341,",fpout); + writebyte(0xC1,fpout); + writestring("(14553)",fpout); + + writebyte(0,fpout); + writeword(14682+2,fpout); /* points to end of program */ + + writeword(60,fpout); /* 60 X=USR(0) */ + writebyte('X',fpout); + writebyte(0xB0,fpout); + writebyte(0xB5,fpout); + writestring("(0)",fpout); + + for (i=1;i<=25;i++) + writebyte(0,fpout); + + fclose(fpout); + + +/*********************/ +/* Binary array file */ +/*********************/ + +/* Write out the header */ + + if ( (fpout=fopen(filename,"wb") ) == NULL ) { + printf("Can't create the data file\n"); + exit(1); + } + + +/* Write out the header */ + for (i=1;i<=12;i++) + writebyte(255,fpout); + + writebyte(0,fpout); + + +/* Write out the "file name" */ + for (i=1;i<=6;i++) + writebyte('#',fpout); + +/* for (i=1;i<=6;i++) + writebyte(0,fpout);*/ + + +/* Mattel games loader relocator */ +/* + writebyte(0x2A,fpout); // ld hl,(14552) + writeword(14552,fpout); + writebyte(0x23,fpout); // inc hl + writebyte(0x23,fpout); // inc hl + writebyte(0x4e,fpout); // ld c,(hl) + writebyte(0x23,fpout); // inc hl + writebyte(0x46,fpout); // ld b,(hl) + writebyte(0x11,fpout); // le de,67 + writeword(67,fpout); + writebyte(0x19,fpout); // add hl,de + writebyte(0xe5,fpout); // push hl + writebyte(0xc5,fpout); // push bc + writebyte(0xe1,fpout); // pop hl + writebyte(0xb7,fpout); // or a + writebyte(0xed,fpout); // sbc hl,de + writebyte(0x52,fpout); + writebyte(0xe5,fpout); // push hl + writebyte(0xc1,fpout); // pop bc + writebyte(0xe1,fpout); // pop hl + writebyte(0x23,fpout); // inc hl + writebyte(0x7e,fpout); // ld a,(hl) + writebyte(0xb7,fpout); // or a + writebyte(0x28,fpout); // jr z,-4 + writebyte(0xfb,fpout); + writebyte(0x11,fpout); // ld de,14768 + writeword(14768,fpout); + writebyte(0xed,fpout); // ldir + writebyte(0xb0,fpout); + + for (i=1;i<=41;i++) + writebyte(0,fpout); +*/ + + +/* We append the binary file */ + + for (i=0; i +#include +#include "sysinit/sysinit.h" +#include "syscfg/syscfg.h" +#include "host/ble_hs.h" +#include "services/tps/ble_svc_tps.h" + +/* XXX: We shouldn't be including the host's private header files. The host + * API needs to be updated with a function to query the advertising transmit + * power. + */ +#include "../src/ble_hs_hci_priv.h" + +int8_t ble_svc_tps_tx_power_level; + +/* Access function */ +static int +ble_svc_tps_access(uint16_t conn_handle, uint16_t attr_handle, + struct ble_gatt_access_ctxt *ctxt, void *arg); + +static const struct ble_gatt_svc_def ble_svc_tps_defs[] = { + { + /*** Service: Tx Power Service. */ + .type = BLE_GATT_SVC_TYPE_PRIMARY, + .uuid = BLE_UUID16_DECLARE(BLE_SVC_TPS_UUID16), + .characteristics = (struct ble_gatt_chr_def[]) { { + /*** Characteristic: Tx Power Level. */ + .uuid = BLE_UUID16_DECLARE(BLE_SVC_TPS_CHR_UUID16_TX_POWER_LEVEL), + .access_cb = ble_svc_tps_access, + .flags = BLE_GATT_CHR_F_READ, + }, { + 0, /* No more characteristics in this service. */ + } }, + }, + + { + 0, /* No more services. */ + }, +}; + +/** + * Simple read access callback for the tx power level + * characteristic. + */ +static int +ble_svc_tps_access(uint16_t conn_handle, uint16_t attr_handle, + struct ble_gatt_access_ctxt *ctxt, void *arg) +{ + int rc; + + assert(ctxt->chr == &ble_svc_tps_defs[0].characteristics[0]); + + switch (ctxt->op) { + case BLE_GATT_ACCESS_OP_READ_CHR: + rc = ble_hs_hci_util_read_adv_tx_pwr(&ble_svc_tps_tx_power_level); + if (rc != 0) { + return BLE_ATT_ERR_UNLIKELY; + } + + rc = os_mbuf_append(ctxt->om, &ble_svc_tps_tx_power_level, + sizeof ble_svc_tps_tx_power_level); + return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES; + + default: + assert(0); + return BLE_ATT_ERR_UNLIKELY; + } + + return 0; +} + +/** + * Initialize the TPS + */ +void +ble_svc_tps_init(void) +{ + int rc; + + /* Ensure this function only gets called by sysinit. */ + SYSINIT_ASSERT_ACTIVE(); + + rc = ble_gatts_count_cfg(ble_svc_tps_defs); + SYSINIT_PANIC_ASSERT(rc == 0); + + rc = ble_gatts_add_svcs(ble_svc_tps_defs); + SYSINIT_PANIC_ASSERT(rc == 0); +} diff --git a/pool/shard006/C/0119783_srn4.c b/pool/shard006/C/0119783_srn4.c new file mode 100644 index 0000000000000000000000000000000000000000..cef03ef2c04324e65fd66a3b91ac6d0e346ca4e6 --- /dev/null +++ b/pool/shard006/C/0119783_srn4.c @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2008, 2010, 2012 Free Software Foundation, Inc. + * + * Author: Simon Josefsson + * + * This file is part of GnuTLS. + * + * GnuTLS 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. + * + * GnuTLS 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 GnuTLS; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +/* Code based on srn0.c. + * + * This tests that clients without support for safe renegotiation is + * able to handshake properly against a default GnuTLS server, but + * that rehandshake will be refused by the server. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include "../eagain-common.h" +#include "../utils.h" + +const char *side = ""; + +static void tls_log_func(int level, const char *str) +{ + fprintf(stderr, "%s|<%d>| %s", side, level, str); +} + +static unsigned char server_cert_pem[] = + "-----BEGIN CERTIFICATE-----\n" + "MIICVjCCAcGgAwIBAgIERiYdMTALBgkqhkiG9w0BAQUwGTEXMBUGA1UEAxMOR251\n" + "VExTIHRlc3QgQ0EwHhcNMDcwNDE4MTMyOTIxWhcNMDgwNDE3MTMyOTIxWjA3MRsw\n" + "GQYDVQQKExJHbnVUTFMgdGVzdCBzZXJ2ZXIxGDAWBgNVBAMTD3Rlc3QuZ251dGxz\n" + "Lm9yZzCBnDALBgkqhkiG9w0BAQEDgYwAMIGIAoGA17pcr6MM8C6pJ1aqU46o63+B\n" + "dUxrmL5K6rce+EvDasTaDQC46kwTHzYWk95y78akXrJutsoKiFV1kJbtple8DDt2\n" + "DZcevensf9Op7PuFZKBroEjOd35znDET/z3IrqVgbtm2jFqab7a+n2q9p/CgMyf1\n" + "tx2S5Zacc1LWn9bIjrECAwEAAaOBkzCBkDAMBgNVHRMBAf8EAjAAMBoGA1UdEQQT\n" + "MBGCD3Rlc3QuZ251dGxzLm9yZzATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHQ8B\n" + "Af8EBQMDB6AAMB0GA1UdDgQWBBTrx0Vu5fglyoyNgw106YbU3VW0dTAfBgNVHSME\n" + "GDAWgBTpPBz7rZJu5gakViyi4cBTJ8jylTALBgkqhkiG9w0BAQUDgYEAaFEPTt+7\n" + "bzvBuOf7+QmeQcn29kT6Bsyh1RHJXf8KTk5QRfwp6ogbp94JQWcNQ/S7YDFHglD1\n" + "AwUNBRXwd3riUsMnsxgeSDxYBfJYbDLeohNBsqaPDJb7XailWbMQKfAbFQ8cnOxg\n" + "rOKLUQRWJ0K3HyXRMhbqjdLIaQiCvQLuizo=\n" "-----END CERTIFICATE-----\n"; + +const gnutls_datum_t server_cert = { server_cert_pem, + sizeof(server_cert_pem) +}; + +static unsigned char server_key_pem[] = + "-----BEGIN RSA PRIVATE KEY-----\n" + "MIICXAIBAAKBgQDXulyvowzwLqknVqpTjqjrf4F1TGuYvkrqtx74S8NqxNoNALjq\n" + "TBMfNhaT3nLvxqResm62ygqIVXWQlu2mV7wMO3YNlx696ex/06ns+4VkoGugSM53\n" + "fnOcMRP/PciupWBu2baMWppvtr6far2n8KAzJ/W3HZLllpxzUtaf1siOsQIDAQAB\n" + "AoGAYAFyKkAYC/PYF8e7+X+tsVCHXppp8AoP8TEZuUqOZz/AArVlle/ROrypg5kl\n" + "8YunrvUdzH9R/KZ7saNZlAPLjZyFG9beL/am6Ai7q7Ma5HMqjGU8kTEGwD7K+lbG\n" + "iomokKMOl+kkbY/2sI5Czmbm+/PqLXOjtVc5RAsdbgvtmvkCQQDdV5QuU8jap8Hs\n" + "Eodv/tLJ2z4+SKCV2k/7FXSKWe0vlrq0cl2qZfoTUYRnKRBcWxc9o92DxK44wgPi\n" + "oMQS+O7fAkEA+YG+K9e60sj1K4NYbMPAbYILbZxORDecvP8lcphvwkOVUqbmxOGh\n" + "XRmTZUuhBrJhJKKf6u7gf3KWlPl6ShKEbwJASC118cF6nurTjuLf7YKARDjNTEws\n" + "qZEeQbdWYINAmCMj0RH2P0mvybrsXSOD5UoDAyO7aWuqkHGcCLv6FGG+qwJAOVqq\n" + "tXdUucl6GjOKKw5geIvRRrQMhb/m5scb+5iw8A4LEEHPgGiBaF5NtJZLALgWfo5n\n" + "hmC8+G8F0F78znQtPwJBANexu+Tg5KfOnzSILJMo3oXiXhf5PqXIDmbN0BKyCKAQ\n" + "LfkcEcUbVfmDaHpvzwY9VEaoMOKVLitETXdNSxVpvWM=\n" + "-----END RSA PRIVATE KEY-----\n"; + +const gnutls_datum_t server_key = { server_key_pem, + sizeof(server_key_pem) +}; + +void doit(void) +{ + /* Server stuff. */ + gnutls_certificate_credentials_t serverx509cred; + gnutls_session_t server; + int sret = GNUTLS_E_AGAIN; + /* Client stuff. */ + gnutls_certificate_credentials_t clientx509cred; + gnutls_session_t client; + int cret = GNUTLS_E_AGAIN; + + /* General init. */ + global_init(); + gnutls_global_set_log_function(tls_log_func); + if (debug) + gnutls_global_set_log_level(2); + + /* Init server */ + gnutls_certificate_allocate_credentials(&serverx509cred); + gnutls_certificate_set_x509_key_mem(serverx509cred, + &server_cert, &server_key, + GNUTLS_X509_FMT_PEM); + gnutls_init(&server, GNUTLS_SERVER); + gnutls_credentials_set(server, GNUTLS_CRD_CERTIFICATE, + serverx509cred); + gnutls_priority_set_direct(server, "NORMAL", NULL); + gnutls_transport_set_push_function(server, server_push); + gnutls_transport_set_pull_function(server, server_pull); + gnutls_transport_set_ptr(server, server); + + /* Init client */ + gnutls_certificate_allocate_credentials(&clientx509cred); + gnutls_init(&client, GNUTLS_CLIENT); + gnutls_credentials_set(client, GNUTLS_CRD_CERTIFICATE, + clientx509cred); + gnutls_priority_set_direct(client, + "NORMAL:%DISABLE_SAFE_RENEGOTIATION", + NULL); + gnutls_transport_set_push_function(client, client_push); + gnutls_transport_set_pull_function(client, client_pull); + gnutls_transport_set_ptr(client, client); + + HANDSHAKE(client, server); + + if (gnutls_safe_renegotiation_status(client) || + gnutls_safe_renegotiation_status(server)) { + tls_log_func(0, + "Session using safe renegotiation but shouldn't!\n"); + exit(1); + } + + sret = gnutls_rehandshake(server); + if (debug) { + tls_log_func(0, "gnutls_rehandshake (server)...\n"); + tls_log_func(0, gnutls_strerror(sret)); + tls_log_func(0, "\n"); + } + + { + ssize_t n; + char b[1]; + n = gnutls_record_recv(client, b, 1); + if (n != GNUTLS_E_REHANDSHAKE) + abort(); + } + + HANDSHAKE_EXPECT(client, server, GNUTLS_E_AGAIN, + GNUTLS_E_UNSAFE_RENEGOTIATION_DENIED); + + if (gnutls_safe_renegotiation_status(client) || + gnutls_safe_renegotiation_status(server)) { + tls_log_func(0, + "Rehandshaked session not using safe renegotiation!\n"); + exit(1); + } + + gnutls_bye(client, GNUTLS_SHUT_RDWR); + gnutls_bye(server, GNUTLS_SHUT_RDWR); + + gnutls_deinit(client); + gnutls_deinit(server); + + gnutls_certificate_free_credentials(serverx509cred); + gnutls_certificate_free_credentials(clientx509cred); + + gnutls_global_deinit(); + + if (debug) { + puts("Self-test successful"); + } + + return; +} diff --git a/pool/shard006/C/0119791_ali14xx.c b/pool/shard006/C/0119791_ali14xx.c new file mode 100644 index 0000000000000000000000000000000000000000..4c7d07930a5152157bd49df13ac4805df9330d0b --- /dev/null +++ b/pool/shard006/C/0119791_ali14xx.c @@ -0,0 +1,249 @@ +/* + * Copyright (C) 1996 Linus Torvalds & author (see below) + */ + +/* + * ALI M14xx chipset EIDE controller + * + * Works for ALI M1439/1443/1445/1487/1489 chipsets. + * + * Adapted from code developed by derekn@vw.ece.cmu.edu. -ml + * Derek's notes follow: + * + * I think the code should be pretty understandable, + * but I'll be happy to (try to) answer questions. + * + * The critical part is in the setupDrive function. The initRegisters + * function doesn't seem to be necessary, but the DOS driver does it, so + * I threw it in. + * + * I've only tested this on my system, which only has one disk. I posted + * it to comp.sys.linux.hardware, so maybe some other people will try it + * out. + * + * Derek Noonburg (derekn@ece.cmu.edu) + * 95-sep-26 + * + * Update 96-jul-13: + * + * I've since upgraded to two disks and a CD-ROM, with no trouble, and + * I've also heard from several others who have used it successfully. + * This driver appears to work with both the 1443/1445 and the 1487/1489 + * chipsets. I've added support for PIO mode 4 for the 1487. This + * seems to work just fine on the 1443 also, although I'm not sure it's + * advertised as supporting mode 4. (I've been running a WDC AC21200 in + * mode 4 for a while now with no trouble.) -Derek + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define DRV_NAME "ali14xx" + +/* port addresses for auto-detection */ +#define ALI_NUM_PORTS 4 +static const int ports[ALI_NUM_PORTS] __initdata = + { 0x074, 0x0f4, 0x034, 0x0e4 }; + +/* register initialization data */ +typedef struct { u8 reg, data; } RegInitializer; + +static const RegInitializer initData[] __initdata = { + {0x01, 0x0f}, {0x02, 0x00}, {0x03, 0x00}, {0x04, 0x00}, + {0x05, 0x00}, {0x06, 0x00}, {0x07, 0x2b}, {0x0a, 0x0f}, + {0x25, 0x00}, {0x26, 0x00}, {0x27, 0x00}, {0x28, 0x00}, + {0x29, 0x00}, {0x2a, 0x00}, {0x2f, 0x00}, {0x2b, 0x00}, + {0x2c, 0x00}, {0x2d, 0x00}, {0x2e, 0x00}, {0x30, 0x00}, + {0x31, 0x00}, {0x32, 0x00}, {0x33, 0x00}, {0x34, 0xff}, + {0x35, 0x03}, {0x00, 0x00} +}; + +/* timing parameter registers for each drive */ +static struct { u8 reg1, reg2, reg3, reg4; } regTab[4] = { + {0x03, 0x26, 0x04, 0x27}, /* drive 0 */ + {0x05, 0x28, 0x06, 0x29}, /* drive 1 */ + {0x2b, 0x30, 0x2c, 0x31}, /* drive 2 */ + {0x2d, 0x32, 0x2e, 0x33}, /* drive 3 */ +}; + +static int basePort; /* base port address */ +static int regPort; /* port for register number */ +static int dataPort; /* port for register data */ +static u8 regOn; /* output to base port to access registers */ +static u8 regOff; /* output to base port to close registers */ + +/*------------------------------------------------------------------------*/ + +/* + * Read a controller register. + */ +static inline u8 inReg(u8 reg) +{ + outb_p(reg, regPort); + return inb(dataPort); +} + +/* + * Write a controller register. + */ +static void outReg(u8 data, u8 reg) +{ + outb_p(reg, regPort); + outb_p(data, dataPort); +} + +static DEFINE_SPINLOCK(ali14xx_lock); + +/* + * Set PIO mode for the specified drive. + * This function computes timing parameters + * and sets controller registers accordingly. + */ +static void ali14xx_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive) +{ + int driveNum; + int time1, time2; + u8 param1, param2, param3, param4; + unsigned long flags; + int bus_speed = ide_vlb_clk ? ide_vlb_clk : 50; + const u8 pio = drive->pio_mode - XFER_PIO_0; + struct ide_timing *t = ide_timing_find_mode(XFER_PIO_0 + pio); + + /* calculate timing, according to PIO mode */ + time1 = ide_pio_cycle_time(drive, pio); + time2 = t->active; + param3 = param1 = (time2 * bus_speed + 999) / 1000; + param4 = param2 = (time1 * bus_speed + 999) / 1000 - param1; + if (pio < 3) { + param3 += 8; + param4 += 8; + } + printk(KERN_DEBUG "%s: PIO mode%d, t1=%dns, t2=%dns, cycles = %d+%d, %d+%d\n", + drive->name, pio, time1, time2, param1, param2, param3, param4); + + /* stuff timing parameters into controller registers */ + driveNum = (drive->hwif->index << 1) + (drive->dn & 1); + spin_lock_irqsave(&ali14xx_lock, flags); + outb_p(regOn, basePort); + outReg(param1, regTab[driveNum].reg1); + outReg(param2, regTab[driveNum].reg2); + outReg(param3, regTab[driveNum].reg3); + outReg(param4, regTab[driveNum].reg4); + outb_p(regOff, basePort); + spin_unlock_irqrestore(&ali14xx_lock, flags); +} + +/* + * Auto-detect the IDE controller port. + */ +static int __init findPort(void) +{ + int i; + u8 t; + unsigned long flags; + + local_irq_save(flags); + for (i = 0; i < ALI_NUM_PORTS; ++i) { + basePort = ports[i]; + regOff = inb(basePort); + for (regOn = 0x30; regOn <= 0x33; ++regOn) { + outb_p(regOn, basePort); + if (inb(basePort) == regOn) { + regPort = basePort + 4; + dataPort = basePort + 8; + t = inReg(0) & 0xf0; + outb_p(regOff, basePort); + local_irq_restore(flags); + if (t != 0x50) + return 0; + return 1; /* success */ + } + } + outb_p(regOff, basePort); + } + local_irq_restore(flags); + return 0; +} + +/* + * Initialize controller registers with default values. + */ +static int __init initRegisters(void) +{ + const RegInitializer *p; + u8 t; + unsigned long flags; + + local_irq_save(flags); + outb_p(regOn, basePort); + for (p = initData; p->reg != 0; ++p) + outReg(p->data, p->reg); + outb_p(0x01, regPort); + t = inb(regPort) & 0x01; + outb_p(regOff, basePort); + local_irq_restore(flags); + return t; +} + +static const struct ide_port_ops ali14xx_port_ops = { + .set_pio_mode = ali14xx_set_pio_mode, +}; + +static const struct ide_port_info ali14xx_port_info = { + .name = DRV_NAME, + .chipset = ide_ali14xx, + .port_ops = &ali14xx_port_ops, + .host_flags = IDE_HFLAG_NO_DMA, + .pio_mask = ATA_PIO4, +}; + +static int __init ali14xx_probe(void) +{ + printk(KERN_DEBUG "ali14xx: base=0x%03x, regOn=0x%02x.\n", + basePort, regOn); + + /* initialize controller registers */ + if (!initRegisters()) { + printk(KERN_ERR "ali14xx: Chip initialization failed.\n"); + return 1; + } + + return ide_legacy_device_add(&ali14xx_port_info, 0); +} + +static int probe_ali14xx; + +module_param_named(probe, probe_ali14xx, bool, 0); +MODULE_PARM_DESC(probe, "probe for ALI M14xx chipsets"); + +static int __init ali14xx_init(void) +{ + if (probe_ali14xx == 0) + goto out; + + /* auto-detect IDE controller port */ + if (findPort()) { + if (ali14xx_probe()) + return -ENODEV; + return 0; + } + printk(KERN_ERR "ali14xx: not found.\n"); +out: + return -ENODEV; +} + +module_init(ali14xx_init); + +MODULE_AUTHOR("see local file"); +MODULE_DESCRIPTION("support of ALI 14XX IDE chipsets"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0119792_oldtmpfile.c b/pool/shard006/C/0119792_oldtmpfile.c new file mode 100644 index 0000000000000000000000000000000000000000..631e339472c1422b68cc51f5fecfbda63808f8a3 --- /dev/null +++ b/pool/shard006/C/0119792_oldtmpfile.c @@ -0,0 +1,55 @@ +/* Copyright (C) 1991-2017 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, see + . */ + +#include +#if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_1) + +#define _IO_USE_OLD_IO_FILE +#include +#include +#include + +/* This returns a new stream opened on a temporary file (generated + by tmpnam). The file is opened with mode "w+b" (binary read/write). + If we couldn't generate a unique filename or the file couldn't + be opened, NULL is returned. */ +FILE * +attribute_compat_text_section +__old_tmpfile (void) +{ + char buf[FILENAME_MAX]; + int fd; + FILE *f; + + if (__path_search (buf, FILENAME_MAX, NULL, "tmpf", 0)) + return NULL; + fd = __gen_tempname (buf, 0, 0, __GT_FILE); + if (fd < 0) + return NULL; + + /* Note that this relies on the Unix semantics that + a file is not really removed until it is closed. */ + (void) __unlink (buf); + + if ((f = _IO_old_fdopen (fd, "w+b")) == NULL) + __close (fd); + + return f; +} + +compat_symbol (libc, __old_tmpfile, tmpfile, GLIBC_2_0); +#endif diff --git a/pool/shard006/C/0119793_fbtest_04.c b/pool/shard006/C/0119793_fbtest_04.c new file mode 100644 index 0000000000000000000000000000000000000000..7b30cfdfbc72038adb5673cd2e0f1394cb6e6eac --- /dev/null +++ b/pool/shard006/C/0119793_fbtest_04.c @@ -0,0 +1,111 @@ +/* + * fbtest4.c + * + * http://raspberrycompote.blogspot.ie/2013/03/low-level-graphics-on-raspberry-pi-part.html + * + * Original work by J-P Rosti (a.k.a -rst- and 'Raspberry Compote') + * + * Licensed under the Creative Commons Attribution 3.0 Unported License + * (http://creativecommons.org/licenses/by/3.0/deed.en_US) + * + * Distributed in the hope that this will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* 'global' variables to store screen info */ +char *fbp = 0; +struct fb_var_screeninfo vinfo; +struct fb_fix_screeninfo finfo; + +/* helper function to 'plot' a pixel in given color */ +void put_pixel(int x, int y, int c) { + /* calculate the pixel's byte offset inside the buffer */ + unsigned int pix_offset = x + y * finfo.line_length; + + /* now this is about the same as 'fbp[pix_offset] = value' */ + *((char *)(fbp + pix_offset)) = c; +} + +/* helper function for drawing - no more need to go mess with + the main function when just want to change what to draw... */ +void draw() { + unsigned int x, y; + + for (y = 0; y < (vinfo.yres / 2); y++) { + for (x = 0; x < vinfo.xres; x++) { + + /* color based on the 16th of the screen width */ + int c = 16 * x / vinfo.xres; + + /* call the helper function */ + put_pixel(x, y, c); + } + } +} + +/* application entry point */ +int main(void) { + int fbfd = 0; + struct fb_var_screeninfo orig_vinfo; + long int screensize = 0; + + /* Open the file for reading and writing */ + fbfd = open("/dev/fb0", O_RDWR); + if (!fbfd) { + printf("Error: cannot open framebuffer device.\n"); + exit(EXIT_FAILURE); + } + printf("The framebuffer device was opened successfully.\n"); + + /* Get variable screen information */ + if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo)) + printf("Error reading variable information.\n"); + + printf("Original %dx%d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel); + + /* Store for reset (copy vinfo to vinfo_orig) */ + memcpy(&orig_vinfo, &vinfo, sizeof(struct fb_var_screeninfo)); + + /* Change variable info */ + vinfo.bits_per_pixel = 8; + if (ioctl(fbfd, FBIOPUT_VSCREENINFO, &vinfo)) + printf("Error setting variable information.\n"); + + /* Get fixed screen information */ + if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo)) + printf("Error reading fixed information.\n"); + + /* map fb to user mem */ + screensize = vinfo.xres * vinfo.yres; + fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0); + + if ((void *)fbp == MAP_FAILED) { + printf("Failed to mmap.\n"); + exit(EXIT_FAILURE); + } else { + /* draw... */ + draw(); + sleep(5); + } + + /* cleanup */ + munmap(fbp, screensize); + if (ioctl(fbfd, FBIOPUT_VSCREENINFO, &orig_vinfo)) { + printf("Error re-setting variable information.\n"); + exit(EXIT_FAILURE); + } + close(fbfd); + + return 0; +} diff --git a/pool/shard006/C/0119795_globals.c b/pool/shard006/C/0119795_globals.c new file mode 100644 index 0000000000000000000000000000000000000000..bf33fc091c268e05502c192daccb81126e76b451 --- /dev/null +++ b/pool/shard006/C/0119795_globals.c @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include + +#include "globals.h" + +void init_rng(long int seed, struct drand48_data *buffer) +{ + struct timeval now; + + gettimeofday(&now, NULL); + srand48_r(seed, buffer); +} + +int int_cmp(const void *a, const void *b) +{ + const int *ia = a, *ib = b; + return *ia - *ib; +} + +int int_cmp_r(const void *a, const void *b) +{ + const int *ia = a, *ib = b; + return *ib - *ia; +} + +int double_cmp(const void *a, const void *b) +{ + const double *fa = a, *fb = b; + + if (*fa < *fb) + return -1; + else if (*fa > *fb) + return 1; + return 0; +} + +int double_cmp_r(const void *a, const void *b) +{ + return -double_cmp(a, b); +} + +static double laplace(double lambda, struct drand48_data *buffer) +{ + double rnd; + + drand48_r(buffer, &rnd); /* rnd \in [0, 1) */ + rnd = 0.5 - rnd; /* rnd \in (-0.5, 0.5] */ + + if (signbit(rnd)) /* rnd < 0 */ + return lambda * log(1 + 2 * rnd); + return -lambda * log(1 - 2 * rnd); +} + +double laplace_mechanism(double x, double eps, double sens, + struct drand48_data *buffer) +{ + return x + laplace(sens/eps, buffer); +} + +int bsearch_i(const void *key, const void *base, size_t nmemb, size_t size, + int (*compar)(const void *, const void *)) +{ + int low = 0, high = nmemb - 1, mid, test; + + while (low <= high) { + mid = low + ((high - low) >> 1); + test = compar(base + mid * size, key); + if (test > 0) + high = mid - 1; + else + low = mid + 1; + } + + return low; +} + +double div_or_zero(double a, double b) +{ + double r = a / b; + if (r != r) return 0; /* nan */ + return r; +} diff --git a/pool/shard006/C/0119796_events.c b/pool/shard006/C/0119796_events.c new file mode 100644 index 0000000000000000000000000000000000000000..c73e4c0c090b3da7f6d989aee8ac771378f39c93 --- /dev/null +++ b/pool/shard006/C/0119796_events.c @@ -0,0 +1,219 @@ +#include +#include +#include "events.h" +#include "board.h" +#include "window.h" + + +void on_draw_event(GtkWidget *widget, cairo_t *dr, gpointer user_data) +{ +void renderBoard(cairo_t *); // Prototype of the function renderBoard + + renderBoard(dr); +} + + +/* On button Destroyer clicked: + + 1. Load image of destroyer and make it appear next to the pointer of the mouse + 2. Decrement counter*/ + + +void btn_destroyer_clicked(GtkWidget *widget, gpointer button) +{ + g_print("destroyer clicked\n"); + + selButton=0; + pix=gdk_pixbuf_new_from_file("/res/images/Destroyer_Top_Horizontal.png", &pixbuf_error); + + if(!pix) + { + g_print("%s\n", pixbuf_error->message); + g_error_free(pixbuf_error); + } + else surface=gdk_cairo_surface_create_from_pixbuf(pix, 0, gtk_widget_get_window(player_board)); +} + + +/* On button Submarine clicked: + + 1. Load image of submarine and make it appear next to the pointer of the mouse + 2. Decrement counter*/ + + +void btn_submarine_clicked(GtkWidget *widget, gpointer data) +{ + g_print("submarine clicked\n"); + + selButton=1; + pix=gdk_pixbuf_new_from_file("/res/images/Submarine_top_horizontal.png", &pixbuf_error); + + if(!pix) + { + g_print("%s\n", pixbuf_error->message); + g_error_free(pixbuf_error); + } + else surface=gdk_cairo_surface_create_from_pixbuf(pix, 0, gtk_widget_get_window(player_board)); + +} + + +/* On button Battleship clicked: + + 1. Load image of battleship and make it appear next to the pointer of the mouse + 2. Decrement counter*/ + + +void btn_battleship_clicked(GtkWidget *widget, gpointer data) +{ + g_print("battleship clicked\n"); + + selButton=2; + pix=gdk_pixbuf_new_from_file("/res/images/Battleship_top_horizontal.png", &pixbuf_error); + + if(!pix) + { + g_print("%s\n", pixbuf_error->message); + g_error_free(pixbuf_error); + } + else surface=gdk_cairo_surface_create_from_pixbuf(pix, 0, gtk_widget_get_window(player_board)); + +} + + +/* On button Cruiser clicked: + + 1. Load image of cruiser and make it appear next to the pointer of the mouse + 2. Decrement counter*/ + + +void btn_cruiser_clicked(GtkWidget *widget, gpointer data) +{ + g_print("cruiser clicked\n"); + + selButton=3; + pix=gdk_pixbuf_new_from_file("/res/images/cruiser_top_horizontal.png", &pixbuf_error); + + if(!pix) + { + g_print("%s\n", pixbuf_error->message); + g_error_free(pixbuf_error); + } + else surface=gdk_cairo_surface_create_from_pixbuf(pix, 0, gtk_widget_get_window(player_board)); + +} + + +/* On button Carrier clicked: + + 1. Load image of carrier and make it appear next to the pointer of the mouse + 2. Decrement counter*/ + + +void btn_carrier_clicked(GtkWidget *widget, gpointer data) +{ + g_print("carrier clicked\n"); + + selButton=4; + pix=gdk_pixbuf_new_from_file("/res/images/carrier_top_horizontal.png", &pixbuf_error); + + if(!pix) + { + g_print("%s\n", pixbuf_error->message); + g_error_free(pixbuf_error); + } + else surface=gdk_cairo_surface_create_from_pixbuf(pix, 0, gtk_widget_get_window(player_board)); + +} + +void btn_clear_clicked(GtkWidget *widget, gpointer data) +{ + g_print("clear clicked\n"); +} + + +/* if key pressed is equal to left mouse button key then: + +1. Get the coordinates of the pointer of the mouse +2. Place the img previously selected at the cell located at those coordinates on the player board when placing ships */ + + +void btn_mouse_pressed(GtkWidget *widget, GdkEventButton * event) +{ + +} + + +/* if key released is equal to right mouse button key then: + +1. rotate (switch from img horizontal to vertical and vice-versa) */ + + +void btn_mouse_released(GtkWidget *widget, GdkEventButton * event) +{ + if(event->button == 2) + { + switch(selButton) + { + case 0: pix=gdk_pixbuf_new_from_file("/res/images/Destroyer_Top_vertical.png", &pixbuf_error); + break; + case 1: pix=gdk_pixbuf_new_from_file("/res/images/Submarine_top_vertical.png", &pixbuf_error); + break; + case 2: pix=gdk_pixbuf_new_from_file("/res/images/Battleship_top_vertical.png", &pixbuf_error); + break; + case 3: pix=gdk_pixbuf_new_from_file("/res/images/cruiser_top_vertical.png", &pixbuf_error); + break; + case 4: pix=gdk_pixbuf_new_from_file("/res/images/carrier_top_vertical.png", &pixbuf_error); + break; + default: g_print("Invalid Button selected."); + } + + } + +} + +/* If user presses the key 'Enter' on the textfield then: + + 1. Get value from Textfield + 2. Parse string char by char + 3. If letter equals one of the letters in the the enum Letters then go to that row on enemy board + 4. If number equals one of the numbers in the enum Numbers then go to that column + 5. Get the cell located at those coordinates and place img target on that cell on enemy board */ + +void txtfield_action(GtkWidget *widget, GdkEventKey *event) +{ + +} + + +/* On redraw: +1. Redraw a region of the Drawing area, which is basically the area defined by Img. */ + +void redraw(cairo_t *er, gdouble x, gdouble y) +{ + er=cairo_create(surface); + + cairo_rectangle(er, x, y, cairo_image_surface_get_width(surface), cairo_image_surface_get_height(surface)); + cairo_paint(er); + cairo_fill(er); + cairo_destroy(er); +} + +/* On mouse moved within the PlayerBoard bounds: +1. Drag the selected image as mouse pointer moves within the Drawing Area +2. Queue a Redraw with the redraw method previously defined as the mouse pointer moves +3. In this method, the image should be redrawn on a layer on top of Drawing Area, not on Drawing Area itself. +4. After redrawing at the mouse pointer coordinates, as the mouse moves over the Drawing Area, the previous image should be removed */ + + +void mouse_moved(GtkWidget *widget, GdkEventMotion *event) +{ +void redraw(cairo_t *, gdouble, gdouble); // Prototype of the function redraw + + g_print("motion\n"); + //redraw(cr, event->x, event->y); + //gtk_widget_queue_draw_area (widget, event->x, event->y, cairo_image_surface_get_width(surface), cairo_image_surface_get_height(surface)); + +} + + diff --git a/pool/shard006/C/0119797_test-float.c b/pool/shard006/C/0119797_test-float.c new file mode 100644 index 0000000000000000000000000000000000000000..06cb7f651fc7eb90f02c3da43189919d59f55724 --- /dev/null +++ b/pool/shard006/C/0119797_test-float.c @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2013-2021 Canonical, Ltd. + * Copyright (C) 2022 Colin Ian King + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include + +#include "../stress-version.h" + +/* GCC hot attribute */ +#if defined(__GNUC__) && NEED_GNUC(4,6,0) +#define HOT __attribute__ ((hot)) +#else +#define HOT +#endif + +/* -O3 attribute support */ +#if defined(__GNUC__) && \ + !defined(__clang__) && \ + NEED_GNUC(4,6,0) +#define OPTIMIZE3 __attribute__((optimize("-O3"))) +#else +#define OPTIMIZE3 +#endif + +/* From stress-cpu.c */ +#define float_ops(_type, a, b, c, d, _sin, _cos) \ + do { \ + a = a + b; \ + b = a * c; \ + c = a - b; \ + d = a / b; \ + a = c / (_type)0.1923L; \ + b = c + a; \ + c = b * (_type)3.12L; \ + d = d + b + (_type)_sin(a); \ + a = (b + c) / c; \ + b = b * c; \ + c = c + (_type)1.0L; \ + d = d - (_type)_sin(c); \ + a = a * (_type)_cos(b); \ + b = b + (_type)_cos(c); \ + c = (_type)_sin(a + b) / (_type)2.344L; \ + b = d - (_type)1.0L; \ + } while (0) + +static FLOAT HOT OPTIMIZE3 test(void) +{ + FLOAT a = 0.0, b = 0.0, c = 0.0, d = 0.0; + + float_ops(FLOAT, a, b, c, d, sin, cos); + float_ops(FLOAT, a, b, c, d, sinl, cosl); + + return a + b + c + d; +} + +int main(void) +{ + return (int)test(); +} diff --git a/pool/shard006/C/0119798_lapacke_chegvx_work.c b/pool/shard006/C/0119798_lapacke_chegvx_work.c new file mode 100644 index 0000000000000000000000000000000000000000..22b9dd842906a1934637504e725cd74445d35553 --- /dev/null +++ b/pool/shard006/C/0119798_lapacke_chegvx_work.c @@ -0,0 +1,146 @@ +/***************************************************************************** + Copyright (c) 2010, 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: + + * 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. +****************************************************************************** +* Contents: Native middle-level C interface to LAPACK function chegvx +* Author: Intel Corporation +* Generated October, 2010 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_chegvx_work( int matrix_order, lapack_int itype, char jobz, + char range, char uplo, lapack_int n, + lapack_complex_float* a, lapack_int lda, + lapack_complex_float* b, lapack_int ldb, + float vl, float vu, lapack_int il, + lapack_int iu, float abstol, lapack_int* m, + float* w, lapack_complex_float* z, + lapack_int ldz, lapack_complex_float* work, + lapack_int lwork, float* rwork, + lapack_int* iwork, lapack_int* ifail ) +{ + lapack_int info = 0; + if( matrix_order == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_chegvx( &itype, &jobz, &range, &uplo, &n, a, &lda, b, &ldb, &vl, + &vu, &il, &iu, &abstol, m, w, z, &ldz, work, &lwork, + rwork, iwork, ifail, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_order == LAPACK_ROW_MAJOR ) { + lapack_int ncols_z = ( LAPACKE_lsame( range, 'a' ) || + LAPACKE_lsame( range, 'v' ) ) ? n : + ( LAPACKE_lsame( range, 'i' ) ? (iu-il+1) : 1); + lapack_int lda_t = MAX(1,n); + lapack_int ldb_t = MAX(1,n); + lapack_int ldz_t = MAX(1,n); + lapack_complex_float* a_t = NULL; + lapack_complex_float* b_t = NULL; + lapack_complex_float* z_t = NULL; + /* Check leading dimension(s) */ + if( lda < n ) { + info = -8; + LAPACKE_xerbla( "LAPACKE_chegvx_work", info ); + return info; + } + if( ldb < n ) { + info = -10; + LAPACKE_xerbla( "LAPACKE_chegvx_work", info ); + return info; + } + if( ldz < ncols_z ) { + info = -19; + LAPACKE_xerbla( "LAPACKE_chegvx_work", info ); + return info; + } + /* Query optimal working array(s) size if requested */ + if( lwork == -1 ) { + LAPACK_chegvx( &itype, &jobz, &range, &uplo, &n, a, &lda_t, b, + &ldb_t, &vl, &vu, &il, &iu, &abstol, m, w, z, &ldz_t, + work, &lwork, rwork, iwork, ifail, &info ); + return (info < 0) ? (info - 1) : info; + } + /* Allocate memory for temporary array(s) */ + a_t = (lapack_complex_float*) + LAPACKE_malloc( sizeof(lapack_complex_float) * lda_t * MAX(1,n) ); + if( a_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + b_t = (lapack_complex_float*) + LAPACKE_malloc( sizeof(lapack_complex_float) * ldb_t * MAX(1,n) ); + if( b_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_1; + } + if( LAPACKE_lsame( jobz, 'v' ) ) { + z_t = (lapack_complex_float*) + LAPACKE_malloc( sizeof(lapack_complex_float) * + ldz_t * MAX(1,ncols_z) ); + if( z_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_2; + } + } + /* Transpose input matrices */ + LAPACKE_che_trans( matrix_order, uplo, n, a, lda, a_t, lda_t ); + LAPACKE_cge_trans( matrix_order, n, n, b, ldb, b_t, ldb_t ); + /* Call LAPACK function and adjust info */ + LAPACK_chegvx( &itype, &jobz, &range, &uplo, &n, a_t, &lda_t, b_t, + &ldb_t, &vl, &vu, &il, &iu, &abstol, m, w, z_t, &ldz_t, + work, &lwork, rwork, iwork, ifail, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_che_trans( LAPACK_COL_MAJOR, uplo, n, a_t, lda_t, a, lda ); + LAPACKE_cge_trans( LAPACK_COL_MAJOR, n, n, b_t, ldb_t, b, ldb ); + if( LAPACKE_lsame( jobz, 'v' ) ) { + LAPACKE_cge_trans( LAPACK_COL_MAJOR, n, ncols_z, z_t, ldz_t, z, + ldz ); + } + /* Release memory and exit */ + if( LAPACKE_lsame( jobz, 'v' ) ) { + LAPACKE_free( z_t ); + } +exit_level_2: + LAPACKE_free( b_t ); +exit_level_1: + LAPACKE_free( a_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_chegvx_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_chegvx_work", info ); + } + return info; +} diff --git a/pool/shard006/C/0119799_rockchip.c b/pool/shard006/C/0119799_rockchip.c new file mode 100644 index 0000000000000000000000000000000000000000..52f1f65320fe035c3722df83b3809b258b0fc0e1 --- /dev/null +++ b/pool/shard006/C/0119799_rockchip.c @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0+ +/** + * drivers/net/phy/rockchip.c + * + * Driver for ROCKCHIP Ethernet PHYs + * + * Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd + * + * David Wu + */ + +#include +#include +#include +#include +#include +#include + +#define INTERNAL_EPHY_ID 0x1234d400 + +#define MII_INTERNAL_CTRL_STATUS 17 +#define SMI_ADDR_TSTCNTL 20 +#define SMI_ADDR_TSTREAD1 21 +#define SMI_ADDR_TSTREAD2 22 +#define SMI_ADDR_TSTWRITE 23 +#define MII_SPECIAL_CONTROL_STATUS 31 + +#define MII_AUTO_MDIX_EN BIT(7) +#define MII_MDIX_EN BIT(6) + +#define MII_SPEED_10 BIT(2) +#define MII_SPEED_100 BIT(3) + +#define TSTCNTL_RD (BIT(15) | BIT(10)) +#define TSTCNTL_WR (BIT(14) | BIT(10)) + +#define TSTMODE_ENABLE 0x400 +#define TSTMODE_DISABLE 0x0 + +#define WR_ADDR_A7CFG 0x18 + +static int rockchip_init_tstmode(struct phy_device *phydev) +{ + int ret; + + /* Enable access to Analog and DSP register banks */ + ret = phy_write(phydev, SMI_ADDR_TSTCNTL, TSTMODE_ENABLE); + if (ret) + return ret; + + ret = phy_write(phydev, SMI_ADDR_TSTCNTL, TSTMODE_DISABLE); + if (ret) + return ret; + + return phy_write(phydev, SMI_ADDR_TSTCNTL, TSTMODE_ENABLE); +} + +static int rockchip_close_tstmode(struct phy_device *phydev) +{ + /* Back to basic register bank */ + return phy_write(phydev, SMI_ADDR_TSTCNTL, TSTMODE_DISABLE); +} + +static int rockchip_integrated_phy_analog_init(struct phy_device *phydev) +{ + int ret; + + ret = rockchip_init_tstmode(phydev); + if (ret) + return ret; + + /* + * Adjust tx amplitude to make sginal better, + * the default value is 0x8. + */ + ret = phy_write(phydev, SMI_ADDR_TSTWRITE, 0xB); + if (ret) + return ret; + ret = phy_write(phydev, SMI_ADDR_TSTCNTL, TSTCNTL_WR | WR_ADDR_A7CFG); + if (ret) + return ret; + + return rockchip_close_tstmode(phydev); +} + +static int rockchip_integrated_phy_config_init(struct phy_device *phydev) +{ + int val, ret; + + /* + * The auto MIDX has linked problem on some board, + * workround to disable auto MDIX. + */ + val = phy_read(phydev, MII_INTERNAL_CTRL_STATUS); + if (val < 0) + return val; + val &= ~MII_AUTO_MDIX_EN; + ret = phy_write(phydev, MII_INTERNAL_CTRL_STATUS, val); + if (ret) + return ret; + + return rockchip_integrated_phy_analog_init(phydev); +} + +static void rockchip_link_change_notify(struct phy_device *phydev) +{ + /* + * If mode switch happens from 10BT to 100BT, all DSP/AFE + * registers are set to default values. So any AFE/DSP + * registers have to be re-initialized in this case. + */ + if (phydev->state == PHY_RUNNING && phydev->speed == SPEED_100) { + int ret = rockchip_integrated_phy_analog_init(phydev); + + if (ret) + phydev_err(phydev, "rockchip_integrated_phy_analog_init err: %d.\n", + ret); + } +} + +static int rockchip_set_polarity(struct phy_device *phydev, int polarity) +{ + int reg, err, val; + + /* get the current settings */ + reg = phy_read(phydev, MII_INTERNAL_CTRL_STATUS); + if (reg < 0) + return reg; + + reg &= ~MII_AUTO_MDIX_EN; + val = reg; + switch (polarity) { + case ETH_TP_MDI: + val &= ~MII_MDIX_EN; + break; + case ETH_TP_MDI_X: + val |= MII_MDIX_EN; + break; + case ETH_TP_MDI_AUTO: + case ETH_TP_MDI_INVALID: + default: + return 0; + } + + if (val != reg) { + /* Set the new polarity value in the register */ + err = phy_write(phydev, MII_INTERNAL_CTRL_STATUS, val); + if (err) + return err; + } + + return 0; +} + +static int rockchip_config_aneg(struct phy_device *phydev) +{ + int err; + + err = rockchip_set_polarity(phydev, phydev->mdix); + if (err < 0) + return err; + + return genphy_config_aneg(phydev); +} + +static int rockchip_phy_resume(struct phy_device *phydev) +{ + genphy_resume(phydev); + + return rockchip_integrated_phy_config_init(phydev); +} + +static struct phy_driver rockchip_phy_driver[] = { +{ + .phy_id = INTERNAL_EPHY_ID, + .phy_id_mask = 0xfffffff0, + .name = "Rockchip integrated EPHY", + /* PHY_BASIC_FEATURES */ + .flags = 0, + .link_change_notify = rockchip_link_change_notify, + .soft_reset = genphy_soft_reset, + .config_init = rockchip_integrated_phy_config_init, + .config_aneg = rockchip_config_aneg, + .suspend = genphy_suspend, + .resume = rockchip_phy_resume, +}, +}; + +module_phy_driver(rockchip_phy_driver); + +static struct mdio_device_id __maybe_unused rockchip_phy_tbl[] = { + { INTERNAL_EPHY_ID, 0xfffffff0 }, + { } +}; + +MODULE_DEVICE_TABLE(mdio, rockchip_phy_tbl); + +MODULE_AUTHOR("David Wu "); +MODULE_DESCRIPTION("Rockchip Ethernet PHY driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0119801_ratetorquekf.c b/pool/shard006/C/0119801_ratetorquekf.c new file mode 100644 index 0000000000000000000000000000000000000000..e849570b7394a0a62b1f30665335b2fd0d7a0442 --- /dev/null +++ b/pool/shard006/C/0119801_ratetorquekf.c @@ -0,0 +1,141 @@ +/** + ****************************************************************************** + * @addtogroup TauLabsCore Tau Labs Core components + * @{ + * @addtogroup UAVObjects UAVObject set for this firmware + * @{ + * + * @file ratetorquekf.c + * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. + * @author Tau Labs, http://taulabs.org, Copyright (C) 2012-2015 + * @brief Implementation of the RateTorqueKF object. This file has been + * automatically generated by the UAVObjectGenerator. + * + * @note Object definition file: ratetorquekf.xml. + * This is an automatically generated file. + * DO NOT modify manually. + * + * @see The GNU Public License (GPL) Version 3 + * + *****************************************************************************/ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include "uavobjectmanager.h" +#include "ratetorquekf.h" + +// Private variables +static UAVObjHandle handle = NULL; + +/** + * Initialize object. + * \return 0 Success + * \return -1 Failure to initialize or -2 for already initialized + */ +int32_t RateTorqueKFInitialize(void) +{ + // Don't set the handle to null if already registered + if(UAVObjGetByID(RATETORQUEKF_OBJID) != NULL) + return -2; + + // Register object with the object manager + handle = UAVObjRegister(RATETORQUEKF_OBJID, + RATETORQUEKF_ISSINGLEINST, RATETORQUEKF_ISSETTINGS, RATETORQUEKF_NUMBYTES, &RateTorqueKFSetDefaults); + + // Done + if (handle != 0) + { + return 0; + } + else + { + return -1; + } +} + +/** + * Initialize object fields and metadata with the default values. + * If a default value is not specified the object fields + * will be initialized to zero. + */ +void RateTorqueKFSetDefaults(UAVObjHandle obj, uint16_t instId) +{ + RateTorqueKFData data; + + // Initialize object fields to their default values + UAVObjGetInstanceData(obj, instId, &data); + memset(&data, 0, sizeof(RateTorqueKFData)); + data.Rate[0] = 0; + data.Rate[1] = 0; + data.Rate[2] = 0; + data.Torque[0] = 0; + data.Torque[1] = 0; + data.Torque[2] = 0; + + UAVObjSetInstanceData(obj, instId, &data); + + // Initialize object metadata to their default values + if (instId == 0) { + UAVObjMetadata metadata; + metadata.flags = + ACCESS_READWRITE << UAVOBJ_ACCESS_SHIFT | + ACCESS_READONLY << UAVOBJ_GCS_ACCESS_SHIFT | + 0 << UAVOBJ_TELEMETRY_ACKED_SHIFT | + 0 << UAVOBJ_GCS_TELEMETRY_ACKED_SHIFT | + UPDATEMODE_THROTTLED << UAVOBJ_TELEMETRY_UPDATE_MODE_SHIFT | + UPDATEMODE_MANUAL << UAVOBJ_GCS_TELEMETRY_UPDATE_MODE_SHIFT; + metadata.telemetryUpdatePeriod = 100; + metadata.gcsTelemetryUpdatePeriod = 0; + metadata.loggingUpdatePeriod = 0; + UAVObjSetMetadata(obj, &metadata); + } +} + +/** + * Get object handle + */ +UAVObjHandle RateTorqueKFHandle() +{ + return handle; +} + +/** + * Get/Set object Functions + */ +void RateTorqueKFRateSet( float *NewRate ) +{ + UAVObjSetDataField(RateTorqueKFHandle(), (void*)NewRate, offsetof( RateTorqueKFData, Rate), 3*sizeof(float)); +} +void RateTorqueKFRateGet( float *NewRate ) +{ + UAVObjGetDataField(RateTorqueKFHandle(), (void*)NewRate, offsetof( RateTorqueKFData, Rate), 3*sizeof(float)); +} +void RateTorqueKFTorqueSet( float *NewTorque ) +{ + UAVObjSetDataField(RateTorqueKFHandle(), (void*)NewTorque, offsetof( RateTorqueKFData, Torque), 3*sizeof(float)); +} +void RateTorqueKFTorqueGet( float *NewTorque ) +{ + UAVObjGetDataField(RateTorqueKFHandle(), (void*)NewTorque, offsetof( RateTorqueKFData, Torque), 3*sizeof(float)); +} + + +/** + * @} + * @} + */ + diff --git a/pool/shard006/C/0119803_WIDGET_SimpleListBox.c b/pool/shard006/C/0119803_WIDGET_SimpleListBox.c new file mode 100644 index 0000000000000000000000000000000000000000..c107bd31df69c447817904ef0495bf5571b49feb --- /dev/null +++ b/pool/shard006/C/0119803_WIDGET_SimpleListBox.c @@ -0,0 +1,99 @@ +/* +********************************************************************************************************* +* uC/GUI +* Universal graphic software for embedded applications +* +* (c) Copyright 2002, Micrium Inc., Weston, FL +* (c) Copyright 2002, SEGGER Microcontroller Systeme GmbH +* +* µC/GUI is protected by international copyright laws. Knowledge of the +* source code may not be used to write a similar product. This file may +* only be used in accordance with a license and should not be redistributed +* in any way. We appreciate your understanding and fairness. +* +---------------------------------------------------------------------- +File : WIDGET_SimpleListBox.c +Purpose : Example demonstrating the LISTBOX widget +---------------------------------------------------------------------- +*/ + +#include "gui.H" +#include "listbox.h" +#include + +/******************************************************************* +* +* defines +* +******************************************************************** +*/ + +#define countof(Array) (sizeof(Array) / sizeof(Array[0])) + +/******************************************************************* +* +* static variables +* +******************************************************************** +*/ + +const GUI_ConstString _ListBox[] = { + "English", "Deutsch", "Français", "Japanese", "Italiano", NULL +}; + +/******************************************************************* +* +* static code +* +******************************************************************** +*/ + +/******************************************************************* +* +* _DemoListBox +*/ +void _DemoListBox(void) { + int i; + int Entries = countof(_ListBox) - 1; + LISTBOX_Handle hListBox; + int ySize = GUI_GetFontSizeYOf(&GUI_Font13B_1) * Entries; + /* Create the listbox */ + hListBox = LISTBOX_Create(_ListBox, 130, 80, 60, ySize, WM_CF_SHOW); + /* Change current selection of the listbox */ + for (i = 0; i < Entries-1; i++) { + GUI_Delay(500); + LISTBOX_IncSel(hListBox); + WM_ExecIdle(); + } + for (i = 0; i < Entries-1; i++) { + GUI_Delay(500); + LISTBOX_DecSel(hListBox); + WM_ExecIdle(); + } + GUI_Delay(750); + /* Delete listbox widget */ + LISTBOX_Delete(hListBox); + GUI_ClearRect(0, 50, 319, 239); + GUI_Delay(750); +} + +/******************************************************************* +* +* MainTask +* +* Demonstrates LISTBOX widget +* +******************************************************************** +*/ + +void MainTask(void) { + GUI_Init(); + GUI_SetBkColor(GUI_BLUE); + GUI_Clear(); + GUI_SetColor(GUI_WHITE); + GUI_SetFont(&GUI_Font24_ASCII); + GUI_DispStringHCenterAt("WIDGET_SimpleListBox - Sample", 160, 5); + while(1) { + _DemoListBox(); + } +} diff --git a/pool/shard006/C/0119808_char.c b/pool/shard006/C/0119808_char.c new file mode 100644 index 0000000000000000000000000000000000000000..aecebc2d67affbdb4ca05cbba35462e2b5cfa935 --- /dev/null +++ b/pool/shard006/C/0119808_char.c @@ -0,0 +1,43 @@ +/* Provides functions for read/write/ctl of char devices */ +#include +#include +static ssize_t zero_rw(int rw, struct file *file, off_t m, uint8_t *buf, size_t c) +{ + (void)m; + (void)file; + if(rw == READ) + memset(buf, 0, c); + else if(rw == WRITE) + return 0; + return c; +} + +static ssize_t null_rw(int rw, struct file *file, off_t m, uint8_t *buf, size_t c) +{ + (void)m; + (void)file; + if(rw == READ) + return 0; + return c; +} + +static struct kdevice __zero_kdev = { + .select = 0,.open = 0,.close = 0,.destroy = 0,.create = 0,.ioctl = 0, + .name = "zero", + .rw = zero_rw, +}; + +static struct kdevice __null_kdev = { + .select = 0,.open = 0,.close = 0,.destroy = 0,.create = 0,.ioctl = 0, + .name = "null", + .rw = null_rw, +}; + +void dm_init_char_devices(void) +{ + int zero = dm_device_register(&__zero_kdev); + int null = dm_device_register(&__null_kdev); + sys_mknod("/dev/null", S_IFCHR | 0666, GETDEV(null, 0)); + sys_mknod("/dev/zero", S_IFCHR | 0666, GETDEV(zero, 0)); +} + diff --git a/pool/shard006/C/0119810_te.c b/pool/shard006/C/0119810_te.c new file mode 100644 index 0000000000000000000000000000000000000000..415222a26e6f72908b2c5c34340d0116624d3281 --- /dev/null +++ b/pool/shard006/C/0119810_te.c @@ -0,0 +1,178 @@ +#include +#include +#include + +#include +#include + +#define BUFFSIZE 509 + +typedef struct ln { + char text[BUFFSIZE]; + struct ln * next; + struct ln * prev; +} line; + +typedef struct f { + line * head; + line * tail; + int lc; + char filename[BUFFSIZE]; +} file; + +file * create_file (const char * filename) +{ + file * f = malloc(sizeof(file)); + f->head = NULL; + f->tail = NULL; + f->lc = 0; + + strcpy(f->filename, filename); + + return f; +} + +void add_line (file * f, const char * lt) +{ + line * l = malloc(sizeof(line)); + + strcpy(l->text, lt); + l->next = NULL; + + if (f->head == NULL) { + f->head = l; + f->tail = l; + } else { + l->prev = f->tail; + f->tail->next = l; + f->tail = l; + } + + (f->lc)++; +} + +file * read_file (const char * filename) +{ + FILE *fp; + char buffer[BUFFSIZE]; + file * f = create_file(filename); + + fp = fopen(filename, "r"); + if (fp == NULL) { + fprintf(stderr, "Failed to open %s\n", filename); + return NULL; + } + + while (fgets(buffer, BUFFSIZE, fp)) { + add_line(f, buffer); + } + + fclose(fp); + + return f; +} + +void print_lines (WINDOW * lwin, line * head, int n) +{ + int i = 1; + line * curr = head; + + while (curr != NULL && n >= ++i) { + wprintw(lwin, "%s", curr->text); + curr = curr->next; + } + + wrefresh(lwin); +} + +WINDOW * init_disp (file * f) +{ + WINDOW * win; + int rows, cols; + + initscr(); + noecho(); + refresh(); + + getmaxyx(stdscr, rows, cols); + win = newwin(rows, cols, 0, 0); + + print_lines(win, f->head, rows); + + return win; +} + +void no_scroll (void) +{ + printf("\a\n"); +} + +line * scrollw (WINDOW * win, line * top, int up) +{ + int rows, cols; + if (up && top->prev != NULL) + top = top->prev; + else if (!up && top->next != NULL) + top = top->next; + else + no_scroll(); + + getmaxyx(win, rows, cols); + wclear(win); + print_lines(win, top, rows); + + return top; +} + +void main_loop (WINDOW * win, file * f) +{ + int q = 0; + line * top = f->head; + while (!q) { + switch (getch()) { + case EOF: + q = 1; + break; + case 'q': + q = 1; + break; + case 'k': + top = scrollw(win, top, 1); + break; + case 'j': + top = scrollw(win, top, 0); + break; + } + } +} + +static void print_usage (void) +{ + printf("te: Text editor\n"); + printf("Usage:\n"); + printf("\tte filename\n"); +} + +int main(int argc, char *argv[]) +{ + file * f; + WINDOW * win; + + if (argc != 2) { + print_usage(); + exit(EXIT_SUCCESS); + } + + f = read_file(argv[1]); + + win = init_disp(f); + + curs_set(2); + wmove(win, 10, 10); + + main_loop(win, f); + + endwin(); + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard006/C/0119812_many.c b/pool/shard006/C/0119812_many.c new file mode 100644 index 0000000000000000000000000000000000000000..89c581077807345966ef185c2832233647f52fb9 --- /dev/null +++ b/pool/shard006/C/0119812_many.c @@ -0,0 +1,59 @@ +/* Area: ffi_call + Purpose: Check return value float, with many arguments + Limitations: none. + PR: none. + Originator: From the original ffitest.c */ + +/* { dg-do run } */ +#include "ffitest.h" + +#include +#include +#include + +static float ABI_ATTR many(float f1, float f2, float f3, float f4, float f5, float f6, float f7, float f8, float f9, float f10, float f11, float f12, float f13) +{ +#if 0 + printf("%f %f %f %f %f %f %f %f %f %f %f %f %f\n", + (double) f1, (double) f2, (double) f3, (double) f4, (double) f5, + (double) f6, (double) f7, (double) f8, (double) f9, (double) f10, + (double) f11, (double) f12, (double) f13); +#endif + + return f1+f2+f3+f4+f5+f6+f7+f8+f9+f10+f11+f12+f13; +} + +int main (void) +{ + ffi_cif cif; + ffi_type *args[13]; + void *values[13]; + float fa[13]; + float f, ff; + int i; + + for (i = 0; i < 13; i++) + { + args[i] = &ffi_type_float; + values[i] = &fa[i]; + fa[i] = (float) i; + } + + /* Initialize the cif */ + CHECK(ffi_prep_cif(&cif, ABI_NUM, 13, + &ffi_type_float, args) == FFI_OK); + + ffi_call(&cif, FFI_FN(many), &f, values); + + ff = many(fa[0], fa[1], + fa[2], fa[3], + fa[4], fa[5], + fa[6], fa[7], + fa[8], fa[9], + fa[10],fa[11],fa[12]); + + if (fabs(f - ff) < FLT_EPSILON) + exit(0); + else + abort(); +} diff --git a/pool/shard006/C/0119817_part_dos.c b/pool/shard006/C/0119817_part_dos.c new file mode 100644 index 0000000000000000000000000000000000000000..b53eba6764557f4643b31f8fc3e858590f1a2ad1 --- /dev/null +++ b/pool/shard006/C/0119817_part_dos.c @@ -0,0 +1,295 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein + * is confidential and proprietary to MediaTek Inc. and/or its licensors. + * Without the prior written permission of MediaTek inc. and/or its licensors, + * any reproduction, modification, use or disclosure of MediaTek Software, + * and information contained herein, in whole or in part, shall be strictly prohibited. + * + * MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON + * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. + * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE + * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR + * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH + * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES + * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES + * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK + * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND + * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, + * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, + * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO + * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek Software") + * have been modified by MediaTek Inc. All revisions are subject to any receiver's + * applicable license agreements with MediaTek Inc. + */ + +/* + * (C) Copyright 2001 + * Raymond Lo, lo@routefree.com + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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 + */ + +/* + * Support for harddisk partitions. + * + * To be compatible with LinuxPPC and Apple we use the standard Apple + * SCSI disk partitioning scheme. For more information see: + * http://developer.apple.com/techpubs/mac/Devices/Devices-126.html#MARKER-14-92 + */ + +#include +#include +#include +#include "part_dos.h" + +#if defined(CONFIG_CMD_IDE) || \ + defined(CONFIG_CMD_MG_DISK) || \ + defined(CONFIG_CMD_SATA) || \ + defined(CONFIG_CMD_SCSI) || \ + defined(CONFIG_CMD_USB) || \ + defined(CONFIG_MMC) || \ + defined(CONFIG_SYSTEMACE) + +/* Convert char[4] in little endian format to the host format integer + */ +static inline int le32_to_int(unsigned char *le32) +{ + return ((le32[3] << 24) + + (le32[2] << 16) + + (le32[1] << 8) + + le32[0] + ); +} + +static inline int is_extended(int part_type) +{ + return (part_type == 0x5 || + part_type == 0xf || + part_type == 0x85); +} + +static void print_one_part (dos_partition_t *p, int ext_part_sector, int part_num) +{ + int lba_start = ext_part_sector + le32_to_int (p->start4); + int lba_size = le32_to_int (p->size4); + + printf ("%5d\t\t%10d\t%10d\t%2x%s\n", + part_num, lba_start, lba_size, p->sys_ind, + (is_extended (p->sys_ind) ? " Extd" : "")); +} + +static int test_block_type(unsigned char *buffer) +{ + if((buffer[DOS_PART_MAGIC_OFFSET + 0] != 0x55) || + (buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) ) { + return (-1); + } /* no DOS Signature at all */ + if(strncmp((char *)&buffer[DOS_PBR_FSTYPE_OFFSET],"FAT",3)==0) + return DOS_PBR; /* is PBR */ + return DOS_MBR; /* Is MBR */ +} + + +int test_part_dos (block_dev_desc_t *dev_desc) +{ + unsigned char buffer[DEFAULT_SECTOR_SIZE]; + + if ((dev_desc->block_read(dev_desc->dev, 0, 1, (ulong *) buffer) != 1) || + (buffer[DOS_PART_MAGIC_OFFSET + 0] != 0x55) || + (buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) ) { + return (-1); + } + return (0); +} + +/* Print a partition that is relative to its Extended partition table + */ +static void print_partition_extended (block_dev_desc_t *dev_desc, int ext_part_sector, int relative, + int part_num) +{ + unsigned char buffer[DEFAULT_SECTOR_SIZE]; + dos_partition_t *pt; + int i; + + if (dev_desc->block_read(dev_desc->dev, ext_part_sector, 1, (ulong *) buffer) != 1) { + printf ("** Can't read partition table on %d:%d **\n", + dev_desc->dev, ext_part_sector); + return; + } + i=test_block_type(buffer); + if(i==-1) { + printf ("bad MBR sector signature 0x%02x%02x\n", + buffer[DOS_PART_MAGIC_OFFSET], + buffer[DOS_PART_MAGIC_OFFSET + 1]); + return; + } + if(i==DOS_PBR) { + printf (" 1\t\t 0\t%10ld\t%2x\n", + dev_desc->lba, buffer[DOS_PBR_MEDIA_TYPE_OFFSET]); + return; + } + /* Print all primary/logical partitions */ + pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET); + for (i = 0; i < 4; i++, pt++) { + /* + * fdisk does not show the extended partitions that + * are not in the MBR + */ + + if ((pt->sys_ind != 0) && + (ext_part_sector == 0 || !is_extended (pt->sys_ind)) ) { + print_one_part (pt, ext_part_sector, part_num); + } + + /* Reverse engr the fdisk part# assignment rule! */ + if ((ext_part_sector == 0) || + (pt->sys_ind != 0 && !is_extended (pt->sys_ind)) ) { + part_num++; + } + } + + /* Follows the extended partitions */ + pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET); + for (i = 0; i < 4; i++, pt++) { + if (is_extended (pt->sys_ind)) { + int lba_start = le32_to_int (pt->start4) + relative; + + print_partition_extended (dev_desc, lba_start, + ext_part_sector == 0 ? lba_start + : relative, + part_num); + } + } + + return; +} + + +/* Print a partition that is relative to its Extended partition table + */ +static int get_partition_info_extended (block_dev_desc_t *dev_desc, int ext_part_sector, + int relative, int part_num, + int which_part, disk_partition_t *info) +{ + unsigned char buffer[DEFAULT_SECTOR_SIZE]; + dos_partition_t *pt; + int i; + + if (dev_desc->block_read (dev_desc->dev, ext_part_sector, 1, (ulong *) buffer) != 1) { + printf ("** Can't read partition table on %d:%d **\n", + dev_desc->dev, ext_part_sector); + return -1; + } + if (buffer[DOS_PART_MAGIC_OFFSET] != 0x55 || + buffer[DOS_PART_MAGIC_OFFSET + 1] != 0xaa) { + printf ("bad MBR sector signature 0x%02x%02x\n", + buffer[DOS_PART_MAGIC_OFFSET], + buffer[DOS_PART_MAGIC_OFFSET + 1]); + return -1; + } + + /* Print all primary/logical partitions */ + pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET); + for (i = 0; i < 4; i++, pt++) { + /* + * fdisk does not show the extended partitions that + * are not in the MBR + */ + if (((pt->boot_ind & ~0x80) == 0) && + (pt->sys_ind != 0) && + (part_num == which_part) && + (is_extended(pt->sys_ind) == 0)) { + info->blksz = 512; + info->start = ext_part_sector + le32_to_int (pt->start4); + info->size = le32_to_int (pt->size4); + switch(dev_desc->if_type) { + case IF_TYPE_IDE: + case IF_TYPE_SATA: + case IF_TYPE_ATAPI: + sprintf ((char *)info->name, "hd%c%d", + 'a' + dev_desc->dev, part_num); + break; + case IF_TYPE_SCSI: + sprintf ((char *)info->name, "sd%c%d", + 'a' + dev_desc->dev, part_num); + break; + case IF_TYPE_USB: + sprintf ((char *)info->name, "usbd%c%d", + 'a' + dev_desc->dev, part_num); + break; + case IF_TYPE_DOC: + sprintf ((char *)info->name, "docd%c%d", + 'a' + dev_desc->dev, part_num); + break; + default: + sprintf ((char *)info->name, "xx%c%d", + 'a' + dev_desc->dev, part_num); + break; + } + /* sprintf(info->type, "%d, pt->sys_ind); */ + sprintf ((char *)info->type, "U-Boot"); + return 0; + } + + /* Reverse engr the fdisk part# assignment rule! */ + if ((ext_part_sector == 0) || + (pt->sys_ind != 0 && !is_extended (pt->sys_ind)) ) { + part_num++; + } + } + + /* Follows the extended partitions */ + pt = (dos_partition_t *) (buffer + DOS_PART_TBL_OFFSET); + for (i = 0; i < 4; i++, pt++) { + if (is_extended (pt->sys_ind)) { + int lba_start = le32_to_int (pt->start4) + relative; + + return get_partition_info_extended (dev_desc, lba_start, + ext_part_sector == 0 ? lba_start : relative, + part_num, which_part, info); + } + } + return -1; +} + +void print_part_dos (block_dev_desc_t *dev_desc) +{ + printf ("Partition Start Sector Num Sectors Type\n"); + print_partition_extended (dev_desc, 0, 0, 1); +} + +int get_partition_info_dos (block_dev_desc_t *dev_desc, int part, disk_partition_t * info) +{ + return get_partition_info_extended (dev_desc, 0, 0, 1, part, info); +} + + +#endif diff --git a/pool/shard006/C/0119818_timer.c b/pool/shard006/C/0119818_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..2be12bb7896535f12c7bac3d2d52cadec39173a5 --- /dev/null +++ b/pool/shard006/C/0119818_timer.c @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2009 Samsung Electronics + * Heungjun Kim + * Inki Dae + * Minkyu Kang + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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 +#include +#include +#include +#include + +#define PRESCALER_1 (16 - 1) /* prescaler of timer 2, 3, 4 */ +#define MUX_DIV_2 1 /* 1/2 period */ +#define MUX_DIV_4 2 /* 1/4 period */ +#define MUX_DIV_8 3 /* 1/8 period */ +#define MUX_DIV_16 4 /* 1/16 period */ +#define MUX4_DIV_SHIFT 16 + +#define TCON_TIMER4_SHIFT 20 + +static unsigned long count_value; + +/* Internal tick units */ +static unsigned long long timestamp; /* Monotonic incrementing timer */ +static unsigned long lastdec; /* Last decremneter snapshot */ + +/* macro to read the 16 bit timer */ + +static inline struct s5p_timer *s5p_get_base_timer(void) +{ + //return (struct s5p_timer *)samsung_get_base_timer(); +#if defined(CONFIG_ARCH_EXYNOS) + return (struct s5p_timer *)samsung_get_base_timer(); +#elif defined(CONFIG_S5PC210) + return (struct s5p_timer *)0x139D0000; +#elif defined(CONFIG_S5PC110) + return (struct s5p_timer *)0xE2500000; +#endif +} + +int timer_init(void) +{ + struct s5p_timer *const timer = s5p_get_base_timer(); + u32 val; + + /* + * @ PWM Timer 4 + * Timer Freq(HZ) = + * PWM_CLK / { (prescaler_value + 1) * (divider_value) } + */ + + /* set prescaler : 16 */ + /* set divider : 2 */ + writel((PRESCALER_1 & 0xff) << 8, &timer->tcfg0); + writel((MUX_DIV_2 & 0xf) << MUX4_DIV_SHIFT, &timer->tcfg1); + /* count_value = 2085937.5(HZ) (per 1 sec)*/ + //count_value = get_pwm_clk() / ((PRESCALER_1 + 1) * + // (MUX_DIV_2 + 1)); + count_value = 2500000; + + /* count_value / 100 = 20859.375(HZ) (per 10 msec) */ + count_value = count_value / 100; + + /* set count value */ + writel(count_value, &timer->tcntb4); + lastdec = count_value; + + val = (readl(&timer->tcon) & ~(0x07 << TCON_TIMER4_SHIFT)) | + TCON4_AUTO_RELOAD; + + /* auto reload & manual update */ + writel(val | TCON4_UPDATE, &timer->tcon); + + /* start PWM timer 4 */ + writel(val | TCON4_START, &timer->tcon); + + timestamp = 0; + + return 0; +} + +/* + * timer without interrupts + */ +void reset_timer(void) +{ + reset_timer_masked(); +} + +unsigned long get_timer(unsigned long base) +{ + return get_timer_masked() - base; +} + +void set_timer(unsigned long t) +{ + timestamp = t; +} + +/* delay x useconds */ +void __udelay(unsigned long usec) +{ + struct s5p_timer *const timer = s5p_get_base_timer(); + unsigned long tmo, tmp; + + count_value = readl(&timer->tcntb4); + + if (usec >= 1000) { + /* + * if "big" number, spread normalization + * to seconds + * 1. start to normalize for usec to ticks per sec + * 2. find number of "ticks" to wait to achieve target + * 3. finish normalize. + */ + tmo = usec / 1000; + tmo *= (CONFIG_SYS_HZ * count_value / 10); + tmo /= 1000; + } else { + /* else small number, don't kill it prior to HZ multiply */ + tmo = usec * CONFIG_SYS_HZ * count_value / 10; + tmo /= (1000 * 1000); + } + + /* get current timestamp */ + tmp = get_timer(0); + + /* if setting this fordward will roll time stamp */ + /* reset "advancing" timestamp to 0, set lastdec value */ + /* else, set advancing stamp wake up time */ + if ((tmo + tmp + 1) < tmp) + reset_timer_masked(); + else + tmo += tmp; + + /* loop till event */ + while (get_timer_masked() < tmo) + ; /* nop */ +} + +void reset_timer_masked(void) +{ + struct s5p_timer *const timer = s5p_get_base_timer(); + + /* reset time */ + lastdec = readl(&timer->tcnto4); + timestamp = 0; +} + +unsigned long get_timer_masked(void) +{ + struct s5p_timer *const timer = s5p_get_base_timer(); + unsigned long now = readl(&timer->tcnto4); + + if (lastdec >= now) + timestamp += lastdec - now; + else + timestamp += lastdec + count_value - now; + + lastdec = now; + + return timestamp; +} + +/* + * This function is derived from PowerPC code (read timebase as long long). + * On ARM it just returns the timer value. + */ +unsigned long long get_ticks(void) +{ + return get_timer(0); +} + +/* + * This function is derived from PowerPC code (timebase clock frequency). + * On ARM it returns the number of timer ticks per second. + */ +unsigned long get_tbclk(void) +{ + return CONFIG_SYS_HZ; +} diff --git a/pool/shard006/C/0119819_mod_tests.c b/pool/shard006/C/0119819_mod_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..5e184b9fe3718d4f699ab61b5bfc22cba43fc0a5 --- /dev/null +++ b/pool/shard006/C/0119819_mod_tests.c @@ -0,0 +1,118 @@ +#include +#include +#include + +#include "dyn_array.h" + + +void test_da_init() { + struct dyn_array da; + da_init(&da); + + assert(0 == da.max); + assert(0 == da.n); + assert(NULL == da.values); +} + + +void test_da_push() { + struct dyn_array da; + da_init(&da); + da_value_t i = 123; + + assert(0 == da.max); + assert(0 == da.n); + + assert(da_push(&da, i) == 1); + assert(0 != da.max); + assert(1 == da.n); +} + + +void test_da_pop() { + struct dyn_array da; + da_init(&da); + da_value_t i = 0; + + da_push(&da, i); + da_pop(&da); + + assert(0 != da.max); + assert(0 == da.n); +} + + +void test_da_first_last() { + struct dyn_array da; + da_init(&da); + + da_value_t i = 0; + const da_value_t value_first = 100; + const da_value_t value_last = 120; + + for (i = value_first; i <= value_last; i++) { + da_push(&da, i); + } + + assert(da_first(&da) == value_first); + assert(da_last(&da) == value_last); + + da_pop(&da); + assert(da_last(&da) == ( value_last - 1 )); +} + + +void test_da_get_set() { + struct dyn_array da; + da_init(&da); + + da_push(&da, 123); + da_push(&da, 456); + da_push(&da, 789); + assert(da_get(&da, 0) == 123); + assert(da_get(&da, 1) == 456); + assert(da_get(&da, 2) == 789); + + da_set(&da, 0, 10); + assert(da_get(&da, 0) == 10); + assert(da_get(&da, 1) == 456); + assert(da_get(&da, 2) == 789); + + da_set(&da, 1, 20); + assert(da_get(&da, 0) == 10); + assert(da_get(&da, 1) == 20); + assert(da_get(&da, 2) == 789); + + da_free(&da); +} + + +int main(int argc, char *argv[]) +{ + struct dyn_array da; + unsigned cnt = 0; + int rv = 0; + + da_init(&da); + + test_da_init(); + test_da_push(); + test_da_pop(); + test_da_first_last(); + test_da_get_set(); + + printf("all tests successful !!!\n"); + printf("starting stress test !!!\n"); + + do { + da_value_t value = rand() % 1024; + rv = da_push(&da, value); + cnt++; + if (!(cnt%1024)) printf("pushed %u, size: %u\n", cnt, da.max); + } while (rv >= 0); + + printf("failure %u, %u\n", cnt, da.max); + + da_free(&da); + return 0; +} diff --git a/pool/shard006/C/0119820_data.c b/pool/shard006/C/0119820_data.c new file mode 100644 index 0000000000000000000000000000000000000000..b4507b0ebfee9969e9e0188ccac0cf7e68bb3c2e --- /dev/null +++ b/pool/shard006/C/0119820_data.c @@ -0,0 +1,89 @@ +/* + kcomedilib/data.c + implements comedi_data_*() functions + + COMEDI - Linux Control and Measurement Device Interface + Copyright (C) 2000 David A. Schleef + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. + +*/ + +#include +#include +#include /* for comedi_udelay() */ + +#include + +int comedi_data_write(comedi_t * dev, unsigned int subdev, unsigned int chan, + unsigned int range, unsigned int aref, lsampl_t data) +{ + comedi_insn insn; + + memset(&insn, 0, sizeof(insn)); + insn.insn = INSN_WRITE; + insn.n = 1; + insn.data = &data; + insn.subdev = subdev; + insn.chanspec = CR_PACK(chan, range, aref); + + return comedi_do_insn(dev, &insn); +} + +int comedi_data_read(comedi_t * dev, unsigned int subdev, unsigned int chan, + unsigned int range, unsigned int aref, lsampl_t * data) +{ + comedi_insn insn; + + memset(&insn, 0, sizeof(insn)); + insn.insn = INSN_READ; + insn.n = 1; + insn.data = data; + insn.subdev = subdev; + insn.chanspec = CR_PACK(chan, range, aref); + + return comedi_do_insn(dev, &insn); +} + +int comedi_data_read_hint(comedi_t * dev, unsigned int subdev, + unsigned int chan, unsigned int range, unsigned int aref) +{ + comedi_insn insn; + lsampl_t dummy_data; + + memset(&insn, 0, sizeof(insn)); + insn.insn = INSN_READ; + insn.n = 0; + insn.data = &dummy_data; + insn.subdev = subdev; + insn.chanspec = CR_PACK(chan, range, aref); + + return comedi_do_insn(dev, &insn); +} + +int comedi_data_read_delayed(comedi_t * dev, unsigned int subdev, + unsigned int chan, unsigned int range, unsigned int aref, + lsampl_t * data, unsigned int nano_sec) +{ + int retval; + + retval = comedi_data_read_hint(dev, subdev, chan, range, aref); + if (retval < 0) + return retval; + + comedi_udelay((nano_sec + 999) / 1000); + + return comedi_data_read(dev, subdev, chan, range, aref, data); +} diff --git a/pool/shard006/C/0119823_robtkapp.c b/pool/shard006/C/0119823_robtkapp.c new file mode 100644 index 0000000000000000000000000000000000000000..b6c232d6682a80b990909cad6f4879e54b92e2f0 --- /dev/null +++ b/pool/shard006/C/0119823_robtkapp.c @@ -0,0 +1,263 @@ +/* robtk GUI application + * + * Copyright (C) 2012-2015 Robin Gareus + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +#ifndef UI_UPDATE_FPS +#define UI_UPDATE_FPS 25 +#endif + +/////////////////////////////////////////////////////////////////////////////// + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE +#endif + +#ifdef WIN32 +#include +#include +#define pthread_t //< override jack.h def +#endif + +#include "lv2/lv2plug.in/ns/lv2core/lv2.h" +#include "lv2/lv2plug.in/ns/extensions/ui/ui.h" + +#ifdef __APPLE__ +#include +extern void rtk_osx_api_init(void); +extern void rtk_osx_api_terminate(void); +extern void rtk_osx_api_run(void); +extern void rtk_osx_api_err(const char *msg); +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if (defined _WIN32 && defined RTK_STATIC_INIT) +#include +#endif + +#ifndef _WIN32 +#include +#include +#else +#include +#endif + +#include "./gl/xternalui.h" + +#define LV2_EXTERNAL_UI_RUN(ptr) (ptr)->run(ptr) +#define LV2_EXTERNAL_UI_SHOW(ptr) (ptr)->show(ptr) +#define LV2_EXTERNAL_UI_HIDE(ptr) (ptr)->hide(ptr) + +#define nan NAN + +typedef struct _RtkLv2Description { + const LV2UI_Descriptor* (*lv2ui_descriptor)(uint32_t index); + const uint32_t gui_descriptor_id; + const char *plugin_human_id; +} RtkLv2Description; + + +static const LV2UI_Descriptor *plugin_gui; + +//static LV2_Handle plugin_instance = NULL; +static LV2UI_Handle gui_instance = NULL; + +static pthread_mutex_t gui_thread_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t data_ready = PTHREAD_COND_INITIALIZER; + + +static RtkLv2Description const *inst; + +/* a simple state machine for this client */ +static volatile enum { + Run, + Exit +} client_state = Run; + +struct lv2_external_ui_host extui_host; +struct lv2_external_ui *extui = NULL; + + +static const RtkLv2Description _plugin = { + & RTK_DESCRIPTOR, 0, APPTITLE +}; + +/****************************************************************************** + * MAIN + */ + +static void cleanup(int sig) { + if (plugin_gui && gui_instance && plugin_gui->cleanup) { + plugin_gui->cleanup(gui_instance); + } + fprintf(stderr, "bye.\n"); +} + +static void run_one() { + plugin_gui->port_event(gui_instance, 0, 0, 0, NULL); + LV2_EXTERNAL_UI_RUN(extui); +} + +#ifdef __APPLE__ + +static void osx_loop (CFRunLoopTimerRef timer, void *info) { + if (client_state == Run) { + run_one(); + } + if (client_state == Exit) { + rtk_osx_api_terminate(); + } +} + +#else + +static void main_loop(void) { + struct timespec timeout; + pthread_mutex_lock (&gui_thread_lock); + while (client_state != Exit) { + run_one(); + + if (client_state == Exit) break; + +#ifdef _WIN32 + //Sleep(1000/UI_UPDATE_FPS); +#if (defined(__MINGW64__) || defined(__MINGW32__)) && __MSVCRT_VERSION__ >= 0x0601 + struct __timeb64 timebuffer; + _ftime64(&timebuffer); +#else + struct __timeb32 timebuffer; + _ftime(&timebuffer); +#endif + timeout.tv_nsec = timebuffer.millitm * 1000000; + timeout.tv_sec = timebuffer.time; +#else // POSIX + clock_gettime(CLOCK_REALTIME, &timeout); +#endif + timeout.tv_nsec += 1000000000 / (UI_UPDATE_FPS); + if (timeout.tv_nsec >= 1000000000) {timeout.tv_nsec -= 1000000000; timeout.tv_sec+=1;} + pthread_cond_timedwait (&data_ready, &gui_thread_lock, &timeout); + + } /* while running */ + pthread_mutex_unlock (&gui_thread_lock); +} +#endif // APPLE RUNLOOP + +static void catchsig (int sig) { + fprintf(stderr,"caught signal - shutting down.\n"); + client_state=Exit; + pthread_cond_signal (&data_ready); +} + +static void on_external_ui_closed(void* controller) { + catchsig(0); +} + +int main (int argc, char **argv) { + int rv = 0; + + inst = & _plugin; + +#ifdef __APPLE__ + rtk_osx_api_init(); +#endif + +#ifdef _WIN32 + pthread_win32_process_attach_np(); +#endif +#if (defined _WIN32 && defined RTK_STATIC_INIT) + glib_init_static(); + gobject_init_ctor(); +#endif + + struct { int argc; char **argv; } rtkargv; + rtkargv.argc = argc; + rtkargv.argv = argv; + + const LV2_Feature external_lv_feature = { LV2_EXTERNAL_UI_URI, &extui_host}; + const LV2_Feature external_kx_feature = { LV2_EXTERNAL_UI_URI__KX__Host, &extui_host}; + const LV2_Feature robtk_argv = { "http://gareus.org/oss/lv2/robtk#argv", &rtkargv}; + + // TODO add argv[] as feature + const LV2_Feature* ui_features[] = { + &external_lv_feature, + &external_kx_feature, + &robtk_argv, + NULL + }; + + extui_host.plugin_human_id = inst->plugin_human_id; + + plugin_gui = inst->lv2ui_descriptor(inst->gui_descriptor_id); + + if (plugin_gui) { + /* init plugin GUI */ + extui_host.ui_closed = on_external_ui_closed; + gui_instance = plugin_gui->instantiate(plugin_gui, + "URI TODO", NULL, NULL, NULL, + (void **)&extui, ui_features); + + } + + if (!gui_instance || !extui) { + fprintf(stderr, "Error: GUI was not initialized.\n"); + rv |= 2; + goto out; + } + +#ifndef _WIN32 + signal (SIGHUP, catchsig); + signal (SIGINT, catchsig); +#endif + + { + + LV2_EXTERNAL_UI_SHOW(extui); + +#ifdef __APPLE__ + CFRunLoopRef runLoop = CFRunLoopGetCurrent(); + CFRunLoopTimerContext context = {0, NULL, NULL, NULL, NULL}; + CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault, 0, 1.0/UI_UPDATE_FPS, 0, 0, &osx_loop, &context); + CFRunLoopAddTimer(runLoop, timer, kCFRunLoopCommonModes); + rtk_osx_api_run(); +#else + + main_loop(); +#endif + + LV2_EXTERNAL_UI_HIDE(extui); + } + +out: + cleanup(0); +#ifdef _WIN32 + pthread_win32_process_detach_np(); +#endif +#if (defined _WIN32 && defined RTK_STATIC_INIT) + glib_cleanup_static(); +#endif + return(rv); +} +/* vi:set ts=2 sts=2 sw=2: */ diff --git a/pool/shard006/C/0119827_Cache.c b/pool/shard006/C/0119827_Cache.c new file mode 100644 index 0000000000000000000000000000000000000000..6c95a0722525d9aa742b4e5d651b6f989a304ed1 --- /dev/null +++ b/pool/shard006/C/0119827_Cache.c @@ -0,0 +1,211 @@ +#include "Cache.h" +#include "Util.h" +#include +#include +#include + +#define __malloc(__type, s) (__type*)malloc(sizeof(__type) * s); + +/* Esta estructura de datos representa la información que guardaremos en nuestra "cache" por +cada bloque */ +typedef struct +{ + unsigned int etiqueta; /* guardamos la etiqueta del bloque que se almacena. Tendrá un valor consistente si valido=1 */ + int valido; /* Tendrá valor 0 o 1 indicando si esta celda/linea esta ocupada por un bloque */ + unsigned int contador_lru; /* tendrá un valor consistente si valido=1 y la caché tiene algorimo de reemplazo lru. + Valores grandes indican que la línea ha sido recientemente añadida, valores pequeños indican lo contrario. */ +}linea; + +unsigned int num_conjuntos; /* Será el número de conjuntos de la caché*/ +unsigned int asociatividad; /* Será el número de líneas por conjunto de la caché */ +unsigned short es_lru; /* 1 si la caché es lru, 0 si el reemplazo es aleatorio */ + +unsigned int num_bits_offset; /*'Será el número de bits de una dirección usado para indexar un byte dentro de un bloque */ +unsigned int num_bits_indice; /* Será el número de bits usados para indexar el conjunto donde se mapean los bloques */ +unsigned int num_bits_etiqueta; /* Será el numero de bits usados para indexar, dentro de un mismo conjunto, + el bloque */ + + + +/* siempre se cumplirá que 32 = num_bits_offset + num_bits_indice + num_bits_etiqueta */ + + +linea** cache; /* guarda toda la información de las líneas de la caché. Es una matriz donde a cada conjunto le corresponde +una fila, y hay tantas columnas como líneas por conjunto haya */ + + + +/* Funciones auxiliares */ + +/* Devuelve la etiqueta de una dirección */ +unsigned int obtener_etiqueta(unsigned int direccion); + +/* Devuelve el nºconjunto de una dirección */ +unsigned int obtener_indice(unsigned int direccion); + +/* Comprueba si un acceso es un acierto: Si el bloque con la etiqueta especificada está en el conjunto indicado (comparando +etiquetas) */ +int es_acierto(unsigned int etiqueta, unsigned int indice); + +/* Si el conjunto no esta lleno, reemplaza el bloque cuya etiqueta es la indicada en el primer hueco libre. Si esta lleno, se +selecciona un bloque de entre todos los del conjunto y se reemplaza por el nuevo (solo se reemplaza la etiqueta) */ +void traer_bloque(unsigned int etiqueta, unsigned int indice); + +/* Se actualizan los contadores lru. La precondición para este método es que exista un bloque con esta etiqueta en el conjunto +indicado, y que el algoritmo de reemplazo sea el lru. Los contadores de todas las líneas que tengan etiquetas no coincidentes, +son decrementadas si su contador es mayor que el contador actual de la línea cuya etiqueta sea coincidente. Posteriormente, +el contador de la línea con la etiqueta coincidente se establece al máximo (nºlines por conjunto) */ +void actualizar_contadores(unsigned int etiqueta, unsigned int indice); + + + +void inicializar_cache(const configuracion* conf) +{ + int i, j; + + num_conjuntos = conf->num_lineas / conf->asociatividad; + asociatividad = conf->asociatividad; + es_lru = conf->reemplazo; + + num_bits_offset = log_base_2(conf->tamano_linea); + num_bits_indice = log_base_2(num_conjuntos); + num_bits_etiqueta = 32 - num_bits_offset - num_bits_indice; + + /* inicializamos la caché, de forma que todas las líneas esten disponibles */ + cache = __malloc(linea*, num_conjuntos); + for(i = 0; i != num_conjuntos; ++i) + cache[i] = __malloc(linea, asociatividad); + + for(i = 0;i != num_conjuntos; ++i) + for(j = 0; j != asociatividad; ++j) + { + linea* l = &cache[i][j]; + l->contador_lru = 1; + l->valido = 0; + } +} + +int acceder_direccion(unsigned int direccion) +{ + unsigned int etiqueta, indice; + + /* obttener la etiqueta y el nºconjunto (índice), de la dirección */ + + etiqueta = obtener_etiqueta(direccion); + indice = obtener_indice(direccion); + + /* comprobar si el acceso es un fallo o es un acierto, es decir, si se encuentra o no en cache dicho + bloque */ + if(es_acierto(etiqueta, indice)) + { +#ifdef _DEBUG + printf("Acierto de cache para: %x\n", direccion); +#endif + /* actualizamos los contadores lru */ + if(es_lru) + actualizar_contadores(etiqueta, indice); + return 1; + } + +#ifdef _DEBUG + printf("Fallo en la cache para: %x\n", direccion); +#endif + + /* si es fallo, traer el bloque que contiene el dato apuntado por la dirección, a la caché */ + + /* traer dicho bloque a la memoria cache */ + traer_bloque(etiqueta, indice); + + /* actualizamos los contadores lru */ + if(es_lru) + actualizar_contadores(etiqueta, indice); + + return 0; +} + +unsigned int obtener_etiqueta(unsigned int direccion) +{ + return rangobits(direccion, num_bits_offset + num_bits_indice, 31); +} + +unsigned int obtener_indice(unsigned int direccion) +{ + return rangobits(direccion, num_bits_offset, num_bits_offset + num_bits_indice - 1); +} + + +int es_acierto(unsigned int etiqueta, unsigned int indice) +{ + /* buscar una línea que contenga un bloque donde el valor de su etiqueta es el mismo que + la etiqueta dela dirección, dentro de las líneas del conjunto. */ + + /* seleccionamos el conjunto */ + linea* l = cache[indice]; + + /* buscamos la etiqueta */ + int j = 0; + while((j < (asociatividad - 1)) && (!l[j].valido || (etiqueta != l[j].etiqueta) )) + j++; + return l[j].valido && (etiqueta == l[j].etiqueta); +} + +void traer_bloque(unsigned int etiqueta, unsigned int indice) +{ + linea* l = cache[indice]; + int i, j; + + /* comprobamos si hay alguna línea vacía */ + i = 0; + while((i < (asociatividad - 1)) && l[i].valido) + i++; + + /* Si hay alguna línea vacía, "copiar" el bloque a esa línea, y establecer el "bit de validez" + a cero. */ + if(!l[i].valido) + { + l[i].etiqueta = etiqueta; + l[i].valido = 1; + } + else + { + /* Si no hay ninguna línea vacía pasamos al algoritmo de reemplazo ... */ + + /* Seleccionamos él bloque a reemplazar, es decir, que bloque eliminamos */ + if(es_lru) + { + /* Seleccionamos la línea cuyo contador es mínimo */ + j = 0; + for(i = 1; i != asociatividad; ++i) + if(l[i].contador_lru < l[j].contador_lru) + j = i; + } + else + { + /* seleccionamos una línea de forma aleatoria */ + j = numero_aleatorio(0, asociatividad); + } + + /* La línea con el bloque eliminado está vacía, y "copiamos" el nuevo bloque a esta línea */ + l[j].etiqueta = etiqueta; + } +} + + +void actualizar_contadores(unsigned int etiqueta, unsigned int indice) +{ + linea* l = cache[indice]; + int i, j; + i = 0; + while(!l[i].valido || (l[i].etiqueta != etiqueta)) + i++; + + /* actualizamos los contadores lru de un conjunto: + 1º Para toda línea cuya etiqueta no encaje con la especificada, su contador lru se decrementa si + su valor actual es mayor que el contador de la línea con la etiqueta coincidente */ + for(j = 0; j != asociatividad; j++) + if((j != i) && l[j].valido && (l[j].contador_lru > l[i].contador_lru)) + l[j].contador_lru--; + + /* Establecemos el contador lru de la línea con la etiqueta especificada al máximo */ + l[i].contador_lru = asociatividad; +} diff --git a/pool/shard006/C/0119828_preempt_timing.c b/pool/shard006/C/0119828_preempt_timing.c new file mode 100644 index 0000000000000000000000000000000000000000..b84d5469242adea1b1818c2fe859498810645601 --- /dev/null +++ b/pool/shard006/C/0119828_preempt_timing.c @@ -0,0 +1,159 @@ +/****************************************************************************** + * + * Copyright © International Business Machines Corp., 2006, 2008 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See + * the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * NAME + * preempt_timing.c + * + * DESCRIPTION + * This program indicated the preemption delays that may be encountered + * by realtime apps. The program runs with the scheduling policy of + * SCHED_FIFO at a maximum SCHED_FIFO priority. It is bound to a single + * processor and its address space is locked as well. It makes successive + * calls to the gettimeofday() function(via inlined assembly to read the + * TSC).The value returned between two such consecutive calls is reported + * as the latency. + * The maximum, minimum and average delays are reported for x pairs of such + * calls. + * + * USAGE: + * Use run_auto.sh script in current directory to build and run test. + * + * AUTHOR + * + * + * HISTORY + * + * + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tst_tsc.h" + +#define ITERATIONS 1000000ULL +#define INTERVALS 10 + +void usage(void) +{ + rt_help(); + printf("preempt_timing specific options:\n"); +} + +int parse_args(int c, char *v) +{ + + int handled = 1; + switch (c) { + case 'h': + usage(); + exit(0); + default: + handled = 0; + break; + } + return handled; +} + +unsigned long long sample_list[ITERATIONS]; +int main(int argc, char *argv[]) +{ + unsigned long long i, j, delta, min, max, avg; + struct sched_param param; + cpu_set_t mask; + int err; + +#ifdef TSC_UNSUPPORTED + printf("Error: test cannot be executed on an arch wihout TSC.\n"); + return ENOTSUP; +#endif + + max = avg = 0; + min = -1; + setup(); + + rt_init("h", parse_args, argc, argv); + + /* switch to SCHED_FIFO 99 */ + param.sched_priority = sched_get_priority_max(SCHED_FIFO); + err = sched_setscheduler(0, SCHED_FIFO, ¶m); + + /* Check that the user has the appropriate privileges */ + if (err) { + if (errno == EPERM) { + fprintf(stderr, + "This program runs with a scheduling policy of SCHED_FIFO at priority %d\n", + param.sched_priority); + fprintf(stderr, + "You don't have the necessary privileges to create such a real-time process.\n"); + } else { + fprintf(stderr, "Failed to set scheduler, errno %d\n", + errno); + } + exit(1); + } + + /* BIND TO A SINGLE CPU */ + CPU_ZERO(&mask); + CPU_SET(0, &mask); + err = sched_setaffinity(0, sizeof(mask), &mask); + if (err < 0) { + printf("Can't set affinity: %d %s\n", err, strerror(err)); + exit(-1); + } + + for (j = 0; j < INTERVALS; j++) { + /* Collect samples */ + for (i = 0; i < ITERATIONS; i++) + rdtscll(sample_list[i]); + + /* Process samples */ + for (i = 0; i < (ITERATIONS - 1); i++) { + delta = sample_list[i + 1] - sample_list[i]; + if (delta < min) + min = delta; + if (delta > max) + max = delta; + if (delta > 100000) + printf("maxd(%llu:%llu): %llu %llu = %llu\n", j, + i, sample_list[i], sample_list[i + 1], + delta); + avg += delta; + } + usleep(100); /*let necessary things happen */ + } + avg /= (ITERATIONS * INTERVALS); + + printf("%lld pairs of gettimeofday() calls completed\n", + ITERATIONS * INTERVALS); + printf("Time between calls:\n"); + printf("Minimum: %llu \n", min); + printf("Maximum: %llu \n", max); + printf("Average: %llu \n", avg); + + return 0; +} diff --git a/pool/shard006/C/0119829_pta-ptrarith-3.c b/pool/shard006/C/0119829_pta-ptrarith-3.c new file mode 100644 index 0000000000000000000000000000000000000000..70829375c0c1d395e80def0aab553b48ebbeef67 --- /dev/null +++ b/pool/shard006/C/0119829_pta-ptrarith-3.c @@ -0,0 +1,36 @@ +/* { dg-do run } */ +/* { dg-options "-fdump-tree-alias" } */ +/* { dg-skip-if "" { *-*-* } { "-O0" "-fno-fat-lto-objects" } { "" } } */ + +extern void abort (void); +struct X { + int *p; + int *q; + int *r; +}; +int __attribute__((noinline)) +foo(int i, int j, int k, __SIZE_TYPE__ off) +{ + struct X x; + int **p, *q; + x.p = &i; + x.q = &j; + x.r = &k; + p = &x.q; + p += off; + /* *p points to { i, j, k } */ + q = *p; + return *q; +} +int main() +{ + if (foo(1, 2, 3, -1) != 1) + abort (); + if (foo(1, 2, 3, 0) != 2) + abort (); + if (foo(1, 2, 3, 1) != 3) + abort (); + return 0; +} + +/* { dg-final { scan-tree-dump "q_\[0-9\]* = { i j k }" "alias" } } */ diff --git a/pool/shard006/C/0119832_program1.c b/pool/shard006/C/0119832_program1.c new file mode 100644 index 0000000000000000000000000000000000000000..9f98a301741907c4a3e9870236c90ba69cff01bc --- /dev/null +++ b/pool/shard006/C/0119832_program1.c @@ -0,0 +1,93 @@ +#include +#include + +/*Vivian Lam, CS2211 Assignment3: Program 1*/ + +/* Name: Program1 + Purpose: Asks user to input the time of day (24hour time) and time +duration and add the two together +*/ + +int main (void) +{ + + /*Declares and initializes variables. + First integer represents time of day + second integer represents time duration. + Third variable is the sum of the two integers. + digitTens is used to extract the digit in the tens column of + timeDur and timeDay + checkCorrect is a boolean used to check if the digit in the tens + column of timeDay and timeDur are valid*/ + + int timeDay = 0; + int timeDur; + int result; + int digitTens; + bool checkCorrect = false; + +/*NOTE: +first integer must be less than 2400 and the minutes must be less than 59 +(tens digit is <6) +second integer minutes must be less than 59 (tens digit < 6) +*/ + /*if the above conditions are not met then loop and keep prompting + user to enter a correct value*/ + //loop for first value. also makes sure that time of day is positive + while((timeDay > 2400) || (timeDay < 0) || (checkCorrect == false)) + { + /*resets the boolean checking variable to be false*/ + checkCorrect = false; + + /*Asks the user to enter the first integer*/ + printf("Please enter the first integer (time of day on a 24 hour clock): "); + + /*reads the integer and stores it into timeDay*/ + scanf("%d", &timeDay); + + /*extracts the digit from the tens column from input and checks if it's under 6*/ + digitTens = (timeDay / 10) %10; + if (digitTens <=5) + { + checkCorrect = true; + } + } + checkCorrect = false; //resets the value of the boolean variable to be false + + //loop for second variable + while(checkCorrect == false) + { + /*resets the boolean checking variable to be false*/ + checkCorrect = false; + + /*prompts user to enter the second integer and stores it into timeDur*/ + printf("Please enter the second integer (time duration): "); + scanf("%d", &timeDur); + + /*extracts the digit from the tens column from input and +checks if it's between -5 and 5 (inclusive*/ + digitTens = (timeDur / 10) %10; + if ((digitTens <=5) && (digitTens >= -5)) + { + checkCorrect = true; + } + } + + /*adds the time duration to the time of day*/ + result = timeDay + timeDur; + + /*mods result so that it will be in proper 24 hour time*/ + result = result % 2400; + + /*if the result is a negative number, converts it to proper 24 +hour time*/ + if(result < 0) + { + result = 2400 + result; + } + + /*print the results to the screen in 4 digit time*/ + printf("Time of day + time duration is : %.4d", result); + + return 0; +} diff --git a/pool/shard006/C/0119833_humidity.c b/pool/shard006/C/0119833_humidity.c new file mode 100644 index 0000000000000000000000000000000000000000..910ecfe6fc5e322c9a741a06d30f018e418977fb --- /dev/null +++ b/pool/shard006/C/0119833_humidity.c @@ -0,0 +1,107 @@ +#include "./humidity.h" + +Humidity* Humidity_new (uint32_t value, + char* unit, + char* location, + char* name, + char* description) +{ + Humidity* t = malloc(sizeof(Humidity)); + + *t = (Humidity) { + .type = humidity, + .value = value, + .unit = NULL, + .location = NULL, + .name = NULL, + .description = NULL, + .Humidity_free = Humidity_free, + .Humidity_menu = Humidity_menu, + .Humidity_draw = Humidity_draw, + .Humidity_destroy = Humidity_destroy, + }; + + if (unit) { + size_t length = strlen(unit); + t->unit = malloc(sizeof(char) * length); + memcpy(t->unit, unit, length); + + snprintf(t->formated_value, 32, "%ld %s", t->value, t->unit); + } else { + snprintf(t->formated_value, 32, "%ld", t->value); + } + + if (location) { + size_t length = strlen(location); + t->location = malloc(sizeof(char) * length); + memcpy(t->location, location, length); + } + + if (name) { + size_t length = strlen(name); + t->name = malloc(sizeof(char) * length); + memcpy(t->name, name, length); + } + + if (description) { + size_t length = strlen(description); + t->description = malloc(sizeof(char) * length); + memcpy(t->description, description, length); + } + + return t; +} + +void Humidity_free(void* s) { + Humidity* self = (Humidity*) s; + if (self->unit) { + free(self->unit); + } + + if (self->location) { + free(self->location); + } + + if (self->name) { + free(self->name); + } + + if (self->description) { + free(self->description); + } + + free(self); +} + +SimpleMenuItem Humidity_menu (void* s) { + Humidity* t = (Humidity*) s; + SimpleMenuItem result = { + .title = "Humidity", + .subtitle = t->formated_value, + .icon = get_icon(RESOURCE_ID_HUMIDITY_ICON), + .callback = NULL, + }; + + if (t->name) { + result.title = t->name; + } else if (t->location) { + result.title = t->location; + } + + return result; +} + +void Humidity_draw (Window* window, void* s) { + Humidity* self = (Humidity*) s; + + self->layers = draw_basic(window, + "humidity in the space : ", + self->formated_value, + self->name, + self->location, + self->description); +} + +void Humidity_destroy (void* s) { + free_basic(((Humidity*) s)->layers); +} diff --git a/pool/shard006/C/0119834_cleancache.c b/pool/shard006/C/0119834_cleancache.c new file mode 100644 index 0000000000000000000000000000000000000000..32e6f4136fa2297e13a6ac51444d50c18b78e9a3 --- /dev/null +++ b/pool/shard006/C/0119834_cleancache.c @@ -0,0 +1,220 @@ +/* + * Cleancache frontend + * + * This code provides the generic "frontend" layer to call a matching + * "backend" driver implementation of cleancache. See + * Documentation/vm/cleancache.txt for more information. + * + * Copyright (C) 2009-2010 Oracle Corp. All rights reserved. + * Author: Dan Magenheimer + * + * This work is licensed under the terms of the GNU GPL, version 2. + */ + +#include +#include +#include +#include +#include +#include + +/* + * This global enablement flag may be read thousands of times per second + * by cleancache_get/put/invalidate even on systems where cleancache_ops + * is not claimed (e.g. cleancache is config'ed on but remains + * disabled), so is preferred to the slower alternative: a function + * call that checks a non-global. + */ +int cleancache_enabled __read_mostly; +EXPORT_SYMBOL(cleancache_enabled); + +/* + * cleancache_ops is set by cleancache_ops_register to contain the pointers + * to the cleancache "backend" implementation functions. + */ +static struct cleancache_ops cleancache_ops __read_mostly; + +/* + * Counters available via /sys/kernel/debug/frontswap (if debugfs is + * properly configured. These are for information only so are not protected + * against increment races. + */ +static u64 cleancache_succ_gets; +static u64 cleancache_failed_gets; +static u64 cleancache_puts; +static u64 cleancache_invalidates; + +/* + * register operations for cleancache, returning previous thus allowing + * detection of multiple backends and possible nesting + */ +struct cleancache_ops cleancache_register_ops(struct cleancache_ops *ops) +{ + struct cleancache_ops old = cleancache_ops; + + cleancache_ops = *ops; + cleancache_enabled = 1; + return old; +} +EXPORT_SYMBOL(cleancache_register_ops); + +/* Called by a cleancache-enabled filesystem at time of mount */ +void __cleancache_init_fs(struct super_block *sb) +{ + sb->cleancache_poolid = (*cleancache_ops.init_fs)(PAGE_SIZE); +} +EXPORT_SYMBOL(__cleancache_init_fs); + +/* Called by a cleancache-enabled clustered filesystem at time of mount */ +void __cleancache_init_shared_fs(char *uuid, struct super_block *sb) +{ + sb->cleancache_poolid = + (*cleancache_ops.init_shared_fs)(uuid, PAGE_SIZE); +} +EXPORT_SYMBOL(__cleancache_init_shared_fs); + +/* + * If the filesystem uses exportable filehandles, use the filehandle as + * the key, else use the inode number. + */ +static int cleancache_get_key(struct inode *inode, + struct cleancache_filekey *key) +{ + int (*fhfn)(struct inode *, __u32 *fh, int *, struct inode *); + int len = 0, maxlen = CLEANCACHE_KEY_MAX; + struct super_block *sb = inode->i_sb; + + key->u.ino = inode->i_ino; + if (sb->s_export_op != NULL) { + fhfn = sb->s_export_op->encode_fh; + if (fhfn) { + len = (*fhfn)(inode, &key->u.fh[0], &maxlen, NULL); + if (len <= 0 || len == 255) + return -1; + if (maxlen > CLEANCACHE_KEY_MAX) + return -1; + } + } + return 0; +} + +/* + * "Get" data from cleancache associated with the poolid/inode/index + * that were specified when the data was put to cleanache and, if + * successful, use it to fill the specified page with data and return 0. + * The pageframe is unchanged and returns -1 if the get fails. + * Page must be locked by caller. + */ +int __cleancache_get_page(struct page *page) +{ + int ret = -1; + int pool_id; + struct cleancache_filekey key = { .u.key = { 0 } }; + + VM_BUG_ON(!PageLocked(page)); + pool_id = page->mapping->host->i_sb->cleancache_poolid; + if (pool_id < 0) + goto out; + + if (cleancache_get_key(page->mapping->host, &key) < 0) + goto out; + + ret = (*cleancache_ops.get_page)(pool_id, key, page->index, page); + if (ret == 0) + cleancache_succ_gets++; + else + cleancache_failed_gets++; +out: + return ret; +} +EXPORT_SYMBOL(__cleancache_get_page); + +/* + * "Put" data from a page to cleancache and associate it with the + * (previously-obtained per-filesystem) poolid and the page's, + * inode and page index. Page must be locked. Note that a put_page + * always "succeeds", though a subsequent get_page may succeed or fail. + */ +void __cleancache_put_page(struct page *page) +{ + int pool_id; + struct cleancache_filekey key = { .u.key = { 0 } }; + + VM_BUG_ON(!PageLocked(page)); + pool_id = page->mapping->host->i_sb->cleancache_poolid; + if (pool_id >= 0 && + cleancache_get_key(page->mapping->host, &key) >= 0) { + (*cleancache_ops.put_page)(pool_id, key, page->index, page); + cleancache_puts++; + } +} +EXPORT_SYMBOL(__cleancache_put_page); + +/* + * Invalidate any data from cleancache associated with the poolid and the + * page's inode and page index so that a subsequent "get" will fail. + */ +void __cleancache_invalidate_page(struct address_space *mapping, + struct page *page) +{ + /* careful... page->mapping is NULL sometimes when this is called */ + int pool_id = mapping->host->i_sb->cleancache_poolid; + struct cleancache_filekey key = { .u.key = { 0 } }; + + if (pool_id >= 0) { + VM_BUG_ON(!PageLocked(page)); + if (cleancache_get_key(mapping->host, &key) >= 0) { + (*cleancache_ops.invalidate_page)(pool_id, + key, page->index); + cleancache_invalidates++; + } + } +} +EXPORT_SYMBOL(__cleancache_invalidate_page); + +/* + * Invalidate all data from cleancache associated with the poolid and the + * mappings's inode so that all subsequent gets to this poolid/inode + * will fail. + */ +void __cleancache_invalidate_inode(struct address_space *mapping) +{ + int pool_id = mapping->host->i_sb->cleancache_poolid; + struct cleancache_filekey key = { .u.key = { 0 } }; + + if (pool_id >= 0 && cleancache_get_key(mapping->host, &key) >= 0) + (*cleancache_ops.invalidate_inode)(pool_id, key); +} +EXPORT_SYMBOL(__cleancache_invalidate_inode); + +/* + * Called by any cleancache-enabled filesystem at time of unmount; + * note that pool_id is surrendered and may be reutrned by a subsequent + * cleancache_init_fs or cleancache_init_shared_fs + */ +void __cleancache_invalidate_fs(struct super_block *sb) +{ + if (sb->cleancache_poolid >= 0) { + int old_poolid = sb->cleancache_poolid; + sb->cleancache_poolid = -1; + (*cleancache_ops.invalidate_fs)(old_poolid); + } +} +EXPORT_SYMBOL(__cleancache_invalidate_fs); + +static int __init init_cleancache(void) +{ +#ifdef CONFIG_DEBUG_FS + struct dentry *root = debugfs_create_dir("cleancache", NULL); + if (root == NULL) + return -ENXIO; + debugfs_create_u64("succ_gets", S_IRUGO, root, &cleancache_succ_gets); + debugfs_create_u64("failed_gets", S_IRUGO, + root, &cleancache_failed_gets); + debugfs_create_u64("puts", S_IRUGO, root, &cleancache_puts); + debugfs_create_u64("invalidates", S_IRUGO, + root, &cleancache_invalidates); +#endif + return 0; +} +module_init(init_cleancache) diff --git a/pool/shard006/C/0119835_show.c b/pool/shard006/C/0119835_show.c new file mode 100644 index 0000000000000000000000000000000000000000..3ec291a53615bce885e1117129a1e1e887223fc7 --- /dev/null +++ b/pool/shard006/C/0119835_show.c @@ -0,0 +1,156 @@ +/* Show (print) CnS replies contents + + Big fat assumption here: CnS output is context-free. + That is, it's ok to use the same output format regardless of why + or when or where did the packet arrive. + + Given sierracns scope, and the packets it supports, + this assumption works well. */ + +#include +#include +#include + +#include "abbr.h" +#include "wire.h" +#include "dict.h" + +extern int opt_C; +extern int opt_n; + +extern struct cns* cns; +extern struct hip* hip; + +void dumpcns(int len, char* buf); +void dumphip(int len, char* buf); + +#define GR (1 << CNS_GETREPLY) +#define NO (1 << CNS_NOTIFICATION) +#define SR (1 << CNS_SETREPLY) +#define GN (GR | NO) + +#undef OID$ +#define OID$(oid, ops, len, func) extern void func(void); +#include "oid.hh" + +static struct dict opnames[] = { + { CNS_GET, "GE" }, + { CNS_SET, "SE" }, + { CNS_GETREPLY, "GR" }, + { CNS_SETREPLY, "SR" }, + { CNS_NE, "EN" }, + { CNS_ND, "DN" }, + { CNS_NEREPLY, "ER" }, + { CNS_NDREPLY, "DR" }, + { CNS_NOTIFICATION, "NO" }, + { CNS_GETREPLY | CNS_ERRORMASK, "G!" }, + { CNS_SETREPLY | CNS_ERRORMASK, "S!" }, + { CNS_NEREPLY | CNS_ERRORMASK, "E!" }, + { CNS_NDREPLY | CNS_ERRORMASK, "D!" }, + { 0, NULL } +}; + + +struct showcnsobject { + uint16_t oid; + uint16_t opm; + int len; + void (*call)(void); + char* arg; +} showcnsobject[] = { +#undef OID$ +#define OID$(oid, ops, len, func) \ + { 0x##oid, ops, len, func }, +#include "oid.hh" + { 0x0000, 0, 0, NULL } +}; + +void showcns(void) +{ + int oid = ntohs(cns->oid); + int len = ntohs(cns->len); + struct showcnsobject* p; + + if(cns->op & CNS_ERRORMASK) { + printf("%04X %.*s\n", oid, len, cns->payload); + return; + } + + if(cns->op == CNS_NEREPLY) { + if(opt_n) + printf("CNS %04X notifications enabled\n", oid); + return; + } + if(cns->op == CNS_NDREPLY) { + if(opt_n) + printf("CNS %04X notifications disabled\n", oid); + return; + } + + for(p = showcnsobject; p->call; p++) { + if(p->oid != oid) + continue; + if(!(p->opm & (1 << cns->op))) + continue; + if(p->len > 0 && len != p->len) + continue; + if(p->len < 0 && len < -p->len) + continue; + + p->call(); + return; + } + + if(!opt_C && cns) + dumpcns(cns->len + sizeof(struct cns), (char*) cns); + /* with -C, it's been dumped already */ +} + +void dumphip(int len, char* buf) +{ + char* p; + struct hip* hip = (struct hip*) buf; + + if(len < sizeof(struct hip)) { + printf("HIP ...\n"); + return; + } + + int hiplen = ntohs(hip->len); + int paylen; + + if(len >= sizeof(struct hip) + hiplen) + paylen = hiplen; + else + paylen = len - sizeof(struct hip); + + printf("HIP 0x%02X 0x%02X { ", hip->mid, hip->par); + for(p = hip->payload; p < hip->payload + paylen; p++) + printf("%02X ", (int)(*p & 0xFF)); + if(paylen < hiplen) + printf("... "); + printf("}\n"); +} + +void dumpcns(int len, char* buf) +{ + char* p; + struct cns* cns = (struct cns*) buf; + + if(len < sizeof(struct cns)) { + printf("CNS ...\n"); + return; + } + + int cnslen = ntohs(cns->len); + int paylen = (len >= sizeof(struct cns) + cnslen ? cnslen : len - sizeof(struct cns)); + + printf("CNS %04X %s %i:{ ", + ntohs(cns->oid), dict(opnames, cns->op, 1), ntohs(cns->len)); + for(p = cns->payload; p < cns->payload + paylen; p++) + printf("%02X ", (int)(*p & 0xFF)); + if(paylen < cnslen) + printf("... "); + printf("}\n"); + +} diff --git a/pool/shard006/C/0119836_gb-command.c b/pool/shard006/C/0119836_gb-command.c new file mode 100644 index 0000000000000000000000000000000000000000..cd7ab659883149faf2f090bca167ea57947b17f1 --- /dev/null +++ b/pool/shard006/C/0119836_gb-command.c @@ -0,0 +1,70 @@ +/* gb-command.c + * + * Copyright (C) 2014 Christian Hergert + * + * 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 . + */ + +#include "gb-command.h" + +G_DEFINE_TYPE (GbCommand, gb_command, G_TYPE_OBJECT) + +enum { + EXECUTE, + LAST_SIGNAL +}; + +static guint signals [LAST_SIGNAL]; + +GbCommand * +gb_command_new (void) +{ + return g_object_new (GB_TYPE_COMMAND, NULL); +} + +static GbCommandResult * +gb_command_real_execute (GbCommand *command) +{ + return NULL; +} + +GbCommandResult * +gb_command_execute (GbCommand *command) +{ + GbCommandResult *ret = NULL; + g_return_val_if_fail (GB_IS_COMMAND (command), NULL); + g_signal_emit (command, signals [EXECUTE], 0, &ret); + return ret; +} + +static void +gb_command_class_init (GbCommandClass *klass) +{ + klass->execute = gb_command_real_execute; + + signals [EXECUTE] = + g_signal_new ("execute", + GB_TYPE_COMMAND, + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (GbCommandClass, execute), + g_signal_accumulator_first_wins, + NULL, NULL, + GB_TYPE_COMMAND_RESULT, + 0); +} + +static void +gb_command_init (GbCommand *self) +{ +} diff --git a/pool/shard006/C/0119839_gnrc_netif_ieee802154.c b/pool/shard006/C/0119839_gnrc_netif_ieee802154.c new file mode 100644 index 0000000000000000000000000000000000000000..f72f6ff1d4849c40288aa27c467a6c9ec652bf10 --- /dev/null +++ b/pool/shard006/C/0119839_gnrc_netif_ieee802154.c @@ -0,0 +1,248 @@ +/* + * Copyright (C) 2017 Freie Universität Berlin + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @{ + * + * @file + * @author Martine Lenders + */ + +#include "net/gnrc.h" +#include "net/gnrc/netif/ieee802154.h" +#include "net/netdev/ieee802154.h" + +#ifdef MODULE_GNRC_IPV6 +#include "net/ipv6/hdr.h" +#endif + +#define ENABLE_DEBUG (0) +#include "debug.h" + +#if defined(MODULE_OD) && ENABLE_DEBUG +#include "od.h" +#endif + +#ifdef MODULE_NETDEV_IEEE802154 +static int _send(gnrc_netif_t *netif, gnrc_pktsnip_t *pkt); +static gnrc_pktsnip_t *_recv(gnrc_netif_t *netif); + +static const gnrc_netif_ops_t ieee802154_ops = { + .send = _send, + .recv = _recv, + .get = gnrc_netif_get_from_netdev, + .set = gnrc_netif_set_from_netdev, +}; + +gnrc_netif_t *gnrc_netif_ieee802154_create(char *stack, int stacksize, + char priority, char *name, + netdev_t *dev) +{ + return gnrc_netif_create(stack, stacksize, priority, name, dev, + &ieee802154_ops); +} + +static gnrc_pktsnip_t *_make_netif_hdr(uint8_t *mhr) +{ + gnrc_pktsnip_t *snip; + uint8_t src[IEEE802154_LONG_ADDRESS_LEN], dst[IEEE802154_LONG_ADDRESS_LEN]; + int src_len, dst_len; + le_uint16_t _pan_tmp; /* TODO: hand-up PAN IDs to GNRC? */ + + dst_len = ieee802154_get_dst(mhr, dst, &_pan_tmp); + src_len = ieee802154_get_src(mhr, src, &_pan_tmp); + if ((dst_len < 0) || (src_len < 0)) { + DEBUG("_make_netif_hdr: unable to get addresses\n"); + return NULL; + } + /* allocate space for header */ + snip = gnrc_netif_hdr_build(src, (size_t)src_len, dst, (size_t)dst_len); + if (snip == NULL) { + DEBUG("_make_netif_hdr: no space left in packet buffer\n"); + return NULL; + } + /* set broadcast flag for broadcast destination */ + if ((dst_len == 2) && (dst[0] == 0xff) && (dst[1] == 0xff)) { + gnrc_netif_hdr_t *hdr = snip->data; + hdr->flags |= GNRC_NETIF_HDR_FLAGS_BROADCAST; + } + return snip; +} + +static gnrc_pktsnip_t *_recv(gnrc_netif_t *netif) +{ + netdev_t *dev = netif->dev; + netdev_ieee802154_rx_info_t rx_info; + netdev_ieee802154_t *state = (netdev_ieee802154_t *)netif->dev; + gnrc_pktsnip_t *pkt = NULL; + int bytes_expected = dev->driver->recv(dev, NULL, 0, NULL); + + if (bytes_expected >= (int)IEEE802154_MIN_FRAME_LEN) { + int nread; + + pkt = gnrc_pktbuf_add(NULL, NULL, bytes_expected, GNRC_NETTYPE_UNDEF); + if (pkt == NULL) { + DEBUG("_recv_ieee802154: cannot allocate pktsnip.\n"); + return NULL; + } + nread = dev->driver->recv(dev, pkt->data, bytes_expected, &rx_info); + if (nread <= 0) { + gnrc_pktbuf_release(pkt); + return NULL; + } + if (!(state->flags & NETDEV_IEEE802154_RAW)) { + gnrc_pktsnip_t *ieee802154_hdr, *netif_hdr; + gnrc_netif_hdr_t *hdr; +#if ENABLE_DEBUG + char src_str[GNRC_NETIF_HDR_L2ADDR_PRINT_LEN]; +#endif + size_t mhr_len = ieee802154_get_frame_hdr_len(pkt->data); + + if (mhr_len == 0) { + DEBUG("_recv_ieee802154: illegally formatted frame received\n"); + gnrc_pktbuf_release(pkt); + return NULL; + } + nread -= mhr_len; + /* mark IEEE 802.15.4 header */ + ieee802154_hdr = gnrc_pktbuf_mark(pkt, mhr_len, GNRC_NETTYPE_UNDEF); + if (ieee802154_hdr == NULL) { + DEBUG("_recv_ieee802154: no space left in packet buffer\n"); + gnrc_pktbuf_release(pkt); + return NULL; + } + netif_hdr = _make_netif_hdr(ieee802154_hdr->data); + if (netif_hdr == NULL) { + DEBUG("_recv_ieee802154: no space left in packet buffer\n"); + gnrc_pktbuf_release(pkt); + return NULL; + } + + hdr = netif_hdr->data; + +#ifdef MODULE_L2FILTER + if (!l2filter_pass(dev->filter, gnrc_netif_hdr_get_src_addr(hdr), + hdr->src_l2addr_len)) { + gnrc_pktbuf_release(pkt); + gnrc_pktbuf_release(netif_hdr); + DEBUG("_recv_ieee802154: packet dropped by l2filter\n"); + return NULL; + } +#endif + + hdr->lqi = rx_info.lqi; + hdr->rssi = rx_info.rssi; + hdr->if_pid = thread_getpid(); + pkt->type = state->proto; +#if ENABLE_DEBUG + DEBUG("_recv_ieee802154: received packet from %s of length %u\n", + gnrc_netif_addr_to_str(gnrc_netif_hdr_get_src_addr(hdr), + hdr->src_l2addr_len, + src_str), + nread); +#if defined(MODULE_OD) + od_hex_dump(pkt->data, nread, OD_WIDTH_DEFAULT); +#endif +#endif + gnrc_pktbuf_remove_snip(pkt, ieee802154_hdr); + LL_APPEND(pkt, netif_hdr); + } + + DEBUG("_recv_ieee802154: reallocating.\n"); + gnrc_pktbuf_realloc_data(pkt, nread); + } else if (bytes_expected > 0) { + DEBUG("_recv_ieee802154: received frame is too short\n"); + dev->driver->recv(dev, NULL, bytes_expected, NULL); + } + + return pkt; +} + +static int _send(gnrc_netif_t *netif, gnrc_pktsnip_t *pkt) +{ + netdev_t *dev = netif->dev; + netdev_ieee802154_t *state = (netdev_ieee802154_t *)netif->dev; + gnrc_netif_hdr_t *netif_hdr; + const uint8_t *src, *dst = NULL; + int res = 0; + size_t src_len, dst_len; + uint8_t mhr[IEEE802154_MAX_HDR_LEN]; + uint8_t flags = (uint8_t)(state->flags & NETDEV_IEEE802154_SEND_MASK); + le_uint16_t dev_pan = byteorder_btols(byteorder_htons(state->pan)); + + flags |= IEEE802154_FCF_TYPE_DATA; + if (pkt == NULL) { + DEBUG("_send_ieee802154: pkt was NULL\n"); + return -EINVAL; + } + if (pkt->type != GNRC_NETTYPE_NETIF) { + DEBUG("_send_ieee802154: first header is not generic netif header\n"); + return -EBADMSG; + } + netif_hdr = pkt->data; + /* prepare destination address */ + if (netif_hdr->flags & /* If any of these flags is set assume broadcast */ + (GNRC_NETIF_HDR_FLAGS_BROADCAST | GNRC_NETIF_HDR_FLAGS_MULTICAST)) { + dst = ieee802154_addr_bcast; + dst_len = IEEE802154_ADDR_BCAST_LEN; + } + else { + dst = gnrc_netif_hdr_get_dst_addr(netif_hdr); + dst_len = netif_hdr->dst_l2addr_len; + } + src_len = netif_hdr->src_l2addr_len; + if (src_len > 0) { + src = gnrc_netif_hdr_get_src_addr(netif_hdr); + } + else { + src_len = netif->l2addr_len; + src = netif->l2addr; + } + /* fill MAC header, seq should be set by device */ + if ((res = ieee802154_set_frame_hdr(mhr, src, src_len, + dst, dst_len, dev_pan, + dev_pan, flags, state->seq++)) == 0) { + DEBUG("_send_ieee802154: Error preperaring frame\n"); + return -EINVAL; + } + + /* prepare iolist for netdev / mac layer */ + iolist_t iolist = { + .iol_next = (iolist_t *)pkt->next, + .iol_base = mhr, + .iol_len = (size_t)res + }; + +#ifdef MODULE_NETSTATS_L2 + if (netif_hdr->flags & + (GNRC_NETIF_HDR_FLAGS_BROADCAST | GNRC_NETIF_HDR_FLAGS_MULTICAST)) { + netif->dev->stats.tx_mcast_count++; + } + else { + netif->dev->stats.tx_unicast_count++; + } +#endif +#ifdef MODULE_GNRC_MAC + if (netif->mac.mac_info & GNRC_NETIF_MAC_INFO_CSMA_ENABLED) { + res = csma_sender_csma_ca_send(dev, &iolist, &netif->mac.csma_conf); + } + else { + res = dev->driver->send(dev, &iolist); + } +#else + res = dev->driver->send(dev, &iolist); +#endif + + /* release old data */ + gnrc_pktbuf_release(pkt); + return res; +} +#else /* MODULE_NETDEV_IEEE802154 */ +typedef int dont_be_pedantic; +#endif /* MODULE_NETDEV_IEEE802154 */ +/** @} */ diff --git a/pool/shard006/C/0119850_bbuf_test.c b/pool/shard006/C/0119850_bbuf_test.c new file mode 100644 index 0000000000000000000000000000000000000000..707c2df3c6e8a1f895b29c817f502cd9b98356ed --- /dev/null +++ b/pool/shard006/C/0119850_bbuf_test.c @@ -0,0 +1,145 @@ +/* + * Copyright 2014-2017 Jetperch 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 + * + * 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 +#include +#include +#include +#include "embc/bbuf.h" +#include "hal_test_impl.h" +#include "embc.h" + + +static void u8_unsafe(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u8(&p1, 42); + assert_int_equal(b + 1, p1); + assert_int_equal(42, *b); + assert_int_equal(42, embc_bbuf_unsafe_decode_u8(&p2)); + assert_int_equal(p1, p2); +} + +static void u16_unsafe_be(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u16_be(&p1, 0x1122); + assert_int_equal(b + 2, p1); + assert_int_equal(0x11, b[0]); + assert_int_equal(0x22, b[1]); + assert_int_equal(0x1122, embc_bbuf_unsafe_decode_u16_be(&p2)); + assert_int_equal(p1, p2); +} + +static void u16_unsafe_le(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u16_le(&p1, 0x1122); + assert_int_equal(b + 2, p1); + assert_int_equal(0x22, b[0]); + assert_int_equal(0x11, b[1]); + assert_int_equal(0x1122, embc_bbuf_unsafe_decode_u16_le(&p2)); + assert_int_equal(p1, p2); +} + +static void u32_unsafe_be(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u32_be(&p1, 0x11223344); + assert_int_equal(b + 4, p1); + assert_int_equal(0x11, b[0]); + assert_int_equal(0x22, b[1]); + assert_int_equal(0x33, b[2]); + assert_int_equal(0x44, b[3]); + assert_int_equal(0x11223344, embc_bbuf_unsafe_decode_u32_be(&p2)); + assert_int_equal(p1, p2); +} + +static void u32_unsafe_le(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u32_le(&p1, 0x11223344); + assert_int_equal(b + 4, p1); + assert_int_equal(0x44, b[0]); + assert_int_equal(0x33, b[1]); + assert_int_equal(0x22, b[2]); + assert_int_equal(0x11, b[3]); + assert_int_equal(0x11223344, embc_bbuf_unsafe_decode_u32_le(&p2)); + assert_int_equal(p1, p2); +} + +static void u64_unsafe_be(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u64_be(&p1, 0x1122334455667788llu); + assert_int_equal(b + 8, p1); + assert_int_equal(0x11, b[0]); + assert_int_equal(0x22, b[1]); + assert_int_equal(0x33, b[2]); + assert_int_equal(0x44, b[3]); + assert_int_equal(0x55, b[4]); + assert_int_equal(0x66, b[5]); + assert_int_equal(0x77, b[6]); + assert_int_equal(0x88, b[7]); + assert_int_equal(0x1122334455667788llu, embc_bbuf_unsafe_decode_u64_be(&p2)); + assert_int_equal(p1, p2); +} + +static void u64_unsafe_le(void **state) { + (void) state; + uint8_t b[16]; + uint8_t * p1 = b; + uint8_t const * p2 = b; + embc_bbuf_unsafe_encode_u64_le(&p1, 0x1122334455667788llu); + assert_int_equal(b + 8, p1); + assert_int_equal(0x88, b[0]); + assert_int_equal(0x77, b[1]); + assert_int_equal(0x66, b[2]); + assert_int_equal(0x55, b[3]); + assert_int_equal(0x44, b[4]); + assert_int_equal(0x33, b[5]); + assert_int_equal(0x22, b[6]); + assert_int_equal(0x11, b[7]); + assert_int_equal(0x1122334455667788llu, embc_bbuf_unsafe_decode_u64_le(&p2)); + assert_int_equal(p1, p2); +} + +int main(void) { + embc_allocator_set((embc_alloc_fn) malloc, free); + const struct CMUnitTest tests[] = { + cmocka_unit_test(u8_unsafe), + cmocka_unit_test(u16_unsafe_be), + cmocka_unit_test(u16_unsafe_le), + cmocka_unit_test(u32_unsafe_be), + cmocka_unit_test(u32_unsafe_le), + cmocka_unit_test(u64_unsafe_be), + cmocka_unit_test(u64_unsafe_le), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} diff --git a/pool/shard006/C/0119855_ahci_st.c b/pool/shard006/C/0119855_ahci_st.c new file mode 100644 index 0000000000000000000000000000000000000000..ea0ff005b86ce702e4ccd0224c5b8f14c0fcfc89 --- /dev/null +++ b/pool/shard006/C/0119855_ahci_st.c @@ -0,0 +1,253 @@ +/* + * Copyright (C) 2012 STMicroelectronics Limited + * + * Authors: Francesco Virlinzi + * Alexandre Torgue + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ahci.h" + +#define DRV_NAME "st_ahci" + +#define ST_AHCI_OOBR 0xbc +#define ST_AHCI_OOBR_WE BIT(31) +#define ST_AHCI_OOBR_CWMIN_SHIFT 24 +#define ST_AHCI_OOBR_CWMAX_SHIFT 16 +#define ST_AHCI_OOBR_CIMIN_SHIFT 8 +#define ST_AHCI_OOBR_CIMAX_SHIFT 0 + +struct st_ahci_drv_data { + struct platform_device *ahci; + struct reset_control *pwr; + struct reset_control *sw_rst; + struct reset_control *pwr_rst; + struct ahci_host_priv *hpriv; +}; + +static void st_ahci_configure_oob(void __iomem *mmio) +{ + unsigned long old_val, new_val; + + new_val = (0x02 << ST_AHCI_OOBR_CWMIN_SHIFT) | + (0x04 << ST_AHCI_OOBR_CWMAX_SHIFT) | + (0x08 << ST_AHCI_OOBR_CIMIN_SHIFT) | + (0x0C << ST_AHCI_OOBR_CIMAX_SHIFT); + + old_val = readl(mmio + ST_AHCI_OOBR); + writel(old_val | ST_AHCI_OOBR_WE, mmio + ST_AHCI_OOBR); + writel(new_val | ST_AHCI_OOBR_WE, mmio + ST_AHCI_OOBR); + writel(new_val, mmio + ST_AHCI_OOBR); +} + +static int st_ahci_deassert_resets(struct device *dev) +{ + struct st_ahci_drv_data *drv_data = dev_get_drvdata(dev); + int err; + + if (drv_data->pwr) { + err = reset_control_deassert(drv_data->pwr); + if (err) { + dev_err(dev, "unable to bring out of pwrdwn\n"); + return err; + } + } + + if (drv_data->sw_rst) { + err = reset_control_deassert(drv_data->sw_rst); + if (err) { + dev_err(dev, "unable to bring out of sw-rst\n"); + return err; + } + } + + if (drv_data->pwr_rst) { + err = reset_control_deassert(drv_data->pwr_rst); + if (err) { + dev_err(dev, "unable to bring out of pwr-rst\n"); + return err; + } + } + + return 0; +} + +static void st_ahci_host_stop(struct ata_host *host) +{ + struct ahci_host_priv *hpriv = host->private_data; + struct device *dev = host->dev; + struct st_ahci_drv_data *drv_data = dev_get_drvdata(dev); + int err; + + if (drv_data->pwr) { + err = reset_control_assert(drv_data->pwr); + if (err) + dev_err(dev, "unable to pwrdwn\n"); + } + + ahci_platform_disable_resources(hpriv); +} + +static int st_ahci_probe_resets(struct platform_device *pdev) +{ + struct st_ahci_drv_data *drv_data = platform_get_drvdata(pdev); + + drv_data->pwr = devm_reset_control_get(&pdev->dev, "pwr-dwn"); + if (IS_ERR(drv_data->pwr)) { + dev_info(&pdev->dev, "power reset control not defined\n"); + drv_data->pwr = NULL; + } + + drv_data->sw_rst = devm_reset_control_get(&pdev->dev, "sw-rst"); + if (IS_ERR(drv_data->sw_rst)) { + dev_info(&pdev->dev, "soft reset control not defined\n"); + drv_data->sw_rst = NULL; + } + + drv_data->pwr_rst = devm_reset_control_get(&pdev->dev, "pwr-rst"); + if (IS_ERR(drv_data->pwr_rst)) { + dev_dbg(&pdev->dev, "power soft reset control not defined\n"); + drv_data->pwr_rst = NULL; + } + + return st_ahci_deassert_resets(&pdev->dev); +} + +static struct ata_port_operations st_ahci_port_ops = { + .inherits = &ahci_platform_ops, + .host_stop = st_ahci_host_stop, +}; + +static const struct ata_port_info st_ahci_port_info = { + .flags = AHCI_FLAG_COMMON, + .pio_mask = ATA_PIO4, + .udma_mask = ATA_UDMA6, + .port_ops = &st_ahci_port_ops, +}; + +static struct scsi_host_template ahci_platform_sht = { + AHCI_SHT(DRV_NAME), +}; + +static int st_ahci_probe(struct platform_device *pdev) +{ + struct st_ahci_drv_data *drv_data; + struct ahci_host_priv *hpriv; + int err; + + drv_data = devm_kzalloc(&pdev->dev, sizeof(*drv_data), GFP_KERNEL); + if (!drv_data) + return -ENOMEM; + + platform_set_drvdata(pdev, drv_data); + + hpriv = ahci_platform_get_resources(pdev); + if (IS_ERR(hpriv)) + return PTR_ERR(hpriv); + + drv_data->hpriv = hpriv; + + err = st_ahci_probe_resets(pdev); + if (err) + return err; + + err = ahci_platform_enable_resources(hpriv); + if (err) + return err; + + st_ahci_configure_oob(drv_data->hpriv->mmio); + + err = ahci_platform_init_host(pdev, hpriv, &st_ahci_port_info, + &ahci_platform_sht); + if (err) { + ahci_platform_disable_resources(hpriv); + return err; + } + + return 0; +} + +#ifdef CONFIG_PM_SLEEP +static int st_ahci_suspend(struct device *dev) +{ + struct st_ahci_drv_data *drv_data = dev_get_drvdata(dev); + struct ahci_host_priv *hpriv = drv_data->hpriv; + int err; + + err = ahci_platform_suspend_host(dev); + if (err) + return err; + + if (drv_data->pwr) { + err = reset_control_assert(drv_data->pwr); + if (err) { + dev_err(dev, "unable to pwrdwn"); + return err; + } + } + + ahci_platform_disable_resources(hpriv); + + return 0; +} + +static int st_ahci_resume(struct device *dev) +{ + struct st_ahci_drv_data *drv_data = dev_get_drvdata(dev); + struct ahci_host_priv *hpriv = drv_data->hpriv; + int err; + + err = ahci_platform_enable_resources(hpriv); + if (err) + return err; + + err = st_ahci_deassert_resets(dev); + if (err) { + ahci_platform_disable_resources(hpriv); + return err; + } + + st_ahci_configure_oob(drv_data->hpriv->mmio); + + return ahci_platform_resume_host(dev); +} +#endif + +static SIMPLE_DEV_PM_OPS(st_ahci_pm_ops, st_ahci_suspend, st_ahci_resume); + +static const struct of_device_id st_ahci_match[] = { + { .compatible = "st,ahci", }, + {}, +}; +MODULE_DEVICE_TABLE(of, st_ahci_match); + +static struct platform_driver st_ahci_driver = { + .driver = { + .name = DRV_NAME, + .pm = &st_ahci_pm_ops, + .of_match_table = of_match_ptr(st_ahci_match), + }, + .probe = st_ahci_probe, + .remove = ata_platform_remove_one, +}; +module_platform_driver(st_ahci_driver); + +MODULE_AUTHOR("Alexandre Torgue "); +MODULE_AUTHOR("Francesco Virlinzi "); +MODULE_DESCRIPTION("STMicroelectronics SATA AHCI Driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard006/C/0119861_xml_sax_parser_context.c b/pool/shard006/C/0119861_xml_sax_parser_context.c new file mode 100644 index 0000000000000000000000000000000000000000..d042e4fe93a4216db06fd4aca56833143e3dfb89 --- /dev/null +++ b/pool/shard006/C/0119861_xml_sax_parser_context.c @@ -0,0 +1,222 @@ +#include + +VALUE cNokogiriXmlSaxParserContext ; + +static void deallocate(xmlParserCtxtPtr ctxt) +{ + NOKOGIRI_DEBUG_START(handler); + + ctxt->sax = NULL; + + xmlFreeParserCtxt(ctxt); + + NOKOGIRI_DEBUG_END(handler); +} + +/* + * call-seq: + * parse_io(io, encoding) + * + * Parse +io+ object with +encoding+ + */ +static VALUE +parse_io(VALUE klass, VALUE io, VALUE encoding) +{ + xmlParserCtxtPtr ctxt; + xmlCharEncoding enc = (xmlCharEncoding)NUM2INT(encoding); + + ctxt = xmlCreateIOParserCtxt(NULL, NULL, + (xmlInputReadCallback)io_read_callback, + (xmlInputCloseCallback)io_close_callback, + (void *)io, enc); + if (ctxt->sax) { + xmlFree(ctxt->sax); + ctxt->sax = NULL; + } + + return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); +} + +/* + * call-seq: + * parse_file(filename) + * + * Parse file given +filename+ + */ +static VALUE parse_file(VALUE klass, VALUE filename) +{ + xmlParserCtxtPtr ctxt = xmlCreateFileParserCtxt(StringValuePtr(filename)); + return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); +} + +/* + * call-seq: + * parse_memory(data) + * + * Parse the XML stored in memory in +data+ + */ +static VALUE +parse_memory(VALUE klass, VALUE data) +{ + xmlParserCtxtPtr ctxt; + + if (NIL_P(data)) + rb_raise(rb_eArgError, "data cannot be nil"); + if (!(int)RSTRING_LEN(data)) + rb_raise(rb_eRuntimeError, "data cannot be empty"); + + ctxt = xmlCreateMemoryParserCtxt(StringValuePtr(data), + (int)RSTRING_LEN(data)); + if (ctxt->sax) { + xmlFree(ctxt->sax); + ctxt->sax = NULL; + } + + return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); +} + +static VALUE +parse_doc(VALUE ctxt_val) +{ + xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)ctxt_val; + xmlParseDocument(ctxt); + return Qnil; +} + +static VALUE +parse_doc_finalize(VALUE ctxt_val) +{ + xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr)ctxt_val; + + if (NULL != ctxt->myDoc) + xmlFreeDoc(ctxt->myDoc); + + NOKOGIRI_SAX_TUPLE_DESTROY(ctxt->userData); + return Qnil; +} + +/* + * call-seq: + * parse_with(sax_handler) + * + * Use +sax_handler+ and parse the current document + */ +static VALUE +parse_with(VALUE self, VALUE sax_handler) +{ + xmlParserCtxtPtr ctxt; + xmlSAXHandlerPtr sax; + + if (!rb_obj_is_kind_of(sax_handler, cNokogiriXmlSaxParser)) + rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::SAX::Parser"); + + Data_Get_Struct(self, xmlParserCtxt, ctxt); + Data_Get_Struct(sax_handler, xmlSAXHandler, sax); + + /* Free the sax handler since we'll assign our own */ + if (ctxt->sax && ctxt->sax != (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) + xmlFree(ctxt->sax); + + ctxt->sax = sax; + ctxt->userData = (void *)NOKOGIRI_SAX_TUPLE_NEW(ctxt, sax_handler); + + rb_ensure(parse_doc, (VALUE)ctxt, parse_doc_finalize, (VALUE)ctxt); + + return Qnil; +} + +/* + * call-seq: + * replace_entities=(boolean) + * + * Should this parser replace entities? & will get converted to '&' if + * set to true + */ +static VALUE set_replace_entities(VALUE self, VALUE value) +{ + xmlParserCtxtPtr ctxt; + Data_Get_Struct(self, xmlParserCtxt, ctxt); + + if(Qfalse == value) + ctxt->replaceEntities = 0; + else + ctxt->replaceEntities = 1; + + return value; +} + +/* + * call-seq: + * replace_entities + * + * Should this parser replace entities? & will get converted to '&' if + * set to true + */ +static VALUE get_replace_entities(VALUE self) +{ + xmlParserCtxtPtr ctxt; + Data_Get_Struct(self, xmlParserCtxt, ctxt); + + if(0 == ctxt->replaceEntities) + return Qfalse; + else + return Qtrue; +} + +/* + * call-seq: line + * + * Get the current line the parser context is processing. + */ +static VALUE line(VALUE self) +{ + xmlParserCtxtPtr ctxt; + xmlParserInputPtr io; + + Data_Get_Struct(self, xmlParserCtxt, ctxt); + + io = ctxt->input; + if(io) + return INT2NUM(io->line); + + return Qnil; +} + +/* + * call-seq: column + * + * Get the current column the parser context is processing. + */ +static VALUE column(VALUE self) +{ + xmlParserCtxtPtr ctxt; + xmlParserInputPtr io; + + Data_Get_Struct(self, xmlParserCtxt, ctxt); + + io = ctxt->input; + if(io) + return INT2NUM(io->col); + + return Qnil; +} + +void init_xml_sax_parser_context() +{ + VALUE nokogiri = rb_define_module("Nokogiri"); + VALUE xml = rb_define_module_under(nokogiri, "XML"); + VALUE sax = rb_define_module_under(xml, "SAX"); + VALUE klass = rb_define_class_under(sax, "ParserContext", rb_cObject); + + cNokogiriXmlSaxParserContext = klass; + + rb_define_singleton_method(klass, "io", parse_io, 2); + rb_define_singleton_method(klass, "memory", parse_memory, 1); + rb_define_singleton_method(klass, "file", parse_file, 1); + + rb_define_method(klass, "parse_with", parse_with, 1); + rb_define_method(klass, "replace_entities=", set_replace_entities, 1); + rb_define_method(klass, "replace_entities", get_replace_entities, 0); + rb_define_method(klass, "line", line, 0); + rb_define_method(klass, "column", column, 0); +} diff --git a/pool/shard006/C/0119873_ags_script_for.c b/pool/shard006/C/0119873_ags_script_for.c new file mode 100644 index 0000000000000000000000000000000000000000..477e07af430cd282f6f1f39adc10178d4fb2dc46 --- /dev/null +++ b/pool/shard006/C/0119873_ags_script_for.c @@ -0,0 +1,160 @@ +/* AGS Client - Advanced GTK Sequencer Client + * Copyright (C) 2013 Joël Krähemann + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include + +#include + +void ags_script_for_class_init(AgsScriptForClass *script_for); +void ags_script_for_connectable_interface_init(AgsConnectableInterface *connectable); +void ags_script_for_init(AgsScriptFor *script_for); +void ags_script_for_connect(AgsConnectable *connectable); +void ags_script_for_disconnect(AgsConnectable *connectable); +void ags_script_for_finalize(GObject *gobject); + +AgsScriptObject* ags_script_for_launch(AgsScriptObject *script_object, GError **error); + +static gpointer ags_script_for_parent_class = NULL; + +GType +ags_script_for_get_type() +{ + static GType ags_type_script_for = 0; + + if(!ags_type_script_for){ + static const GTypeInfo ags_script_for_info = { + sizeof (AgsScriptForClass), + NULL, /* base_init */ + NULL, /* base_finalize */ + (GClassInitFunc) ags_script_for_class_init, + NULL, /* class_finalize */ + NULL, /* class_data */ + sizeof (AgsScriptFor), + 0, /* n_preallocs */ + (GInstanceInitFunc) ags_script_for_init, + }; + + static const GInterfaceInfo ags_connectable_interface_info = { + (GInterfaceInitFunc) ags_script_for_connectable_interface_init, + NULL, /* interface_finalize */ + NULL, /* interface_data */ + }; + + ags_type_script_for = g_type_register_static(AGS_TYPE_SCRIPT_CONTROLLER, + "AgsScriptFor\0", + &ags_script_for_info, + 0); + + g_type_add_interface_static(ags_type_script_for, + AGS_TYPE_CONNECTABLE, + &ags_connectable_interface_info); + } + + return (ags_type_script_for); +} + +void +ags_script_for_class_init(AgsScriptForClass *script_for) +{ + AgsScriptObjectClass *script_object; + GObjectClass *gobject; + + ags_script_for_parent_class = g_type_class_peek_parent(script_for); + + /* GObjectClass */ + gobject = (GObjectClass *) script_for; + + gobject->finalize = ags_script_for_finalize; + + /* AgsScriptObjectClass */ + script_object = (AgsScriptObjectClass *) script_for; + + script_object->launch = ags_script_for_launch; +} + +void +ags_script_for_connectable_interface_init(AgsConnectableInterface *connectable) +{ + connectable->connect = ags_script_for_connect; + connectable->disconnect = ags_script_for_disconnect; +} + +void +ags_script_for_init(AgsScriptFor *script_for) +{ + script_for->initializer = ags_script_set_new(); + script_for->loop_control = ags_script_set_new(); + script_for->step = ags_script_set_new(); +} + +void +ags_script_for_connect(AgsConnectable *connectable) +{ + /* empty */ +} + +void +ags_script_for_disconnect(AgsConnectable *connectable) +{ + /* empty */ +} + +void +ags_script_for_finalize(GObject *gobject) +{ + AgsScriptFor *script_for; + + script_for = AGS_SCRIPT_FOR(gobject); + + g_object_unref(G_OBJECT(script_for->initializer)); + g_object_unref(G_OBJECT(script_for->loop_control)); + g_object_unref(G_OBJECT(script_for->step)); + + G_OBJECT_CLASS(ags_script_for_parent_class)->finalize(gobject); +} + +AgsScriptObject* +ags_script_for_launch(AgsScriptObject *script_object, GError **error) +{ + AgsScriptFor *script_for; + AgsScriptSet *initializer, *loop_control, *step; + GError *initializer_error, *step_error, *body_error; + + script_for = AGS_SCRIPT_FOR(script_object); + + initializer = AGS_SCRIPT_SET(script_for->initializer); + loop_control = AGS_SCRIPT_SET(script_for->loop_control); + step = AGS_SCRIPT_SET(script_for->step); + + for(ags_script_object_launch(AGS_SCRIPT_OBJECT(initializer), &initializer_error); + ags_script_set_boolean_term(loop_control); + ags_script_object_launch(AGS_SCRIPT_OBJECT(step), &step_error)){ + AGS_SCRIPT_OBJECT_CLASS(ags_script_for_parent_class)->launch(script_object, body_error); + } +} + +AgsScriptFor* +ags_script_for_new() +{ + AgsScriptFor *script_for; + + script_for = (AgsScriptFor *) g_object_new(AGS_TYPE_SCRIPT_FOR, + NULL); + + return(script_for); +} diff --git a/pool/shard006/C/0119874_saj_topicListener.c b/pool/shard006/C/0119874_saj_topicListener.c new file mode 100644 index 0000000000000000000000000000000000000000..e99fc430ba86b03ec7b2d19a602be1e25edd92e8 --- /dev/null +++ b/pool/shard006/C/0119874_saj_topicListener.c @@ -0,0 +1,65 @@ +/* + * OpenSplice DDS + * + * This software and documentation are Copyright 2006 to 2013 PrismTech + * Limited and its licensees. All rights reserved. See file: + * + * $OSPL_HOME/LICENSE + * + * for full copyright notice and license terms. + * + */ + +#include "saj_utilities.h" +#include "saj_status.h" +#include "saj_topicListener.h" + +struct gapi_topicListener* +saj_topicListenerNew( + JNIEnv *env, + jobject jlistener) +{ + struct gapi_topicListener* listener; + saj_listenerData ld; + + listener = NULL; + + ld = saj_listenerDataNew(env, jlistener); + + if(ld != NULL){ + listener = gapi_topicListener__alloc(); + saj_listenerInit((struct gapi_listener*)listener); + listener->listener_data = ld; + + listener->on_inconsistent_topic = saj_topicListenerOnInconsistentTopic; + } + return listener; +} + +void +saj_topicListenerOnInconsistentTopic( + void* listenerData, + gapi_topic topic, + const gapi_inconsistentTopicStatus *status) +{ + saj_listenerData ld; + JNIEnv *env; + jobject jstatus; + jobject jtopic; + saj_returnCode rc; + + ld = saj_listenerData(listenerData); + env = *(JNIEnv**)os_threadMemGet(OS_THREAD_JVM); + + rc = saj_statusCopyOutInconsistentTopicStatus(env, + (gapi_inconsistentTopicStatus *)status, &jstatus); + + if(rc == SAJ_RETCODE_OK){ + jtopic = saj_read_java_address(topic); + (*env)->CallVoidMethod( + env, ld->jlistener, + GET_CACHED(listener_onInconsistentTopic_mid), + jtopic, jstatus); + } + +} diff --git a/pool/shard006/C/0119879_pr38948.c b/pool/shard006/C/0119879_pr38948.c new file mode 100644 index 0000000000000000000000000000000000000000..90906eebf22e3de724e301ac41557f26f8d2afe6 --- /dev/null +++ b/pool/shard006/C/0119879_pr38948.c @@ -0,0 +1,103 @@ +/* { dg-options "-fno-tree-sra" } */ +/* { dg-options "-fno-tree-sra -march=v32" { target cris-*-* } } */ +typedef unsigned char byte; +typedef unsigned int uint; +typedef int bool; +typedef struct gs_const_string_s +{ + const byte *data; +} +gs_const_string; +struct gs_matrix_s +{ + float xx, xy, yx, yy, tx, ty; +}; +typedef struct gs_matrix_s gs_matrix; +typedef long fixed; +typedef struct gs_fixed_point_s +{ + fixed x, y; +} +gs_fixed_point; +typedef struct gs_matrix_fixed_s +{ + int x; +} +gs_matrix_fixed; +int gx_path_add_curve_notes (); +static int +append_simple (const byte * glyph, const gs_matrix_fixed * pmat, void * ppath) +{ + int numContours = + (int) (((((uint) ((glyph)[0]) << 8) + (glyph)[1]) ^ 0x8000) - 0x8000); + const byte *pends = glyph + 10; + int code = 0; + { + uint i = 0; + uint np = 0; + gs_fixed_point pt = {0}; + uint reps = 0; + for (i = 0, np = 0; i < numContours; ++i) + { + bool move = ((bool) 1); + uint last_point = + (((uint) ((pends + i * 2)[0]) << 8) + (pends + i * 2)[1]); + int off_curve = 0; + gs_fixed_point cpoints[3]; + for (; np <= last_point; --reps, ++np) + { + if (move) + { + cpoints[0] = pt; + move = ((bool) 0); + } + else + { + switch (off_curve++) + { + default: + cpoints[2].x = ((cpoints[1].x + pt.x) / 2); + cpoints[2].y = ((cpoints[1].y + pt.y) / 2); + code = + gx_path_add_curve_notes (ppath, + ((cpoints[0].x + + 2 * cpoints[1].x) / 3), + ((cpoints[0].y + + 2 * cpoints[1].y) / 3), + ((2 * cpoints[1].x + + cpoints[2].x) / 3), + ((2 * cpoints[1].y + + cpoints[2].y) / 3), + cpoints[2].x, cpoints[2].y, + 0); + cpoints[0] = cpoints[2]; + case 0: + cpoints[1] = pt; + } + } + } + } + } +} +void gs_matrix_multiply (gs_matrix *, const gs_matrix *, gs_matrix *); +int +append_outline (uint glyph_index, const gs_matrix_fixed *pmat, void *ppath) +{ + gs_const_string glyph_string = {0}; + int numContours = 0; + numContours = + (int) (((((uint) ((glyph_string.data)[0]) << 8) + + (glyph_string.data)[1]) ^ 0x8000) - 0x8000); + if (numContours >= 0) + return append_simple (glyph_string.data, pmat, ppath); + { + uint flags = 0; + do + { + gs_matrix_fixed mat = {0}; + gs_matrix scale_mat = {0}; + gs_matrix_multiply (&scale_mat, (const gs_matrix *) &mat, (gs_matrix *) & mat); + } + while (flags & 32); + } +} diff --git a/pool/shard006/C/0119884_mruc.c b/pool/shard006/C/0119884_mruc.c new file mode 100644 index 0000000000000000000000000000000000000000..e385b2622539fc6d035685a5b4e60d334c84b4cd --- /dev/null +++ b/pool/shard006/C/0119884_mruc.c @@ -0,0 +1,270 @@ +/* $NoKeywords:$ */ +/** + * @file + * + * mruc.c + * + * Utility functions recovery + * + * @xrefitem bom "File Content Label" "Release Content" + * @e project: AGESA + * @e sub-project: (Proc/Recovery/Mem) + * @e \$Revision: 52577 $ @e \$Date: 2011-05-09 12:58:33 -0600 (Mon, 09 May 2011) $ + * + **/ +/***************************************************************************** +* +* Copyright (C) 2012 Advanced Micro Devices, 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 Advanced Micro Devices, Inc. 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 ADVANCED MICRO DEVICES, INC. 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. +* +* *************************************************************************** +* +*/ + +/* + *---------------------------------------------------------------------------- + * MODULES USED + * + *---------------------------------------------------------------------------- + */ + + +#include "AGESA.h" +#include "OptionMemory.h" +#include "PlatformMemoryConfiguration.h" +#include "amdlib.h" +#include "Ids.h" +#include "mrport.h" +#include "mru.h" +#include "Filecode.h" +CODE_GROUP (G2_PEI) +RDATA_GROUP (G2_PEI) + +#define FILECODE PROC_RECOVERY_MEM_MRUC_FILECODE +/*---------------------------------------------------------------------------- + * DEFINITIONS AND MACROS + * + *---------------------------------------------------------------------------- + */ + +/*---------------------------------------------------------------------------- + * TYPEDEFS AND STRUCTURES + * + *---------------------------------------------------------------------------- + */ + +/*---------------------------------------------------------------------------- + * PROTOTYPES OF LOCAL FUNCTIONS + * + *---------------------------------------------------------------------------- + */ + +VOID +STATIC +MemRecUResetTargetWTIO ( + IN OUT MEM_DATA_STRUCT *MemPtr + ); + +VOID +STATIC +MemRecUSetTargetWTIO ( + IN UINT32 Address, + IN OUT MEM_DATA_STRUCT *MemPtr + ); + + +/*---------------------------------------------------------------------------- + * EXPORTED FUNCTIONS + * + *---------------------------------------------------------------------------- + */ +/* -----------------------------------------------------------------------------*/ +/** + * + * This function returns the (Index)th UINT8 + * from an indicated test Pattern. + * + * @param[in] Pattern - encoding of test Pattern type + * @param[in] Buffer[] - buffer to be filled + * @param[in] Size - Size of the bugger + * @param[in] *StdHeader - pointer to AMD_CONFIG_PARAMS + * + */ + +VOID +MemRecUFillTrainPattern ( + IN TRAIN_PATTERN Pattern, + IN UINT8 Buffer[], + IN UINT16 Size, + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + STATIC UINT8 PatternData[2] = {0x55, 0xAA}; + + LibAmdMemFill (Buffer, PatternData[Pattern == TestPattern0 ? TestPattern1 : TestPattern0], Size, StdHeader); +} + +/* -----------------------------------------------------------------------------*/ +/** + * + * This function flushes cache lines + * + * @param[in] Address - System Address [39:8] + * @param[in,out] *MemPtr - Pointer to MEM_DATA_STRUCT + * + */ + +VOID +MemRecUProcIOClFlush ( + IN UINT32 Address, + IN OUT MEM_DATA_STRUCT *MemPtr + ) +{ + MemRecUSetTargetWTIO (Address, MemPtr); + MemRecUFlushPattern (Address); + MemRecUResetTargetWTIO (MemPtr); +} + +/*---------------------------------------------------------------------------- + * LOCAL FUNCTIONS + * + *---------------------------------------------------------------------------- + */ + +/* -----------------------------------------------------------------------------*/ +/** + * + * This function resets the target address space to Write Through IO by disabling IORRs + */ + +VOID +STATIC +MemRecUResetTargetWTIO ( + IN OUT MEM_DATA_STRUCT *MemPtr + ) +{ + S_UINT64 Smsr; + Smsr.hi = 0; + Smsr.lo = 0; + LibAmdMsrWrite (IORR0_MASK, (UINT64 *)&Smsr, &MemPtr->StdHeader); +} + +/* -----------------------------------------------------------------------------*/ +/** + * + * This function sets the target range to WT IO (using an IORR overlapping + * the already existing + * @param[in,out] *MemPtr - pointer to MEM_DATA_STRUCTURE + * @param[in] Address - System Address + * + */ + +VOID +STATIC +MemRecUSetTargetWTIO ( + IN UINT32 Address, + IN OUT MEM_DATA_STRUCT *MemPtr + ) +{ + S_UINT64 SMsr; + + SMsr.lo = Address; + SMsr.hi = 0; + LibAmdMsrWrite (IORR0_BASE,(UINT64 *)&SMsr, &MemPtr->StdHeader); // ;IORR0 Base + SMsr.hi = 0xFFFF; + SMsr.lo = 0xFC000800; + LibAmdMsrWrite (IORR0_MASK, (UINT64 *)&SMsr, &MemPtr->StdHeader); // ;64MB Mask +} + +/* -----------------------------------------------------------------------------*/ +/** + * + * Waits specified number of 10ns cycles + * @param[in,out] MemPtr - pointer to MEM_DATA_STRUCTURE + * @param[in] Count - Number of 10ns cycles to wait + * + */ + +VOID +MemRecUWait10ns ( + IN UINT32 Count, + IN OUT MEM_DATA_STRUCT *MemPtr + ) +{ + S_UINT64 SMsr; + + LibAmdMsrRead (TSC, (UINT64 *)&SMsr, &MemPtr->StdHeader); + Count += SMsr.lo; + while (SMsr.lo < Count) { + LibAmdMsrRead (TSC, (UINT64 *)&SMsr, &MemPtr->StdHeader); + } +} + +/* -----------------------------------------------------------------------------*/ +/** + * + * Find the entry of platform specific overriding table. + * + * @param[in] PlatformMemoryConfiguration - Platform config table + * @param[in] EntryType - Entry type + * @param[in] SocketID - Physical socket ID + * @param[in] ChannelID - Physical channel ID + * @param[in] DimmID - Physical Dimm ID + * + * @return NULL - entry could not be found. + * @return Pointer - points to the entry's data. + * + * ---------------------------------------------------------------------------- + */ +VOID * +MemRecFindPSOverrideEntry ( + IN PSO_TABLE *PlatformMemoryConfiguration, + IN PSO_ENTRY EntryType, + IN UINT8 SocketID, + IN UINT8 ChannelID, + IN UINT8 DimmID + ) +{ + UINT8 *Buffer; + + Buffer = PlatformMemoryConfiguration; + while (Buffer[0] != PSO_END) { + if (Buffer[0] == EntryType) { + if ((Buffer[2] & ((UINT8) 1 << SocketID)) != 0 ) { + if ((Buffer[3] & ((UINT8) 1 << ChannelID)) != 0 ) { + ASSERT ((Buffer[0] == PSO_MAX_DIMMS) ? (Buffer[5] <= MAX_DIMMS_PER_CHANNEL) : TRUE); + ASSERT ((Buffer[0] == PSO_MAX_CHIPSELS) ? (Buffer[5] <= MAX_CS_PER_CHANNEL) : TRUE); + ASSERT ((Buffer[0] == PSO_MAX_CHNLS) ? (Buffer[5] <= MAX_CHANNELS_PER_SOCKET) : TRUE); + if ((Buffer[4] & ((UINT8) 1 << DimmID)) != 0 ) { + return &Buffer[5]; + } + } + } + } + Buffer += Buffer[1] + 2; + } + return NULL; +} + diff --git a/pool/shard006/C/0119892_lua-float.c b/pool/shard006/C/0119892_lua-float.c new file mode 100644 index 0000000000000000000000000000000000000000..37c7a9529a1abb7e5e2ee246569eaaa457e64b04 --- /dev/null +++ b/pool/shard006/C/0119892_lua-float.c @@ -0,0 +1,69 @@ +#define LUA_LIB + +#include +#include +#include +#include +#include +#include + +union float_number { + double d; + int64_t i; +}; + +static bool +check_support() +{ +#ifdef _MSC_VER +#else + assert(sizeof(int64_t) == sizeof(double)); /*double must be 64bit*/ + assert(0x3ff0000000000000 == ((union float_number) {1.0}).i); /*check little-endian and IEEE 754*/ +#endif // _MSC_VER + return true; +} + +static int +lua_encode_float(lua_State* L) +{ + assert(check_support()); + + union float_number number; + number.d = lua_tonumber(L, 1); + lua_pushinteger(L, number.i); + return 1; +} + +static int +lua_decode_float(lua_State* L) +{ + assert(check_support()); + + union float_number number; + number.i = lua_tointeger(L, 1); + lua_pushnumber(L, number.d); + return 1; +} + +static int +lua_encode_tointeger(lua_State* L) +{ + lua_Number f = luaL_checknumber(L, 1); + long long i = floor(f); + lua_pushinteger(L, i); + return 1; +} + +LUAMOD_API int +luaopen_chestnut_float(lua_State* L) +{ + luaL_checkversion(L); + luaL_Reg l[] = { + {"encode", lua_encode_float}, + {"tointeger", lua_encode_tointeger}, + {"decode", lua_decode_float}, + {NULL, NULL}, + }; + luaL_newlib(L, l); + return 1; +} \ No newline at end of file diff --git a/pool/shard006/C/0119896_eap_gtc.c b/pool/shard006/C/0119896_eap_gtc.c new file mode 100644 index 0000000000000000000000000000000000000000..6f5c38eddcd057697306b5e89d30b3dca7568775 --- /dev/null +++ b/pool/shard006/C/0119896_eap_gtc.c @@ -0,0 +1,282 @@ +/* + * Copyright (C) 2007-2012 Martin Willi + * Copyright (C) 2012 revosec AG + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See . + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include "eap_gtc.h" + +#include +#include + +#define GTC_REQUEST_MSG "password" + +typedef struct private_eap_gtc_t private_eap_gtc_t; + +/** + * Private data of an eap_gtc_t object. + */ +struct private_eap_gtc_t { + + /** + * Public authenticator_t interface. + */ + eap_gtc_t public; + + /** + * ID of the server + */ + identification_t *server; + + /** + * ID of the peer + */ + identification_t *peer; + + /** + * EAP message identififier + */ + uint8_t identifier; +}; + +typedef struct eap_gtc_header_t eap_gtc_header_t; + +/** + * packed eap GTC header struct + */ +struct eap_gtc_header_t { + /** EAP code (REQUEST/RESPONSE) */ + uint8_t code; + /** unique message identifier */ + uint8_t identifier; + /** length of whole message */ + uint16_t length; + /** EAP type */ + uint8_t type; + /** type data */ + uint8_t data[]; +} __attribute__((__packed__)); + +METHOD(eap_method_t, initiate_peer, status_t, + private_eap_gtc_t *this, eap_payload_t **out) +{ + /* peer never initiates */ + return FAILED; +} + +METHOD(eap_method_t, initiate_server, status_t, + private_eap_gtc_t *this, eap_payload_t **out) +{ + eap_gtc_header_t *req; + size_t len; + + len = strlen(GTC_REQUEST_MSG); + req = alloca(sizeof(eap_gtc_header_t) + len); + req->length = htons(sizeof(eap_gtc_header_t) + len); + req->code = EAP_REQUEST; + req->identifier = this->identifier; + req->type = EAP_GTC; + memcpy(req->data, GTC_REQUEST_MSG, len); + + *out = eap_payload_create_data(chunk_create((void*)req, + sizeof(eap_gtc_header_t) + len)); + return NEED_MORE; +} + +METHOD(eap_method_t, process_peer, status_t, + private_eap_gtc_t *this, eap_payload_t *in, eap_payload_t **out) +{ + eap_gtc_header_t *res; + shared_key_t *shared; + chunk_t key; + size_t len; + + shared = lib->credmgr->get_shared(lib->credmgr, SHARED_EAP, + this->peer, this->server); + if (shared == NULL) + { + DBG1(DBG_IKE, "no EAP key found for '%Y' - '%Y'", + this->peer, this->server); + return FAILED; + } + key = shared->get_key(shared); + len = key.len; + + /* TODO: According to the draft we should "SASLprep" password, RFC4013. */ + + this->identifier = in->get_identifier(in); + res = alloca(sizeof(eap_gtc_header_t) + len); + res->length = htons(sizeof(eap_gtc_header_t) + len); + res->code = EAP_RESPONSE; + res->identifier = this->identifier; + res->type = EAP_GTC; + memcpy(res->data, key.ptr, len); + + shared->destroy(shared); + + *out = eap_payload_create_data(chunk_create((void*)res, + sizeof(eap_gtc_header_t) + len)); + return NEED_MORE; +} + +METHOD(eap_method_t, process_server, status_t, + private_eap_gtc_t *this, eap_payload_t *in, eap_payload_t **out) +{ + status_t status = FAILED; + chunk_t user, pass; + xauth_method_t *xauth; + cp_payload_t *ci, *co; + char *backend; + + user = this->peer->get_encoding(this->peer); + pass = chunk_skip(in->get_data(in), 5); + if (this->identifier != in->get_identifier(in) || !pass.len) + { + DBG1(DBG_IKE, "received invalid EAP-GTC message"); + return FAILED; + } + + /* get XAuth backend to use for credential verification. Default to PAM + * to support legacy EAP-GTC configurations */ + backend = lib->settings->get_str(lib->settings, + "%s.plugins.eap-gtc.backend", "pam", lib->ns); + xauth = charon->xauth->create_instance(charon->xauth, backend, XAUTH_SERVER, + this->server, this->peer); + if (!xauth) + { + DBG1(DBG_IKE, "creating EAP-GTC XAuth backend '%s' failed", backend); + return FAILED; + } + if (xauth->initiate(xauth, &co) == NEED_MORE) + { + /* assume that "out" contains username/password attributes */ + co->destroy(co); + ci = cp_payload_create_type(PLV1_CONFIGURATION, CFG_REPLY); + ci->add_attribute(ci, configuration_attribute_create_chunk( + PLV1_CONFIGURATION_ATTRIBUTE, XAUTH_USER_NAME, user)); + ci->add_attribute(ci, configuration_attribute_create_chunk( + PLV1_CONFIGURATION_ATTRIBUTE, XAUTH_USER_PASSWORD, pass)); + switch (xauth->process(xauth, ci, &co)) + { + case SUCCESS: + status = SUCCESS; + break; + case NEED_MORE: + /* TODO: multiple exchanges currently not supported */ + co->destroy(co); + break; + case FAILED: + default: + break; + } + ci->destroy(ci); + } + xauth->destroy(xauth); + return status; +} + +METHOD(eap_method_t, get_type, eap_type_t, + private_eap_gtc_t *this, uint32_t *vendor) +{ + *vendor = 0; + return EAP_GTC; +} + +METHOD(eap_method_t, get_msk, status_t, + private_eap_gtc_t *this, chunk_t *msk) +{ + return FAILED; +} + +METHOD(eap_method_t, get_identifier, uint8_t, + private_eap_gtc_t *this) +{ + return this->identifier; +} + +METHOD(eap_method_t, set_identifier, void, + private_eap_gtc_t *this, uint8_t identifier) +{ + this->identifier = identifier; +} + +METHOD(eap_method_t, is_mutual, bool, + private_eap_gtc_t *this) +{ + return FALSE; +} + +METHOD(eap_method_t, destroy, void, + private_eap_gtc_t *this) +{ + this->peer->destroy(this->peer); + this->server->destroy(this->server); + free(this); +} + +/** + * Generic constructor + */ +static private_eap_gtc_t *eap_gtc_create_generic(identification_t *server, + identification_t *peer) +{ + private_eap_gtc_t *this; + + INIT(this, + .public = { + .eap_method_interface = { + .get_type = _get_type, + .is_mutual = _is_mutual, + .get_msk = _get_msk, + .get_identifier = _get_identifier, + .set_identifier = _set_identifier, + .destroy = _destroy, + }, + }, + .peer = peer->clone(peer), + .server = server->clone(server), + ); + + return this; +} + +/* + * see header + */ +eap_gtc_t *eap_gtc_create_server(identification_t *server, identification_t *peer) +{ + private_eap_gtc_t *this = eap_gtc_create_generic(server, peer); + + this->public.eap_method_interface.initiate = _initiate_server; + this->public.eap_method_interface.process = _process_server; + + /* generate a non-zero identifier */ + do { + this->identifier = random(); + } while (!this->identifier); + + return &this->public; +} + +/* + * see header + */ +eap_gtc_t *eap_gtc_create_peer(identification_t *server, identification_t *peer) +{ + private_eap_gtc_t *this = eap_gtc_create_generic(server, peer); + + this->public.eap_method_interface.initiate = _initiate_peer; + this->public.eap_method_interface.process = _process_peer; + + return &this->public; +} diff --git a/pool/shard006/C/0119899_2016-5-28-1.c b/pool/shard006/C/0119899_2016-5-28-1.c new file mode 100644 index 0000000000000000000000000000000000000000..5ae36fa1c9d14cacca7d93a2e2430a9c1b60af40 --- /dev/null +++ b/pool/shard006/C/0119899_2016-5-28-1.c @@ -0,0 +1,14 @@ +#include +#include +#define LL long long + +int main(int argc, char** argv) { + int i, a, len, ans = 0; + char string[0xfffff]; + memset(string, '0', 0xfffff); + scanf("%s%d", string, &a); + for(i = 0; i < strlen(string); i++) + ans = (int) (((long long) ans * 10 + string[i] - '0') % a); + printf("%d", ans); + return 0; +} diff --git a/pool/shard006/C/0119902_miniz-extensions.c b/pool/shard006/C/0119902_miniz-extensions.c new file mode 100644 index 0000000000000000000000000000000000000000..beab7b4af243896b03e6379ba336b993cbbf2f7f --- /dev/null +++ b/pool/shard006/C/0119902_miniz-extensions.c @@ -0,0 +1,58 @@ +#include +#define MINIZ_HEADER_FILE_ONLY +#include "miniz.c" +#include "miniz-extensions.h" + +// Like mz_zip_reader_locate_file, but uses a matching predicate +// instead of a constant name. +static int find_file_match( + mz_zip_archive *zip_archive, + name_matcher_t matcher, + void* userdata) +{ + unsigned int num_files = mz_zip_reader_get_num_files(zip_archive); + for (unsigned int idx = 0; idx < num_files; idx++) { + mz_zip_archive_file_stat file_stat; + if (!mz_zip_reader_file_stat(zip_archive, idx, &file_stat)) { + return -1; + } + + if (matcher(userdata, file_stat.m_filename)) { + return idx; + } + } + + return -1; +} + +void *mzx_extract_match_to_heap( + const char *pZip_filename, + name_matcher_t matcher, + void* userdata, + size_t *pSize, + mz_uint flags) +{ + int file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!matcher)) + return NULL; + + // Inlined MZ_CLEAR_OBJ(zip_archive); + memset(&zip_archive, 0, sizeof(zip_archive)); + if (!mz_zip_reader_init_file( + &zip_archive, + pZip_filename, + flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return NULL; + + if ((file_index = find_file_match(&zip_archive, matcher, userdata)) >= 0) + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + + mz_zip_reader_end(&zip_archive); + return p; +} diff --git a/pool/shard006/C/0119906_memory.c b/pool/shard006/C/0119906_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..a64a55e0367909641318a03c86cd536b6517b8f3 --- /dev/null +++ b/pool/shard006/C/0119906_memory.c @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2005 iptelorg GmbH + * + * This file is part of ser, a free SIP server. + * + * ser 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 + * + * For a license to use the ser software under conditions + * other than those described here, or to purchase support for this + * software, please contact iptel.org by e-mail at the following addresses: + * info@iptel.org + * + * ser is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* Common Data Structures - functions for memory allocation and deallocation + * and may be other memory management. */ + +#include +#include +#include +#include +#include + +#ifdef TRACE_CDS_MEMORY + +cds_mutex_t *mem_mutex = NULL; +int *allocated_cnt = NULL; +char *debug_file = "/tmp/mem.log"; + +#define write_debug(s,args...) if (1) { \ + FILE *f = fopen(debug_file, "a"); \ + if (f) { \ + fprintf(f,s,##args); \ + fclose(f); \ + } \ + TRACE_LOG(s,##args); \ +} + +void *debug_malloc(int size, const char *file, int line) +{ + void *m = NULL; + if (allocated_cnt && mem_mutex) { + cds_mutex_lock(mem_mutex); + (*allocated_cnt)++; + cds_mutex_unlock(mem_mutex); + } +#ifdef SER + m = shm_malloc(size); +#else + m = malloc(size); +#endif + write_debug("ALLOC %p size %u from %s(%d)\n", m, size, file, line); + /* LOG(L_INFO, "%p\n", m); */ + return m; +} + +void debug_free(void *block, const char *file, int line) +{ + if (allocated_cnt && mem_mutex) { + cds_mutex_lock(mem_mutex); + (*allocated_cnt)--; + cds_mutex_unlock(mem_mutex); + } +#ifdef SER + shm_free(block); +#else + free(block); +#endif + write_debug("FREE %p from %s(%d)\n", block, file, line); +} + +void *debug_malloc_ex(unsigned int size) +{ + return debug_malloc(size, "", 0); +} + +void debug_free_ex(void *block) +{ + debug_free(block, "", 0); +} + +void cds_memory_trace_init() +{ + cds_mutex_init(mem_mutex); + allocated_cnt = cds_malloc(sizeof(int)); + *allocated_cnt = 0; +} + +void cds_memory_trace(char *dst, int dst_len) +{ + if (allocated_cnt && mem_mutex) { + cds_mutex_lock(mem_mutex); + snprintf(dst, dst_len, "There are allocated: %d memory blocks\n", *allocated_cnt); + cds_mutex_unlock(mem_mutex); + } +} + +#else /* ! CDS_TRACE_MEMORY */ + +#ifdef SER + +void* shm_malloc_x(unsigned int size) +{ + return shm_malloc(size); +} + +void shm_free_x(void *ptr) +{ + shm_free(ptr); +} + +#endif + +#endif diff --git a/pool/shard006/C/0119907_main.c b/pool/shard006/C/0119907_main.c new file mode 100644 index 0000000000000000000000000000000000000000..72dc8676fa1892148ebca292ecd503d245e08cb5 --- /dev/null +++ b/pool/shard006/C/0119907_main.c @@ -0,0 +1,41 @@ +#include +#include + +EXTERN_C void xs_init (pTHX); + +EXTERN_C void boot_DynaLoader (pTHX_ CV* cv); + +EXTERN_C void +xs_init(pTHX) +{ + char *file = __FILE__; + dXSUB_SYS; + + /* DynaLoader is a special case */ + newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file); +} + +static PerlInterpreter *my_perl; + +int main(int argc, char **argv, char **env) { + char *cmd[argc+1]; + int i; + + cmd[0] = ""; + cmd[1] = "/usr/lib/vmprobe/main.pl"; + for(i = 1; i < argc; i++) { + cmd[i+1] = argv[i]; + } + + PERL_SYS_INIT3(&argc,&argv,&env); + my_perl = perl_alloc(); + perl_construct(my_perl); + + perl_parse(my_perl, xs_init, argc+1, cmd, (char **)NULL); + PL_exit_flags |= PERL_EXIT_DESTRUCT_END; + perl_run(my_perl); + + perl_destruct(my_perl); + perl_free(my_perl); + PERL_SYS_TERM(); +} diff --git a/pool/shard006/C/0119910_avx512f-vcvtpd2udq-2.c b/pool/shard006/C/0119910_avx512f-vcvtpd2udq-2.c new file mode 100644 index 0000000000000000000000000000000000000000..24788d97a441af1ce845d5d8a3a4a701b6ff4720 --- /dev/null +++ b/pool/shard006/C/0119910_avx512f-vcvtpd2udq-2.c @@ -0,0 +1,57 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -mavx512f" } */ +/* { dg-require-effective-target avx512f } */ + +#define AVX512F + +#include "avx512f-helper.h" + +#define SRC_SIZE ((AVX512F_LEN) / 64) +#include "avx512f-mask-type.h" +#define DST_SIZE ((AVX512F_LEN_HALF) / 32) + +static void +CALC (double *s, unsigned *r) +{ + int i; + + for (i = 0; i < DST_SIZE; i++) + { + r[i] = (unsigned) (s[i] + 0.5); + } +} + +static void +TEST (void) +{ + UNION_TYPE (AVX512F_LEN, d) s; + UNION_TYPE (AVX512F_LEN_HALF, i_d) res1, res2, res3; + MASK_TYPE mask = MASK_VALUE; + unsigned res_ref[DST_SIZE] = { 0 }; + int i; + + for (i = 0; i < SRC_SIZE; i++) + { + s.a[i] = 123.456 * (i + 2000); + } + + for (i = 0; i < DST_SIZE; i++) + res2.a[i] = DEFAULT_VALUE; + + res1.x = INTRINSIC (_cvtpd_epu32) (s.x); + res2.x = INTRINSIC (_mask_cvtpd_epu32) (res2.x, mask, s.x); + res3.x = INTRINSIC (_maskz_cvtpd_epu32) (mask, s.x); + + CALC (s.a, res_ref); + + if (UNION_CHECK (AVX512F_LEN_HALF, i_d) (res1, res_ref)) + abort (); + + MASK_MERGE (i_d) (res_ref, mask, SRC_SIZE); + if (UNION_CHECK (AVX512F_LEN_HALF, i_d) (res2, res_ref)) + abort (); + + MASK_ZERO (i_d) (res_ref, mask, SRC_SIZE); + if (UNION_CHECK (AVX512F_LEN_HALF, i_d) (res3, res_ref)) + abort (); +} diff --git a/pool/shard006/C/0119912_gdt.c b/pool/shard006/C/0119912_gdt.c new file mode 100644 index 0000000000000000000000000000000000000000..10efb0e4e6f8b8162a20b2bb84c17fda50fdc5c2 --- /dev/null +++ b/pool/shard006/C/0119912_gdt.c @@ -0,0 +1,169 @@ +/* + Orion OS, The educational operatingsystem + Copyright (C) 2011 Bart Kuivenhoven + + 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 . +*/ + +#ifdef __INTEL +#include +#include +#include + +gdtEntry_t GDT[5]; + +/** + * The code below holds ifdefs called FAST. This is because the code that's + * between those statements uses full registers at a time, in stead of the + * individual bits. The limitations opposed by both pieces of code are the same + * though. + * + * For performance reasons, compile with the FAST flag enabled. We've defaulted + * not to, because the other piece of code is better for educational use. + */ + +#ifdef FAST +void setEntry(int num, unsigned int base, unsigned int limit, + unsigned char access, unsigned char gran); +#else +void setEntry(int num, unsigned int base, unsigned int limit, + unsigned int type, unsigned int dpl); +#endif + +#define ENTRIES 5 + +/// All this does is set the general descriptor table to a flat memory model. +/// For all I know this is only necessary on intel machines as they support +/// segmentation. We'll use paging for our memory protection. + +void setGDT() +{ + #ifdef GDTTEST + printf("GDT ptr size\tGDT Entry size\n"); + printhex(sizeof(gdt_t)); printf("\t\t"); + printhex(sizeof(gdtEntry_t)); putc('\n'); + #endif + + /* + * Set up a GDT. (1) + */ + #ifdef FAST + setEntry(0, 0, 0, 0, 0); // Null segment + setEntry(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Code segment + setEntry(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // Data segment + setEntry(3, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User mode code segment + setEntry(4, 0, 0xFFFFFFFF, 0xF2, 0xCF); // User mode data segment + #else + //void setEntry (int num, unsigned int base, + //unsigned int limit, unsigned int type, unsigned int dpl) + setEntry (0, 0, 0, 0, 0); + setEntry (1, 0, 0xFFFFFFFF, 0xA, 0x0); + setEntry (2, 0, 0xFFFFFFFF, 0x2, 0x0); + setEntry (3, 0, 0xFFFFFFFF, 0xA, 0x3); + setEntry (4, 0, 0xFFFFFFFF, 0x2, 0x3); + #endif + + /* + * Load the GDT into the CPU.(1) + */ + + struct gdtPtr gdt; + gdt.limit = sizeof(gdtEntry_t)*ENTRIES; + gdt.baseAddr = (unsigned int)((void*)GDT); + #ifdef GDTTEST + printhex(gdt->limit); putc('\t'); + printhex(gdt->baseAddr); putc('\n'); + printf("checkpoint 1\n"); + + int i; + for (i = 0; i < ENTRIES*2; i++) + { + int *out = ((void*)GDT)+i*4; + printhex(*out); putc('\n'); + } + + #endif + lgdt(&gdt); + #ifdef GDTTEST + printf("checkpoint 2\n"); + #endif +} + +#ifdef X86 +#ifdef FAST +void setEntry(int num, unsigned int base, unsigned int limit, + unsigned char access, unsigned char gran) +{ + GDT[num].base_low = (base & 0xFFFFFF); + GDT[num].base_high = (base >> 24) & 0xFF; + + GDT[num].limit_low = (limit & 0xFFFF); + GDT[num].granularity = (limit >> 16) & 0x0F; + + GDT[num].granularity |= gran & 0xF0; + GDT[num].access = access; +} +#else +void setEntry (int num, unsigned int base, unsigned int limit, + unsigned int type, unsigned int dpl) +{ + if (num == 0) + { + GDT[0].limit = 0; + GDT[0].baseLow = 0; + GDT[0].type = 0; + GDT[0].s = 0; + GDT[0].dpl = 0; + GDT[0].one = 0; + GDT[0].limitHigh = 0; + GDT[0].avl = 0; + GDT[0].zero = 0; + GDT[0].mode = 0; + GDT[0].granularity = 0; + GDT[0].baseHigh = 0; + } + else + { + limit = limit >> 8; + GDT[num].baseLow = (base & 0xFFFFFF); + GDT[num].baseHigh = (base >> 24) & 0xFF; + GDT[num].limit = (limit & 0xFFFF); + GDT[num].limitHigh = (limit >> 16) & 0xF; + GDT[num].dpl = dpl & 0x3; + GDT[num].type = type & 0xF; + GDT[num].zero = 0; + GDT[num].one = 1; + GDT[num].granularity= 1; + GDT[num].s = 1; + GDT[num].mode = 1; + } +} +#endif +#endif + +#endif +/* +(1) A GDT or general descriptor table is a table that holds the segment data. + To get to know more about the data, see GDT.h. + Whenever an application does a memory reference it is passed by the GDT to + figure out to which address the address given should be mapped. + The addresses on the intel machine are built up out of segment registers + and the pointer itself. + + The segment registers hold an index into the GDT. + + For more info on segmentation, read volume 1 of the basic architecture + documentation by intel. +*/ + diff --git a/pool/shard006/C/0119919_exynos5-uart.c b/pool/shard006/C/0119919_exynos5-uart.c new file mode 100644 index 0000000000000000000000000000000000000000..ad6dab01022f256de3dd6e96341fbd62fcca9154 --- /dev/null +++ b/pool/shard006/C/0119919_exynos5-uart.c @@ -0,0 +1,328 @@ +/* + * xen/drivers/char/exynos5-uart.c + * + * Driver for ARM PrimeCell PL011 UART. + * + * Anthony PERARD + * Copyright (c) 2012 Citrix Systems. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include + +// fifo does not work +#define EXYNOS_UART_USE_FIFO + +static struct exynos5_uart { + unsigned int baud, clock_hz, data_bits, parity, stop_bits, irq; + volatile uint32_t *regs; + struct irqaction irqaction; +} exynos5_com[4] = {{0}}; + +/* register addresses */ +#define ULCON (0x00/4) +#define UCON (0x04/4) +#define UFCON (0x08/4) +#define UMCON (0x0c/4) +#define UTRSTAT (0x10/4) +#define UERSTAT (0x14/4) +#define UFSTAT (0x18/4) +#define UMSTAT (0x1c/4) +#define UTXH (0x20/4) +#define URXH (0x24/4) +#define UBRDIV (0x28/4) +#define UFRACVAL (0x2c/4) +#define UINTP (0x30/4) +#define UINTS (0x34/4) +#define UINTM (0x38/4) + +/* ULCON */ +#define RXIRQ (0x1<<0) +#define RXDMA (0x2<<0) +#define TXIRQ (0x1<<2) +#define TXDMA (0x2<<2) + +/* UFCON */ +#define FIFO_TX_RESET (1<<2) +#define FIFO_RX_RESET (1<<1) +#define FIFO_EN (1<<0) + +/* UMCON */ +#define INT_EN (1<<3) + +/* UTRSTAT */ +#define TXE (1<<2) +#define TXFE (1<<1) +#define RXDR (1<<0) + +/* Interrupt bits (UINTP, UINTS, UINTM) */ +#define MODEM (1<<3) +#define TXD (1<<2) +#define ERROR (1<<1) +#define RXD (1<<0) +#define ALLI (MODEM|TXD|ERROR|RXD) + +/* These parity settings can be ORed directly into the ULCON. */ +#define PARITY_NONE (0) +#define PARITY_ODD (0x4) +#define PARITY_EVEN (0x5) +#define FORCED_CHECKED_AS_ONE (0x6) +#define FORCED_CHECKED_AS_ZERO (0x7) + +static void exynos5_uart_interrupt(int irq, void *data, struct cpu_user_regs *regs) +{ + struct serial_port *port = data; + struct exynos5_uart *uart = port->uart; + unsigned int status = uart->regs[UINTP]; + + if ( status ) + { + do + { + // clear all pending interrept + // but should take care of ERROR and MODEM + + if (status & ERROR) { + int error_bit = uart->regs[UERSTAT] & 0xf; + if (error_bit & (1<<0)) + printk("uart: overrun error\n"); + if (error_bit & (1<<1)) + printk("uart: parity error\n"); + if (error_bit & (1<<2)) + printk("uart: frame error\n"); + if (error_bit & (1<<3)) + printk("uart: break detected\n"); + uart->regs[UINTP] = ERROR; + } + + + if ( status & (RXD|ERROR) ) { + /* uart->regs[UINTM] |= RXD|ERROR; */ + serial_rx_interrupt(port, regs); + /* uart->regs[UINTM] &= ~(RXD|ERROR); */ + uart->regs[UINTP] = RXD|ERROR; + } + + if ( status & (TXD|MODEM) ) { + /* uart->regs[UINTM] |= TXD|MODEM; */ + serial_tx_interrupt(port, regs); + /* uart->regs[UINTM] &= ~(TXD|MODEM); */ + uart->regs[UINTP] = TXD|MODEM; + } + + status = uart->regs[UINTP]; + } while (status != 0); + } +} + +static void __init exynos5_uart_init_preirq(struct serial_port *port) +{ + struct exynos5_uart *uart = port->uart; + unsigned int divisor; + + /* reset, TX/RX disables */ + uart->regs[UCON] = 0x0; + + /* No Interrupt, auto flow control */ + uart->regs[UMCON] = 0x0; + + /* Line control and baud-rate generator. */ + if ( uart->baud != BAUD_AUTO ) + { + /* Baud rate specified: program it into the divisor latch. */ + // div_val = ubrdiv + ufracval/16 + // or + // div_val = (clock_uart/(baud*16))-1 + divisor = ((uart->clock_hz) / (uart->baud)) - 1; + // FIXME will use a hacked divisor, assuming the src clock and bauds + uart->regs[UFRACVAL] = 53; + uart->regs[UBRDIV] = 4; + /* uart->regs[UFRACVAL] = divisor & 0xf; */ + /* uart->regs[UBRDIV] = divisor >> 4; */ + } + else + { + // TODO, should be updated + /* Baud rate already set: read it out from the divisor latch. */ + //divisor = (uart->regs[IBRD] << 6) | uart->regs[FBRD]; + //uart->baud = (uart->clock_hz << 2) / divisor; + } + uart->regs[ULCON] = ( (uart->data_bits - 5) << 0 + | ((uart->stop_bits - 1) << 2) + | uart->parity << 3 ); + + /* Mask and clear the interrupts */ + uart->regs[UINTM] = ALLI; + uart->regs[UINTP] = ALLI; + + /* enable FIFO */ + uart->regs[UFCON] = FIFO_TX_RESET | FIFO_RX_RESET; + while (uart->regs[UFCON] & (FIFO_TX_RESET | FIFO_RX_RESET)) + ; + // reset FIFO_TX_RESET | FIFO_RX_RESET | +#ifdef EXYNOS_UART_USE_FIFO + uart->regs[UFCON] = (0x6<<8)|FIFO_EN; +#else + uart->regs[UFCON] = 0; +#endif + + + /* Enable the UART for RX and TX */ + // level tx/rx inturrupt,only rx + // enable rx timeout interrupt + uart->regs[UCON] = (0<<9)|(0<<8)|RXIRQ|TXIRQ|(1<<7); +} + +static void __init exynos5_uart_init_postirq(struct serial_port *port) +{ + struct exynos5_uart *uart = port->uart; + int rc; + + if ( uart->irq > 0 ) + { + uart->irqaction.handler = exynos5_uart_interrupt; + uart->irqaction.name = "exynos5_uart"; + uart->irqaction.dev_id = port; + if ( (rc = setup_irq(uart->irq, &uart->irqaction)) != 0 ) + printk("ERROR: Failed to allocate exynos5_uart IRQ %d\n", uart->irq); + + /* Unmask interrupts */ + uart->regs[UINTM] = 0; //MODEM|TXD|ERROR; // only have rx interrupt + + /* Clear pending error interrupts */ + uart->regs[UINTP] = ALLI; + + /* Enable interrupts */ + uart->regs[UMCON] |= INT_EN; + } +} + +static void exynos5_uart_suspend(struct serial_port *port) +{ + BUG(); // XXX +} + +static void exynos5_uart_resume(struct serial_port *port) +{ + BUG(); // XXX +} + +static unsigned int exynos5_uart_tx_ready(struct serial_port *port) +{ + struct exynos5_uart *uart = port->uart; + +#ifdef EXYNOS_UART_USE_FIFO + // Tx FIFO full + if (uart->regs[UFSTAT] & (1<<24)) + return 0; + else + { + int x = 16 - ((uart->regs[UFSTAT] >> 16) & 0xff); + // Tx FIFO count + if (x > 0) + return x; + else if (x == 0) + return 0; + else { + panic("unwanted value: %d\n", x); + return 0; + } + } +#else + return uart->regs[UTRSTAT] & TXFE ? 1 : 0; +#endif +} + +static void exynos5_uart_putc(struct serial_port *port, char c) +{ + struct exynos5_uart *uart = port->uart; + uart->regs[UTXH] = (uint32_t) (unsigned char) c; +} + +static int exynos5_uart_getc(struct serial_port *port, char *pc) +{ + struct exynos5_uart *uart = port->uart; + +#ifdef EXYNOS_UART_USE_FIFO + // check if rx fifo is full or if there is something in it + if ( (uart->regs[UFSTAT] & (1<<8)) || (uart->regs[UFSTAT] & 0xff)) + { + *pc = uart->regs[URXH] & 0xff; + return 1; + } + else + return 0; +#else + if ( !(uart->regs[UTRSTAT] & RXDR) ) + return 0; + *pc = uart->regs[URXH] & 0xff; + return 1; +#endif +} + +static int __init exynos5_uart_irq(struct serial_port *port) +{ + struct exynos5_uart *uart = port->uart; + if ( uart->irq > 0 ) + return uart->irq; + else + return -1; +} + +static struct uart_driver __read_mostly exynos5_uart_driver = { + .init_preirq = exynos5_uart_init_preirq, + .init_postirq = exynos5_uart_init_postirq, + .endboot = NULL, + .suspend = exynos5_uart_suspend, + .resume = exynos5_uart_resume, + .tx_ready = exynos5_uart_tx_ready, + .putc = exynos5_uart_putc, + .getc = exynos5_uart_getc, + .irq = exynos5_uart_irq +}; + +void __init exynos5_uart_init(int index, unsigned long register_base_address) +{ + // in device tree: compatible = "samsung,exynos4210-uart" + // node: serial@ + struct exynos5_uart *uart; + + if ( (index < 0) || (index > 4) ) + return; + + uart = &exynos5_com[index]; + + /* uart->clock_hz = 0x16e3600; */ + uart->baud = BAUD_AUTO;//115200; + uart->data_bits = 8; + uart->parity = PARITY_NONE; + uart->stop_bits = 1; + uart->irq = 32+51 + index; /* TODO Need to find this from devicetree */ + uart->regs = (uint32_t *) register_base_address; + + /* Register with generic serial driver. */ + serial_register_uart(uart - exynos5_com, &exynos5_uart_driver, uart); +} + +/* + * Local variables: + * mode: C + * c-set-style: "BSD" + * c-basic-offset: 4 + * indent-tabs-mode: nil + * End: + */ diff --git a/pool/shard006/C/0119920_tarea4_4a.c b/pool/shard006/C/0119920_tarea4_4a.c new file mode 100644 index 0000000000000000000000000000000000000000..ac030afca847659c2992a0278f63c9d129f3ff7c --- /dev/null +++ b/pool/shard006/C/0119920_tarea4_4a.c @@ -0,0 +1,26 @@ +#include +#include +#include + +char *duplica_string(char *s){ + char *p; + + p = malloc(strlen(s)+1); /* sumamos uno para almacenar el caracter '\0'*/ + if(p!=NULL) + strcpy(p,s); + + return p; +} + +int main(void){ + char *s = malloc( sizeof(char) * sizeof("Campos verdes")) ; + char *s_duplicado; + + s = "Campos verdes"; + s_duplicado = duplica_string(s); + printf("%s\n", s_duplicado); + + free(s); + free(s_duplicado); + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C/0119921_s_ldexp.c b/pool/shard006/C/0119921_s_ldexp.c new file mode 100644 index 0000000000000000000000000000000000000000..f54cc3e007155df8b4f92f7bb244e7e65a24db10 --- /dev/null +++ b/pool/shard006/C/0119921_s_ldexp.c @@ -0,0 +1,28 @@ + +/* @(#)s_ldexp.c 1.3 95/01/18 */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include "fdlibm.h" +#include + +#ifdef __STDC__ + double ldexp(double value, int exp) +#else + double ldexp(value, exp) + double value; int exp; +#endif +{ + if(!finite(value)||value==0.0) return value; + value = scalbn(value,exp); + if(!finite(value)||value==0.0) errno = ERANGE; + return value; +} diff --git a/pool/shard006/C/0119922_coll_basic_allgatherv.c b/pool/shard006/C/0119922_coll_basic_allgatherv.c new file mode 100644 index 0000000000000000000000000000000000000000..027499298d8ae2821a7e700a0a1c387fcd65982a --- /dev/null +++ b/pool/shard006/C/0119922_coll_basic_allgatherv.c @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2015 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2005 The Regents of the University of California. + * All rights reserved. + * Copyright (c) 2012 Oak Ridge National Labs. All rights reserved. + * Copyright (c) 2015 Research Organization for Information Science + * and Technology (RIST). All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "ompi_config.h" +#include "coll_basic.h" + +#include "mpi.h" +#include "ompi/datatype/ompi_datatype.h" +#include "ompi/constants.h" +#include "ompi/mca/coll/coll.h" +#include "ompi/mca/coll/base/coll_tags.h" +#include "coll_basic.h" + + +/* + * allgatherv_inter + * + * Function: - allgatherv using other MPI collectives + * Accepts: - same as MPI_Allgatherv() + * Returns: - MPI_SUCCESS or error code + */ +int +mca_coll_basic_allgatherv_inter(const void *sbuf, int scount, + struct ompi_datatype_t *sdtype, + void *rbuf, const int *rcounts, const int *disps, + struct ompi_datatype_t *rdtype, + struct ompi_communicator_t *comm, + mca_coll_base_module_t *module) +{ + int rsize, err, i; + int *scounts, *sdisps; + + rsize = ompi_comm_remote_size(comm); + + scounts = (int *) malloc(2 * rsize * sizeof(int)); + sdisps = scounts + rsize; + if (NULL == scounts) { + return OMPI_ERR_OUT_OF_RESOURCE; + } + + for (i = 0; i < rsize; i++) { + scounts[i] = scount; + sdisps[i] = 0; + } + + err = comm->c_coll.coll_alltoallv(sbuf, scounts, sdisps, sdtype, + rbuf, rcounts, disps, rdtype, comm, + comm->c_coll.coll_alltoallv_module); + + if (NULL != scounts) { + free(scounts); + } + + return err; +} diff --git a/pool/shard006/C/0119923_redc_2.c b/pool/shard006/C/0119923_redc_2.c new file mode 100644 index 0000000000000000000000000000000000000000..a15879d4a298ff4b2b63377a35543a05e48a7e16 --- /dev/null +++ b/pool/shard006/C/0119923_redc_2.c @@ -0,0 +1,98 @@ +/* mpn_redc_2. Set cp[] <- up[]/R^n mod mp[]. Clobber up[]. + mp[] is n limbs; up[] is 2n limbs. + + THIS IS AN INTERNAL FUNCTION WITH A MUTABLE INTERFACE. IT IS ONLY + SAFE TO REACH THIS FUNCTION THROUGH DOCUMENTED INTERFACES. + +Copyright (C) 2000, 2001, 2002, 2004, 2008 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 3 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. If not, see http://www.gnu.org/licenses/. */ + +#include "mpir.h" +#include "gmp-impl.h" +#include "longlong.h" + + +#if GMP_NAIL_BITS != 0 +#error not supported +#endif + +/* For testing purposes, define our own mpn_addmul_2 if there is none already + available. */ +#ifndef HAVE_NATIVE_mpn_addmul_2 +mp_limb_t +mpn_addmul_2 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_srcptr vp) +{ + rp[n] = mpn_addmul_1 (rp, up, n, vp[0]); + return mpn_addmul_1 (rp + 1, up, n, vp[1]); +} +#endif + +#if defined (__GNUC__) && defined (__ia64) && W_TYPE_SIZE == 64 +#define umul2low(ph, pl, uh, ul, vh, vl) \ + do { \ + mp_limb_t _ph, _pl; \ + __asm__ ("xma.hu %0 = %3, %5, f0\n\t" \ + "xma.l %1 = %3, %5, f0\n\t" \ + ";;\n\t" \ + "xma.l %0 = %3, %4, %0\n\t" \ + ";;\n\t" \ + "xma.l %0 = %2, %5, %0" \ + : "=&f" (ph), "=&f" (pl) \ + : "f" (uh), "f" (ul), "f" (vh), "f" (vl)); \ + } while (0) +#endif + +#ifndef umul2low +#define umul2low(ph, pl, uh, ul, vh, vl) \ + do { \ + mp_limb_t _ph, _pl; \ + umul_ppmm (_ph, _pl, ul, vl); \ + (ph) = _ph + (ul) * (vh) + (uh) * (vl); \ + (pl) = _pl; \ + } while (0) +#endif + +void +mpn_redc_2 (mp_ptr rp, mp_ptr up, mp_srcptr mp, mp_size_t n, mp_srcptr mip) +{ + mp_limb_t q[2]; + mp_size_t j; + mp_limb_t upn; + mp_limb_t cy; + + ASSERT (n > 0); + ASSERT_MPN (up, 2*n); + + if ((n & 1) != 0) + { + up[0] = mpn_addmul_1 (up, mp, n, (up[0] * mip[0]) & GMP_NUMB_MASK); + up++; + } + + for (j = n - 2; j >= 0; j -= 2) + { + umul2low (q[1], q[0], mip[1], mip[0], up[1], up[0]); + upn = up[n]; /* mpn_addmul_2 overwrites this */ + up[1] = mpn_addmul_2 (up, mp, n, q); + up[0] = up[n]; + up[n] = upn; + up += 2; + } + cy = mpn_add_n (rp, up, up - n, n); + if (cy != 0) + mpn_sub_n (rp, rp, mp, n); +} diff --git a/pool/shard006/C/0119924_buoh-comic-list.c b/pool/shard006/C/0119924_buoh-comic-list.c new file mode 100644 index 0000000000000000000000000000000000000000..c56b454640e97f4ae359b14974235438b9758508 --- /dev/null +++ b/pool/shard006/C/0119924_buoh-comic-list.c @@ -0,0 +1,244 @@ +/* + * 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 Library 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. + * + * Authors: Pablo Arroyo Loma (zioma) + * Esteban Sanchez Muñoz (steve-o) + * Carlos García Campos + */ + +#include +#include +#include + +#include "buoh-application.h" +#include "buoh-comic-list.h" + +/** + * BuohComicList: + * @tree_view: The #GtkTreeView displaying the list subscribed comic series. + * @model: The model of @tree_view. + * @comic_manager: Manager representing the currently selected series in the @tree_view. + * + * A widget displaying the list of subscribed comic series for switching between them. + */ + +struct _BuohComicList { + GtkBin parent; + + GtkWidget *tree_view; + GtkTreeModel *model; + BuohComicManager *comic_manager; + + BuohView *view; +}; + +static void buoh_comic_list_init (BuohComicList *buoh_comic_list); +static void buoh_comic_list_class_init (BuohComicListClass *klass); +static void buoh_comic_list_finalize (GObject *object); + +static void buoh_comic_list_get_preferred_width (GtkWidget *widget, + gint *minimum, + gint *natural); +static void buoh_comic_list_size_allocate (GtkWidget *widget, + GtkAllocation *allocation); +static void buoh_comic_list_selection_changed (GtkTreeSelection *selection, + gpointer gdata); +static gboolean buoh_comic_list_visible (GtkTreeModel *model, + GtkTreeIter *iter, + gpointer gdata); + +G_DEFINE_FINAL_TYPE (BuohComicList, buoh_comic_list, GTK_TYPE_BIN) + +static void +buoh_comic_list_selection_changed (GtkTreeSelection *selection, gpointer gdata) +{ + BuohComicList *comic_list = BUOH_COMIC_LIST (gdata); + GtkTreeModel *model; + GtkTreeIter iter; + GObject *comic_manager; + BuohComic *comic; + + if (gtk_tree_selection_get_selected (selection, &model, &iter)) { + gtk_tree_model_get (model, &iter, + COMIC_LIST_COMIC_MANAGER, &comic_manager, + -1); + + comic_list->comic_manager = BUOH_COMIC_MANAGER (comic_manager); + comic = buoh_comic_manager_get_current (comic_list->comic_manager); + g_object_unref (comic_manager); + + buoh_view_set_comic (comic_list->view, comic); + buoh_debug ("selection changed: set comic"); + } else { + if (comic_list->view != NULL) { + buoh_view_clear (comic_list->view); + } + } +} + +static gboolean +buoh_comic_list_visible (GtkTreeModel *model, + GtkTreeIter *iter, + gpointer gdata) +{ + gboolean visible = FALSE; + + gtk_tree_model_get (model, iter, COMIC_LIST_VISIBLE, &visible, -1); + + return visible; +} + +static void +buoh_comic_list_init (BuohComicList *buoh_comic_list) +{ + gtk_widget_init_template (GTK_WIDGET (buoh_comic_list)); +} + +static void +buoh_comic_list_class_init (BuohComicListClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); + + widget_class->get_preferred_width = buoh_comic_list_get_preferred_width; + widget_class->size_allocate = buoh_comic_list_size_allocate; + + object_class->finalize = buoh_comic_list_finalize; + + gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/buoh/ui/comic-list.ui"); + + gtk_widget_class_bind_template_child (widget_class, BuohComicList, tree_view); + + gtk_widget_class_bind_template_callback (widget_class, buoh_comic_list_selection_changed); +} + +static void +buoh_comic_list_finalize (GObject *object) +{ + BuohComicList *comic_list = BUOH_COMIC_LIST (object); + + buoh_debug ("comic-list finalize"); + + if (comic_list->model) { + g_object_unref (comic_list->model); + comic_list->model = NULL; + } + + if (G_OBJECT_CLASS (buoh_comic_list_parent_class)->finalize) { + (* G_OBJECT_CLASS (buoh_comic_list_parent_class)->finalize) (object); + } +} + +static void +buoh_comic_list_get_preferred_width (GtkWidget *widget, + gint *minimum, + gint *natural) +{ + GtkBin *bin = GTK_BIN (widget); + GtkWidget *child; + gint child_minimum; + gint child_natural; + + child = gtk_bin_get_child (bin); + + if (child && gtk_widget_get_visible (child)) { + gtk_widget_get_preferred_width (child, + &child_minimum, + &child_natural); + /* we need some extra size */ + *minimum = child_minimum + 100; + *natural = child_natural + 100; + } else { + *minimum = 0; + *natural = 0; + } +} + +static void +buoh_comic_list_size_allocate (GtkWidget *widget, GtkAllocation *allocation) +{ + GtkBin *bin = GTK_BIN (widget); + GtkWidget *child; + + child = gtk_bin_get_child (bin); + + gtk_widget_set_allocation (widget, allocation); + + if (child && gtk_widget_get_visible (child)) { + gtk_widget_size_allocate (child, allocation); + + /* we need some extra size */ + allocation->width += 100; + } +} + +GtkWidget * +buoh_comic_list_new (void) +{ + return GTK_WIDGET (g_object_new (BUOH_TYPE_COMIC_LIST, NULL)); +} + +void +buoh_comic_list_set_view (BuohComicList *comic_list, BuohView *view) +{ + g_return_if_fail (BUOH_IS_COMIC_LIST (comic_list)); + g_return_if_fail (BUOH_IS_VIEW (view)); + + if (comic_list->view) { + return; + } + + comic_list->view = view; +} + +void +buoh_comic_list_set_model (BuohComicList *comic_list, GtkTreeModel *model) +{ + g_return_if_fail (BUOH_IS_COMIC_LIST (comic_list)); + g_return_if_fail (GTK_IS_TREE_MODEL (model)); + + comic_list->model = gtk_tree_model_filter_new (model, NULL); + gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (comic_list->model), + buoh_comic_list_visible, + NULL, NULL); + + gtk_tree_view_set_model (GTK_TREE_VIEW (comic_list->tree_view), + comic_list->model); +} + +GtkWidget * +buoh_comic_list_get_list (BuohComicList *comic_list) +{ + g_return_val_if_fail (BUOH_IS_COMIC_LIST (comic_list), NULL); + + return comic_list->tree_view; +} + +void +buoh_comic_list_clear_selection (BuohComicList *comic_list) +{ + g_return_if_fail (BUOH_IS_COMIC_LIST (comic_list)); + + gtk_tree_selection_unselect_all ( + gtk_tree_view_get_selection (GTK_TREE_VIEW (comic_list->tree_view))); +} + +BuohComicManager * +buoh_comic_list_get_selected (BuohComicList *comic_list) +{ + g_return_val_if_fail (BUOH_IS_COMIC_LIST (comic_list), NULL); + + return comic_list->comic_manager; +} diff --git a/pool/shard006/C/0119925_process.c b/pool/shard006/C/0119925_process.c new file mode 100644 index 0000000000000000000000000000000000000000..d7990df9025a6e1f77c1e98668a625700c323bea --- /dev/null +++ b/pool/shard006/C/0119925_process.c @@ -0,0 +1,273 @@ +/* + * OpenRISC process.c + * + * Linux architectural port borrowing liberally from similar works of + * others. All original copyrights apply as per the original source + * declaration. + * + * Modifications for the OpenRISC architecture: + * Copyright (C) 2003 Matjaz Breskvar + * Copyright (C) 2010-2011 Jonas Bonn + * + * 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 file handles the architecture-dependent parts of process handling... + */ + +#define __KERNEL_SYSCALLS__ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +/* + * Pointer to Current thread info structure. + * + * Used at user space -> kernel transitions. + */ +struct thread_info *current_thread_info_set[NR_CPUS] = { &init_thread_info, }; + +void machine_restart(void) +{ + printk(KERN_INFO "*** MACHINE RESTART ***\n"); + __asm__("l.nop 1"); +} + +/* + * Similar to machine_power_off, but don't shut off power. Add code + * here to freeze the system for e.g. post-mortem debug purpose when + * possible. This halt has nothing to do with the idle halt. + */ +void machine_halt(void) +{ + printk(KERN_INFO "*** MACHINE HALT ***\n"); + __asm__("l.nop 1"); +} + +/* If or when software power-off is implemented, add code here. */ +void machine_power_off(void) +{ + printk(KERN_INFO "*** MACHINE POWER OFF ***\n"); + __asm__("l.nop 1"); +} + +void (*pm_power_off) (void) = machine_power_off; + +/* + * When a process does an "exec", machine state like FPU and debug + * registers need to be reset. This is a hook function for that. + * Currently we don't have any such state to reset, so this is empty. + */ +void flush_thread(void) +{ +} + +void show_regs(struct pt_regs *regs) +{ + extern void show_registers(struct pt_regs *regs); + + show_regs_print_info(KERN_DEFAULT); + /* __PHX__ cleanup this mess */ + show_registers(regs); +} + +unsigned long thread_saved_pc(struct task_struct *t) +{ + return (unsigned long)user_regs(t->stack)->pc; +} + +void release_thread(struct task_struct *dead_task) +{ +} + +/* + * Copy the thread-specific (arch specific) info from the current + * process to the new one p + */ +extern asmlinkage void ret_from_fork(void); + +/* + * copy_thread + * @clone_flags: flags + * @usp: user stack pointer or fn for kernel thread + * @arg: arg to fn for kernel thread; always NULL for userspace thread + * @p: the newly created task + * @regs: CPU context to copy for userspace thread; always NULL for kthread + * + * At the top of a newly initialized kernel stack are two stacked pt_reg + * structures. The first (topmost) is the userspace context of the thread. + * The second is the kernelspace context of the thread. + * + * A kernel thread will not be returning to userspace, so the topmost pt_regs + * struct can be uninitialized; it _does_ need to exist, though, because + * a kernel thread can become a userspace thread by doing a kernel_execve, in + * which case the topmost context will be initialized and used for 'returning' + * to userspace. + * + * The second pt_reg struct needs to be initialized to 'return' to + * ret_from_fork. A kernel thread will need to set r20 to the address of + * a function to call into (with arg in r22); userspace threads need to set + * r20 to NULL in which case ret_from_fork will just continue a return to + * userspace. + * + * A kernel thread 'fn' may return; this is effectively what happens when + * kernel_execve is called. In that case, the userspace pt_regs must have + * been initialized (which kernel_execve takes care of, see start_thread + * below); ret_from_fork will then continue its execution causing the + * 'kernel thread' to return to userspace as a userspace thread. + */ + +int +copy_thread(unsigned long clone_flags, unsigned long usp, + unsigned long arg, struct task_struct *p) +{ + struct pt_regs *userregs; + struct pt_regs *kregs; + unsigned long sp = (unsigned long)task_stack_page(p) + THREAD_SIZE; + unsigned long top_of_kernel_stack; + + top_of_kernel_stack = sp; + + p->set_child_tid = p->clear_child_tid = NULL; + + /* Locate userspace context on stack... */ + sp -= STACK_FRAME_OVERHEAD; /* redzone */ + sp -= sizeof(struct pt_regs); + userregs = (struct pt_regs *) sp; + + /* ...and kernel context */ + sp -= STACK_FRAME_OVERHEAD; /* redzone */ + sp -= sizeof(struct pt_regs); + kregs = (struct pt_regs *)sp; + + if (unlikely(p->flags & PF_KTHREAD)) { + memset(kregs, 0, sizeof(struct pt_regs)); + kregs->gpr[20] = usp; /* fn, kernel thread */ + kregs->gpr[22] = arg; + } else { + *userregs = *current_pt_regs(); + + if (usp) + userregs->sp = usp; + + /* + * For CLONE_SETTLS set "tp" (r10) to the TLS pointer passed to sys_clone. + * + * The kernel entry is: + * int clone (long flags, void *child_stack, int *parent_tid, + * int *child_tid, struct void *tls) + * + * This makes the source r7 in the kernel registers. + */ + if (clone_flags & CLONE_SETTLS) + userregs->gpr[10] = userregs->gpr[7]; + + userregs->gpr[11] = 0; /* Result from fork() */ + + kregs->gpr[20] = 0; /* Userspace thread */ + } + + /* + * _switch wants the kernel stack page in pt_regs->sp so that it + * can restore it to thread_info->ksp... see _switch for details. + */ + kregs->sp = top_of_kernel_stack; + kregs->gpr[9] = (unsigned long)ret_from_fork; + + task_thread_info(p)->ksp = (unsigned long)kregs; + + return 0; +} + +/* + * Set up a thread for executing a new program + */ +void start_thread(struct pt_regs *regs, unsigned long pc, unsigned long sp) +{ + unsigned long sr = mfspr(SPR_SR) & ~SPR_SR_SM; + + memset(regs, 0, sizeof(struct pt_regs)); + + regs->pc = pc; + regs->sr = sr; + regs->sp = sp; +} + +/* Fill in the fpu structure for a core dump. */ +int dump_fpu(struct pt_regs *regs, elf_fpregset_t * fpu) +{ + /* TODO */ + return 0; +} + +extern struct thread_info *_switch(struct thread_info *old_ti, + struct thread_info *new_ti); + +struct task_struct *__switch_to(struct task_struct *old, + struct task_struct *new) +{ + struct task_struct *last; + struct thread_info *new_ti, *old_ti; + unsigned long flags; + + local_irq_save(flags); + + /* current_set is an array of saved current pointers + * (one for each cpu). we need them at user->kernel transition, + * while we save them at kernel->user transition + */ + new_ti = new->stack; + old_ti = old->stack; + + current_thread_info_set[smp_processor_id()] = new_ti; + last = (_switch(old_ti, new_ti))->task; + + local_irq_restore(flags); + + return last; +} + +/* + * Write out registers in core dump format, as defined by the + * struct user_regs_struct + */ +void dump_elf_thread(elf_greg_t *dest, struct pt_regs* regs) +{ + dest[0] = 0; /* r0 */ + memcpy(dest+1, regs->gpr+1, 31*sizeof(unsigned long)); + dest[32] = regs->pc; + dest[33] = regs->sr; + dest[34] = 0; + dest[35] = 0; +} + +unsigned long get_wchan(struct task_struct *p) +{ + /* TODO */ + + return 0; +} diff --git a/pool/shard006/C/0119926_CWE78_OS_Command_Injection__char_environment_w32spawnl_08.c b/pool/shard006/C/0119926_CWE78_OS_Command_Injection__char_environment_w32spawnl_08.c new file mode 100644 index 0000000000000000000000000000000000000000..c122ab5efe0919ced2d132b41aa03591198fa005 --- /dev/null +++ b/pool/shard006/C/0119926_CWE78_OS_Command_Injection__char_environment_w32spawnl_08.c @@ -0,0 +1,160 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_environment_w32spawnl_08.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-08.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: environment Read input from an environment variable + * GoodSource: Fixed string + * Sink: w32spawnl + * BadSink : execute command with spawnl + * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "ls" +#define COMMAND_ARG2 "-la" +#define COMMAND_ARG3 data +#endif + +#define ENV_VARIABLE "ADD" + +#ifdef _WIN32 +#define GETENV getenv +#else +#define GETENV getenv +#endif + +#include + +/* The two function below always return the same value, so a tool + * should be able to identify that calls to the functions will always + * return a fixed value. + */ +static int staticReturnsTrue() +{ + return 1; +} + +static int staticReturnsFalse() +{ + return 0; +} + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_environment_w32spawnl_08_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(staticReturnsTrue()) + { + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(staticReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(staticReturnsTrue()) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__char_environment_w32spawnl_08_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_environment_w32spawnl_08_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_environment_w32spawnl_08_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0119928_test.c b/pool/shard006/C/0119928_test.c new file mode 100644 index 0000000000000000000000000000000000000000..1aed332db84103a33d2aa7ed7817361f68fe8006 --- /dev/null +++ b/pool/shard006/C/0119928_test.c @@ -0,0 +1,68 @@ +#include +#include +#include +#include"/usr/local/include/pbc/pbc.h" +#include"/home/ping/Desktop/pbc-0.5.14/testCode/Weil/weilPairing.h" + +int main(){ + pairing_t pairing; + char param[1024]; + size_t count = fread(param,1,1024,stdin); + int result = 0; + clock_t tStart,tEnd;//tStart:the start of tate pairing, tEnd:the end of tate pairing + clock_t wStart,wEnd;//wStart:the start of weil pairing, wEnd:the end of weil pairing + float difftime = 0; + printf("Hello!\n"); + if(!count) pbc_die("input error!\n"); + result = pairing_init_set_buf(pairing,param,count); + if(result) printf("Finish!\n"); + element_t g,h; + element_t public_key, secret_key; + element_t sig; + element_t temp1,temp2; + + element_init_G2(g, pairing); + element_init_G2(public_key,pairing); + element_init_G1(h,pairing); + element_init_G1(sig,pairing); + element_init_GT(temp1,pairing); + element_init_GT(temp2,pairing); + element_init_Zr(secret_key,pairing); + + element_random(g); + element_random(secret_key); + element_pow_zn(public_key, g, secret_key); + element_from_hash(h, "ABCDEF", 6); + element_pow_zn(sig, h, secret_key); + //tate pairing + tStart = clock(); + pairing_apply(temp1, sig, g, pairing); + pairing_apply(temp2, h, public_key, pairing); + if(!element_cmp(temp1, temp2)){ + printf("T signature verifies\n"); + } else { + printf("T signautre does not verify\n"); + } + tEnd = clock(); + difftime = (float)(tEnd-tStart)/CLOCKS_PER_SEC; + printf("The cost time of tate pairing: %f\n",difftime); + //clear the element temp1, temp2 + element_clear(temp1); + element_clear(temp2); + element_init_GT(temp1,pairing); + element_init_GT(temp2,pairing); + //weil pairing + wStart = clock(); + weilPairing(&temp1,sig,g,pairing); + weilPairing(&temp2,h,public_key,pairing); + if(!element_cmp(temp1,temp2)){ + printf("W signature verifies\n"); + } else { + printf("W signature does not verify\n"); + } + wEnd = clock(); + difftime = (float)(wEnd-wStart)/CLOCKS_PER_SEC; + printf("The cost time of weil pairing: %f\n",difftime); + + return 0; +} diff --git a/pool/shard006/C/0119929_kmalloc.c b/pool/shard006/C/0119929_kmalloc.c new file mode 100644 index 0000000000000000000000000000000000000000..b54e87e58a50f5ac7327e0982b745ad25e1f1b04 --- /dev/null +++ b/pool/shard006/C/0119929_kmalloc.c @@ -0,0 +1,78 @@ +#include + +//DISABLED FOR NOW! +//DISABLED FOR NOW! +//DISABLED FOR NOW! +//DISABLED FOR NOW! +//DISABLED FOR NOW! + +#define FREE_MAGIC 0x05C00BEE //0scoobee - Free Block MAGIC +#define USED_MAGIC 0xD00BED00 //doobedoo - Used Block MAGIC + +#ifdef __i386__ + #define KMALLOC_START (0x1000000 - sizeof(struct heapstruct)) + #define KMALLOC_END 0xC0000000 +#endif + +struct heapstruct { + uint32_t MAGIC; + struct heapstruct *next; + uint32_t length; + uint32_t pad; +}; + +struct heapstruct *heap_start = KMALLOC_START; + +typedef struct heapstruct heapstruct_t; + + +void malloc_init() { + heap_start->MAGIC = FREE_MAGIC; + heap_start->next = KMALLOC_START; + heap_start->length = 4096; +} + +uintptr_t malloc(uint32_t bytes) { + heapstruct_t *current_header; + heapstruct_t *prev_header; + + prev_header = current_header = heap_start; + + while(1) { + if(current_header->MAGIC == FREE_MAGIC) { //excuse me, is this free? + while(current_header->length < bytes) { //orly, is free? can i crash here? + alloc_page(current_header + current_header->length); + current_header->length += 4096; + } + + current_header->MAGIC = USED_MAGIC; //this region is now used + prev_header = current_header; //set "prev" + current_header->length = bytes; + + current_header = (current_header + bytes + sizeof(heapstruct_t)); //go to the end + + //create a new header at the end + current_header->MAGIC = FREE_MAGIC; + current_header->length = 0; + current_header->next = prev_header->next; + prev_header->next = current_header; + + kprintf("prev: %x len %x next %x\n",prev_header,prev_header->length ,prev_header->next); + return (uintptr_t) (prev_header + sizeof(heapstruct_t)); + }else { //oh sorry, its not, lets go find some other place + prev_header = current_header = current_header->next; + } + } +} + +uintptr_t calloc(uint32_t bytes) { + uintptr_t zerobytes = malloc(bytes); + memset((void *) zerobytes, 0, bytes); + return zerobytes; +} + +void free(uintptr_t freebytes) { + //implement me! + +} + diff --git a/pool/shard006/C/0119930_irls.c b/pool/shard006/C/0119930_irls.c new file mode 100644 index 0000000000000000000000000000000000000000..b4928ad64995c072723a735cafd2bb0c8109603e --- /dev/null +++ b/pool/shard006/C/0119930_irls.c @@ -0,0 +1,230 @@ +#include +#include +#include +#define ISCL_MACROS_SRC 1 +#include "iscl/iscl/errorCheckMacros.h" +#include "iscl/linalg/linalg.h" +#ifdef ISCL_USE_INTEL +#include +#include +#else +#include +#include +#endif +#include "iscl/array/array.h" +#include "iscl/memory/memory.h" +/*! + * @brief Iteratively reweighed least squares algorithm. The algorithm works + * by first solving \f$ Ax = y \f$ in a least squares sense for the + * initial model x0. Then, it successively solves in a least squares + * sense \f$ WAx = y \f$ where \f$ W \f$ is the diagonal matrix of + * weights computed by + * if (p == 1.0) + * W_{i,i} = \sqrt{\frac{1}{\max(eps,|y[i] - Gx_k[i]|)}} + * else if (p < 2.0) + * W_{i,i} = \sqrt{p \max(eps,|y[i] - G x_k[i]|)^{p-2}} + * else + * W_{i,i} = \sqrt(p |y[i] - Gx_k[i]|^{p-2} + * endif + * + * Next, the algorithm iterates and solves the data regularized + * least squares problem \f$ W_k A x_{k+1} = W_k y \f$ + * for the new model x_{k+1}. + * + * Lastly, the algorithm checks for convergence + * \f$ ||x_{k+1} - x_{k}||_2/(1 + ||x_{k+1||_2) < tol \f$. + * + * More details can be found in: + * Parameter Estimation and Inverse Problems 2nd Edition pg 46 . + * + * Fast lp solution of large sparse linear systems: Application + * to seismic travel time tomography - Scales, Gersztenkorn, Treitel + * 1987. + * + * @param[in] m Number of rows in matrix. This must be >= n. + * @param[in] n Number of colums in matrix. + * @param[in] maxit Max number of iterations. This must be positive. + * @param[in] p Norm to minimize in; p >= 1.0. If p < 2.0 one + * must specify epsin. + * @param[in] eps When minimizing in a norm less than 2 this is applied + * to the i'th residual s.t. max(epsin, |r_i|) to + * avoid a division by zero. A recommended value is 1.e-4. + * @param[in] tol Stopping criteria for which we use : + * ||x_{k+1} - x_{k}||/||x_{k+1}|| < tolin + * A recommended value is 1.e-6. + * @param[in] Amat This is the overdetermined system of equations + * with m rows and n columns in column major format. + * This is an array of dimension [m x n] with leading + * dimension n. + * @param[in] y Observation vector. This is an array with dimension + * [m]. + * + * @param[out] x On a successful exit this is the least-squares + * solution in the desired norm. This is an array + * of dimension [n]. + * @param[out] wts Diagonal weights such that A^T W(y - Ax) is + * small. This is an array with dimension [m]. + * + * @result 0 indicates success. \n + * -1 input error. \n + * -2 solution to overdetermine problem failed. \n + * -3 space error. \n + * 1 algorithm did not converge. + * + * @author Ben Baker + * + * @copyright ISTI distributed under Apache 2 + * + */ +enum isclError_enum + linalg_irls64f_work(const int m, const int n, + const int maxit, const double p, + const double eps, const double tol, + const double *__restrict__ Amat, + const double *__restrict__ y, + double *__restrict__ x, + double *__restrict__ wts) +{ + double *Awork, *yhat, *x0, absRes, xnum, xden; + int i, j, k, lda, mn; + enum isclError_enum ierr; + const double one = 1.0; + const double zero = 0.0; + const double two = 2.0; + const int incx = 1; + const int incy = 1; + //------------------------------------------------------------------------// + // + // check the inputs + ierr = ISCL_SUCCESS; + isclReturnNullPointerError("Amat", Amat); + isclReturnNullPointerError("y", y); + isclReturnNullPointerError("x", x); + isclReturnNullPointerError("wts", wts); + if (m < 1 || m < n || p < one || maxit < 1 || tol <= zero) + { + if (m < 1){isclPrintError("Invalid number of rows=%d\n", n);} + if (m < n){isclPrintError("Error m=%d must be >= n\n", m);} + if (p < one){isclPrintError("Error p=%f must be >= 1\n", p);} + if (maxit < 1){isclPrintError("Error maxit=%d must be > 0\n", maxit);} + if (tol <= zero){isclPrintError("tol=%f must be positive\n", tol);} + return ISCL_INVALID_INPUT; + } + if (p < two && eps <= zero) + { + if (eps <= zero){isclPrintError("eps=%f must be positive when p=2", eps);} + if (p < two){isclPrintError("p=%f must be at least 2 when eps<=zero", p);} + return ISCL_INVALID_INPUT; + } + // Initialize the output weights + array_set64f_work(m, one, wts); + // Compute the least squares solution and leave + if (fabs(p - two) < 1.e-10) + { + ierr = linalg_lstsq_qr64f_work(LAPACK_COL_MAJOR, m, n, 1, + false, Amat, y, x, NULL); + if (ierr != ISCL_SUCCESS) + { + isclPrintError("Failed to compute least squares solution"); + } + return ierr; + } + // Null out output and set space + lda = m; + mn = m*n; + array_zeros64f_work(n, x); + x0 = memory_calloc64f(n); + Awork = memory_calloc64f(mn); + yhat = memory_calloc64f(m); + // Set the initial solution x0 <- Ax = y + isclPrintDebug("%s", "Computing initial x0..."); + ierr = linalg_lstsq_qr64f_work(LAPACK_COL_MAJOR, m, n, 1, + false, Amat, y, x0, NULL); + if (ierr != ISCL_SUCCESS) + { + isclPrintError("Error failed to compute least squares solution"); + ierr = ISCL_ALGORITHM_FAILURE; + goto ERROR; + } + // Begin the non-linear iteration + for (k=0; k one && p < two) + { + // p*|fmax(eps,r)|^{p-2}; fmax b/c r ends up denominator + for (i=0; i= maxit && ierr == ISCL_SUCCESS) + { + ierr = ISCL_CONVERGENCE_ERROR; + isclPrintWarning("Failed to converge after %d iterations", maxit); + } + // Free space +ERROR:; + memory_free64f(&yhat); + memory_free64f(&x0); + memory_free64f(&Awork); + return ierr; +} diff --git a/pool/shard006/C/0119933_smc_sw_regs.c b/pool/shard006/C/0119933_smc_sw_regs.c new file mode 100644 index 0000000000000000000000000000000000000000..ae12d98e3a54094ec778240e14e74d8c9d468fa1 --- /dev/null +++ b/pool/shard006/C/0119933_smc_sw_regs.c @@ -0,0 +1,157 @@ +/* + author Sylvain Bertrand + Protected by linux GNU GPLv2 + Copyright 2012-2014 +*/ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../mc.h" +#include "../rlc.h" +#include "../ih.h" +#include "../fence.h" +#include "../ring.h" +#include "../dmas.h" +#include "../ba.h" +#include "../cps.h" +#include "../gpu.h" +#include "../drv.h" + +#include "../smc_tbls.h" +#include "../smc_regs.h" +#include "../smc.h" + +#include "ctx.h" +#include "private.h" +#include "ulv.h" +#include "smc_mc_reg_tbl.h" +#include "smc_cac_cfg_tbl.h" + +#ifdef CONFIG_ALGA_AMD_SI_DYN_PM_LOG +#define L(fmt,...) printk(KERN_INFO fmt "\n", ##__VA_ARGS__) +void smc_sw_regs_dump(struct pci_dev *dev) +{ + u32 tmp; + + L("SMC_SW_REGS START"); + + tmp = smc_sw_r32(dev,SMC_SW_MCLK_CHG_TIMEOUT); + L("SMC_SW_MCLK_CHG_TIMEOUT=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_DELAY_VREG); + L("SMC_SW_DELAY_VREG=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_DELAY_EMERGENCY); + L("SMC_SW_DELAY_EMERGENCY=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_SEQ_IDX); + L("SMC_SW_SEQ_IDX=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_MVDD_CHG_TIME); + L("SMC_SW_MVDD_CHG_TIME=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_MCLK_SWITCH_LIM); + L("SMC_SW_MCLK_SWITCH_LIM=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_WATERMARK_THRESHOLD); + L("SMC_SW_WATERMARK_THRESHOLD=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_PHASE_SHEDDING_DELAY); + L("SMC_SW_PHASE_SHEDDING_DELAY=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_ULV_VOLT_CHANGE_DELAY); + L("SMC_SW_ULV_VOLT_CHANGE_DELAY=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_MC_BLK_DELAY); + L("SMC_SW_MC_BLK_DELAY=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_TICKS_PER_US); + L("SMC_SW_TICKS_PER_US=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_CRTC_IDX); + L("SMC_SW_CRTC_IDX=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_MCLK_CHANGE_BLK_CP_MIN); + L("SMC_SW_MCLK_CHANGE_BLK_CP_MIN=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_MCLK_CHANGE_BLK_CP_MAX); + L("SMC_SW_MCLK_CHANGE_BLK_CP_MAX=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_NON_ULV_PCIE_LINK_WIDTH); + L("SMC_SW_NON_ULV_PCIE_LINK_WIDTH=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_TDR_IS_ABOUT_TO_HAPPEN); + L("SMC_SW_TDR_IS_ABOUT_TO_HAPPEN=0x%08x",tmp); + + tmp = smc_sw_r32(dev,SMC_SW_VR_HOT_GPIO); + L("SMC_SW_VR_HOT_GPIO=0x%08x",tmp); + + L("SMC_SW_REGS END"); +} +#endif + +#define VOLT_TIME_DEFAULT 1000 +#define VBI_TIMEOUT 100000 +void response_times_init(struct ctx *ctx) +{ + u32 volt_time; + u32 delay; + + smc_sw_wr32(ctx->dev, 1, SMC_SW_MVDD_CHG_TIME); + + volt_time = (u32)ctx->atb_volt_time; + if (volt_time == 0) /* 0 means gpu generation default */ + volt_time = VOLT_TIME_DEFAULT; + + delay = (volt_time * ctx->gpu_aux_clk) / 100; + smc_sw_wr32(ctx->dev, delay, SMC_SW_DELAY_VREG); + + delay = (15000 * ctx->gpu_aux_clk) / 100; + smc_sw_wr32(ctx->dev, delay, SMC_SW_DELAY_EMERGENCY); + + delay = (VBI_TIMEOUT * ctx->gpu_aux_clk) / 100; + smc_sw_wr32(ctx->dev, delay, SMC_SW_MCLK_CHG_TIMEOUT); + smc_sw_wr32(ctx->dev, 0xaa, SMC_SW_MC_BLK_DELAY); +} + +#define BACK_BIAS_TIME_DEFAULT 1000 +void smc_sw_regs_init(struct ctx *ctx) +{ + struct dev_drv_data *dd; + + LOG("smc software registers init"); + + dd = pci_get_drvdata(ctx->dev); + + if (ctx->volt_caps & VOLT_CAPS_VDDC_PHASE_SHED_CTL_ENA) + smc_sw_wr32(ctx->dev, ctx->atb_vddc_phase_shed_tbl.phase_delay, + SMC_SW_PHASE_SHEDDING_DELAY); + + if (ctx->platform_caps & ATB_PP_PLATFORM_CAPS_VRHOT_GPIO_CONFIGURABLE) { + u32 back_bias_time; + + back_bias_time = ctx->atb_back_bias_time; + if (back_bias_time == 0) /* 0 means gpu generation default */ + back_bias_time = BACK_BIAS_TIME_DEFAULT; + + smc_sw_wr32(ctx->dev, back_bias_time, SMC_SW_VR_HOT_GPIO); + } + + if (ctx->atb_ulv.lvls_n) + smc_sw_regs_ulv_init(ctx); + + smc_mc_reg_tbl_sw_regs_init(ctx); + smc_cac_cfg_tbl_sw_regs_init(ctx); + response_times_init(ctx); +} diff --git a/pool/shard006/C/0119937_deprecations.c b/pool/shard006/C/0119937_deprecations.c new file mode 100644 index 0000000000000000000000000000000000000000..b3225ef44daf92e6915aa61bb0ffb4e82b193d27 --- /dev/null +++ b/pool/shard006/C/0119937_deprecations.c @@ -0,0 +1,71 @@ +/*********************************************************************** + Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold + 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. + + 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. +***********************************************************************/ + +#ifdef HAVE_CONFIG_H +#include +#endif /* HAVE_CONFIG_H */ + +#include "fc_prehdrs.h" + +#include + +/* utility */ +#include "log.h" +#include "shared.h" + +#include "deprecations.h" + +static deprecation_warn_callback depr_cb = NULL; + +static bool depr_warns_enabled = FALSE; + +/********************************************************************//** + Enable deprecation warnings. +************************************************************************/ +void deprecation_warnings_enable(void) +{ + depr_warns_enabled = TRUE; +} + +/********************************************************************//** + Return whether deprecation warnings are currently enabled. +************************************************************************/ +bool are_deprecation_warnings_enabled(void) +{ + return depr_warns_enabled; +} + +/********************************************************************//** + Set callback to call when deprecation warnings are issued +************************************************************************/ +void deprecation_warn_cb_set(deprecation_warn_callback new_cb) +{ + depr_cb = new_cb; +} + +/********************************************************************//** + Log the deprecation warning +************************************************************************/ +void do_log_deprecation(const char *format, ...) +{ + va_list args; + char buf[1024]; + + va_start(args, format); + vdo_log(__FILE__, __FUNCTION__, __FC_LINE__, FALSE, LOG_DEPRECATION, + buf, sizeof(buf), format, args); + if (depr_cb != NULL) { + depr_cb(buf); + } + va_end(args); +} diff --git a/pool/shard006/C/0119939_hi_usb_ser.c b/pool/shard006/C/0119939_hi_usb_ser.c new file mode 100644 index 0000000000000000000000000000000000000000..27645c3391a9da13da60a2f697437077df6ce6cf --- /dev/null +++ b/pool/shard006/C/0119939_hi_usb_ser.c @@ -0,0 +1,109 @@ +/* + * linux/driver/usb/serial/hi_usb_ser.c + * + * Copyright (c) 2011 Hisi technology corporation. + * + * 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;version 2 of the License. + * + * NOTE:Only use this driver for devices that provide AT/Diag port and all other generic serials. + * and CDC-ACM port should probably be driven by option.ko. + */ + +#include +#include +#include +#include +#include +#include "usb-wwan.h" + +#define DRIVER_AUTHOR "Hisi Inc" +#define DRIVER_DESC "Hisi USB Serial driver" + +static const struct usb_device_id id_table[] = { + {USB_DEVICE(0x058b, 0x0041)}, /* */ + {USB_DEVICE(0x12d1, 0x1506)}, + { } /* Terminating entry */ +}; +MODULE_DEVICE_TABLE(usb, id_table); + +static struct usb_driver hi_gs_driver = { + .name = "hi_gs", + .probe = usb_serial_probe, + .disconnect = usb_serial_disconnect, + .id_table = id_table, + .suspend = usb_serial_suspend, + .resume = usb_serial_resume, + .supports_autosuspend = true, +}; + +static int hi_gs_probe(struct usb_serial *serial, const struct usb_device_id *id) +{ + struct usb_wwan_intf_private *data; + + + data = serial->private = kzalloc(sizeof(struct usb_wwan_intf_private), + GFP_KERNEL); + if (!data) + return -ENOMEM; + + spin_lock_init(&data->susp_lock); + return 0; +} +//set bulk size to 8k to improve download modem image speed +#define USB_BULK_OUT_SIZE (8*1024) +static struct usb_serial_driver hi_gs_device = { + .driver = { + .owner = THIS_MODULE, + .name = "hi_gs", + }, + .description = "Hisi USB generic serial", + .id_table = id_table, + .usb_driver = &hi_gs_driver, + .num_ports = 1, + .probe = hi_gs_probe, + .open = usb_wwan_open, + .close = usb_wwan_close, + .write = usb_wwan_write, + .write_room = usb_wwan_write_room, + .chars_in_buffer = usb_wwan_chars_in_buffer, + .attach = usb_wwan_startup, + .disconnect = usb_wwan_disconnect, + .release = usb_wwan_release, + .bulk_out_size = USB_BULK_OUT_SIZE, +#ifdef CONFIG_PM + .suspend = usb_wwan_suspend, + .resume = usb_wwan_resume, +#endif +}; + +static int __init hi_gs_init(void) +{ + int retval; + retval = usb_serial_register(&hi_gs_device); + if (retval) + return retval; + + retval = usb_register(&hi_gs_driver); + if (retval) { + usb_serial_deregister(&hi_gs_device); + return retval; + } + + return 0; +} + +static void __exit hi_gs_exit(void) +{ + usb_deregister(&hi_gs_driver); + usb_serial_deregister(&hi_gs_device); +} + +module_init(hi_gs_init); +module_exit(hi_gs_exit); + +MODULE_AUTHOR(DRIVER_AUTHOR); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL v2"); + diff --git a/pool/shard006/C/0119943_binsearch.c b/pool/shard006/C/0119943_binsearch.c new file mode 100644 index 0000000000000000000000000000000000000000..87beeaf6d33207a74bc7277548c9b1ba9ab0927d --- /dev/null +++ b/pool/shard006/C/0119943_binsearch.c @@ -0,0 +1,36 @@ +/* binsearch: Implementation of Binary Search,In the array v[],search for n in the binary way*/ + +#include + +int binsearch(int x,int v[],int n); + +int main(void) +{ + int arr[]={2,4,5,7,8,9,11,23,45,50}; + int x,n; + + printf("%d",binsearch(9,arr,10)); + + return 0; +} + +int binsearch(int x,int v[],int n) +{ + int low,high,mid; + + low=0; + high=n-1; + + while(low v[mid]) + low = mid + 1; + else + return mid; + } + return -1; +} diff --git a/pool/shard006/C/0119947_sigwaitinfo.c b/pool/shard006/C/0119947_sigwaitinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..47e6dd6bddba3b020bb50f53a63d15a9d4091fd4 --- /dev/null +++ b/pool/shard006/C/0119947_sigwaitinfo.c @@ -0,0 +1,73 @@ +/* Copyright (C) 1997-2015 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, see + . */ + +#include +#include +#define __need_NULL +#include +#include + +#include +#include +#include + +#ifdef __NR_rt_sigtimedwait + +/* Return any pending signal or wait for one for the given time. */ +int +__sigwaitinfo (const sigset_t *set, siginfo_t *info) +{ +#ifdef SIGCANCEL + sigset_t tmpset; + if (set != NULL + && (__builtin_expect (__sigismember (set, SIGCANCEL), 0) +# ifdef SIGSETXID + || __builtin_expect (__sigismember (set, SIGSETXID), 0) +# endif + )) + { + /* Create a temporary mask without the bit for SIGCANCEL set. */ + // We are not copying more than we have to. + memcpy (&tmpset, set, _NSIG / 8); + __sigdelset (&tmpset, SIGCANCEL); +# ifdef SIGSETXID + __sigdelset (&tmpset, SIGSETXID); +# endif + set = &tmpset; + } +#endif + + /* XXX The size argument hopefully will have to be changed to the + real size of the user-level sigset_t. */ + int result = SYSCALL_CANCEL (rt_sigtimedwait, set, info, NULL, _NSIG / 8); + + /* The kernel generates a SI_TKILL code in si_code in case tkill is + used. tkill is transparently used in raise(). Since having + SI_TKILL as a code is useful in general we fold the results + here. */ + if (result != -1 && info != NULL && info->si_code == SI_TKILL) + info->si_code = SI_USER; + + return result; +} + +libc_hidden_def (__sigwaitinfo) +weak_alias (__sigwaitinfo, sigwaitinfo) +#else +# include +#endif +strong_alias (__sigwaitinfo, __libc_sigwaitinfo) diff --git a/pool/shard006/C/0119949_12342_-_Tax_Calculator.c b/pool/shard006/C/0119949_12342_-_Tax_Calculator.c new file mode 100644 index 0000000000000000000000000000000000000000..ebb97bea5c08a5c33ddd7375e929a6ddc6820a90 --- /dev/null +++ b/pool/shard006/C/0119949_12342_-_Tax_Calculator.c @@ -0,0 +1,18 @@ +#include + +int main() +{ + long long int t,i,n,sum; + scanf("%lld\n",&t); + for(i=1;i<=t;i++) + { + sum = 0; + scanf("%lld",&n); + if(n<=180000) + sum = 0; + else if(n>180000) + { + if(n<) + } + } +} diff --git a/pool/shard006/C/0119953_benchmark.c b/pool/shard006/C/0119953_benchmark.c new file mode 100644 index 0000000000000000000000000000000000000000..fda8268f189f0a88b1762cc59564d77ddcbbb812 --- /dev/null +++ b/pool/shard006/C/0119953_benchmark.c @@ -0,0 +1,145 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + 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 +#include +#include +#include +#include "expat.h" + +#ifdef XML_LARGE_SIZE +# define XML_FMT_INT_MOD "ll" +#else +# define XML_FMT_INT_MOD "l" +#endif + +#ifdef XML_UNICODE_WCHAR_T +# define XML_FMT_STR "ls" +#else +# define XML_FMT_STR "s" +#endif + +static void +usage(const char *prog, int rc) { + fprintf(stderr, "usage: %s [-n] filename bufferSize nr_of_loops\n", prog); + exit(rc); +} + +int +main(int argc, char *argv[]) { + XML_Parser parser; + char *XMLBuf, *XMLBufEnd, *XMLBufPtr; + FILE *fd; + struct stat fileAttr; + int nrOfLoops, bufferSize, fileSize, i, isFinal; + int j = 0, ns = 0; + clock_t tstart, tend; + double cpuTime = 0.0; + + if (argc > 1) { + if (argv[1][0] == '-') { + if (argv[1][1] == 'n' && argv[1][2] == '\0') { + ns = 1; + j = 1; + } else + usage(argv[0], 1); + } + } + + if (argc != j + 4) + usage(argv[0], 1); + + if (stat(argv[j + 1], &fileAttr) != 0) { + fprintf(stderr, "could not access file '%s'\n", argv[j + 1]); + return 2; + } + + fd = fopen(argv[j + 1], "r"); + if (! fd) { + fprintf(stderr, "could not open file '%s'\n", argv[j + 1]); + exit(2); + } + + bufferSize = atoi(argv[j + 2]); + nrOfLoops = atoi(argv[j + 3]); + if (bufferSize <= 0 || nrOfLoops <= 0) { + fprintf(stderr, "buffer size and nr of loops must be greater than zero.\n"); + exit(3); + } + + XMLBuf = malloc(fileAttr.st_size); + fileSize = fread(XMLBuf, sizeof(char), fileAttr.st_size, fd); + fclose(fd); + + if (ns) + parser = XML_ParserCreateNS(NULL, '!'); + else + parser = XML_ParserCreate(NULL); + + i = 0; + XMLBufEnd = XMLBuf + fileSize; + while (i < nrOfLoops) { + XMLBufPtr = XMLBuf; + isFinal = 0; + tstart = clock(); + do { + int parseBufferSize = XMLBufEnd - XMLBufPtr; + if (parseBufferSize <= bufferSize) + isFinal = 1; + else + parseBufferSize = bufferSize; + if (! XML_Parse(parser, XMLBufPtr, parseBufferSize, isFinal)) { + fprintf(stderr, + "error '%" XML_FMT_STR "' at line %" XML_FMT_INT_MOD + "u character %" XML_FMT_INT_MOD "u\n", + XML_ErrorString(XML_GetErrorCode(parser)), + XML_GetCurrentLineNumber(parser), + XML_GetCurrentColumnNumber(parser)); + free(XMLBuf); + XML_ParserFree(parser); + exit(4); + } + XMLBufPtr += bufferSize; + } while (! isFinal); + tend = clock(); + cpuTime += ((double)(tend - tstart)) / CLOCKS_PER_SEC; + XML_ParserReset(parser, NULL); + i++; + } + + XML_ParserFree(parser); + free(XMLBuf); + + printf("%d loops, with buffer size %d. Average time per loop: %f\n", + nrOfLoops, bufferSize, cpuTime / (double)nrOfLoops); + return 0; +} diff --git a/pool/shard006/C/0119955_modref-5.c b/pool/shard006/C/0119955_modref-5.c new file mode 100644 index 0000000000000000000000000000000000000000..fde317728622faaf8809ab364c56a50044b64bb8 --- /dev/null +++ b/pool/shard006/C/0119955_modref-5.c @@ -0,0 +1,27 @@ +/* { dg-options "-O2 -fdump-tree-modref1" } */ +/* { dg-do run } */ +__attribute__ ((noinline)) +void +copy (int *a, int *b) +{ + *a=*b; +} +int p, *ptr = &p; +__attribute__ ((noinline)) +void +barrier () +{ + asm ("":"=r"(ptr):"0"(ptr)); +} +int +main() +{ + int a = 1, b = 2; + copy (&a,&b); + barrier (); + *ptr = 1; + if (!__builtin_constant_p (b == 2)) + __builtin_abort (); + return 0; +} +/* { dg-final { scan-tree-dump "parm 1 flags: nodirectescape" "modref1" } } */ diff --git a/pool/shard006/C/0119959_mv.c b/pool/shard006/C/0119959_mv.c new file mode 100644 index 0000000000000000000000000000000000000000..f55984422c9155e2da2719844e2305dcbbc1f839 --- /dev/null +++ b/pool/shard006/C/0119959_mv.c @@ -0,0 +1,177 @@ +/* +mv [-d] file1 file2 + +unlink file2 +link file1 file2 +unlink file1 +*/ +int stbuf[42]; +struct sbuf { +int dev; +int inum; +int imode; +char nlink; +char uid; +char gid; +char siz0; +char siz1; +int addr[8]; +int adate[2]; +int mdate[2]; +}; +char strbuf[70]; + +main(argc,argv) +int argc; +char *argv[]; +{ +char **argp; +char *argp1, *argp2, *argp3, *argp4; +char *p, *p1, *p2; +char place[100]; +int i; +int status; +int b; +argp = argv; +/* + check for correct number + of arguments +*/ +if(argc != 3){ + write(1,"Usage: mv name1 name2\n",22); + exit(); +} +/* + is there anything to do? +*/ +argp3 = argp[1]; +argp4 = argp[2]; +if(stat(argp[1], stbuf) < 0){ + write(1,"Source file non-existent\n",25); + exit(); +} +/* + yes, there is a source. + check whether file or directory +*/ +if((stbuf[0].imode & 060000) == 040000){ +/* + The source is a directory, so + we do lots of checking and + messing around so as not to get + into trouble. This patch of + code contains administrative + policies rather than system + restrictions. +*/ + if(stat(argp[2], stbuf) >= 0){ + write(1,"Directory target exists.\n",25); + exit(); + } + argp1 = argp[1]; + argp2 = argp[2]; + while(*argp1 == *argp2){ + argp1++; + if(*argp2++ == 0){ + write(1,"???\n",4); + exit(); + } + } + while(*argp1)if(*argp1++ == '/'){ + write(1,"Directory rename only\n",22); + exit(); + } + while(*argp2)if(*argp2++ == '/'){ + write(1,"Directory rename only\n",22); + exit(); + } + if(*--argp1 == '.'){ + write(1,"values of B will give rise to dom!\n",37); + exit(); + } +}else{ +/* + the source is a file. +*/ + setuid(getuid()); + if(stat(argp4, &stbuf[2]) >= 0){ + if((stbuf[2].imode & 060000) == 040000){ + argp2 = strbuf; + while(*argp2++ = *argp4++); + argp2[-1] = '/'; + argp4 = argp[1]; + argp1 = argp[1]; + while(*argp4) + if(*argp4++ == '/') + argp1 = argp4; + while(*argp2++ = *argp1++); + argp4 = strbuf; + } + if(stat(argp4, &stbuf[2]) >= 0){ + if((stbuf[0]==stbuf[2]) && (stbuf[1]==stbuf[3])){ + write(1,"Files are identical.\n",21); + exit(); + } + if((getuid()&0377) == stbuf[2].uid) + b = 0200; else + if((getgid()&0377) == stbuf[2].gid) + b = 020; else + b = 02; + if((stbuf[2].imode & b) == 0) { + printf("%s: %o mode ", argp4, + stbuf[2].imode & 07777); + i = b = getchar(); + while(b != '\n' && b != '\0') + b = getchar(); + if(i != 'y') + exit(); + } + if(unlink(argp4) < 0){ + write(1,"Cannot remove target file.\n",27); + exit(); + } + } + } +} +if(link(argp3, argp4) < 0){ + i = fork(); + if(i == -1){ + write(1,"Try again.\n",11); + exit(); + } + if(i){ + while(wait(&status) != i); + }else{ + p = place; + p1 = p; + while(*p++ = *argp3++); + p2 = p; + while(*p++ = *argp4++); + execl("/bin/cp","cp", p1, p2, 0); + write(1, "no cp\n", 6); + exit(1); + } + if((status & 0377) != 0){ + write(1,"?\n", 2); + exit(); + } + if(status != 0) exit(); +} +if(unlink(argp3) < 0){ + write(1,"Cannot unlink source file.\n",27); + exit(); +} +} + +putchar(c) +{ + write(1, &c, 1); +} + +getchar() +{ + char c; + + if(read(0, &c, 1) != 1) return(0); + return(c); +} diff --git a/pool/shard006/C/0119961_armstrong.c b/pool/shard006/C/0119961_armstrong.c new file mode 100644 index 0000000000000000000000000000000000000000..ed5943061bdb66cddfe4cf7298bcd317461561c8 --- /dev/null +++ b/pool/shard006/C/0119961_armstrong.c @@ -0,0 +1,24 @@ +#include +#include +void main() +{ +int i,n,r,s=0,x; +printf("Enter a number:"); +scanf("%d",&n); +x=n; +while(x) +{ +r=x%10; +x=x/10; +s+=r*r*r; +} +if(n==s) +{ +printf("Armstrong Number"); +} +else +{ +printf("Not Armstrong Number"); +} +getch(); +} \ No newline at end of file diff --git a/pool/shard006/C/0119962_mantis_vp3030.c b/pool/shard006/C/0119962_mantis_vp3030.c new file mode 100644 index 0000000000000000000000000000000000000000..9797c9fd82599e8a34feca95bf27d4369670a8da --- /dev/null +++ b/pool/shard006/C/0119962_mantis_vp3030.c @@ -0,0 +1,105 @@ +/* + Mantis VP-3030 driver + + Copyright (C) Manu Abraham (abraham.manu@gmail.com) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "zl10353.h" +#include "tda665x.h" +#include "mantis_common.h" +#include "mantis_ioc.h" +#include "mantis_dvb.h" +#include "mantis_vp3030.h" + +static struct zl10353_config mantis_vp3030_config = { + .demod_address = 0x0f, +}; + +static struct tda665x_config env57h12d5_config = { + .name = "ENV57H12D5 (ET-50DT)", + .addr = 0x60, + .frequency_min = 47 * MHz, + .frequency_max = 862 * MHz, + .frequency_offst = 3616667, + .ref_multiplier = 6, /* 1/6 MHz */ + .ref_divider = 100000, /* 1/6 MHz */ +}; + +#define MANTIS_MODEL_NAME "VP-3030" +#define MANTIS_DEV_TYPE "DVB-T" + + +static int vp3030_frontend_init(struct mantis_pci *mantis, struct dvb_frontend *fe) +{ + struct i2c_adapter *adapter = &mantis->adapter; + struct mantis_hwconfig *config = mantis->hwconfig; + int err = 0; + + mantis_gpio_set_bits(mantis, config->reset, 0); + msleep(100); + err = mantis_frontend_power(mantis, POWER_ON); + msleep(100); + mantis_gpio_set_bits(mantis, config->reset, 1); + + if (err == 0) { + msleep(250); + dprintk(MANTIS_ERROR, 1, "Probing for 10353 (DVB-T)"); + fe = dvb_attach(zl10353_attach, &mantis_vp3030_config, adapter); + + if (!fe) + return -1; + + dvb_attach(tda665x_attach, fe, &env57h12d5_config, adapter); + } else { + dprintk(MANTIS_ERROR, 1, "Frontend on <%s> POWER ON failed! <%d>", + adapter->name, + err); + + return -EIO; + + } + mantis->fe = fe; + dprintk(MANTIS_ERROR, 1, "Done!"); + + return 0; +} + +struct mantis_hwconfig vp3030_config = { + .model_name = MANTIS_MODEL_NAME, + .dev_type = MANTIS_DEV_TYPE, + .ts_size = MANTIS_TS_188, + + .baud_rate = MANTIS_BAUD_9600, + .parity = MANTIS_PARITY_NONE, + .bytes = 0, + + .frontend_init = vp3030_frontend_init, + .power = GPIF_A12, + .reset = GPIF_A13, + + .i2c_mode = MANTIS_BYTE_MODE +}; diff --git a/pool/shard006/C/0119966_taintcheck_opt.c b/pool/shard006/C/0119966_taintcheck_opt.c new file mode 100644 index 0000000000000000000000000000000000000000..6ffc23a6708b15d5471e8d1ad781c377da51b92b --- /dev/null +++ b/pool/shard006/C/0119966_taintcheck_opt.c @@ -0,0 +1,287 @@ +/* +Copyright (C) <2012> + +DECAF is based on QEMU, a whole-system emulator. You can redistribute +and modify it under the terms of the GNU GPL, version 3 or later, +but it is made available WITHOUT ANY WARRANTY. See the top-level +README file for more details. + +For more information about DECAF and other softwares, see our +web site at: +http://sycurelab.ecs.syr.edu/ + +If you have any questions about DECAF,please post it on +http://code.google.com/p/decaf-platform/ +*/ + +#include "config.h" +#include +#include +#include +#include "hw/hw.h" +#include "qemu-common.h" +#include "sysemu.h" +#include "hw/hw.h" /* {de,}register_savevm */ +#include "cpu.h" +#include "DECAF_main.h" +#include "DECAF_main_internal.h" +#include "shared/tainting/taintcheck_opt.h" +//#include "shared/tainting/taintcheck.h" +#include "shared/DECAF_vm_compress.h" +#include "shared/tainting/taint_memory.h" +#include "tcg.h" // tcg_abort() + +#ifdef CONFIG_TCG_TAINT + +uint8_t nic_bitmap[1024 * 32 ]; //!index == index && drec->bs == bs) { + found = 1; + break; + } + if (drec->index > index) + break; + } + if (!found) { + if (!is_tainted) + return 0; + + if (!(new_drec = g_malloc0((size_t)sizeof(disk_record_t)))) + return -1; + + new_drec->index = index; + new_drec->bs = bs; + memcpy(&new_drec->bitmap[offset], taint, size); + LIST_INSERT_HEAD(head, new_drec, entry); + } else { + memcpy(&drec->bitmap[offset], taint, size); + if (!is_tainted && !memcmp(drec->bitmap, zero_mem, sizeof(drec->bitmap))) { + LIST_REMOVE(drec, entry); + g_free(drec); + } + } + return 0; +} + +static void taintcheck_disk_check(uint8_t *taint, const uint64_t index, const int offset, + const int size, const void *bs) +{ + struct disk_record_list_head *head = + &disk_record_heads[index & (DISK_HTAB_SIZE - 1)]; + disk_record_t *drec; + int found = 0; + + assert(offset + size <= 512); + + LIST_FOREACH(drec, head, entry) { + if (drec->index == index && drec->bs == bs) { + found = 1; + break; + } + if (drec->index > index) + break; + } + + if (!found) { + bzero(taint, size); + return; + } + + memcpy(taint, &drec->bitmap[offset], size); +} + +int taintcheck_init(void) +{ + int i; + for (i = 0; i < DISK_HTAB_SIZE; i++) + LIST_INIT(&disk_record_heads[i]); + + bzero(zero_mem, sizeof(zero_mem)); + return 0; +} + +void taintcheck_cleanup(void) +{ + //clean nic buffer + bzero(nic_bitmap, sizeof(nic_bitmap)); + //clean disk + //TODO: + // AWH - deregister_savevm(), first parm NULL + unregister_savevm(NULL, "taintcheck", 0); +} + +void taintcheck_chk_hdout(const int size, const int64_t sect_num, + const uint32_t offset, const void *s) +{ + taintcheck_taint_disk((uint8_t *)&cpu_single_env->tempidx, sect_num, offset, size, s); +} + +void taintcheck_chk_hdin(const int size, const int64_t sect_num, + const uint32_t offset, const void *s) +{ + taintcheck_disk_check((uint8_t *)&cpu_single_env->tempidx, sect_num, + offset, size, s); +} + +void taintcheck_chk_hdwrite(const ram_addr_t paddr, const int size, const int64_t sect_num, const void *s) +{ + //We assume size is multiple of 512, because this function is used in DMA, and paddr is also aligned. + int i; + uint8_t taint[512]; + if (!taint_tracking_enabled) { + return ; + } + for (i = 0; i < size; i += 512) { + taint_mem_check(paddr+i, 512, taint); + taintcheck_taint_disk(taint, sect_num + i/512, 0, 512, s); + } +} + + +void taintcheck_chk_hdread(const ram_addr_t paddr, const int size, const int64_t sect_num, const void *s) { + //We assume size is multiple of 512, because this function is used in DMA, and paddr is also aligned. + int i; + uint8_t taint[512]; + if (!taint_tracking_enabled) { + return ; + } + for (i = 0; i < size; i += 512) { + taintcheck_disk_check(taint, sect_num + i/512, 0, size, s); + taint_mem(paddr+i, 512, taint); + } +} + +/// \brief check the taint of a memory buffer given the start virtual address. +/// +/// \param vaddr the virtual address of the memory buffer +/// \param size the memory buffer size +/// \param taint the output taint array, it must hold at least [size] bytes +/// \return 0 means success, -1 means failure +int taintcheck_check_virtmem(gva_t vaddr, uint32_t size, uint8_t * taint) +{ + gpa_t paddr = 0, offset; + uint32_t size1, size2; + // uint8_t taint=0; + CPUState *env; + env = cpu_single_env ? cpu_single_env : first_cpu; + + // AWH - If tainting is disabled, return no taint + if (!taint_tracking_enabled) { + bzero(taint, size); + return 0; + } + + paddr = DECAF_get_phys_addr(env,vaddr); + if(paddr == -1) return -1; + + offset = vaddr& ~TARGET_PAGE_MASK; + if(offset+size > TARGET_PAGE_SIZE) { + size1 = TARGET_PAGE_SIZE-offset; + size2 = size -size1; + } else + size1 = size, size2 = 0; + + taint_mem_check(paddr, size1, taint); + if(size2) { + paddr = DECAF_get_phys_addr(env, (vaddr&TARGET_PAGE_MASK) + TARGET_PAGE_SIZE); + if(paddr == -1) + return -1; + + taint_mem_check(paddr, size2, (uint8_t*)(taint+size1)); + } + + return 0; +} + + +/// \brief set taint for a memory buffer given the start virtual address. +/// +/// \param vaddr the virtual address of the memory buffer +/// \param size the memory buffer size +/// \param taint the taint array, it must hold at least [size] bytes +/// \return 0 means success, -1 means failure +int taintcheck_taint_virtmem(gva_t vaddr, uint32_t size, uint8_t * taint) +{ + gpa_t paddr = 0, offset; + uint32_t size1, size2; + // uint8_t taint=0; + CPUState *env; + env = cpu_single_env ? cpu_single_env : first_cpu; + + // AWH - If tainting is disabled, return no taint + if (!taint_tracking_enabled) { + return 0; + } + + paddr = DECAF_get_phys_addr(env,vaddr); + if(paddr == -1) return -1; + + offset = vaddr& ~TARGET_PAGE_MASK; + if(offset+size > TARGET_PAGE_SIZE) { + size1 = TARGET_PAGE_SIZE-offset; + size2 = size -size1; + } else + size1 = size, size2 = 0; + + taint_mem(paddr, size1, taint); + if(size2) { + paddr = DECAF_get_phys_addr(env, (vaddr&TARGET_PAGE_MASK) + TARGET_PAGE_SIZE); + if(paddr == -1) + return -1; + + taint_mem(paddr, size2, (uint8_t*)(taint+size1)); + } + + return 0; +} + + + +void taintcheck_nic_writebuf(const uint32_t addr, const int size, const uint8_t * taint) +{ + memcpy(&nic_bitmap[addr], taint, size); +} + +void taintcheck_nic_readbuf(const uint32_t addr, const int size, uint8_t *taint) +{ + memcpy(taint, &nic_bitmap[addr], size); +} + +void taintcheck_nic_cleanbuf(const uint32_t addr, const int size) +{ + memset(&nic_bitmap[addr], 0, size); +} + +#endif + diff --git a/pool/shard006/C/0119967_pwm-bfin.c b/pool/shard006/C/0119967_pwm-bfin.c new file mode 100644 index 0000000000000000000000000000000000000000..733d24c4b0a741f870fb109d1217bdbfa7b7d85b --- /dev/null +++ b/pool/shard006/C/0119967_pwm-bfin.c @@ -0,0 +1,178 @@ +/* + * Blackfin Pulse Width Modulation (PWM) core + * + * Copyright (c) 2011 Analog Devices Inc. + * + * Licensed under the GPL-2 or later. + */ + +#include +#include +#include +#include + +#include +#include + +struct bfin_pwm_chip +{ + struct pwm_chip chip; +}; + +struct bfin_pwm +{ + unsigned short pin; +}; + +static const unsigned short pwm_to_gptimer_per[] = +{ + P_TMR0, P_TMR1, P_TMR2, P_TMR3, P_TMR4, P_TMR5, + P_TMR6, P_TMR7, P_TMR8, P_TMR9, P_TMR10, P_TMR11, +}; + +static int bfin_pwm_request(struct pwm_chip *chip, struct pwm_device *pwm) +{ + struct bfin_pwm *priv; + int ret; + + if (pwm->hwpwm >= ARRAY_SIZE(pwm_to_gptimer_per)) + { + return -EINVAL; + } + + priv = kzalloc(sizeof(*priv), GFP_KERNEL); + + if (!priv) + { + return -ENOMEM; + } + + priv->pin = pwm_to_gptimer_per[pwm->hwpwm]; + + ret = peripheral_request(priv->pin, NULL); + + if (ret) + { + kfree(priv); + return ret; + } + + pwm_set_chip_data(pwm, priv); + + return 0; +} + +static void bfin_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm) +{ + struct bfin_pwm *priv = pwm_get_chip_data(pwm); + + if (priv) + { + peripheral_free(priv->pin); + kfree(priv); + } +} + +static int bfin_pwm_config(struct pwm_chip *chip, struct pwm_device *pwm, + int duty_ns, int period_ns) +{ + struct bfin_pwm *priv = pwm_get_chip_data(pwm); + unsigned long period, duty; + unsigned long long val; + + val = (unsigned long long)get_sclk() * period_ns; + do_div(val, NSEC_PER_SEC); + period = val; + + val = (unsigned long long)period * duty_ns; + do_div(val, period_ns); + duty = period - val; + + if (duty >= period) + { + duty = period - 1; + } + + set_gptimer_config(priv->pin, TIMER_MODE_PWM | TIMER_PERIOD_CNT); + set_gptimer_pwidth(priv->pin, duty); + set_gptimer_period(priv->pin, period); + + return 0; +} + +static int bfin_pwm_enable(struct pwm_chip *chip, struct pwm_device *pwm) +{ + struct bfin_pwm *priv = pwm_get_chip_data(pwm); + + enable_gptimer(priv->pin); + + return 0; +} + +static void bfin_pwm_disable(struct pwm_chip *chip, struct pwm_device *pwm) +{ + struct bfin_pwm *priv = pwm_get_chip_data(pwm); + + disable_gptimer(priv->pin); +} + +static struct pwm_ops bfin_pwm_ops = +{ + .request = bfin_pwm_request, + .free = bfin_pwm_free, + .config = bfin_pwm_config, + .enable = bfin_pwm_enable, + .disable = bfin_pwm_disable, + .owner = THIS_MODULE, +}; + +static int bfin_pwm_probe(struct platform_device *pdev) +{ + struct bfin_pwm_chip *pwm; + int ret; + + pwm = devm_kzalloc(&pdev->dev, sizeof(*pwm), GFP_KERNEL); + + if (!pwm) + { + dev_err(&pdev->dev, "failed to allocate memory\n"); + return -ENOMEM; + } + + platform_set_drvdata(pdev, pwm); + + pwm->chip.dev = &pdev->dev; + pwm->chip.ops = &bfin_pwm_ops; + pwm->chip.base = -1; + pwm->chip.npwm = 12; + + ret = pwmchip_add(&pwm->chip); + + if (ret < 0) + { + dev_err(&pdev->dev, "pwmchip_add() failed: %d\n", ret); + return ret; + } + + return 0; +} + +static int bfin_pwm_remove(struct platform_device *pdev) +{ + struct bfin_pwm_chip *pwm = platform_get_drvdata(pdev); + + return pwmchip_remove(&pwm->chip); +} + +static struct platform_driver bfin_pwm_driver = +{ + .driver = { + .name = "bfin-pwm", + }, + .probe = bfin_pwm_probe, + .remove = bfin_pwm_remove, +}; + +module_platform_driver(bfin_pwm_driver); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0119970_mtdLib_strings.c b/pool/shard006/C/0119970_mtdLib_strings.c new file mode 100644 index 0000000000000000000000000000000000000000..c4291c5704df8305dfbb0845bb02e51f486baff5 --- /dev/null +++ b/pool/shard006/C/0119970_mtdLib_strings.c @@ -0,0 +1,67 @@ +/* + * String manipulation functions + * Created by: Marco Túlio + * */ + +#include +#include +#include + +/* Function to get number of Columns by delimiter from an string */ +int mtdLib_str_getColNumbers(char *array, char delimiter) +{ + int pos, count; + pos = count = 0; + for (pos=0; array[pos]!='\0'; pos++) + if (array[pos] == delimiter) + count++; + + // check line is not finishing with delimiter. Eg. delimiter=',': [A,B,] + if (array[pos-1]!=delimiter) + count++; + + return count; +} + +/* Get integer value from column by position of delimiter - number of + * column could be get by function mtdLib_str_getColNumbers() */ +void mtdLib_str_getColByDelPos_int(char *array_in, char delimiter, int posDel, int *resp) +{ + int count=1; // considering that exist at least delimiter + + char *buff; + buff = malloc(sizeof(char *)*strlen(array_in)); + memset(buff,strlen(buff),'\0'); + + for (int posA=0, posB=0; posA + * Author: Kevin JOLY joly.kevin25@gmail.com + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#ifndef CONFIG_MACH_APF9328 /* To remove when MX1 platform is merged */ +#include +#endif + +#include "../../virtual_components/pod_gpio/pod_gpio.h" + +/*$foreach:instance$*/ +#define /*$instance_name$*/_BASE /*$registers_base_address:swb16$*/ +/*$foreach:instance:end$*/ + +/*$foreach:instance$*/ +static struct resource /*$instance_name$*/_resources[] = { + [0] = { + .start = ARMADEUS_FPGA_BASE_ADDR + /*$instance_name$*/_BASE, + .end = ARMADEUS_FPGA_BASE_ADDR + /*$instance_name$*/_BASE + 0x07, + .flags = IORESOURCE_MEM | IORESOURCE_MEM_16BIT, + }, + [1] = { + .start = IRQ_FPGA(/*$interrupt_number$*/), + .end = IRQ_FPGA(/*$interrupt_number$*/), + .flags = IORESOURCE_IRQ, + } +}; + +void /*$instance_name$*/_release(struct device *dev) +{ + dev_dbg(dev, "released\n"); +} + +static struct platform_device /*$instance_name$*/_pdev = { + .name = pod_gpio_DRIVER_NAME, + .id = /*$generic:id$*/, + .dev = { + .release = /*$instance_name$*/_release, + }, + .num_resources = ARRAY_SIZE(/*$instance_name$*/_resources), + .resource = /*$instance_name$*/_resources, +}; +/*$foreach:instance:end$*/ + +static int __init pod_gpio_platform_init(void) +{ + int ret; + +/*$foreach:instance$*/ + ret = platform_device_register(&/*$instance_name$*/_pdev); + if (ret < 0) + printk(KERN_ERR "Error: Can't init device /*$instance_name$*/\n"); +/*$foreach:instance:end$*/ + + return ret; +} +module_init(pod_gpio_platform_init); + +static void __exit pod_gpio_platform_exit(void) +{ +/*$foreach:instance$*/ + platform_device_unregister(&/*$instance_name$*/_pdev); +/*$foreach:instance:end$*/ +} +module_exit(pod_gpio_platform_exit); + +MODULE_AUTHOR("Kevin Joly "); +MODULE_DESCRIPTION("GPIO driver for pod_gpio component of POD"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard006/C/0119974_usb_descriptors.c b/pool/shard006/C/0119974_usb_descriptors.c new file mode 100644 index 0000000000000000000000000000000000000000..b1edfcc18fd8ff7f564ccbe068a0e478cc51e344 --- /dev/null +++ b/pool/shard006/C/0119974_usb_descriptors.c @@ -0,0 +1,117 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2019 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 "tusb.h" + +#ifndef MICROPY_HW_USB_VID +#define MICROPY_HW_USB_VID (0xf055) +#define MICROPY_HW_USB_PID (0x9802) +#endif + +#define USBD_DESC_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN) +#define USBD_MAX_POWER_MA (250) + +#define USBD_ITF_CDC (0) // needs 2 interfaces +#define USBD_ITF_MAX (2) + +#define USBD_CDC_EP_CMD (0x81) +#define USBD_CDC_EP_OUT (0x02) +#define USBD_CDC_EP_IN (0x82) +#define USBD_CDC_CMD_MAX_SIZE (8) +#define USBD_CDC_IN_OUT_MAX_SIZE (64) + +#define USBD_STR_0 (0x00) +#define USBD_STR_MANUF (0x01) +#define USBD_STR_PRODUCT (0x02) +#define USBD_STR_SERIAL (0x03) +#define USBD_STR_CDC (0x04) + +// Note: descriptors returned from callbacks must exist long enough for transfer to complete + +static const tusb_desc_device_t usbd_desc_device = { + .bLength = sizeof(tusb_desc_device_t), + .bDescriptorType = TUSB_DESC_DEVICE, + .bcdUSB = 0x0200, + .bDeviceClass = TUSB_CLASS_MISC, + .bDeviceSubClass = MISC_SUBCLASS_COMMON, + .bDeviceProtocol = MISC_PROTOCOL_IAD, + .bMaxPacketSize0 = CFG_TUD_ENDOINT0_SIZE, + .idVendor = MICROPY_HW_USB_VID, + .idProduct = MICROPY_HW_USB_PID, + .bcdDevice = 0x0100, + .iManufacturer = USBD_STR_MANUF, + .iProduct = USBD_STR_PRODUCT, + .iSerialNumber = USBD_STR_SERIAL, + .bNumConfigurations = 1, +}; + +static const uint8_t usbd_desc_cfg[USBD_DESC_LEN] = { + TUD_CONFIG_DESCRIPTOR(1, USBD_ITF_MAX, USBD_STR_0, USBD_DESC_LEN, + TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, USBD_MAX_POWER_MA), + + TUD_CDC_DESCRIPTOR(USBD_ITF_CDC, USBD_STR_CDC, USBD_CDC_EP_CMD, + USBD_CDC_CMD_MAX_SIZE, USBD_CDC_EP_OUT, USBD_CDC_EP_IN, USBD_CDC_IN_OUT_MAX_SIZE), +}; + +static const char *const usbd_desc_str[] = { + [USBD_STR_MANUF] = "MicroPython", + [USBD_STR_PRODUCT] = "Board in FS mode", + [USBD_STR_SERIAL] = "000000000000", // TODO + [USBD_STR_CDC] = "Board CDC", +}; + +const uint8_t *tud_descriptor_device_cb(void) { + return (const uint8_t*)&usbd_desc_device; +} + +const uint8_t *tud_descriptor_configuration_cb(uint8_t index) { + (void)index; + return usbd_desc_cfg; +} + +const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + #define DESC_STR_MAX (20) + static uint16_t desc_str[DESC_STR_MAX]; + + uint8_t len; + if (index == 0) { + desc_str[1] = 0x0409; // supported language is English + len = 1; + } else { + if (index >= sizeof(usbd_desc_str) / sizeof(usbd_desc_str[0])) { + return NULL; + } + const char* str = usbd_desc_str[index]; + for (len = 0; len < DESC_STR_MAX - 1 && str[len]; ++len) { + desc_str[1 + len] = str[len]; + } + } + + // first byte is length (including header), second byte is string type + desc_str[0] = (TUSB_DESC_STRING << 8 ) | (2 * len + 2); + + return desc_str; +} diff --git a/pool/shard006/C/0119976_findsaddr-socket.c b/pool/shard006/C/0119976_findsaddr-socket.c new file mode 100644 index 0000000000000000000000000000000000000000..39c81349478e3673e0117fb4f2bdc65bce54ad98 --- /dev/null +++ b/pool/shard006/C/0119976_findsaddr-socket.c @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2000 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Computer Systems + * Engineering Group at Lawrence Berkeley Laboratory. + * 4. Neither the name of the University nor of the Laboratory may be used + * to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. + */ + +/* XXX Yes this is WAY too complicated */ + +#ifndef lint +static const char rcsid[] = + "@(#) $Id: findsaddr-socket.c,v 1.1 2000/11/23 20:17:12 leres Exp $ (LBL)"; +#endif + +#include +#include +#include +#include +#ifdef HAVE_SYS_SOCKIO_H +#include +#endif +#include /* concession to AIX */ + +#if __STDC__ +struct mbuf; +struct rtentry; +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "gnuc.h" +#ifdef HAVE_OS_PROTO_H +#include "os-proto.h" +#endif + +#include "findsaddr.h" + +#ifdef HAVE_SOCKADDR_SA_LEN +#define SALEN(sa) ((sa)->sa_len) +#else +#define SALEN(sa) salen(sa) +#endif + +#ifndef roundup +#define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */ +#endif + +struct rtmsg { + struct rt_msghdr rtmsg; + u_char data[512]; +}; + +static struct rtmsg rtmsg = { + { 0, RTM_VERSION, RTM_GET, 0, + RTF_UP | RTF_GATEWAY | RTF_HOST | RTF_STATIC, + RTA_DST | RTA_IFA, 0, 0, 0, 0, 0, { 0 } }, + { 0 } +}; + +#ifndef HAVE_SOCKADDR_SA_LEN +static int salen(struct sockaddr *); +#endif + +/* + * Return the source address for the given destination address + */ +const char * +findsaddr(register const struct sockaddr_in *to, + register struct sockaddr_in *from) +{ + register struct rt_msghdr *rp; + register u_char *cp; + + register struct sockaddr_in *sp, *ifa; + register struct sockaddr *sa; + register int s, size, cc, seq, i; + register pid_t pid; + static char errbuf[512]; + + s = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC); + if (s < 0) { + sprintf(errbuf, "socket: %.128s", strerror(errno)); + return (errbuf); + } + + seq = 0; + pid = getpid(); + + rp = &rtmsg.rtmsg; + rp->rtm_seq = ++seq; + cp = (u_char *)(rp + 1); + + sp = (struct sockaddr_in *)cp; + *sp = *to; + cp += roundup(SALEN((struct sockaddr *)sp), sizeof(u_int32_t)); + + size = cp - (u_char *)rp; + rp->rtm_msglen = size; + + cc = write(s, (char *)rp, size); + if (cc < 0) { + sprintf(errbuf, "write: %.128s", strerror(errno)); + close(s); + return (errbuf); + } + if (cc != size) { + sprintf(errbuf, "short write (%d != %d)", cc, size); + close(s); + return (errbuf); + } + + size = sizeof(rtmsg); + do { + memset(rp, 0, size); + cc = read(s, (char *)rp, size); + if (cc < 0) { + sprintf(errbuf, "read: %.128s", strerror(errno)); + close(s); + return (errbuf); + } + + } while (rp->rtm_seq != seq || rp->rtm_pid != pid); + close(s); + + + if (rp->rtm_version != RTM_VERSION) { + sprintf(errbuf, "bad version %d", rp->rtm_version); + return (errbuf); + } + if (rp->rtm_msglen > cc) { + sprintf(errbuf, "bad msglen %d > %d", rp->rtm_msglen, cc); + return (errbuf); + } + if (rp->rtm_errno != 0) { + sprintf(errbuf, "rtm_errno: %.128s", strerror(rp->rtm_errno)); + return (errbuf); + } + + /* Find the interface sockaddr */ + cp = (u_char *)(rp + 1); + for (i = 1; i != 0; i <<= 1) + if ((i & rp->rtm_addrs) != 0) { + sa = (struct sockaddr *)cp; + switch (i) { + + case RTA_IFA: + if (sa->sa_family == AF_INET) { + ifa = (struct sockaddr_in *)cp; + if (ifa->sin_addr.s_addr != 0) { + *from = *ifa; + return (NULL); + } + } + break; + + default: + /* empty */ + } + + if (SALEN(sa) == 0) + cp += sizeof(u_int32_t); + else + cp += roundup(SALEN(sa), sizeof(u_int32_t)); + } + + return ("failed!"); +} + +#ifndef HAVE_SOCKADDR_SA_LEN +static int +salen(struct sockaddr *sa) +{ + switch (sa->sa_family) { + + case AF_INET: + return (sizeof(struct sockaddr_in)); + + case AF_LINK: + return (sizeof(struct sockaddr_dl)); + + default: + return (sizeof(struct sockaddr)); + } +} +#endif diff --git a/pool/shard006/C/0119978_unit_test_map.c b/pool/shard006/C/0119978_unit_test_map.c new file mode 100644 index 0000000000000000000000000000000000000000..16c963051006666e78e42fa7f412f2badcc61268 --- /dev/null +++ b/pool/shard006/C/0119978_unit_test_map.c @@ -0,0 +1,222 @@ +/* + * unit_test_map.c Map debugging tool. + * + * Version: $Id$ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + * + * @copyright 2015 Alan DeKok + */ + +RCSID("$Id$") + +#include + +#include +#include +#include + +#include + +#ifdef HAVE_GETOPT_H +# include +#endif + +#include + +#include + +module_instance_t *module_find_with_method(UNUSED rlm_components_t *method, + UNUSED CONF_SECTION *modules, UNUSED char const *name) +{ + return NULL; +} + +module_thread_instance_t *module_thread_instance_find(UNUSED module_instance_t *mi) +{ + return NULL; +} + +/* Linker hacks */ + +static void NEVER_RETURNS usage(void) +{ + fprintf(stderr, "usage: unit_test_map [OPTS] filename ...\n"); + fprintf(stderr, " -d Set user dictionary directory (defaults to " RADDBDIR ").\n"); + fprintf(stderr, " -D Set main dictionary directory (defaults to " DICTDIR ").\n"); + fprintf(stderr, " -O Set output directory\n"); + fprintf(stderr, " -x Debugging mode.\n"); + fprintf(stderr, " -M Show program version information.\n"); + + exit(EXIT_FAILURE); +} + +static int process_file(char const *filename) +{ + int rcode; + char const *name1, *name2; + CONF_SECTION *cs; + vp_map_t *head, *map; + char buffer[8192]; + + main_config_t *config; + + vp_tmpl_rules_t parse_rules = { + .allow_foreign = true /* Because we don't know what protocol we're operating with */ + }; + + config = main_config_alloc(NULL); + if (!config) { + fprintf(stderr, "Failed allocating main config"); + exit(EXIT_FAILURE); + } + config->root_cs = cf_section_alloc(config, NULL, "main", NULL); + if ((cf_file_read(config->root_cs, filename) < 0) || (cf_section_pass2(config->root_cs) < 0)) { + fprintf(stderr, "unit_test_map: Failed parsing %s\n", filename); + exit(EXIT_FAILURE); + } + + main_config_name_set_default(config, "unit_test_map", false); + + /* + * Always has to be an "update" section. + */ + cs = cf_section_find(config->root_cs, "update", CF_IDENT_ANY); + if (!cs) { + talloc_free(config->root_cs); + return -1; + } + + /* + * Convert the update section to a list of maps. + */ + rcode = map_afrom_cs(&head, cs, &parse_rules, &parse_rules, unlang_fixup_update, NULL, 128); + if (rcode < 0) { + cf_log_err(cs, "map_afrom_cs failed: %s", fr_strerror()); + return -1; /* message already printed */ + } + if (!head) { + cf_log_err(cs, "'update' sections cannot be empty"); + return -1; + } + + buffer[0] = '\t'; + + name1 = cf_section_name1(cs); + name2 = cf_section_name2(cs); + + /* + * And print it all out. + */ + if (!name2) { + printf("%s {\n", name1); + } else { + printf("%s %s {\n", name1, name2); + } + + for (map = head; map != NULL; map = map->next) { + map_snprint(buffer + 1, sizeof(buffer) - 1, map); + puts(buffer); + } + printf("}\n"); + + talloc_free(config->root_cs); + talloc_free(config); + + return 0; +} + +int main(int argc, char *argv[]) +{ + int c, rcode = 0; + char const *raddb_dir = RADDBDIR; + char const *dict_dir = DICTDIR; + fr_dict_t *dict = NULL; + + TALLOC_CTX *autofree = talloc_autofree_context(); + +#ifndef NDEBUG + if (fr_fault_setup(autofree, getenv("PANIC_ACTION"), argv[0]) < 0) { + fr_perror("unit_test_map"); + exit(EXIT_FAILURE); + } +#endif + + while ((c = getopt(argc, argv, "d:D:xMh")) != EOF) switch (c) { + case 'd': + raddb_dir = optarg; + break; + + case 'D': + dict_dir = optarg; + break; + + case 'x': + fr_debug_lvl++; + rad_debug_lvl = fr_debug_lvl; + break; + + case 'M': + talloc_enable_leak_report(); + break; + + case 'h': + default: + usage(); + } + argc -= (optind - 1); + argv += (optind - 1); + + /* + * Mismatch between the binary and the libraries it depends on + */ + if (fr_check_lib_magic(RADIUSD_MAGIC_NUMBER) < 0) { + fr_perror("unit_test_map"); + exit(EXIT_FAILURE); + } + + if (fr_dict_global_init(autofree, dict_dir) < 0) { + fr_perror("unit_test_map"); + exit(EXIT_FAILURE); + } + + if (fr_dict_from_file(&dict, FR_DICTIONARY_FILE) < 0) { + fr_perror("unit_test_map"); + exit(EXIT_FAILURE); + } + + if (fr_dict_read(dict, raddb_dir, FR_DICTIONARY_FILE) == -1) { + fr_log_perror(&default_log, L_ERR, "Failed to initialize the dictionaries"); + exit(EXIT_FAILURE); + } + + if (argc < 2) { + rcode = process_file("-"); + + } else { + rcode = process_file(argv[1]); + } + + if (rcode < 0) rcode = 1; /* internal to Unix process return code */ + + /* + * Try really hard to free any allocated + * memory, so we get clean talloc reports. + */ + xlat_free(); + fr_strerror_free(); + + return rcode; +} diff --git a/pool/shard006/C/0119982_shmem.c b/pool/shard006/C/0119982_shmem.c new file mode 100644 index 0000000000000000000000000000000000000000..5ead8e755d855777d108d141a8bc3b0d4ee8f45a --- /dev/null +++ b/pool/shard006/C/0119982_shmem.c @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015, Xilinx Inc. and Contributors. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +/* + * @file generic/shmem.c + * @brief Generic libmetal shared memory handling. + */ + +#include +#include +#include +#include +#include + +int metal_shmem_register_generic(struct metal_generic_shmem *shmem) +{ + /* Make sure that we can be found. */ + metal_assert(shmem->name && strlen(shmem->name) != 0); + + /* Statically registered shmem regions cannot have a destructor. */ + metal_assert(!shmem->io.ops.close); + + metal_list_add_tail(&_metal.common.generic_shmem_list, + &shmem->node); + return 0; +} + +int metal_shmem_open_generic(const char *name, size_t size, + struct metal_io_region **result) +{ + struct metal_generic_shmem *shmem; + struct metal_list *node; + + metal_list_for_each(&_metal.common.generic_shmem_list, node) { + shmem = metal_container_of(node, struct metal_generic_shmem, node); + if (strcmp(shmem->name, name) != 0) + continue; + if (size > metal_io_region_size(&shmem->io)) + continue; + *result = &shmem->io; + return 0; + } + + return -ENOENT; +} diff --git a/pool/shard006/C/0119983_uniform_ld.c b/pool/shard006/C/0119983_uniform_ld.c new file mode 100644 index 0000000000000000000000000000000000000000..d12004d9dd698d6181b30979dbea2f6fdbd972d5 --- /dev/null +++ b/pool/shard006/C/0119983_uniform_ld.c @@ -0,0 +1,108 @@ +/* The batman package: fast computation of exoplanet transit light curves + * Copyright (C) 2015 Laura Kreidberg + * + * 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 . + */ + +#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION +#include +#include "numpy/arrayobject.h" +#include + +#if defined (_OPENMP) +# include +#endif + +#ifndef M_PI + #define M_PI 3.14159265358979323846 +#endif + +static PyObject *_uniform_ld(PyObject *self, PyObject *args) +{ + int nthreads; + double d, p, kap0, kap1; + + PyArrayObject *ds, *flux; + npy_intp i, dims[1]; + + if(!PyArg_ParseTuple(args, "Odi", &ds, &p, &nthreads)) return NULL; //parses function input + + dims[0] = PyArray_DIMS(ds)[0]; + flux = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_TYPE(ds)); //creates numpy array to store return flux values + + double *f_array = PyArray_DATA(flux); + double *d_array = PyArray_DATA(ds); + + if(fabs(p - 0.5) < 1.e-3) p = 0.5; + + #if defined (_OPENMP) + omp_set_num_threads(nthreads); + #endif + + #if defined (_OPENMP) + #pragma omp parallel for private(d, kap1, kap0) + #endif + for(i=0; i= 1. + p) f_array[i] = 1.; //no overlap + if(p >= 1. && d <= p - 1.) f_array[i] = 0.; //total eclipse of the star + else if(d <= 1. - p) f_array[i] = 1. - p*p; //planet is fully in transit + else //planet is crossing the limb + { + kap1=acos(fmin((1. - p*p + d*d)/2./d, 1.)); + kap0=acos(fmin((p*p + d*d - 1.)/2./p/d, 1.)); + f_array[i] = 1. - (p*p*kap0 + kap1 - 0.5*sqrt(fmax(4.*d*d - pow(1. + d*d - p*p, 2.), 0.)))/M_PI; + } + } + + return PyArray_Return((PyArrayObject *)flux); +} + + +static char _uniform_ld_doc[] = "This extension module returns a limb darkened light curve for a uniform stellar intensity profile."; + +static PyMethodDef _uniform_ld_methods[] = { + {"_uniform_ld", _uniform_ld, METH_VARARGS, _uniform_ld_doc},{NULL}}; + +#if PY_MAJOR_VERSION >= 3 + static struct PyModuleDef _uniform_ld_module = { + PyModuleDef_HEAD_INIT, + "_uniform_ld", + _uniform_ld_doc, + -1, + _uniform_ld_methods + }; + + PyMODINIT_FUNC + PyInit__uniform_ld(void) + { + PyObject* module = PyModule_Create(&_uniform_ld_module); + if(!module) + { + return NULL; + } + import_array(); + return module; + } +#else + + void init_uniform_ld(void) + { + Py_InitModule("_uniform_ld", _uniform_ld_methods); + import_array(); + } +#endif + diff --git a/pool/shard006/C/0119988_cc-panel-loader.c b/pool/shard006/C/0119988_cc-panel-loader.c new file mode 100644 index 0000000000000000000000000000000000000000..79a0fb12b3d3673fb0f95440aed37f191122d594 --- /dev/null +++ b/pool/shard006/C/0119988_cc-panel-loader.c @@ -0,0 +1,331 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ +/* + * Copyright (c) 2012 Giovanni Campagna + * + * The Control Center 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. + * + * The Control Center 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 the Control Center; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: Thomas Wood + */ + +#include + +#include +#include +#include + +#include "cc-panel.h" +#include "cc-panel-loader.h" + +#ifndef CC_PANEL_LOADER_NO_GTYPES + +/* Extension points */ +extern GType cc_applications_panel_get_type (void); +extern GType cc_background_panel_get_type (void); +#ifdef BUILD_BLUETOOTH +extern GType cc_bluetooth_panel_get_type (void); +#endif /* BUILD_BLUETOOTH */ +extern GType cc_color_panel_get_type (void); +extern GType cc_date_time_panel_get_type (void); +extern GType cc_default_apps_panel_get_type (void); +extern GType cc_display_panel_get_type (void); +extern GType cc_info_overview_panel_get_type (void); +extern GType cc_keyboard_panel_get_type (void); +extern GType cc_mouse_panel_get_type (void); +extern GType cc_multitasking_panel_get_type (void); +#ifdef BUILD_NETWORK +extern GType cc_network_panel_get_type (void); +extern GType cc_wifi_panel_get_type (void); +#endif /* BUILD_NETWORK */ +extern GType cc_notifications_panel_get_type (void); +extern GType cc_goa_panel_get_type (void); +extern GType cc_power_panel_get_type (void); +extern GType cc_printers_panel_get_type (void); +extern GType cc_region_panel_get_type (void); +extern GType cc_removable_media_panel_get_type (void); +extern GType cc_search_panel_get_type (void); +extern GType cc_sharing_panel_get_type (void); +extern GType cc_sound_panel_get_type (void); +#ifdef BUILD_THUNDERBOLT +extern GType cc_bolt_panel_get_type (void); +#endif /* BUILD_THUNDERBOLT */ +extern GType cc_ua_panel_get_type (void); +extern GType cc_updates_panel_get_type (void); +extern GType cc_user_panel_get_type (void); +#ifdef BUILD_WACOM +extern GType cc_wacom_panel_get_type (void); +#endif /* BUILD_WACOM */ +#ifdef BUILD_WWAN +extern GType cc_wwan_panel_get_type (void); +#endif /* BUILD_WWAN */ +extern GType cc_location_panel_get_type (void); +extern GType cc_camera_panel_get_type (void); +extern GType cc_microphone_panel_get_type (void); +extern GType cc_usage_panel_get_type (void); +extern GType cc_lock_panel_get_type (void); +extern GType cc_diagnostics_panel_get_type (void); +extern GType cc_metrics_panel_get_type (void); + +/* Static init functions */ +extern void cc_diagnostics_panel_static_init_func (void); +#ifdef BUILD_NETWORK +extern void cc_wifi_panel_static_init_func (void); +#endif /* BUILD_NETWORK */ +#ifdef BUILD_WACOM +extern void cc_wacom_panel_static_init_func (void); +#endif /* BUILD_WACOM */ +#ifdef BUILD_WWAN +extern void cc_wwan_panel_static_init_func (void); +#endif /* BUILD_WWAN */ + +#define PANEL_TYPE(name, get_type, init_func) { name, get_type, init_func } + +#else /* CC_PANEL_LOADER_NO_GTYPES */ + +#define PANEL_TYPE(name, get_type, init_func) { name } + +#endif + +static CcPanelLoaderVtable default_panels[] = +{ + PANEL_TYPE("applications", cc_applications_panel_get_type, NULL), + PANEL_TYPE("background", cc_background_panel_get_type, NULL), +#ifdef BUILD_BLUETOOTH + PANEL_TYPE("bluetooth", cc_bluetooth_panel_get_type, NULL), +#endif + PANEL_TYPE("camera", cc_camera_panel_get_type, NULL), + PANEL_TYPE("color", cc_color_panel_get_type, NULL), + PANEL_TYPE("datetime", cc_date_time_panel_get_type, NULL), + PANEL_TYPE("default-apps", cc_default_apps_panel_get_type, NULL), + PANEL_TYPE("diagnostics", cc_diagnostics_panel_get_type, cc_diagnostics_panel_static_init_func), + PANEL_TYPE("display", cc_display_panel_get_type, NULL), + PANEL_TYPE("info-overview", cc_info_overview_panel_get_type, NULL), + PANEL_TYPE("keyboard", cc_keyboard_panel_get_type, NULL), + PANEL_TYPE("location", cc_location_panel_get_type, NULL), + PANEL_TYPE("lock", cc_lock_panel_get_type, NULL), + PANEL_TYPE("metrics", cc_metrics_panel_get_type, NULL), + PANEL_TYPE("microphone", cc_microphone_panel_get_type, NULL), + PANEL_TYPE("mouse", cc_mouse_panel_get_type, NULL), + PANEL_TYPE("multitasking", cc_multitasking_panel_get_type, NULL), +#ifdef BUILD_NETWORK + PANEL_TYPE("network", cc_network_panel_get_type, NULL), + PANEL_TYPE("wifi", cc_wifi_panel_get_type, cc_wifi_panel_static_init_func), +#endif + PANEL_TYPE("notifications", cc_notifications_panel_get_type, NULL), + PANEL_TYPE("online-accounts", cc_goa_panel_get_type, NULL), + PANEL_TYPE("power", cc_power_panel_get_type, NULL), + PANEL_TYPE("printers", cc_printers_panel_get_type, NULL), + PANEL_TYPE("region", cc_region_panel_get_type, NULL), + PANEL_TYPE("removable-media", cc_removable_media_panel_get_type, NULL), + PANEL_TYPE("search", cc_search_panel_get_type, NULL), + PANEL_TYPE("sharing", cc_sharing_panel_get_type, NULL), + PANEL_TYPE("sound", cc_sound_panel_get_type, NULL), +#ifdef BUILD_THUNDERBOLT + PANEL_TYPE("thunderbolt", cc_bolt_panel_get_type, NULL), +#endif + PANEL_TYPE("universal-access", cc_ua_panel_get_type, NULL), + PANEL_TYPE("updates", cc_updates_panel_get_type, NULL), + PANEL_TYPE("usage", cc_usage_panel_get_type, NULL), + PANEL_TYPE("user-accounts", cc_user_panel_get_type, NULL), +#ifdef BUILD_WACOM + PANEL_TYPE("wacom", cc_wacom_panel_get_type, cc_wacom_panel_static_init_func), +#endif +#ifdef BUILD_WWAN + PANEL_TYPE("wwan", cc_wwan_panel_get_type, cc_wwan_panel_static_init_func), +#endif +}; + +/* Override for the panel vtable. When NULL, the default_panels will + * be used. + */ +static CcPanelLoaderVtable *panels_vtable = default_panels; +static gsize panels_vtable_len = G_N_ELEMENTS (default_panels); + + +static int +parse_categories (GDesktopAppInfo *app) +{ + g_auto(GStrv) split = NULL; + const gchar *categories; + gint retval; + + categories = g_desktop_app_info_get_categories (app); + split = g_strsplit (categories, ";", -1); + + retval = -1; + +#define const_strv(s) ((const gchar* const*) s) + + if (g_strv_contains (const_strv (split), "X-GNOME-ConnectivitySettings")) + retval = CC_CATEGORY_CONNECTIVITY; + else if (g_strv_contains (const_strv (split), "X-GNOME-PersonalizationSettings")) + retval = CC_CATEGORY_PERSONALIZATION; + else if (g_strv_contains (const_strv (split), "X-GNOME-AccountSettings")) + retval = CC_CATEGORY_ACCOUNT; + else if (g_strv_contains (const_strv (split), "X-GNOME-DevicesSettings")) + retval = CC_CATEGORY_DEVICES; + else if (g_strv_contains (const_strv (split), "X-GNOME-DetailsSettings")) + retval = CC_CATEGORY_DETAILS; + else if (g_strv_contains (const_strv (split), "X-GNOME-PrivacySettings")) + retval = CC_CATEGORY_PRIVACY; + else if (g_strv_contains (const_strv (split), "HardwareSettings")) + retval = CC_CATEGORY_HARDWARE; + +#undef const_strv + + if (retval < 0) + { + g_warning ("Invalid categories %s for panel %s", + categories, g_app_info_get_id (G_APP_INFO (app))); + } + + return retval; +} + +#ifndef CC_PANEL_LOADER_NO_GTYPES + +static GHashTable *panel_types; + +static void +ensure_panel_types (void) +{ + int i; + + if (G_LIKELY (panel_types != NULL)) + return; + + panel_types = g_hash_table_new (g_str_hash, g_str_equal); + for (i = 0; i < panels_vtable_len; i++) + g_hash_table_insert (panel_types, (char*)panels_vtable[i].name, panels_vtable[i].get_type); +} + +/** + * cc_panel_loader_load_by_name: + * @shell: a #CcShell implementation + * @name: name of the panel + * @parameters: parameters passed to the new panel + * + * Creates a new instance of a #CcPanel from @name, and sets the + * @shell and @parameters properties at construction time. + */ +CcPanel * +cc_panel_loader_load_by_name (CcShell *shell, + const gchar *name, + GVariant *parameters) +{ + GType (*get_type) (void); + + ensure_panel_types (); + + get_type = g_hash_table_lookup (panel_types, name); + g_assert (get_type != NULL); + + return g_object_new (get_type (), + "shell", shell, + "parameters", parameters, + NULL); +} + +#endif /* CC_PANEL_LOADER_NO_GTYPES */ + +/** + * cc_panel_loader_fill_model: + * @model: a #CcShellModel + * + * Fills @model with information from the available panels. It + * iterates over the panel vtable, gathering the panel names, + * build the desktop filename from it, and retrieves additional + * information from it. + */ +void +cc_panel_loader_fill_model (CcShellModel *model) +{ + guint i; + + for (i = 0; i < panels_vtable_len; i++) + { + g_autoptr(GDesktopAppInfo) app = NULL; + g_autofree gchar *desktop_name = NULL; + gint category; + + desktop_name = g_strconcat ("gnome-", panels_vtable[i].name, "-panel.desktop", NULL); + app = g_desktop_app_info_new (desktop_name); + + if (!app) + { + g_warning ("Ignoring broken panel %s (missing desktop file)", panels_vtable[i].name); + continue; + } + + category = parse_categories (app); + if (G_UNLIKELY (category < 0)) + continue; + + cc_shell_model_add_item (model, category, G_APP_INFO (app), panels_vtable[i].name); + } + + /* If there's an static init function, execute it after adding all panels to + * the model. This will allow the panels to show or hide themselves without + * having an instance running. + */ +#ifndef CC_PANEL_LOADER_NO_GTYPES + for (i = 0; i < panels_vtable_len; i++) + { + if (panels_vtable[i].static_init_func) + panels_vtable[i].static_init_func (); + } +#endif +} + +/** + * cc_panel_loader_list_panels: + * + * Prints the list of panels from the current panel vtable, + * usually as response to running GNOME Settings with the + * '--list' command line argument. + */ +void +cc_panel_loader_list_panels (void) +{ + guint i; + + g_print ("%s\n", _("Available panels:")); + + for (i = 0; i < panels_vtable_len; i++) + g_print ("\t%s\n", panels_vtable[i].name); + +} + +/** + * cc_panel_loader_override_vtable: + * @override_vtable: the new panel vtable + * @n_elements: number of items of @override_vtable + * + * Override the default panel vtable so that GNOME Settings loads + * a custom set of panels. Intended to be used by tests to inject + * panels that exercise specific interactions with CcWindow (e.g. + * header widgets, permissions, etc). + */ +void +cc_panel_loader_override_vtable (CcPanelLoaderVtable *override_vtable, + gsize n_elements) +{ + g_assert (override_vtable != NULL); + g_assert (n_elements > 0); + + g_debug ("Overriding default panel vtable"); + + panels_vtable = override_vtable; + panels_vtable_len = n_elements; +} diff --git a/pool/shard006/C/0119989_softintr.c b/pool/shard006/C/0119989_softintr.c new file mode 100644 index 0000000000000000000000000000000000000000..820ee2c813698c5df2be9cc45a23ad5d7ce5fc3c --- /dev/null +++ b/pool/shard006/C/0119989_softintr.c @@ -0,0 +1,201 @@ +/* $NetBSD: softintr.c,v 1.6 2001/11/27 01:12:55 thorpej Exp $ */ + +/*- + * Copyright (c) 2001 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by IWAMOTO Toshihiro. + * + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include + +#include +#include +#include + +extern int ipl_to_spl(int); +void softintr_free(void *); + +struct softintr_handler { + struct softintr_handler *sh_vlink; /* vertical link */ + struct softintr_handler *sh_hlink; /* horizontal link */ + + void (*sh_fun)(void *); + void *sh_arg; + int sh_level; + + int sh_pending; +}; + +struct softintr_handler *softintrs; +struct softintr_handler *softintr_pending; + +void * +softintr_establish(int level, void (*fun)(void *), void *arg) +{ + struct softintr_handler *sh; + + sh = malloc(sizeof(*sh), M_DEVBUF, M_NOWAIT); + if (sh == NULL) + return(NULL); + + sh->sh_fun = fun; + sh->sh_level = ipl_to_spl(level); + sh->sh_arg = arg; + sh->sh_pending = 0; + + return sh; +} + +void +softintr_disestablish(void *cookie) +{ + struct softintr_handler *sh = cookie; + u_int saved_cpsr; + + saved_cpsr = SetCPSR(I32_bit, I32_bit); + if (sh->sh_pending) { + sh->sh_fun = softintr_free; + sh->sh_arg = sh; + SetCPSR(I32_bit, I32_bit & saved_cpsr); + } else { + SetCPSR(I32_bit, I32_bit & saved_cpsr); + free(sh, M_DEVBUF); + } +} + +void +softintr_free(void *arg) +{ + + free(arg, M_DEVBUF); +} + +void +softintr_schedule(void *cookie) +{ + struct softintr_handler **p, *sh = cookie; + register int pending, saved_cpsr; + + pending = 1; + asm("swp %0, %0, [%1]" : "+r" (pending) : "r" (&sh->sh_pending)); + + if (pending) + return; + + sh->sh_vlink = NULL; + sh->sh_hlink = NULL; + +#ifdef __GNUC__ + asm volatile("mrs %0, cpsr_all\n orr r1, %0, %1\n msr cpsr_all, r1" : + "=r" (saved_cpsr) : "i" (I32_bit) : "r1"); +#else + saved_cpsr = SetCPSR(I32_bit, I32_bit); +#endif + p = &softintr_pending; + + for (;; p = &(*p)->sh_vlink) { + if (*p == NULL) + goto set_and_exit; + + if ((*p)->sh_level <= sh->sh_level) + break; + } + + if ((*p)->sh_level == sh->sh_level) { + sh->sh_hlink = *p; + sh->sh_vlink = (*p)->sh_vlink; + goto set_and_exit; + } + + sh->sh_vlink = *p; +set_and_exit: + *p = sh; +#ifdef __GNUC__ + asm volatile("msr cpsr_c, %0" : : "r" (saved_cpsr)); +#else + SetCPSR(I32_bit, I32_bit & saved_cpsr); +#endif + return; +} + +void +softintr_dispatch(int s) +{ + struct softintr_handler *sh, *sh1; + register int saved_cpsr; + + while (1) { + /* Protect list operation from interrupts */ +#ifdef __GNUC__ + asm volatile("mrs %0, cpsr_all\n orr r1, %0, %1\n" + " msr cpsr_all, r1" : "=r" (saved_cpsr) : + "i" (I32_bit) : "r1"); +#else + saved_cpsr = SetCPSR(I32_bit, I32_bit); +#endif + + if (softintr_pending == NULL || + softintr_pending->sh_level <= s) { +#ifdef __GNUC__ + asm("msr cpsr_c, %0" : : "r" (saved_cpsr)); +#else + SetCPSR(I32_bit, I32_bit & saved_cpsr); +#endif + return; + } + sh = softintr_pending; + softintr_pending = softintr_pending->sh_vlink; + + s = raisespl(sh->sh_level); +#ifdef __GNUC__ + asm volatile("msr cpsr_c, %0" : : "r" (saved_cpsr)); +#else + SetCPSR(I32_bit, I32_bit & saved_cpsr); +#endif + + while (1) { + /* The order is important */ + sh1 = sh->sh_hlink; + sh->sh_pending = 0; + + (sh->sh_fun)(sh->sh_arg); + if (sh1 == NULL) + break; + sh = sh1; + } + splx(s); + } +} diff --git a/pool/shard006/C/0119993_DxeServicesTable.c b/pool/shard006/C/0119993_DxeServicesTable.c new file mode 100644 index 0000000000000000000000000000000000000000..fe0f597682ae5c2f67dc040e1d61c89e7f0e06b4 --- /dev/null +++ b/pool/shard006/C/0119993_DxeServicesTable.c @@ -0,0 +1,232 @@ +/** @file + Display the DXE services table + + Copyright (c) 2011 - 2012 Intel Corporation. All rights reserved.
+ This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license. + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. +--*/ +#include +#include +#include + +/** + Respond with the DXE services table + + @param[in] SocketFD The socket's file descriptor to add to the list. + @param[in] pPort The WSDT_PORT structure address + @param[out] pbDone Address to receive the request completion status + + @retval EFI_SUCCESS The request was successfully processed + +**/ +EFI_STATUS +DxeServicesTablePage ( + IN int SocketFD, + IN WSDT_PORT * pPort, + OUT BOOLEAN * pbDone + ) +{ + EFI_DXE_SERVICES * pDS; + EFI_STATUS Status; + + DBG_ENTER ( ); + + // + // Send the DXE services page + // + for ( ; ; ) { + // + // Get the DXE services table + // + Status = EfiGetSystemConfigurationTable (&gEfiDxeServicesTableGuid, (VOID **) &pDS); + if ( EFI_ERROR ( Status )) { + break; + } + + // + // Send the page and table header + // + Status = TableHeader ( SocketFD, pPort, L"DXE Services Table", pDS ); + if ( EFI_ERROR ( Status )) { + break; + } + + /// + /// The table header for the DXE Services Table. + /// This header contains the DXE_SERVICES_SIGNATURE and DXE_SERVICES_REVISION values. + /// + Status = EfiTableHeader ( SocketFD, + pPort, + &pDS->Hdr ); + if ( EFI_ERROR ( Status )) { + break; + } + + // + // Global Coherency Domain Services + // + Status = RowPointer ( SocketFD, + pPort, + "AddMemorySpace", + (VOID *)pDS->AddMemorySpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "AllocateMemorySpace", + (VOID *)pDS->AllocateMemorySpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "FreeMemorySpace", + (VOID *)pDS->FreeMemorySpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "RemoveMemorySpace", + (VOID *)pDS->RemoveMemorySpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "GetMemorySpaceDescriptor", + (VOID *)pDS->GetMemorySpaceDescriptor, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "SetMemorySpaceAttributes", + (VOID *)pDS->SetMemorySpaceAttributes, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "GetMemorySpaceMap", + (VOID *)pDS->GetMemorySpaceMap, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "AddIoSpace", + (VOID *)pDS->AddIoSpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "AllocateIoSpace", + (VOID *)pDS->AllocateIoSpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "FreeIoSpace", + (VOID *)pDS->FreeIoSpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "RemoveIoSpace", + (VOID *)pDS->RemoveIoSpace, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "GetIoSpaceDescriptor", + (VOID *)pDS->GetIoSpaceDescriptor, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "GetIoSpaceMap", + (VOID *)pDS->GetIoSpaceMap, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + + // + // Dispatcher Services + // + Status = RowPointer ( SocketFD, + pPort, + "Dispatch", + (VOID *)pDS->Dispatch, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "Schedule", + (VOID *)pDS->Schedule, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + Status = RowPointer ( SocketFD, + pPort, + "Trust", + (VOID *)pDS->Trust, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + + // + // Service to process a single firmware volume found in a capsule + // + Status = RowPointer ( SocketFD, + pPort, + "ProcessFirmwareVolume", + (VOID *)pDS->ProcessFirmwareVolume, + NULL ); + if ( EFI_ERROR ( Status )) { + break; + } + + // + // Build the table trailer + // + Status = TableTrailer ( SocketFD, + pPort, + pbDone ); + break; + } + + // + // Return the operation status + // + DBG_EXIT_STATUS ( Status ); + return Status; +} diff --git a/pool/shard006/C/0119995_scannerapi.c b/pool/shard006/C/0119995_scannerapi.c new file mode 100644 index 0000000000000000000000000000000000000000..a8c6879d37e3b3b660d8075eb13f8a6fa43bdcb8 --- /dev/null +++ b/pool/shard006/C/0119995_scannerapi.c @@ -0,0 +1,142 @@ +/* Gtk+ object tests + * Copyright (C) 2007 Patrick Hulin + * Copyright (C) 2007 Imendio AB + * Authors: Tim Janik + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ +#include +#include +#include + + +/* GScanner fixture */ +typedef struct { + GScanner *scanner; +} ScannerFixture; +static void +scanner_fixture_setup (ScannerFixture *fix, + gconstpointer test_data) +{ + fix->scanner = g_scanner_new (NULL); + g_assert (fix->scanner != NULL); +} +static void +scanner_fixture_teardown (ScannerFixture *fix, + gconstpointer test_data) +{ + g_assert (fix->scanner != NULL); + g_scanner_destroy (fix->scanner); +} + +static void +scanner_msg_func (GScanner *scanner, + gchar *message, + gboolean error) +{ + g_assert_cmpstr (message, ==, "test"); +} + +static void +test_scanner_warn (ScannerFixture *fix, + gconstpointer test_data) +{ + fix->scanner->msg_handler = scanner_msg_func; + g_scanner_warn (fix->scanner, "test"); +} + +static void +test_scanner_error (ScannerFixture *fix, + gconstpointer test_data) +{ + if (g_test_subprocess ()) + { + int pe = fix->scanner->parse_errors; + g_scanner_error (fix->scanner, "scanner-error-message-test"); + g_assert_cmpint (fix->scanner->parse_errors, ==, pe + 1); + exit (0); + } + + g_test_trap_subprocess (NULL, 0, 0); + g_test_trap_assert_passed (); + g_test_trap_assert_stderr ("*scanner-error-message-test*"); +} + +static void +check_keys (gpointer key, + gpointer value, + gpointer user_data) +{ + g_assert_cmpint (GPOINTER_TO_INT (value), ==, g_ascii_strtoull (key, NULL, 0)); +} + +static void +test_scanner_symbols (ScannerFixture *fix, + gconstpointer test_data) +{ + gint i; + gchar buf[2]; + + g_scanner_set_scope (fix->scanner, 1); + + for (i = 0; i < 10; i++) + g_scanner_scope_add_symbol (fix->scanner, + 1, + g_ascii_dtostr (buf, 2, (gdouble)i), + GINT_TO_POINTER (i)); + g_scanner_scope_foreach_symbol (fix->scanner, 1, check_keys, NULL); + g_assert_cmpint (GPOINTER_TO_INT (g_scanner_lookup_symbol (fix->scanner, "5")), ==, 5); + g_scanner_scope_remove_symbol (fix->scanner, 1, "5"); + g_assert (g_scanner_lookup_symbol (fix->scanner, "5") == NULL); + + g_assert_cmpint (GPOINTER_TO_INT (g_scanner_scope_lookup_symbol (fix->scanner, 1, "4")), ==, 4); + g_assert_cmpint (GPOINTER_TO_INT (g_scanner_scope_lookup_symbol (fix->scanner, 1, "5")), ==, 0); +} + +static void +test_scanner_tokens (ScannerFixture *fix, + gconstpointer test_data) +{ + gchar buf[] = "(\t\n\r\\){}"; + const gint buflen = strlen (buf); + gchar tokbuf[] = "(\\){}"; + const gint tokbuflen = strlen (tokbuf); + guint i; + + g_scanner_input_text (fix->scanner, buf, buflen); + + g_assert_cmpint (g_scanner_cur_token (fix->scanner), ==, G_TOKEN_NONE); + g_scanner_get_next_token (fix->scanner); + g_assert_cmpint (g_scanner_cur_token (fix->scanner), ==, tokbuf[0]); + g_assert_cmpint (g_scanner_cur_line (fix->scanner), ==, 1); + + for (i = 1; i < tokbuflen; i++) + g_assert_cmpint (g_scanner_get_next_token (fix->scanner), ==, tokbuf[i]); + g_assert_cmpint (g_scanner_get_next_token (fix->scanner), ==, G_TOKEN_EOF); + return; +} + +int +main (int argc, + char *argv[]) +{ + g_test_init (&argc, &argv, NULL); + + g_test_add ("/scanner/warn", ScannerFixture, 0, scanner_fixture_setup, test_scanner_warn, scanner_fixture_teardown); + g_test_add ("/scanner/error", ScannerFixture, 0, scanner_fixture_setup, test_scanner_error, scanner_fixture_teardown); + g_test_add ("/scanner/symbols", ScannerFixture, 0, scanner_fixture_setup, test_scanner_symbols, scanner_fixture_teardown); + g_test_add ("/scanner/tokens", ScannerFixture, 0, scanner_fixture_setup, test_scanner_tokens, scanner_fixture_teardown); + + return g_test_run(); +} diff --git a/pool/shard006/C/0119997_libc-start.c b/pool/shard006/C/0119997_libc-start.c new file mode 100644 index 0000000000000000000000000000000000000000..191cf86a309dd83156a0dfb08c3235e3a41e4f16 --- /dev/null +++ b/pool/shard006/C/0119997_libc-start.c @@ -0,0 +1,297 @@ +/* Copyright (C) 1998-2012 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, see + . */ + +#include +#include +#include +#include +#include +#include + +extern void __libc_init_first (int argc, char **argv, char **envp); +#ifndef SHARED +extern void __libc_csu_irel (void); +#endif + +extern int __libc_multiple_libcs; + +#include +#ifndef SHARED +# include +extern void __pthread_initialize_minimal (void); +# ifndef THREAD_SET_STACK_GUARD +/* Only exported for architectures that don't store the stack guard canary + in thread local area. */ +uintptr_t __stack_chk_guard attribute_relro; +# endif +# ifndef THREAD_SET_POINTER_GUARD +/* Only exported for architectures that don't store the pointer guard + value in thread local area. */ +uintptr_t __pointer_chk_guard_local + attribute_relro attribute_hidden __attribute__ ((nocommon)); +# endif +#endif + +#ifdef HAVE_PTR_NTHREADS +/* We need atomic operations. */ +# include +#endif + + +#ifndef SHARED +# include +# include + +# ifdef ELF_MACHINE_IRELA +# define IREL_T ElfW(Rela) +# define IPLT_START __rela_iplt_start +# define IPLT_END __rela_iplt_end +# define IREL elf_irela +# elif defined ELF_MACHINE_IREL +# define IREL_T ElfW(Rel) +# define IPLT_START __rel_iplt_start +# define IPLT_END __rel_iplt_end +# define IREL elf_irel +# endif + +static void +apply_irel (void) +{ +# ifdef IREL + /* We use weak references for these so that we'll still work with a linker + that doesn't define them. Such a linker doesn't support IFUNC at all + and so uses won't work, but a statically-linked program that doesn't + use any IFUNC symbols won't have a problem. */ + extern const IREL_T IPLT_START[] __attribute__ ((weak)); + extern const IREL_T IPLT_END[] __attribute__ ((weak)); + for (const IREL_T *ipltent = IPLT_START; ipltent < IPLT_END; ++ipltent) + IREL (ipltent); +# endif +} +#endif + + +#ifdef LIBC_START_MAIN +# ifdef LIBC_START_DISABLE_INLINE +# define STATIC static +# else +# define STATIC static inline __attribute__ ((always_inline)) +# endif +#else +# define STATIC +# define LIBC_START_MAIN BP_SYM (__libc_start_main) +#endif + +#ifdef MAIN_AUXVEC_ARG +/* main gets passed a pointer to the auxiliary. */ +# define MAIN_AUXVEC_DECL , void * +# define MAIN_AUXVEC_PARAM , auxvec +#else +# define MAIN_AUXVEC_DECL +# define MAIN_AUXVEC_PARAM +#endif + +STATIC int LIBC_START_MAIN (int (*main) (int, char **, char ** + MAIN_AUXVEC_DECL), + int argc, + char *__unbounded *__unbounded ubp_av, +#ifdef LIBC_START_MAIN_AUXVEC_ARG + ElfW(auxv_t) *__unbounded auxvec, +#endif + __typeof (main) init, + void (*fini) (void), + void (*rtld_fini) (void), + void *__unbounded stack_end) + __attribute__ ((noreturn)); + + +/* Note: the fini parameter is ignored here for shared library. It + is registered with __cxa_atexit. This had the disadvantage that + finalizers were called in more than one place. */ +STATIC int +LIBC_START_MAIN (int (*main) (int, char **, char ** MAIN_AUXVEC_DECL), + int argc, char *__unbounded *__unbounded ubp_av, +#ifdef LIBC_START_MAIN_AUXVEC_ARG + ElfW(auxv_t) *__unbounded auxvec, +#endif + __typeof (main) init, + void (*fini) (void), + void (*rtld_fini) (void), void *__unbounded stack_end) +{ +#if __BOUNDED_POINTERS__ + char **argv; +#else +# define argv ubp_av +#endif + + /* Result of the 'main' function. */ + int result; + + __libc_multiple_libcs = &_dl_starting_up && !_dl_starting_up; + +#ifndef SHARED + char *__unbounded *__unbounded ubp_ev = &ubp_av[argc + 1]; + + INIT_ARGV_and_ENVIRON; + + /* Store the lowest stack address. This is done in ld.so if this is + the code for the DSO. */ + __libc_stack_end = stack_end; + +# ifdef HAVE_AUX_VECTOR + /* First process the auxiliary vector since we need to find the + program header to locate an eventually present PT_TLS entry. */ +# ifndef LIBC_START_MAIN_AUXVEC_ARG + ElfW(auxv_t) *__unbounded auxvec; + { + char *__unbounded *__unbounded evp = ubp_ev; + while (*evp++ != NULL) + ; + auxvec = (ElfW(auxv_t) *__unbounded) evp; + } +# endif + _dl_aux_init (auxvec); +# endif +# ifdef DL_SYSDEP_OSCHECK + if (!__libc_multiple_libcs) + { + /* This needs to run to initiliaze _dl_osversion before TLS + setup might check it. */ + DL_SYSDEP_OSCHECK (__libc_fatal); + } +# endif + + /* Perform IREL{,A} relocations. */ + apply_irel (); + + /* Initialize the thread library at least a bit since the libgcc + functions are using thread functions if these are available and + we need to setup errno. */ + __pthread_initialize_minimal (); + + /* Set up the stack checker's canary. */ + uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random); +# ifdef THREAD_SET_STACK_GUARD + THREAD_SET_STACK_GUARD (stack_chk_guard); +# else + __stack_chk_guard = stack_chk_guard; +# endif +#endif + + /* Register the destructor of the dynamic linker if there is any. */ + if (__builtin_expect (rtld_fini != NULL, 1)) + __cxa_atexit ((void (*) (void *)) rtld_fini, NULL, NULL); + +#ifndef SHARED + /* Call the initializer of the libc. This is only needed here if we + are compiling for the static library in which case we haven't + run the constructors in `_dl_start_user'. */ + __libc_init_first (argc, argv, __environ); + + /* Register the destructor of the program, if any. */ + if (fini) + __cxa_atexit ((void (*) (void *)) fini, NULL, NULL); + + /* Some security at this point. Prevent starting a SUID binary where + the standard file descriptors are not opened. We have to do this + only for statically linked applications since otherwise the dynamic + loader did the work already. */ + if (__builtin_expect (__libc_enable_secure, 0)) + __libc_check_standard_fds (); +#endif + + /* Call the initializer of the program, if any. */ +#ifdef SHARED + if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_IMPCALLS, 0)) + GLRO(dl_debug_printf) ("\ninitialize program: %s\n\n", argv[0]); +#endif + if (init) + (*init) (argc, argv, __environ MAIN_AUXVEC_PARAM); + +#ifdef SHARED + /* Auditing checkpoint: we have a new object. */ + if (__builtin_expect (GLRO(dl_naudit) > 0, 0)) + { + struct audit_ifaces *afct = GLRO(dl_audit); + struct link_map *head = GL(dl_ns)[LM_ID_BASE]._ns_loaded; + for (unsigned int cnt = 0; cnt < GLRO(dl_naudit); ++cnt) + { + if (afct->preinit != NULL) + afct->preinit (&head->l_audit[cnt].cookie); + + afct = afct->next; + } + } +#endif + +#ifdef SHARED + if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_IMPCALLS, 0)) + GLRO(dl_debug_printf) ("\ntransferring control: %s\n\n", argv[0]); +#endif + +#ifdef HAVE_CLEANUP_JMP_BUF + /* Memory for the cancellation buffer. */ + struct pthread_unwind_buf unwind_buf; + + int not_first_call; + not_first_call = setjmp ((struct __jmp_buf_tag *) unwind_buf.cancel_jmp_buf); + if (__builtin_expect (! not_first_call, 1)) + { + struct pthread *self = THREAD_SELF; + + /* Store old info. */ + unwind_buf.priv.data.prev = THREAD_GETMEM (self, cleanup_jmp_buf); + unwind_buf.priv.data.cleanup = THREAD_GETMEM (self, cleanup); + + /* Store the new cleanup handler info. */ + THREAD_SETMEM (self, cleanup_jmp_buf, &unwind_buf); + + /* Run the program. */ + result = main (argc, argv, __environ MAIN_AUXVEC_PARAM); + } + else + { + /* Remove the thread-local data. */ +# ifdef SHARED + PTHFCT_CALL (ptr__nptl_deallocate_tsd, ()); +# else + extern void __nptl_deallocate_tsd (void) __attribute ((weak)); + __nptl_deallocate_tsd (); +# endif + + /* One less thread. Decrement the counter. If it is zero we + terminate the entire process. */ + result = 0; +# ifdef SHARED + unsigned int *ptr = __libc_pthread_functions.ptr_nthreads; + PTR_DEMANGLE (ptr); +# else + extern unsigned int __nptl_nthreads __attribute ((weak)); + unsigned int *const ptr = &__nptl_nthreads; +# endif + + if (! atomic_decrement_and_test (ptr)) + /* Not much left to do but to exit the thread, not the process. */ + __exit_thread (0); + } +#else + /* Nothing fancy, just call the function. */ + result = main (argc, argv, __environ MAIN_AUXVEC_PARAM); +#endif + + exit (result); +} diff --git a/pool/shard006/C/0120001_ares_parse_ns_reply.c b/pool/shard006/C/0120001_ares_parse_ns_reply.c new file mode 100644 index 0000000000000000000000000000000000000000..5e9af71d1a9676f1d81992151f3eb3abe95ecbb3 --- /dev/null +++ b/pool/shard006/C/0120001_ares_parse_ns_reply.c @@ -0,0 +1,182 @@ +/* Copyright 1998 by the Massachusetts Institute of Technology. + * + * Permission to use, copy, modify, and distribute this + * software and its documentation for any purpose and without + * fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in + * advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" + * without express or implied warranty. + */ + +/* + * ares_parse_ns_reply created by Vlad Dinulescu + * on behalf of AVIRA Gmbh - http://www.avira.com + */ + +#include "ares_setup.h" + +#ifdef HAVE_SYS_SOCKET_H +# include +#endif +#ifdef HAVE_NETINET_IN_H +# include +#endif +#ifdef HAVE_NETDB_H +# include +#endif +#ifdef HAVE_ARPA_INET_H +# include +#endif +#ifdef HAVE_ARPA_NAMESER_H +# include +#else +# include "nameser.h" +#endif +#ifdef HAVE_ARPA_NAMESER_COMPAT_H +# include +#endif + +#include +#include +#include "ares.h" +#include "ares_dns.h" +#include "ares_private.h" + +int ares_parse_ns_reply( const unsigned char* abuf, int alen, + struct hostent** host ) +{ + unsigned int qdcount, ancount; + int status, i, rr_type, rr_class, rr_len; + int nameservers_num; + long len; + const unsigned char *aptr; + char* hostname, *rr_name, *rr_data, **nameservers; + struct hostent *hostent; + + /* Set *host to NULL for all failure cases. */ + *host = NULL; + + /* Give up if abuf doesn't have room for a header. */ + if ( alen < HFIXEDSZ ) + return ARES_EBADRESP; + + /* Fetch the question and answer count from the header. */ + qdcount = DNS_HEADER_QDCOUNT( abuf ); + ancount = DNS_HEADER_ANCOUNT( abuf ); + if ( qdcount != 1 ) + return ARES_EBADRESP; + + /* Expand the name from the question, and skip past the question. */ + aptr = abuf + HFIXEDSZ; + status = ares__expand_name_for_response( aptr, abuf, alen, &hostname, &len); + if ( status != ARES_SUCCESS ) + return status; + if ( aptr + len + QFIXEDSZ > abuf + alen ) + { + free( hostname ); + return ARES_EBADRESP; + } + aptr += len + QFIXEDSZ; + + /* Allocate nameservers array; ancount gives an upper bound */ + nameservers = malloc( ( ancount + 1 ) * sizeof( char * ) ); + if ( !nameservers ) + { + free( hostname ); + return ARES_ENOMEM; + } + nameservers_num = 0; + + /* Examine each answer resource record (RR) in turn. */ + for ( i = 0; i < ( int ) ancount; i++ ) + { + /* Decode the RR up to the data field. */ + status = ares__expand_name_for_response( aptr, abuf, alen, &rr_name, &len ); + if ( status != ARES_SUCCESS ) + break; + aptr += len; + if ( aptr + RRFIXEDSZ > abuf + alen ) + { + status = ARES_EBADRESP; + free(rr_name); + break; + } + rr_type = DNS_RR_TYPE( aptr ); + rr_class = DNS_RR_CLASS( aptr ); + rr_len = DNS_RR_LEN( aptr ); + aptr += RRFIXEDSZ; + + if ( rr_class == C_IN && rr_type == T_NS ) + { + /* Decode the RR data and add it to the nameservers list */ + status = ares__expand_name_for_response( aptr, abuf, alen, &rr_data, + &len); + if ( status != ARES_SUCCESS ) + { + free(rr_name); + break; + } + + nameservers[nameservers_num] = malloc(strlen(rr_data)+1); + + if (nameservers[nameservers_num]==NULL) + { + free(rr_name); + free(rr_data); + status=ARES_ENOMEM; + break; + } + strcpy(nameservers[nameservers_num],rr_data); + free(rr_data); + + nameservers_num++; + } + + free( rr_name ); + + aptr += rr_len; + if ( aptr > abuf + alen ) + { + status = ARES_EBADRESP; + break; + } + } + + if ( status == ARES_SUCCESS && nameservers_num == 0 ) + { + status = ARES_ENODATA; + } + if ( status == ARES_SUCCESS ) + { + /* We got our answer. Allocate memory to build the host entry. */ + nameservers[nameservers_num] = NULL; + hostent = malloc( sizeof( struct hostent ) ); + if ( hostent ) + { + hostent->h_addr_list = malloc( 1 * sizeof( char * ) ); + if ( hostent->h_addr_list ) + { + /* Fill in the hostent and return successfully. */ + hostent->h_name = hostname; + hostent->h_aliases = nameservers; + hostent->h_addrtype = AF_INET; + hostent->h_length = sizeof( struct in_addr ); + hostent->h_addr_list[0] = NULL; + *host = hostent; + return ARES_SUCCESS; + } + free( hostent ); + } + status = ARES_ENOMEM; + } + for ( i = 0; i < nameservers_num; i++ ) + free( nameservers[i] ); + free( nameservers ); + free( hostname ); + return status; +} diff --git a/pool/shard006/C/0120004_getutent_r.c b/pool/shard006/C/0120004_getutent_r.c new file mode 100644 index 0000000000000000000000000000000000000000..876cc518b650c0d0678c4d6453af6a4ff308855e --- /dev/null +++ b/pool/shard006/C/0120004_getutent_r.c @@ -0,0 +1,183 @@ +/* Copyright (C) 1996-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper + and Paul Janzen , 1996. + + 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 + . */ + +#include +#include +#include + +#include "utmp-private.h" + + +/* Functions defined here. */ +static int setutent_unknown (void); +static int getutent_r_unknown (struct utmp *buffer, struct utmp **result); +static int getutid_r_unknown (const struct utmp *line, struct utmp *buffer, + struct utmp **result); +static int getutline_r_unknown (const struct utmp *id, struct utmp *buffer, + struct utmp **result); +static struct utmp *pututline_unknown (const struct utmp *data); +static void endutent_unknown (void); + +/* Initial Jump table. */ +const struct utfuncs __libc_utmp_unknown_functions = +{ + setutent_unknown, + getutent_r_unknown, + getutid_r_unknown, + getutline_r_unknown, + pututline_unknown, + endutent_unknown, + NULL +}; + +/* Currently selected backend. */ +const struct utfuncs *__libc_utmp_jump_table = &__libc_utmp_unknown_functions; + +/* We need to protect the opening of the file. */ +__libc_lock_define_initialized (, __libc_utmp_lock attribute_hidden) + + +static int +setutent_unknown (void) +{ + int result; + + result = (*__libc_utmp_file_functions.setutent) (); + if (result) + __libc_utmp_jump_table = &__libc_utmp_file_functions; + + return result; +} + + +static int +getutent_r_unknown (struct utmp *buffer, struct utmp **result) +{ + /* The backend was not yet initialized. */ + if (setutent_unknown ()) + return (*__libc_utmp_jump_table->getutent_r) (buffer, result); + + /* Not available. */ + *result = NULL; + return -1; +} + + +static int +getutid_r_unknown (const struct utmp *id, struct utmp *buffer, + struct utmp **result) +{ + /* The backend was not yet initialized. */ + if (setutent_unknown ()) + return (*__libc_utmp_jump_table->getutid_r) (id, buffer, result); + + /* Not available. */ + *result = NULL; + return -1; +} + + +static int +getutline_r_unknown (const struct utmp *line, struct utmp *buffer, + struct utmp **result) +{ + /* The backend was not yet initialized. */ + if (setutent_unknown ()) + return (*__libc_utmp_jump_table->getutline_r) (line, buffer, result); + + /* Not available. */ + *result = NULL; + return -1; +} + + +static struct utmp * +pututline_unknown (const struct utmp *data) +{ + /* The backend was not yet initialized. */ + if (setutent_unknown ()) + return (*__libc_utmp_jump_table->pututline) (data); + + /* Not available. */ + return NULL; +} + + +static void +endutent_unknown (void) +{ + /* Nothing to do. */ +} + + +void +__setutent (void) +{ + __libc_lock_lock (__libc_utmp_lock); + + (*__libc_utmp_jump_table->setutent) (); + + __libc_lock_unlock (__libc_utmp_lock); +} +weak_alias (__setutent, setutent) + + +int +__getutent_r (struct utmp *buffer, struct utmp **result) +{ + int retval; + + __libc_lock_lock (__libc_utmp_lock); + + retval = (*__libc_utmp_jump_table->getutent_r) (buffer, result); + + __libc_lock_unlock (__libc_utmp_lock); + + return retval; +} +weak_alias (__getutent_r, getutent_r) + + +struct utmp * +__pututline (const struct utmp *data) +{ + struct utmp *buffer; + + __libc_lock_lock (__libc_utmp_lock); + + buffer = (*__libc_utmp_jump_table->pututline) (data); + + __libc_lock_unlock (__libc_utmp_lock); + + return buffer; +} +weak_alias (__pututline, pututline) + + +void +__endutent (void) +{ + __libc_lock_lock (__libc_utmp_lock); + + (*__libc_utmp_jump_table->endutent) (); + __libc_utmp_jump_table = &__libc_utmp_unknown_functions; + + __libc_lock_unlock (__libc_utmp_lock); +} +weak_alias (__endutent, endutent) diff --git a/pool/shard006/C/0120005_sign.c b/pool/shard006/C/0120005_sign.c new file mode 100644 index 0000000000000000000000000000000000000000..72b4b5053030b8b5d5b2c664e62d0358280c4bbb --- /dev/null +++ b/pool/shard006/C/0120005_sign.c @@ -0,0 +1,317 @@ +/* + * Copyright (C) 2011-2012 Free Software Foundation, Inc. + * + * Author: Nikos Mavrogiannopoulos + * + * This file is part of GnuTLS. + * + * The GnuTLS 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 program. If not, see + * + */ + +#include +#include +#include +#include + +/* signature algorithms; + */ +struct gnutls_sign_entry +{ + const char *name; + const char *oid; + gnutls_sign_algorithm_t id; + gnutls_pk_algorithm_t pk; + gnutls_digest_algorithm_t mac; + /* See RFC 5246 HashAlgorithm and SignatureAlgorithm + for values to use in aid struct. */ + const sign_algorithm_st aid; +}; +typedef struct gnutls_sign_entry gnutls_sign_entry; + +#define TLS_SIGN_AID_UNKNOWN {255, 255} +static const sign_algorithm_st unknown_tls_aid = TLS_SIGN_AID_UNKNOWN; + +static const gnutls_sign_entry sign_algorithms[] = { + {"RSA-SHA1", SIG_RSA_SHA1_OID, GNUTLS_SIGN_RSA_SHA1, GNUTLS_PK_RSA, + GNUTLS_DIG_SHA1, {2, 1}}, + {"RSA-SHA224", SIG_RSA_SHA224_OID, GNUTLS_SIGN_RSA_SHA224, GNUTLS_PK_RSA, + GNUTLS_DIG_SHA224, {3, 1}}, + {"RSA-SHA256", SIG_RSA_SHA256_OID, GNUTLS_SIGN_RSA_SHA256, GNUTLS_PK_RSA, + GNUTLS_DIG_SHA256, {4, 1}}, + {"RSA-SHA384", SIG_RSA_SHA384_OID, GNUTLS_SIGN_RSA_SHA384, GNUTLS_PK_RSA, + GNUTLS_DIG_SHA384, {5, 1}}, + {"RSA-SHA512", SIG_RSA_SHA512_OID, GNUTLS_SIGN_RSA_SHA512, GNUTLS_PK_RSA, + GNUTLS_DIG_SHA512, {6, 1}}, + {"RSA-RMD160", SIG_RSA_RMD160_OID, GNUTLS_SIGN_RSA_RMD160, GNUTLS_PK_RSA, + GNUTLS_DIG_RMD160, TLS_SIGN_AID_UNKNOWN}, + {"DSA-SHA1", SIG_DSA_SHA1_OID, GNUTLS_SIGN_DSA_SHA1, GNUTLS_PK_DSA, + GNUTLS_DIG_SHA1, {2, 2}}, + {"DSA-SHA224", SIG_DSA_SHA224_OID, GNUTLS_SIGN_DSA_SHA224, GNUTLS_PK_DSA, + GNUTLS_DIG_SHA224, {3, 2}}, + {"DSA-SHA256", SIG_DSA_SHA256_OID, GNUTLS_SIGN_DSA_SHA256, GNUTLS_PK_DSA, + GNUTLS_DIG_SHA256, {4, 2}}, + {"RSA-MD5", SIG_RSA_MD5_OID, GNUTLS_SIGN_RSA_MD5, GNUTLS_PK_RSA, + GNUTLS_DIG_MD5, {1, 1}}, + {"RSA-MD2", SIG_RSA_MD2_OID, GNUTLS_SIGN_RSA_MD2, GNUTLS_PK_RSA, + GNUTLS_DIG_MD2, TLS_SIGN_AID_UNKNOWN}, + {"ECDSA-SHA1", "1.2.840.10045.4.1", GNUTLS_SIGN_ECDSA_SHA1, GNUTLS_PK_EC, GNUTLS_DIG_SHA1, {2, 3}}, + {"ECDSA-SHA224", "1.2.840.10045.4.3.1", GNUTLS_SIGN_ECDSA_SHA224, GNUTLS_PK_EC, GNUTLS_DIG_SHA224, {3, 3}}, + {"ECDSA-SHA256", "1.2.840.10045.4.3.2", GNUTLS_SIGN_ECDSA_SHA256, GNUTLS_PK_EC, GNUTLS_DIG_SHA256, {4, 3}}, + {"ECDSA-SHA384", "1.2.840.10045.4.3.3", GNUTLS_SIGN_ECDSA_SHA384, GNUTLS_PK_EC, GNUTLS_DIG_SHA384, {5, 3}}, + {"ECDSA-SHA512", "1.2.840.10045.4.3.4", GNUTLS_SIGN_ECDSA_SHA512, GNUTLS_PK_EC, GNUTLS_DIG_SHA512, {6, 3}}, + {"GOST R 34.10-2001", SIG_GOST_R3410_2001_OID, 0, 0, 0, + TLS_SIGN_AID_UNKNOWN}, + {"GOST R 34.10-94", SIG_GOST_R3410_94_OID, 0, 0, 0, TLS_SIGN_AID_UNKNOWN}, + {0, 0, 0, 0, 0, TLS_SIGN_AID_UNKNOWN} +}; + +#define GNUTLS_SIGN_LOOP(b) \ + do { \ + const gnutls_sign_entry *p; \ + for(p = sign_algorithms; p->name != NULL; p++) { b ; } \ + } while (0) + +#define GNUTLS_SIGN_ALG_LOOP(a) \ + GNUTLS_SIGN_LOOP( if(p->id && p->id == sign) { a; break; } ) + +/** + * gnutls_sign_get_name: + * @algorithm: is a sign algorithm + * + * Convert a #gnutls_sign_algorithm_t value to a string. + * + * Returns: a string that contains the name of the specified sign + * algorithm, or %NULL. + **/ +const char * +gnutls_sign_get_name (gnutls_sign_algorithm_t algorithm) +{ + gnutls_sign_algorithm_t sign = algorithm; + const char *ret = NULL; + + /* avoid prefix */ + GNUTLS_SIGN_ALG_LOOP (ret = p->name); + + return ret; +} + +/** + * gnutls_sign_is_secure: + * @algorithm: is a sign algorithm + * + * Returns: Non-zero if the provided signature algorithm is considered to be secure. + **/ +int +gnutls_sign_is_secure (gnutls_sign_algorithm_t algorithm) +{ + gnutls_sign_algorithm_t sign = algorithm; + gnutls_digest_algorithm_t dig = GNUTLS_DIG_UNKNOWN; + + /* avoid prefix */ + GNUTLS_SIGN_ALG_LOOP (dig = p->mac); + + if (dig != GNUTLS_DIG_UNKNOWN) + return _gnutls_digest_is_secure(dig); + + return 0; +} + +/** + * gnutls_sign_list: + * + * Get a list of supported public key signature algorithms. + * + * Returns: a (0)-terminated list of #gnutls_sign_algorithm_t + * integers indicating the available ciphers. + * + **/ +const gnutls_sign_algorithm_t * +gnutls_sign_list (void) +{ +static gnutls_sign_algorithm_t supported_sign[MAX_ALGOS] = {0}; + + if (supported_sign[0] == 0) + { + int i = 0; + + GNUTLS_SIGN_LOOP (supported_sign[i++]=p->id); + supported_sign[i++]=0; + } + + return supported_sign; +} + +/** + * gnutls_sign_get_id: + * @name: is a sign algorithm name + * + * The names are compared in a case insensitive way. + * + * Returns: return a #gnutls_sign_algorithm_t value corresponding to + * the specified algorithm, or %GNUTLS_SIGN_UNKNOWN on error. + **/ +gnutls_sign_algorithm_t +gnutls_sign_get_id (const char *name) +{ + gnutls_sign_algorithm_t ret = GNUTLS_SIGN_UNKNOWN; + + GNUTLS_SIGN_LOOP ( + if (strcasecmp (p->name, name) == 0) + { + ret = p->id; + break; + } + ); + + return ret; + +} + +gnutls_sign_algorithm_t +_gnutls_x509_oid2sign_algorithm (const char *oid) +{ + gnutls_sign_algorithm_t ret = 0; + + GNUTLS_SIGN_LOOP (if (p->oid && strcmp (oid, p->oid) == 0) + { + ret = p->id; + break; + } + ); + + if (ret == 0) + { + _gnutls_debug_log ("Unknown SIGN OID: '%s'\n", oid); + return GNUTLS_SIGN_UNKNOWN; + } + return ret; +} + +/** + * gnutls_pk_to_sign: + * @pk: is a public key algorithm + * @hash: a hash algorithm + * + * This function maps public key and hash algorithms combinations + * to signature algorithms. + * + * Returns: return a #gnutls_sign_algorithm_t value, or %GNUTLS_SIGN_UNKNOWN on error. + **/ +gnutls_sign_algorithm_t +gnutls_pk_to_sign (gnutls_pk_algorithm_t pk, gnutls_digest_algorithm_t hash) +{ + gnutls_sign_algorithm_t ret = 0; + + GNUTLS_SIGN_LOOP (if (pk == p->pk && hash == p->mac) + { + ret = p->id; break;} + ); + + if (ret == 0) + return GNUTLS_SIGN_UNKNOWN; + return ret; +} + +const char * +_gnutls_x509_sign_to_oid (gnutls_pk_algorithm_t pk, + gnutls_digest_algorithm_t mac) +{ + gnutls_sign_algorithm_t sign; + const char *ret = NULL; + + sign = gnutls_pk_to_sign (pk, mac); + if (sign == GNUTLS_SIGN_UNKNOWN) + return NULL; + + GNUTLS_SIGN_ALG_LOOP (ret = p->oid); + return ret; +} + +/** + * gnutls_sign_get_hash_algorithm: + * @sign: is a signature algorithm + * + * This function returns the digest algorithm corresponding to + * the given signature algorithms. + * + * Since: 3.1.1 + * + * Returns: return a #gnutls_digest_algorithm_t value, or %GNUTLS_DIG_UNKNOWN on error. + **/ +gnutls_digest_algorithm_t +gnutls_sign_get_hash_algorithm (gnutls_sign_algorithm_t sign) +{ + gnutls_digest_algorithm_t ret = GNUTLS_DIG_UNKNOWN; + + GNUTLS_SIGN_ALG_LOOP (ret = p->mac); + + return ret; +} + +/** + * gnutls_sign_get_pk_algorithm: + * @sign: is a signature algorithm + * + * This function returns the public key algorithm corresponding to + * the given signature algorithms. + * + * Since: 3.1.1 + * + * Returns: return a #gnutls_pk_algorithm_t value, or %GNUTLS_PK_UNKNOWN on error. + **/ +gnutls_pk_algorithm_t +gnutls_sign_get_pk_algorithm (gnutls_sign_algorithm_t sign) +{ + gnutls_pk_algorithm_t ret = GNUTLS_PK_UNKNOWN; + + GNUTLS_SIGN_ALG_LOOP (ret = p->pk); + + return ret; +} + +gnutls_sign_algorithm_t +_gnutls_tls_aid_to_sign (const sign_algorithm_st * aid) +{ + gnutls_sign_algorithm_t ret = GNUTLS_SIGN_UNKNOWN; + + if (memcmp(aid, &unknown_tls_aid, sizeof(*aid))==0) + return ret; + + GNUTLS_SIGN_LOOP (if (p->aid.hash_algorithm == aid->hash_algorithm + && p->aid.sign_algorithm == aid->sign_algorithm) + { + ret = p->id; break; + } + ); + + + return ret; +} + +/* Returns NULL if a valid AID is not found + */ +const sign_algorithm_st* +_gnutls_sign_to_tls_aid (gnutls_sign_algorithm_t sign) +{ + const sign_algorithm_st * ret = NULL; + + GNUTLS_SIGN_ALG_LOOP (ret = &p->aid); + + if (ret != NULL && memcmp(ret, &unknown_tls_aid, sizeof(*ret))==0) + return NULL; + + return ret; +} + diff --git a/pool/shard006/C/0120013_omap_intr.c b/pool/shard006/C/0120013_omap_intr.c new file mode 100644 index 0000000000000000000000000000000000000000..59bd4c2b9101e2c645fd6f1648283fb4c7b9cd93 --- /dev/null +++ b/pool/shard006/C/0120013_omap_intr.c @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include + +#include "kernel/kernel.h" +#include "kernel/proc.h" +#include "kernel/vm.h" +#include "kernel/proto.h" +#include "arch_proto.h" +#include "hw_intr.h" + +#include "omap_intr_registers.h" +static struct omap_intr +{ + vir_bytes base; + int size; +} omap_intr; + +static kern_phys_map intr_phys_map; + +int +intr_init(const int auto_eoi) +{ + if (BOARD_IS_BBXM(machine.board_id)) { + omap_intr.base = OMAP3_DM37XX_INTR_BASE; + } else if (BOARD_IS_BB(machine.board_id)) { + omap_intr.base = OMAP3_AM335X_INTR_BASE; + } else { + panic + ("Can not do the interrupt setup. machine (0x%08x) is unknown\n", + machine.board_id); + }; + omap_intr.size = 0x1000; /* 4K */ + + kern_phys_map_ptr(omap_intr.base, omap_intr.size, + VMMF_UNCACHED | VMMF_WRITE, + &intr_phys_map, (vir_bytes) & omap_intr.base); + return 0; +} + +void +bsp_irq_handle(void) +{ + /* Function called from assembly to handle interrupts */ + + /* get irq */ + int irq = + mmio_read(omap_intr.base + + OMAP3_INTCPS_SIR_IRQ) & OMAP3_INTR_ACTIVEIRQ_MASK; + /* handle irq */ + irq_handle(irq); + /* re-enable. this should not trigger interrupts due to current cpsr + * state */ + mmio_write(omap_intr.base + OMAP3_INTCPS_CONTROL, + OMAP3_INTR_NEWIRQAGR); +} + +void +bsp_irq_unmask(int irq) +{ + mmio_write(OMAP3_INTR_MIR_CLEAR(omap_intr.base, irq >> 5), + 1 << (irq & 0x1f)); +} + +void +bsp_irq_mask(const int irq) +{ + mmio_write(OMAP3_INTR_MIR_SET(omap_intr.base, irq >> 5), + 1 << (irq & 0x1f)); +} diff --git a/pool/shard006/C/0120018_strfry.c b/pool/shard006/C/0120018_strfry.c new file mode 100644 index 0000000000000000000000000000000000000000..d3fcb14bab090decaf05a8c8f90d577757282bbc --- /dev/null +++ b/pool/shard006/C/0120018_strfry.c @@ -0,0 +1,53 @@ +/* Copyright (C) 1992, 1996, 1999, 2002, 2007 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. */ + +#include +#include +#include +#include + +char * +strfry (char *string) +{ + static int init; + static struct random_data rdata; + + if (!init) + { + static char state[32]; + rdata.state = NULL; + __initstate_r (time ((time_t *) NULL) ^ getpid (), + state, sizeof (state), &rdata); + init = 1; + } + + size_t len = strlen (string); + if (len > 0) + for (size_t i = 0; i < len - 1; ++i) + { + int32_t j; + __random_r (&rdata, &j); + j = j % (len - i) + i; + + char c = string[i]; + string[i] = string[j]; + string[j] = c; + } + + return string; +} diff --git a/pool/shard006/C/0120020_time_Trsm_lun.c b/pool/shard006/C/0120020_time_Trsm_lun.c new file mode 100644 index 0000000000000000000000000000000000000000..41e70bca81c92be985b855a1e860db8a1b1c00ad --- /dev/null +++ b/pool/shard006/C/0120020_time_Trsm_lun.c @@ -0,0 +1,164 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ + +#include "FLAME.h" + +#define FLA_ALG_REFERENCE 0 +#define FLA_ALG_UNBLOCKED 1 +#define FLA_ALG_BLOCKED 2 +#define FLA_ALG_OPTIMIZED 3 + + +void time_Trsm_lun( + int variant, int type, int nrepeats, int n, int nb_alg, + FLA_Obj A, FLA_Obj B, FLA_Obj C, FLA_Obj C_ref, + double *dtime, double *diff, double *gflops ) +{ + int + irep; + + double + dtime_old = 1.0e9; + + FLA_Obj + C_old; + + fla_blocksize_t* + bp; + fla_gemm_t* + cntl_gemm_blas; + fla_trsm_t* + cntl_trsm_blas; + fla_trsm_t* + cntl_trsm_var; + + bp = FLA_Blocksize_create( nb_alg, nb_alg, nb_alg, nb_alg ); + cntl_gemm_blas = FLA_Cntl_gemm_obj_create( FLA_FLAT, FLA_SUBPROBLEM, NULL, NULL ); + cntl_trsm_blas = FLA_Cntl_trsm_obj_create( FLA_FLAT, FLA_SUBPROBLEM, NULL, NULL, NULL ); + cntl_trsm_var = FLA_Cntl_trsm_obj_create( FLA_FLAT, variant, bp, cntl_trsm_blas, cntl_gemm_blas ); + + FLA_Obj_create_conf_to( FLA_NO_TRANSPOSE, C, &C_old ); + + FLA_Copy_external( C, C_old ); + + + for ( irep = 0 ; irep < nrepeats; irep++ ) + { + FLA_Copy_external( C_old, C ); + + *dtime = FLA_Clock(); + + switch( variant ){ + + case 0: + // Time reference implementation + REF_Trsm( FLA_LEFT, FLA_UPPER_TRIANGULAR, + FLA_NO_TRANSPOSE, FLA_NONUNIT_DIAG, + FLA_ONE, A, C ); + break; + + case 1:{ + // Time variant 1 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lun_unb_var1( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lun_blk_var1( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + + case 2:{ + // Time variant 2 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lun_unb_var2( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lun_blk_var2( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + + case 3:{ + // Time variant 3 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lun_unb_var3( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lun_blk_var3( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + + case 4:{ + // Time variant 4 + switch( type ){ + case FLA_ALG_UNBLOCKED: + FLA_Trsm_lun_unb_var4( FLA_NONUNIT_DIAG, FLA_ONE, A, C ); + break; + case FLA_ALG_BLOCKED: + FLA_Trsm_lun_blk_var4( FLA_NONUNIT_DIAG, FLA_ONE, A, C, cntl_trsm_var ); + break; + default: + printf("trouble\n"); + } + + break; + } + } + + *dtime = FLA_Clock() - *dtime; + dtime_old = min( *dtime, dtime_old ); + } + + FLA_Cntl_obj_free( cntl_trsm_var ); + FLA_Cntl_obj_free( cntl_trsm_blas ); + FLA_Cntl_obj_free( cntl_gemm_blas ); + FLA_Blocksize_free( bp ); + + if ( variant == 0 ) + { + FLA_Copy_external( C, C_ref ); + *diff = 0.0; + } + else + { + *diff = FLA_Max_elemwise_diff( C, C_ref ); + } + + *gflops = 1.0 * + FLA_Obj_length( C ) * + FLA_Obj_width( C ) * + FLA_Obj_width( A ) / + dtime_old / + 1.0e9; + + *dtime = dtime_old; + + FLA_Copy_external( C_old, C ); + + FLA_Obj_free( &C_old ); +} + diff --git a/pool/shard006/C/0120021_ec_udp.c b/pool/shard006/C/0120021_ec_udp.c new file mode 100644 index 0000000000000000000000000000000000000000..a4071f8c76b16077d4af34b26007b907c084a84a --- /dev/null +++ b/pool/shard006/C/0120021_ec_udp.c @@ -0,0 +1,198 @@ +/* + ettercap -- UDP decoder module + + Copyright (C) ALoR & NaGA + + 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 +#include +#include +#include + +/* globals */ + +struct udp_header { + u_int16 sport; /* source port */ + u_int16 dport; /* destination port */ + u_int16 ulen; /* udp length */ + u_int16 csum; /* udp checksum */ +}; + +/* protos */ + +FUNC_DECODER(decode_udp); +FUNC_INJECTOR(inject_udp); +void udp_init(void); + +/*******************************************/ + +/* + * this function is the initializer. + * it adds the entry in the table of registered decoder + */ + +void __init udp_init(void) +{ + add_decoder(PROTO_LAYER, NL_TYPE_UDP, decode_udp); + add_injector(CHAIN_ENTRY, NL_TYPE_UDP, inject_udp); +} + + +FUNC_DECODER(decode_udp) +{ + FUNC_DECODER_PTR(next_decoder); + struct udp_header *udp; + u_int16 sum; + + udp = (struct udp_header *)DECODE_DATA; + + DECODED_LEN = sizeof(struct udp_header); + + /* source and dest port */ + PACKET->L4.src = udp->sport; + PACKET->L4.dst = udp->dport; + + PACKET->L4.len = DECODED_LEN; + PACKET->L4.header = (u_char *)DECODE_DATA; + PACKET->L4.options = NULL; + + /* this is UDP */ + PACKET->L4.proto = NL_TYPE_UDP; + + /* set up the data poiters */ + PACKET->DATA.data = ((u_char *)udp) + sizeof(struct udp_header); + /* check for bogus len */ + if (ntohs(udp->ulen) < (u_int16)sizeof(struct udp_header) || + ntohs(udp->ulen) > PACKET->L3.payload_len) + return NULL; + PACKET->DATA.len = ntohs(udp->ulen) - (u_int16)sizeof(struct udp_header); + + /* create the buffer to be displayed */ + packet_disp_data(PACKET, PACKET->DATA.data, PACKET->DATA.len); + + /* + * if the checsum is wrong, don't parse it (avoid ettercap spotting) + * the checksum is should be CSUM_RESULT and not equal to udp->csum ;) + * + * don't perform the check in unoffensive mode + */ + if (GBL_CONF->checksum_check) { + if (!GBL_OPTIONS->unoffensive && (sum = L4_checksum(PACKET)) != CSUM_RESULT) { + char tmp[MAX_ASCII_ADDR_LEN]; +#if defined(OS_DARWIN) || defined(OS_WINDOWS) || defined(OS_LINUX) + /* + * XXX - hugly hack here ! Mac OS X really sux + * + * Packets transmitted on interfaces with TCP checksum offloading + * don't have valid checksums as presented to the machine's packet-capture + * mechanism, as those packets are wrapped around internally rather + * than being captured after passing through the network interface, as + * the OS doesn't bother computing the checksum and adding it to the packet + * it leaves that up to the network interface. + * (taken from a bug report by Guy Harris - libpcap engineer) + * + * For Windows at least, TCP checksum off-loading can be disabled with a + * registry setting. + * + * if the source is the ettercap host, don't display the message + */ + if (!ip_addr_is_ours(&PACKET->L3.src) == E_FOUND) + return NULL; +#endif + if (GBL_CONF->checksum_warning) + USER_MSG("Invalid UDP packet from %s:%d : csum [%#x] should be (%#x)\n", ip_addr_ntoa(&PACKET->L3.src, tmp), + ntohs(udp->sport), ntohs(udp->csum), checksum_shouldbe(udp->csum, sum)); + return NULL; + } + } + + /* HOOK POINT: HOOK_PACKET_UDP */ + hook_point(HOOK_PACKET_UDP, po); + + /* get the next decoder */ + next_decoder = get_decoder(APP_LAYER, PL_DEFAULT); + EXECUTE_DECODER(next_decoder); + + /* + * in unoffensive mode the filters don't touch + * the packet, so we don't have to check here + * for unoffensive option + */ + + /* Adjustments after filters */ + if ((PACKET->flags & PO_MODIFIED) && (PACKET->flags & PO_FORWARDABLE)) { + + /* Recalculate checksum */ + udp->csum = CSUM_INIT; + udp->csum = L4_checksum(PACKET); + } + + return NULL; +} + +/*******************************************/ + +FUNC_INJECTOR(inject_udp) +{ + struct udp_header *udph; + u_char *udp_payload; + + /* Rember where the payload has to start */ + udp_payload = PACKET->packet; + + /* Allocate stack for tcp header */ + PACKET->packet -= sizeof(struct udp_header); + + /* Create the udp header */ + udph = (struct udp_header *)PACKET->packet; + + udph->sport = PACKET->L4.src; + udph->dport = PACKET->L4.dst; + udph->csum = CSUM_INIT; + + /* + * Go deeper into injectors chain. + * XXX We assume next layer is IP. + */ + LENGTH += sizeof(struct udp_header); + PACKET->session = NULL; + EXECUTE_INJECTOR(CHAIN_LINKED, STATELESS_IP_MAGIC); + + /* + * Attach the data (LENGTH was adjusted by LINKED injectors). + * Set LENGTH to injectable data len. + */ + LENGTH = GBL_IFACE->mtu - LENGTH; + if (LENGTH > PACKET->DATA.inject_len) + LENGTH = PACKET->DATA.inject_len; + memcpy(udp_payload, PACKET->DATA.inject, LENGTH); + + /* Set datagram len and calculate checksum */ + PACKET->L4.header = (u_char *)udph; + PACKET->L4.len = sizeof(struct udp_header); + PACKET->DATA.len = LENGTH; + udph->ulen = htons(PACKET->DATA.len + PACKET->L4.len); + udph->csum = L4_checksum(PACKET); + + return E_SUCCESS; +} + +/* EOF */ + +// vim:ts=3:expandtab + diff --git a/pool/shard006/C/0120025_imageshared.c b/pool/shard006/C/0120025_imageshared.c new file mode 100644 index 0000000000000000000000000000000000000000..d8d4802d1638526c2bf278140ebcd67f8c937e6d --- /dev/null +++ b/pool/shard006/C/0120025_imageshared.c @@ -0,0 +1,72 @@ +/* imageshared.c + * + * Copyright (c) 2001 Sean Walton and Macmillan Publishers. Use may be in + * whole or in part in accordance to the General Public License (GPL). + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. +*/ + +/*****************************************************************************/ +/*** imageshared.c ***/ +/*** ***/ +/*** Shared tools for UDP file multicasting. ***/ +/*****************************************************************************/ + +#include +#include "imagecaster.h" + +/*---------------------------------------------------------------------*/ +/*--- dx_hack_hash - relatively uniform hash (leveraged). ---*/ +/*---------------------------------------------------------------------*/ +u32 dx_hack_hash(const void *d, int len) +{ const char *data = d; + u32 hash0 = 0x12A3FE2D; + u32 hash1 = 0x37ABE8F9; + while ( len-- ) + { + u32 hash = hash1 + (hash0 ^ (*data++ * 71523)); + if ( hash < 0 ) + hash -= 0x7FFFFFFF; /* when is hash going to be less than zero if unsigned? */ + hash1 = hash0; + hash0 = hash; + } + return hash0; +} + +/*---------------------------------------------------------------------*/ +/*--- checksum - calculate the checksum of data. ---*/ +/*---------------------------------------------------------------------*/ +u16 checksum(const void *d, int len) +{ + u32 sum = 0; + const unsigned char *data = d; + + while ( len-- ) + sum += *data++; + sum = (sum & 0xFFFF) + (sum >> 16); + sum = (sum & 0xFFFF) + (sum >> 16); + return sum; +} + +/*---------------------------------------------------------------------*/ +/*--- ismulticast - check range for multicast address. ---*/ +/*---------------------------------------------------------------------*/ +int ismulticast(struct in_addr in_addr) +{ struct in_addr MCAST_LOWER, MCAST_UPPER; + + inet_aton("224.0.0.0", &MCAST_LOWER); + inet_aton("239.255.255.255", &MCAST_UPPER); + return (ntohl(MCAST_LOWER.s_addr) <= ntohl(in_addr.s_addr) && + (ntohl(in_addr.s_addr) <= ntohl(MCAST_UPPER.s_addr)) ); +} + diff --git a/pool/shard006/C/0120030_flash_m25p16.c b/pool/shard006/C/0120030_flash_m25p16.c new file mode 100644 index 0000000000000000000000000000000000000000..ea22ffddde878cb94abc0f92c462c41d2053d5d2 --- /dev/null +++ b/pool/shard006/C/0120030_flash_m25p16.c @@ -0,0 +1,369 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +#include +#include + +#include "platform.h" + +#ifdef USE_FLASH_M25P16 + +#include "flash_m25p16.h" +#include "drivers/io.h" +#include "drivers/bus.h" +#include "drivers/time.h" + +#define M25P16_INSTRUCTION_RDID 0x9F +#define M25P16_INSTRUCTION_READ_BYTES 0x03 +#define M25P16_INSTRUCTION_READ_STATUS_REG 0x05 +#define M25P16_INSTRUCTION_WRITE_STATUS_REG 0x01 +#define M25P16_INSTRUCTION_WRITE_ENABLE 0x06 +#define M25P16_INSTRUCTION_WRITE_DISABLE 0x04 +#define M25P16_INSTRUCTION_PAGE_PROGRAM 0x02 +#define M25P16_INSTRUCTION_SECTOR_ERASE 0xD8 +#define M25P16_INSTRUCTION_BULK_ERASE 0xC7 + +#define M25P16_STATUS_FLAG_WRITE_IN_PROGRESS 0x01 +#define M25P16_STATUS_FLAG_WRITE_ENABLED 0x02 + +#define W25Q256_INSTRUCTION_ENTER_4BYTE_ADDRESS_MODE 0xB7 + +// Format is manufacturer, memory type, then capacity +#define JEDEC_ID_MACRONIX_MX25L3206E 0xC22016 +#define JEDEC_ID_MACRONIX_MX25L6406E 0xC22017 +#define JEDEC_ID_MACRONIX_MX25L25635E 0xC22019 +#define JEDEC_ID_MICRON_M25P16 0x202015 +#define JEDEC_ID_MICRON_N25Q064 0x20BA17 +#define JEDEC_ID_MICRON_N25Q128 0x20ba18 +#define JEDEC_ID_WINBOND_W25Q16 0xEF4015 +#define JEDEC_ID_WINBOND_W25Q64 0xEF4017 +#define JEDEC_ID_WINBOND_W25Q128 0xEF4018 +#define JEDEC_ID_WINBOND_W25Q256 0xEF4019 +#define JEDEC_ID_SPANSION_S25FL116 0x014015 +#define JEDEC_ID_EON_W25Q64 0x1C3017 +#define JEDEC_ID_CYPRESS_S25FL128L 0x016018 + +// The timeout we expect between being able to issue page program instructions +#define DEFAULT_TIMEOUT_MILLIS 6 + +// These take sooooo long: +#define SECTOR_ERASE_TIMEOUT_MILLIS 5000 +#define BULK_ERASE_TIMEOUT_MILLIS 21000 + +static flashGeometry_t geometry = {.pageSize = M25P16_PAGESIZE}; + +static busDevice_t * busDev = NULL; +static bool isLargeFlash = false; +static uint32_t timeoutAt = 0; + +/* + * Whether we've performed an action that could have made the device busy for writes. + * + * This allows us to avoid polling for writable status when it is definitely ready already. + */ +static bool couldBeBusy = false; + +/** + * Send the given command byte to the device. + */ +static void m25p16_performOneByteCommand(uint8_t command) +{ + busTransfer(busDev, NULL, &command, 1); +} + +/** + * The flash requires this write enable command to be sent before commands that would cause + * a write like program and erase. + */ +static void m25p16_writeEnable(void) +{ + m25p16_performOneByteCommand(M25P16_INSTRUCTION_WRITE_ENABLE); + + // Assume that we're about to do some writing, so the device is just about to become busy + couldBeBusy = true; +} + +static uint8_t m25p16_readStatus(void) +{ + uint8_t command[2] = { M25P16_INSTRUCTION_READ_STATUS_REG, 0 }; + uint8_t in[2]; + + busTransfer(busDev, in, command, sizeof(command)); + + return in[1]; +} + +bool m25p16_isReady(void) +{ + // If couldBeBusy is false, don't bother to poll the flash chip for its status + couldBeBusy = couldBeBusy && ((m25p16_readStatus() & M25P16_STATUS_FLAG_WRITE_IN_PROGRESS) != 0); + + return !couldBeBusy; +} + +static void m25p16_setTimeout(uint32_t timeoutMillis) +{ + uint32_t now = millis(); + timeoutAt = now + timeoutMillis; +} + +bool m25p16_waitForReady(uint32_t timeoutMillis) +{ + uint32_t timeoutAtUse; + if (timeoutMillis == 0) { + timeoutAtUse = timeoutAt; + } + else { + timeoutAtUse = millis() + timeoutMillis; + } + + while (!m25p16_isReady()) { + uint32_t now = millis(); + if (now >= timeoutAtUse) { + return false; + } + } + + timeoutAt = 0; + return true; +} + +/** + * Read chip identification and geometry information (into global `geometry`). + * + * Returns true if we get valid ident, false if something bad happened like there is no M25P16. + */ +static bool m25p16_readIdentification(void) +{ + uint8_t out[] = { M25P16_INSTRUCTION_RDID, 0, 0, 0 }; + uint8_t in[4]; + uint32_t chipID; + + delay(50); // short delay required after initialisation of SPI device instance. + + /* Just in case transfer fails and writes nothing, so we don't try to verify the ID against random garbage + * from the stack: + */ + in[1] = 0; + + busTransfer(busDev, in, out, sizeof(out)); + + // Manufacturer, memory type, and capacity + chipID = (in[1] << 16) | (in[2] << 8) | (in[3]); + + // All supported chips use the same pagesize of 256 bytes + + switch (chipID) { + case JEDEC_ID_MICRON_M25P16: + case JEDEC_ID_SPANSION_S25FL116: + case JEDEC_ID_WINBOND_W25Q16: + geometry.sectors = 32; + geometry.pagesPerSector = 256; + break; + + case JEDEC_ID_MACRONIX_MX25L3206E: + geometry.sectors = 64; + geometry.pagesPerSector = 256; + break; + + case JEDEC_ID_MICRON_N25Q064: + case JEDEC_ID_WINBOND_W25Q64: + case JEDEC_ID_MACRONIX_MX25L6406E: + case JEDEC_ID_EON_W25Q64: + geometry.sectors = 128; + geometry.pagesPerSector = 256; + break; + + case JEDEC_ID_MICRON_N25Q128: + case JEDEC_ID_WINBOND_W25Q128: + case JEDEC_ID_CYPRESS_S25FL128L: + geometry.sectors = 256; + geometry.pagesPerSector = 256; + break; + + case JEDEC_ID_WINBOND_W25Q256: + case JEDEC_ID_MACRONIX_MX25L25635E: + geometry.sectors = 512; + geometry.pagesPerSector = 256; + break; + + default: + // Unsupported chip or not an SPI NOR flash + geometry.sectors = 0; + geometry.pagesPerSector = 0; + + geometry.sectorSize = 0; + geometry.totalSize = 0; + return false; + } + + geometry.sectorSize = geometry.pagesPerSector * geometry.pageSize; + geometry.totalSize = geometry.sectorSize * geometry.sectors; + + if (geometry.totalSize > 16 * 1024 * 1024) { + isLargeFlash = true; + m25p16_performOneByteCommand(W25Q256_INSTRUCTION_ENTER_4BYTE_ADDRESS_MODE); + } + + couldBeBusy = true; // Just for luck we'll assume the chip could be busy even though it isn't specced to be + + return true; +} + +/** + * Initialize the driver, must be called before any other routines. + * + * Attempts to detect a connected m25p16. If found, true is returned and device capacity can be fetched with + * m25p16_getGeometry(). + */ +bool m25p16_init(int flashNumToUse) +{ + busDev = busDeviceInit(BUSTYPE_SPI, DEVHW_M25P16, flashNumToUse, OWNER_FLASH); + if (busDev == NULL) { + return false; + } + +#ifndef M25P16_SPI_SHARED + busSetSpeed(busDev, BUS_SPEED_FAST); +#endif + + return m25p16_readIdentification(); +} + +void m25p16_setCommandAddress(uint8_t *buf, uint32_t address, bool useLongAddress) +{ + if (useLongAddress) { + *buf++ = (address >> 24) & 0xff; + } + + *buf++ = (address >> 16) & 0xff; + *buf++ = (address >> 8) & 0xff; + *buf = address & 0xff; +} + +/** + * Erase a sector full of bytes to all 1's at the given byte offset in the flash chip. + */ +void m25p16_eraseSector(uint32_t address) +{ + uint8_t out[5] = { M25P16_INSTRUCTION_SECTOR_ERASE }; + + m25p16_setCommandAddress(&out[1], address, isLargeFlash); + + if (!m25p16_waitForReady(0)) { + return; + } + + m25p16_writeEnable(); + + busTransfer(busDev, NULL, out, isLargeFlash ? 5 : 4); + + m25p16_setTimeout(SECTOR_ERASE_TIMEOUT_MILLIS); +} + +void m25p16_eraseCompletely(void) +{ + if (!m25p16_waitForReady(0)) { + return; + } + + m25p16_writeEnable(); + + m25p16_performOneByteCommand(M25P16_INSTRUCTION_BULK_ERASE); + + m25p16_setTimeout(BULK_ERASE_TIMEOUT_MILLIS); +} + +/** + * Write bytes to a flash page. Address must not cross a page boundary. + * + * Bits can only be set to zero, not from zero back to one again. In order to set bits to 1, use the erase command. + * + * Length must be smaller than the page size. + * + * This will wait for the flash to become ready before writing begins. + * + * Datasheet indicates typical programming time is 0.8ms for 256 bytes, 0.2ms for 64 bytes, 0.05ms for 16 bytes. + * (Although the maximum possible write time is noted as 5ms). + * + * If you want to write multiple buffers (whose sum of sizes is still not more than the page size) then you can + * break this operation up into one beginProgram call, one or more continueProgram calls, and one finishProgram call. + */ +uint32_t m25p16_pageProgram(uint32_t address, const uint8_t *data, int length) +{ + uint8_t command[5] = { M25P16_INSTRUCTION_PAGE_PROGRAM }; + + busTransferDescriptor_t txn[2] = { + { NULL, command, isLargeFlash ? 5 : 4 }, + { NULL, data, length } + }; + + m25p16_setCommandAddress(&command[1], address, isLargeFlash); + + if (!m25p16_waitForReady(0)) { + // return same address to indicate timeout + return address; + } + + m25p16_writeEnable(); + + busTransferMultiple(busDev, txn, 2); + + m25p16_setTimeout(DEFAULT_TIMEOUT_MILLIS); + + return address + length; +} + +/** + * Read `length` bytes into the provided `buffer` from the flash starting from the given `address` (which need not lie + * on a page boundary). + * + * Waits up to DEFAULT_TIMEOUT_MILLIS milliseconds for the flash to become ready before reading. + * + * The number of bytes actually read is returned, which can be zero if an error or timeout occurred. + */ +int m25p16_readBytes(uint32_t address, uint8_t *buffer, int length) +{ + uint8_t command[5] = { M25P16_INSTRUCTION_READ_BYTES }; + + busTransferDescriptor_t txn[2] = { + { NULL, command, isLargeFlash ? 5 : 4 }, + { buffer, NULL, length } + }; + + m25p16_setCommandAddress(&command[1], address, isLargeFlash); + + if (!m25p16_waitForReady(0)) { + return 0; + } + + busTransferMultiple(busDev, txn, 2); + + return length; +} + +/** + * Fetch information about the detected flash chip layout. + * + * Can be called before calling m25p16_init() (the result would have totalSize = 0). + */ +const flashGeometry_t* m25p16_getGeometry(void) +{ + return &geometry; +} + +#endif diff --git a/pool/shard006/C/0120032_cesare.c b/pool/shard006/C/0120032_cesare.c new file mode 100644 index 0000000000000000000000000000000000000000..4350bd815650b7f6ad7c86379c849321b49e3f76 --- /dev/null +++ b/pool/shard006/C/0120032_cesare.c @@ -0,0 +1,53 @@ +#define LEN 160 +#define KMIN 0 +#define KMAX 10 + +#include +#include + +int main() { + char messaggio[LEN+1]; + + int i; + int chiave; + int len; + + printf( + "Scrivere un SMS su una riga (massimo %d caratteri):\n" + "---premere invio per terminare il messaggio---\n", LEN); + gets(messaggio); + + do { + printf("Inserire la chiave di cifratura: intero in [%d, %d]: ", + KMIN, KMAX); + scanf("%d", &chiave); + + if (chiave < KMIN || chiave > KMAX) + printf("Chiave non valida!"); + } while (chiave < KMIN || chiave > KMAX); + + len = strlen(messaggio); + + printf("Messaggio cifrato:\n"); + + //cifratura (scorrimento al contrario + chiave) + for (i = 0; i < len+1; i++) + printf("%c", messaggio[len-i] + chiave); + printf("\n\n"); + + //alternativa alla fflush(stdin), che su alcuni terminali + //potrebbe non funzionare correttamente + while(getchar() != '\n'); + + //decifratura + printf( + "Scrivere l'SMS cifrato su una riga (massimo %d caratteri):\n" + "---premere invio per terminare il messaggio---\n", LEN); + gets(messaggio); + + len = strlen(messaggio); + + for (i = len; i > 0; i--) + printf("%c", messaggio[i-1] - chiave); + printf("\n"); +} diff --git a/pool/shard006/C/0120038_dumpelf.c b/pool/shard006/C/0120038_dumpelf.c new file mode 100644 index 0000000000000000000000000000000000000000..50fd33489c8e3a6389f98e8e9ce69cd796a8255b --- /dev/null +++ b/pool/shard006/C/0120038_dumpelf.c @@ -0,0 +1,129 @@ + +/* + Copyright (C) 2001 Tensilica, Inc. All Rights Reserved. + Revised to support Tensilica processors and to improve overall performance + */ + +/* + + Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. + + This program is free software; you can redistribute it and/or modify it + under the terms of version 2.1 of the GNU Lesser General Public License + as published by the Free Software Foundation. + + This program is distributed in the hope that it would be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + Further, this software is distributed without any warranty that it is + free of the rightful claim of any third person regarding infringement + or the like. Any license provided herein, whether implied or + otherwise, applies only to this software file. Patent licenses, if + any, provided herein do not apply to combinations of this program with + other software, or any other product whatsoever. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, + USA. + + Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, + Mountain View, CA 94043, or: + + http://www.sgi.com + + For further information regarding this notice, see: + + http://oss.sgi.com/projects/GenInfo/NoticeExplan + +*/ + + + +#include +#include +#include +#include + +#define USE_STANDARD_TYPES 1 +#include "defs.h" +#include "em_elf.h" + + + +/* unwind table and/or unwind info dumping to elf */ +/* convention: last arg is text elf section pointer */ +__unw_error_t unwind_dump2elf(char *unwind_table_ptr, + __uint64_t unwind_table_size, + char *unwind_info_ptr, + __uint64_t unwind_info_size, + void *arg) { + __uint64_t i, unwind_table_size_in_entries = + unwind_table_size/sizeof(__unw_table_entry_t); + __unw_table_entry_t *unwind_table = + (__unw_table_entry_t *)unwind_table_ptr; + pSCNINFO scninfo_table, scninfo_info, scninfo_text = (pSCNINFO)arg; + Elf64_Word symindex_table, symindex_info, symindex_text; + __unw_addr_t zero_offset = 0L; + + /* check that both pointers are valid */ + if ((NULL == unwind_table_ptr) || (NULL == unwind_info_ptr)) { + return __UNW_INV_ARG_ERROR; + } + + /* create elf sections */ + scninfo_table = Em_New_Section(IA64_UNWIND, SHT_IA64_UNWIND, + SHF_ALLOC | SHF_IRIX_NOSTRIP, + (Elf64_Xword)sizeof(__unw_table_entry_t), + ELF64_FSZ_WORD); + scninfo_info = Em_New_Section(IA64_UNWIND_INFO, SHT_IA64_UNWIND_INFO, + SHF_ALLOC | SHF_IRIX_NOSTRIP, + (Elf64_Xword)sizeof(__unw_dbl_word_t), + ELF64_FSZ_XWORD); + + /* get symbol indices for the elf sections needed for relocations */ + symindex_table = Em_Create_Section_Symbol(scninfo_table); + symindex_info = Em_Create_Section_Symbol(scninfo_info); + symindex_text = Em_Create_Section_Symbol(scninfo_text); + + /* set up buffers for better performance */ + Em_New_Data_Buffer(scninfo_info, (Elf64_Xword)unwind_table_size, + ELF64_FSZ_WORD); + Em_New_Data_Buffer(scninfo_table, (Elf64_Xword)unwind_info_size, + ELF64_FSZ_XWORD); + + /* dump unwind table */ + for (i = 0; i < unwind_table_size_in_entries; i++) { + Em_Add_Bytes_To_Scn(scninfo_table, (void *)&zero_offset, + (Elf64_Xword)sizeof(__unw_addr_t), ELF64_FSZ_WORD); + Em_Add_New_Rela(symindex_text, (unsigned char)R_IA_64_SEGREL64MSB, + (Elf64_Addr)(i*sizeof(__unw_table_entry_t)), + (Elf64_Sxword)unwind_table[i]._start, + scninfo_table); + Em_Add_Bytes_To_Scn(scninfo_table, (void *)&zero_offset, + (Elf64_Xword)sizeof(__unw_addr_t), ELF64_FSZ_WORD); + Em_Add_New_Rela(symindex_text, (unsigned char)R_IA_64_SEGREL64MSB, + (Elf64_Addr)(i*sizeof(__unw_table_entry_t) + + 1*sizeof(__unw_addr_t)), + (Elf64_Sxword)unwind_table[i]._end, + scninfo_table); + Em_Add_Bytes_To_Scn(scninfo_table, (void *)&zero_offset, + (Elf64_Xword)sizeof(__unw_addr_t), ELF64_FSZ_WORD); + Em_Add_New_Rela(symindex_info, (unsigned char)R_IA_64_SEGREL64MSB, + (Elf64_Addr)(i*sizeof(__unw_table_entry_t) + + 2*sizeof(__unw_addr_t)), + (Elf64_Sxword)unwind_table[i]._info, + scninfo_table); + } + + /* dump unwind info */ + Em_Add_Bytes_To_Scn(scninfo_info, (void *)unwind_info_ptr, + (Elf64_Xword)unwind_info_size, ELF64_FSZ_XWORD); + + /* finalize elf sections */ + Em_End_Section(scninfo_table); + Em_End_Section(scninfo_info); + + return __UNW_OK; +} diff --git a/pool/shard006/C/0120041_Pin_Input_PM.c b/pool/shard006/C/0120041_Pin_Input_PM.c new file mode 100644 index 0000000000000000000000000000000000000000..7c241847801f4c7a3ae30007dbb560048b0b5dbb --- /dev/null +++ b/pool/shard006/C/0120041_Pin_Input_PM.c @@ -0,0 +1,98 @@ +/******************************************************************************* +* File Name: Pin_Input.c +* Version 2.20 +* +* Description: +* This file contains APIs to set up the Pins component for low power modes. +* +* Note: +* +******************************************************************************** +* Copyright 2015, Cypress Semiconductor Corporation. All rights reserved. +* You may use this file only in accordance with the license, terms, conditions, +* disclaimers, and limitations in the end user license agreement accompanying +* the software package with which this file was provided. +*******************************************************************************/ + +#include "cytypes.h" +#include "Pin_Input.h" + +static Pin_Input_BACKUP_STRUCT Pin_Input_backup = {0u, 0u, 0u}; + + +/******************************************************************************* +* Function Name: Pin_Input_Sleep +****************************************************************************//** +* +* \brief Stores the pin configuration and prepares the pin for entering chip +* deep-sleep/hibernate modes. This function must be called for SIO and USBIO +* pins. It is not essential if using GPIO or GPIO_OVT pins. +* +* Note This function is available in PSoC 4 only. +* +* \return +* None +* +* \sideeffect +* For SIO pins, this function configures the pin input threshold to CMOS and +* drive level to Vddio. This is needed for SIO pins when in device +* deep-sleep/hibernate modes. +* +* \funcusage +* \snippet Pin_Input_SUT.c usage_Pin_Input_Sleep_Wakeup +*******************************************************************************/ +void Pin_Input_Sleep(void) +{ + #if defined(Pin_Input__PC) + Pin_Input_backup.pcState = Pin_Input_PC; + #else + #if (CY_PSOC4_4200L) + /* Save the regulator state and put the PHY into suspend mode */ + Pin_Input_backup.usbState = Pin_Input_CR1_REG; + Pin_Input_USB_POWER_REG |= Pin_Input_USBIO_ENTER_SLEEP; + Pin_Input_CR1_REG &= Pin_Input_USBIO_CR1_OFF; + #endif + #endif + #if defined(CYIPBLOCK_m0s8ioss_VERSION) && defined(Pin_Input__SIO) + Pin_Input_backup.sioState = Pin_Input_SIO_REG; + /* SIO requires unregulated output buffer and single ended input buffer */ + Pin_Input_SIO_REG &= (uint32)(~Pin_Input_SIO_LPM_MASK); + #endif +} + + +/******************************************************************************* +* Function Name: Pin_Input_Wakeup +****************************************************************************//** +* +* \brief Restores the pin configuration that was saved during Pin_Sleep(). +* +* For USBIO pins, the wakeup is only triggered for falling edge interrupts. +* +* Note This function is available in PSoC 4 only. +* +* \return +* None +* +* \funcusage +* Refer to Pin_Input_Sleep() for an example usage. +*******************************************************************************/ +void Pin_Input_Wakeup(void) +{ + #if defined(Pin_Input__PC) + Pin_Input_PC = Pin_Input_backup.pcState; + #else + #if (CY_PSOC4_4200L) + /* Restore the regulator state and come out of suspend mode */ + Pin_Input_USB_POWER_REG &= Pin_Input_USBIO_EXIT_SLEEP_PH1; + Pin_Input_CR1_REG = Pin_Input_backup.usbState; + Pin_Input_USB_POWER_REG &= Pin_Input_USBIO_EXIT_SLEEP_PH2; + #endif + #endif + #if defined(CYIPBLOCK_m0s8ioss_VERSION) && defined(Pin_Input__SIO) + Pin_Input_SIO_REG = Pin_Input_backup.sioState; + #endif +} + + +/* [] END OF FILE */ diff --git a/pool/shard006/C/0120042_utils.c b/pool/shard006/C/0120042_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..3a5666b5dde6d13ad09185278ce38ba162484e9d --- /dev/null +++ b/pool/shard006/C/0120042_utils.c @@ -0,0 +1,349 @@ +/* + * Copyright (c) 2008, Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU Lesser General Public License, + * version 2.1, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include "utils.h" + +/* + * Read a line from the specified file in the specified directory + * into the buffer. The file is opened and closed. + * Any trailing white space is trimmed off. + * This is useful for accessing /sys files. + * Returns 0 or an error number. + */ +int +sa_sys_read_line(const char *dir, const char *file, char *buf, size_t len) +{ + FILE *fp; + char file_name[256]; + char *cp; + int rc = 0; + + snprintf(file_name, sizeof(file_name), "%s/%s", dir, file); + fp = fopen(file_name, "r"); + if (fp == NULL) + rc = -1; + else { + cp = fgets(buf, len, fp); + if (cp == NULL) { + fprintf(stderr, + "%s: read error or empty file %s," + " errno=0x%x\n", __func__, + file_name, errno); + rc = -1; + } else { + + /* + * Trim off trailing newline or other white space. + */ + cp = buf + strlen(buf); + while (--cp >= buf && isspace(*cp)) + *cp = '\0'; + } + fclose(fp); + } + return rc; +} + +/* + * Write a string to the specified file in the specified directory. + * The file is opened and closed. + * The string has a new-line appended to it. + * This is useful for accessing /sys files. + * Returns 0 or an error number. + */ +int +sa_sys_write_line(const char *dir, const char *file, const char *string) +{ + FILE *fp; + char file_name[256]; + int rc = 0; + + snprintf(file_name, sizeof(file_name), "%s/%s", dir, file); + fp = fopen(file_name, "w"); + if (fp == NULL) { + fprintf(stderr, "%s: fopen of %s failed, errno=0x%x\n", + __func__, file_name, errno); + rc = -1; + } else { + rc = fprintf(fp, "%s\n", string); + if (rc < 0) + fprintf(stderr, + "%s: write to %s of %s failed, errno=0x%x\n", + __func__, file_name, string, errno); + fclose(fp); + } + return rc; +} + +int +sa_sys_read_u32(const char *dir, const char *file, u_int32_t *vp) +{ + char buf[256]; + int rc; + u_int32_t val; + char *endptr; + + rc = sa_sys_read_line(dir, file, buf, sizeof(buf)); + if (rc == 0) { + val = strtoul(buf, &endptr, 0); + if (*endptr != '\0') { + fprintf(stderr, + "%s: parse error. file %s/%s line '%s'\n", + __func__, dir, file, buf); + rc = -1; + } else + *vp = val; + } + return rc; +} + +int +sa_sys_read_u64(const char *dir, const char *file, u_int64_t *vp) +{ + char buf[256]; + int rc; + u_int64_t val; + char *endptr; + + rc = sa_sys_read_line(dir, file, buf, sizeof(buf)); + if (rc == 0) { + val = strtoull(buf, &endptr, 0); + if (*endptr != '\0') { + fprintf(stderr, + "%s: parse error. file %s/%s line '%s'\n", + __func__, dir, file, buf); + rc = -1; + } else + *vp = val; + } + return rc; +} + +/* + * Make a printable NUL-terminated copy of the string. + * The source buffer might not be NUL-terminated. + */ +char * +sa_strncpy_safe(char *dest, size_t len, const char *src, size_t src_len) +{ + char *dp = dest; + const char *sp = src; + + while (len-- > 1 && src_len-- > 0 && *sp != '\0') { + *dp++ = isprint(*sp) ? *sp : (isspace(*sp) ? ' ' : '.'); + sp++; + } + *dp = '\0'; + + /* + * Take off trailing blanks. + */ + while (--dp >= dest && isspace(*dp)) + *dp = '\0'; + + return dest; +} + +/** sa_enum_encode(tp, name, valp) + * + * @param tp pointer to table of names and values, struct sa_nameval. + * @param name string to be encoded into a value + * @returns zero on success, non-zero if no matching string found. + */ +int +sa_enum_encode(const struct sa_nameval *tp, const char *name, u_int32_t *valp) +{ + for (; tp->nv_name != NULL; tp++) { + if (strcasecmp(tp->nv_name, name) == 0) { + *valp = tp->nv_val; + return 0; + } + } + return -1; +} + +/** sa_enum_decode(buf, len, tp, val) + * + * @param buf buffer for result (may be used or not). + * @param len size of buffer (at least 32 bytes recommended). + * @param tp pointer to table of names and values, struct sa_nameval. + * @param val value to be decoded into a name. + * @returns pointer to name string. Unknown values are put into buffer in hex. + */ +const char * +sa_enum_decode(char *buf, size_t len, + const struct sa_nameval *tp, u_int32_t val) +{ + for (; tp->nv_name != NULL; tp++) { + if (tp->nv_val == val) + return tp->nv_name; + } + snprintf(buf, len, "Unknown (code 0x%X)", val); + return buf; +} + +/* + * Read through a directory and call a function for each entry. + */ +int +sa_dir_read(char *dir_name, int (*func)(struct dirent *dp, void *), void *arg) +{ + DIR *dir; + struct dirent *dp; + int error = 0; + + dir = opendir(dir_name); + if (dir == NULL) + error = errno; + else { + while ((dp = readdir(dir)) != NULL && error == 0) { + if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || + (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))) + continue; + error = (*func)(dp, arg); + } + closedir(dir); + } + return error; +} + +/* + * Size of on-stack line buffers. + * These shouldn't be to large for a kernel stack frame. + */ +#define SA_LOG_BUF_LEN 200 /* on-stack line buffer size */ + +static const u_int32_t sa_table_growth = 16; /* entries to grow by */ + +/** sa_table_grow(tp, index) - add space to a table for index. + * + * @param tp pointer to sa_table structure. + * @param index - new index past the end of the current table. + * @returns new index, or -1 if table couldn't be grown. + * + * Note: if the table has never been used, and is still all zero, this works. + * + * Note: perhaps not safe for multithreading. Caller can lock the table + * externally, but reallocation can take a while, during which time the + * caller may not wish to hold the lock. + */ +int +sa_table_grow(struct sa_table *tp, u_int32_t index) +{ + u_int32_t new_size; + void **ap; + + if (index >= tp->st_size) { + new_size = index + sa_table_growth; + ap = realloc(tp->st_table, new_size * sizeof(*ap)); + if (ap == NULL) + return -1; + memset(ap + tp->st_size, 0, + (new_size - tp->st_size) * sizeof(*ap)); + tp->st_table = ap; + tp->st_size = new_size; + } + tp->st_limit = index + 1; + return index; +} + +/** sa_table_destroy(tp) - free memory used by table. + * + * @param tp pointer to sa_table structure. + */ +void +sa_table_destroy(struct sa_table *tp) +{ + if (tp->st_table) { + free(tp->st_table); + tp->st_table = NULL; + } + tp->st_limit = 0; + tp->st_size = 0; +} + +/** sa_table_destroy_all(tp) - free memory used by table, including entries. + * + * @param tp pointer to sa_table structure. + */ +void +sa_table_destroy_all(struct sa_table *tp) +{ + int i; + + if (tp->st_table) { + for (i = 0; i < tp->st_limit; i++) { + if (tp->st_table[i]) { + free(tp->st_table[i]); + tp->st_table[i] = NULL; + } + } + } + sa_table_destroy(tp); +} + +/** sa_table_iterate(tp, handler, arg) + * + * @param tp pointer to sa_table structure. + * @param handler function to be called for each non-NULL entry. + * @param arg argument for function. + */ +void +sa_table_iterate(struct sa_table *tp, + void (*handler)(void *ep, void *arg), + void *arg) +{ + int i; + void *ep; + + for (i = 0; i < tp->st_limit; i++) { + ep = tp->st_table[i]; + if (ep != NULL) + (*handler)(ep, arg); + } +} + +/** sa_table_search(tp, match, arg) + * + * @param tp pointer to sa_table structure. + * @param match function to compare entries with arg and + * return non-NULL if match. + * @param arg argument for match function. + * + * Note that the value found could actually be something not in the table + * if the match function is doing something clever, like returning a + * sub-structure of the table entry. + */ +void * +sa_table_search(struct sa_table *tp, void *(*match)(void *ep, void *arg), + void *arg) +{ + int i; + void *found = NULL; + void *ep; + + for (i = 0; i < tp->st_limit; i++) { + ep = tp->st_table[i]; + if (ep != NULL) { + found = (*match)(ep, arg); + if (found != NULL) + break; + } + } + return found; +} diff --git a/pool/shard006/C/0120044_jail.c b/pool/shard006/C/0120044_jail.c new file mode 100644 index 0000000000000000000000000000000000000000..c7c5c00539aa2d6a35020677f5bb56e0ef4bad8c --- /dev/null +++ b/pool/shard006/C/0120044_jail.c @@ -0,0 +1,61 @@ +/* + * functional test of trap functions jail / unjail + */ +#include "include/zvmlib.h" +#include "include/ztest.h" + +/* + * should be large enough to hold one small function and + * small enough to be less or equal than text segment size + */ +#define SIZE 0x10000 + +/* should pass validation */ +static void good() +{ + ZTEST("good function"); +} + +/* should not pass validation */ +static char bad[] = {0xf, 0x31, 0xc3}; + +static int test_function(void(*func)()) +{ + char *p, *g; + int i, result; + + /* allocate and align buffer */ + p = malloc(SIZE + PAGESIZE); + ZFAIL(p != NULL); + g = p; + p = (char*)(uintptr_t)(ROUNDUP_64K((uintptr_t)p)); + + /* store a good function to buffer */ + memcpy(p, func, SIZE); + + /* validate it */ + result = zvm_jail(p, SIZE); + + /* run it */ + if(result == 0) ((void(*)())p)(); + + /* + * release resources and check if they really available + * warning: "for" can produce signal #11 + */ + ZFAIL(zvm_unjail(p, SIZE) == 0); + for(i = 0; i < SIZE; ++i) + p[i] = 0xdb; + + free(g); + return result; +} + +int main() +{ + ZTEST(test_function(good) == 0); + ZTEST(test_function((void (*)())bad) != 0); + + ZREPORT; + return 0; /* prevent warning */ +} diff --git a/pool/shard006/C/0120046_vector.c b/pool/shard006/C/0120046_vector.c new file mode 100644 index 0000000000000000000000000000000000000000..626dfd72f0eebfda23b3def1508088617a5bbc6d --- /dev/null +++ b/pool/shard006/C/0120046_vector.c @@ -0,0 +1,64 @@ +#include +#include + +struct CgreenVector_ { + int size; + void (*destructor)(void *); + int space; + void **items; +}; + +static void increase_space(CgreenVector *vector); + +CgreenVector *create_cgreen_vector(void (*destructor)(void *)) { + CgreenVector *vector = (CgreenVector *)malloc(sizeof(CgreenVector)); + vector->size = 0; + vector->destructor = destructor; + vector->space = 0; + vector->items = NULL; + return vector; +} + +void destroy_cgreen_vector(CgreenVector *vector) { + int i; + if (vector->destructor != NULL) { + for (i = 0; i < vector->size; i++) { + (*vector->destructor)(vector->items[i]); + } + } + free(vector->items); + free(vector); +} + +void cgreen_vector_add(CgreenVector *vector, void *item) { + if (vector->size == vector->space) { + increase_space(vector); + } + vector->items[vector->size] = item; + vector->size++; +} + +void *cgreen_vector_remove(CgreenVector *vector, int position) { + void *item = vector->items[position]; + int i; + for (i = position; i < vector->size; i++) { + vector->items[i] = vector->items[i + 1]; + } + vector->size--; + return item; +} + +void *cgreen_vector_get(CgreenVector *vector, int position) { + return vector->items[position]; +} + +int cgreen_vector_size(CgreenVector *vector) { + return (vector == NULL ? 0 : vector->size); +} + +static void increase_space(CgreenVector *vector) { + vector->space += 100; + vector->items = (void**)realloc(vector->items, sizeof(void *) * vector->space); +} + +/* vim: set ts=4 sw=4 et cindent: */ diff --git a/pool/shard006/C/0120053_main.c b/pool/shard006/C/0120053_main.c new file mode 100644 index 0000000000000000000000000000000000000000..130a6004f08e0114e5efdbc92e6f05ed6f2cc4c9 --- /dev/null +++ b/pool/shard006/C/0120053_main.c @@ -0,0 +1,99 @@ +/* + ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio + + 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 "ch.h" +#include "hal.h" + +#define EEPROM_SIZE 8192 // 64Kb, 8KB +#define EEPROM_PAGE_SIZE 32 +#define EEPROM_WRITE_TIME_MS 10 // byte/page write time +#define EEPROM_SPID SPID1 +#define EEPROM_SPIDCONFIG spi1cfg + +static const SPIConfig EEPROM_SPIDCONFIG = { + NULL, + GPIOA, + 12, + 0, // Up to 20Mhz + SPI_CR2_DS_2 | SPI_CR2_DS_1 | SPI_CR2_DS_0 +}; + +static SPIEepromFileConfig eeCfg = { + 0, + EEPROM_SIZE, + EEPROM_SIZE, + EEPROM_PAGE_SIZE, + MS2ST(EEPROM_WRITE_TIME_MS), + &EEPROM_SPID, + &EEPROM_SPIDCONFIG, +}; + +static SPIEepromFileStream eeFile; +static EepromFileStream *eeFS; + +static uint8_t buffer[64]; + +THD_WORKING_AREA(waThreadEE, 256); +static THD_FUNCTION(ThreadEE, arg) +{ + (void)arg; + uint8_t len = 64; + + while (TRUE) + { + + eeFS = SPIEepromFileOpen(&eeFile, &eeCfg, EepromFindDevice(EEPROM_DEV_25XX)); + fileStreamSeek(eeFS, 0); + + fileStreamWrite(eeFS, buffer, len); + fileStreamRead(eeFS, buffer, len); + + fileStreamClose(eeFS); + + chThdSleepMilliseconds(500); + } + + return; +} + +/* + * Application entry point. + */ +int main(void) { + + /* + * System initializations. + * - HAL initialization, this also initializes the configured device drivers + * and performs the board-specific initializations. + * - Kernel initialization, the main() function becomes a thread and the + * RTOS is active. + */ + halInit(); + chSysInit(); + + spiStart(&EEPROM_SPID, &EEPROM_SPIDCONFIG); + + chThdCreateStatic(waThreadEE, sizeof(waThreadEE), NORMALPRIO, ThreadEE, NULL); + + /* + * Normal main() thread activity, it resets the watchdog. + */ + while (true) { + palToggleLine(LINE_LED4_BLUE); + chThdSleepMilliseconds(500); + } + return 0; +} diff --git a/pool/shard006/C/0120056_ioremap.c b/pool/shard006/C/0120056_ioremap.c new file mode 100644 index 0000000000000000000000000000000000000000..1780df3ed9e590997529aadcbd9d3a1c7f134abd --- /dev/null +++ b/pool/shard006/C/0120056_ioremap.c @@ -0,0 +1,170 @@ +/* + * arch/cris/mm/ioremap.c + * + * Re-map IO memory to kernel address space so that we can access it. + * Needed for memory-mapped I/O devices mapped outside our normal DRAM + * window (that is, all memory-mapped I/O devices). + * + * (C) Copyright 1995 1996 Linus Torvalds + * CRIS-port by Axis Communications AB + */ + +#include +#include +#include +#include +#include +#include + +static inline void remap_area_pte(pte_t * pte, unsigned long address, unsigned long size, + unsigned long phys_addr, pgprot_t prot) +{ + unsigned long end; + + address &= ~PMD_MASK; + end = address + size; + if (end > PMD_SIZE) + end = PMD_SIZE; + if (address >= end) + BUG(); + do { + if (!pte_none(*pte)) { + printk("remap_area_pte: page already exists\n"); + BUG(); + } + set_pte(pte, mk_pte_phys(phys_addr, prot)); + address += PAGE_SIZE; + phys_addr += PAGE_SIZE; + pte++; + } while (address && (address < end)); +} + +static inline int remap_area_pmd(pmd_t * pmd, unsigned long address, unsigned long size, + unsigned long phys_addr, pgprot_t prot) +{ + unsigned long end; + + address &= ~PGDIR_MASK; + end = address + size; + if (end > PGDIR_SIZE) + end = PGDIR_SIZE; + phys_addr -= address; + if (address >= end) + BUG(); + do { + pte_t * pte = pte_alloc_kernel(pmd, address); + if (!pte) + return -ENOMEM; + remap_area_pte(pte, address, end - address, address + phys_addr, prot); + address = (address + PMD_SIZE) & PMD_MASK; + pmd++; + } while (address && (address < end)); + return 0; +} + +static int remap_area_pages(unsigned long address, unsigned long phys_addr, + unsigned long size, pgprot_t prot) +{ + int error; + pgd_t * dir; + unsigned long end = address + size; + + phys_addr -= address; + dir = pgd_offset(&init_mm, address); + flush_cache_all(); + if (address >= end) + BUG(); + do { + pud_t *pud; + pmd_t *pmd; + + error = -ENOMEM; + pud = pud_alloc(&init_mm, dir, address); + if (!pud) + break; + pmd = pmd_alloc(&init_mm, pud, address); + + if (!pmd) + break; + if (remap_area_pmd(pmd, address, end - address, + phys_addr + address, prot)) + break; + error = 0; + address = (address + PGDIR_SIZE) & PGDIR_MASK; + dir++; + } while (address && (address < end)); + flush_tlb_all(); + return error; +} + +/* + * Generic mapping function (not visible outside): + */ + +/* + * Remap an arbitrary physical address space into the kernel virtual + * address space. Needed when the kernel wants to access high addresses + * directly. + * + * NOTE! We need to allow non-page-aligned mappings too: we will obviously + * have to convert them into an offset in a page-aligned mapping, but the + * caller shouldn't need to know that small detail. + */ +void __iomem * __ioremap_prot(unsigned long phys_addr, unsigned long size, pgprot_t prot) +{ + void __iomem * addr; + struct vm_struct * area; + unsigned long offset, last_addr; + + /* Don't allow wraparound or zero size */ + last_addr = phys_addr + size - 1; + if (!size || last_addr < phys_addr) + return NULL; + + /* + * Mappings have to be page-aligned + */ + offset = phys_addr & ~PAGE_MASK; + phys_addr &= PAGE_MASK; + size = PAGE_ALIGN(last_addr+1) - phys_addr; + + /* + * Ok, go for it.. + */ + area = get_vm_area(size, VM_IOREMAP); + if (!area) + return NULL; + addr = (void __iomem *)area->addr; + if (remap_area_pages((unsigned long) addr, phys_addr, size, prot)) { + vfree((void __force *)addr); + return NULL; + } + return (void __iomem *) (offset + (char __iomem *)addr); +} + +void __iomem * __ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags) +{ + return __ioremap_prot(phys_addr, size, + __pgprot(_PAGE_PRESENT | __READABLE | + __WRITEABLE | _PAGE_GLOBAL | + _PAGE_KERNEL | flags)); +} + +/** + * ioremap_nocache - map bus memory into CPU space + * @offset: bus address of the memory + * @size: size of the resource to map + * + * Must be freed with iounmap. + */ + +void __iomem *ioremap_nocache (unsigned long phys_addr, unsigned long size) +{ + return __ioremap(phys_addr | MEM_NON_CACHEABLE, size, 0); +} + +void iounmap(volatile void __iomem *addr) +{ + if (addr > high_memory) + return vfree((void *) (PAGE_MASK & (unsigned long) addr)); +} diff --git a/pool/shard006/C/0120057_openauth.c b/pool/shard006/C/0120057_openauth.c new file mode 100644 index 0000000000000000000000000000000000000000..7a8254bb1cd584a31f0d9a3fb001bfc3b087e66b --- /dev/null +++ b/pool/shard006/C/0120057_openauth.c @@ -0,0 +1,285 @@ +/* This is a copy of the hellolibvirt example demonstaring how to use + * virConnectOpenAuth with a custom auth callback */ + +#include + +#include +#include +#include +#include +#include + +static void +showError(virConnectPtr conn) +{ + int ret; + virErrorPtr err; + + err = malloc(sizeof(*err)); + if (err == NULL) { + printf("Could not allocate memory for error data\n"); + goto out; + } + + ret = virConnCopyLastError(conn, err); + + switch (ret) { + case 0: + printf("No error found\n"); + break; + + case -1: + printf("Parameter error when attempting to get last error\n"); + break; + + default: + printf("libvirt reported: \"%s\"\n", err->message); + break; + } + + virResetError(err); + free(err); + + out: + return; +} + + +static int +showHypervisorInfo(virConnectPtr conn) +{ + int ret = 0; + unsigned long hvVer, major, minor, release; + const char *hvType; + + /* virConnectGetType returns a pointer to a static string, so no + * allocation or freeing is necessary; it is possible for the call + * to fail if, for example, there is no connection to a + * hypervisor, so check what it returns. */ + hvType = virConnectGetType(conn); + if (hvType == NULL) { + ret = 1; + printf("Failed to get hypervisor type\n"); + showError(conn); + goto out; + } + + if (virConnectGetVersion(conn, &hvVer) != 0) { + ret = 1; + printf("Failed to get hypervisor version\n"); + showError(conn); + goto out; + } + + major = hvVer / 1000000; + hvVer %= 1000000; + minor = hvVer / 1000; + release = hvVer % 1000; + + printf("Hypervisor: \"%s\" version: %lu.%lu.%lu\n", + hvType, + major, + minor, + release); + + out: + return ret; +} + + +static int +showDomains(virConnectPtr conn) +{ + int ret = 0, numNames, numInactiveDomains, numActiveDomains; + ssize_t i; + char **nameList = NULL; + + numActiveDomains = virConnectNumOfDomains(conn); + if (numActiveDomains == -1) { + ret = 1; + printf("Failed to get number of active domains\n"); + showError(conn); + goto out; + } + + numInactiveDomains = virConnectNumOfDefinedDomains(conn); + if (numInactiveDomains == -1) { + ret = 1; + printf("Failed to get number of inactive domains\n"); + showError(conn); + goto out; + } + + printf("There are %d active and %d inactive domains\n", + numActiveDomains, numInactiveDomains); + + nameList = malloc(sizeof(*nameList) * numInactiveDomains); + + if (nameList == NULL) { + ret = 1; + printf("Could not allocate memory for list of inactive domains\n"); + goto out; + } + + numNames = virConnectListDefinedDomains(conn, + nameList, + numInactiveDomains); + + if (numNames == -1) { + ret = 1; + printf("Could not get list of defined domains from hypervisor\n"); + showError(conn); + goto out; + } + + if (numNames > 0) + printf("Inactive domains:\n"); + + for (i = 0; i < numNames; i++) { + printf(" %s\n", *(nameList + i)); + /* The API documentation doesn't say so, but the names + * returned by virConnectListDefinedDomains are strdup'd and + * must be freed here. */ + free(*(nameList + i)); + } + + out: + free(nameList); + return ret; +} + +/* Struct to pass the credentials to the auth callback via the cbdata pointer */ +struct _AuthData { + char *username; + char *password; +}; + +typedef struct _AuthData AuthData; + +/* This function will be called by libvirt to obtain credentials in order to + * authenticate to the hypervisor */ +static int +authCallback(virConnectCredentialPtr cred, unsigned int ncred, void *cbdata) +{ + size_t i; + AuthData *authData = cbdata; + + /* libvirt might request multiple credentials in a single call. + * This example supports VIR_CRED_AUTHNAME and VIR_CRED_PASSPHRASE + * credentials only, but there are several other types. + * + * A request may also contain a prompt message that can be displayed + * to the user and a challenge. The challenge is specific to the + * credential type and hypervisor type. + * + * For example the ESX driver passes the hostname of the ESX or vCenter + * server as challenge. This allows a auth callback to return the + * proper credentials. */ + for (i = 0; i < ncred; ++i) { + switch (cred[i].type) { + case VIR_CRED_AUTHNAME: + cred[i].result = strdup(authData->username); + + if (cred[i].result == NULL) + return -1; + + cred[i].resultlen = strlen(cred[i].result); + break; + + case VIR_CRED_PASSPHRASE: + cred[i].result = strdup(authData->password); + + if (cred[i].result == NULL) + return -1; + + cred[i].resultlen = strlen(cred[i].result); + break; + + default: + return -1; + } + } + + return 0; +} + + +/* The list of credential types supported by our auth callback */ +static int credTypes[] = { + VIR_CRED_AUTHNAME, + VIR_CRED_PASSPHRASE +}; + + +/* The auth struct that will be passed to virConnectOpenAuth */ +static virConnectAuth auth = { + credTypes, + sizeof(credTypes) / sizeof(int), + authCallback, + NULL, // cbdata will be initialized in main +}; + + +int +main(int argc, char *argv[]) +{ + int ret = 0; + virConnectPtr conn; + char *uri; + AuthData authData; + + if (argc != 4) { + ret = 1; + printf("Usage: %s \n", argv[0]); + goto out; + } + + uri = argv[1]; + authData.username = argv[2]; + authData.password = argv[3]; + auth.cbdata = &authData; + + printf("Attempting to connect to hypervisor\n"); + + conn = virConnectOpenAuth(uri, &auth, 0); + + if (NULL == conn) { + ret = 1; + printf("No connection to hypervisor\n"); + showError(conn); + goto out; + } + + uri = virConnectGetURI(conn); + if (uri == NULL) { + ret = 1; + printf("Failed to get URI for hypervisor connection\n"); + showError(conn); + goto disconnect; + } + + printf("Connected to hypervisor at \"%s\"\n", uri); + free(uri); + + if (showHypervisorInfo(conn) != 0) { + ret = 1; + goto disconnect; + } + + if (showDomains(conn) != 0) { + ret = 1; + goto disconnect; + } + + disconnect: + if (virConnectClose(conn) != 0) { + printf("Failed to disconnect from hypervisor\n"); + showError(conn); + ret = 1; + } else { + printf("Disconnected from hypervisor\n"); + } + + out: + return ret; +} diff --git a/pool/shard006/C/0120063_icmpin.c b/pool/shard006/C/0120063_icmpin.c new file mode 100644 index 0000000000000000000000000000000000000000..e7a103056c39081dd04ce13de228ab0bdf21967a --- /dev/null +++ b/pool/shard006/C/0120063_icmpin.c @@ -0,0 +1,202 @@ +/* + * Copyright (C) 2001-2004 by egnite Software GmbH + * Copyright (c) 1993 by Digital Equipment Corporation + * Copyright (c) 1983, 1993 by The Regents of the University of California + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that 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 copyright holders nor the names of + * 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. + * + * For additional information see http://www.ethernut.de/ + */ + +/*! + * \file net/icmpin.c + * \brief ICMP input functions. + * + * \verbatim + * $Id: icmpin.c 5079 2013-03-21 19:13:56Z olereinhardt $ + * \endverbatim + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/*! + * \addtogroup xgICMP + */ +/*@{*/ + +/*! + * \brief Translation table from icmp error code to errno. + */ + +static const int icmp_code2errno[16] = +{ + ENETUNREACH, + EHOSTUNREACH, + ENOPROTOOPT, + ECONNREFUSED, + EMSGSIZE, + EOPNOTSUPP, + ENETUNREACH, + EHOSTDOWN, + ENETUNREACH, + ENETUNREACH, + EHOSTUNREACH, + ENETUNREACH, + EHOSTUNREACH, + EHOSTUNREACH, + EHOSTUNREACH, + EHOSTUNREACH, +}; + +/* + * Send out ICMP echo response. + */ +static int NutIcmpReflect(NUTDEVICE * dev, uint8_t type, NETBUF * nb) +{ + IPHDR *ip; + uint32_t dest; + IFNET *nif; + + ip = nb->nb_nw.vp; + dest = ip->ip_src; + nif = dev->dev_icb; + ip->ip_src = nif->if_local_ip; + ip->ip_ttl = MAXTTL; + + return NutIcmpOutput(type, dest, nb); +} + +/* + * Process incoming ICMP messages for destination unreachable. + */ +static int NutIcmpUnreach(NETBUF * nb, int icmp_code) +{ + IPHDR *ih; + + if (nb->nb_ap.sz < sizeof(IPHDR) + 8) + return -1; + + ih = nb->nb_ap.vp; + + switch (ih->ip_p) { + case IPPROTO_TCP: + { + TCPHDR *th; + TCPSOCKET *sock_tcp; + + th = (TCPHDR *) ((char *) ih) + sizeof(IPHDR); + sock_tcp = NutTcpFindSocket(th->th_dport, th->th_sport, ih->ip_src); + if (sock_tcp == 0) + return -1; + + if (sock_tcp->so_state != TCPS_SYN_SENT && sock_tcp->so_state != TCPS_ESTABLISHED) + return -1; + + NutTcpAbortSocket(sock_tcp, icmp_code2errno[icmp_code]); + } + break; + +#ifndef NUT_UDP_ICMP_EXCLUDE + case IPPROTO_UDP: + { + UDPHDR *uh; + UDPSOCKET *sock_udp; + + uh = (UDPHDR *) (((char *) ih) + sizeof(IPHDR)); + sock_udp = NutUdpFindSocket(uh->uh_dport); + + if (sock_udp == NULL) + return -1; + + if (NutUdpSetSocketError(sock_udp, ih->ip_dst, uh->uh_dport, icmp_code2errno[icmp_code])) + return -1; + } + break; +#endif + + default: + return -1; + } + + + return 0; +} + +/*! + * \brief Handle incoming ICMP packets. + * + * Incoming ICMP packets are processed in the background. + * NutNet currently handles echo request and destination + * unreachable packets. Any other packet type is silently + * discarded. + * + * \note This routine is called by the IP layer on incoming + * ICMP datagrams. Applications typically do not call + * this function. + * + * \param dev Identifies the device that received the packet. + * \param nb Pointer to a network buffer structure containing + * the ICMP datagram. + */ +void NutIcmpInput(NUTDEVICE * dev, NETBUF * nb) +{ + ICMPHDR *icp = (ICMPHDR *) nb->nb_tp.vp; + + /* Silently discard packets, which are too small. */ + if (icp == NULL || nb->nb_tp.sz < sizeof(ICMPHDR)) { + NutNetBufFree(nb); + return; + } + + nb->nb_ap.sz = nb->nb_tp.sz - sizeof(ICMPHDR); + if (nb->nb_ap.sz) { + nb->nb_ap.vp = icp + 1; + nb->nb_tp.sz = sizeof(ICMPHDR); + } + + switch (icp->icmp_type) { + case ICMP_ECHO: + if (NutIcmpReflect(dev, ICMP_ECHOREPLY, nb)) { + break; + } + case ICMP_UNREACH: + NutIcmpUnreach(nb, icp->icmp_code); + default: + NutNetBufFree(nb); + } +} + +/*@}*/ diff --git a/pool/shard006/C/0120064_main.c b/pool/shard006/C/0120064_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5babf04c6c43da88afdc0ff73d82733129a7f984 --- /dev/null +++ b/pool/shard006/C/0120064_main.c @@ -0,0 +1,147 @@ +/******************************************************************//** +* @file main.c +* @brief Program to interface of Stepper Motor and demonstrate fixed rotation of motor +* @version v1.0 +* @date Apr 16, 2015 +* @author Bhavin R. Darji +**********************************************************************/ + + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f4xx_hal.h" +#include "gpio.h" + +/* USER CODE BEGIN Includes */ +#include "stm32f4_global.h" +#include "stm32f4_discovery_uart.h" +//#include "stm32f4_discovery.h" +#include "stm32f4_ask25.h" +//#include "stm32f4_ask25_lcd.h" + +/* USER CODE END Includes */ + +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +void SystemClock_Config(void); + +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +int main(void) +{ + + /* USER CODE BEGIN 1 */ + + /* USER CODE END 1 */ + + /* MCU Configuration----------------------------------------------------------*/ + + /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ + HAL_Init(); + + /* Configure the system clock */ + SystemClock_Config(); + + /* Initialize all configured peripherals */ + MX_GPIO_Init(); + + /* USER CODE BEGIN 2 */ + BSP_UART_Init(115200); + + /* Initialize Stepper Motor pins */ + ASK25_SM_Init(); + + /* rotate stepper motor fix 90 degree with delay 60 */ + ASK25_SM_Rotate(MotorClockwise,90,60); + + trace_printf("Hello\n"); + /* USER CODE END 2 */ + + /* Infinite loop */ + /* USER CODE BEGIN WHILE */ + while (1) + { + /* USER CODE END WHILE */ + + /* USER CODE BEGIN 3 */ + + } + /* USER CODE END 3 */ + +} + +/** System Clock Configuration +*/ +void SystemClock_Config(void) +{ + + RCC_OscInitTypeDef RCC_OscInitStruct; + RCC_ClkInitTypeDef RCC_ClkInitStruct; + + __PWR_CLK_ENABLE(); + + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 5; + RCC_OscInitStruct.PLL.PLLN = 210; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 4; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|RCC_CLOCKTYPE_PCLK1 + |RCC_CLOCKTYPE_PCLK2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); + +} + +/* USER CODE BEGIN 4 */ + +/* USER CODE END 4 */ + +#ifdef USE_FULL_ASSERT + +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + /* USER CODE END 6 */ + +} + +#endif + +/** + * @} + */ + +/** + * @} +*/ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0120065_digits.c b/pool/shard006/C/0120065_digits.c new file mode 100644 index 0000000000000000000000000000000000000000..3641a5ddced24971992340bc6886c245ed562628 --- /dev/null +++ b/pool/shard006/C/0120065_digits.c @@ -0,0 +1,40 @@ +/**/ + +//**/ +//**/ + +#include +#include +#include + +int main() { + +int n, digit; + +printf("Enter an integer > "); +scanf("%d", &n); + + if (n==0){ + printf("\n0"); + printf("\nThat's all, have a nice day!\n"); + return(0); + } + + while (abs(n)>0){ + if (n>0 || (n<0 && (n/10.0)> 10.0)){ + digit = n % 10; + printf("\n%d", digit); + n= n/10.0; + } + else if(n<0 && (n/10.0)< 10.0){ + digit = n % 10; + printf("\n%d", digit); + n= (n)/10.0; + } + } + +//**/ + +printf("\nThat's all, have a nice day!\n"); +return (0); +} diff --git a/pool/shard006/C/0120066_zeus.c b/pool/shard006/C/0120066_zeus.c new file mode 100644 index 0000000000000000000000000000000000000000..f17dcb067350c4142613d56181041ad46a1e0dfb --- /dev/null +++ b/pool/shard006/C/0120066_zeus.c @@ -0,0 +1,88 @@ +#include + +/* + + *** WORK IN PROGRESS *** + + Zeus mode + + A Zeus instance can load all of the available imperial monitor plugins, but instead of spawning + vassals it delegates actions to Emperors connected to it. + + The Zeus instance try to distribute vassals evenly between Emperors. + + Emperors register to one (ore more, maybe...) Zeus instance, passing various informations (like the maximum number + of vassals it can manage) + + to spawn a Zeus: + + + # unencrypted mode + uwsgi --zeus 192.168.173.17:4040 --emperor /etc/uwsgi/vassals + # crypted mode + uwsgi --zeus 192.168.173.17:4040,foobar.crt,foobar.key --emperor /etc/uwsgi/vassals + # crypted + authentication mode + uwsgi --zeus 192.168.173.17:4040,foobar.crt,foobar.key,clients.pem --emperor /etc/uwsgi/vassals + + + to connect an Emperor to Zeus + + # unencrypted mode + uwsgi --emperor zeus:192.168.173.17:4040 + # crypted mode + uwsgi --emperor zeus-ssl:192.168.173.17:4040 + # crypted + authentication mode + uwsgi --emperor zeus-ssl:192.168.173.17:4040,myself.key + + + Protocol + + (each message is a basic uwsgi packet: modifier1 pktsize modifier2 payload) + + modifier2 identifies the type of the message + + 0 -> I_AM_ALIVE {node: 'node001', max_vassals: '100', running_vassals: '17'} [ emperor -> zeus ] + + 1 -> NEW_VASSAL {name: 'foobar.ini'} [ zeus -> the choosen emperor ] + + 2 -> ACCEPTED_VASSAL {name: 'foobar.ini'} [ emperor -> zeus ] + + 3 -> CONFIG_CHUNK {name: 'foobar.ini', body: '[uwsgi].....'} [ zeus -> the choosen emperor ] + + 4 -> CONFIG_END {name: 'foobar.ini'} [ zeus -> the choosen emperor ] + + 5 -> VASSAL_SPAWNED {name: 'foobar.ini'} [the choosen emperor -> zeus] + + 6 -> VASSAL_REJECTED {name: 'foobar.ini'} [the choosen emperor -> zeus] + + 7 -> VASSAL_RELOAD {name: 'foobar.ini'} [ zeus -> the choosen emperor ] + + 8 -> VASSAL_UPDATE {name: 'foobar.ini'} [ zeus -> the choosen emperor ] + + 9 -> VASSAL_DESTROY {name: 'foobar.ini'} [ zeus -> the choosen emperor ] + + 10 -> VASSAL_RELOADED {name: 'foobar.ini'} [the choosen emperor -> zeus] + + 11 -> VASSAL_DESTROYED {name: 'foobar.ini'} [the choosen emperor -> zeus] + +*/ + +/* + check how many nodes the instace needs (default 1) +*/ + +int uwsgi_zeus_spawn_instance(struct uwsgi_instance *ui) { + int i, nodes = 1; + char *how_many_nodes = vassal_attr_get(ui, "zeus-nodes"); + if (how_many_nodes) { + nodes = atoi(how_many_nodes); + } + for(i=0;i + + 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, 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 . +*/ + +#include "mininim.h" + +struct frameset kid_sword_walkb_frameset[KID_SWORD_WALKB_FRAMESET_NMEMB]; + +static void init_kid_sword_walkb_frameset (void); +static bool flow (struct anim *k); +static bool physics_in (struct anim *k); +static void physics_out (struct anim *k); + +ALLEGRO_BITMAP *kid_sword_walkb_00, *kid_sword_walkb_01; + +static void +init_kid_sword_walkb_frameset (void) +{ + struct frameset frameset[KID_SWORD_WALKB_FRAMESET_NMEMB] = + {{kid_sword_walkb_00,-1,0},{kid_sword_walkb_01,+11,0}}; + + memcpy (&kid_sword_walkb_frameset, &frameset, + KID_SWORD_WALKB_FRAMESET_NMEMB * sizeof (struct frameset)); +} + +void +load_kid_sword_walkb (void) +{ + /* bitmaps */ + kid_sword_walkb_00 = load_bitmap (KID_SWORD_WALKB_00); + kid_sword_walkb_01 = load_bitmap (KID_SWORD_WALKB_01); + + /* frameset */ + init_kid_sword_walkb_frameset (); +} + +void +unload_kid_sword_walkb (void) +{ + destroy_bitmap (kid_sword_walkb_00); + destroy_bitmap (kid_sword_walkb_01); +} + +void +kid_sword_walkb (struct anim *k) +{ + k->oaction = k->action; + k->action = kid_sword_walkb; + k->f.flip = (k->f.dir == RIGHT) ? ALLEGRO_FLIP_HORIZONTAL : 0; + + if (! flow (k)) return; + if (! physics_in (k)) return; + next_frame (&k->f, &k->f, &k->fo); + physics_out (k); +} + +static bool +flow (struct anim *k) +{ + if (k->oaction != kid_sword_walkb) k->i = -1; + + if (k->i == 1) { + kid_sword_normal (k); + return false; + } + + if (k->i == -1) k->j = 10; + if (k->i == 0) k->j = 17; + + if (k->f.b == kid_sword_attack_frameset[5].frame) k->i = 0; + + select_frame (k, kid_sword_walkb_frameset, k->i + 1); + select_xframe (&k->xf, sword_frameset, k->j); + + return true; +} + +static bool +physics_in (struct anim *k) +{ + struct pos pbf, pmbo, pbb; + + /* collision */ + uncollide (&k->f, &k->fo, &k->fo, +0, true, &k->ci); + + /* fall */ + survey (_bf, pos, &k->f, NULL, &pbf, NULL); + survey (_mbo, pos, &k->f, NULL, &pmbo, NULL); + survey (_bb, pos, &k->f, NULL, &pbb, NULL); + if (is_strictly_traversable (&pbf) + || is_strictly_traversable (&pmbo) + || is_strictly_traversable (&pbb)) { + k->xf.b = NULL; + kid_fall (k); + return false; + } + + return true; +} + +static void +physics_out (struct anim *k) +{ + /* depressible floors */ + if (k->i == 1) update_depressible_floor (k, -1, -24); + else keep_depressible_floor (k); +} diff --git a/pool/shard006/C/0120071_hal_tick.c b/pool/shard006/C/0120071_hal_tick.c new file mode 100644 index 0000000000000000000000000000000000000000..f0e04a10c19296dd159db4c07ab46c9811811657 --- /dev/null +++ b/pool/shard006/C/0120071_hal_tick.c @@ -0,0 +1,159 @@ +/** + ****************************************************************************** + * @file hal_tick.c + * @author MCD Application Team + * @brief Initialization of HAL tick + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ +#include "hal_tick.h" + +TIM_HandleTypeDef TimMasterHandle; +uint32_t PreviousVal = 0; + +void us_ticker_irq_handler(void); +void set_compare(uint16_t count); + +extern volatile uint32_t SlaveCounter; +extern volatile uint32_t oc_int_part; +extern volatile uint16_t oc_rem_part; + +// Used to increment the slave counter +void timer_update_irq_handler(void) +{ + TimMasterHandle.Instance = TIM_MST; + + // Clear Update interrupt flag + if (__HAL_TIM_GET_FLAG(&TimMasterHandle, TIM_FLAG_UPDATE) == SET) { + __HAL_TIM_CLEAR_FLAG(&TimMasterHandle, TIM_FLAG_UPDATE); + SlaveCounter++; + } +} + +// Used for mbed timeout (channel 1) and HAL tick (channel 2) +void timer_oc_irq_handler(void) +{ + uint16_t cval = TIM_MST->CNT; + TimMasterHandle.Instance = TIM_MST; + + // Channel 1 for mbed timeout + if (__HAL_TIM_GET_FLAG(&TimMasterHandle, TIM_FLAG_CC1) == SET) { + __HAL_TIM_CLEAR_FLAG(&TimMasterHandle, TIM_FLAG_CC1); + if (oc_rem_part > 0) { + set_compare(oc_rem_part); // Finish the remaining time left + oc_rem_part = 0; + } else { + if (oc_int_part > 0) { + set_compare(0xFFFF); + oc_rem_part = cval; // To finish the counter loop the next time + oc_int_part--; + } else { + us_ticker_irq_handler(); + } + } + } + + // Channel 2 for HAL tick + if (__HAL_TIM_GET_FLAG(&TimMasterHandle, TIM_FLAG_CC2) == SET) { + __HAL_TIM_CLEAR_FLAG(&TimMasterHandle, TIM_FLAG_CC2); + uint32_t val = __HAL_TIM_GetCounter(&TimMasterHandle); + if ((val - PreviousVal) >= HAL_TICK_DELAY) { + // Increment HAL variable + HAL_IncTick(); + // Prepare next interrupt + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, val + HAL_TICK_DELAY); + PreviousVal = val; + } + } +} + +// Reconfigure the HAL tick using a standard timer instead of systick. +HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { + + static uint32_t ticker_inited=0; + if(ticker_inited)return HAL_OK; + ticker_inited=1; + + // Enable timer clock + TIM_MST_RCC; + + // Reset timer + TIM_MST_RESET_ON; + TIM_MST_RESET_OFF; + + // Update the SystemCoreClock variable + SystemCoreClockUpdate(); + + // Configure time base + TimMasterHandle.Instance = TIM_MST; + TimMasterHandle.Init.Period = 0xFFFF; + TimMasterHandle.Init.Prescaler = (uint32_t)(SystemCoreClock / 1000000) - 1; // 1 us tick + TimMasterHandle.Init.ClockDivision = 0; + TimMasterHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + HAL_TIM_Base_Init(&TimMasterHandle); + + // Configure output compare channel 1 for mbed timeout (enabled later when used) + HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_1); + + // Configure output compare channel 2 for HAL tick + HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_2); + PreviousVal = __HAL_TIM_GetCounter(&TimMasterHandle); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, PreviousVal + HAL_TICK_DELAY); + + // Configure interrupts + // Update interrupt used for 32-bit counter + // Output compare channel 1 interrupt for mbed timeout + // Output compare channel 2 interrupt for HAL tick + NVIC_SetVector(TIM_MST_UP_IRQ, (uint32_t)timer_update_irq_handler); + NVIC_EnableIRQ(TIM_MST_UP_IRQ); + NVIC_SetVector(TIM_MST_OC_IRQ, (uint32_t)timer_oc_irq_handler); + NVIC_EnableIRQ(TIM_MST_OC_IRQ); + + // Enable interrupts + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_UPDATE); // For 32-bit counter + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_CC2); // For HAL tick + + // Enable timer + HAL_TIM_Base_Start(&TimMasterHandle); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0120076_tsens-8996.c b/pool/shard006/C/0120076_tsens-8996.c new file mode 100644 index 0000000000000000000000000000000000000000..e1f77818d8fa3bd4cf4608e47820b1974f4e65fb --- /dev/null +++ b/pool/shard006/C/0120076_tsens-8996.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2015, The Linux Foundation. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include "tsens.h" + +#define STATUS_OFFSET 0x10a0 +#define LAST_TEMP_MASK 0xfff +#define STATUS_VALID_BIT BIT(21) +#define CODE_SIGN_BIT BIT(11) + +static int get_temp_8996(struct tsens_device *tmdev, int id, int *temp) +{ + struct tsens_sensor *s = &tmdev->sensor[id]; + u32 code; + unsigned int sensor_addr; + int last_temp = 0, last_temp2 = 0, last_temp3 = 0, ret; + + sensor_addr = STATUS_OFFSET + s->hw_id * 4; + ret = regmap_read(tmdev->map, sensor_addr, &code); + if (ret) + return ret; + last_temp = code & LAST_TEMP_MASK; + if (code & STATUS_VALID_BIT) + goto done; + + /* Try a second time */ + ret = regmap_read(tmdev->map, sensor_addr, &code); + if (ret) + return ret; + if (code & STATUS_VALID_BIT) { + last_temp = code & LAST_TEMP_MASK; + goto done; + } else { + last_temp2 = code & LAST_TEMP_MASK; + } + + /* Try a third/last time */ + ret = regmap_read(tmdev->map, sensor_addr, &code); + if (ret) + return ret; + if (code & STATUS_VALID_BIT) { + last_temp = code & LAST_TEMP_MASK; + goto done; + } else { + last_temp3 = code & LAST_TEMP_MASK; + } + + if (last_temp == last_temp2) + last_temp = last_temp2; + else if (last_temp2 == last_temp3) + last_temp = last_temp3; +done: + /* Code sign bit is the sign extension for a negative value */ + if (last_temp & CODE_SIGN_BIT) + last_temp |= ~CODE_SIGN_BIT; + + /* Temperatures are in deciCelicius */ + *temp = last_temp * 100; + + return 0; +} + +static const struct tsens_ops ops_8996 = { + .init = init_common, + .get_temp = get_temp_8996, +}; + +const struct tsens_data data_8996 = { + .num_sensors = 13, + .ops = &ops_8996, +}; diff --git a/pool/shard006/C/0120078_common_string.c b/pool/shard006/C/0120078_common_string.c new file mode 100644 index 0000000000000000000000000000000000000000..f1e02e6fd66b0736f1d0a2a27566e0d17e8df99f --- /dev/null +++ b/pool/shard006/C/0120078_common_string.c @@ -0,0 +1,109 @@ +/* Copyright 2010 ENSEIRB, INRIA & CNRS +** +** This file is part of the Scotch software package for static mapping, +** graph partitioning and sparse matrix ordering. +** +** This software is governed by the CeCILL-C license under French law +** and abiding by the rules of distribution of free software. You can +** use, modify and/or redistribute the software under the terms of the +** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following +** URL: "http://www.cecill.info". +** +** As a counterpart to the access to the source code and rights to copy, +** modify and redistribute granted by the license, users are provided +** only with a limited warranty and the software's author, the holder of +** the economic rights, and the successive licensors have only limited +** liability. +** +** In this respect, the user's attention is drawn to the risks associated +** with loading, using, modifying and/or developing or reproducing the +** software by the user in light of its specific status of free software, +** that may mean that it is complicated to manipulate, and that also +** therefore means that it is reserved for developers and experienced +** professionals having in-depth computer knowledge. Users are therefore +** encouraged to load and test the software's suitability as regards +** their requirements in conditions enabling the security of their +** systems and/or data to be ensured and, more generally, to use and +** operate it in the same conditions as regards security. +** +** The fact that you are presently reading this means that you have had +** knowledge of the CeCILL-C license and that you accept its terms. +*/ +/************************************************************/ +/** **/ +/** NAME : common_string.c **/ +/** **/ +/** AUTHORS : Francois PELLEGRINI **/ +/** **/ +/** FUNCTION : Part of a parallel direct block solver. **/ +/** These lines are common routines used **/ +/** by all modules. **/ +/** **/ +/** DATES : # Version 5.1 : from : 23 jul 2010 **/ +/** to 23 jul 2010 **/ +/** **/ +/************************************************************/ + +/* +** The defines and includes. +*/ + +#define COMMON + +#ifndef COMMON_NOMODULE +#include "module.h" +#endif /* COMMON_NOMODULE */ +#include +#include "common.h" + +/********************************/ +/* */ +/* String substitution routine. */ +/* */ +/********************************/ + +static +void +stringSubst2 ( +char * const bsrcptr, +char * const bdstptr, +const char * const pattstr, +const char * const replstr, +const int pattsiz, +const int replsiz) +{ + char * pattptr; + int pattidx; + + pattptr = strstr (bsrcptr, pattstr); /* Search for the pattern in the remaining source string */ + pattidx = (pattptr == NULL) ? (strlen (bsrcptr) + 1): (pattptr - bsrcptr); /* Get length of unchanged part */ + + if (replsiz < pattsiz) /* If replacement is smaller, pre-move unchanged part */ + memMov (bdstptr, bsrcptr, pattidx * sizeof (char)); + + if (pattptr != NULL) /* If remaining part of string has to be processed */ + stringSubst2 (pattptr + pattsiz, bdstptr + pattidx + replsiz, pattstr, replstr, pattsiz, replsiz); + + if (replsiz > pattsiz) /* If replacement is longer, post-move unchanged part */ + memMov (bdstptr, bsrcptr, pattidx * sizeof (char)); + + if (pattptr != NULL) /* If there is something to replace */ + memCpy (bdstptr + pattidx, replstr, replsiz * sizeof (char)); /* Write replacement string */ + + return; +} + +void +stringSubst ( +char * const buffptr, /* String to search into */ +const char * const pattstr, /* Pattern to search for */ +const char * const replstr) /* Replacement string */ +{ + int pattsiz; + int replsiz; + + pattsiz = strlen (pattstr); + replsiz = strlen (replstr); + + stringSubst2 (buffptr, buffptr, pattstr, replstr, pattsiz, replsiz); +} diff --git a/pool/shard006/C/0120089_pci-dma.c b/pool/shard006/C/0120089_pci-dma.c new file mode 100644 index 0000000000000000000000000000000000000000..1a7b56b89e82db9d05e5b232038622e2f4a7a363 --- /dev/null +++ b/pool/shard006/C/0120089_pci-dma.c @@ -0,0 +1,41 @@ +/* + * BK Id: SCCS/s.pci-dma.c 1.5 05/17/01 18:14:21 cort + */ +/* + * Copyright (C) 2000 Ani Joshi + * + * + * Dynamic DMA mapping support. + * + * swiped from i386 + * + */ + +#include +#include +#include +#include +#include + +void *pci_alloc_consistent(struct pci_dev *hwdev, size_t size, + dma_addr_t *dma_handle) +{ + void *ret; + int gfp = GFP_ATOMIC; + + if (hwdev == NULL || hwdev->dma_mask != 0xffffffff) + gfp |= GFP_DMA; + ret = (void *)__get_free_pages(gfp, get_order(size)); + + if (ret != NULL) { + memset(ret, 0, size); + *dma_handle = virt_to_bus(ret); + } + return ret; +} + +void pci_free_consistent(struct pci_dev *hwdev, size_t size, + void *vaddr, dma_addr_t dma_handle) +{ + free_pages((unsigned long)vaddr, get_order(size)); +} diff --git a/pool/shard006/C/0120092_timer.c b/pool/shard006/C/0120092_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..c420848b9ffe9d11e222db4db6b0eb060f6e3098 --- /dev/null +++ b/pool/shard006/C/0120092_timer.c @@ -0,0 +1,101 @@ +/* +Copyright (C) 2008 by Radiation Laboratories Development-Crew +DEV@rad-lab.net +File: timer.c +Created on: 19. Februar 2008, 14:49 +Belongs to project: uvXpose + +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 "timer.h" +#include "relay.h" + +char *Con_Time_Int_Str(uint16_t contime) +{ + if(contime <= 3600) + { + static char chartime[6]; + uint8_t minutes10 = (contime / 60 / 10); + uint8_t minutes1 = (contime / 60) % 10; + uint8_t seconds10 = (contime / 10) % 6; + uint8_t seconds1 = contime%10; + + chartime[0]=(char)minutes10 + 48; + chartime[1]=(char)minutes1 + 48; + chartime[2]=(char)0x3A /*No ASCII Standard for :*/; + chartime[3]=(char)seconds10 + 48; + chartime[4]=(char)seconds1 + 48; + chartime[5]='\0'; + + return chartime; + } + else + { + return "ERRT1"; + } +} + +void TIMER_Init( void ) +{ + /*clear interrupts for accessing Output Compare Register*/ + INTERRUPT_Clear(); + /*set OCR1 1 second on current clock*/ + OCR1A |= _TIMER_CLOCK_1SEC_TOP_; + /*reactivate interrupts*/ + INTERRUPT_Restore(); + /*initialise variable for number of received chars from usart*/ + global.serial_char_count=0; +} +void TIMER_Start( void ) +{ + /*clear interrupts for accessing Output Compare Register*/ + INTERRUPT_Clear(); + /*start value*/ + TCNT1=0x0000; + /*reactivate interrupts*/ + INTERRUPT_Restore(); + /*set Interrupt for timer 1*/ + TIMSK |= (1< +#include +#include +#include +#include +#include + +#include +#include + +EXPORT_NO_SYMBOLS; +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("IPv6 AH match"); +MODULE_AUTHOR("Andras Kis-Szabo "); + +#if 0 +#define DEBUGP printk +#else +#define DEBUGP(format, args...) +#endif + +struct ahhdr { + __u8 nexthdr; + __u8 hdrlen; + __u16 reserved; + __u32 spi; +}; + +/* Returns 1 if the spi is matched by the range, 0 otherwise */ +static inline int +spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, int invert) +{ + int r=0; + DEBUGP("ah spi_match:%c 0x%x <= 0x%x <= 0x%x",invert? '!':' ', + min,spi,max); + r=(spi >= min && spi <= max) ^ invert; + DEBUGP(" result %s\n",r? "PASS\n" : "FAILED\n"); + return r; +} + +static int +match(const struct sk_buff *skb, + const struct net_device *in, + const struct net_device *out, + const void *matchinfo, + int offset, + const void *protohdr, + u_int16_t datalen, + int *hotdrop) +{ + struct ahhdr *ah = NULL; + const struct ip6t_ah *ahinfo = matchinfo; + unsigned int temp; + int len; + u8 nexthdr; + unsigned int ptr; + unsigned int hdrlen = 0; + + /*DEBUGP("IPv6 AH entered\n");*/ + /* if (opt->auth == 0) return 0; + * It does not filled on output */ + + /* type of the 1st exthdr */ + nexthdr = skb->nh.ipv6h->nexthdr; + /* pointer to the 1st exthdr */ + ptr = sizeof(struct ipv6hdr); + /* available length */ + len = skb->len - ptr; + temp = 0; + + while (ip6t_ext_hdr(nexthdr)) { + struct ipv6_opt_hdr *hdr; + + DEBUGP("ipv6_ah header iteration \n"); + + /* Is there enough space for the next ext header? */ + if (len < (int)sizeof(struct ipv6_opt_hdr)) + return 0; + /* No more exthdr -> evaluate */ + if (nexthdr == NEXTHDR_NONE) { + break; + } + /* ESP -> evaluate */ + if (nexthdr == NEXTHDR_ESP) { + break; + } + + hdr=(struct ipv6_opt_hdr *)skb->data+ptr; + + /* Calculate the header length */ + if (nexthdr == NEXTHDR_FRAGMENT) { + hdrlen = 8; + } else if (nexthdr == NEXTHDR_AUTH) + hdrlen = (hdr->hdrlen+2)<<2; + else + hdrlen = ipv6_optlen(hdr); + + /* AH -> evaluate */ + if (nexthdr == NEXTHDR_AUTH) { + temp |= MASK_AH; + break; + } + + + /* set the flag */ + switch (nexthdr){ + case NEXTHDR_HOP: + case NEXTHDR_ROUTING: + case NEXTHDR_FRAGMENT: + case NEXTHDR_AUTH: + case NEXTHDR_DEST: + break; + default: + DEBUGP("ipv6_ah match: unknown nextheader %u\n",nexthdr); + return 0; + break; + } + + nexthdr = hdr->nexthdr; + len -= hdrlen; + ptr += hdrlen; + if ( ptr > skb->len ) { + DEBUGP("ipv6_ah: new pointer too large! \n"); + break; + } + } + + /* AH header not found */ + if ( temp != MASK_AH ) return 0; + + if (len < (int)sizeof(struct ahhdr)){ + *hotdrop = 1; + return 0; + } + + ah = (struct ahhdr *) (skb->data + ptr); + + DEBUGP("IPv6 AH LEN %u %u ", hdrlen, ah->hdrlen); + DEBUGP("RES %04X ", ah->reserved); + DEBUGP("SPI %u %08X\n", ntohl(ah->spi), ntohl(ah->spi)); + + DEBUGP("IPv6 AH spi %02X ", + (spi_match(ahinfo->spis[0], ahinfo->spis[1], + ntohl(ah->spi), + !!(ahinfo->invflags & IP6T_AH_INV_SPI)))); + DEBUGP("len %02X %04X %02X ", + ahinfo->hdrlen, hdrlen, + (!ahinfo->hdrlen || + (ahinfo->hdrlen == hdrlen) ^ + !!(ahinfo->invflags & IP6T_AH_INV_LEN))); + DEBUGP("res %02X %04X %02X\n", + ahinfo->hdrres, ah->reserved, + !(ahinfo->hdrres && ah->reserved)); + + return (ah != NULL) + && + (spi_match(ahinfo->spis[0], ahinfo->spis[1], + ntohl(ah->spi), + !!(ahinfo->invflags & IP6T_AH_INV_SPI))) + && + (!ahinfo->hdrlen || + (ahinfo->hdrlen == hdrlen) ^ + !!(ahinfo->invflags & IP6T_AH_INV_LEN)) + && + !(ahinfo->hdrres && ah->reserved); +} + +/* Called when user tries to insert an entry of this type. */ +static int +checkentry(const char *tablename, + const struct ip6t_ip6 *ip, + void *matchinfo, + unsigned int matchinfosize, + unsigned int hook_mask) +{ + const struct ip6t_ah *ahinfo = matchinfo; + + if (matchinfosize != IP6T_ALIGN(sizeof(struct ip6t_ah))) { + DEBUGP("ip6t_ah: matchsize %u != %u\n", + matchinfosize, IP6T_ALIGN(sizeof(struct ip6t_ah))); + return 0; + } + if (ahinfo->invflags & ~IP6T_AH_INV_MASK) { + DEBUGP("ip6t_ah: unknown flags %X\n", + ahinfo->invflags); + return 0; + } + + return 1; +} + +static struct ip6t_match ah_match += { { NULL, NULL }, "ah", &match, &checkentry, NULL, THIS_MODULE }; + +static int __init init(void) +{ + return ip6t_register_match(&ah_match); +} + +static void __exit cleanup(void) +{ + ip6t_unregister_match(&ah_match); +} + +module_init(init); +module_exit(cleanup); diff --git a/pool/shard006/C/0120097_Prog1a.c b/pool/shard006/C/0120097_Prog1a.c new file mode 100644 index 0000000000000000000000000000000000000000..8190e70d294ab6dab36c191bc746e531f0466275 --- /dev/null +++ b/pool/shard006/C/0120097_Prog1a.c @@ -0,0 +1,40 @@ +/* Day 6 + * Question 1(a) + * Write a program to print the fibonacci sequence upto n terms + * + * + * Author - + * Akshay Anand + * CSE 2nd Sem - St. Thomas' College of Engineering & Technology + */ + + #include + + int main() + { + int length, i; + printf("Enter the length of the sequence: "); + scanf("%d", &length); + + int arr[length]; + + arr[0] = 0; + arr[1] = 1; + + for(i=2; i +#include +#include +#include +#include +#include +#include +#include +#include "posixtest.h" + +int main(void) +{ + struct timespec interval; + int result = -2, child_pid, stat_loc; + struct sched_param param; + + param.sched_priority = sched_get_priority_min(SCHED_RR); + if (sched_setscheduler(0, SCHED_RR, ¶m) == -1) { + printf("sched_setscheduler failed: %d (%s)\n", + errno, strerror(errno)); + return PTS_UNRESOLVED; + } + + /* Create a child process which exit immediately */ + child_pid = fork(); + if (child_pid == -1) { + perror("fork failed"); + return PTS_UNRESOLVED; + } else if (child_pid == 0) { + exit(0); + } + + /* Wait for the child process to exit */ + if (wait(&stat_loc) == -1) { + perror("wait failed"); + return PTS_UNRESOLVED; + } + + /* Assume the pid is not yet reatributed to an other process */ + result = sched_rr_get_interval(child_pid, &interval); + + if (result == -1 && errno == ESRCH) { + printf("Test PASSED\n"); + return PTS_PASS; + } + + if (errno != ESRCH) { + perror("Returned error is not ESRCH"); + return PTS_FAIL; + } + + if (result == 0) { + printf("Returned code == 0.\n"); + return PTS_FAIL; + } else { + perror("Unresolved test error"); + return PTS_UNRESOLVED; + } + +} diff --git a/pool/shard006/C/0120102_gl620a.c b/pool/shard006/C/0120102_gl620a.c new file mode 100644 index 0000000000000000000000000000000000000000..d257a8e026d6182b77fea025a60376eb842b063b --- /dev/null +++ b/pool/shard006/C/0120102_gl620a.c @@ -0,0 +1,245 @@ +/* + * GeneSys GL620USB-A based links + * Copyright (C) 2001 by Jiun-Jie Huang + * Copyright (C) 2001 by Stanislav Brabec + * + * 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 + */ + +// #define DEBUG // error path messages, extra info +// #define VERBOSE // more; success messages + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "usbnet.h" + + +/* + * GeneSys GL620USB-A (www.genesyslogic.com.tw) + * + * ... should partially interop with the Win32 driver for this hardware. + * The GeneSys docs imply there's some NDIS issue motivating this framing. + * + * Some info from GeneSys: + * - GL620USB-A is full duplex; GL620USB is only half duplex for bulk. + * (Some cables, like the BAFO-100c, use the half duplex version.) + * - For the full duplex model, the low bit of the version code says + * which side is which ("left/right"). + * - For the half duplex type, a control/interrupt handshake settles + * the transfer direction. (That's disabled here, partially coded.) + * A control URB would block until other side writes an interrupt. + * + * Original code from Jiun-Jie Huang + * and merged into "usbnet" by Stanislav Brabec . + */ + +// control msg write command +#define GENELINK_CONNECT_WRITE 0xF0 +// interrupt pipe index +#define GENELINK_INTERRUPT_PIPE 0x03 +// interrupt read buffer size +#define INTERRUPT_BUFSIZE 0x08 +// interrupt pipe interval value +#define GENELINK_INTERRUPT_INTERVAL 0x10 +// max transmit packet number per transmit +#define GL_MAX_TRANSMIT_PACKETS 32 +// max packet length +#define GL_MAX_PACKET_LEN 1514 +// max receive buffer size +#define GL_RCV_BUF_SIZE \ + (((GL_MAX_PACKET_LEN + 4) * GL_MAX_TRANSMIT_PACKETS) + 4) + +struct gl_packet { + __le32 packet_length; + char packet_data [1]; +}; + +struct gl_header { + __le32 packet_count; + struct gl_packet packets; +}; + +static int genelink_rx_fixup(struct usbnet *dev, struct sk_buff *skb) +{ + struct gl_header *header; + struct gl_packet *packet; + struct sk_buff *gl_skb; + u32 size; + u32 count; + + header = (struct gl_header *) skb->data; + + // get the packet count of the received skb + count = le32_to_cpu(header->packet_count); + if (count > GL_MAX_TRANSMIT_PACKETS) { + dbg("genelink: invalid received packet count %u", count); + return 0; + } + + // set the current packet pointer to the first packet + packet = &header->packets; + + // decrement the length for the packet count size 4 bytes + skb_pull(skb, 4); + + while (count > 1) { + // get the packet length + size = le32_to_cpu(packet->packet_length); + + // this may be a broken packet + if (size > GL_MAX_PACKET_LEN) { + dbg("genelink: invalid rx length %d", size); + return 0; + } + + // allocate the skb for the individual packet + gl_skb = alloc_skb(size, GFP_ATOMIC); + if (gl_skb) { + + // copy the packet data to the new skb + memcpy(skb_put(gl_skb, size), + packet->packet_data, size); + usbnet_skb_return(dev, gl_skb); + } + + // advance to the next packet + packet = (struct gl_packet *)&packet->packet_data[size]; + count--; + + // shift the data pointer to the next gl_packet + skb_pull(skb, size + 4); + } + + // skip the packet length field 4 bytes + skb_pull(skb, 4); + + if (skb->len > GL_MAX_PACKET_LEN) { + dbg("genelink: invalid rx length %d", skb->len); + return 0; + } + return 1; +} + +static struct sk_buff * +genelink_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags) +{ + int padlen; + int length = skb->len; + int headroom = skb_headroom(skb); + int tailroom = skb_tailroom(skb); + __le32 *packet_count; + __le32 *packet_len; + + // FIXME: magic numbers, bleech + padlen = ((skb->len + (4 + 4*1)) % 64) ? 0 : 1; + + if ((!skb_cloned(skb)) + && ((headroom + tailroom) >= (padlen + (4 + 4*1)))) { + if ((headroom < (4 + 4*1)) || (tailroom < padlen)) { + skb->data = memmove(skb->head + (4 + 4*1), + skb->data, skb->len); + skb->tail = skb->data + skb->len; + } + } else { + struct sk_buff *skb2; + skb2 = skb_copy_expand(skb, (4 + 4*1) , padlen, flags); + dev_kfree_skb_any(skb); + skb = skb2; + if (!skb) + return NULL; + } + + // attach the packet count to the header + packet_count = (__le32 *) skb_push(skb, (4 + 4*1)); + packet_len = packet_count + 1; + + *packet_count = cpu_to_le32(1); + *packet_len = cpu_to_le32(length); + + // add padding byte + if ((skb->len % dev->maxpacket) == 0) + skb_put(skb, 1); + + return skb; +} + +static int genelink_bind(struct usbnet *dev, struct usb_interface *intf) +{ + dev->hard_mtu = GL_RCV_BUF_SIZE; + dev->net->hard_header_len += 4; + dev->in = usb_rcvbulkpipe(dev->udev, dev->driver_info->in); + dev->out = usb_sndbulkpipe(dev->udev, dev->driver_info->out); + return 0; +} + +static const struct driver_info genelink_info = { + .description = "Genesys GeneLink", + .flags = FLAG_FRAMING_GL | FLAG_NO_SETINT, + .bind = genelink_bind, + .rx_fixup = genelink_rx_fixup, + .tx_fixup = genelink_tx_fixup, + + .in = 1, .out = 2, + +#ifdef GENELINK_ACK + .check_connect =genelink_check_connect, +#endif +}; + +static const struct usb_device_id products [] = { + +{ + USB_DEVICE(0x05e3, 0x0502), // GL620USB-A + .driver_info = (unsigned long) &genelink_info, +}, + /* NOT: USB_DEVICE(0x05e3, 0x0501), // GL620USB + * that's half duplex, not currently supported + */ + { }, // END +}; +MODULE_DEVICE_TABLE(usb, products); + +static struct usb_driver gl620a_driver = { + .name = "gl620a", + .id_table = products, + .probe = usbnet_probe, + .disconnect = usbnet_disconnect, + .suspend = usbnet_suspend, + .resume = usbnet_resume, +}; + +static int __init usbnet_init(void) +{ + return usb_register(&gl620a_driver); +} +module_init(usbnet_init); + +static void __exit usbnet_exit(void) +{ + usb_deregister(&gl620a_driver); +} +module_exit(usbnet_exit); + +MODULE_AUTHOR("Jiun-Jie Huang"); +MODULE_DESCRIPTION("GL620-USB-A Host-to-Host Link cables"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard006/C/0120103_stm32f4xx_hal_msp.c b/pool/shard006/C/0120103_stm32f4xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..b9531911d303ba0b9f0bc19b5dced38bd0755b00 --- /dev/null +++ b/pool/shard006/C/0120103_stm32f4xx_hal_msp.c @@ -0,0 +1,128 @@ +/** + ****************************************************************************** + * @file TIM/TIM_OCToggle/Src/stm32f4xx_hal_msp.c + * @author MCD Application Team + * @version V1.3.3 + * @date 29-January-2016 + * @brief HAL MSP module. + * This file template is located in the HAL folder and should be copied + * to the user folder. + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + +/** @addtogroup STM32F4xx_HAL_Examples + * @{ + */ + +/** @defgroup HAL_MSP + * @brief HAL MSP module. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_MSP_Private_Functions + * @{ + */ + + +/** + * @brief TIM MSP Initialization + * This function configures the hardware resources used in this example: + * - Peripheral's clock enable + * - Peripheral's GPIO Configuration + * @param htim: TIM handle pointer + * @retval None + */ +void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) +{ + GPIO_InitTypeDef GPIO_InitStruct; + + /*##-1- Enable peripherals and GPIO Clocks #################################*/ + /* TIMx Peripheral clock enable */ + TIMx_CLK_ENABLE(); + + /* Enable GPIO Channels Clock */ + TIMx_CHANNEL_GPIO_PORT(); + + /*##-2- Configure I/Os #####################################################*/ + /* Configure PC.6 (TIM3_Channel1), PC.7 (TIM3_Channel1), PC.8 (TIM3_Channel1), + PC.9 (TIM3_Channel1) in output, push-pull, alternate function mode*/ + + /* Common configuration for all channels */ + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF2_TIM3; + + /* Channel 1 configuration */ + GPIO_InitStruct.Pin = GPIO_PIN_CHANNEL1; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* Channel 2 configuration */ + GPIO_InitStruct.Pin = GPIO_PIN_CHANNEL2; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* Channel 3 configuration */ + GPIO_InitStruct.Pin = GPIO_PIN_CHANNEL3; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* Channel 4 configuration */ + GPIO_InitStruct.Pin = GPIO_PIN_CHANNEL4; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* Enable the TIM1 global Interrupt & set priority */ + HAL_NVIC_SetPriority(TIM3_IRQn, 0, 1); + HAL_NVIC_EnableIRQ(TIM3_IRQn); +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0120104_gproxyresolver.c b/pool/shard006/C/0120104_gproxyresolver.c new file mode 100644 index 0000000000000000000000000000000000000000..082274e4f615ad8966edd099f7873325b9408822 --- /dev/null +++ b/pool/shard006/C/0120104_gproxyresolver.c @@ -0,0 +1,211 @@ +/* GIO - GLib Input, Output and Streaming Library + * + * Copyright (C) 2010 Collabora, Ltd. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this library; if not, see . + * + * Author: Nicolas Dufresne + */ + +#include "config.h" + +#include "gproxyresolver.h" + +#include +#include "glibintl.h" + +#include "gasyncresult.h" +#include "gcancellable.h" +#include "giomodule.h" +#include "giomodule-priv.h" + +/** + * SECTION:gproxyresolver + * @short_description: Asynchronous and cancellable network proxy resolver + * @include: gio/gio.h + * + * #GProxyResolver provides synchronous and asynchronous network proxy + * resolution. #GProxyResolver is used within #GSocketClient through + * the method g_socket_connectable_proxy_enumerate(). + * + * Implementations of #GProxyResolver based on libproxy and GNOME settings can + * be found in glib-networking. GIO comes with an implementation for use inside + * Flatpak portals. + */ + +/** + * GProxyResolverInterface: + * @g_iface: The parent interface. + * @is_supported: the virtual function pointer for g_proxy_resolver_is_supported() + * @lookup: the virtual function pointer for g_proxy_resolver_lookup() + * @lookup_async: the virtual function pointer for + * g_proxy_resolver_lookup_async() + * @lookup_finish: the virtual function pointer for + * g_proxy_resolver_lookup_finish() + * + * The virtual function table for #GProxyResolver. + */ + +G_DEFINE_INTERFACE (GProxyResolver, g_proxy_resolver, G_TYPE_OBJECT) + +static void +g_proxy_resolver_default_init (GProxyResolverInterface *iface) +{ +} + +/** + * g_proxy_resolver_get_default: + * + * Gets the default #GProxyResolver for the system. + * + * Returns: (transfer none): the default #GProxyResolver. + * + * Since: 2.26 + */ +GProxyResolver * +g_proxy_resolver_get_default (void) +{ + return _g_io_module_get_default (G_PROXY_RESOLVER_EXTENSION_POINT_NAME, + "GIO_USE_PROXY_RESOLVER", + (GIOModuleVerifyFunc)g_proxy_resolver_is_supported); +} + +/** + * g_proxy_resolver_is_supported: + * @resolver: a #GProxyResolver + * + * Checks if @resolver can be used on this system. (This is used + * internally; g_proxy_resolver_get_default() will only return a proxy + * resolver that returns %TRUE for this method.) + * + * Returns: %TRUE if @resolver is supported. + * + * Since: 2.26 + */ +gboolean +g_proxy_resolver_is_supported (GProxyResolver *resolver) +{ + GProxyResolverInterface *iface; + + g_return_val_if_fail (G_IS_PROXY_RESOLVER (resolver), FALSE); + + iface = G_PROXY_RESOLVER_GET_IFACE (resolver); + + return (* iface->is_supported) (resolver); +} + +/** + * g_proxy_resolver_lookup: + * @resolver: a #GProxyResolver + * @uri: a URI representing the destination to connect to + * @cancellable: (nullable): a #GCancellable, or %NULL + * @error: return location for a #GError, or %NULL + * + * Looks into the system proxy configuration to determine what proxy, + * if any, to use to connect to @uri. The returned proxy URIs are of + * the form `://[user[:password]@]host:port` or + * `direct://`, where could be http, rtsp, socks + * or other proxying protocol. + * + * If you don't know what network protocol is being used on the + * socket, you should use `none` as the URI protocol. + * In this case, the resolver might still return a generic proxy type + * (such as SOCKS), but would not return protocol-specific proxy types + * (such as http). + * + * `direct://` is used when no proxy is needed. + * Direct connection should not be attempted unless it is part of the + * returned array of proxies. + * + * Returns: (transfer full) (array zero-terminated=1): A + * NULL-terminated array of proxy URIs. Must be freed + * with g_strfreev(). + * + * Since: 2.26 + */ +gchar ** +g_proxy_resolver_lookup (GProxyResolver *resolver, + const gchar *uri, + GCancellable *cancellable, + GError **error) +{ + GProxyResolverInterface *iface; + + g_return_val_if_fail (G_IS_PROXY_RESOLVER (resolver), NULL); + g_return_val_if_fail (uri != NULL, NULL); + + iface = G_PROXY_RESOLVER_GET_IFACE (resolver); + + return (* iface->lookup) (resolver, uri, cancellable, error); +} + +/** + * g_proxy_resolver_lookup_async: + * @resolver: a #GProxyResolver + * @uri: a URI representing the destination to connect to + * @cancellable: (nullable): a #GCancellable, or %NULL + * @callback: (scope async): callback to call after resolution completes + * @user_data: (closure): data for @callback + * + * Asynchronous lookup of proxy. See g_proxy_resolver_lookup() for more + * details. + * + * Since: 2.26 + */ +void +g_proxy_resolver_lookup_async (GProxyResolver *resolver, + const gchar *uri, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + GProxyResolverInterface *iface; + + g_return_if_fail (G_IS_PROXY_RESOLVER (resolver)); + g_return_if_fail (uri != NULL); + + iface = G_PROXY_RESOLVER_GET_IFACE (resolver); + + (* iface->lookup_async) (resolver, uri, cancellable, callback, user_data); +} + +/** + * g_proxy_resolver_lookup_finish: + * @resolver: a #GProxyResolver + * @result: the result passed to your #GAsyncReadyCallback + * @error: return location for a #GError, or %NULL + * + * Call this function to obtain the array of proxy URIs when + * g_proxy_resolver_lookup_async() is complete. See + * g_proxy_resolver_lookup() for more details. + * + * Returns: (transfer full) (array zero-terminated=1): A + * NULL-terminated array of proxy URIs. Must be freed + * with g_strfreev(). + * + * Since: 2.26 + */ +gchar ** +g_proxy_resolver_lookup_finish (GProxyResolver *resolver, + GAsyncResult *result, + GError **error) +{ + GProxyResolverInterface *iface; + + g_return_val_if_fail (G_IS_PROXY_RESOLVER (resolver), NULL); + + iface = G_PROXY_RESOLVER_GET_IFACE (resolver); + + return (* iface->lookup_finish) (resolver, result, error); +} diff --git a/pool/shard006/C/0120105_io_i2c.c b/pool/shard006/C/0120105_io_i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..a0b2dac203e52f1c5ded0ffce1105751fd7df2d1 --- /dev/null +++ b/pool/shard006/C/0120105_io_i2c.c @@ -0,0 +1,159 @@ +/** + * @file + */ +/****************************************************************************** + * Copyright AllSeen Alliance. All rights reserved. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + ******************************************************************************/ + +#define AJ_MODULE GPIO + +#include +#include + +#include "ajs.h" +#include "ajs_io.h" + +using namespace concurrency; +using namespace Windows::Devices::Enumeration; +using namespace Windows::Foundation; +using namespace Platform; + +// The namespace is availalbe on Windows IoT Extensions Kit reference +using namespace Windows::Devices::I2c; + + +/** +* Controls debug output for this module +*/ +#ifndef NDEBUG +extern uint8_t dbgGPIO; +#endif + +IInspectable* AddRefAsInspectable(Object^ o) +{ + IInspectable* obj = reinterpret_cast(o); + obj->AddRef(); + return obj; +} + +Object^ AsObjectRef(void *o) +{ + IInspectable* pO = reinterpret_cast(o); + return reinterpret_cast(pO); +} + +Object^ ReleaseAsObjectRef(void *o) +{ + IInspectable* pO = reinterpret_cast(o); + Object^ obj = reinterpret_cast(pO); + pO->Release(); + return obj; +} + +AJ_Status AJS_TargetIO_I2cOpen(uint8_t sda, uint8_t scl, uint32_t clock, uint8_t mode, uint8_t ownAddress, void** ctx) +{ + String^ i2cAqs = nullptr; + const AJS_IO_Info* info = AJS_TargetIO_GetInfo(sda); + if (info == nullptr) { + AJ_ErrPrintf(("AJS_TargetIO_I2cOpen(): invalid sda pin (%d)\n", sda)); + return AJ_ERR_INVALID; + } + std::string schematicId(info->schematicId); + if (schematicId.length() > 0) { + i2cAqs = I2cDevice::GetDeviceSelector(ref new String(std::wstring(schematicId.begin(), schematicId.end()).c_str())); + } else { + i2cAqs = I2cDevice::GetDeviceSelector(); + } + + auto task = create_task(DeviceInformation::FindAllAsync(i2cAqs)); + auto c1 = task.then([clock, ownAddress, ctx](DeviceInformationCollection^ deviceInfos) + { + String^ deviceId = deviceInfos->GetAt(0)->Id; + I2cConnectionSettings^ settings = ref new I2cConnectionSettings(ownAddress); + if (clock >= 400000) { + settings->BusSpeed = I2cBusSpeed::FastMode; + } else { + settings->BusSpeed = I2cBusSpeed::StandardMode; + } + settings->SharingMode = I2cSharingMode::Shared; + + auto task2 = create_task(I2cDevice::FromIdAsync(deviceId, settings)); + auto c2 = task2.then([ctx](I2cDevice^ i2cDevice) { + *ctx = AddRefAsInspectable(i2cDevice); + }); + + try { + task2.wait(); + c2.wait(); + } catch (...) { + AJ_ErrPrintf(("AJS_TargetIO_I2cOpen(): invalid device settings:\n")); + AJ_ErrPrintf((" address=%d\n", ownAddress)); + AJ_ErrPrintf((" BusSpeed=%d\n", settings->BusSpeed)); + throw; + } + }); + + try { + task.wait(); + c1.wait(); + } catch (...) { + AJ_ErrPrintf(("AJS_TargetIO_I2cOpen(): invalid id (%s)\n", info->schematicId)); + return AJ_ERR_DRIVER; + } + + return AJ_OK; +} + +AJ_Status AJS_TargetIO_I2cClose(void* ctx) +{ + I2cDevice^ i2cDevice = reinterpret_cast(ReleaseAsObjectRef(ctx)); + i2cDevice = nullptr; + return AJ_OK; +} + +AJ_Status AJS_TargetIO_I2cTransfer(void* ctx, uint8_t addr, uint8_t* txBuf, uint8_t txLen, uint8_t* rxBuf, uint8_t rxLen, uint8_t* rxBytes) +{ + I2cDevice^ i2cDevice = reinterpret_cast(AsObjectRef(ctx)); + Array^ writeBuffer = nullptr; + WriteOnlyArray^ readBuffer = nullptr; + + if (txLen > 0) { + writeBuffer = ArrayReference(txBuf, txLen); + } + if (rxLen > 0) { + readBuffer = ArrayReference(rxBuf, rxLen); + } + + try { + if (txLen > 0) { + if (rxLen > 0) { + i2cDevice->WriteRead(writeBuffer, readBuffer); + } else { + i2cDevice->Write(writeBuffer); + } + } else if (rxLen > 0) { + i2cDevice->Read(readBuffer); + } + } catch (...) { + AJ_ErrPrintf(("AJS_TargetIO_I2cTransfer(): i2C read/write failed\n")); + return AJ_ERR_FAILURE; + } + + if (rxLen > 0 && rxBytes != NULL) { + *rxBytes = readBuffer->Length; + } + + return AJ_OK; +} \ No newline at end of file diff --git a/pool/shard006/C/0120109_tst-tlsmod3.c b/pool/shard006/C/0120109_tst-tlsmod3.c new file mode 100644 index 0000000000000000000000000000000000000000..12505f623fa873a0683b3d4b657477ed01a55952 --- /dev/null +++ b/pool/shard006/C/0120109_tst-tlsmod3.c @@ -0,0 +1,41 @@ +#include + +#include + +#ifdef USE_TLS +# include "tls-macros.h" + +extern int in_dso (int n, int *caller_foop); + +COMMON_INT_DEF(comm_n); + + + + +int +in_dso2 (void) +{ + int *foop; + int result = 0; + static int n; + int *np; + + puts ("foo"); /* Make sure PLT is used before macros. */ + __asm__ ("" ::: "memory"); + + foop = TLS_GD (foo); + np = TLS_GD (comm_n); + + if (n != *np) + { + printf ("n = %d != comm_n = %d\n", n, *np); + result = 1; + } + + result |= in_dso (*foop = 42 + n++, foop); + + *foop = 16; + + return result; +} +#endif diff --git a/pool/shard006/C/0120111_test_find_field.c b/pool/shard006/C/0120111_test_find_field.c new file mode 100644 index 0000000000000000000000000000000000000000..ba48d71517cd0ac050c49db606d712c5d15a99a7 --- /dev/null +++ b/pool/shard006/C/0120111_test_find_field.c @@ -0,0 +1,167 @@ +/* ========================================================================= + * This file is part of NITRO + * ========================================================================= + * + * (C) Copyright 2004 - 2014, MDA Information Systems LLC + * + * NITRO 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 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, If not, + * see . + * + */ + +#include + +void lookForTREField(nitf_Extensions* ext, + const char* tag, + const char* pattern) +{ + nitf_ListIterator current, last; + + nitf_List* list = nitf_Extensions_getTREsByName(ext, tag); + if (list == NULL) return; + + current = nitf_List_begin(list); + last = nitf_List_end(list); + + while (nitf_ListIterator_notEqualTo(¤t, &last)) + { + nitf_Error error; + nitf_TRE* tre = nitf_ListIterator_get(¤t); + nitf_ListIterator currentInst; + nitf_ListIterator lastInst; + + nitf_List* found = nitf_TRE_find(tre, pattern, &error); + if (!found) return; + + + currentInst = nitf_List_begin(found); + lastInst = nitf_List_end(found); + + while (nitf_ListIterator_notEqualTo(¤tInst, &lastInst)) + { + nitf_Pair* pair = nitf_ListIterator_get(¤tInst); + nitf_Field* field = (nitf_Field*)pair->data; + printf("Found: %s [%.*s]\n", pair->key, (int)field->length, field->raw); + nitf_ListIterator_increment(¤tInst); + + } + nitf_ListIterator_increment(¤t); + } + + +} + +int main(int argc, char **argv) +{ + /* Get the error object */ + nitf_Error error; + + /* so I can remember what Im doing with args */ + const char* treName; + const char* fieldName; + + /* This is the reader object */ + nitf_Reader *reader; + nitf_Record *record; + + /* The IO handle */ + nitf_IOHandle io; + int num; + + /* Check argv and make sure we are happy */ + if (argc != 4) + { + printf("Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + if (nitf_Reader_getNITFVersion(argv[1]) == NITF_VER_UNKNOWN) + { + printf("File: %s is not a NITF\n", argv[1]); + exit(EXIT_FAILURE); + } + + treName = argv[2]; + fieldName = argv[3]; + + io = nitf_IOHandle_create(argv[1], NITF_ACCESS_READONLY, + NITF_OPEN_EXISTING, &error); + + if (NITF_INVALID_HANDLE(io)) + { + nitf_Error_print(&error, stdout, "Exiting..."); + exit(EXIT_FAILURE); + } + + reader = nitf_Reader_construct(&error); + if (!reader) + { + nitf_Error_print(&error, stdout, "Exiting (1) ..."); + exit(EXIT_FAILURE); + } + +#if NITF_VERBOSE_READER + printf("Here are the loaded handlers\n"); + printf("* * * * * * * * * * * * * * * *\n"); + nitf_HashTable_print(reader->reg->treHandlers); + printf("* * * * * * * * * * * * * * * *\n"); +#endif + record = nitf_Reader_read(reader, io, &error); + + + lookForTREField(record->header->extendedSection, treName, fieldName); + lookForTREField(record->header->userDefinedSection, treName, fieldName); + + + + if (!nitf_Field_get(record->header->numImages, + &num, NITF_CONV_INT, NITF_INT32_SZ, &error)) + goto CATCH_ERROR; + + /* And now show the image information */ + if (num > 0) + { + + /* Walk each image and show */ + nitf_ListIterator iter = nitf_List_begin(record->images); + nitf_ListIterator end = nitf_List_end(record->images); + + while (nitf_ListIterator_notEqualTo(&iter, &end)) + { + nitf_ImageSegment *segment = + (nitf_ImageSegment *) nitf_ListIterator_get(&iter); + + lookForTREField(segment->subheader->extendedSection, treName, fieldName); + lookForTREField(segment->subheader->userDefinedSection, treName, fieldName); + nitf_ListIterator_increment(&iter); + } + } + else + { + printf("No image in file!\n"); + } + + nitf_IOHandle_close(io); + nitf_Record_destruct(&record); + + nitf_Reader_destruct(&reader); + + return 0; + +CATCH_ERROR: + printf("!!! we had a problem reading the file !!!\n"); + nitf_Error_print(&error, stdout, "Exiting..."); + exit(EXIT_FAILURE); +} + diff --git a/pool/shard006/C/0120115_rename_c.c b/pool/shard006/C/0120115_rename_c.c new file mode 100644 index 0000000000000000000000000000000000000000..25fcea2f16cc5e3448ec59d599114ee4442a9b44 --- /dev/null +++ b/pool/shard006/C/0120115_rename_c.c @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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 "kadm5_locl.h" + +RCSID("$Id$"); + +kadm5_ret_t +kadm5_c_rename_principal(void *server_handle, + krb5_principal source, + krb5_principal target) +{ + kadm5_client_context *context = server_handle; + kadm5_ret_t ret; + krb5_storage *sp; + unsigned char buf[1024]; + int32_t tmp; + krb5_data reply; + + ret = _kadm5_connect(server_handle); + if(ret) + return ret; + + sp = krb5_storage_from_mem(buf, sizeof(buf)); + if (sp == NULL) + return ENOMEM; + krb5_store_int32(sp, kadm_rename); + krb5_store_principal(sp, source); + krb5_store_principal(sp, target); + ret = _kadm5_client_send(context, sp); + krb5_storage_free(sp); + if (ret) + return ret; + ret = _kadm5_client_recv(context, &reply); + if(ret) + return ret; + sp = krb5_storage_from_data (&reply); + if (sp == NULL) { + krb5_data_free (&reply); + return ENOMEM; + } + krb5_ret_int32(sp, &tmp); + ret = tmp; + krb5_storage_free(sp); + krb5_data_free (&reply); + return ret; +} diff --git a/pool/shard006/C/0120116_interface.c b/pool/shard006/C/0120116_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..c8dd31e154b9c9b17e819eff999c752ad5f20945 --- /dev/null +++ b/pool/shard006/C/0120116_interface.c @@ -0,0 +1,169 @@ +/* + interface.c -- parted binding glue to libext2resize + Copyright (C) 1998-2000, 2007-2011 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 . +*/ + +/* VERSION: libext2resize 1.1.6 (by Lennert) + * merged 1.1.11 changes (by Andrew) + */ + +#include + +#include +#include "ext2.h" + +static PedFileSystemType _ext2_type; +static PedFileSystemType _ext3_type; + +struct ext2_dev_handle* ext2_make_dev_handle_from_parted_geometry(PedGeometry* geom); + +static PedGeometry* +_ext2_generic_probe (PedGeometry* geom, int expect_ext_ver) +{ + void *sb_v; + if (!ped_geometry_read_alloc(geom, &sb_v, 2, 2)) + return NULL; + struct ext2_super_block *sb = sb_v; + + if (EXT2_SUPER_MAGIC(*sb) == EXT2_SUPER_MAGIC_CONST) { + PedSector block_size = 1 << (EXT2_SUPER_LOG_BLOCK_SIZE(*sb) + 1); + PedSector block_count = EXT2_SUPER_BLOCKS_COUNT(*sb); + PedSector group_blocks = EXT2_SUPER_BLOCKS_PER_GROUP(*sb); + PedSector group_nr = EXT2_SUPER_BLOCK_GROUP_NR(*sb); + PedSector first_data_block = EXT2_SUPER_FIRST_DATA_BLOCK(*sb); + int version = EXT2_SUPER_REV_LEVEL(*sb); + int is_ext3 = 0; + int is_ext4 = 0; + + is_ext3 = (EXT2_SUPER_FEATURE_COMPAT (*sb) + & EXT3_FEATURE_COMPAT_HAS_JOURNAL) != 0; + if (is_ext3) { + is_ext4 = ((EXT2_SUPER_FEATURE_RO_COMPAT (*sb) + & EXT4_FEATURE_RO_COMPAT_HUGE_FILE) + || (EXT2_SUPER_FEATURE_RO_COMPAT (*sb) + & EXT4_FEATURE_RO_COMPAT_GDT_CSUM) + || (EXT2_SUPER_FEATURE_RO_COMPAT (*sb) + & EXT4_FEATURE_RO_COMPAT_DIR_NLINK) + || (EXT2_SUPER_FEATURE_INCOMPAT (*sb) + & EXT4_FEATURE_INCOMPAT_EXTENTS) + || (EXT2_SUPER_FEATURE_INCOMPAT (*sb) + & EXT4_FEATURE_INCOMPAT_64BIT) + || (EXT2_SUPER_FEATURE_INCOMPAT (*sb) + & EXT4_FEATURE_INCOMPAT_FLEX_BG)); + if (is_ext4) + is_ext3 = 0; + } + free (sb); + + if (expect_ext_ver == 2 && (is_ext3 || is_ext4)) + return NULL; + if (expect_ext_ver == 3 && !is_ext3) + return NULL; + else if (expect_ext_ver == 4 && !is_ext4) + return NULL; + + if (version > 0 && group_nr > 0) { + PedSector start; + PedGeometry probe_geom; + + start = geom->start + - group_blocks * group_nr + - first_data_block; + + if (start < 0) + return NULL; + ped_geometry_init (&probe_geom, geom->dev, + start, block_count * block_size); + return _ext2_generic_probe (&probe_geom, + expect_ext_ver); + } else { + return ped_geometry_new (geom->dev, geom->start, + block_count * block_size); + } + } + else { + free (sb); + } + + return NULL; +} + +static PedGeometry* +_ext2_probe (PedGeometry* geom) +{ + return _ext2_generic_probe (geom, 2); +} + +static PedGeometry* +_ext3_probe (PedGeometry* geom) +{ + return _ext2_generic_probe (geom, 3); +} + +static PedGeometry* +_ext4_probe (PedGeometry* geom) +{ + return _ext2_generic_probe (geom, 4); +} + +static PedFileSystemOps _ext2_ops = { + probe: _ext2_probe, +}; + +static PedFileSystemOps _ext3_ops = { + probe: _ext3_probe, +}; + +static PedFileSystemOps _ext4_ops = { + probe: _ext4_probe, +}; + +#define EXT23_BLOCK_SIZES ((int[6]){512, 1024, 2048, 4096, 8192, 0}) + +static PedFileSystemType _ext2_type = { + next: NULL, + ops: &_ext2_ops, + name: "ext2", + block_sizes: EXT23_BLOCK_SIZES +}; + +static PedFileSystemType _ext3_type = { + next: NULL, + ops: &_ext3_ops, + name: "ext3", + block_sizes: EXT23_BLOCK_SIZES +}; + +static PedFileSystemType _ext4_type = { + next: NULL, + ops: &_ext4_ops, + name: "ext4", + block_sizes: EXT23_BLOCK_SIZES +}; + +void ped_file_system_ext2_init () +{ + ped_file_system_type_register (&_ext2_type); + ped_file_system_type_register (&_ext3_type); + ped_file_system_type_register (&_ext4_type); +} + +void ped_file_system_ext2_done () +{ + ped_file_system_type_unregister (&_ext2_type); + ped_file_system_type_unregister (&_ext3_type); + ped_file_system_type_unregister (&_ext4_type); +} diff --git a/pool/shard006/C/0120118_ftnseq.c b/pool/shard006/C/0120118_ftnseq.c new file mode 100644 index 0000000000000000000000000000000000000000..31a08456571ddc508b094abd27fc2c532311f351 --- /dev/null +++ b/pool/shard006/C/0120118_ftnseq.c @@ -0,0 +1,134 @@ +/*:ts=8*/ +/***************************************************************************** + * FIDOGATE --- Gateway UNIX Mail/News <-> FTN NetMail/EchoMail + * + * $Id: ftnseq.c,v 4.10 2004/08/22 20:19:14 n0ll Exp $ + * + * Command line interface to sequencer files + ***************************************************************************** + * Copyright (C) 1990-2004 + * _____ _____ + * | |___ | Martin Junius + * | | | | | | Radiumstr. 18 + * |_|_|_|@home| D-51069 Koeln, Germany + * + * This file is part of FIDOGATE. + * + * FIDOGATE 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. + * + * FIDOGATE 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 FIDOGATE; see the file COPYING. If not, write to the Free + * Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + *****************************************************************************/ + +#include "fidogate.h" +#include "getopt.h" + + +#define PROGRAM "ftnseq" +#define VERSION "$Revision: 4.10 $" +#define CONFIG DEFAULT_CONFIG_MAIN + + + +/* + * Prototypes + */ +void short_usage (void); +void usage (void); + + + +/* + * Usage messages + */ +void short_usage(void) +{ + fprintf(stderr, "usage: %s [-options] SEQ\n", PROGRAM); + fprintf(stderr, " %s --help for more information\n", PROGRAM); +} + + +void usage(void) +{ + fprintf(stderr, "FIDOGATE %s %s %s\n\n", + version_global(), PROGRAM, version_local(VERSION) ); + + fprintf(stderr, "usage: %s [-options] SEQ\n\n", PROGRAM); + fprintf(stderr, "\ +options: -v --verbose more verbose\n\ + -h --help this help\n\ + -c --config name read config file (\"\" = none)\n"); +} + + + +/***** main() ****************************************************************/ + +int main(int argc, char **argv) +{ + int c; + char *c_flag=NULL; + long n; + + int option_index; + static struct option long_options[] = + { + { "verbose", 0, 0, 'v'}, /* More verbose */ + { "help", 0, 0, 'h'}, /* Help */ + { "config", 1, 0, 'c'}, /* Config file */ + { 0, 0, 0, 0 } + }; + + log_program(PROGRAM); + + /* Init configuration */ + cf_initialize(); + + + while ((c = getopt_long(argc, argv, "vhc:", + long_options, &option_index )) != EOF) + switch (c) { + /***** Common options *****/ + case 'v': + verbose++; + break; + case 'h': + usage(); + exit(0); + break; + case 'c': + c_flag = optarg; + break; + default: + short_usage(); + exit(EX_USAGE); + break; + } + + cf_read_config_file(c_flag ? c_flag : CONFIG); + cf_debug(); + + /* + * Process command line file args + */ + if( (argc - optind) != 1 ) + { + short_usage(); + exit(EX_USAGE); + } + + n = sequencer_nx(argv[optind], FALSE); + + n == -1L ? printf("ERROR\n") : printf("%ld\n", n) ; + + exit(EX_OK); +} diff --git a/pool/shard006/C/0120119_medwidget.c b/pool/shard006/C/0120119_medwidget.c new file mode 100644 index 0000000000000000000000000000000000000000..051c5b2874a6a42b197aa72f46ca4b6f55cb6edd --- /dev/null +++ b/pool/shard006/C/0120119_medwidget.c @@ -0,0 +1,191 @@ +/* + * medwidget.c + * + * Copyright 2013-2021 AmatCoder + * + * This file is part of Mednaffe. + * + * Mednaffe 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. + * + * Mednaffe 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 Mednaffe; if not, see . + * + * + */ + + +#include "medwidget.h" + + +#define MED_WIDGET_GET_INTERFACE(obj) (G_TYPE_INSTANCE_GET_INTERFACE ((obj), med_widget_get_type (), MedWidgetInterface)) + + +G_DEFINE_INTERFACE (MedWidget, med_widget, G_TYPE_OBJECT); + + +const gchar* +med_widget_get_value (MedWidget* self) +{ + g_return_val_if_fail (self != NULL, NULL); + + return MED_WIDGET_GET_INTERFACE (self)->get_value (self); +} + + +void +med_widget_set_value (MedWidget* self, + const gchar* v) +{ + g_return_if_fail (self != NULL); + + MED_WIDGET_GET_INTERFACE (self)->set_value (self, v); +} + + +static void +med_widget_real_init (MedWidget* self, + GtkWidget* widget) +{ + g_return_if_fail (widget != NULL); + + med_widget_set_updated ((MedWidget*) widget, TRUE); + med_widget_set_modified ((MedWidget*) widget, FALSE); +} + + +static void +med_widget_realize (GtkWidget* widget, + gpointer data) +{ + g_return_if_fail (widget != NULL); + + GtkWidget *toplevel = gtk_widget_get_toplevel (widget); + if (toplevel) + { + GHashTable* table = g_object_get_data ((GObject*) toplevel, "table"); + + if (table) + { + gchar* value; + const gchar* command = med_widget_get_command ((MedWidget*) widget); + gchar* command2 = g_strconcat ("-", command, NULL); + + if (g_hash_table_contains (table, command2)) + value = g_hash_table_lookup (table, command2); + else + value = g_hash_table_lookup (table, command); + + g_free (command2); + + if (value) + { + med_widget_set_value ((MedWidget*) widget, value); + med_widget_set_updated ((MedWidget*) widget, FALSE); + } + else + gtk_widget_set_sensitive (widget, FALSE); + } + } +} + + +void +med_widget_init (MedWidget* self, + GtkWidget* widget) +{ + g_return_if_fail (self != NULL); + + MED_WIDGET_GET_INTERFACE (self)->init (self, widget); + g_signal_connect_object ((GtkWidget*) self, "realize", (GCallback) med_widget_realize, self, 0); +} + + +const gchar* +med_widget_get_command (MedWidget* self) +{ + g_return_val_if_fail (self != NULL, NULL); + + return MED_WIDGET_GET_INTERFACE (self)->get_command (self); +} + + +void +med_widget_set_command (MedWidget* self, + const gchar* value) +{ + g_return_if_fail (self != NULL); + + MED_WIDGET_GET_INTERFACE (self)->set_command (self, value); +} + + +gboolean +med_widget_get_updated (MedWidget* self) +{ + g_return_val_if_fail (self != NULL, FALSE); + + return MED_WIDGET_GET_INTERFACE (self)->get_updated (self); +} + + +void +med_widget_set_updated (MedWidget* self, + gboolean value) +{ + g_return_if_fail (self != NULL); + MED_WIDGET_GET_INTERFACE (self)->set_updated (self, value); +} + +gboolean +med_widget_get_modified (MedWidget* self) +{ + g_return_val_if_fail (self != NULL, FALSE); + return MED_WIDGET_GET_INTERFACE (self)->get_modified (self); +} + + +void +med_widget_set_modified (MedWidget* self, + gboolean value) +{ + g_return_if_fail (self != NULL); + + MED_WIDGET_GET_INTERFACE (self)->set_modified (self, value); + + if (med_widget_get_updated(self)) + return; + + GtkWidget *toplevel = gtk_widget_get_toplevel ((GtkWidget*) self); + if (toplevel) + { + GHashTable* table = g_object_get_data ((GObject*) toplevel, "table"); + + if (table) + { + gchar* key = g_strconcat("-", med_widget_get_command (self), NULL); + g_hash_table_insert (table, key, g_strdup(med_widget_get_value (self))); + } + } +} + + +static void +med_widget_default_init (MedWidgetInterface* iface) +{ + g_object_interface_install_property (iface, + g_param_spec_string ("command", + "command", + "command", + NULL, + G_PARAM_STATIC_STRINGS | G_PARAM_READABLE | G_PARAM_WRITABLE)); + + iface->init = med_widget_real_init; +} diff --git a/pool/shard006/C/0120124_topology.c b/pool/shard006/C/0120124_topology.c new file mode 100644 index 0000000000000000000000000000000000000000..fdf4044d2e74a90a24ff7b5e44a16efcab52c7a4 --- /dev/null +++ b/pool/shard006/C/0120124_topology.c @@ -0,0 +1,175 @@ +/* + * driver/base/topology.c - Populate sysfs with cpu topology information + * + * Written by: Zhang Yanmin, Intel Corporation + * + * Copyright (C) 2006, Intel Corp. + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or + * NON INFRINGEMENT. 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + */ +#include +#include +#include +#include +#include +#include + +#define define_one_ro(_name) \ +static SYSDEV_ATTR(_name, 0444, show_##_name, NULL) + +#define define_id_show_func(name) \ +static ssize_t show_##name(struct sys_device *dev, char *buf) \ +{ \ + unsigned int cpu = dev->id; \ + return sprintf(buf, "%d\n", topology_##name(cpu)); \ +} + +static ssize_t show_cpumap(int type, cpumask_t *mask, char *buf) +{ + ptrdiff_t len = PTR_ALIGN(buf + PAGE_SIZE - 1, PAGE_SIZE) - buf; + int n = 0; + + if (len > 1) { + n = type? + cpulist_scnprintf(buf, len-2, *mask): + cpumask_scnprintf(buf, len-2, *mask); + buf[n++] = '\n'; + buf[n] = '\0'; + } + return n; +} + +#define define_siblings_show_map(name) \ +static inline ssize_t show_##name(struct sys_device *dev, char *buf) \ +{ \ + unsigned int cpu = dev->id; \ + return show_cpumap(0, &(topology_##name(cpu)), buf); \ +} + +#define define_siblings_show_list(name) \ +static inline ssize_t show_##name##_list(struct sys_device *dev, char *buf) \ +{ \ + unsigned int cpu = dev->id; \ + return show_cpumap(1, &(topology_##name(cpu)), buf); \ +} + +#define define_siblings_show_func(name) \ + define_siblings_show_map(name); define_siblings_show_list(name) + +#ifdef topology_physical_package_id +define_id_show_func(physical_package_id); +define_one_ro(physical_package_id); +#define ref_physical_package_id_attr &attr_physical_package_id.attr, +#else +#define ref_physical_package_id_attr +#endif + +#ifdef topology_core_id +define_id_show_func(core_id); +define_one_ro(core_id); +#define ref_core_id_attr &attr_core_id.attr, +#else +#define ref_core_id_attr +#endif + +#ifdef topology_thread_siblings +define_siblings_show_func(thread_siblings); +define_one_ro(thread_siblings); +define_one_ro(thread_siblings_list); +#define ref_thread_siblings_attr \ + &attr_thread_siblings.attr, &attr_thread_siblings_list.attr, +#else +#define ref_thread_siblings_attr +#endif + +#ifdef topology_core_siblings +define_siblings_show_func(core_siblings); +define_one_ro(core_siblings); +define_one_ro(core_siblings_list); +#define ref_core_siblings_attr \ + &attr_core_siblings.attr, &attr_core_siblings_list.attr, +#else +#define ref_core_siblings_attr +#endif + +static struct attribute *default_attrs[] = { + ref_physical_package_id_attr + ref_core_id_attr + ref_thread_siblings_attr + ref_core_siblings_attr + NULL +}; + +static struct attribute_group topology_attr_group = { + .attrs = default_attrs, + .name = "topology" +}; + +/* Add/Remove cpu_topology interface for CPU device */ +static int __cpuinit topology_add_dev(unsigned int cpu) +{ + struct sys_device *sys_dev = get_cpu_sysdev(cpu); + + return sysfs_create_group(&sys_dev->kobj, &topology_attr_group); +} + +static void __cpuinit topology_remove_dev(unsigned int cpu) +{ + struct sys_device *sys_dev = get_cpu_sysdev(cpu); + + sysfs_remove_group(&sys_dev->kobj, &topology_attr_group); +} + +static int __cpuinit topology_cpu_callback(struct notifier_block *nfb, + unsigned long action, void *hcpu) +{ + unsigned int cpu = (unsigned long)hcpu; + int rc = 0; + + switch (action) { + case CPU_UP_PREPARE: + case CPU_UP_PREPARE_FROZEN: + rc = topology_add_dev(cpu); + break; + case CPU_UP_CANCELED: + case CPU_UP_CANCELED_FROZEN: + case CPU_DEAD: + case CPU_DEAD_FROZEN: + topology_remove_dev(cpu); + break; + } + return rc ? NOTIFY_BAD : NOTIFY_OK; +} + +static int __cpuinit topology_sysfs_init(void) +{ + int cpu; + int rc; + + for_each_online_cpu(cpu) { + rc = topology_add_dev(cpu); + if (rc) + return rc; + } + hotcpu_notifier(topology_cpu_callback, 0); + + return 0; +} + +device_initcall(topology_sysfs_init); diff --git a/pool/shard006/C/0120127_html.c b/pool/shard006/C/0120127_html.c new file mode 100644 index 0000000000000000000000000000000000000000..c0c5fd090fc2fbff126d6e40e743cf2284e6ee4c --- /dev/null +++ b/pool/shard006/C/0120127_html.c @@ -0,0 +1,175 @@ +/** + * @file html.c HTML favicon and feed link auto discovery + * + * Copyright (C) 2004 ahmed el-helw + * Copyright (C) 2004-2009 Lars Windolf + * + * 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 +#include +#include + +#include "common.h" +#include "debug.h" +#include "html.h" +#include "xml.h" + +enum { + LINK_FAVICON, + LINK_RSS_ALTERNATE, +}; + +static gchar * +checkLinkRef (const gchar* str, gint linkType) +{ + gchar *res; + const gchar *tmp, *tmp2; + size_t len = 0; + gchar quote; + + /*debug1(DEBUG_PARSING, "checking link %s", str); */ + tmp = common_strcasestr (str, "href="); + if (!tmp) + return NULL; + tmp += 5; + + /* skip spaces up to the first quote. This is really slightly + wrong. SGML allows unquoted atributes, but not if they contain + slashes, so 99% of all URIs will require quotes. */ + while (*tmp != '\"' && *tmp != '\'') { + if (*tmp == '>' || *tmp == '\0' || !isspace(*tmp)) + return NULL; + tmp++; + } + quote = *tmp; /* The type of quote mark used to delimit the arg */ + tmp++; + tmp2 = tmp; + while ((*tmp2 != quote && *(tmp2-1) != '\\') && /* Escaped quote*/ + *tmp2 != '\0') + tmp2++, len++; + + res = g_strndup (tmp, len); + + if (linkType == LINK_FAVICON) { + /* The type attribute is optional, so don't check for it, + * as according to the W3C, it must be must be png, gif or + * ico anyway: http://www.w3.org/2005/10/howto-favicon + * Instead, do stronger checks for the rel attribute. */ + if (((NULL != common_strcasestr (str, "rel=\"shortcut icon\"")) || + (NULL != common_strcasestr (str, "rel=\"icon\"")) || + (NULL != common_strcasestr (str, "rel=\'shortcut icon\'")) || + (NULL != common_strcasestr (str, "rel=\'icon\'"))) /*&& + ((NULL != common_strcasestr (str, "image/x-icon")) || + (NULL != common_strcasestr (str, "image/png")) || + (NULL != common_strcasestr (str, "image/gif")))*/) + return res; + } else if (linkType == LINK_RSS_ALTERNATE) { + if ((common_strcasestr (str, "alternate") != NULL) && + ((common_strcasestr (str, "text/xml") != NULL) || + (common_strcasestr (str, "rss+xml") != NULL) || + (common_strcasestr (str, "rdf+xml") != NULL) || + (common_strcasestr (str, "atom+xml") != NULL))) + return res; + } + g_free (res); + return NULL; +} + +static gchar * +search_links (const gchar* data, gint linkType) +{ + gchar *ptr; + const gchar *tmp = data; + gchar *result = NULL; + gchar *res; + gchar *tstr; + gchar *endptr; + + while (1) { + ptr = common_strcasestr (tmp, "'); + if (!endptr) + return NULL; + *endptr = '\0'; + tstr = g_strdup (ptr); + *endptr = '>'; + res = checkLinkRef (tstr, linkType); + g_free (tstr); + if (res) { + result = res; + break; +/* deactivated as long as we support only subscribing + to the first found link (BTW this code crashes on + sites like Groklaw!) + + gchar* t; + if(result == NULL) + result = res; + else { + t = g_strdup_printf("%s\n%s", result, res); + g_free(res); + g_free(result); + result = t; + }*/ + } + tmp = endptr; + } + + result = unhtmlize (result); /* URIs can contain escaped things.... All ampersands must be escaped, for example */ + return result; +} + +gchar * +html_auto_discover_feed (const gchar* data, const gchar *baseUri) +{ + gchar *res, *tmp; + + debug0 (DEBUG_UPDATE, "searching through link tags"); + res = search_links (data, LINK_RSS_ALTERNATE); + debug1 (DEBUG_UPDATE, "search result: %s", res?res:"none found"); + + if (res) { + /* turn relative URIs into absolute URIs */ + tmp = res; + res = common_build_url (res, baseUri); + g_free (tmp); + } + + return res; +} + +gchar * +html_discover_favicon (const gchar * data, const gchar * baseUri) +{ + gchar *res, *tmp; + + debug0 (DEBUG_UPDATE, "searching through link tags"); + res = search_links (data, LINK_FAVICON); + debug1 (DEBUG_UPDATE, "search result: %s", res? res : "none found"); + + if (res) { + /* turn relative URIs into absolute URIs */ + tmp = res; + res = common_build_url (res, baseUri); + g_free (tmp); + } + + return res; +} diff --git a/pool/shard006/C/0120128_closed_loop.c b/pool/shard006/C/0120128_closed_loop.c new file mode 100644 index 0000000000000000000000000000000000000000..5a86bb9060ec5971586824206951c1e1f2390e46 --- /dev/null +++ b/pool/shard006/C/0120128_closed_loop.c @@ -0,0 +1,66 @@ +/*************************************************************************** + * Copyright (C) 2004 by Ralf Kaestner * + * ralf.kaestner@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * 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 +#include + +#include "era.h" +#include "control/closed_loop.h" + +thread_t control_thread; + +int quit = 0; + +void era_signaled(int signal) { + era_control_closed_loop_exit(&control_thread); +} + +int main(int argc, char **argv) { + int result; + thread_mutex_t mutex; + era_arm_t arm; + era_trajectory_t trajectory; + + if (era_init_arg(&arm, argc, argv, 0, "FILE FREQUENCY")) + return -1; + const char* file = argv[1]; + float freq = atof(argv[2]); + + thread_mutex_init(&mutex); + if ((result = era_trajectory_read(file, &trajectory)) < 0) { + fprintf(stderr, "%s\n", era_trajectory_errors[-result]); + return -1; + } + + signal(SIGINT, era_signaled); + + if (era_open(&arm)) + return -1; + if (!(result = era_control_closed_loop_start(&control_thread, &arm, + &mutex, &trajectory, freq))) + thread_wait_exit(&control_thread); + else + fprintf(stderr, "%s\n", era_control_closed_loop_errors[result]); + era_close(&arm); + + era_destroy(&arm); + thread_mutex_destroy(&mutex); + return 0; +} diff --git a/pool/shard006/C/0120130_new_server.c b/pool/shard006/C/0120130_new_server.c new file mode 100644 index 0000000000000000000000000000000000000000..4e7b4c4ec0978b042d13a6a87fb630bca0bc373c --- /dev/null +++ b/pool/shard006/C/0120130_new_server.c @@ -0,0 +1,277 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BUFSIZE 1024 + +typedef struct mymsg{ + int size; + char name[BUFSIZE]; +}msg; +typedef struct ap{ + long off; + char name[BUFSIZE]; +}app; + +void err_quit(char *msg) { + fputs(msg, stderr); + fputc('\n', stderr); + exit(1); +} + +void addClient(int s, struct sockaddr_in *newcliaddr){ + char buf[20]; + + inet_ntop(AF_INET, &newcliaddr->sin_addr, buf, sizeof(buf)); + printf("new client: %s\n", buf); +} + +int recvn(int s, char *buf, int len) { + int received, left = len; + char *ptr = buf; + + while(left > 0) { + received = read(s, buf, left); + if(received == -1) + return -1; + else if(received == 0) + break; + left -= received; + ptr += received; + } + + return (len - left); +} + +void* WorkerThread(void *Arg){ + int retval, client_sock = (int)Arg; + off_t endoff; + msg* list; + list = (msg*) malloc(sizeof(msg)); + app* append; + append = (app*)malloc(sizeof(app)); + struct stat file_info; + struct sockaddr_in serveraddr; + DIR * dirp; + struct dirent * direntp; + int addrlen; + + char buf[BUFSIZE]; + char menu[2]; + int fd; + + while(1) + + { + retval = recvn(client_sock,menu,2); + if(!strcmp(menu,"2")) + + { + char filename[256]; + char ssend[BUFSIZE]; + retval = recvn(client_sock, ssend, sizeof(app)); + + memcpy(append, ssend, sizeof(app)); + + if(retval == -1) + err_quit("write() error 1"); + printf("recived name : %s\n", append->name); + fd = open(append->name,O_RDONLY); + if(fd < 0) + err_quit("fopen() error"); + + + int totalbytes=lseek(fd,0,SEEK_END); + + retval = write(client_sock, (char *)&totalbytes, sizeof(totalbytes)); + + + char buf[BUFSIZE]={0}; + + int numread = 0, sum = 0, numtotal=0; + lseek(fd, 0, SEEK_SET); + char writebuf[BUFSIZE]; + + while(1) { + + numread = read(fd,writebuf,BUFSIZE); + if(numtotal == totalbytes){ + printf("파일 전송 완료 : %d bytes\n", numtotal); + break; + } + + else if(numread > 0) { + retval = write(client_sock,writebuf,numread); + if(retval == -1) + err_quit("write() error!"); + numtotal += retval; + } + + else { + err_quit("file I/O error"); + } + + } + close(fd); + + + } + else if(!strcmp(menu,"3")) + { + + char filename[256]; + char ssend[BUFSIZE]; + + retval = recvn(client_sock, ssend, sizeof(app)); + memcpy(append, ssend, sizeof(app)); + + if(retval == -1) + err_quit("write() error"); + fd = open(append->name, O_RDWR|O_APPEND); + + if(fd < 0) + err_quit("fopen() error"); + + int totalbytes=lseek(fd, 0, SEEK_END); + retval = write(client_sock, (char *)&totalbytes, sizeof(totalbytes)); + + if(retval == -1) + err_quit("write() error"); + + + char buf[BUFSIZE]; + int numread=0; + + int numtotal = 0; + if(totalbytes == append->off){ + printf("이미 다 받으셨습니다.\n"); + buf[0] = -100; + write(client_sock, buf, sizeof(buf)); + } + + lseek(fd, 0, SEEK_SET); + lseek(fd, append->off-1, SEEK_SET); + int sum=0; + while(1) { + char writebuf[BUFSIZE]={0}; + sum=append->off-1 + numtotal; + numread = read(fd,writebuf, BUFSIZE); + if(sum== totalbytes) { + + printf("파일 전송 완료 : %d bytes\n", numtotal); + break; + } + + else if(numread > 0) { + retval = write(client_sock,writebuf,numread); + numtotal += numread; + } + + else { + err_quit("file I/O error"); + } + + } + close(fd); + + + } + else if(!strcmp(menu,"1")) + { + + int ptr; + + dirp = opendir("./"); + while ((direntp = (struct dirent*)readdir(dirp)) != NULL){ + stat(direntp->d_name, &file_info); + + printf("\n"); + list->size = file_info.st_size; + memcpy(list->name, direntp->d_name, sizeof(direntp->d_name)); + + memcpy(buf, list, sizeof(msg)); + write(client_sock, buf, sizeof(msg)); + } + if(direntp == NULL){ + list->size = -1; + memcpy(buf, list, sizeof(msg)); + write(client_sock, &buf, sizeof(msg)); + } + + } + else if(!strcmp(menu,"4")) + { + + printf("연결안됨\n"); + close(client_sock); + break; + + } + } + +} + +int main(int argc, char *argv[]) +{ + int retval; + int maxfdp1 = 101; + off_t endoff; + msg* list; + list = (msg*) malloc(sizeof(msg)); + app* append; + append = (app*)malloc(sizeof(app)); + int listen_sock = socket(PF_INET, SOCK_STREAM, 0); + + struct stat file_info; + struct sockaddr_in serveraddr; + DIR * dirp; + struct dirent * direntp; + fd_set read_fds; + + memset(&serveraddr, 0, sizeof(serveraddr)); + serveraddr.sin_family = AF_INET; + serveraddr.sin_port = htons(9000); + serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); + retval = bind(listen_sock, (struct sockaddr*) &serveraddr, sizeof(serveraddr)); + retval = listen(listen_sock, 5); + + int client_sock; + struct sockaddr_in clientaddr; + int addrlen; + char buf[BUFSIZE]; + char menu[2]; + while(1) { + pthread_t tid; + tid = pthread_self(); + FD_ZERO(&read_fds); + FD_SET(listen_sock, &read_fds); + if(select(maxfdp1, &read_fds, NULL, NULL, NULL)<0){ + perror("error : "); + } + if(FD_ISSET(listen_sock, &read_fds)){ + addrlen = sizeof(clientaddr); + client_sock = accept(listen_sock, (struct sockaddr*) &clientaddr, &addrlen); + if(client_sock == -1) + err_quit("accept() error"); + + printf("\n->FileSender connect : IP = %s, Port = %d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); + addClient(client_sock, &clientaddr); + } + pthread_create(&tid, NULL, WorkerThread, client_sock); + pthread_detach(tid); + } + close(listen_sock); + + return 0; + +} + diff --git a/pool/shard006/C/0120132_avr_lua.c b/pool/shard006/C/0120132_avr_lua.c new file mode 100644 index 0000000000000000000000000000000000000000..7aa46c00b56d7b347e7f5a4a42ce264ab16880cc --- /dev/null +++ b/pool/shard006/C/0120132_avr_lua.c @@ -0,0 +1,171 @@ +/* + * This file is part of MCUSim, an XSPICE library with microcontrollers. + * + * Copyright (C) 2017-2019 MCUSim Developers, see AUTHORS.txt for contributors. + * + * MCUSim 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. + * + * MCUSim 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 . + */ + +/* Device models defined as Lua scripts can be used during a scheme + * simulation in order to substitute important parts (external RAM, + * displays, etc.) connected to the simulated microcontroller. + * + * This file provides basic functions to load, run and unload these models. + */ +#include + +#include "mcusim/mcusim.h" +#include "mcusim/log.h" +#include "mcusim/avr/sim/private/macro.h" +#include "mcusim/avr/sim/luaapi.h" +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" + +static lua_State *lua_states[MSIM_AVR_LUAMODELS]; +static uint64_t models_num; + +int +MSIM_AVR_LUALoadModel(struct MSIM_AVR *mcu, char *model) +{ + uint8_t err = 0; + uint64_t i = models_num; + + /* Initialize Lua */ + lua_states[i] = luaL_newstate(); + /* Load various Lua libraries */ + luaL_openlibs(lua_states[i]); + + /* Load peripheral */ + if (luaL_loadfile(lua_states[i], model) || + lua_pcall(lua_states[i], 0, 0, 0)) { + snprintf(LOG, LOGSZ, "cannot load model: %s, reason: %s", + model, lua_tostring(lua_states[i], -1)); + MSIM_LOG_ERROR(LOG); + err = 1; + } else { + models_num++; + /* Register MCUSim API functions */ + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRIOBit); + lua_setglobal(lua_states[i], "AVR_IOBit"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRReadIO); + lua_setglobal(lua_states[i], "AVR_ReadIO"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRReadIO16); + lua_setglobal(lua_states[i], "AVR_ReadIO16"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRReadReg); + lua_setglobal(lua_states[i], "AVR_ReadReg"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRRegBit); + lua_setglobal(lua_states[i], "AVR_RegBit"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRSetIOBit); + lua_setglobal(lua_states[i], "AVR_SetIOBit"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRSetRegBit); + lua_setglobal(lua_states[i], "AVR_SetRegBit"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRWriteIO); + lua_setglobal(lua_states[i], "AVR_WriteIO"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRWriteIO16); + lua_setglobal(lua_states[i], "AVR_WriteIO16"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_AVRWriteReg); + lua_setglobal(lua_states[i], "AVR_WriteReg"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_SetState); + lua_setglobal(lua_states[i], "MSIM_SetState"); + lua_pushcfunction(lua_states[i], MSIM_LUAF_Freq); + lua_setglobal(lua_states[i], "MSIM_Freq"); + /* Override existing Lua functions */ + lua_pushcfunction(lua_states[i], MSIM_LUAF_Print); + lua_setglobal(lua_states[i], "print"); + + /* Add registers available for the current MCU model to + * the Lua state. */ + for (uint32_t j = 0; j < MSIM_AVR_DMSZ; j++) { + if (mcu->ioregs[j].off < 0) { + continue; + } + if (mcu->ioregs[j].name[0] == 0) { + continue; + } + + lua_pushinteger(lua_states[i], + (int)mcu->ioregs[j].off); + lua_setglobal(lua_states[i], mcu->ioregs[j].name); + } + + /* Add available MCU states to the Lua state. */ + lua_pushinteger(lua_states[i], AVR_RUNNING); + lua_setglobal(lua_states[i], "AVR_RUNNING"); + lua_pushinteger(lua_states[i], AVR_STOPPED); + lua_setglobal(lua_states[i], "AVR_STOPPED"); + lua_pushinteger(lua_states[i], AVR_SLEEPING); + lua_setglobal(lua_states[i], "AVR_SLEEPING"); + lua_pushinteger(lua_states[i], AVR_MSIM_STEP); + lua_setglobal(lua_states[i], "AVR_MSIM_STEP"); + lua_pushinteger(lua_states[i], AVR_MSIM_STOP); + lua_setglobal(lua_states[i], "AVR_MSIM_STOP"); + lua_pushinteger(lua_states[i], AVR_MSIM_TESTFAIL); + lua_setglobal(lua_states[i], "AVR_MSIM_TESTFAIL"); + + /* Attempt to call configuration function of the + * current model */ + lua_getglobal(lua_states[i], "module_conf"); + lua_pushlightuserdata(lua_states[i], mcu); + if (lua_pcall(lua_states[i], 1, 0, 0) != 0) { +#ifdef DEBUG + snprintf(LOG, LOGSZ, "model %s does not provide a " + "configuration function: %s", model, + lua_tostring(lua_states[i], -1)); + MSIM_LOG_DEBUG(LOG); +#endif + } + /* Find a "module_tick" function and push it onto a stack. + * This is a cache mechanism of the function value. */ + lua_getglobal(lua_states[i], "module_tick"); + } + return err; +} + +void +MSIM_AVR_LUACleanModels(void) +{ + for (uint64_t i = 0; i < models_num; i++) { + if (lua_states[i] != NULL) { + lua_close(lua_states[i]); + } + } + models_num = 0; +} + +void +MSIM_AVR_LUATickModels(struct MSIM_AVR *mcu) +{ + for (uint32_t i = 0; i < models_num; i++) { + if (lua_states[i] == NULL) { + break; + } + /* Push a cached value of the "module_tick" function onto + * the stack. */ + lua_pushvalue(lua_states[i], -1); + /* Push argument to call the "module_tick" function. */ + lua_pushlightuserdata(lua_states[i], mcu); +#ifndef DEBUG + /* Call the "module_tick" function. */ + lua_call(lua_states[i], 1, 0); +#else + /* Call the "module_tick" function (protected call). */ + if (lua_pcall(lua_states[i], 1, 0, 0) != 0) { + snprintf(LOG, LOGSZ, "cannot run module_tick(): %s", + lua_tostring(lua_states[i], -1)); + MSIM_LOG_DEBUG(LOG); + } +#endif + } +} diff --git a/pool/shard006/C/0120137_guillemot.c b/pool/shard006/C/0120137_guillemot.c new file mode 100644 index 0000000000000000000000000000000000000000..6a70ec429f063eb28d6f6f251037b695cb794841 --- /dev/null +++ b/pool/shard006/C/0120137_guillemot.c @@ -0,0 +1,289 @@ +/* + * $Id: guillemot.c,v 1.10 2002/01/22 20:28:12 vojtech Exp $ + * + * Copyright (c) 2001 Vojtech Pavlik + */ + +/* + * Guillemot Digital Interface Protocol driver for Linux + */ + +/* + * 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 + * + * Should you need to contact me, the author, you can do so either by + * e-mail - mail your message to , or by paper mail: + * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic + */ + +#include +#include +#include +#include +#include +#include +#include + +#define DRIVER_DESC "Guillemot Digital joystick driver" + +MODULE_AUTHOR("Vojtech Pavlik "); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL"); + +#define GUILLEMOT_MAX_START 600 /* 600 us */ +#define GUILLEMOT_MAX_STROBE 60 /* 60 us */ +#define GUILLEMOT_MAX_LENGTH 17 /* 17 bytes */ + +static short guillemot_abs_pad[] = + { ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, -1 }; + +static short guillemot_btn_pad[] = + { BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_MODE, BTN_SELECT, -1 }; + +static struct { + int x; + int y; +} guillemot_hat_to_axis[16] = {{ 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}}; + +struct guillemot_type { + unsigned char id; + short *abs; + short *btn; + int hat; + char *name; +}; + +struct guillemot { + struct gameport *gameport; + struct input_dev dev; + int bads; + int reads; + struct guillemot_type *type; + unsigned char length; + char phys[32]; +}; + +static struct guillemot_type guillemot_type[] = { + { 0x00, guillemot_abs_pad, guillemot_btn_pad, 1, "Guillemot Pad" }, + { 0 }}; + +/* + * guillemot_read_packet() reads Guillemot joystick data. + */ + +static int guillemot_read_packet(struct gameport *gameport, u8 *data) +{ + unsigned long flags; + unsigned char u, v; + unsigned int t, s; + int i; + + for (i = 0; i < GUILLEMOT_MAX_LENGTH; i++) + data[i] = 0; + + i = 0; + t = gameport_time(gameport, GUILLEMOT_MAX_START); + s = gameport_time(gameport, GUILLEMOT_MAX_STROBE); + + local_irq_save(flags); + gameport_trigger(gameport); + v = gameport_read(gameport); + + while (t > 0 && i < GUILLEMOT_MAX_LENGTH * 8) { + t--; + u = v; v = gameport_read(gameport); + if (v & ~u & 0x10) { + data[i >> 3] |= ((v >> 5) & 1) << (i & 7); + i++; + t = s; + } + } + + local_irq_restore(flags); + + return i; +} + +/* + * guillemot_poll() reads and analyzes Guillemot joystick data. + */ + +static void guillemot_poll(struct gameport *gameport) +{ + struct guillemot *guillemot = gameport_get_drvdata(gameport); + struct input_dev *dev = &guillemot->dev; + u8 data[GUILLEMOT_MAX_LENGTH]; + int i; + + guillemot->reads++; + + if (guillemot_read_packet(guillemot->gameport, data) != GUILLEMOT_MAX_LENGTH * 8 || + data[0] != 0x55 || data[16] != 0xaa) { + guillemot->bads++; + } else { + + for (i = 0; i < 6 && guillemot->type->abs[i] >= 0; i++) + input_report_abs(dev, guillemot->type->abs[i], data[i + 5]); + + if (guillemot->type->hat) { + input_report_abs(dev, ABS_HAT0X, guillemot_hat_to_axis[data[4] >> 4].x); + input_report_abs(dev, ABS_HAT0Y, guillemot_hat_to_axis[data[4] >> 4].y); + } + + for (i = 0; i < 16 && guillemot->type->btn[i] >= 0; i++) + input_report_key(dev, guillemot->type->btn[i], (data[2 + (i >> 3)] >> (i & 7)) & 1); + } + + input_sync(dev); +} + +/* + * guillemot_open() is a callback from the input open routine. + */ + +static int guillemot_open(struct input_dev *dev) +{ + struct guillemot *guillemot = dev->private; + + gameport_start_polling(guillemot->gameport); + return 0; +} + +/* + * guillemot_close() is a callback from the input close routine. + */ + +static void guillemot_close(struct input_dev *dev) +{ + struct guillemot *guillemot = dev->private; + + gameport_stop_polling(guillemot->gameport); +} + +/* + * guillemot_connect() probes for Guillemot joysticks. + */ + +static int guillemot_connect(struct gameport *gameport, struct gameport_driver *drv) +{ + struct guillemot *guillemot; + u8 data[GUILLEMOT_MAX_LENGTH]; + int i, t; + int err; + + if (!(guillemot = kzalloc(sizeof(struct guillemot), GFP_KERNEL))) + return -ENOMEM; + + guillemot->gameport = gameport; + + gameport_set_drvdata(gameport, guillemot); + + err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW); + if (err) + goto fail1; + + i = guillemot_read_packet(gameport, data); + + if (i != GUILLEMOT_MAX_LENGTH * 8 || data[0] != 0x55 || data[16] != 0xaa) { + err = -ENODEV; + goto fail2; + } + + for (i = 0; guillemot_type[i].name; i++) + if (guillemot_type[i].id == data[11]) + break; + + if (!guillemot_type[i].name) { + printk(KERN_WARNING "guillemot.c: Unknown joystick on %s. [ %02x%02x:%04x, ver %d.%02d ]\n", + gameport->phys, data[12], data[13], data[11], data[14], data[15]); + err = -ENODEV; + goto fail2; + } + + gameport_set_poll_handler(gameport, guillemot_poll); + gameport_set_poll_interval(gameport, 20); + + sprintf(guillemot->phys, "%s/input0", gameport->phys); + + guillemot->type = guillemot_type + i; + + guillemot->dev.private = guillemot; + guillemot->dev.open = guillemot_open; + guillemot->dev.close = guillemot_close; + + guillemot->dev.name = guillemot_type[i].name; + guillemot->dev.phys = guillemot->phys; + guillemot->dev.id.bustype = BUS_GAMEPORT; + guillemot->dev.id.vendor = GAMEPORT_ID_VENDOR_GUILLEMOT; + guillemot->dev.id.product = guillemot_type[i].id; + guillemot->dev.id.version = (int)data[14] << 8 | data[15]; + + guillemot->dev.evbit[0] = BIT(EV_KEY) | BIT(EV_ABS); + + for (i = 0; (t = guillemot->type->abs[i]) >= 0; i++) + input_set_abs_params(&guillemot->dev, t, 0, 255, 0, 0); + + if (guillemot->type->hat) { + input_set_abs_params(&guillemot->dev, ABS_HAT0X, -1, 1, 0, 0); + input_set_abs_params(&guillemot->dev, ABS_HAT0Y, -1, 1, 0, 0); + } + + for (i = 0; (t = guillemot->type->btn[i]) >= 0; i++) + set_bit(t, guillemot->dev.keybit); + + input_register_device(&guillemot->dev); + printk(KERN_INFO "input: %s ver %d.%02d on %s\n", + guillemot->type->name, data[14], data[15], gameport->phys); + + return 0; + +fail2: gameport_close(gameport); +fail1: gameport_set_drvdata(gameport, NULL); + kfree(guillemot); + return err; +} + +static void guillemot_disconnect(struct gameport *gameport) +{ + struct guillemot *guillemot = gameport_get_drvdata(gameport); + + printk(KERN_INFO "guillemot.c: Failed %d reads out of %d on %s\n", guillemot->reads, guillemot->bads, guillemot->phys); + input_unregister_device(&guillemot->dev); + gameport_close(gameport); + kfree(guillemot); +} + +static struct gameport_driver guillemot_drv = { + .driver = { + .name = "guillemot", + }, + .description = DRIVER_DESC, + .connect = guillemot_connect, + .disconnect = guillemot_disconnect, +}; + +static int __init guillemot_init(void) +{ + gameport_register_driver(&guillemot_drv); + return 0; +} + +static void __exit guillemot_exit(void) +{ + gameport_unregister_driver(&guillemot_drv); +} + +module_init(guillemot_init); +module_exit(guillemot_exit); diff --git a/pool/shard006/C/0120138_ne_genv.c b/pool/shard006/C/0120138_ne_genv.c new file mode 100644 index 0000000000000000000000000000000000000000..472074ab5b00b284ed03fea94ad7605b59570574 --- /dev/null +++ b/pool/shard006/C/0120138_ne_genv.c @@ -0,0 +1,139 @@ +/* + * Copyright (c) 1998 Sandia Corporation. Under the terms of Contract + * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement + * retains certain rights in this software. + * + * 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 Sandia 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. + * + */ +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ +/* Function(s) contained in this file: + * + * ne_get_n_elem_var() + * + ***************************************************************************** + * + * Variable Index: + * + * neid - The NetCDF ID of an already open NemesisI file. + * time_step - The time step to write this data to. + * elem_var_index - The index of this elemental variable. + * elem_blk_id - The ID of the element block being written to. + * num_elem_this_blk - The number of elements in this block. + * start_elem_num - The start point for outputting data. + * num_elem - The number of values to be output. + * elem_var_vals - Pointer to the vector of values to be output. + */ +/*****************************************************************************/ +/*****************************************************************************/ +/*****************************************************************************/ + +#include "exodusII.h" +#include "exodusII_int.h" + +#include "ne_nemesisI.h" +#include "ne_nemesisI_int.h" + +/* + * reads the values of a single element variable for one element block at + * one time step in the database; assume the first time step and + * element variable index is 1 + */ + +int ne_get_n_elem_var (int neid, + int time_step, + int elem_var_index, + int elem_blk_id, + int num_elem_this_blk, + int start_elem_num, + int num_elem, + void *elem_var_vals) +{ + int varid, elem_blk_id_ndx, status; + size_t start[2], count[2]; + char errmsg[MAX_ERR_LENGTH]; + + exerrval = 0; /* clear error code */ + + /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */ + if ((elem_blk_id_ndx = ex_id_lkup(neid,EX_ELEM_BLOCK,elem_blk_id)) < 0) { + if (exerrval == EX_NULLENTITY) { + sprintf(errmsg, + "Warning: no element variables for NULL block %d in file id %d", + elem_blk_id,neid); + ex_err("ne_get_n_elem_var",errmsg,EX_MSG); + return (EX_WARN); + } else { + sprintf(errmsg, + "Error: failed to locate element block id %d in %s variable in file id %d", + elem_blk_id, VAR_ID_EL_BLK, neid); + ex_err("ne_get_n_elem_var",errmsg,exerrval); + return (EX_FATAL); + } + } + + + /* inquire previously defined variable */ + if ((status = nc_inq_varid(neid,VAR_ELEM_VAR(elem_var_index,elem_blk_id_ndx), &varid)) != NC_NOERR) { + exerrval = status; + sprintf(errmsg, + "Error: failed to locate elem var %d for elem block %d in file id %d", + elem_var_index,elem_blk_id,neid); /* this msg needs to be improved */ + ex_err("ne_get_n_elem_var",errmsg,exerrval); + return (EX_FATAL); + } + + /* read values of element variable */ + start[0] = --time_step; + start[1] = --start_elem_num; + + count[0] = 1; + if ((num_elem_this_blk - start_elem_num) > num_elem) + count[1] = num_elem; + else + count[1] = num_elem_this_blk - start_elem_num; + + if (ex_comp_ws(neid) == 4) { + status = nc_get_vara_float(neid, varid, start, count, elem_var_vals); + } else { + status = nc_get_vara_double(neid, varid, start, count, elem_var_vals); + } + + if (status != NC_NOERR) { + exerrval = status; + sprintf(errmsg, + "Error: failed to get elem var %d for block %d in file id %d", + elem_var_index,elem_blk_id,neid);/*this msg needs to be improved*/ + ex_err("ne_get_n_elem_var",errmsg,exerrval); + return (EX_FATAL); + } + return (EX_NOERR); +} diff --git a/pool/shard006/C/0120140_stm8s_awu.c b/pool/shard006/C/0120140_stm8s_awu.c new file mode 100644 index 0000000000000000000000000000000000000000..f66bd48c2c88329a67240fdca86f012a19150afe --- /dev/null +++ b/pool/shard006/C/0120140_stm8s_awu.c @@ -0,0 +1,198 @@ +/** + ****************************************************************************** + * @file stm8s_awu.c + * @author MCD Application Team + * @version V2.3.0 + * @date 16-June-2017 + * @brief This file contains all the functions for the AWU peripheral. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 2014 STMicroelectronics

+ * + * 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 "stm8s_awu.h" + +/** @addtogroup STM8S_StdPeriph_Driver + * @{ + */ +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/* See also AWU_Timebase_TypeDef structure in stm8s_awu.h file : + N 2 5 1 2 4 8 1 3 6 1 2 5 1 2 1 3 + O 5 0 m m m m 6 2 4 2 5 1 s s 2 0 + I 0 0 s s s s m m m 8 6 2 s s + T u u s s s m m m + s s s s s +*/ +/** Contains the different values to write in the APR register (used by AWU_Init function) */ +CONST uint8_t APR_Array[17] = + { + 0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 61, 23, 23, 62 + }; + +/** Contains the different values to write in the TBR register (used by AWU_Init function) */ +CONST uint8_t TBR_Array[17] = + { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 14, 15, 15 + }; + +/* Public functions ----------------------------------------------------------*/ + +/** + * @addtogroup AWU_Public_Functions + * @{ + */ + +/** + * @brief Deinitializes the AWU peripheral registers to their default reset + * values. + * @param None + * @retval None + */ +void AWU_DeInit(void) +{ + AWU->CSR = AWU_CSR_RESET_VALUE; + AWU->APR = AWU_APR_RESET_VALUE; + AWU->TBR = AWU_TBR_RESET_VALUE; +} + +/** + * @brief Initializes the AWU peripheral according to the specified parameters. + * @param AWU_TimeBase : Time base selection (interval between AWU interrupts). + * can be one of the values of @ref AWU_Timebase_TypeDef. + * @retval None + * @par Required preconditions: + * The LS RC calibration must be performed before calling this function. + */ +void AWU_Init(AWU_Timebase_TypeDef AWU_TimeBase) +{ + /* Check parameter */ + assert_param(IS_AWU_TIMEBASE_OK(AWU_TimeBase)); + + /* Enable the AWU peripheral */ + AWU->CSR |= AWU_CSR_AWUEN; + + /* Set the TimeBase */ + AWU->TBR &= (uint8_t)(~AWU_TBR_AWUTB); + AWU->TBR |= TBR_Array[(uint8_t)AWU_TimeBase]; + + /* Set the APR divider */ + AWU->APR &= (uint8_t)(~AWU_APR_APR); + AWU->APR |= APR_Array[(uint8_t)AWU_TimeBase]; +} + +/** + * @brief Enable or disable the AWU peripheral. + * @param NewState Indicates the new state of the AWU peripheral. + * @retval None + * @par Required preconditions: + * Initialisation of AWU and LS RC calibration must be done before. + */ +void AWU_Cmd(FunctionalState NewState) +{ + if (NewState != DISABLE) + { + /* Enable the AWU peripheral */ + AWU->CSR |= AWU_CSR_AWUEN; + } + else + { + /* Disable the AWU peripheral */ + AWU->CSR &= (uint8_t)(~AWU_CSR_AWUEN); + } +} + +/** + * @brief Update APR register with the measured LSI frequency. + * @par Note on the APR calculation: + * A is the integer part of lsifreqkhz/4 and x the decimal part. + * x <= A/(1+2A) is equivalent to A >= x(1+2A) and also to 4A >= 4x(1+2A) [F1] + * but we know that A + x = lsifreqkhz/4 ==> 4x = lsifreqkhz-4A + * so [F1] can be written : + * 4A >= (lsifreqkhz-4A)(1+2A) + * @param LSIFreqHz Low Speed RC frequency measured by timer (in Hz). + * @retval None + * @par Required preconditions: + * - AWU must be disabled to avoid unwanted interrupts. + */ +void AWU_LSICalibrationConfig(uint32_t LSIFreqHz) +{ + uint16_t lsifreqkhz = 0x0; + uint16_t A = 0x0; + + /* Check parameter */ + assert_param(IS_LSI_FREQUENCY_OK(LSIFreqHz)); + + lsifreqkhz = (uint16_t)(LSIFreqHz / 1000); /* Converts value in kHz */ + + /* Calculation of AWU calibration value */ + + A = (uint16_t)(lsifreqkhz >> 2U); /* Division by 4, keep integer part only */ + + if ((4U * A) >= ((lsifreqkhz - (4U * A)) * (1U + (2U * A)))) + { + AWU->APR = (uint8_t)(A - 2U); + } + else + { + AWU->APR = (uint8_t)(A - 1U); + } +} + +/** + * @brief Configures AWU in Idle mode to reduce power consumption. + * @param None + * @retval None + */ +void AWU_IdleModeEnable(void) +{ + /* Disable AWU peripheral */ + AWU->CSR &= (uint8_t)(~AWU_CSR_AWUEN); + + /* No AWU timebase */ + AWU->TBR = (uint8_t)(~AWU_TBR_AWUTB); +} + +/** + * @brief Returns status of the AWU peripheral flag. + * @param None + * @retval FlagStatus : Status of the AWU flag. + * This parameter can be any of the @ref FlagStatus enumeration. + */ +FlagStatus AWU_GetFlagStatus(void) +{ + return((FlagStatus)(((uint8_t)(AWU->CSR & AWU_CSR_AWUF) == (uint8_t)0x00) ? RESET : SET)); +} + + +/** + * @} + */ + +/** + * @} + */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0120142_unlink_10.c b/pool/shard006/C/0120142_unlink_10.c new file mode 100644 index 0000000000000000000000000000000000000000..58f541c69a17a9680645b8ffde303e579efe2c9b --- /dev/null +++ b/pool/shard006/C/0120142_unlink_10.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include + +#define MAX_BUFF_SIZE 255 +char g_workgroup[MAX_BUFF_SIZE]; +char g_username[MAX_BUFF_SIZE]; +char g_password[MAX_BUFF_SIZE]; +char g_server[MAX_BUFF_SIZE]; +char g_share[MAX_BUFF_SIZE]; + + +void auth_fn(const char *server, const char *share, char *workgroup, int wgmaxlen, + char *username, int unmaxlen, char *password, int pwmaxlen) +{ + + strncpy(workgroup, g_workgroup, wgmaxlen - 1); + + strncpy(username, g_username, unmaxlen - 1); + + strncpy(password, g_password, pwmaxlen - 1); + + strcpy(g_server, server); + strcpy(g_share, share); + +} + +int main(int argc, char** argv) +{ + int err = -1; + int fd = 0; + char url[MAX_BUFF_SIZE]; + + bzero(g_workgroup,MAX_BUFF_SIZE); + bzero(url,MAX_BUFF_SIZE); + + if ( argc == 5 ) + { + + strncpy(g_workgroup,argv[1],strlen(argv[1])); + strncpy(g_username,argv[2],strlen(argv[2])); + strncpy(g_password,argv[3],strlen(argv[3])); + strncpy(url,argv[4],strlen(argv[4])); + + smbc_init(auth_fn, 0); + fd = smbc_open(url, O_RDWR | O_CREAT, 0000); + smbc_close(fd); + + strncpy(g_username, "xxxxxx", 6); + strncpy(g_password, "xxxxxx", 6); + + smbc_unlink(url); + + err = errno; + + } + + return err; + +} + diff --git a/pool/shard006/C/0120144_kzm.c b/pool/shard006/C/0120144_kzm.c new file mode 100644 index 0000000000000000000000000000000000000000..68cd1b48b909632c67b793fd13b06047c826a52f --- /dev/null +++ b/pool/shard006/C/0120144_kzm.c @@ -0,0 +1,154 @@ +/* + * KZM Board System emulation. + * + * Copyright (c) 2008 OKL and 2011 NICTA + * Written by Hans at OK-Labs + * Updated by Peter Chubb. + * + * This code is licensed under the GPL, version 2 or later. + * See the file `COPYING' in the top level directory. + * + * It (partially) emulates a Kyoto Microcomputer + * KZM-ARM11-01 evaluation board, with a Freescale + * i.MX31 SoC + */ + +#include "sysbus.h" +#include "exec-memory.h" +#include "hw.h" +#include "arm-misc.h" +#include "devices.h" +#include "net.h" +#include "sysemu.h" +#include "boards.h" +#include "pc.h" /* for the FPGA UART that emulates a 16550 */ +#include "imx.h" + + /* Memory map for Kzm Emulation Baseboard: + * 0x00000000-0x00003fff 16k secure ROM IGNORED + * 0x00004000-0x00407fff Reserved IGNORED + * 0x00404000-0x00407fff ROM IGNORED + * 0x00408000-0x0fffffff Reserved IGNORED + * 0x10000000-0x1fffbfff RAM aliasing IGNORED + * 0x1fffc000-0x1fffffff RAM EMULATED + * 0x20000000-0x2fffffff Reserved IGNORED + * 0x30000000-0x7fffffff I.MX31 Internal Register Space + * 0x43f00000 IO_AREA0 + * 0x43f90000 UART1 EMULATED + * 0x43f94000 UART2 EMULATED + * 0x68000000 AVIC EMULATED + * 0x53f80000 CCM EMULATED + * 0x53f94000 PIT 1 EMULATED + * 0x53f98000 PIT 2 EMULATED + * 0x53f90000 GPT EMULATED + * 0x80000000-0x87ffffff RAM EMULATED + * 0x88000000-0x8fffffff RAM Aliasing EMULATED + * 0xa0000000-0xafffffff NAND Flash IGNORED + * 0xb0000000-0xb3ffffff Unavailable IGNORED + * 0xb4000000-0xb4000fff 8-bit free space IGNORED + * 0xb4001000-0xb400100f Board control IGNORED + * 0xb4001003 DIP switch + * 0xb4001010-0xb400101f 7-segment LED IGNORED + * 0xb4001020-0xb400102f LED IGNORED + * 0xb4001030-0xb400103f LED IGNORED + * 0xb4001040-0xb400104f FPGA, UART EMULATED + * 0xb4001050-0xb400105f FPGA, UART EMULATED + * 0xb4001060-0xb40fffff FPGA IGNORED + * 0xb6000000-0xb61fffff LAN controller EMULATED + * 0xb6200000-0xb62fffff FPGA NAND Controller IGNORED + * 0xb6300000-0xb7ffffff Free IGNORED + * 0xb8000000-0xb8004fff Memory control registers IGNORED + * 0xc0000000-0xc3ffffff PCMCIA/CF IGNORED + * 0xc4000000-0xffffffff Reserved IGNORED + */ + +#define KZM_RAMADDRESS (0x80000000) +#define KZM_FPGA (0xb4001040) + +static struct arm_boot_info kzm_binfo = { + .loader_start = KZM_RAMADDRESS, + .board_id = 1722, +}; + +static void kzm_init(ram_addr_t ram_size, + const char *boot_device, + const char *kernel_filename, const char *kernel_cmdline, + const char *initrd_filename, const char *cpu_model) +{ + ARMCPU *cpu; + MemoryRegion *address_space_mem = get_system_memory(); + MemoryRegion *ram = g_new(MemoryRegion, 1); + MemoryRegion *sram = g_new(MemoryRegion, 1); + MemoryRegion *ram_alias = g_new(MemoryRegion, 1); + qemu_irq *cpu_pic; + DeviceState *dev; + DeviceState *ccm; + + if (!cpu_model) { + cpu_model = "arm1136"; + } + + cpu = cpu_arm_init(cpu_model); + if (!cpu) { + fprintf(stderr, "Unable to find CPU definition\n"); + exit(1); + } + + /* On a real system, the first 16k is a `secure boot rom' */ + + memory_region_init_ram(ram, "kzm.ram", ram_size); + vmstate_register_ram_global(ram); + memory_region_add_subregion(address_space_mem, KZM_RAMADDRESS, ram); + + memory_region_init_alias(ram_alias, "ram.alias", ram, 0, ram_size); + memory_region_add_subregion(address_space_mem, 0x88000000, ram_alias); + + memory_region_init_ram(sram, "kzm.sram", 0x4000); + memory_region_add_subregion(address_space_mem, 0x1FFFC000, sram); + + cpu_pic = arm_pic_init_cpu(cpu); + dev = sysbus_create_varargs("imx_avic", 0x68000000, + cpu_pic[ARM_PIC_CPU_IRQ], + cpu_pic[ARM_PIC_CPU_FIQ], NULL); + + + imx_serial_create(0, 0x43f90000, qdev_get_gpio_in(dev, 45)); + imx_serial_create(1, 0x43f94000, qdev_get_gpio_in(dev, 32)); + + ccm = sysbus_create_simple("imx_ccm", 0x53f80000, NULL); + + imx_timerp_create(0x53f94000, qdev_get_gpio_in(dev, 28), ccm); + imx_timerp_create(0x53f98000, qdev_get_gpio_in(dev, 27), ccm); + imx_timerg_create(0x53f90000, qdev_get_gpio_in(dev, 29), ccm); + + if (nd_table[0].used) { + lan9118_init(&nd_table[0], 0xb6000000, qdev_get_gpio_in(dev, 52)); + } + + if (serial_hds[2]) { /* touchscreen */ + serial_mm_init(address_space_mem, KZM_FPGA+0x10, 0, + qdev_get_gpio_in(dev, 52), + 14745600, serial_hds[2], + DEVICE_NATIVE_ENDIAN); + } + + kzm_binfo.ram_size = ram_size; + kzm_binfo.kernel_filename = kernel_filename; + kzm_binfo.kernel_cmdline = kernel_cmdline; + kzm_binfo.initrd_filename = initrd_filename; + kzm_binfo.nb_cpus = 1; + arm_load_kernel(cpu, &kzm_binfo); +} + +static QEMUMachine kzm_machine = { + .name = "kzm", + .desc = "ARM KZM Emulation Baseboard (ARM1136)", + .init = kzm_init, +}; + +static void kzm_machine_init(void) +{ + qemu_register_machine(&kzm_machine); +} + +machine_init(kzm_machine_init) diff --git a/pool/shard006/C/0120148_304.c b/pool/shard006/C/0120148_304.c new file mode 100644 index 0000000000000000000000000000000000000000..c3223f029dc1a97d390e0e3516644872aeec66ab --- /dev/null +++ b/pool/shard006/C/0120148_304.c @@ -0,0 +1,59 @@ +/** + * \file + * + * \author Georg Hopp + * + * \copyright + * Copyright © 2012 Georg Hopp + * + * 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 . + */ + +#include + +#include "class.h" + +#include "http/response.h" +#include "http/message.h" +#include "http/header.h" + +#include "utils/memory.h" +#include "hash.h" + +HttpResponse +httpResponse304( + const char * mime, size_t nmime, + const char * etag, size_t netag, + const char * mtime, size_t nmtime) +{ + HttpResponse response; + HttpMessage message; + + response = new(HttpResponse, "HTTP/1.1", 304, "Not Modified"); + message = (HttpMessage)response; + + message->nbody = 0; + message->body = NULL; + + hashAdd(message->header, + new(HttpHeader, CSTRA("Content-Type"), mime, nmime)); + hashAdd(message->header, + new(HttpHeader, CSTRA("ETag"), etag, netag)); + hashAdd(message->header, + new(HttpHeader, CSTRA("Last-Modified"), mtime, nmtime)); + + return response; +} + +// vim: set ts=4 sw=4: diff --git a/pool/shard006/C/0120151_lights.c b/pool/shard006/C/0120151_lights.c new file mode 100644 index 0000000000000000000000000000000000000000..97732670a2b7a86dd40af516a05a7e88a71fcfc6 --- /dev/null +++ b/pool/shard006/C/0120151_lights.c @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2008 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. + */ + +#define LOG_TAG "lights" + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; + +static int write_int(char const *path, int value) +{ + int fd; + static int already_warned = -1; + fd = open(path, O_RDWR); + if (fd >= 0) { + char buffer[20]; + int bytes = sprintf(buffer, "%d\n", value); + int amt = write(fd, buffer, bytes); + close(fd); + return amt == -1 ? -errno : 0; + } else { + if (already_warned == -1) { + ALOGE("write_int failed to open %s\n", path); + already_warned = 1; + } + return -errno; + } +} + +static int rgb_to_brightness(struct light_state_t const *state) +{ + int color = state->color & 0x00ffffff; + return ((77 * ((color >> 16) & 0x00ff)) + + (150 * ((color >> 8) & 0x00ff)) + + (29 * (color & 0x00ff))) >> 8; +} + +static int set_light_backlight(struct light_device_t *dev, + struct light_state_t const *state) +{ + int err = 0; + int brightness = rgb_to_brightness(state); + + pthread_mutex_lock(&g_lock); + err = write_int("/sys/class/backlight/pwm-backlight/brightness", + brightness); + pthread_mutex_unlock(&g_lock); + + return err; +} + +/** Close the lights device */ +static int close_lights(struct light_device_t *dev) +{ + if (dev) + free(dev); + return 0; +} + +/** Open a new instance of a lights device using name */ +static int open_lights(const struct hw_module_t *module, char const *name, + struct hw_device_t **device) +{ + pthread_t lighting_poll_thread; + + int (*set_light) (struct light_device_t *dev, + struct light_state_t const *state); + + if (0 == strcmp(LIGHT_ID_BACKLIGHT, name)) + set_light = set_light_backlight; + else + return -EINVAL; + + pthread_mutex_init(&g_lock, NULL); + + struct light_device_t *dev = malloc(sizeof(struct light_device_t)); + memset(dev, 0, sizeof(*dev)); + + dev->common.tag = HARDWARE_DEVICE_TAG; + dev->common.version = 0; + dev->common.module = (struct hw_module_t *)module; + dev->common.close = (int (*)(struct hw_device_t *))close_lights; + dev->set_light = set_light; + + *device = (struct hw_device_t *)dev; + + return 0; +} + +static struct hw_module_methods_t lights_methods = +{ + .open = open_lights, +}; + +/* + * The backlight Module + */ +struct hw_module_t HAL_MODULE_INFO_SYM = +{ + .tag = HARDWARE_MODULE_TAG, + .version_major = 1, + .version_minor = 0, + .id = LIGHTS_HARDWARE_MODULE_ID, + .name = "NVIDIA Ventana lights module", + .author = "NVIDIA", + .methods = &lights_methods, +}; diff --git a/pool/shard006/C/0120152_inode.c b/pool/shard006/C/0120152_inode.c new file mode 100644 index 0000000000000000000000000000000000000000..49dfb2ab783e6f921fdd344f1b6c39ee29cd1935 --- /dev/null +++ b/pool/shard006/C/0120152_inode.c @@ -0,0 +1,217 @@ +/* + * linux/fs/proc/inode.c + * + * Copyright (C) 1991, 1992 Linus Torvalds + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "internal.h" + +static inline struct proc_dir_entry * de_get(struct proc_dir_entry *de) +{ + if (de) + atomic_inc(&de->count); + return de; +} + +/* + * Decrements the use count and checks for deferred deletion. + */ +static void de_put(struct proc_dir_entry *de) +{ + if (de) { + lock_kernel(); + if (!atomic_read(&de->count)) { + printk("de_put: entry %s already free!\n", de->name); + unlock_kernel(); + return; + } + + if (atomic_dec_and_test(&de->count)) { + if (de->deleted) { + printk("de_put: deferred delete of %s\n", + de->name); + free_proc_entry(de); + } + } + unlock_kernel(); + } +} + +/* + * Decrement the use count of the proc_dir_entry. + */ +static void proc_delete_inode(struct inode *inode) +{ + struct proc_dir_entry *de; + + truncate_inode_pages(&inode->i_data, 0); + + /* Stop tracking associated processes */ + put_pid(PROC_I(inode)->pid); + + /* Let go of any associated proc directory entry */ + de = PROC_I(inode)->pde; + if (de) { + if (de->owner) + module_put(de->owner); + de_put(de); + } + clear_inode(inode); +} + +struct vfsmount *proc_mnt; + +static void proc_read_inode(struct inode * inode) +{ + inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME; +} + +static kmem_cache_t * proc_inode_cachep; + +static struct inode *proc_alloc_inode(struct super_block *sb) +{ + struct proc_inode *ei; + struct inode *inode; + + ei = (struct proc_inode *)kmem_cache_alloc(proc_inode_cachep, SLAB_KERNEL); + if (!ei) + return NULL; + ei->pid = NULL; + ei->fd = 0; + ei->op.proc_get_link = NULL; + ei->pde = NULL; + inode = &ei->vfs_inode; + inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME; + return inode; +} + +static void proc_destroy_inode(struct inode *inode) +{ + kmem_cache_free(proc_inode_cachep, PROC_I(inode)); +} + +static void init_once(void * foo, kmem_cache_t * cachep, unsigned long flags) +{ + struct proc_inode *ei = (struct proc_inode *) foo; + + if ((flags & (SLAB_CTOR_VERIFY|SLAB_CTOR_CONSTRUCTOR)) == + SLAB_CTOR_CONSTRUCTOR) + inode_init_once(&ei->vfs_inode); +} + +int __init proc_init_inodecache(void) +{ + proc_inode_cachep = kmem_cache_create("proc_inode_cache", + sizeof(struct proc_inode), + 0, (SLAB_RECLAIM_ACCOUNT| + SLAB_MEM_SPREAD), + init_once, NULL); + if (proc_inode_cachep == NULL) + return -ENOMEM; + return 0; +} + +static int proc_remount(struct super_block *sb, int *flags, char *data) +{ + *flags |= MS_NODIRATIME; + return 0; +} + +static struct super_operations proc_sops = { + .alloc_inode = proc_alloc_inode, + .destroy_inode = proc_destroy_inode, + .read_inode = proc_read_inode, + .drop_inode = generic_delete_inode, + .delete_inode = proc_delete_inode, + .statfs = simple_statfs, + .remount_fs = proc_remount, +}; + +struct inode *proc_get_inode(struct super_block *sb, unsigned int ino, + struct proc_dir_entry *de) +{ + struct inode * inode; + + /* + * Increment the use count so the dir entry can't disappear. + */ + de_get(de); + + WARN_ON(de && de->deleted); + + if (de != NULL && !try_module_get(de->owner)) + goto out_mod; + + inode = iget(sb, ino); + if (!inode) + goto out_ino; + + PROC_I(inode)->pde = de; + if (de) { + if (de->mode) { + inode->i_mode = de->mode; + inode->i_uid = de->uid; + inode->i_gid = de->gid; + } + if (de->size) + inode->i_size = de->size; + if (de->nlink) + inode->i_nlink = de->nlink; + if (de->proc_iops) + inode->i_op = de->proc_iops; + if (de->proc_fops) + inode->i_fop = de->proc_fops; + } + + return inode; + +out_ino: + if (de != NULL) + module_put(de->owner); +out_mod: + de_put(de); + return NULL; +} + +int proc_fill_super(struct super_block *s, void *data, int silent) +{ + struct inode * root_inode; + + s->s_flags |= MS_NODIRATIME | MS_NOSUID | MS_NOEXEC; + s->s_blocksize = 1024; + s->s_blocksize_bits = 10; + s->s_magic = PROC_SUPER_MAGIC; + s->s_op = &proc_sops; + s->s_time_gran = 1; + + root_inode = proc_get_inode(s, PROC_ROOT_INO, &proc_root); + if (!root_inode) + goto out_no_root; + root_inode->i_uid = 0; + root_inode->i_gid = 0; + s->s_root = d_alloc_root(root_inode); + if (!s->s_root) + goto out_no_root; + return 0; + +out_no_root: + printk("proc_read_super: get root inode failed\n"); + iput(root_inode); + return -ENOMEM; +} +MODULE_LICENSE("GPL"); diff --git a/pool/shard006/C/0120153_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_61b.c b/pool/shard006/C/0120153_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_61b.c new file mode 100644 index 0000000000000000000000000000000000000000..dcb5448c625f81449e856942a8e3961d83aef279 --- /dev/null +++ b/pool/shard006/C/0120153_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_61b.c @@ -0,0 +1,40 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_61b.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml +Template File: sources-sink-61b.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sinks: loop + * BadSink : Copy twoIntsStruct array to data using a loop + * Flow Variant: 61 Data flow: data returned from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_61b_badSource(twoIntsStruct * data) +{ + /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = (twoIntsStruct *)malloc(50*sizeof(twoIntsStruct)); + return data; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_61b_goodG2BSource(twoIntsStruct * data) +{ + /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = (twoIntsStruct *)malloc(100*sizeof(twoIntsStruct)); + return data; +} + +#endif /* OMITGOOD */ diff --git a/pool/shard006/C/0120154_mtk_cooler_shutdown.c b/pool/shard006/C/0120154_mtk_cooler_shutdown.c new file mode 100644 index 0000000000000000000000000000000000000000..1b309bdf82d6cf7e10698e5dd579b2f29efde764 --- /dev/null +++ b/pool/shard006/C/0120154_mtk_cooler_shutdown.c @@ -0,0 +1,295 @@ +#include +#include +#include +#include +#include + + +#include "mach/mtk_thermal_monitor.h" +#include + +#define MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN 3 + +//#define MTK_COOLER_SHUTDOWN_UEVENT +#define MTK_COOLER_SHUTDOWN_SIGNAL + +#if defined(MTK_COOLER_SHUTDOWN_SIGNAL) +#include +#include +#include +#include +#include + +#define MAX_LEN 256 +#endif + +#if 1 +#define mtk_cooler_shutdown_dprintk(fmt, args...) \ + do { xlog_printk(ANDROID_LOG_DEBUG, "thermal/cooler/shutdown", fmt, ##args); } while(0) +#else +#define mtk_cooler_shutdown_dprintk(fmt, args...) +#endif + +static struct thermal_cooling_device *cl_shutdown_dev[MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN] = {0}; +static unsigned long cl_shutdown_state[MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN] = {0}; + +#if defined(MTK_COOLER_SHUTDOWN_SIGNAL) + +static unsigned int tm_pid = 0; +static unsigned int tm_input_pid = 0; +static unsigned int mtk_cl_sd_rst = 0; +static struct task_struct g_task; +static struct task_struct *pg_task = &g_task; + +static ssize_t _mtk_cl_sd_rst_write( struct file *filp, const char __user *buf, unsigned long len, void *data ) +{ + int ret = 0; + char tmp[MAX_LEN] = {0}; + + /* write data to the buffer */ + if ( copy_from_user(tmp, buf, len) ) { + return -EFAULT; + } + + ret = kstrtouint(tmp, 10, &mtk_cl_sd_rst); + if (ret) + WARN_ON(1); + + + if (1 == mtk_cl_sd_rst) + { + int i; + for (i = MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN; i-- > 0; ) + { + cl_shutdown_state[i] = 0; + } + mtk_cl_sd_rst = 0; + } + mtk_cooler_shutdown_dprintk("[%s] %s = %d\n", __func__, tmp, mtk_cl_sd_rst); + + return len; +} + +static ssize_t _mtk_cl_sd_pid_write( struct file *filp, const char __user *buf, unsigned long len, void *data ) +{ + int ret = 0; + char tmp[MAX_LEN] = {0}; + + /* write data to the buffer */ + if ( copy_from_user(tmp, buf, len) ) { + return -EFAULT; + } + + ret = kstrtouint(tmp, 10, &tm_input_pid); + if (ret) + WARN_ON(1); + + mtk_cooler_shutdown_dprintk("[%s] %s = %d\n", __func__, tmp, tm_input_pid); + + return len; +} + +static int _mtk_cl_sd_pid_read( char *buf, char **start, off_t offset , int count, int *eof, void *data ) +{ + int ret; + char tmp[MAX_LEN] = {0}; + + sprintf(tmp, "%d", tm_input_pid); + ret = strlen(tmp); + + memcpy(buf, tmp, ret*sizeof(char)); + + mtk_cooler_shutdown_dprintk("[%s] %s = %d\n", __func__, buf, tm_input_pid); + + return ret; +} + +static int _mtk_cl_sd_send_signal(void) +{ + int ret = 0; + + if (tm_input_pid == 0) { + mtk_cooler_shutdown_dprintk("[%s] pid is empty\n", __func__); + ret = -1; + } + + mtk_cooler_shutdown_dprintk("[%s] pid is %d, %d\n", __func__, tm_pid, tm_input_pid); + + if (ret == 0 && tm_input_pid != tm_pid) { + tm_pid = tm_input_pid; + pg_task = get_pid_task(find_vpid(tm_pid), PIDTYPE_PID); + } + + if (ret == 0 && pg_task) { + siginfo_t info; + info.si_signo = SIGIO; + info.si_errno = 0; + info.si_code = 1; + info.si_addr = NULL; + ret = send_sig_info(SIGIO, &info, pg_task); + } + + if (ret != 0) mtk_cooler_shutdown_dprintk("[%s] ret=%d\n", __func__, ret); + + return ret; +} + +#endif + +static int +mtk_cl_shutdown_get_max_state(struct thermal_cooling_device *cdev, + unsigned long *state) +{ + *state = 1; + //mtk_cooler_shutdown_dprintk("mtk_cl_shutdown_get_max_state() %s %d\n", cdev->type, *state); + return 0; +} + +static int +mtk_cl_shutdown_get_cur_state(struct thermal_cooling_device *cdev, + unsigned long *state) +{ + *state = *((unsigned long*) cdev->devdata); + //mtk_cooler_shutdown_dprintk("mtk_cl_shutdown_get_cur_state() %s %d\n", cdev->type, *state); + return 0; +} + +static int +mtk_cl_shutdown_set_cur_state(struct thermal_cooling_device *cdev, + unsigned long state) +{ +#if defined(MTK_COOLER_SHUTDOWN_SIGNAL) + volatile unsigned long original_state; +#endif + //mtk_cooler_shutdown_dprintk("mtk_cl_shutdown_set_cur_state() %s %d\n", cdev->type, state); +#if defined(MTK_COOLER_SHUTDOWN_SIGNAL) + original_state = *((unsigned long*) cdev->devdata); +#endif + + *((unsigned long*) cdev->devdata) = state; + + if(1 == state) + { +#if defined(MTK_COOLER_SHUTDOWN_UEVENT) + { + // send uevent to notify current call must be dropped + char event[] = "SHUTDOWN=1"; + char *envp[] = { event, NULL }; + + kobject_uevent_env(&(cdev->device.kobj), KOBJ_CHANGE, envp); + } +#endif + +#if defined(MTK_COOLER_SHUTDOWN_SIGNAL) + if (0 == original_state) // make this an edge trigger instead of level trigger + { + // send signal to target process + _mtk_cl_sd_send_signal(); + } +#endif + } + + return 0; +} + +/* bind fan callbacks to fan device */ +static struct thermal_cooling_device_ops mtk_cl_shutdown_ops = { + .get_max_state = mtk_cl_shutdown_get_max_state, + .get_cur_state = mtk_cl_shutdown_get_cur_state, + .set_cur_state = mtk_cl_shutdown_set_cur_state, +}; + +static int mtk_cooler_shutdown_register_ltf(void) +{ + int i; + mtk_cooler_shutdown_dprintk("register ltf\n"); + + for (i = MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN; i-- > 0; ) + { + char temp[20] = {0}; + sprintf(temp, "mtk-cl-shutdown%02d", i); + cl_shutdown_dev[i] = mtk_thermal_cooling_device_register(temp, + (void*) &cl_shutdown_state[i], + &mtk_cl_shutdown_ops); + } + + return 0; +} + +static void mtk_cooler_shutdown_unregister_ltf(void) +{ + int i; + mtk_cooler_shutdown_dprintk("unregister ltf\n"); + + for (i = MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN; i-- > 0; ) + { + if (cl_shutdown_dev[i]) + { + mtk_thermal_cooling_device_unregister(cl_shutdown_dev[i]); + cl_shutdown_dev[i] = NULL; + cl_shutdown_state[i] = 0; + } + } +} + + +static int __init mtk_cooler_shutdown_init(void) +{ + int err = 0; + int i; + + for (i = MAX_NUM_INSTANCE_MTK_COOLER_SHUTDOWN; i-- > 0; ) + { + cl_shutdown_dev[i] = NULL; + cl_shutdown_state[i] = 0; + } + + mtk_cooler_shutdown_dprintk("init\n"); + +#if defined(MTK_COOLER_SHUTDOWN_SIGNAL) + { + struct proc_dir_entry *entry; + + entry = create_proc_entry("driver/mtk_cl_sd_pid", S_IRUGO | S_IWUSR, NULL); + if (NULL != entry) + { + entry->read_proc = _mtk_cl_sd_pid_read; + entry->write_proc = _mtk_cl_sd_pid_write; + } + } + + { + struct proc_dir_entry *entry; + + entry = create_proc_entry("driver/mtk_cl_sd_rst", S_IRUGO | S_IWUSR | S_IWGRP, NULL); + if (NULL != entry) + { + entry->write_proc = _mtk_cl_sd_rst_write; + entry->gid = 1000; + } + } +#endif + + err = mtk_cooler_shutdown_register_ltf(); + if (err) + goto err_unreg; + + return 0; + +err_unreg: + mtk_cooler_shutdown_unregister_ltf(); + return err; +} + +static void __exit mtk_cooler_shutdown_exit(void) +{ + mtk_cooler_shutdown_dprintk("exit\n"); + + mtk_cooler_shutdown_unregister_ltf(); +} + +module_init(mtk_cooler_shutdown_init); +module_exit(mtk_cooler_shutdown_exit); + + + diff --git a/pool/shard006/C/0120157_child-linear.c b/pool/shard006/C/0120157_child-linear.c new file mode 100644 index 0000000000000000000000000000000000000000..eca3e3f5a19dac0305319104ae15f5e8cb0e7ea5 --- /dev/null +++ b/pool/shard006/C/0120157_child-linear.c @@ -0,0 +1,36 @@ +/* Child process of page-parallel. + Encrypts 1 MB of zeros, then decrypts it, and ensures that + the zeros are back. */ + +#include +#include "tests/arc4.h" +#include "tests/lib.h" +#include "tests/main.h" + +const char *test_name = "child-linear"; + +#define SIZE (1024 * 1024) +static char buf[SIZE]; + +int +main (int argc, char *argv[]) +{ + const char *key = argv[argc - 1]; + struct arc4 arc4; + size_t i; + + /* Encrypt zeros. */ + arc4_init (&arc4, key, strlen (key)); + arc4_crypt (&arc4, buf, SIZE); + + /* Decrypt back to zeros. */ + arc4_init (&arc4, key, strlen (key)); + arc4_crypt (&arc4, buf, SIZE); + + /* Check that it's all zeros. */ + for (i = 0; i < SIZE; i++) + if (buf[i] != '\0') + fail ("byte %zu != 0", i); + + return 0x42; +} diff --git a/pool/shard006/C/0120158_lock-memory-shared.c b/pool/shard006/C/0120158_lock-memory-shared.c new file mode 100644 index 0000000000000000000000000000000000000000..c4361fa8a92d6174f1fcd72ed31c9f477f6c71f8 --- /dev/null +++ b/pool/shard006/C/0120158_lock-memory-shared.c @@ -0,0 +1,169 @@ +/* + * ===================================================================================== + * + * Filename: lock-memory-shared.c + * + * Description: + * + * Version: 1.0 + * Created: 12/08/2016 02:13:49 PM + * Revision: none + * Compiler: gcc + * + * Author: YOUR NAME (), + * Organization: + * + * ===================================================================================== + */ +#include +#include +#include +#include +#include +#include +#include + +#define SHARE_LOCK 0x1123 + +struct memlock{ + pthread_mutex_t lk; + char szmsg[1024]; +}; + +int mem_lock(struct memlock * lock, const char * info) { + if(NULL == lock) { + printf("lock is NULL when locking\n"); + return -1; + } + int x = pthread_mutex_lock(&lock -> lk); + printf("lock, pre message : [%s]\n", lock -> szmsg); + snprintf(lock -> szmsg, sizeof(lock -> szmsg) - 1, "%s", info); + return x; +} + +int mem_trylock(struct memlock * lock, const char * info) { + if(NULL == lock) { + printf("lock is NULL when trylocking\n"); + return -1; + } + int x = pthread_mutex_trylock(&lock -> lk); + printf("lock, pre message : [%s]\n", lock -> szmsg); + snprintf(lock -> szmsg, sizeof(lock -> szmsg) - 1, "%s", info); + return x; +} + +int mem_unlock(struct memlock * lock, const char * info) { + if(NULL == lock) { + printf("lock is NULL when unlocking\n"); + return -1; + } + printf("unlock, pre message : [%s]\n", lock -> szmsg); + snprintf(lock -> szmsg, sizeof(lock -> szmsg) - 1, "%s", info); + int x = pthread_mutex_unlock(&lock -> lk); + return x; +} + +struct memlock * get_memlock() { + errno = 0; + int shmid = shmget(SHARE_LOCK, sizeof(struct memlock), IPC_CREAT | IPC_EXCL); + if(shmid < 0) { + if(EEXIST == errno) { + printf("shared memory of [0x%x] is exists\n", SHARE_LOCK); + shmid = shmget(SHARE_LOCK, sizeof(struct memlock), IPC_CREAT); + if(shmid < 0) { + printf("shmget() faild\n"); + shmid = shmget(SHARE_LOCK, 0, 0); + if(shmid < 0) { + printf("find shared memory of [0x%x] faild\n", SHARE_LOCK); + return NULL; + } + shmctl(shmid, IPC_RMID, NULL); + } + shmid = shmget(SHARE_LOCK, sizeof(struct memlock), IPC_CREAT); + printf("shmid : [%d]\n", shmid); + if(shmid < 0) { + printf("find shared memory of [0x%x] faild\n", SHARE_LOCK); + return NULL; + } + + return (struct memlock *)shmat(shmid, NULL,0); + } else { + printf("create shared memory [%d] faild\n", SHARE_LOCK); + return NULL; + } + } + struct memlock * ptr = (struct memlock *)shmat(shmid, NULL,0); + if(NULL == ptr) { + printf("get shared memory faild\n"); + return NULL; + } + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + pthread_mutex_init(&ptr -> lk, &attr); + + return ptr; +} + +void show_usage(const char * name) { + const char * p = ""; + if(NULL != p){ + p = name; + } + + printf("%s -l : to lock\n", p); + printf("%s -u : to unlock\n", p); +} + +int do_lock() { + struct memlock * lock = get_memlock(); + if(NULL == lock) { + printf("get lock faild\n"); + return -1; + } + + while(1){ +#if 1 + mem_lock(lock, "lock ..."); +#else + getchar(); + if(0 == mem_trylock(lock, "trylock")) { + printf("\033[0;32mlock success\033[0m\n"); + } else { + printf("\033[0;31mlock faild\033[0m\n"); + } +#endif + } + + return 0; +} + +int do_unlock() { + struct memlock * lock = get_memlock(); + if(NULL == lock) { + printf("get lock faild\n"); + return -1; + } + + while(1){ + getchar(); + mem_unlock(lock, "unlock"); + } +} + +int main(int argc, char * argv[]) { + int i = 0; + for(i = 0; i < argc; i++) { + if(strcmp("-l", argv[i]) == 0) { + return do_lock(); + } + if(strcmp("-u", argv[i]) == 0) { + return do_unlock(); + } + } + + show_usage(argv[0]); + + return 0; +} + diff --git a/pool/shard006/C/0120159_ReturnMatrix.c b/pool/shard006/C/0120159_ReturnMatrix.c new file mode 100644 index 0000000000000000000000000000000000000000..957bec48e15794638ebb3884f1d65ce2ba5bf8e6 --- /dev/null +++ b/pool/shard006/C/0120159_ReturnMatrix.c @@ -0,0 +1,19 @@ +#include +#include + +void integerPower(int y, int ret[4]) { + ret[0] = pow(y, 2); + ret[1] = pow(y, 3); + ret[2] = pow(y, 4); + ret[3] = ret[0] + ret[1] + ret[2]; +} +int main(void) { + int valores[4]; + integerPower(5, valores); + printf("%d\n", valores[0]); + printf("%d\n", valores[1]); + printf("%d\n", valores[2]); + printf("%d\n", valores[3]); +} + +//https://pt.stackoverflow.com/q/171149/101 diff --git a/pool/shard006/C/0120161_scb2_flash.c b/pool/shard006/C/0120161_scb2_flash.c new file mode 100644 index 0000000000000000000000000000000000000000..53f99306e2c05c2695e571d06a990c574647cb93 --- /dev/null +++ b/pool/shard006/C/0120161_scb2_flash.c @@ -0,0 +1,192 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MODNAME "scb2_flash" +#define SCB2_ADDR 0xfff00000 +#define SCB2_WINDOW 0x00100000 + + +static void __iomem *scb2_ioaddr; +static struct mtd_info *scb2_mtd; +static struct map_info scb2_map = { + .name = "SCB2 BIOS Flash", + .size = 0, + .bankwidth = 1, +}; +static int region_fail; + +static int __devinit +scb2_fixup_mtd(struct mtd_info *mtd) +{ + int i; + int done = 0; + struct map_info *map = mtd->priv; + struct cfi_private *cfi = map->fldrv_priv; + + + if (cfi->cfiq->InterfaceDesc != CFI_INTERFACE_X16_ASYNC) { + printk(KERN_ERR MODNAME ": unsupported InterfaceDesc: %#x\n", + cfi->cfiq->InterfaceDesc); + return -1; + } + + + + + mtd->size = map->size; + + + mtd->erasesize /= 2; + for (i = 0; i < mtd->numeraseregions; i++) { + struct mtd_erase_region_info *region = &mtd->eraseregions[i]; + region->erasesize /= 2; + } + + + for (i = 0; !done && i < mtd->numeraseregions; i++) { + struct mtd_erase_region_info *region = &mtd->eraseregions[i]; + + if (region->numblocks * region->erasesize > mtd->size) { + region->numblocks = ((unsigned long)mtd->size / + region->erasesize); + done = 1; + } else { + region->numblocks = 0; + } + region->offset = 0; + } + + return 0; +} + + +#define CSB5_FCR 0x41 +#define CSB5_FCR_DECODE_ALL 0x0e +static int __devinit +scb2_flash_probe(struct pci_dev *dev, const struct pci_device_id *ent) +{ + u8 reg; + + + pci_read_config_byte(dev, CSB5_FCR, ®); + pci_write_config_byte(dev, CSB5_FCR, reg | CSB5_FCR_DECODE_ALL); + + if (!request_mem_region(SCB2_ADDR, SCB2_WINDOW, scb2_map.name)) { + + printk(KERN_WARNING MODNAME + ": warning - can't reserve rom window, continuing\n"); + region_fail = 1; + } + + + scb2_ioaddr = ioremap_nocache(SCB2_ADDR, SCB2_WINDOW); + if (!scb2_ioaddr) { + printk(KERN_ERR MODNAME ": Failed to ioremap window!\n"); + if (!region_fail) + release_mem_region(SCB2_ADDR, SCB2_WINDOW); + return -ENOMEM; + } + + scb2_map.phys = SCB2_ADDR; + scb2_map.virt = scb2_ioaddr; + scb2_map.size = SCB2_WINDOW; + + simple_map_init(&scb2_map); + + + scb2_mtd = do_map_probe("cfi_probe", &scb2_map); + + if (!scb2_mtd) { + printk(KERN_ERR MODNAME ": flash probe failed!\n"); + iounmap(scb2_ioaddr); + if (!region_fail) + release_mem_region(SCB2_ADDR, SCB2_WINDOW); + return -ENODEV; + } + + scb2_mtd->owner = THIS_MODULE; + if (scb2_fixup_mtd(scb2_mtd) < 0) { + del_mtd_device(scb2_mtd); + map_destroy(scb2_mtd); + iounmap(scb2_ioaddr); + if (!region_fail) + release_mem_region(SCB2_ADDR, SCB2_WINDOW); + return -ENODEV; + } + + printk(KERN_NOTICE MODNAME ": chip size 0x%llx at offset 0x%llx\n", + (unsigned long long)scb2_mtd->size, + (unsigned long long)(SCB2_WINDOW - scb2_mtd->size)); + + add_mtd_device(scb2_mtd); + + return 0; +} + +static void __devexit +scb2_flash_remove(struct pci_dev *dev) +{ + if (!scb2_mtd) + return; + + + if (scb2_mtd->lock) + scb2_mtd->lock(scb2_mtd, 0, scb2_mtd->size); + + del_mtd_device(scb2_mtd); + map_destroy(scb2_mtd); + + iounmap(scb2_ioaddr); + scb2_ioaddr = NULL; + + if (!region_fail) + release_mem_region(SCB2_ADDR, SCB2_WINDOW); + pci_set_drvdata(dev, NULL); +} + +static struct pci_device_id scb2_flash_pci_ids[] = { + { + .vendor = PCI_VENDOR_ID_SERVERWORKS, + .device = PCI_DEVICE_ID_SERVERWORKS_CSB5, + .subvendor = PCI_ANY_ID, + .subdevice = PCI_ANY_ID + }, + { 0, } +}; + +static struct pci_driver scb2_flash_driver = { + .name = "Intel SCB2 BIOS Flash", + .id_table = scb2_flash_pci_ids, + .probe = scb2_flash_probe, + .remove = __devexit_p(scb2_flash_remove), +}; + +static int __init +scb2_flash_init(void) +{ + return pci_register_driver(&scb2_flash_driver); +} + +static void __exit +scb2_flash_exit(void) +{ + pci_unregister_driver(&scb2_flash_driver); +} + +module_init(scb2_flash_init); +module_exit(scb2_flash_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Tim Hockin "); +MODULE_DESCRIPTION("MTD map driver for Intel SCB2 BIOS Flash"); +MODULE_DEVICE_TABLE(pci, scb2_flash_pci_ids); diff --git a/pool/shard006/C/0120163_bwtmisc.c b/pool/shard006/C/0120163_bwtmisc.c new file mode 100644 index 0000000000000000000000000000000000000000..c35d684fd5fe7f01899d4a226f110d1e3201c113 --- /dev/null +++ b/pool/shard006/C/0120163_bwtmisc.c @@ -0,0 +1,230 @@ +/* The MIT License + + Copyright (c) 2008 Genome Research Ltd (GRL). + + 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. +*/ + +/* Contact: Heng Li */ + +#include +#include +#include +#include +#include "bntseq.h" +#include "utils.h" +#include "main.h" +#include "bwt.h" + +#ifdef _DIVBWT +#include "divsufsort.h" +#endif + +int is_bwt(ubyte_t *T, int n); + +int64_t bwa_seq_len(const char *fn_pac) +{ + FILE *fp; + int64_t pac_len; + ubyte_t c; + fp = xopen(fn_pac, "rb"); + fseek(fp, -1, SEEK_END); + pac_len = ftell(fp); + fread(&c, 1, 1, fp); + fclose(fp); + return (pac_len - 1) * 4 + (int)c; +} + +bwt_t *bwt_pac2bwt(const char *fn_pac, int use_is) +{ + bwt_t *bwt; + ubyte_t *buf, *buf2; + int i, pac_size; + FILE *fp; + + // initialization + bwt = (bwt_t*)calloc(1, sizeof(bwt_t)); + bwt->seq_len = bwa_seq_len(fn_pac); + bwt->bwt_size = (bwt->seq_len + 15) >> 4; + fp = xopen(fn_pac, "rb"); + + // prepare sequence + pac_size = (bwt->seq_len>>2) + ((bwt->seq_len&3) == 0? 0 : 1); + buf2 = (ubyte_t*)calloc(pac_size, 1); + fread(buf2, 1, pac_size, fp); + fclose(fp); + memset(bwt->L2, 0, 5 * 4); + buf = (ubyte_t*)calloc(bwt->seq_len + 1, 1); + for (i = 0; i < bwt->seq_len; ++i) { + buf[i] = buf2[i>>2] >> ((3 - (i&3)) << 1) & 3; + ++bwt->L2[1+buf[i]]; + } + for (i = 2; i <= 4; ++i) bwt->L2[i] += bwt->L2[i-1]; + free(buf2); + + // Burrows-Wheeler Transform + if (use_is) { + bwt->primary = is_bwt(buf, bwt->seq_len); + } else { +#ifdef _DIVBWT + bwt->primary = divbwt(buf, buf, 0, bwt->seq_len); +#else + err_fatal_simple("libdivsufsort is not compiled in."); +#endif + } + bwt->bwt = (u_int32_t*)calloc(bwt->bwt_size, 4); + for (i = 0; i < bwt->seq_len; ++i) + bwt->bwt[i>>4] |= buf[i] << ((15 - (i&15)) << 1); + free(buf); + return bwt; +} + +int bwa_pac2bwt(int argc, char *argv[]) +{ + bwt_t *bwt; + int c, use_is = 1; + while ((c = getopt(argc, argv, "d")) >= 0) { + switch (c) { + case 'd': use_is = 0; break; + default: return 1; + } + } + if (optind + 2 > argc) { + fprintf(stderr, "Usage: bwa pac2bwt [-d] \n"); + return 1; + } + bwt = bwt_pac2bwt(argv[optind], use_is); + bwt_dump_bwt(argv[optind+1], bwt); + bwt_destroy(bwt); + return 0; +} + +#define bwt_B00(b, k) ((b)->bwt[(k)>>4]>>((~(k)&0xf)<<1)&3) + +void bwt_bwtupdate_core(bwt_t *bwt) +{ + bwtint_t i, k, c[4], n_occ; + uint32_t *buf; + + n_occ = (bwt->seq_len + OCC_INTERVAL - 1) / OCC_INTERVAL + 1; + bwt->bwt_size += n_occ * sizeof(bwtint_t); // the new size + buf = (uint32_t*)calloc(bwt->bwt_size, 4); // will be the new bwt + c[0] = c[1] = c[2] = c[3] = 0; + for (i = k = 0; i < bwt->seq_len; ++i) { + if (i % OCC_INTERVAL == 0) { + memcpy(buf + k, c, sizeof(bwtint_t) * 4); + k += sizeof(bwtint_t); // in fact: sizeof(bwtint_t)=4*(sizeof(bwtint_t)/4) + } + if (i % 16 == 0) buf[k++] = bwt->bwt[i/16]; // 16 == sizeof(uint32_t)/2 + ++c[bwt_B00(bwt, i)]; + } + // the last element + memcpy(buf + k, c, sizeof(bwtint_t) * 4); + xassert(k + sizeof(bwtint_t) == bwt->bwt_size, "inconsistent bwt_size"); + // update bwt + free(bwt->bwt); bwt->bwt = buf; +} + +int bwa_bwtupdate(int argc, char *argv[]) +{ + bwt_t *bwt; + if (argc < 2) { + fprintf(stderr, "Usage: bwa bwtupdate \n"); + return 1; + } + bwt = bwt_restore_bwt(argv[1]); + bwt_bwtupdate_core(bwt); + bwt_dump_bwt(argv[1], bwt); + bwt_destroy(bwt); + return 0; +} + +const int nst_color_space_table[] = { 4, 0, 0, 1, 0, 2, 3, 4, 0, 3, 2, 4, 1, 4, 4, 4}; + +/* this function is not memory efficient, but this will make life easier + Ideally we should also change .amb files as one 'N' in the nucleotide + sequence leads to two ambiguous colors. I may do this later... */ +uint8_t *bwa_pac2cspac_core(const bntseq_t *bns) +{ + uint8_t *pac, *cspac; + bwtint_t i; + int c1, c2; + pac = (uint8_t*)calloc(bns->l_pac/4 + 1, 1); + cspac = (uint8_t*)calloc(bns->l_pac/4 + 1, 1); + fread(pac, 1, bns->l_pac/4+1, bns->fp_pac); + rewind(bns->fp_pac); + c1 = pac[0]>>6; cspac[0] = c1<<6; + for (i = 1; i < bns->l_pac; ++i) { + c2 = pac[i>>2] >> (~i&3)*2 & 3; + cspac[i>>2] |= nst_color_space_table[(1< \n"); + return 1; + } + bns = bns_restore(argv[1]); + cspac = bwa_pac2cspac_core(bns); + bns_dump(bns, argv[2]); + // now write cspac + str = (char*)calloc(strlen(argv[2]) + 5, 1); + strcat(strcpy(str, argv[2]), ".pac"); + fp = xopen(str, "wb"); + fwrite(cspac, 1, bns->l_pac/4 + 1, fp); + ct = bns->l_pac % 4; + fwrite(&ct, 1, 1, fp); + fclose(fp); + bns_destroy(bns); + free(cspac); + return 0; +} + +int bwa_bwt2sa(int argc, char *argv[]) +{ + bwt_t *bwt; + int c, sa_intv = 32; + while ((c = getopt(argc, argv, "i:")) >= 0) { + switch (c) { + case 'i': sa_intv = atoi(optarg); break; + default: return 1; + } + } + if (optind + 2 > argc) { + fprintf(stderr, "Usage: bwa bwt2sa [-i %d] \n", sa_intv); + return 1; + } + bwt = bwt_restore_bwt(argv[optind]); + bwt_cal_sa(bwt, sa_intv); + bwt_dump_sa(argv[optind+1], bwt); + bwt_destroy(bwt); + return 0; +} diff --git a/pool/shard006/C/0120165_GPIOL_Driver.c b/pool/shard006/C/0120165_GPIOL_Driver.c new file mode 100644 index 0000000000000000000000000000000000000000..2c43a3d77fed50704e4d6411680f9c80b57395d5 --- /dev/null +++ b/pool/shard006/C/0120165_GPIOL_Driver.c @@ -0,0 +1,161 @@ +/*******************************************ÉêÃ÷*************************************** +±¾Ç¶Èëʽ²Ù×÷ϵͳδ¾­ÊÚȨ£¬½ûÖ¹Ó¦ÓÃÓÚÈκÎÉÌÒµÓÃ; +°æÈ¨ËùÓУ¬ÇÖȨ±Ø¾¿ +http://www.trtos.com/ +**************************************************************************************/ +#include +#include +#include + +uint8 DeviceId_GPIO=DeviceNull; +/************************************************************************************** + Func: ¹ÒÔØGPIOÉ豸 + Time: 2016-11-03 + Ver.: V1.0 + Note; +**************************************************************************************/ +void DeviceMount_GPIO(const GPIO_ListStruct *List) +{ + DeviceId_GPIO=DeviceId_Index++; + Tos_Device_Tab[DeviceId_GPIO].DeviceId=DeviceId_GPIO; + Tos_Device_Tab[DeviceId_GPIO].DeviceName="GPIO"; + Tos_Device_Tab[DeviceId_GPIO].DeviceOwnerId=Null; + Tos_Device_Tab[DeviceId_GPIO].DeviceVirtue=DV_IOList; + Tos_Device_Tab[DeviceId_GPIO].DeviceState=NotBusy; + Tos_Device_Tab[DeviceId_GPIO].Init=GPIO_InitList; + Tos_Device_Tab[DeviceId_GPIO].Note=(uintbus)List; + Tos_Device_Tab[DeviceId_GPIO].Write=Null; + Tos_Device_Tab[DeviceId_GPIO].Read=Null; + Tos_Device_Tab[DeviceId_GPIO].Exit=Null; +} +/************************************************************************************** + Func: ÉèÖÃGPIOµçƽ + Time: 2016-11-03 + Ver.: V1.0 + Note;°´ÕÕmap +**************************************************************************************/ +void GPIO_Set(const GPIO_ListStruct List,uint8 H) +{ + if(H)GPIO_SetBits(List.GPIOx,List.GPIO_Pin); + else GPIO_ResetBits(List.GPIOx,List.GPIO_Pin); +} +/************************************************************************************** + Func: ÉèÖÃGPIOµçƽ + Time: 2016-11-03 + Ver.: V1.0 + Note;°´ÕÕË÷Òý +**************************************************************************************/ +void GPIO_SetIndex(uint8 i,uint8 H) +{ + const GPIO_ListStruct *List; + List=(const GPIO_ListStruct *)(Tos_Device_Tab[DeviceId_GPIO].Note); + GPIO_Set(List[i],H); +} +/************************************************************************************** + Func: »ñÈ¡GPIO״̬ + Time: 2016-11-03 + Ver.: V1.0 + Note;ÖØÅÅ +**************************************************************************************/ +void GPIO_SetAll(uint32 D) +{ + uint8 i; + const GPIO_ListStruct *List; + List=(const GPIO_ListStruct *)(Tos_Device_Tab[DeviceId_GPIO].Note); + for(i=0;i<0xff;i++) + { + if(!List[i].GPIO_Speed)break; + GPIO_Set(List[i],(BOOL)(D&0x01)); + D>>=1; + } +} +/************************************************************************************** + Func: »ñÈ¡GPIO״̬ + Time: 2016-11-03 + Ver.: V1.0 + Note;µ¥¸ö +**************************************************************************************/ +BOOL GPIO_Get(const GPIO_ListStruct List) +{ + if(GPIO_ReadInputDataBit(List.GPIOx,List.GPIO_Pin))return True; + return False; +} +/************************************************************************************** + Func: »ñÈ¡GPIO״̬ + Time: 2016-11-03 + Ver.: V1.0 + Note;ÖØÅÅ +**************************************************************************************/ +uint32 GPIO_GetAll() +{ + uint8 i; + uint32 D=0; + const GPIO_ListStruct *List; + List=(const GPIO_ListStruct *)(Tos_Device_Tab[DeviceId_GPIO].Note); + for(i=0;i<0xff;i++) + { + if(!List[i].GPIO_Speed)break; + if(GPIO_ReadInputDataBit(List[i].GPIOx,List[i].GPIO_Pin))D|=BIT(i); + else D&=~BIT(i); + } + return D; +} +/************************************************************************************** + Func: »ñÈ¡ + Time: 2016-11-03 + Ver.: V1.0 + Note;°´ÕÕË÷Òý +**************************************************************************************/ +BOOL GPIO_GetIndex(uint8 i) +{ + const GPIO_ListStruct *List; + List=(const GPIO_ListStruct *)(Tos_Device_Tab[DeviceId_GPIO].Note); + if(GPIO_ReadInputDataBit(List[i].GPIOx,List[i].GPIO_Pin))return True; + return False; +} +/************************************************************************************** + Func: ÉèÖö˿Úģʽ + Time: 2016-11-03 + Ver.: V1.0 + Note; + GPIO_Mode_AIN = 0x0, + GPIO_Mode_IN_FLOATING = 0x04, + GPIO_Mode_IPD = 0x28, + GPIO_Mode_IPU = 0x48, + GPIO_Mode_Out_OD = 0x14, + GPIO_Mode_Out_PP = 0x10, + GPIO_Mode_AF_OD = 0x1C, + GPIO_Mode_AF_PP = 0x18 +**************************************************************************************/ +void GPIO_Set_Mode(const GPIO_ListStruct Pin_Map,GPIOMode_TypeDef Mode) +{ + + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.GPIO_Pin = Pin_Map.GPIO_Pin; + GPIO_InitStructure.GPIO_Mode = Mode ; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; + GPIO_Init(Pin_Map.GPIOx, &GPIO_InitStructure); +} +//void GPIO_ExitInit(const GPIO_InitStruct Pin_Map,FunctionalState En) +//{ +// NVIC_InitTypeDef NVIC_InitStructure; +// GPIO_InitTypeDef GPIO_InitStructure; +// EXTI_InitTypeDef EXTI_InitStructure; + +// GPIO_InitStructure.GPIO_Pin =Pin_Map.GPIO_Pin; +// GPIO_InitStructure.GPIO_Mode = Pin_Map.GPIO_Mode; +// GPIO_Init(Pin_Map.GPIOx, &GPIO_InitStructure); + +// GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource9); +// EXTI_InitStructure.EXTI_Line = Pin_Map.GPIO_Pin; +// EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; +// EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; +// EXTI_InitStructure.EXTI_LineCmd = ENABLE; +// EXTI_Init(&EXTI_InitStructure); + +// NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); +// NVIC_InitStructure.NVIC_IRQChannel =EXTI9_5_IRQn; +// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; +// NVIC_InitStructure.NVIC_IRQChannelCmd = En; +// NVIC_Init(&NVIC_InitStructure); +//} diff --git a/pool/shard006/C/0120166_main.c b/pool/shard006/C/0120166_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5ed0015c45816e3211f073cda62b5eaef56fc7e4 --- /dev/null +++ b/pool/shard006/C/0120166_main.c @@ -0,0 +1,153 @@ +/** + ****************************************************************************** + * @file WWDG/main.c + * @author MCD Application Team + * @version V3.1.2 + * @date 09/28/2009 + * @brief Main program body. + ****************************************************************************** + * @copy + * + * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS + * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE + * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY + * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING + * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE + * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. + * + *

© COPYRIGHT 2009 STMicroelectronics

+ */ + + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f10x.h" +#include "stm32_eval.h" + +/** @addtogroup STM32F10x_StdPeriph_Examples + * @{ + */ + +/** @addtogroup WWDG_Example + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +ErrorStatus HSEStartUpStatus; + +/* Private function prototypes -----------------------------------------------*/ +void NVIC_Configuration(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program. + * @param None + * @retval None + */ +int main(void) +{ + /* Setup the microcontroller system. Initialize the Embedded Flash Interface, + initialize the PLL and update the SystemFrequency variable. */ + SystemInit(); + + /* Initialize LED1 and Key Button mounted on STM3210X-EVAL board */ + STM_EVAL_LEDInit(LED1); + STM_EVAL_LEDInit(LED2); + STM_EVAL_PBInit(Button_KEY, Mode_EXTI); + + + /* Check if the system has resumed from WWDG reset */ + if (RCC_GetFlagStatus(RCC_FLAG_WWDGRST) != RESET) + { + /* WWDGRST flag set */ + /* Turn on LED1 */ + STM_EVAL_LEDOn(LED1); + + /* Clear reset flags */ + RCC_ClearFlag(); + } + else + { + /* WWDGRST flag is not set */ + /* Turn off LED1 */ + STM_EVAL_LEDOff(LED1); + } + + /* NVIC configuration */ + NVIC_Configuration(); + + /* WWDG configuration */ + /* Enable WWDG clock */ + RCC_APB1PeriphClockCmd(RCC_APB1Periph_WWDG, ENABLE); + + /* WWDG clock counter = (PCLK1/4096)/8 = 1099 Hz (~910 µs) */ + WWDG_SetPrescaler(WWDG_Prescaler_8); + + /* Set Window value to 65 */ + WWDG_SetWindowValue(65); + + /* Enable WWDG and set counter value to 127, WWDG timeout = ~910 µs * 64 = 58.25 ms */ + WWDG_Enable(127); + + /* Clear EWI flag */ + WWDG_ClearFlag(); + + /* Enable EW interrupt */ + WWDG_EnableIT(); + + while (1) + { + } +} + +/** + * @brief Configures NVIC. + * @param None + * @retval None + */ +void NVIC_Configuration(void) +{ + NVIC_InitTypeDef NVIC_InitStructure; + + /* 2 bits for Preemption Priority and 2 bits for Sub Priority */ + NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); + + NVIC_InitStructure.NVIC_IRQChannel = WWDG_IRQn; + NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; + NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + + NVIC_Init(&NVIC_InitStructure); +} + +#ifdef USE_FULL_ASSERT +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t* file, uint32_t line) +{ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + + /* Infinite loop */ + while (1) + {} +} +#endif + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard006/C/0120167_gstgsmdec.c b/pool/shard006/C/0120167_gstgsmdec.c new file mode 100644 index 0000000000000000000000000000000000000000..fc182cd287abf3d1ee1c9bd616dc3cef8bae2d0f --- /dev/null +++ b/pool/shard006/C/0120167_gstgsmdec.c @@ -0,0 +1,246 @@ +/* + * Farsight + * GStreamer GSM encoder + * Copyright (C) 2005 Philippe Khalaf + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include + +#include "gstgsmdec.h" + +GST_DEBUG_CATEGORY_STATIC (gsmdec_debug); +#define GST_CAT_DEFAULT (gsmdec_debug) + +/* GSMDec signals and args */ +enum +{ + /* FILL ME */ + LAST_SIGNAL +}; + +enum +{ + /* FILL ME */ + ARG_0 +}; + +static gboolean gst_gsmdec_start (GstAudioDecoder * dec); +static gboolean gst_gsmdec_stop (GstAudioDecoder * dec); +static gboolean gst_gsmdec_set_format (GstAudioDecoder * dec, GstCaps * caps); +static GstFlowReturn gst_gsmdec_parse (GstAudioDecoder * dec, + GstAdapter * adapter, gint * offset, gint * length); +static GstFlowReturn gst_gsmdec_handle_frame (GstAudioDecoder * dec, + GstBuffer * in_buf); + +/*static guint gst_gsmdec_signals[LAST_SIGNAL] = { 0 }; */ + +#define ENCODED_SAMPLES 160 + +static GstStaticPadTemplate gsmdec_sink_template = + GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("audio/x-gsm, rate = (int) 8000, channels = (int) 1; " + "audio/ms-gsm, rate = (int) [1, MAX], channels = (int) 1") + ); + +static GstStaticPadTemplate gsmdec_src_template = +GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("audio/x-raw, " + "format = (string) " GST_AUDIO_NE (S16) ", " + "layout = (string) interleaved, " + "rate = (int) [1, MAX], channels = (int) 1") + ); + +G_DEFINE_TYPE (GstGSMDec, gst_gsmdec, GST_TYPE_AUDIO_DECODER); + +static void +gst_gsmdec_class_init (GstGSMDecClass * klass) +{ + GstElementClass *element_class; + GstAudioDecoderClass *base_class; + + element_class = (GstElementClass *) klass; + base_class = (GstAudioDecoderClass *) klass; + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gsmdec_sink_template)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gsmdec_src_template)); + gst_element_class_set_static_metadata (element_class, "GSM audio decoder", + "Codec/Decoder/Audio", + "Decodes GSM encoded audio", "Philippe Khalaf "); + + base_class->start = GST_DEBUG_FUNCPTR (gst_gsmdec_start); + base_class->stop = GST_DEBUG_FUNCPTR (gst_gsmdec_stop); + base_class->set_format = GST_DEBUG_FUNCPTR (gst_gsmdec_set_format); + base_class->parse = GST_DEBUG_FUNCPTR (gst_gsmdec_parse); + base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_gsmdec_handle_frame); + + GST_DEBUG_CATEGORY_INIT (gsmdec_debug, "gsmdec", 0, "GSM Decoder"); +} + +static void +gst_gsmdec_init (GstGSMDec * gsmdec) +{ +} + +static gboolean +gst_gsmdec_start (GstAudioDecoder * dec) +{ + GstGSMDec *gsmdec = GST_GSMDEC (dec); + + GST_DEBUG_OBJECT (dec, "start"); + + gsmdec->state = gsm_create (); + + return TRUE; +} + +static gboolean +gst_gsmdec_stop (GstAudioDecoder * dec) +{ + GstGSMDec *gsmdec = GST_GSMDEC (dec); + + GST_DEBUG_OBJECT (dec, "stop"); + + gsm_destroy (gsmdec->state); + + return TRUE; +} + +static gboolean +gst_gsmdec_set_format (GstAudioDecoder * dec, GstCaps * caps) +{ + GstGSMDec *gsmdec; + GstStructure *s; + gboolean ret = FALSE; + gint rate; + GstAudioInfo info; + + gsmdec = GST_GSMDEC (dec); + + s = gst_caps_get_structure (caps, 0); + if (s == NULL) + goto wrong_caps; + + /* figure out if we deal with plain or MSGSM */ + if (gst_structure_has_name (s, "audio/x-gsm")) + gsmdec->use_wav49 = 0; + else if (gst_structure_has_name (s, "audio/ms-gsm")) + gsmdec->use_wav49 = 1; + else + goto wrong_caps; + + gsmdec->needed = 33; + + if (!gst_structure_get_int (s, "rate", &rate)) { + GST_WARNING_OBJECT (gsmdec, "missing sample rate parameter from sink caps"); + goto beach; + } + + /* MSGSM needs different framing */ + gsm_option (gsmdec->state, GSM_OPT_WAV49, &gsmdec->use_wav49); + + /* Setting up src caps based on the input sample rate. */ + gst_audio_info_init (&info); + gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, rate, 1, NULL); + + ret = gst_audio_decoder_set_output_format (dec, &info); + + return ret; + + /* ERRORS */ +wrong_caps: + + GST_ERROR_OBJECT (gsmdec, "invalid caps received"); + +beach: + + return ret; +} + +static GstFlowReturn +gst_gsmdec_parse (GstAudioDecoder * dec, GstAdapter * adapter, + gint * offset, gint * length) +{ + GstGSMDec *gsmdec = GST_GSMDEC (dec); + guint size; + + size = gst_adapter_available (adapter); + g_return_val_if_fail (size > 0, GST_FLOW_ERROR); + + /* WAV49 requires alternating 33 and 32 bytes of input */ + if (gsmdec->use_wav49) { + gsmdec->needed = (gsmdec->needed == 33 ? 32 : 33); + } + + if (size < gsmdec->needed) + return GST_FLOW_EOS; + + *offset = 0; + *length = gsmdec->needed; + + return GST_FLOW_OK; +} + +static GstFlowReturn +gst_gsmdec_handle_frame (GstAudioDecoder * dec, GstBuffer * buffer) +{ + GstGSMDec *gsmdec; + gsm_byte *data; + GstFlowReturn ret = GST_FLOW_OK; + GstBuffer *outbuf; + GstMapInfo map, omap; + + /* no fancy draining */ + if (G_UNLIKELY (!buffer)) + return GST_FLOW_OK; + + gsmdec = GST_GSMDEC (dec); + + /* always the same amount of output samples */ + outbuf = gst_buffer_new_and_alloc (ENCODED_SAMPLES * sizeof (gsm_signal)); + + /* now encode frame into the output buffer */ + gst_buffer_map (buffer, &map, GST_MAP_READ); + gst_buffer_map (outbuf, &omap, GST_MAP_WRITE); + data = (gsm_byte *) map.data; + if (gsm_decode (gsmdec->state, data, (gsm_signal *) omap.data) < 0) { + /* invalid frame */ + GST_AUDIO_DECODER_ERROR (gsmdec, 1, STREAM, DECODE, (NULL), + ("tried to decode an invalid frame"), ret); + gst_buffer_unmap (outbuf, &omap); + gst_buffer_unref (outbuf); + outbuf = NULL; + } else { + gst_buffer_unmap (outbuf, &omap); + } + + gst_buffer_unmap (buffer, &map); + + gst_audio_decoder_finish_frame (dec, outbuf, 1); + + return ret; +} diff --git a/pool/shard006/C/0120168_main.c b/pool/shard006/C/0120168_main.c new file mode 100644 index 0000000000000000000000000000000000000000..41ed988ba76fdf0dcdf2afe5a33e087f274fcebc --- /dev/null +++ b/pool/shard006/C/0120168_main.c @@ -0,0 +1,73 @@ +#include + +serialPort_t * Serial1; + +void SetSysClock(void); + +#ifndef EXTERNAL_DEBUG +void debug(const char * fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + + char buf[100]; + + vsprintf(buf, fmt, ap); + + for (char * p = buf; *p; p++) + serialWrite(Serial1, *p); + + va_end(ap); + + //while (!isSerialTransmitBufferEmpty(Serial1)); +} +#endif + +int main(void) { + +#if defined(STM32F40_41xxx) || defined (STM32F411xE) + SetSysClock(); +#endif + + systemInit(); + + // initialize IO (needed for all IO operations) + IOInitGlobal(); + + ledInit(); + + timerInit(); // timer must be initialized before any channel is allocated + + Serial1 = usbVcpOpen(); + + timerStart(); + + setup(); + + /// supports periodic reboot check + //uint32_t dbg_start_msec = 0; + + while (true) { + +#ifndef EXTERNAL_DEBUG + static uint32_t dbg_start_msec; + // support reboot from host computer + if (millis()-dbg_start_msec > 100) { + dbg_start_msec = millis(); + while (serialRxBytesWaiting(Serial1)) { + uint8_t c = serialRead(Serial1); + if (c == 'R') + systemResetToBootloader(); + } + } +#endif + + loop(); + } +} + +void HardFault_Handler(void) { + while(1) { + } +} diff --git a/pool/shard006/C/0120172_main.c b/pool/shard006/C/0120172_main.c new file mode 100644 index 0000000000000000000000000000000000000000..32425319ed3c5afc59a9516d1f434a208ad59fbf --- /dev/null +++ b/pool/shard006/C/0120172_main.c @@ -0,0 +1,180 @@ +/* + * vim:ts=4:sw=4:expandtab + * + * i3bar - an xcb-based status- and ws-bar for i3 + * © 2010 Axel Wagner and contributors (see also: LICENSE) + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common.h" + +/* + * Having verboselog(), errorlog() and debuglog() is necessary when using libi3. + * + */ +void verboselog(char *fmt, ...) { + va_list args; + + va_start(args, fmt); + vfprintf(stdout, fmt, args); + va_end(args); +} + +void errorlog(char *fmt, ...) { + va_list args; + + va_start(args, fmt); + vfprintf(stderr, fmt, args); + va_end(args); +} + +void debuglog(char *fmt, ...) { +} + +/* + * Glob path, i.e. expand ~ + * + */ +char *expand_path(char *path) { + static glob_t globbuf; + if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0) { + ELOG("glob() failed\n"); + exit(EXIT_FAILURE); + } + char *result = sstrdup(globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path); + globfree(&globbuf); + return result; +} + +void print_usage(char *elf_name) { + printf("Usage: %s -b bar_id [-s sock_path] [-h] [-v]\n", elf_name); + printf("\n"); + printf("-b, --bar_id \tBar ID for which to get the configuration\n"); + printf("-s, --socket \tConnect to i3 via \n"); + printf("-h, --help Display this help message and exit\n"); + printf("-v, --version Display version number and exit\n"); + printf("\n"); + printf(" PLEASE NOTE that i3bar will be automatically started by i3\n" + " as soon as there is a 'bar' configuration block in your\n" + " config file. You should never need to start it manually.\n"); + printf("\n"); +} + +/* + * We watch various signals, that are there to make our application stop. + * If we get one of those, we ev_unloop() and invoke the cleanup routines + * in main() with that + * + */ +void sig_cb(struct ev_loop *loop, ev_signal *watcher, int revents) { + switch (watcher->signum) { + case SIGTERM: + DLOG("Got a SIGTERM, stopping\n"); + break; + case SIGINT: + DLOG("Got a SIGINT, stopping\n"); + break; + case SIGHUP: + DLOG("Got a SIGHUP, stopping\n"); + } + ev_unloop(main_loop, EVUNLOOP_ALL); +} + +int main(int argc, char **argv) { + int opt; + int option_index = 0; + char *socket_path = getenv("I3SOCK"); + char *i3_default_sock_path = "/tmp/i3-ipc.sock"; + + /* Initialize the standard config to use 0 as default */ + memset(&config, '\0', sizeof(config_t)); + + static struct option long_opt[] = { + {"socket", required_argument, 0, 's'}, + {"bar_id", required_argument, 0, 'b'}, + {"help", no_argument, 0, 'h'}, + {"version", no_argument, 0, 'v'}, + {NULL, 0, 0, 0}}; + + while ((opt = getopt_long(argc, argv, "b:s:hv", long_opt, &option_index)) != -1) { + switch (opt) { + case 's': + socket_path = expand_path(optarg); + break; + case 'v': + printf("i3bar version " I3_VERSION " © 2010 Axel Wagner and contributors\n"); + exit(EXIT_SUCCESS); + break; + case 'b': + config.bar_id = sstrdup(optarg); + break; + default: + print_usage(argv[0]); + exit(EXIT_SUCCESS); + break; + } + } + + if (!config.bar_id) { + /* TODO: maybe we want -f which will automatically ask i3 for the first + * configured bar (and error out if there are too many)? */ + ELOG("No bar_id passed. Please let i3 start i3bar or specify --bar_id\n"); + exit(EXIT_FAILURE); + } + + main_loop = ev_default_loop(0); + + char *atom_sock_path = init_xcb_early(); + + if (socket_path == NULL) { + socket_path = atom_sock_path; + } + + if (socket_path == NULL) { + ELOG("No socket path specified, default to %s\n", i3_default_sock_path); + socket_path = expand_path(i3_default_sock_path); + } + + init_outputs(); + if (init_connection(socket_path)) { + /* Request the bar configuration. When it arrives, we fill the config array. */ + i3_send_msg(I3_IPC_MESSAGE_TYPE_GET_BAR_CONFIG, config.bar_id); + } + + /* We listen to SIGTERM/QUIT/INT and try to exit cleanly, by stopping the main loop. + * We only need those watchers on the stack, so putting them on the stack saves us + * some calls to free() */ + ev_signal *sig_term = smalloc(sizeof(ev_signal)); + ev_signal *sig_int = smalloc(sizeof(ev_signal)); + ev_signal *sig_hup = smalloc(sizeof(ev_signal)); + + ev_signal_init(sig_term, &sig_cb, SIGTERM); + ev_signal_init(sig_int, &sig_cb, SIGINT); + ev_signal_init(sig_hup, &sig_cb, SIGHUP); + + ev_signal_start(main_loop, sig_term); + ev_signal_start(main_loop, sig_int); + ev_signal_start(main_loop, sig_hup); + + /* From here on everything should run smooth for itself, just start listening for + * events. We stop simply stop the event loop, when we are finished */ + ev_loop(main_loop, 0); + + kill_child(); + + clean_xcb(); + ev_default_destroy(); + + free_workspaces(); + + return 0; +} diff --git a/pool/shard006/C/0120173_logger.c b/pool/shard006/C/0120173_logger.c new file mode 100644 index 0000000000000000000000000000000000000000..b9fb134ecb9bd715fee66392fd8d62943e118454 --- /dev/null +++ b/pool/shard006/C/0120173_logger.c @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2010-2016, Dhonek(TM) Labs. All Rights Reserved. + * + * + * This copyrighted material is made available to anyone wishing to use, modify, + * copy, or redistribute it subject to the terms and conditions of the GNU + * Lesser General Public License, as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License + * for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this distribution; if not, write to: + * Free Software Foundation, Inc. + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301 USA + * + * or, see . + */ + +#include "platform.h" +#include "ezlogger.h" +#include +#include +#include +#include +#include +#include +#include + +/* TODO: matched the log level with the user defined level in config */ +/* TODO: make logging API available to user */ +char* LVL[5] = {"TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR"}; + +static inline void dnk_log(dnkloglevel lvl, char * message){ + time_t t; + struct tm *tmp; + + t = time(NULL); + tmp = localtime(&t); + char buf[255]; + strftime(buf, sizeof(buf), "%d %b %Y %H:%M:%S", tmp); /* "at %s, line %d", __FILE__, __LINE__*/ + fprintf(stderr, "[%s] - [%s] - %s\n", LVL[lvl], buf, message); +} + +static void dnk_trace(char * fmt, ...){ + char message[1024]; + va_list args; + + va_start(args, fmt); + vsprintf(message, fmt, args); + va_end(args); + + dnk_log(TRACE, message); +} + +static void dnk_debug(char * fmt, ...){ + char message[1024]; + va_list args; + + va_start(args, fmt); + vsprintf(message, fmt, args); + va_end(args); + dnk_log(DEBUG, message); +} + +static void dnk_info(char * fmt, ...){ + char message[1024]; + va_list args; + + va_start(args, fmt); + vsprintf(message, fmt, args); + va_end(args); + dnk_log(INFO, message); +} + +static void dnk_warn(char * fmt, ...){ + char message[1024]; + va_list args; + + va_start(args, fmt); + vsprintf(message, fmt, args); + va_end(args); + dnk_log(WARN, message); +} + +static void dnk_error(char * fmt, ...){ + char message[1024]; + va_list args; + + va_start(args, fmt); + vsprintf(message, fmt, args); + va_end(args); + dnk_log(ERROR, message); +} + +static void dnk_aio_log(dnkloglevel lvl, char * message){ + char buf[4096]; + int retval; + ssize_t nbytes; + struct aiocb cb; + + bzero( &cb, sizeof (struct aiocb)); + bzero( &buf, sizeof (buf)); + + cb.aio_fildes = open( "/dev/null", O_RDWR); + cb.aio_offset = 0; + cb.aio_buf = (void *) buf; + cb.aio_nbytes = sizeof (buf); + cb.aio_sigevent.sigev_notify = SIGEV_NONE; + retval = aio_write( &cb ); + if (retval) perror("aio_write:"); + /* continue processing */ + + /* wait for completion */ + while ( (retval = aio_error( &cb) ) == EINPROGRESS) ; + /* free the aiocb */ + nbytes = aio_return( &cb); +} + +dnklogger dnk_logger = { + .trace = dnk_trace, + .debug = dnk_debug, + .info = dnk_info, + .warn = dnk_warn, + .error = dnk_error +}; + + diff --git a/pool/shard006/C/0120176_infutil.c b/pool/shard006/C/0120176_infutil.c new file mode 100644 index 0000000000000000000000000000000000000000..22af3b8591b26116befe4730d5cb62957ee22fdc --- /dev/null +++ b/pool/shard006/C/0120176_infutil.c @@ -0,0 +1,88 @@ +/* inflate_util.c -- data and routines common to blocks and codes + * Copyright (C) 1995-2002 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "infblock.h" +#include "inftrees.h" +#include "infcodes.h" +#include "infutil.h" + +#ifndef NO_INFLATE_MASK + +/* And'ing with mask[n] masks the lower n bits */ +local const uInt inflate_mask[17] = { + 0x0000, + 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, + 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff +}; + +#endif + +/* copy as much as possible from the sliding window to the output area */ +local int inflate_flush( /* s, z, r) */ +inflate_blocks_statef *s, +z_streamp z, +int r ) +{ + uInt n; + Bytef *p; + Bytef *q; + + /* local copies of source and destination pointers */ + p = z->next_out; + q = s->read; + + /* compute number of bytes to copy as far as end of window */ + n = (uInt)((q <= s->write ? s->write : s->end) - q); + if (n > z->avail_out) n = z->avail_out; + if (n && r == Z_BUF_ERROR) r = Z_OK; + + /* update counters */ + z->avail_out -= n; + z->total_out += n; + + /* update check information */ + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(s->check, q, n); + + /* copy as far as end of window */ + zmemcpy(p, q, n); + p += n; + q += n; + + /* see if more to copy at beginning of window */ + if (q == s->end) + { + /* wrap pointers */ + q = s->window; + if (s->write == s->end) + s->write = s->window; + + /* compute bytes to copy */ + n = (uInt)(s->write - q); + if (n > z->avail_out) n = z->avail_out; + if (n && r == Z_BUF_ERROR) r = Z_OK; + + /* update counters */ + z->avail_out -= n; + z->total_out += n; + + /* update check information */ + if (s->checkfn != Z_NULL) + z->adler = s->check = (*s->checkfn)(s->check, q, n); + + /* copy */ + zmemcpy(p, q, n); + p += n; + q += n; + } + + /* update pointers */ + z->next_out = p; + s->read = q; + + /* done */ + return r; +} diff --git a/pool/shard006/C/0120180_pdf_page.c b/pool/shard006/C/0120180_pdf_page.c new file mode 100644 index 0000000000000000000000000000000000000000..822d12556a57b062e4b3fc3e0482c5f0dac434fa --- /dev/null +++ b/pool/shard006/C/0120180_pdf_page.c @@ -0,0 +1,266 @@ +#include +#include + +static fz_error * +runone(pdf_csi *csi, pdf_xref *xref, fz_obj *rdb, fz_obj *stmref) +{ + fz_error *error; + fz_stream *stm; + + pdf_logpage("simple content stream\n"); + + error = pdf_openstream(&stm, xref, fz_tonum(stmref), fz_togen(stmref)); + if (error) + return error; + + error = pdf_runcsi(csi, xref, rdb, stm); + + fz_dropstream(stm); + + return error; +} + +/* we need to combine all sub-streams into one for pdf_runcsi + * to deal with split dictionaries etc. + */ +static fz_error * +runmany(pdf_csi *csi, pdf_xref *xref, fz_obj *rdb, fz_obj *list) +{ + fz_error *error; + fz_stream *file; + fz_buffer *big; + fz_buffer *one; + fz_obj *stm; + int n; + int i; + + pdf_logpage("multiple content streams: %d\n", fz_arraylen(list)); + + error = fz_newbuffer(&big, 32 * 1024); + if (error) + return error; + + error = fz_openwbuffer(&file, big); + if (error) + goto cleanup0; + + for (i = 0; i < fz_arraylen(list); i++) + { + /* TODO dont use loadstream here */ + + stm = fz_arrayget(list, i); + error = pdf_loadstream(&one, xref, fz_tonum(stm), fz_togen(stm)); + if (error) + goto cleanup1; + + n = fz_write(file, one->rp, one->wp - one->rp); + + fz_dropbuffer(one); + + if (n == -1) + { + error = fz_ioerror(file); + goto cleanup1; + } + + fz_printstr(file, " "); + } + + fz_dropstream(file); + + error = fz_openrbuffer(&file, big); + if (error) + goto cleanup0; + + error = pdf_runcsi(csi, xref, rdb, file); + + fz_dropstream(file); + fz_dropbuffer(big); + + return error; + +cleanup1: + fz_dropstream(file); +cleanup0: + fz_dropbuffer(big); + return error; +} + +static fz_error * +loadpagecontents(fz_tree **treep, pdf_xref *xref, fz_obj *rdb, fz_obj *ref) +{ + fz_error *error; + fz_obj *obj; + pdf_csi *csi; + + error = pdf_newcsi(&csi, 0); + if (error) + return error; + + if (fz_isindirect(ref)) + { + error = pdf_loadindirect(&obj, xref, ref); + if (error) + return error; + + if (fz_isarray(obj)) + { + if (fz_arraylen(obj) == 1) + error = runone(csi, xref, rdb, fz_arrayget(obj, 0)); + else + error = runmany(csi, xref, rdb, obj); + } + else + error = runone(csi, xref, rdb, ref); + + fz_dropobj(obj); + if (error) + goto cleanup; + } + + else if (fz_isarray(ref)) + { + if (fz_arraylen(ref) == 1) + error = runone(csi, xref, rdb, fz_arrayget(ref, 0)); + else + error = runmany(csi, xref, rdb, ref); + } + + *treep = csi->tree; + csi->tree = nil; + error = nil; + +cleanup: + pdf_dropcsi(csi); + return error; +} + +fz_error * +pdf_loadpage(pdf_page **pagep, pdf_xref *xref, fz_obj *dict) +{ + fz_error *error; + fz_obj *obj; + pdf_page *page; + fz_obj *rdb; + pdf_comment *comments = nil; + pdf_link *links = nil; + fz_tree *tree; + fz_rect bbox; + int rotate; + + pdf_logpage("load page {\n"); + + /* + * Sort out page media + */ + + obj = fz_dictgets(dict, "CropBox"); + if (!obj) + obj = fz_dictgets(dict, "MediaBox"); + if (!fz_isarray(obj)) + return fz_throw("syntaxerror: Page missing MediaBox"); + bbox = pdf_torect(obj); + + pdf_logpage("bbox [%g %g %g %g]\n", + bbox.x0, bbox.y0, bbox.x1, bbox.y1); + + obj = fz_dictgets(dict, "Rotate"); + if (fz_isint(obj)) + rotate = fz_toint(obj); + else + rotate = 0; + + pdf_logpage("rotate %d\n", rotate); + + /* + * Load annotations + */ + + obj = fz_dictgets(dict, "Annots"); + if (obj) + { + error = pdf_resolve(&obj, xref); + if (error) + return error; + error = pdf_loadannots(&comments, &links, xref, obj); + fz_dropobj(obj); + if (error) + return error; + } + + /* + * Load resources + */ + + obj = fz_dictgets(dict, "Resources"); + if (!obj) + return fz_throw("syntaxerror: Page missing Resources"); + error = pdf_resolve(&obj, xref); + if (error) + return error; + error = pdf_loadresources(&rdb, xref, obj); + fz_dropobj(obj); + if (error) + return error; + + /* + * Interpret content stream to build display tree + */ + + obj = fz_dictgets(dict, "Contents"); + + error = loadpagecontents(&tree, xref, rdb, obj); + if (error) { + fz_dropobj(rdb); + return error; + } + + pdf_logpage("optimize tree\n"); + error = fz_optimizetree(tree); + if (error) { + fz_dropobj(rdb); + return error; + } + + /* + * Create page object + */ + + page = *pagep = fz_malloc(sizeof(pdf_page)); + if (!page) { + fz_droptree(tree); + fz_dropobj(rdb); + return fz_outofmem; + } + + page->mediabox.x0 = MIN(bbox.x0, bbox.x1); + page->mediabox.y0 = MIN(bbox.y0, bbox.y1); + page->mediabox.x1 = MAX(bbox.x0, bbox.x1); + page->mediabox.y1 = MAX(bbox.y0, bbox.y1); + page->rotate = rotate; + page->resources = rdb; + page->tree = tree; + + page->comments = comments; + page->links = links; + + pdf_logpage("} %p\n", page); + + return nil; +} + +void +pdf_droppage(pdf_page *page) +{ + pdf_logpage("drop page %p\n", page); +/* + if (page->comments) + pdf_dropcomment(page->comments); +*/ + if (page->links) + pdf_droplink(page->links); + fz_dropobj(page->resources); + fz_droptree(page->tree); + fz_free(page); +} + diff --git a/pool/shard006/C/0120187_testSHT1x.c b/pool/shard006/C/0120187_testSHT1x.c new file mode 100644 index 0000000000000000000000000000000000000000..2960a054892469f1a9239f0fb6b2335753f0b8b0 --- /dev/null +++ b/pool/shard006/C/0120187_testSHT1x.c @@ -0,0 +1,105 @@ +// Compile with: gcc -lm -o testSHT1x ./../bcm2835-1.8/src/bcm2835.c ./RPi_SHT1x.c testSHT1x.c + +/* +Raspberry Pi SHT1x communication library. +By: John Burns (www.john.geek.nz) +Date: 01 November 2012 +License: CC BY-SA v3.0 - http://creativecommons.org/licenses/by-sa/3.0/ + +This is a derivative work based on + Name: Nice Guy SHT11 library + By: Daesung Kim + Date: 04/04/2011 + Source: http://www.theniceguy.net/2722 + License: Unknown - Attempts have been made to contact the author + +Dependencies: + BCM2835 Raspberry Pi GPIO Library - http://www.open.com.au/mikem/bcm2835/ + +Sensor: + Sensirion SHT11 Temperature and Humidity Sensor interfaced to Raspberry Pi GPIO port + +SHT pins ( modified for DaisyPi own connections ) + 1. GND - Connected to GPIO Port P1-06 (Ground) + 2. DATA - Connected via a 10k pullup resistor to GPIO Port P1-01 (3V3 Power) + 2. DATA - Connected to GPIO Port P1-11 (GPIO 17) + 3. SCK - Connected to GPIO Port P1-15 (GPIO 22) + 4. VDD - Connected to 3.3 V rail (3V3 Power) + +Modified by Rares Plescan and used in project DaisyPi for temperature/humidity/dew_point retrieval from SHT11 sensor. + +Note: + GPIO Pins can be changed in the Defines of RPi_SHT1x_v2.h +*/ + + +#include +#include +#include "RPi_SHT1x.h" + +void printTempAndHumidity(void) +{ + unsigned char noError = 1; + value humi_val,temp_val; + + // Wait at least 11ms after power-up (chapter 3.1) + delay(20); + + // Set up the SHT1x Data and Clock Pins + SHT1x_InitPins(); + + // Reset the SHT1x + SHT1x_Reset(); + + // Request Temperature measurement + noError = SHT1x_Measure_Start( SHT1xMeaT ); + if (!noError) { + return; + } + + // Read Temperature measurement + noError = SHT1x_Get_Measure_Value( (unsigned short int*) &temp_val.i ); + if (!noError) { + return; + } + // Request Humidity Measurement + noError = SHT1x_Measure_Start( SHT1xMeaRh ); + if (!noError) { + return; + } + + // Read Humidity measurement + noError = SHT1x_Get_Measure_Value( (unsigned short int*) &humi_val.i ); + if (!noError) { + return; + } +// printf("Convertite \n"); + // Convert intergers to float and calculate true values + temp_val.f = (float)temp_val.i; + humi_val.f = (float)humi_val.i; + + // Calculate Temperature and Humidity + SHT1x_Calc(&humi_val.f, &temp_val.f); + //Print the Temperature to the console +// printf("Temperature: %0.2f C\n",temp_val.f); + + //Print the Humidity to the console + //Calculate and print the Dew Point + float fDewPoint; + SHT1x_CalcDewpoint(humi_val.f ,temp_val.f, &fDewPoint); + printf("TEMP_HUMID_DEW %0.4f %0.4f %0.4f\n",temp_val.f,humi_val.f,fDewPoint); +// printf("TEMP_HUMID_DEW_THI %0.4f %0.4f %0.4f\n",temp_val.f,humi_val.f,fDewPoint,(temp_val.f*1.8+32)-((0.55-0.0055*humi_val.f)*((temp_val.f*1.8+32)-58))); +// printf("Final \n"); + +} + +int main () +{ + //Initialise the Raspberry Pi GPIO + if(!bcm2835_init()) + return 1; + + printTempAndHumidity(); + + return 1; +} diff --git a/pool/shard006/C/0120190_curl_fetcher.c b/pool/shard006/C/0120190_curl_fetcher.c new file mode 100644 index 0000000000000000000000000000000000000000..c68b74f9613a631f737e481f39ab25c4da912e22 --- /dev/null +++ b/pool/shard006/C/0120190_curl_fetcher.c @@ -0,0 +1,214 @@ +/* + * Copyright (C) 2008 Martin Willi + * Copyright (C) 2007 Andreas Steffen + * Hochschule fuer Technik Rapperswil + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See . + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include + +#include +#include + +#include "curl_fetcher.h" + +#define DEFAULT_TIMEOUT 10 + +typedef struct private_curl_fetcher_t private_curl_fetcher_t; + +/** + * private data of a curl_fetcher_t object. + */ +struct private_curl_fetcher_t { + /** + * Public data + */ + curl_fetcher_t public; + + /** + * CURL handle + */ + CURL* curl; + + /** + * Optional HTTP headers + */ + struct curl_slist *headers; + + /** + * Callback function + */ + fetcher_callback_t cb; +}; + +/** + * Data to pass to curl callback + */ +typedef struct { + fetcher_callback_t cb; + void *user; +} cb_data_t; + +/** + * Curl callback function, invokes fetcher_callback_t function + */ +static size_t curl_cb(void *ptr, size_t size, size_t nmemb, cb_data_t *data) +{ + size_t realsize = size * nmemb; + + if (data->cb(data->user, chunk_create(ptr, realsize))) + { + return realsize; + } + return 0; +} + +METHOD(fetcher_t, fetch, status_t, + private_curl_fetcher_t *this, char *uri, void *userdata) +{ + char error[CURL_ERROR_SIZE]; + status_t status; + cb_data_t data = { + .cb = this->cb, + .user = userdata, + }; + + if (this->cb == fetcher_default_callback) + { + *(chunk_t*)userdata = chunk_empty; + } + + if (curl_easy_setopt(this->curl, CURLOPT_URL, uri) != CURLE_OK) + { /* URL type not supported by curl */ + return NOT_SUPPORTED; + } + curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, error); + curl_easy_setopt(this->curl, CURLOPT_FAILONERROR, TRUE); + curl_easy_setopt(this->curl, CURLOPT_NOSIGNAL, TRUE); + curl_easy_setopt(this->curl, CURLOPT_CONNECTTIMEOUT, DEFAULT_TIMEOUT); + curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, (void*)curl_cb); + curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &data); + if (this->headers) + { + curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); + } + + DBG2(DBG_LIB, " sending http request to '%s'...", uri); + switch (curl_easy_perform(this->curl)) + { + case CURLE_UNSUPPORTED_PROTOCOL: + status = NOT_SUPPORTED; + break; + case CURLE_OK: + status = SUCCESS; + break; + default: + DBG1(DBG_LIB, "libcurl http request failed: %s", error); + status = FAILED; + break; + } + return status; +} + +METHOD(fetcher_t, set_option, bool, + private_curl_fetcher_t *this, fetcher_option_t option, ...) +{ + bool supported = TRUE; + va_list args; + + va_start(args, option); + switch (option) + { + case FETCH_REQUEST_DATA: + { + chunk_t data = va_arg(args, chunk_t); + + curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, (char*)data.ptr); + curl_easy_setopt(this->curl, CURLOPT_POSTFIELDSIZE, data.len); + break; + } + case FETCH_REQUEST_TYPE: + { + char header[BUF_LEN]; + char *request_type = va_arg(args, char*); + + snprintf(header, BUF_LEN, "Content-Type: %s", request_type); + this->headers = curl_slist_append(this->headers, header); + break; + } + case FETCH_REQUEST_HEADER: + { + char *header = va_arg(args, char*); + + this->headers = curl_slist_append(this->headers, header); + break; + } + case FETCH_HTTP_VERSION_1_0: + { + curl_easy_setopt(this->curl, CURLOPT_HTTP_VERSION, + CURL_HTTP_VERSION_1_0); + break; + } + case FETCH_TIMEOUT: + { + curl_easy_setopt(this->curl, CURLOPT_CONNECTTIMEOUT, + va_arg(args, u_int)); + break; + } + case FETCH_CALLBACK: + { + this->cb = va_arg(args, fetcher_callback_t); + break; + } + default: + supported = FALSE; + break; + } + va_end(args); + return supported; +} + +METHOD(fetcher_t, destroy, void, + private_curl_fetcher_t *this) +{ + curl_slist_free_all(this->headers); + curl_easy_cleanup(this->curl); + free(this); +} + +/* + * Described in header. + */ +curl_fetcher_t *curl_fetcher_create() +{ + private_curl_fetcher_t *this; + + INIT(this, + .public = { + .interface = { + .fetch = _fetch, + .set_option = _set_option, + .destroy = _destroy, + }, + }, + .curl = curl_easy_init(), + .cb = fetcher_default_callback, + ); + + if (!this->curl) + { + free(this); + return NULL; + } + return &this->public; +} + diff --git a/pool/shard006/C/0120193_xstat.c b/pool/shard006/C/0120193_xstat.c new file mode 100644 index 0000000000000000000000000000000000000000..62189637662819e82990a902d40209d4fa680d28 --- /dev/null +++ b/pool/shard006/C/0120193_xstat.c @@ -0,0 +1,60 @@ +/* xstat using old-style Unix stat system call. + Copyright (C) 1991-2015 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, see + . */ + +/* Ho hum, if xstat == xstat64 we must get rid of the prototype or gcc + will complain since they don't strictly match. */ +#define __xstat64 __xstat64_disable + +#include +#include +#include +#include + +#include +#include + +#include + +/* Get information about the file NAME in BUF. */ +int +__xstat (int vers, const char *name, struct stat *buf) +{ + if (vers == _STAT_VER_KERNEL) + return INLINE_SYSCALL (stat, 2, name, (struct kernel_stat *) buf); + +#ifdef STAT_IS_KERNEL_STAT + errno = EINVAL; + return -1; +#else + struct kernel_stat kbuf; + int result; + + result = INLINE_SYSCALL (stat, 2, name, &kbuf); + if (result == 0) + result = __xstat_conv (vers, &kbuf, buf); + + return result; +#endif +} +hidden_def (__xstat) +weak_alias (__xstat, _xstat); +#ifdef XSTAT_IS_XSTAT64 +#undef __xstat64 +strong_alias (__xstat, __xstat64); +hidden_ver (__xstat, __xstat64) +#endif diff --git a/pool/shard006/C/0120195_mia_dsp.c b/pool/shard006/C/0120195_mia_dsp.c new file mode 100644 index 0000000000000000000000000000000000000000..fdad079ad9a13b9232493caf7d44eb24193d4f20 --- /dev/null +++ b/pool/shard006/C/0120195_mia_dsp.c @@ -0,0 +1,225 @@ +/**************************************************************************** + + Copyright Echo Digital Audio Corporation (c) 1998 - 2004 + All rights reserved + www.echoaudio.com + + This file is part of Echo Digital Audio's generic driver library. + + Echo Digital Audio's generic driver library 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. + + 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. + + ************************************************************************* + + Translation from C++ and adaptation for use in ALSA-Driver + were made by Giuliano Pochini + +****************************************************************************/ + + +static int set_input_clock(struct echoaudio *chip, u16 clock); +static int set_professional_spdif(struct echoaudio *chip, char prof); +static int update_flags(struct echoaudio *chip); +static int set_vmixer_gain(struct echoaudio *chip, u16 output, u16 pipe, + int gain); +static int update_vmixer_level(struct echoaudio *chip); + + +static int init_hw(struct echoaudio *chip, u16 device_id, u16 subdevice_id) +{ + int err; + + if (snd_BUG_ON((subdevice_id & 0xfff0) != MIA)) + return -ENODEV; + + if ((err = init_dsp_comm_page(chip))) { + dev_err(chip->card->dev, + "init_hw - could not initialize DSP comm page\n"); + return err; + } + + chip->device_id = device_id; + chip->subdevice_id = subdevice_id; + chip->bad_board = TRUE; + chip->dsp_code_to_load = FW_MIA_DSP; + /* Since this card has no ASIC, mark it as loaded so everything + works OK */ + chip->asic_loaded = TRUE; + if ((subdevice_id & 0x0000f) == MIA_MIDI_REV) + chip->has_midi = TRUE; + chip->input_clock_types = ECHO_CLOCK_BIT_INTERNAL | + ECHO_CLOCK_BIT_SPDIF; + + if ((err = load_firmware(chip)) < 0) + return err; + chip->bad_board = FALSE; + + return err; +} + + + +static int set_mixer_defaults(struct echoaudio *chip) +{ + return init_line_levels(chip); +} + + + +static u32 detect_input_clocks(const struct echoaudio *chip) +{ + u32 clocks_from_dsp, clock_bits; + + /* Map the DSP clock detect bits to the generic driver clock + detect bits */ + clocks_from_dsp = le32_to_cpu(chip->comm_page->status_clocks); + + clock_bits = ECHO_CLOCK_BIT_INTERNAL; + + if (clocks_from_dsp & GLDM_CLOCK_DETECT_BIT_SPDIF) + clock_bits |= ECHO_CLOCK_BIT_SPDIF; + + return clock_bits; +} + + + +/* The Mia has no ASIC. Just do nothing */ +static int load_asic(struct echoaudio *chip) +{ + return 0; +} + + + +static int set_sample_rate(struct echoaudio *chip, u32 rate) +{ + u32 control_reg; + + switch (rate) { + case 96000: + control_reg = MIA_96000; + break; + case 88200: + control_reg = MIA_88200; + break; + case 48000: + control_reg = MIA_48000; + break; + case 44100: + control_reg = MIA_44100; + break; + case 32000: + control_reg = MIA_32000; + break; + default: + dev_err(chip->card->dev, + "set_sample_rate: %d invalid!\n", rate); + return -EINVAL; + } + + /* Override the clock setting if this Mia is set to S/PDIF clock */ + if (chip->input_clock == ECHO_CLOCK_SPDIF) + control_reg |= MIA_SPDIF; + + /* Set the control register if it has changed */ + if (control_reg != le32_to_cpu(chip->comm_page->control_register)) { + if (wait_handshake(chip)) + return -EIO; + + chip->comm_page->sample_rate = cpu_to_le32(rate); /* ignored by the DSP */ + chip->comm_page->control_register = cpu_to_le32(control_reg); + chip->sample_rate = rate; + + clear_handshake(chip); + return send_vector(chip, DSP_VC_UPDATE_CLOCKS); + } + return 0; +} + + + +static int set_input_clock(struct echoaudio *chip, u16 clock) +{ + dev_dbg(chip->card->dev, "set_input_clock(%d)\n", clock); + if (snd_BUG_ON(clock != ECHO_CLOCK_INTERNAL && + clock != ECHO_CLOCK_SPDIF)) + return -EINVAL; + + chip->input_clock = clock; + return set_sample_rate(chip, chip->sample_rate); +} + + + +/* This function routes the sound from a virtual channel to a real output */ +static int set_vmixer_gain(struct echoaudio *chip, u16 output, u16 pipe, + int gain) +{ + int index; + + if (snd_BUG_ON(pipe >= num_pipes_out(chip) || + output >= num_busses_out(chip))) + return -EINVAL; + + if (wait_handshake(chip)) + return -EIO; + + chip->vmixer_gain[output][pipe] = gain; + index = output * num_pipes_out(chip) + pipe; + chip->comm_page->vmixer[index] = gain; + + dev_dbg(chip->card->dev, + "set_vmixer_gain: pipe %d, out %d = %d\n", pipe, output, gain); + return 0; +} + + + +/* Tell the DSP to read and update virtual mixer levels in comm page. */ +static int update_vmixer_level(struct echoaudio *chip) +{ + if (wait_handshake(chip)) + return -EIO; + clear_handshake(chip); + return send_vector(chip, DSP_VC_SET_VMIXER_GAIN); +} + + + +/* Tell the DSP to reread the flags from the comm page */ +static int update_flags(struct echoaudio *chip) +{ + if (wait_handshake(chip)) + return -EIO; + clear_handshake(chip); + return send_vector(chip, DSP_VC_UPDATE_FLAGS); +} + + + +static int set_professional_spdif(struct echoaudio *chip, char prof) +{ + dev_dbg(chip->card->dev, "set_professional_spdif %d\n", prof); + if (prof) + chip->comm_page->flags |= + cpu_to_le32(DSP_FLAG_PROFESSIONAL_SPDIF); + else + chip->comm_page->flags &= + ~cpu_to_le32(DSP_FLAG_PROFESSIONAL_SPDIF); + chip->professional_spdif = prof; + return update_flags(chip); +} + diff --git a/pool/shard006/C/0120201_lua.c b/pool/shard006/C/0120201_lua.c new file mode 100644 index 0000000000000000000000000000000000000000..1f15e0aa3bb50fc196cf32834002afaeac9c7ec4 --- /dev/null +++ b/pool/shard006/C/0120201_lua.c @@ -0,0 +1,133 @@ +/* +* $Id: lua.c 443 2006-05-30 04:37:13Z darren $ +* +* Copyright (c) 2000-2001, Max Ischenko . +* +* This source code is released for free distribution under the terms of the +* GNU General Public License. +* +* This module contains functions for generating tags for Lua language. +*/ + +/* +* INCLUDE FILES +*/ +#include "general.h" /* must always come first */ + +#include + +#include "options.h" +#include "parse.h" +#include "read.h" +#include "vstring.h" + +/* +* DATA DEFINITIONS +*/ +typedef enum { + K_FUNCTION +} luaKind; + +static kindOption LuaKinds [] = { + { TRUE, 'f', "function", "functions" } +}; + +/* +* FUNCTION DEFINITIONS +*/ + +/* for debugging purposes */ +static void __unused__ print_string (char *p, char *q) +{ + for ( ; p != q; p++) + fprintf (errout, "%c", *p); + fprintf (errout, "\n"); +} + +/* + * Helper function. + * Returns 1 if line looks like a line of Lua code. + * + * TODO: Recognize UNIX bang notation. + * (Lua treat first line as a comment if it starts with #!) + * + */ +static boolean is_a_code_line (const unsigned char *line) +{ + boolean result; + const unsigned char *p = line; + while (isspace ((int) *p)) + p++; + if (p [0] == '\0') + result = FALSE; + else if (p [0] == '-' && p [1] == '-') + result = FALSE; + else + result = TRUE; + return result; +} + +static void extract_name (const char *begin, const char *end, vString *name) +{ + if (begin != NULL && end != NULL && begin < end) + { + const char *cp; + + while (isspace ((int) *begin)) + begin++; + while (isspace ((int) *end)) + end--; + if (begin < end) + { + for (cp = begin ; cp != end; cp++) + vStringPut (name, (int) *cp); + vStringTerminate (name); + + makeSimpleTag (name, LuaKinds, K_FUNCTION); + vStringClear (name); + } + } +} + +static void findLuaTags (void) +{ + vString *name = vStringNew (); + const unsigned char *line; + + while ((line = fileReadLine ()) != NULL) + { + const char *p, *q; + + if (! is_a_code_line (line)) + continue; + + p = (const char*) strstr ((const char*) line, "function"); + if (p == NULL) + continue; + + q = strchr ((const char*) line, '='); + + if (q == NULL) { + p = p + 9; /* skip the `function' word */ + q = strchr ((const char*) p, '('); + extract_name (p, q, name); + } else { + p = (const char*) &line[0]; + extract_name (p, q, name); + } + } + vStringDelete (name); +} + +extern parserDefinition* LuaParser (void) +{ + static const char* const extensions [] = { "lua", NULL }; + parserDefinition* def = parserNew ("Lua"); + def->kinds = LuaKinds; + def->kindCount = KIND_COUNT (LuaKinds); + def->extensions = extensions; + def->parser = findLuaTags; + return def; +} + +/* vi:set tabstop=4 shiftwidth=4: */ diff --git a/pool/shard006/C/0120203_gb-command-gaction-provider.c b/pool/shard006/C/0120203_gb-command-gaction-provider.c new file mode 100644 index 0000000000000000000000000000000000000000..50ce0870999e064ed15a307caeb2809009b0bfdf --- /dev/null +++ b/pool/shard006/C/0120203_gb-command-gaction-provider.c @@ -0,0 +1,239 @@ +/* gb-command-gaction-provider.c + * + * Copyright (C) 2014 Christian Hergert + * + * 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 . + */ + +#define G_LOG_DOMAIN "gaction-commands" + +#include + +#include "gb-command-gaction-provider.h" +#include "gb-command-gaction.h" +#include "gb-log.h" + +G_DEFINE_TYPE (GbCommandGactionProvider, gb_command_gaction_provider, + GB_TYPE_COMMAND_PROVIDER) + +GbCommandProvider * +gb_command_gaction_provider_new (GbWorkbench *workbench) +{ + return g_object_new (GB_TYPE_COMMAND_GACTION_PROVIDER, + "workbench", workbench, + NULL); +} + +static GList * +discover_groups (GbCommandGactionProvider *provider) +{ + GbDocumentView *view; + GApplication *application; + GbWorkbench *workbench; + GtkWidget *widget; + GList *list = NULL; + + g_return_val_if_fail (GB_IS_COMMAND_GACTION_PROVIDER (provider), NULL); + + view = gb_command_provider_get_active_view (GB_COMMAND_PROVIDER (provider)); + + for (widget = GTK_WIDGET (view); + widget; + widget = gtk_widget_get_parent (widget)) + { + const gchar **prefixes; + guint i; + + prefixes = gtk_widget_list_action_prefixes (widget); + + if (prefixes) + { + GActionGroup *group; + + for (i = 0; prefixes [i]; i++) + { + group = gtk_widget_get_action_group (widget, prefixes [i]); + + if (G_IS_ACTION_GROUP (group)) + list = g_list_append (list, group); + } + + g_free (prefixes); + } + } + + workbench = gb_command_provider_get_workbench (GB_COMMAND_PROVIDER (provider)); + list = g_list_append (list, G_ACTION_GROUP (workbench)); + + application = g_application_get_default (); + list = g_list_append (list, G_ACTION_GROUP (application)); + + return list; +} + +static gboolean +parse_command_text (const gchar *command_text, + gchar **name, + GVariant **params) +{ + GVariant *ret_params = NULL; + const gchar *str; + gchar *tmp; + gchar **parts; + gchar *ret_name = NULL; + + g_return_val_if_fail (command_text, FALSE); + g_return_val_if_fail (name, FALSE); + g_return_val_if_fail (params, FALSE); + + *name = NULL; + *params = NULL; + + /* Determine the command name */ + tmp = g_strdelimit (g_strdup (command_text), "(", ' '); + parts = g_strsplit (tmp, " ", 2); + ret_name = g_strdup (parts [0]); + g_free (tmp); + g_strfreev (parts); + + /* Advance to the (optional) parameters */ + for (str = command_text + strlen (ret_name); + *str; + str = g_utf8_next_char (str)) + { + gunichar ch; + + ch = g_utf8_get_char (str); + if (g_unichar_isspace (ch)) + continue; + + break; + } + + /* Parse any (optional) parameters */ + if (*str != '\0') + { + ret_params = g_variant_parse (NULL, str, NULL, NULL, NULL); + if (!ret_params) + goto failure; + } + + *name = ret_name; + *params = ret_params; + + return TRUE; + +failure: + g_clear_pointer (&ret_name, g_free); + g_clear_pointer (&ret_params, g_variant_unref); + + return FALSE; +} + +static GbCommand * +gb_command_gaction_provider_lookup (GbCommandProvider *provider, + const gchar *command_text) +{ + GbCommandGactionProvider *self = (GbCommandGactionProvider *)provider; + GbCommand *command = NULL; + GVariant *params = NULL; + GList *groups; + GList *iter; + gchar *action_name = NULL; + + ENTRY; + + g_return_val_if_fail (GB_IS_COMMAND_GACTION_PROVIDER (self), NULL); + g_return_val_if_fail (command_text, NULL); + + if (!parse_command_text (command_text, &action_name, ¶ms)) + RETURN (NULL); + + groups = discover_groups (self); + + for (iter = groups; iter; iter = iter->next) + { + GActionGroup *group = G_ACTION_GROUP (iter->data); + + if (g_action_group_has_action (group, action_name)) + { + command = g_object_new (GB_TYPE_COMMAND_GACTION, + "action-group", group, + "action-name", action_name, + "parameters", params, + NULL); + break; + } + } + + g_clear_pointer (¶ms, g_variant_unref); + g_list_free (groups); + g_free (action_name); + + RETURN (command); +} + +static void +gb_command_gaction_provider_complete (GbCommandProvider *provider, + GPtrArray *completions, + const gchar *initial_command_text) +{ + GbCommandGactionProvider *self = (GbCommandGactionProvider *)provider; + GList *groups; + GList *iter; + + ENTRY; + + g_return_if_fail (GB_IS_COMMAND_GACTION_PROVIDER (self)); + g_return_if_fail (initial_command_text); + + groups = discover_groups (self); + + for (iter = groups; iter; iter = iter->next) + { + GActionGroup *group = iter->data; + gchar **names; + guint i; + + g_assert (G_IS_ACTION_GROUP (group)); + + names = g_action_group_list_actions (group); + + for (i = 0; names [i]; i++) + { + if (g_str_has_prefix (names [i], initial_command_text)) + g_ptr_array_add (completions, g_strdup (names [i])); + } + + g_free (names); + } + + g_list_free (groups); + + EXIT; +} + +static void +gb_command_gaction_provider_class_init (GbCommandGactionProviderClass *klass) +{ + GbCommandProviderClass *provider_class = GB_COMMAND_PROVIDER_CLASS (klass); + + provider_class->lookup = gb_command_gaction_provider_lookup; + provider_class->complete = gb_command_gaction_provider_complete; +} + +static void +gb_command_gaction_provider_init (GbCommandGactionProvider *self) +{ +} diff --git a/pool/shard006/C/0120204_base64.c b/pool/shard006/C/0120204_base64.c new file mode 100644 index 0000000000000000000000000000000000000000..300a5aa37f11398620f115459b6b959b87f15efb --- /dev/null +++ b/pool/shard006/C/0120204_base64.c @@ -0,0 +1,284 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\ + * * + * baselib: a library implementing several simple utilities for C * + * Copyright (C) 2017 LeqxLeqx * + * * + * 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 . * + * * +\* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + + +#include +#include +#include +#include +#include +#include + +#include "mtest.h" +#include "strings.h" +#include "utilities.h" + +#include "base64.h" + +#define __BASE64_PADDING_CHAR '=' +const char __BASE64_VALUE_TO_CHAR_TABLE[] = { + 'A', 'B', 'C', 'D', 'E', + 'F', 'G', 'H', 'I', 'J', + 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', + 'U', 'V', 'W', 'X', 'Y', + 'Z', 'a', 'b', 'c', 'd', + 'e', 'f', 'g', 'h', 'i', + 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', + 't', 'u', 'v', 'w', 'x', + 'y', 'z', '0', '1', '2', + '3', '4', '5', '6', '7', + '8', '9', '+', '/' +}; + + +static char base64_value_to_char(char value) +{ + value &= 0x3F; + return __BASE64_VALUE_TO_CHAR_TABLE[(int) value]; +} + +static char base64_char_to_value(char c) +{ + if (c >= 'A' && c <= 'Z') + return (c - 'A'); + else if (c >= 'a' && c <= 'z') + return (c - 'a') + 26; + else if (c >= '0' && c <= '9') + return (c - '0') + 52; + else if (c == '+') + return 62; + else if (c == '/') + return 63; + else + assert(0); +} + +static void base64_encode_tuple(char * from, char * to, size_t remaining_size, bool padding) +{ + + char buffer [4]; + bool set_2 = false, set_3 = false; + + buffer[0] = (from[0] >> 2) & 0x3F; + buffer[1] = from[0] << 4; + buffer[2] = 0x0; + buffer[3] = 0x0; + + switch (remaining_size) + { + + default: + buffer[2] |= (from[2] >> 6) & 0x03; + buffer[3] |= from[2]; + set_3 = true; + + case 2: + buffer[1] |= (from[1] >> 4) & 0x0F; + buffer[2] |= from[1] << 2; + set_2 = true; + + case 1: + break; + + } + + to[0] = base64_value_to_char(buffer[0]); + to[1] = base64_value_to_char(buffer[1]); + + if (set_2) + to[2] = base64_value_to_char(buffer[2]); + else if (padding) + to[2] = __BASE64_PADDING_CHAR; + + if (set_3) + to[3] = base64_value_to_char(buffer[3]); + else if (padding) + to[3] = __BASE64_PADDING_CHAR; + +} + +static void base64_decode_tuple(char * from, char * to, size_t remaining_size) +{ + char buffer [4]; + + for (unsigned int k = 0; k < remaining_size && k < 4; k++) + { + buffer[k] = base64_char_to_value(from[k]); + } + + to[0] = (buffer[0] << 2) | ((buffer[1] >> 4) & 0x03); + + if (remaining_size >= 3) + to[1] = (buffer[1] << 4) | ((buffer[2] >> 2) & 0x0F); + if (remaining_size >= 4) + to[2] = (buffer[2] << 6) | buffer[3]; +} + +static unsigned int base64_is_well_formed_imp(char * string, unsigned int string_length) +{ + + unsigned int + string_length_mod, + scan_length; + + if (string_length == 0) + return 0; + + string_length_mod = string_length % 4; + if (string_length_mod == 0) + { + if (string[string_length - 1] == __BASE64_PADDING_CHAR) + { + if (string[string_length - 2] == __BASE64_PADDING_CHAR) + scan_length = string_length - 2; + else + scan_length = string_length - 1; + } + else + scan_length = string_length; + } + else if (string_length_mod == 1) + return 0; + else + scan_length = string_length; + + for (unsigned int k = 0; k < scan_length; k++) + { + if (!base64_is_valid_char(string[k])) + return 0; + } + + return scan_length; +} + +static char * base64_encode_imp(char * data, size_t data_size, bool padding) +{ + assert(data); + assert(data_size > 0); + + size_t + ret_size, + data_top; + char + * ret; + + if (padding) + ret_size = 4 * (utilities_round_size_upward(data_size, 3) / 3); + else + ret_size = utilities_multiply_round_up(data_size, 4.0 / 3.0); + + ret = (char *) _malloc(sizeof(char) * (ret_size + 1)); + assert(ret); + + data_top = 0; + for (size_t k = 0; k < ret_size; k += 4) + { + base64_encode_tuple(&data[data_top], &ret[k], data_size - data_top, padding); + data_top += 3; + } + + ret[ret_size] = '\0'; + return ret; +} + +static size_t base64_find_decoded_data_size(unsigned int encoded_size) +{ + unsigned int mod = encoded_size % 4; + if (mod == 0) + return 3 * (encoded_size / 4); + else if (mod == 2) + return 3 * (encoded_size / 4) + 1; + else if (mod == 3) + return 3 * (encoded_size / 4) + 2; + else + assert(0); +} + +bool base64_is_valid_char(char c) +{ + return + (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || + (c == '+') || + (c == '/'); +} + + + +char * base64_encode(char * data, size_t data_size) +{ + return base64_encode_imp(data, data_size, true); +} + +char * base64_encode_non_padded(char * data, size_t data_size) +{ + return base64_encode_imp(data, data_size, false); +} + +char * base64_decode(char * string, size_t * decoded_size_ptr) +{ + assert(string); + + return base64_decode_up_to(string, strings_length(string), decoded_size_ptr); +} + +char * base64_decode_up_to(char * string, size_t string_length, size_t * decoded_size_ptr) +{ + assert(string); + assert(decoded_size_ptr); + assert(string_length > 0); + + unsigned int + normalized_string_length = base64_is_well_formed_imp(string, string_length); + assert(normalized_string_length > 0); + + size_t + ret_size = base64_find_decoded_data_size(normalized_string_length), + ret_top; + char * ret = (char *) _malloc(sizeof(char) * ret_size); + assert(ret); + + ret_top = 0; + for (size_t k = 0; k < normalized_string_length; k += 4) + { + base64_decode_tuple(&string[k], &ret[ret_top], normalized_string_length - k); + ret_top += 3; + } + + *decoded_size_ptr = ret_size; + return ret; +} + +bool base64_is_well_formed(char * data) +{ + assert(data); + + return base64_is_well_formed_imp(data, strings_length(data)) > 0; +} + +bool base64_is_well_formed_up_to(char * data, size_t length) +{ + assert(data); + + return base64_is_well_formed_imp(data, length); +} diff --git a/pool/shard006/C/0120205_generichardwareinterface.c b/pool/shard006/C/0120205_generichardwareinterface.c new file mode 100644 index 0000000000000000000000000000000000000000..39b71221e754c38feebd0dd8deeeddabfc78f19d --- /dev/null +++ b/pool/shard006/C/0120205_generichardwareinterface.c @@ -0,0 +1,151 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MEM_SIZE 20 + +static void __iomem *virtual_base; +static dev_t first; +static struct cdev c_dev; +static struct class *cl; + + +static int myopen(struct inode *i, struct file *f) +{ + printk(KERN_INFO "Driver: open()\n"); + return 0; +} + +static int myclose(struct inode *i, struct file *f) +{ + printk(KERN_INFO "Driver: close()\n"); + return 0; +} + +static ssize_t myread(struct file *f, char __user *buf, size_t len, loff_t *off) +{ + int i; + u8 byte; + + printk(KERN_INFO "Driver: read(): %u\n", len); + + if (*off >= MEM_SIZE) + return 0; + if (*off + len > MEM_SIZE) + len = MEM_SIZE - *off; + for (i = 0; i < len; i++) + { + byte = ioread8((u8 *)virtual_base + *off + i); + if (copy_to_user(buf + i, &byte, 1)) + return -EFAULT; + } + *off += len; + printk(KERN_INFO "%u\n", len); + + return len; +} + +static ssize_t mywrite(struct file *f, const char __user *buf, size_t len, loff_t *off) +{ + int i; + u8 byte; + + printk(KERN_INFO "Driver: write(): %u\n", len); + + if (*off >= MEM_SIZE) + return 0; + if (*off + len > MEM_SIZE) + len = MEM_SIZE - *off; + for (i = 0; i < len; i++) + { + if (copy_from_user(&byte, buf + i, 1)) + return -EFAULT; + iowrite8(byte, (u8 *)virtual_base + *off + i); + } + *off += len; + printk(KERN_INFO "%u\n", len); + return len; +} + + +static struct file_operations ha_ops = +{ + .owner = THIS_MODULE, + .open = myopen, + .release = myclose, + .read = myread, + .write = mywrite +}; + + +static int __init ha_init(void) +{ + printk(KERN_INFO "HA regd()\n"); + + if ((virtual_base = (void *)kmalloc(MEM_SIZE, GFP_KERNEL)) == NULL) + { + printk(KERN_ERR "Kmalloc failed\n"); + return -1; + } + + if (alloc_chrdev_region(&first, 0, 1, "haccessdev_t") < 0) + { + kfree(virtual_base); + return -1; + } + + if ((cl = class_create(THIS_MODULE, "haccessclass")) == NULL) + { + unregister_chrdev_region(first, 1); + kfree(virtual_base); + return -1; + } + + if (device_create(cl, NULL, first, NULL, "haccessdevice") == NULL) + { + class_destroy(cl); + unregister_chrdev_region(first, 1); + kfree(virtual_base); + return -1; + } + + cdev_init(&c_dev, &ha_ops); + + if (cdev_add(&c_dev, first, 1) < 0) + { + device_destroy(cl, first); + class_destroy(cl); + unregister_chrdev_region(first, 1); + kfree(virtual_base); + return -1; + } + + return 0; +} + +static void __exit ha_exit(void) +{ + cdev_del(&c_dev); + device_destroy(cl, first); + class_destroy(cl); + unregister_chrdev_region(first, 1); + kfree(virtual_base); + + printk(KERN_INFO "HA unregd()\n"); +} + + +module_init(ha_init); +module_exit(ha_exit); + + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Sumanjit SenGupta"); +MODULE_DESCRIPTION("Hardware Interfacing Driver"); diff --git a/pool/shard006/C/0120207_ion_cma_heap.c b/pool/shard006/C/0120207_ion_cma_heap.c new file mode 100644 index 0000000000000000000000000000000000000000..98f066953fba0d9e65f316eebbea139352a22187 --- /dev/null +++ b/pool/shard006/C/0120207_ion_cma_heap.c @@ -0,0 +1,259 @@ +/* + * drivers/gpu/ion/ion_cma_heap.c + * + * Copyright (C) Linaro 2012 + * Author: for ST-Ericsson. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "ion.h" +#include "ion_priv.h" + +#define ION_CMA_ALLOCATE_FAILED -1 + +struct ion_cma_buffer_info { + void *cpu_addr; + dma_addr_t handle; + struct sg_table *table; + bool is_cached; +}; + +static int cma_heap_has_outer_cache; +/* + * Create scatter-list for the already allocated DMA buffer. + * This function could be replace by dma_common_get_sgtable + * as soon as it will avalaible. + */ +static int ion_cma_get_sgtable(struct device *dev, struct sg_table *sgt, + void *cpu_addr, dma_addr_t handle, size_t size) +{ + struct page *page = pfn_to_page(PFN_DOWN(handle)); + int ret; + + ret = sg_alloc_table(sgt, 1, GFP_KERNEL); + if (unlikely(ret)) + return ret; + + sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0); + return 0; +} + +/* ION CMA heap operations functions */ +static int ion_cma_allocate(struct ion_heap *heap, struct ion_buffer *buffer, + unsigned long len, unsigned long align, + unsigned long flags) +{ + struct device *dev = heap->priv; + struct ion_cma_buffer_info *info; + + dev_dbg(dev, "Request buffer allocation len %ld\n", len); + + info = kzalloc(sizeof(struct ion_cma_buffer_info), GFP_KERNEL); + if (!info) { + dev_err(dev, "Can't allocate buffer info\n"); + return ION_CMA_ALLOCATE_FAILED; + } + + if (!ION_IS_CACHED(flags)) + info->cpu_addr = dma_alloc_writecombine(dev, len, + &(info->handle), GFP_KERNEL); + else + info->cpu_addr = dma_alloc_nonconsistent(dev, len, + &(info->handle), GFP_KERNEL); + + if (!info->cpu_addr) { + dev_err(dev, "Fail to allocate buffer\n"); + goto err; + } + + info->table = kmalloc(sizeof(struct sg_table), GFP_KERNEL); + if (!info->table) { + dev_err(dev, "Fail to allocate sg table\n"); + goto err; + } + + info->is_cached = ION_IS_CACHED(flags); + + ion_cma_get_sgtable(dev, + info->table, info->cpu_addr, info->handle, len); + + /* keep this for memory release */ + buffer->priv_virt = info; + dev_dbg(dev, "Allocate buffer %p\n", buffer); + + if (heap->id == 27) { + // printk("[ION_alloc id==27|QSEECOM] 0x%p/0x%x => kmap_flush_unused\n", (void*)info->handle, (unsigned int)len); + kmap_flush_unused(); + } + + return 0; + +err: + kfree(info); + return ION_CMA_ALLOCATE_FAILED; +} + +static void ion_cma_free(struct ion_buffer *buffer) +{ + struct device *dev = buffer->heap->priv; + struct ion_cma_buffer_info *info = buffer->priv_virt; + + dev_dbg(dev, "Release buffer %p\n", buffer); + /* release memory */ + dma_free_coherent(dev, buffer->size, info->cpu_addr, info->handle); + sg_free_table(info->table); + /* release sg table */ + kfree(info->table); + kfree(info); +} + +/* return physical address in addr */ +static int ion_cma_phys(struct ion_heap *heap, struct ion_buffer *buffer, + ion_phys_addr_t *addr, size_t *len) +{ + struct device *dev = heap->priv; + struct ion_cma_buffer_info *info = buffer->priv_virt; + + dev_dbg(dev, "Return buffer %p physical address 0x%pa\n", buffer, + &info->handle); + + *addr = info->handle; + *len = buffer->size; + + return 0; +} + +static struct sg_table *ion_cma_heap_map_dma(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + struct ion_cma_buffer_info *info = buffer->priv_virt; + + return info->table; +} + +static void ion_cma_heap_unmap_dma(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + return; +} + +static int ion_cma_mmap(struct ion_heap *mapper, struct ion_buffer *buffer, + struct vm_area_struct *vma) +{ + struct device *dev = buffer->heap->priv; + struct ion_cma_buffer_info *info = buffer->priv_virt; +#ifdef CONFIG_TIMA_RKP + if ((buffer->size) && (boot_mode_security == 1)) { + /* iommu optimization- needs to be turned ON from + * the tz side. + */ + cpu_v7_tima_iommu_opt(vma->vm_start, vma->vm_end, (unsigned long)vma->vm_mm->pgd); + __asm__ __volatile__ ( + "mcr p15, 0, r0, c8, c3, 0\n" + "dsb\n" + "isb\n"); + } +#endif + + if (info->is_cached) + return dma_mmap_nonconsistent(dev, vma, info->cpu_addr, + info->handle, buffer->size); + else + return dma_mmap_writecombine(dev, vma, info->cpu_addr, + info->handle, buffer->size); +} + +static void *ion_cma_map_kernel(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + struct ion_cma_buffer_info *info = buffer->priv_virt; + + return info->cpu_addr; +} + +static void ion_cma_unmap_kernel(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + return; +} + +static int ion_cma_print_debug(struct ion_heap *heap, struct seq_file *s, + const struct list_head *mem_map) +{ + if (mem_map) { + struct mem_map_data *data; + + seq_printf(s, "\nMemory Map\n"); + seq_printf(s, "%16.s %14.s %14.s %14.s\n", + "client", "start address", "end address", + "size (hex)"); + + list_for_each_entry(data, mem_map, node) { + const char *client_name = "(null)"; + + + if (data->client_name) + client_name = data->client_name; + + seq_printf(s, "%16.s %14pa %14pa %14lu (%lx)\n", + client_name, &data->addr, + &data->addr_end, + data->size, data->size); + } + } + return 0; +} + +static struct ion_heap_ops ion_cma_ops = { + .allocate = ion_cma_allocate, + .free = ion_cma_free, + .map_dma = ion_cma_heap_map_dma, + .unmap_dma = ion_cma_heap_unmap_dma, + .phys = ion_cma_phys, + .map_user = ion_cma_mmap, + .map_kernel = ion_cma_map_kernel, + .unmap_kernel = ion_cma_unmap_kernel, + .print_debug = ion_cma_print_debug, +}; + +struct ion_heap *ion_cma_heap_create(struct ion_platform_heap *data) +{ + struct ion_heap *heap; + + heap = kzalloc(sizeof(struct ion_heap), GFP_KERNEL); + + if (!heap) + return ERR_PTR(-ENOMEM); + + heap->ops = &ion_cma_ops; + /* set device as private heaps data, later it will be + * used to make the link with reserved CMA memory */ + heap->priv = data->priv; + heap->type = ION_HEAP_TYPE_DMA; + cma_heap_has_outer_cache = data->has_outer_cache; + return heap; +} + +void ion_cma_heap_destroy(struct ion_heap *heap) +{ + kfree(heap); +} diff --git a/pool/shard006/C/0120208_OpenObjZeroLength.c b/pool/shard006/C/0120208_OpenObjZeroLength.c new file mode 100644 index 0000000000000000000000000000000000000000..0abca996842aa467a707310d5c948f68aff430a9 --- /dev/null +++ b/pool/shard006/C/0120208_OpenObjZeroLength.c @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2007-2009 Daniel Prevost + * + * This file is part of Photon (photonsoftware.org). + * + * This file may be distributed and/or modified under the terms of the + * GNU General Public License version 2 or version 3 as published by the + * Free Software Foundation and appearing in the file COPYING.GPL2 and + * COPYING.GPL3 included in the packaging of this software. + * + * Licensees holding a valid Photon Commercial license can use this file + * in accordance with the terms of their license. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +#include "Common/Common.h" +#include +#include "Tests/PrintError.h" +#include "API/CommonObject.h" +#include "API/Session.h" + +const bool expectedToPass = false; + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +int main( int argc, char * argv[] ) +{ +#if defined(USE_DBC) + PSO_HANDLE sessionHandle; + int errcode; + struct psoaCommonObject object; + + if ( argc > 1 ) { + errcode = psoInit( argv[1], argv[0] ); + } + else { + errcode = psoInit( "10701", argv[0] ); + } + if ( errcode != PSO_OK ) { + fprintf( stderr, "err: %d\n", errcode ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + errcode = psoInitSession( &sessionHandle ); + if ( errcode != PSO_OK ) { + fprintf( stderr, "err: %d\n", errcode ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + errcode = psoCreateFolder( sessionHandle, + "/api_session_openobj_zero_length", + strlen("/api_session_openobj_zero_length") ); + if ( errcode != PSO_OK ) { + fprintf( stderr, "err: %d\n", errcode ); + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + errcode = psoaSessionOpenObj( (psoaSession *) sessionHandle, + PSO_FOLDER, + false, + "/api_session_openobj_zero_length", + 0, + &object ); + + ERROR_EXIT( expectedToPass, NULL, ; ); +#else +# if defined(WIN32) + exit(3); +# else + abort(); +# endif +#endif +} + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + diff --git a/pool/shard006/C/0120211_bug-235681.c b/pool/shard006/C/0120211_bug-235681.c new file mode 100644 index 0000000000000000000000000000000000000000..99114eb6bfbf23f2c0a1b9ef05d7c9263dfe77f8 --- /dev/null +++ b/pool/shard006/C/0120211_bug-235681.c @@ -0,0 +1,94 @@ +/* + * pthread_cond_wait() test program. + * See also https://bugs.kde.org/show_bug.cgi?id=235681. + */ + +#include +#include +#include +#include +#include +#include + +pthread_mutex_t mutex; +pthread_cond_t cond_var; +int status; +int silent; + +static void *run_fn(void *v) +{ + int rc; + + if (!silent) + fprintf(stderr, "run_fn starting\n"); + + rc = pthread_mutex_lock(&mutex); + assert(!rc); + + while (!status) { + if (!silent) + fprintf(stderr, "run_fn(): status==0\n"); + rc = pthread_cond_wait(&cond_var, &mutex); + assert(!rc); + if (!silent) + fprintf(stderr, "run_fn(): woke up\n"); + } + if (!silent) + fprintf(stderr, "run_fn(): status==1\n"); + + rc = pthread_mutex_unlock(&mutex); + assert(!rc); + + if (!silent) + fprintf(stderr, "run_fn done\n"); + + return NULL; +} + +int main(int argc, char **argv) +{ + int rc; + pthread_t other_thread; + + if (argc > 1) + silent = 1; + + rc = pthread_mutex_init(&mutex, NULL); + assert(!rc); + rc = pthread_cond_init(&cond_var, NULL); + assert(!rc); + + status = 0; + + rc = pthread_create(&other_thread, NULL, run_fn, NULL); + assert(!rc); + + /* yield the processor, and give the other thread a chance to get into the while loop */ + if (!silent) + fprintf(stderr, "main(): sleeping...\n"); + sleep(1); + + rc = pthread_mutex_lock(&mutex); + assert(!rc); + /**** BEGIN CS *****/ + + if (!silent) + fprintf(stderr, "main(): status=1\n"); + status = 1; + rc = pthread_cond_broadcast(&cond_var); + assert(!rc); + + /**** END CS *****/ + rc = pthread_mutex_unlock(&mutex); + assert(!rc); + + if (!silent) + fprintf(stderr, "joining...\n"); + + rc = pthread_join(other_thread, NULL); + assert(!rc); + + fprintf(stderr, "Done.\n"); + + return 0; +} diff --git a/pool/shard006/C/0120212_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17.c b/pool/shard006/C/0120212_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17.c new file mode 100644 index 0000000000000000000000000000000000000000..22f67a2cf770b4d3787959336c423c95c8d537d0 --- /dev/null +++ b/pool/shard006/C/0120212_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17.c @@ -0,0 +1,108 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml +Template File: sources-sink-17.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: memcpy + * BadSink : Copy string to data using memcpy + * Flow Variant: 17 Control flow: for loops + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17_bad() +{ + int i; + char * data; + data = NULL; + for(i = 0; i < 1; i++) + { + /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = (char *)malloc(50*sizeof(char)); + if (data == NULL) {exit(-1);} + data[0] = '\0'; /* null terminate */ + } + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + memcpy(data, source, 100*sizeof(char)); + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + printLine(data); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */ +static void goodG2B() +{ + int h; + char * data; + data = NULL; + for(h = 0; h < 1; h++) + { + /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = (char *)malloc(100*sizeof(char)); + if (data == NULL) {exit(-1);} + data[0] = '\0'; /* null terminate */ + } + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + memcpy(data, source, 100*sizeof(char)); + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + printLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_memcpy_17_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C/0120214_crc32.c b/pool/shard006/C/0120214_crc32.c new file mode 100644 index 0000000000000000000000000000000000000000..7888c9d888fd089436e0c123e94af8cddac001f9 --- /dev/null +++ b/pool/shard006/C/0120214_crc32.c @@ -0,0 +1,82 @@ +#include "zlib.h" + +#define local static +#define ZEXPORT /* empty */ +unsigned long crc32 (unsigned long, const unsigned char *, unsigned int); + +local int crc_table_empty = 1; +local uLongf crc_table[256]; +local void make_crc_table OF((void)); + +/* + Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The table is simply the CRC of all possible eight bit values. This is all + the information needed to generate CRC's on data a byte at a time for all + combinations of CRC register values and incoming bytes. +*/ +local void make_crc_table() +{ + uLong c; + int n, k; + uLong poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* make exclusive-or pattern from polynomial (0xedb88320L) */ + poly = 0L; + for (n = 0; n < sizeof(p)/sizeof(Byte); n++) + poly |= 1L << (31 - p[n]); + + for (n = 0; n < 256; n++) + { + c = (uLong)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[n] = c; + } + crc_table_empty = 0; +} + +#define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8); +#define DO2(buf) DO1(buf); DO1(buf); +#define DO4(buf) DO2(buf); DO2(buf); +#define DO8(buf) DO4(buf); DO4(buf); + +/* ========================================================================= */ +uLong ZEXPORT crc32(crc, buf, len) + uLong crc; + const Bytef *buf; + uInt len; +{ + if (crc_table_empty) + make_crc_table(); + crc = crc ^ 0xffffffffL; + while (len >= 8) + { + DO8(buf); + len -= 8; + } + if (len) do { + DO1(buf); + } while (--len); + return crc ^ 0xffffffffL; +} + diff --git a/pool/shard006/C/0120217_os.c b/pool/shard006/C/0120217_os.c new file mode 100644 index 0000000000000000000000000000000000000000..e6da1589e3e0d46557010a752909ee5a4c3df682 --- /dev/null +++ b/pool/shard006/C/0120217_os.c @@ -0,0 +1,96 @@ +/* + * Copyright (C) 1984-2012 Mark Nudelman + * Modified for use with illumos by Garrett D'Amore. + * Copyright 2014 Garrett D'Amore + * + * You may distribute under the terms of either the GNU General Public + * License or the Less License, as specified in the README file. + * + * For more information, see the README file. + */ + +/* + * Operating system dependent routines. + * + * Most of the stuff in here is based on Unix, but an attempt + * has been made to make things work on other operating systems. + * This will sometimes result in a loss of functionality, unless + * someone rewrites code specifically for the new operating system. + * + * The makefile provides defines to decide whether various + * Unix features are present. + */ + +#include "less.h" +#include +#include + +extern volatile sig_atomic_t sigs; + +/* + * Like read() system call, but is deliberately interruptible. + */ +int +iread(int fd, unsigned char *buf, unsigned int len) +{ + int n; + +start: + flush(); + n = read(fd, buf, len); + if (n < 0) { + /* + * Certain values of errno indicate we should just retry the + * read. + */ + if (errno == EINTR) + return (READ_INTR); + if (errno == EAGAIN) + goto start; + return (-1); + } + return (n); +} + +/* + * errno_message: Return an error message based on the value of "errno". + */ +char * +errno_message(char *filename) +{ + return (easprintf("%s: %s", filename, strerror(errno))); +} + +static off_t +muldiv(off_t val, off_t num, off_t den) +{ + double v = (((double)val) * num) / den; + return ((off_t)(v + 0.5)); +} + +/* + * Return the ratio of two off_t, as a percentage. + * {{ Assumes a off_t is a long int. }} + */ +int +percentage(off_t num, off_t den) +{ + return ((int)muldiv(num, (off_t)100, den)); +} + +/* + * Return the specified percentage of a off_t. + */ +off_t +percent_pos(off_t pos, int percent, long fraction) +{ + /* + * Change percent (parts per 100) to perden + * (parts per NUM_FRAC_DENOM). + */ + off_t perden = (percent * (NUM_FRAC_DENOM / 100)) + (fraction / 100); + + if (perden == 0) + return (0); + return (muldiv(pos, perden, (off_t)NUM_FRAC_DENOM)); +} diff --git a/pool/shard006/C/0120219_oom04.c b/pool/shard006/C/0120219_oom04.c new file mode 100644 index 0000000000000000000000000000000000000000..ffb55030451a4957b230e5a15610cb1db90d24ac --- /dev/null +++ b/pool/shard006/C/0120219_oom04.c @@ -0,0 +1,119 @@ +/* + * Out Of Memory (OOM) for CPUSET + * + * The program is designed to cope with unpredictable like amount and + * system physical memory, swap size and other VMM technology like KSM, + * memcg, memory hotplug and so on which may affect the OOM + * behaviours. It simply increase the memory consumption 3G each time + * until all the available memory is consumed and OOM is triggered. + * + * Copyright (C) 2010 Red Hat, Inc. + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + * + * This program is distributed in the hope that it would be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * Further, this software is distributed without any warranty that it + * is free of the rightful claim of any third person regarding + * infringement or the like. Any license provided herein, whether + * implied or otherwise, applies only to this software file. Patent + * licenses, if any, provided herein do not apply to combinations of + * this program with other software, or any other product whatsoever. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include "numa_helper.h" +#include "test.h" +#include "mem.h" + +char *TCID = "oom04"; +int TST_TOTAL = 1; + +#if HAVE_NUMA_H && HAVE_LINUX_MEMPOLICY_H && HAVE_NUMAIF_H \ + && HAVE_MPOL_CONSTANTS + +int main(int argc, char *argv[]) +{ + int lc; + + tst_parse_opts(argc, argv, NULL, NULL); + +#if __WORDSIZE == 32 + tst_brkm(TCONF, NULL, "test is not designed for 32-bit system."); +#endif + + setup(); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + tst_count = 0; + + tst_resm(TINFO, "OOM on CPUSET..."); + testoom(0, 0, ENOMEM, 1); + + if (is_numa(cleanup)) { + /* + * Under NUMA system, the migration of cpuset's memory + * is in charge of cpuset.memory_migrate, we can write + * 1 to cpuset.memory_migrate to enable the migration. + */ + write_cpuset_files(CPATH_NEW, + "memory_migrate", "1"); + tst_resm(TINFO, "OOM on CPUSET with mem migrate:"); + testoom(0, 0, ENOMEM, 1); + } + } + cleanup(); + tst_exit(); +} + +void setup(void) +{ + int memnode, ret; + + tst_require_root(); + tst_sig(FORK, DEF_HANDLER, cleanup); + TEST_PAUSE; + + overcommit = get_sys_tune("overcommit_memory"); + set_sys_tune("overcommit_memory", 1, 1); + + mount_mem("cpuset", "cpuset", NULL, CPATH, CPATH_NEW); + + /* + * Some nodes do not contain memory, so use + * get_allowed_nodes(NH_MEMS) to get a memory + * node. This operation also applies to Non-NUMA + * systems. + */ + ret = get_allowed_nodes(NH_MEMS, 1, &memnode); + if (ret < 0) + tst_brkm(TBROK, NULL, "Failed to get a memory node " + "using get_allowed_nodes()"); + write_cpusets(memnode); +} + +void cleanup(void) +{ + set_sys_tune("overcommit_memory", overcommit, 0); + umount_mem(CPATH, CPATH_NEW); +} + +#else /* no NUMA */ +int main(void) +{ + tst_brkm(TCONF, NULL, "no NUMA development packages installed."); +} +#endif diff --git a/pool/shard006/C/0120223_main.c b/pool/shard006/C/0120223_main.c new file mode 100644 index 0000000000000000000000000000000000000000..168b7fe24fae887aa7e9c4de67ba363fdcd4a17b --- /dev/null +++ b/pool/shard006/C/0120223_main.c @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2018 Workaround GmbH + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include + +#define LOG_LEVEL 4 +#include +LOG_MODULE_REGISTER(main); + +#define LED_DEV_NAME DT_TI_LP5562_0_LABEL +#define NUM_LEDS 4 +#define BLINK_DELAY_ON 500 +#define BLINK_DELAY_OFF 500 +#define DELAY_TIME K_MSEC(2000) +#define COLORS_TO_SHOW 8 +#define VALUES_PER_COLOR 3 + +/* + * We assume that the colors are connected the way it is described in the driver + * datasheet. + */ +#define LED_R 2 +#define LED_G 1 +#define LED_B 0 + +/* + * The following colors are shown in the given order. + */ +static u8_t colors[COLORS_TO_SHOW][VALUES_PER_COLOR] = { + { 0xFF, 0x00, 0x00 }, /*< Red */ + { 0x00, 0xFF, 0x00 }, /*< Green */ + { 0x00, 0x00, 0xFF }, /*< Blue */ + { 0xFF, 0xFF, 0xFF }, /*< White */ + { 0xFF, 0xFF, 0x00 }, /*< Yellow */ + { 0xFF, 0x00, 0xFF }, /*< Purple */ + { 0x00, 0xFF, 0xFF }, /*< Cyan */ + { 0xF4, 0x79, 0x20 }, /*< Orange */ +}; + +/* + * @brief scale hex values [0x00..0xFF] to percent [0..100]. + * + * @param hex Hex value. + * + * @return Hex value scaled to percent. + */ +static inline u8_t scale_color_to_percent(u8_t hex) +{ + return (hex * 100) / 0xFF; +} + +/* + * @brief Set a color using the three RGB LEDs. + * + * @param dev LED device. + * @param r Red value in hex [0x00..0xFF]. + * @param g Green value in hex [0x00..0xFF]. + * @param b Blue value in hex [0x00..0xFF]. + * + * @return 0 if successful, -ERRNO otherwise. + */ +static int set_static_color(struct device *dev, u8_t r, u8_t g, u8_t b) +{ + int ret; + + r = scale_color_to_percent(r); + g = scale_color_to_percent(g); + b = scale_color_to_percent(b); + + ret = led_set_brightness(dev, LED_R, r); + if (ret) { + LOG_ERR("Failed to set color."); + return ret; + } + + ret = led_set_brightness(dev, LED_G, g); + if (ret) { + LOG_ERR("Failed to set color."); + return ret; + } + + ret = led_set_brightness(dev, LED_B, b); + if (ret) { + LOG_ERR("Failed to set color."); + return ret; + } + + return 0; +} + +/* + * @brief Blink the LED in the given color. + * + * Currently it is only possible to create colors by turning the three LEDs + * completely on or off. Proper mixing is not supported by the underlying API. + * + * @param dev LED device. + * @param r Blink the red LED. + * @param g Blink the green LED. + * @param b Blink the blue LED. + * @param delay_on Time in ms the LEDs stay on. + * @param delay_off Time in ms the LEDs stay off. + * + * @return 0 if successful, -ERRNO otherwise. + */ +static int blink_color(struct device *dev, bool r, bool g, bool b, + u32_t delay_on, u32_t delay_off) +{ + int ret; + + if (r) { + ret = led_blink(dev, LED_R, delay_on, delay_off); + if (ret) { + LOG_ERR("Failed to set color."); + return ret; + } + } + + if (g) { + ret = led_blink(dev, LED_G, delay_on, delay_off); + if (ret) { + LOG_ERR("Failed to set color."); + return ret; + } + } + + if (b) { + ret = led_blink(dev, LED_B, delay_on, delay_off); + if (ret) { + LOG_ERR("Failed to set color."); + return ret; + } + } + + return 0; +} + +/* + * @brief Helper function to turn off all LEDs connected to the driver. + * + * @param dev LED driver device. + * + * @return 0 if successful, -ERRNO otherwise. + */ +static int turn_off_all_leds(struct device *dev) +{ + for (int i = 0; i < NUM_LEDS; i++) { + int ret = led_off(dev, i); + + if (ret) { + return ret; + } + } + + return 0; +} + +void main(void) +{ + struct device *dev; + int i, ret; + + dev = device_get_binding(LED_DEV_NAME); + if (dev) { + LOG_INF("Found LED device %s", LED_DEV_NAME); + } else { + LOG_ERR("LED device %s not found", LED_DEV_NAME); + return; + } + + LOG_INF("Testing leds"); + + while (1) { + + for (i = 0; i < COLORS_TO_SHOW; i++) { + ret = set_static_color(dev, + colors[i][0], + colors[i][1], + colors[i][2]); + if (ret) { + return; + } + + k_sleep(DELAY_TIME); + } + + ret = turn_off_all_leds(dev); + if (ret < 0) { + return; + } + + /* Blink white. */ + ret = blink_color(dev, true, true, true, BLINK_DELAY_ON, + BLINK_DELAY_OFF); + if (ret) { + return; + } + + /* Wait a few blinking before turning off the LEDs */ + k_sleep(DELAY_TIME * 2); + + /* Change the color of the LEDs while keeping blinking. */ + for (i = 0; i < COLORS_TO_SHOW; i++) { + ret = set_static_color(dev, + colors[i][0], + colors[i][1], + colors[i][2]); + if (ret) { + return; + } + + k_sleep(DELAY_TIME * 2); + } + + ret = turn_off_all_leds(dev); + if (ret < 0) { + return; + } + + k_sleep(DELAY_TIME); + } +} diff --git a/pool/shard006/C/0120231_mainboard.c b/pool/shard006/C/0120231_mainboard.c new file mode 100644 index 0000000000000000000000000000000000000000..5d06108008f8c43478d7546ecd2492e1b234ddd4 --- /dev/null +++ b/pool/shard006/C/0120231_mainboard.c @@ -0,0 +1,272 @@ +/* + * This file is part of the coreboot project. + * + * Copyright 2014 Google 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; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct clk_rst_ctlr *clk_rst = (void *)TEGRA_CLK_RST_BASE; + +static void set_clock_sources(void) +{ + /* + * The max98090 codec and the temperature sensor are on I2C1. These + * can both run at 400 KHz, but the kernel sets the bus to 100 KHz. + */ + clock_configure_i2c_scl_freq(i2c1, PLLP, 100); + + /* + * MMC3 and MMC4: Set base clock frequency for SD Clock to Tegra MMC's + * maximum speed (48MHz) so we can change SDCLK by second stage divisor + * in payloads, without touching base clock. + */ + clock_configure_source(sdmmc3, PLLP, 48000); + clock_configure_source(sdmmc4, PLLP, 48000); + + /* External peripheral 1: audio codec (max98090) using 12MHz CLK1. + * Note the source id of CLK_M for EXTPERIPH1 is 3. */ + clock_configure_irregular_source(extperiph1, CLK_M, 12000, 3); + + /* + * We need 1.5MHz. So, we use CLK_M. CLK_DIVIDER macro returns a divisor + * (0xe) a little bit off from the ideal value (0xd) but it's good + * enough for beeps. The source id of CLK_M for I2S is 6. + */ + clock_configure_irregular_source(i2s1, CLK_M, 1500, 6); + + /* Note source id of PLLP for HOST1x is 4. */ + clock_configure_irregular_source(host1x, PLLP, 408000, 4); + + /* Use PLLD_OUT0 as clock source for disp1 */ + clrsetbits_le32(&clk_rst->clk_src_disp1, + CLK_SOURCE_MASK | CLK_DIVISOR_MASK, + 2 /*PLLD_OUT0 */ << CLK_SOURCE_SHIFT); + +} + +static void setup_pinmux(void) +{ + // I2C1 clock. + pinmux_set_config(PINMUX_GEN1_I2C_SCL_INDEX, + PINMUX_GEN1_I2C_SCL_FUNC_I2C1 | PINMUX_INPUT_ENABLE); + // I2C1 data. + pinmux_set_config(PINMUX_GEN1_I2C_SDA_INDEX, + PINMUX_GEN1_I2C_SDA_FUNC_I2C1 | PINMUX_INPUT_ENABLE); + // I2C2 clock. + pinmux_set_config(PINMUX_GEN2_I2C_SCL_INDEX, + PINMUX_GEN2_I2C_SCL_FUNC_I2C2 | PINMUX_INPUT_ENABLE | + PINMUX_OPEN_DRAIN); + // I2C2 data. + pinmux_set_config(PINMUX_GEN2_I2C_SDA_INDEX, + PINMUX_GEN2_I2C_SDA_FUNC_I2C2 | PINMUX_INPUT_ENABLE | + PINMUX_OPEN_DRAIN); + // I2C4 (DDC) clock. + pinmux_set_config(PINMUX_DDC_SCL_INDEX, + PINMUX_DDC_SCL_FUNC_I2C4 | PINMUX_INPUT_ENABLE); + // I2C4 (DDC) data. + pinmux_set_config(PINMUX_DDC_SDA_INDEX, + PINMUX_DDC_SDA_FUNC_I2C4 | PINMUX_INPUT_ENABLE); + + // TODO(hungte) Revice pinmux setup, make nice little SoC functions for + // every single logical thing instead of dumping a wall of code below. + uint32_t pin_up = PINMUX_PULL_UP | PINMUX_INPUT_ENABLE, + pin_down = PINMUX_PULL_DOWN | PINMUX_INPUT_ENABLE, + pin_none = PINMUX_PULL_NONE | PINMUX_INPUT_ENABLE; + + // MMC3 (sdcard reader) + pinmux_set_config(PINMUX_SDMMC3_CLK_INDEX, + PINMUX_SDMMC3_CLK_FUNC_SDMMC3 | pin_none); + pinmux_set_config(PINMUX_SDMMC3_CMD_INDEX, + PINMUX_SDMMC3_CMD_FUNC_SDMMC3 | pin_up); + pinmux_set_config(PINMUX_SDMMC3_DAT0_INDEX, + PINMUX_SDMMC3_DAT0_FUNC_SDMMC3 | pin_up); + pinmux_set_config(PINMUX_SDMMC3_DAT1_INDEX, + PINMUX_SDMMC3_DAT1_FUNC_SDMMC3 | pin_up); + pinmux_set_config(PINMUX_SDMMC3_DAT2_INDEX, + PINMUX_SDMMC3_DAT2_FUNC_SDMMC3 | pin_up); + pinmux_set_config(PINMUX_SDMMC3_DAT3_INDEX, + PINMUX_SDMMC3_DAT3_FUNC_SDMMC3 | pin_up); + pinmux_set_config(PINMUX_SDMMC3_CLK_LB_IN_INDEX, + PINMUX_SDMMC3_CLK_LB_IN_FUNC_SDMMC3 | pin_up); + pinmux_set_config(PINMUX_SDMMC3_CLK_LB_OUT_INDEX, + PINMUX_SDMMC3_CLK_LB_OUT_FUNC_SDMMC3 | pin_down); + + // MMC3 Card Detect pin. + gpio_input_pullup(GPIO(V2)); + // Disable SD card reader power so it can be reset even on warm boot. + // Payloads must enable power before accessing SD card slots. + gpio_output(GPIO(R0), 0); + + // MMC4 (eMMC) + pinmux_set_config(PINMUX_SDMMC4_CLK_INDEX, + PINMUX_SDMMC4_CLK_FUNC_SDMMC4 | pin_none); + pinmux_set_config(PINMUX_SDMMC4_CMD_INDEX, + PINMUX_SDMMC4_CMD_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT0_INDEX, + PINMUX_SDMMC4_DAT0_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT1_INDEX, + PINMUX_SDMMC4_DAT1_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT2_INDEX, + PINMUX_SDMMC4_DAT2_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT3_INDEX, + PINMUX_SDMMC4_DAT3_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT4_INDEX, + PINMUX_SDMMC4_DAT4_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT5_INDEX, + PINMUX_SDMMC4_DAT5_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT6_INDEX, + PINMUX_SDMMC4_DAT6_FUNC_SDMMC4 | pin_up); + pinmux_set_config(PINMUX_SDMMC4_DAT7_INDEX, + PINMUX_SDMMC4_DAT7_FUNC_SDMMC4 | pin_up); + + /* We pull the USB VBUS signals up but keep them as inputs since the + * voltage source likes to drive them low on overcurrent conditions */ + gpio_input_pullup(GPIO(N4)); /* USB VBUS EN0 */ + gpio_input_pullup(GPIO(N5)); /* USB VBUS EN1 */ + + /* Clock output 1 (for external peripheral) */ + pinmux_set_config(PINMUX_DAP_MCLK1_INDEX, + PINMUX_DAP_MCLK1_FUNC_EXTPERIPH1 | PINMUX_PULL_NONE); + + /* I2S1 */ + pinmux_set_config(PINMUX_DAP2_DIN_INDEX, + PINMUX_DAP2_DIN_FUNC_I2S1 | PINMUX_INPUT_ENABLE); + pinmux_set_config(PINMUX_DAP2_DOUT_INDEX, + PINMUX_DAP2_DOUT_FUNC_I2S1 | PINMUX_INPUT_ENABLE); + pinmux_set_config(PINMUX_DAP2_FS_INDEX, + PINMUX_DAP2_FS_FUNC_I2S1 | PINMUX_INPUT_ENABLE); + pinmux_set_config(PINMUX_DAP2_SCLK_INDEX, + PINMUX_DAP2_SCLK_FUNC_I2S1 | PINMUX_INPUT_ENABLE); + + /* PWM1 */ + pinmux_set_config(PINMUX_GPIO_PH1_INDEX, + PINMUX_GPIO_PH1_FUNC_PWM1 | PINMUX_PULL_NONE); + + /* DP HPD */ + pinmux_set_config(PINMUX_DP_HPD_INDEX, + PINMUX_DP_HPD_FUNC_DP | PINMUX_INPUT_ENABLE); +} + +static void setup_kernel_info(void) +{ + // Setup required information for Linux kernel. + + // pmc.odmdata: [18:19]: console type, [15:17]: UART id. + // TODO(hungte) This should be done by filling BCT values, or derived + // from CONFIG_CONSOLE_SERIAL_UART[A-E]. Right now we simply copy the + // value defined in BCT. + struct tegra_pmc_regs *pmc = (void*)TEGRA_PMC_BASE; + write32(&pmc->odmdata, 0x80080000); + + // Not strictly info, but kernel graphics driver needs this region locked down + struct tegra_mc_regs *mc = (void *)TEGRA_MC_BASE; + write32(&mc->video_protect_bom, 0); + write32(&mc->video_protect_size_mb, 0); + write32(&mc->video_protect_reg_ctrl, 1); +} + +static void setup_ec_spi(void) +{ + struct tegra_spi_channel *spi; + + spi = tegra_spi_init(CONFIG_EC_GOOGLE_CHROMEEC_SPI_BUS); +} + +static void mainboard_init(device_t dev) +{ + set_clock_sources(); + + clock_external_output(1); /* For external MAX98090 audio codec. */ + + /* + * Confirmed by NVIDIA hardware team, we need to take ALL audio devices + * conntected to AHUB (AUDIO, APBIF, I2S, DAM, AMX, ADX, SPDIF, AFC) out + * of reset and clock-enabled, otherwise reading AHUB devices (In our + * case, I2S/APBIF/AUDIO) will hang. + */ + clock_enable_clear_reset(CLK_L_GPIO | CLK_L_I2C1 | CLK_L_SDMMC4 | + CLK_L_I2S0 | CLK_L_I2S1 | CLK_L_I2S2 | + CLK_L_SPDIF | CLK_L_USBD | CLK_L_DISP1 | + CLK_L_HOST1X | CLK_L_PWM, + + CLK_H_EMC | CLK_H_I2C2 | CLK_H_PMC | + CLK_H_MEM | CLK_H_USB3, + + CLK_U_CSITE | CLK_U_SDMMC3, + + CLK_V_I2C4 | CLK_V_EXTPERIPH1 | CLK_V_APBIF | + CLK_V_AUDIO | CLK_V_I2S3 | CLK_V_I2S4 | + CLK_V_DAM0 | CLK_V_DAM1 | CLK_V_DAM2, + + CLK_W_DVFS | CLK_W_AMX0 | CLK_W_ADX0, + + CLK_X_DPAUX | CLK_X_SOR0 | CLK_X_AMX1 | + CLK_X_ADX1 | CLK_X_AFC0 | CLK_X_AFC1 | + CLK_X_AFC2 | CLK_X_AFC3 | CLK_X_AFC4 | + CLK_X_AFC5); + + usb_setup_utmip((void*)TEGRA_USBD_BASE); + /* USB2 is the camera, we don't need it in firmware */ + usb_setup_utmip((void*)TEGRA_USB3_BASE); + + setup_pinmux(); + + i2c_init(0); + i2c_init(1); + i2c_init(3); + + setup_kernel_info(); + clock_init_arm_generic_timer(); + setup_ec_spi(); + elog_init(); + elog_add_boot_reason(); +} + +static void mainboard_enable(device_t dev) +{ + dev->ops->init = &mainboard_init; +} + +struct chip_operations mainboard_ops = { + .name = "nyan_big", + .enable_dev = mainboard_enable, +}; + +void lb_board(struct lb_header *header) +{ + struct lb_range *dma; + + dma = (struct lb_range *)lb_new_record(header); + dma->tag = LB_TAB_DMA; + dma->size = sizeof(*dma); + dma->range_start = (uintptr_t)_dma_coherent; + dma->range_size = _dma_coherent_size; +} diff --git a/pool/shard006/C/0120232_pkcs_5_2.c b/pool/shard006/C/0120232_pkcs_5_2.c new file mode 100644 index 0000000000000000000000000000000000000000..757b81f1334eb95c4e28a8ff31c03ab68b6ba4c7 --- /dev/null +++ b/pool/shard006/C/0120232_pkcs_5_2.c @@ -0,0 +1,127 @@ +/* LibTomCrypt, modular cryptographic library -- Tom St Denis + * + * LibTomCrypt is a library that provides various cryptographic + * algorithms in a highly modular and flexible manner. + * + * The library is free for all purposes without any express + * guarantee it works. + */ +#include "tomcrypt_private.h" + +/** + @file pkcs_5_2.c + PKCS #5, Algorithm #2, Tom St Denis +*/ +#ifdef LTC_PKCS_5 + +/** + Execute PKCS #5 v2 + @param password The input password (or key) + @param password_len The length of the password (octets) + @param salt The salt (or nonce) + @param salt_len The length of the salt (octets) + @param iteration_count # of iterations desired for PKCS #5 v2 [read specs for more] + @param hash_idx The index of the hash desired + @param out [out] The destination for this algorithm + @param outlen [in/out] The max size and resulting size of the algorithm output + @return CRYPT_OK if successful +*/ +int pkcs_5_alg2(const unsigned char *password, unsigned long password_len, + const unsigned char *salt, unsigned long salt_len, + int iteration_count, int hash_idx, + unsigned char *out, unsigned long *outlen) +{ + int err, itts; + ulong32 blkno; + unsigned long stored, left, x, y; + unsigned char *buf[2]; + hmac_state *hmac; + + LTC_ARGCHK(password != NULL); + LTC_ARGCHK(salt != NULL); + LTC_ARGCHK(out != NULL); + LTC_ARGCHK(outlen != NULL); + + /* test hash IDX */ + if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) { + return err; + } + + buf[0] = XMALLOC(MAXBLOCKSIZE * 2); + hmac = XMALLOC(sizeof(hmac_state)); + if (hmac == NULL || buf[0] == NULL) { + if (hmac != NULL) { + XFREE(hmac); + } + if (buf[0] != NULL) { + XFREE(buf[0]); + } + return CRYPT_MEM; + } + /* buf[1] points to the second block of MAXBLOCKSIZE bytes */ + buf[1] = buf[0] + MAXBLOCKSIZE; + + left = *outlen; + blkno = 1; + stored = 0; + while (left != 0) { + /* process block number blkno */ + zeromem(buf[0], MAXBLOCKSIZE*2); + + /* store current block number and increment for next pass */ + STORE32H(blkno, buf[1]); + ++blkno; + + /* get PRF(P, S||int(blkno)) */ + if ((err = hmac_init(hmac, hash_idx, password, password_len)) != CRYPT_OK) { + goto LBL_ERR; + } + if ((err = hmac_process(hmac, salt, salt_len)) != CRYPT_OK) { + goto LBL_ERR; + } + if ((err = hmac_process(hmac, buf[1], 4)) != CRYPT_OK) { + goto LBL_ERR; + } + x = MAXBLOCKSIZE; + if ((err = hmac_done(hmac, buf[0], &x)) != CRYPT_OK) { + goto LBL_ERR; + } + + /* now compute repeated and XOR it in buf[1] */ + XMEMCPY(buf[1], buf[0], x); + for (itts = 1; itts < iteration_count; ++itts) { + if ((err = hmac_memory(hash_idx, password, password_len, buf[0], x, buf[0], &x)) != CRYPT_OK) { + goto LBL_ERR; + } + for (y = 0; y < x; y++) { + buf[1][y] ^= buf[0][y]; + } + } + + /* now emit upto x bytes of buf[1] to output */ + for (y = 0; y < x && left != 0; ++y) { + out[stored++] = buf[1][y]; + --left; + } + } + *outlen = stored; + + err = CRYPT_OK; +LBL_ERR: +#ifdef LTC_CLEAN_STACK + zeromem(buf[0], MAXBLOCKSIZE*2); + zeromem(hmac, sizeof(hmac_state)); +#endif + + XFREE(hmac); + XFREE(buf[0]); + + return err; +} + +#endif + + +/* ref: HEAD -> develop */ +/* git commit: 9c0d7085234bd6baba2ab8fd9eee62254599341c */ +/* commit time: 2018-10-15 10:51:17 +0200 */ diff --git a/pool/shard006/C/0120235_elina_test_oct_lait.c b/pool/shard006/C/0120235_elina_test_oct_lait.c new file mode 100644 index 0000000000000000000000000000000000000000..daa553a83ed4035ee9f851d81743f2e8a100d6dc --- /dev/null +++ b/pool/shard006/C/0120235_elina_test_oct_lait.c @@ -0,0 +1,150 @@ +/* + * + * This source file is part of ELINA (ETH LIbrary for Numerical Analysis). + * ELINA is Copyright © 2019 Department of Computer Science, ETH Zurich + * This software is distributed under GNU Lesser General Public License Version 3.0. + * For more information, see the ELINA project website at: + * http://elina.ethz.ch + * + * THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER + * EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY + * THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS OR BE ERROR-FREE AND ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, + * TITLE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ETH ZURICH BE LIABLE FOR ANY + * DAMAGES, INCLUDING BUT NOT LIMITED TO DIRECT, INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN + * ANY WAY CONNECTED WITH THIS SOFTWARE (WHETHER OR NOT BASED UPON WARRANTY, + * CONTRACT, TORT OR OTHERWISE). + * + */ + +#include "opt_oct.h" +#include "opt_oct_internal.h" +#include "opt_oct_hmat.h" +#include "opt_oct_lait.h" + +int mat_head[6][7] = { + {1, 1, 0, 0, 1}, + {1, 1, 1, 0, 1}, + {1, 1, 4, 0, 1}, + {1, -1, 4, 0, 1}, + {1, 1, 5, 0, 1}, + {1, -1, 5, 0, 1} +}; + +int mat_oa[18][7] = { + {1, 1, 1, 0, 1}, + {1, 1, 2, 0, 1}, + {1, 1, 5, 0, 1}, + {1, -1, 5, 0, 1}, + {1, 1, 6, 0, 1}, + {1, -1, 6, 0, 1}, + {2, -1, 6, 1, 8, 0, 1}, + {2, 1, 6, 1, 8, 0, 1}, + {1, 1, 8, 0, 1}, + {2, -1, 6, -1, 8, 1, 1}, + {2, 1, 6, -1, 8, 1, 1}, + {1, -1, 8, 1, 1}, + {2, -1, 5, 1, 9, 0, 1}, + {2, 1, 5, 1, 9, 0, 1}, + {1, 1, 9, 0, 1}, + {2, -1, 5, -1, 9, 0, 1}, + {2, 1, 5, -1, 9, 0 ,1}, + {1, -1, 9, 0, 1} +}; + +int mat_ob[16][7] = { + {1, 1, 1, 0, 1}, + {1, 1, 2, 0, 1}, + {1, 1, 5, 0, 1}, + {1, -1, 5, 0, 1}, + {1, 1, 6, 0, 1}, + {1, -1, 6, 0, 1}, + {1, 1, 7, -8, 1}, + {1, -1, 7, 8, 1}, + {2, -1, 6, 1, 8, 0, 1}, + {2, 1, 6, 1, 8, 0, 1}, + {1, 1, 8, 0, 1}, + {2, -1, 6, -1, 8, 0, 1}, + {2, 1, 6, -1, 8, 0, 1}, + {1, -1, 8, 0, 1}, + {1, 1, 9, -1, 1}, + {1, -1, 9, 1, 1}, +}; + +opt_oct_t* generate_oct(elina_manager_t * man, int mat[][7], int num_cons, int num_vars) { + elina_lincons0_array_t lincons0 = elina_lincons0_array_make(num_cons); + + for (int i=0; ip.linterm[j]; + linterm->dim = dim; + coeff = &linterm->coeff; + elina_scalar_set_to_int(coeff->val.scalar, cf, ELINA_SCALAR_MPQ); + } + + int cst = mat[i][1+2*size]; + int cst_type = mat[i][2+2*size]; + elina_scalar_set_to_int((&linexpr0->cst)->val.scalar, cst, ELINA_SCALAR_MPQ); + if (cst_type == 0) { + lincons0.p[i].constyp = ELINA_CONS_EQ; + } else if (cst_type == 1) { + lincons0.p[i].constyp = ELINA_CONS_SUPEQ; + } else if (cst_type == 2) { + lincons0.p[i].constyp = ELINA_CONS_SUP; + } else if (cst_type == 3) { + lincons0.p[i].constyp = ELINA_CONS_DISEQ; + } + lincons0.p[i].linexpr0 = linexpr0; + } + + opt_oct_t* op = opt_oct_top(man, num_vars, 0); + op = opt_oct_meet_lincons_array(man, true, op, &lincons0); + elina_lincons0_array_clear(&lincons0); + + return op; +} + +int main(int argc, char** argv) { + elina_manager_t * man = opt_oct_manager_alloc(); + + // call opt_oct_lait_init at the start of the analysis to initialize Lait + opt_oct_lait_init("/home/hej/ELINA/elina_oct", "/home/hej/ELINA/elina_oct/opt_oct_lait.pt"); + + // the first join input + opt_oct_t* oa = generate_oct(man, mat_oa, 18, 56); + elina_lincons0_array_t arr_a = opt_oct_to_lincons_array(man, oa); + elina_lincons0_array_fprint(stdout, &arr_a, NULL); + elina_lincons0_array_clear(&arr_a); + + // the second join input + opt_oct_t* ob = generate_oct(man, mat_ob, 16, 56); + elina_lincons0_array_t arr_b = opt_oct_to_lincons_array(man, ob); + elina_lincons0_array_fprint(stdout, &arr_b, NULL); + elina_lincons0_array_clear(&arr_b); + + // the join output + opt_oct_t* res = opt_oct_join(man, false, oa, ob); + elina_lincons0_array_t arr_res = opt_oct_to_lincons_array(man, res); + elina_lincons0_array_fprint(stdout, &arr_res, NULL); + elina_lincons0_array_clear(&arr_res); + + // the abstract element at the loop head + opt_oct_t* head = generate_oct(man, mat_head, 6, 6); + elina_lincons0_array_t arr_head = opt_oct_to_lincons_array(man, head); + elina_lincons0_array_fprint(stdout, &arr_head, NULL); + elina_lincons0_array_clear(&arr_head); + + // applying Lait + opt_oct_t* lait_res = opt_oct_lait(man, false, oa, ob, res, head, 0); + elina_lincons0_array_t arr_lait = opt_oct_to_lincons_array(man, lait_res); + elina_lincons0_array_fprint(stdout, &arr_lait, NULL); + elina_lincons0_array_clear(&arr_lait); + + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C/0120237_gstrtpL16depay.c b/pool/shard006/C/0120237_gstrtpL16depay.c new file mode 100644 index 0000000000000000000000000000000000000000..7025583941d536889aa28f258aa5718286c90631 --- /dev/null +++ b/pool/shard006/C/0120237_gstrtpL16depay.c @@ -0,0 +1,268 @@ +/* GStreamer + * Copyright (C) <2007> Wim Taymans + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "gstrtpL16depay.h" + +GST_DEBUG_CATEGORY_STATIC (rtpL16depay_debug); +#define GST_CAT_DEFAULT (rtpL16depay_debug) + +/* elementfactory information */ +static const GstElementDetails gst_rtp_L16_depay_details = +GST_ELEMENT_DETAILS ("RTP packet depayloader", + "Codec/Depayloader/Network", + "Extracts raw audio from RTP packets", + "Zeeshan Ali ," "Wim Taymans "); + +static GstStaticPadTemplate gst_rtp_L16_depay_src_template = +GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("audio/x-raw-int, " + "endianness = (int) BIG_ENDIAN, " + "signed = (boolean) true, " + "width = (int) 16, " + "depth = (int) 16, " + "rate = (int) [ 1, MAX ], " "channels = (int) [ 1, MAX ]") + ); + +static GstStaticPadTemplate gst_rtp_L16_depay_sink_template = + GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("application/x-rtp, " + "media = (string) \"audio\", " + "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", " + "clock-rate = (int) [ 1, MAX ], " + /* "channels = (int) [1, MAX]" */ + /* "emphasis = (string) ANY" */ + /* "channel-order = (string) ANY" */ + "encoding-name = (string) \"L16\";" + "application/x-rtp, " + "media = (string) \"audio\", " + "payload = (int) { " GST_RTP_PAYLOAD_L16_STEREO_STRING ", " + GST_RTP_PAYLOAD_L16_MONO_STRING " }," "clock-rate = (int) [ 1, MAX ]" + /* "channels = (int) [1, MAX]" */ + /* "emphasis = (string) ANY" */ + /* "channel-order = (string) ANY" */ + ) + ); + +GST_BOILERPLATE (GstRtpL16Depay, gst_rtp_L16_depay, GstBaseRTPDepayload, + GST_TYPE_BASE_RTP_DEPAYLOAD); + +static gboolean gst_rtp_L16_depay_setcaps (GstBaseRTPDepayload * depayload, + GstCaps * caps); +static GstBuffer *gst_rtp_L16_depay_process (GstBaseRTPDepayload * depayload, + GstBuffer * buf); + +static GstStateChangeReturn gst_rtp_L16_depay_change_state (GstElement * + element, GstStateChange transition); + +static void +gst_rtp_L16_depay_base_init (gpointer klass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (klass); + + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gst_rtp_L16_depay_src_template)); + gst_element_class_add_pad_template (element_class, + gst_static_pad_template_get (&gst_rtp_L16_depay_sink_template)); + + gst_element_class_set_details (element_class, &gst_rtp_L16_depay_details); +} + +static void +gst_rtp_L16_depay_class_init (GstRtpL16DepayClass * klass) +{ + GstElementClass *gstelement_class; + GstBaseRTPDepayloadClass *gstbasertpdepayload_class; + + gstelement_class = (GstElementClass *) klass; + gstbasertpdepayload_class = (GstBaseRTPDepayloadClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + gstelement_class->change_state = gst_rtp_L16_depay_change_state; + + gstbasertpdepayload_class->set_caps = gst_rtp_L16_depay_setcaps; + gstbasertpdepayload_class->process = gst_rtp_L16_depay_process; + + GST_DEBUG_CATEGORY_INIT (rtpL16depay_debug, "rtpL16depay", 0, + "Raw Audio RTP Depayloader"); +} + +static void +gst_rtp_L16_depay_init (GstRtpL16Depay * rtpL16depay, + GstRtpL16DepayClass * klass) +{ + /* needed because of GST_BOILERPLATE */ +} + +static gint +gst_rtp_L16_depay_parse_int (GstStructure * structure, const gchar * field, + gint def) +{ + const gchar *str; + gint res; + + if ((str = gst_structure_get_string (structure, field))) + return atoi (str); + + if (gst_structure_get_int (structure, field, &res)) + return res; + + return def; +} + +static gboolean +gst_rtp_L16_depay_setcaps (GstBaseRTPDepayload * depayload, GstCaps * caps) +{ + GstStructure *structure; + GstRtpL16Depay *rtpL16depay; + gint clock_rate, payload; + gint channels; + GstCaps *srccaps; + + rtpL16depay = GST_RTP_L16_DEPAY (depayload); + + structure = gst_caps_get_structure (caps, 0); + + payload = 96; + gst_structure_get_int (structure, "payload", &payload); + switch (payload) { + case GST_RTP_PAYLOAD_L16_STEREO: + channels = 2; + clock_rate = 44100; + break; + case GST_RTP_PAYLOAD_L16_MONO: + channels = 1; + clock_rate = 44100; + break; + default: + channels = 0; + clock_rate = 0; + break; + } + + /* caps can overwrite defaults */ + clock_rate = + gst_rtp_L16_depay_parse_int (structure, "clock-rate", clock_rate); + channels = gst_rtp_L16_depay_parse_int (structure, "channels", channels); + + depayload->clock_rate = clock_rate; + rtpL16depay->rate = clock_rate; + rtpL16depay->channels = channels; + + srccaps = gst_caps_new_simple ("audio/x-raw-int", + "endianness", G_TYPE_INT, G_BIG_ENDIAN, + "signed", G_TYPE_BOOLEAN, TRUE, + "width", G_TYPE_INT, 16, + "depth", G_TYPE_INT, 16, + "rate", G_TYPE_INT, clock_rate, "channels", G_TYPE_INT, channels, NULL); + + gst_pad_set_caps (depayload->srcpad, srccaps); + gst_caps_unref (srccaps); + + return TRUE; +} + +static GstBuffer * +gst_rtp_L16_depay_process (GstBaseRTPDepayload * depayload, GstBuffer * buf) +{ + GstRtpL16Depay *rtpL16depay; + GstBuffer *outbuf; + + rtpL16depay = GST_RTP_L16_DEPAY (depayload); + + if (!gst_rtp_buffer_validate (buf)) + goto bad_packet; + + { + gint payload_len; + + payload_len = gst_rtp_buffer_get_payload_len (buf); + + if (payload_len <= 0) + goto empty_packet; + + GST_DEBUG_OBJECT (rtpL16depay, "got payload of %d bytes", payload_len); + + outbuf = gst_rtp_buffer_get_payload_buffer (buf); + + return outbuf; + } + return NULL; + +bad_packet: + { + GST_ELEMENT_WARNING (rtpL16depay, STREAM, DECODE, + ("Packet did not validate."), (NULL)); + return NULL; + } +empty_packet: + { + GST_ELEMENT_WARNING (rtpL16depay, STREAM, DECODE, + ("Empty Payload."), (NULL)); + return NULL; + } +} + +static GstStateChangeReturn +gst_rtp_L16_depay_change_state (GstElement * element, GstStateChange transition) +{ + GstRtpL16Depay *rtpL16depay; + GstStateChangeReturn ret; + + rtpL16depay = GST_RTP_L16_DEPAY (element); + + /* + switch (transition) { + case GST_STATE_CHANGE_NULL_TO_READY: + break; + default: + break; + } + */ + + ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition); + + /* + switch (transition) { + case GST_STATE_CHANGE_READY_TO_NULL: + break; + default: + break; + } + */ + return ret; +} + +gboolean +gst_rtp_L16_depay_plugin_init (GstPlugin * plugin) +{ + return gst_element_register (plugin, "rtpL16depay", + GST_RANK_MARGINAL, GST_TYPE_RTP_L16_DEPAY); +} diff --git a/pool/shard006/C/0120239_romix.c b/pool/shard006/C/0120239_romix.c new file mode 100644 index 0000000000000000000000000000000000000000..3ffa209a08df0f15f5d8c9140c035044321e4aa1 --- /dev/null +++ b/pool/shard006/C/0120239_romix.c @@ -0,0 +1,89 @@ +#include +#include +#include "slurp.h" +#include "crypto_hash.h" +#include "randombytes.h" +#include "crypto_stream.h" +#include "pdkdf.h" + +void memxor(unsigned char *restrict dst, unsigned char *restrict scr, + unsigned long long length){ + for(unsigned long long i=0; i0; iters--){ + crypto_hash(hash2, hash, crypto_hash_BYTES); + crypto_hash(hash, hash2, crypto_hash_BYTES); + } + memcpy(key, hash2, keylength); + return 0; +} + +int romix(unsigned char *key, + unsigned long long keylength, + unsigned char *passphrase, + unsigned long long passlength, + unsigned char *salt, + unsigned long long saltlength){ + /*This code will be tested and debugged sometime*/ + unsigned char *saltphrase; + unsigned char *workspace; + unsigned char **hashes; + unsigned char xarray[crypto_hash_BYTES]; + unsigned char yarray[crypto_hash_BYTES]; + unsigned long long index; + unsigned char nonce[crypto_stream_NONCEBYTES]; + int workfactor=1048576;//2^20. We are using 64 megabytes of ram. + workspace=malloc(workfactor*crypto_hash_BYTES); + hashes=malloc(sizeof(char *)*workfactor); + saltphrase=malloc(saltlength+keylength); + if(workspace ==NULL || hashes==NULL ||saltphrase==NULL) return -1; //error + for(int i=0;i +#include +#include + +#include "globals.h" +#include "master.h" +#include "debug.h" + +/*****************************************************************************/ + +static int ec_debug_disabled = 0; + +// net_device functions +int ec_dbgdev_open(struct net_device *); +int ec_dbgdev_stop(struct net_device *); +int ec_dbgdev_tx(struct sk_buff *, struct net_device *); +struct net_device_stats *ec_dbgdev_stats(struct net_device *); + +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 31) +/** Device operations for debug interfaces. + */ +static const struct net_device_ops ec_dbg_netdev_ops = +{ + .ndo_open = ec_dbgdev_open, + .ndo_stop = ec_dbgdev_stop, + .ndo_start_xmit = ec_dbgdev_tx, + .ndo_get_stats = ec_dbgdev_stats, +}; +#endif + +/*****************************************************************************/ + +/** Debug interface constructor. + * + * Initializes the debug object, creates a net_device and registeres it. + * + * \retval 0 Success. + * \retval <0 Error code. + */ +int ec_debug_init( + ec_debug_t *dbg, /**< Debug object. */ + ec_device_t *device, /**< EtherCAT device. */ + const char *name /**< Interface name. */ + ) +{ + dbg->device = device; + dbg->registered = 0; + dbg->opened = 0; + + memset(&dbg->stats, 0, sizeof(struct net_device_stats)); + + if (!(dbg->dev = + alloc_netdev(sizeof(ec_debug_t *), name, ether_setup))) { + EC_MASTER_ERR(device->master, "Unable to allocate net_device" + " for debug object!\n"); + return -ENODEV; + } + + // initialize net_device +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 31) + dbg->dev->netdev_ops = &ec_dbg_netdev_ops; +#else + dbg->dev->open = ec_dbgdev_open; + dbg->dev->stop = ec_dbgdev_stop; + dbg->dev->hard_start_xmit = ec_dbgdev_tx; + dbg->dev->get_stats = ec_dbgdev_stats; +#endif + + // initialize private data + *((ec_debug_t **) netdev_priv(dbg->dev)) = dbg; + + return 0; +} + +/*****************************************************************************/ + +/** Debug interface destructor. + * + * Unregisters the net_device and frees allocated memory. + */ +void ec_debug_clear( + ec_debug_t *dbg /**< debug object */ + ) +{ + ec_debug_unregister(dbg); + free_netdev(dbg->dev); +} + +/*****************************************************************************/ + +/** Register debug interface. + */ +void ec_debug_register( + ec_debug_t *dbg, /**< debug object */ + const struct net_device *net_dev /**< 'Real' Ethernet device. */ + ) +{ + int result; + + ec_debug_unregister(dbg); + + // use the Ethernet address of the physical device for the debug device + memcpy(dbg->dev->dev_addr, net_dev->dev_addr, ETH_ALEN); + + // connect the net_device to the kernel + if ((result = register_netdev(dbg->dev))) { + EC_MASTER_WARN(dbg->device->master, "Unable to register net_device:" + " error %i\n", result); + } else { + dbg->registered = 1; + } +} + +/*****************************************************************************/ + +/** Unregister debug interface. + */ +void ec_debug_unregister( + ec_debug_t *dbg /**< debug object */ + ) +{ + if (dbg->registered) { + dbg->opened = 0; + dbg->registered = 0; + unregister_netdev(dbg->dev); + } +} + +/*****************************************************************************/ + +/** Sends frame data to the interface. + */ +void ec_debug_send( + ec_debug_t *dbg, /**< debug object */ + const uint8_t *data, /**< frame data */ + size_t size /**< size of the frame data */ + ) +{ + struct sk_buff *skb; + + if (!dbg->opened || ec_debug_disabled) + return; + + // allocate socket buffer + if (!(skb = dev_alloc_skb(size))) { + dbg->stats.rx_dropped++; + return; + } + + // copy frame contents into socket buffer + memcpy(skb_put(skb, size), data, size); + + // update device statistics + dbg->stats.rx_packets++; + dbg->stats.rx_bytes += size; + + // pass socket buffer to network stack + skb->dev = dbg->dev; + skb->protocol = eth_type_trans(skb, dbg->dev); + skb->ip_summed = CHECKSUM_UNNECESSARY; + netif_rx(skb); +} + +/*****************************************************************************/ + +/** + Temporarily disable the debug interface. +*/ + +void ec_debug_disable(int disable) +{ + ec_debug_disabled = disable; +} + +/****************************************************************************** + * NET_DEVICE functions + *****************************************************************************/ + +/** Opens the virtual network device. + */ +int ec_dbgdev_open( + struct net_device *dev /**< debug net_device */ + ) +{ + ec_debug_t *dbg = *((ec_debug_t **) netdev_priv(dev)); + dbg->opened = 1; + EC_MASTER_INFO(dbg->device->master, "Debug interface %s opened.\n", + dev->name); + return 0; +} + +/*****************************************************************************/ + +/** Stops the virtual network device. + */ +int ec_dbgdev_stop( + struct net_device *dev /**< debug net_device */ + ) +{ + ec_debug_t *dbg = *((ec_debug_t **) netdev_priv(dev)); + dbg->opened = 0; + EC_MASTER_INFO(dbg->device->master, "Debug interface %s stopped.\n", + dev->name); + return 0; +} + +/*****************************************************************************/ + +/** Transmits data via the virtual network device. + */ +int ec_dbgdev_tx( + struct sk_buff *skb, /**< transmit socket buffer */ + struct net_device *dev /**< EoE net_device */ + ) +{ + ec_debug_t *dbg = *((ec_debug_t **) netdev_priv(dev)); + + dev_kfree_skb(skb); + dbg->stats.tx_dropped++; + return 0; +} + +/*****************************************************************************/ + +/** Gets statistics about the virtual network device. + */ +struct net_device_stats *ec_dbgdev_stats( + struct net_device *dev /**< debug net_device */ + ) +{ + ec_debug_t *dbg = *((ec_debug_t **) netdev_priv(dev)); + return &dbg->stats; +} + +/*****************************************************************************/ + +/** \cond */ + +EXPORT_SYMBOL(ec_debug_disable); + +/** \endcond */ + +/*****************************************************************************/ diff --git a/pool/shard006/C/0120241_ide-park.c b/pool/shard006/C/0120241_ide-park.c new file mode 100644 index 0000000000000000000000000000000000000000..c875a957596c56f2b505cb272005028f57574922 --- /dev/null +++ b/pool/shard006/C/0120241_ide-park.c @@ -0,0 +1,124 @@ +#include +#include +#include +#include + +DECLARE_WAIT_QUEUE_HEAD(ide_park_wq); + +static void issue_park_cmd(ide_drive_t *drive, unsigned long timeout) +{ + ide_hwif_t *hwif = drive->hwif; + struct request_queue *q = drive->queue; + struct request *rq; + int rc; + + timeout += jiffies; + spin_lock_irq(&hwif->lock); + if (drive->dev_flags & IDE_DFLAG_PARKED) { + int reset_timer = time_before(timeout, drive->sleep); + int start_queue = 0; + + drive->sleep = timeout; + wake_up_all(&ide_park_wq); + if (reset_timer && del_timer(&hwif->timer)) + start_queue = 1; + spin_unlock_irq(&hwif->lock); + + if (start_queue) { + spin_lock_irq(q->queue_lock); + blk_start_queueing(q); + spin_unlock_irq(q->queue_lock); + } + return; + } + spin_unlock_irq(&hwif->lock); + + rq = blk_get_request(q, READ, __GFP_WAIT); + rq->cmd[0] = REQ_PARK_HEADS; + rq->cmd_len = 1; + rq->cmd_type = REQ_TYPE_SPECIAL; + rq->special = &timeout; + rc = blk_execute_rq(q, NULL, rq, 1); + blk_put_request(rq); + if (rc) + goto out; + + /* + * Make sure that *some* command is sent to the drive after the + * timeout has expired, so power management will be reenabled. + */ + rq = blk_get_request(q, READ, GFP_NOWAIT); + if (unlikely(!rq)) + goto out; + + rq->cmd[0] = REQ_UNPARK_HEADS; + rq->cmd_len = 1; + rq->cmd_type = REQ_TYPE_SPECIAL; + elv_add_request(q, rq, ELEVATOR_INSERT_FRONT, 1); + +out: + return; +} + +ssize_t ide_park_show(struct device *dev, struct device_attribute *attr, + char *buf) +{ + ide_drive_t *drive = to_ide_device(dev); + ide_hwif_t *hwif = drive->hwif; + unsigned long now; + unsigned int msecs; + + if (drive->dev_flags & IDE_DFLAG_NO_UNLOAD) + return -EOPNOTSUPP; + + spin_lock_irq(&hwif->lock); + now = jiffies; + if (drive->dev_flags & IDE_DFLAG_PARKED && + time_after(drive->sleep, now)) + msecs = jiffies_to_msecs(drive->sleep - now); + else + msecs = 0; + spin_unlock_irq(&hwif->lock); + + return snprintf(buf, 20, "%u\n", msecs); +} + +ssize_t ide_park_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t len) +{ +#define MAX_PARK_TIMEOUT 30000 + ide_drive_t *drive = to_ide_device(dev); + long int input; + int rc; + + rc = strict_strtol(buf, 10, &input); + if (rc || input < -2) + return -EINVAL; + if (input > MAX_PARK_TIMEOUT) { + input = MAX_PARK_TIMEOUT; + rc = -EOVERFLOW; + } + + mutex_lock(&ide_setting_mtx); + if (input >= 0) { + if (drive->dev_flags & IDE_DFLAG_NO_UNLOAD) + rc = -EOPNOTSUPP; + else if (input || drive->dev_flags & IDE_DFLAG_PARKED) + issue_park_cmd(drive, msecs_to_jiffies(input)); + } else { + if (drive->media == ide_disk) + switch (input) { + case -1: + drive->dev_flags &= ~IDE_DFLAG_NO_UNLOAD; + break; + case -2: + drive->dev_flags |= IDE_DFLAG_NO_UNLOAD; + break; + } + else + rc = -EOPNOTSUPP; + } + mutex_unlock(&ide_setting_mtx); + + return rc ? rc : len; +} diff --git a/pool/shard006/C/0120243_pthread.c b/pool/shard006/C/0120243_pthread.c new file mode 100644 index 0000000000000000000000000000000000000000..68a217318c00d4249a9d0cafd1b95f8ce6a32ce5 --- /dev/null +++ b/pool/shard006/C/0120243_pthread.c @@ -0,0 +1,132 @@ +/* File: "pthread.c" */ + +/* Copyright (c) 2006-2013 by Marc Feeley, All Rights Reserved. */ + +#include +#include + +/* + * ___VERSION must match the version number of the Gambit header file. + */ + +#define ___VERSION 407009 +#include "gambit.h" + +/* + * Include declarations exported by mylib.scm. + */ + +#include "mylib.h" + +/* + * Define SCHEME_LIBRARY_LINKER as the name of the Scheme library + * prefixed with "____20_" and suffixed with "__". This is the + * function that initializes the Scheme library. + */ + +#define SCHEME_LIBRARY_LINKER ____20_mylib__ + +___BEGIN_C_LINKAGE +extern ___mod_or_lnk SCHEME_LIBRARY_LINKER (___global_state); +___END_C_LINKAGE + +#define N 5 /* number of threads */ + +___SCMOBJ counter; /* the Scheme counter record to increment */ + +pthread_mutex_t mut; /* to implement critical section for incrementation */ + +void increment (void) +{ + int got_throw = 0; + + /* + * At most one thread at a time can execute Scheme code. + * So call Scheme in a critical section. + */ + + pthread_mutex_lock (&mut); + + /* call Scheme to increment counter */ + + ___ON_THROW(increment_counter (counter), got_throw=1); + + pthread_mutex_unlock (&mut); + + if (got_throw) + { + printf ("thread %p is terminating\n", pthread_self ()); + pthread_exit (NULL); /* exit if Scheme threw an exception */ + } +} + +void increment_loop (void) +{ + int i; + for (i = 0; i<20000; i++) + increment (); +} + +void* thread_main (void* param) +{ + increment_loop (); + return NULL; +} + +int main (int argc, char **argv) +{ + /* + * Setup the Scheme library by calling "___setup" with appropriate + * parameters. The call to "___setup_params_reset" sets all parameters + * to their default setting. + */ + + ___setup_params_struct setup_params; + + ___setup_params_reset (&setup_params); + + setup_params.version = ___VERSION; + setup_params.linker = SCHEME_LIBRARY_LINKER; + + ___setup (&setup_params); + + /* Main part of program: start N threads that increment a counter */ + + counter = new_counter (); /* create a new counter */ + + pthread_mutex_init (&mut, NULL); /* initialize mutex */ + + { + int i; + pthread_t tid[N]; + void* results[N]; + + for (i = 0; i +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "pic.h" + +#include "mpc8xx.h" + +extern int cpm_pic_init(void); +extern int cpm_get_irq(void); + +/* A place holder for time base interrupts, if they are ever enabled. */ +static irqreturn_t timebase_interrupt(int irq, void *dev) +{ + printk ("timebase_interrupt()\n"); + + return IRQ_HANDLED; +} + +static struct irqaction tbint_irqaction = { + .handler = timebase_interrupt, + .flags = IRQF_NO_THREAD, + .name = "tbint", +}; + +/* per-board overridable init_internal_rtc() function. */ +void __init __attribute__ ((weak)) +init_internal_rtc(void) +{ + sit8xx_t __iomem *sys_tmr = immr_map(im_sit); + + /* Disable the RTC one second and alarm interrupts. */ + clrbits16(&sys_tmr->sit_rtcsc, (RTCSC_SIE | RTCSC_ALE)); + + /* Enable the RTC */ + setbits16(&sys_tmr->sit_rtcsc, (RTCSC_RTF | RTCSC_RTE)); + immr_unmap(sys_tmr); +} + +static int __init get_freq(char *name, unsigned long *val) +{ + struct device_node *cpu; + const unsigned int *fp; + int found = 0; + + /* The cpu node should have timebase and clock frequency properties */ + cpu = of_get_cpu_node(0, NULL); + + if (cpu) { + fp = of_get_property(cpu, name, NULL); + if (fp) { + found = 1; + *val = *fp; + } + + of_node_put(cpu); + } + + return found; +} + +/* The decrementer counts at the system (internal) clock frequency divided by + * sixteen, or external oscillator divided by four. We force the processor + * to use system clock divided by sixteen. + */ +void __init mpc8xx_calibrate_decr(void) +{ + struct device_node *cpu; + cark8xx_t __iomem *clk_r1; + car8xx_t __iomem *clk_r2; + sitk8xx_t __iomem *sys_tmr1; + sit8xx_t __iomem *sys_tmr2; + int irq, virq; + + clk_r1 = immr_map(im_clkrstk); + + /* Unlock the SCCR. */ + out_be32(&clk_r1->cark_sccrk, ~KAPWR_KEY); + out_be32(&clk_r1->cark_sccrk, KAPWR_KEY); + immr_unmap(clk_r1); + + /* Force all 8xx processors to use divide by 16 processor clock. */ + clk_r2 = immr_map(im_clkrst); + setbits32(&clk_r2->car_sccr, 0x02000000); + immr_unmap(clk_r2); + + /* Processor frequency is MHz. + */ + ppc_proc_freq = 50000000; + if (!get_freq("clock-frequency", &ppc_proc_freq)) + printk(KERN_ERR "WARNING: Estimating processor frequency " + "(not found)\n"); + + ppc_tb_freq = ppc_proc_freq / 16; + printk("Decrementer Frequency = 0x%lx\n", ppc_tb_freq); + + /* Perform some more timer/timebase initialization. This used + * to be done elsewhere, but other changes caused it to get + * called more than once....that is a bad thing. + * + * First, unlock all of the registers we are going to modify. + * To protect them from corruption during power down, registers + * that are maintained by keep alive power are "locked". To + * modify these registers we have to write the key value to + * the key location associated with the register. + * Some boards power up with these unlocked, while others + * are locked. Writing anything (including the unlock code?) + * to the unlocked registers will lock them again. So, here + * we guarantee the registers are locked, then we unlock them + * for our use. + */ + sys_tmr1 = immr_map(im_sitk); + out_be32(&sys_tmr1->sitk_tbscrk, ~KAPWR_KEY); + out_be32(&sys_tmr1->sitk_rtcsck, ~KAPWR_KEY); + out_be32(&sys_tmr1->sitk_tbk, ~KAPWR_KEY); + out_be32(&sys_tmr1->sitk_tbscrk, KAPWR_KEY); + out_be32(&sys_tmr1->sitk_rtcsck, KAPWR_KEY); + out_be32(&sys_tmr1->sitk_tbk, KAPWR_KEY); + immr_unmap(sys_tmr1); + + init_internal_rtc(); + + /* Enabling the decrementer also enables the timebase interrupts + * (or from the other point of view, to get decrementer interrupts + * we have to enable the timebase). The decrementer interrupt + * is wired into the vector table, nothing to do here for that. + */ + cpu = of_get_cpu_node(0, NULL); + virq= irq_of_parse_and_map(cpu, 0); + of_node_put(cpu); + irq = virq_to_hw(virq); + + sys_tmr2 = immr_map(im_sit); + out_be16(&sys_tmr2->sit_tbscr, ((1 << (7 - (irq/2))) << 8) | + (TBSCR_TBF | TBSCR_TBE)); + immr_unmap(sys_tmr2); + + if (setup_irq(virq, &tbint_irqaction)) + panic("Could not allocate timer IRQ!"); +} + +/* The RTC on the MPC8xx is an internal register. + * We want to protect this during power down, so we need to unlock, + * modify, and re-lock. + */ + +int mpc8xx_set_rtc_time(struct rtc_time *tm) +{ + sitk8xx_t __iomem *sys_tmr1; + sit8xx_t __iomem *sys_tmr2; + time64_t time; + + sys_tmr1 = immr_map(im_sitk); + sys_tmr2 = immr_map(im_sit); + time = rtc_tm_to_time64(tm); + + out_be32(&sys_tmr1->sitk_rtck, KAPWR_KEY); + out_be32(&sys_tmr2->sit_rtc, (u32)time); + out_be32(&sys_tmr1->sitk_rtck, ~KAPWR_KEY); + + immr_unmap(sys_tmr2); + immr_unmap(sys_tmr1); + return 0; +} + +void mpc8xx_get_rtc_time(struct rtc_time *tm) +{ + unsigned long data; + sit8xx_t __iomem *sys_tmr = immr_map(im_sit); + + /* Get time from the RTC. */ + data = in_be32(&sys_tmr->sit_rtc); + rtc_time64_to_tm(data, tm); + immr_unmap(sys_tmr); + return; +} + +void __noreturn mpc8xx_restart(char *cmd) +{ + car8xx_t __iomem *clk_r = immr_map(im_clkrst); + + + local_irq_disable(); + + setbits32(&clk_r->car_plprcr, 0x00000080); + /* Clear the ME bit in MSR to cause checkstop on machine check + */ + mtmsr(mfmsr() & ~0x1000); + + in_8(&clk_r->res[0]); + panic("Restart failed\n"); +} + +static void cpm_cascade(struct irq_desc *desc) +{ + generic_handle_irq(cpm_get_irq()); +} + +/* Initialize the internal interrupt controllers. The number of + * interrupts supported can vary with the processor type, and the + * 82xx family can have up to 64. + * External interrupts can be either edge or level triggered, and + * need to be initialized by the appropriate driver. + */ +void __init mpc8xx_pics_init(void) +{ + int irq; + + if (mpc8xx_pic_init()) { + printk(KERN_ERR "Failed interrupt 8xx controller initialization\n"); + return; + } + + irq = cpm_pic_init(); + if (irq) + irq_set_chained_handler(irq, cpm_cascade); +} diff --git a/pool/shard006/C/0120246_init.c b/pool/shard006/C/0120246_init.c new file mode 100644 index 0000000000000000000000000000000000000000..a6a64bad60e13d743d7277b7382cb18432d30c5a --- /dev/null +++ b/pool/shard006/C/0120246_init.c @@ -0,0 +1,100 @@ +/* + * COPYRIGHT (c) 1989-2012. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.org/license/LICENSE. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +const char rtems_test_name[] = "PSXINTRCRITICAL 1"; + +/* forward declarations to avoid warnings */ +rtems_task Init(rtems_task_argument ignored); + +#define TEST_NAME "01" +#define TEST_STRING "POSIX Timer" + +static timer_t Timer; +static struct itimerspec TimerParams; + +#define POSIX_TIMER_RELATIVE 0 + +static bool test_body( void *arg ) +{ + int rv; + + (void) arg; + + rv = timer_settime(Timer, POSIX_TIMER_RELATIVE, &TimerParams, NULL); + rtems_test_assert( rv == 0 ); + + return false; +} + +static rtems_timer_service_routine test_release_from_isr( + rtems_id timer, + void *arg +) +{ + test_body( NULL ); +} + +rtems_task Init( + rtems_task_argument ignored +) +{ + int sc; + + TEST_BEGIN(); + + puts( "Init - Trying to generate timer fire from ISR while firing" ); + puts( "Init - Variation is: " TEST_STRING ); + + puts( "Init - There is no way for the test to know if it hits the case" ); + + /* create POSIX Timer */ + sc = timer_create (CLOCK_REALTIME, NULL, &Timer); + if ( sc == -1 ) { + perror ("Error in timer creation\n"); + rtems_test_exit(0); + } + + /* we don't care if it ever fires */ + TimerParams.it_interval.tv_sec = 10; + TimerParams.it_interval.tv_nsec = 0; + TimerParams.it_value.tv_sec = 10; + TimerParams.it_value.tv_nsec = 0; + + interrupt_critical_section_test( test_body, NULL, test_release_from_isr ); + + TEST_END(); + rtems_test_exit(0); +} + +/* configuration information */ + +#define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER +#define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER + +#define CONFIGURE_MAXIMUM_TASKS 1 +#define CONFIGURE_MAXIMUM_TIMERS 1 +#define CONFIGURE_MAXIMUM_POSIX_TIMERS 1 +#define CONFIGURE_MAXIMUM_USER_EXTENSIONS 1 +#define CONFIGURE_MICROSECONDS_PER_TICK 1000 +#define CONFIGURE_INITIAL_EXTENSIONS RTEMS_TEST_INITIAL_EXTENSION + +#define CONFIGURE_RTEMS_INIT_TASKS_TABLE + +#define CONFIGURE_INIT +#include + +/* global variables */ diff --git a/pool/shard006/C/0120247_desktop.c b/pool/shard006/C/0120247_desktop.c new file mode 100644 index 0000000000000000000000000000000000000000..466bee8a138da30ad63a8a9e31f42d8cc0eb8e5e --- /dev/null +++ b/pool/shard006/C/0120247_desktop.c @@ -0,0 +1,104 @@ +#include "desktop.h" + +desktop *cria_desktop(void) { + desktop *desk = malloc(sizeof(desktop)); + if (!desk) + falha_aloc(); + desk->lista_caixas = cria_lista(); + desk->desenha = &desenha_desktop; + desk->monitora = &monitora_desktop; + desk->atualiza = &atualiza_desktop; + return desk; +} + +desktop *insere_elemento(desktop *xdesktop, caixa *xcaixa) { /*pressupoe caixa e desktop alocados*/ + xdesktop->lista_caixas->insere(xdesktop->lista_caixas, xcaixa); + return xdesktop; +} + +desktop *remove_elemento(desktop *xdesktop, unsigned int poslist) { + xdesktop->lista_caixas->remove(xdesktop->lista_caixas, poslist); + return xdesktop; +} + +desktop *gerencia_remocao(desktop *xdesktop){ + long int esc = 1; + long int id_insercao; + limpa_buffer(); + while(esc){ + printf("Gostaria de remover alguma caixa (1->s/0->n)? "); + scanf("%ld",&esc); + if (esc){ + printf("Digite seu numero na ordem de insercao: "); + scanf("%ld",&id_insercao); + xdesktop = remove_elemento(xdesktop,id_insercao); + } + } + return xdesktop; +} + +desktop *desenha_desktop(desktop *xdesktop) { + if (xdesktop->lista_caixas->prox) { + lista *no_ativo; + lista *perc = xdesktop->lista_caixas->prox; + colore_tela(); + do{ /*lembre q a lista tem noh sentinela*/ + if (perc->comando->visibilidade) + perc->comando->desenha(perc->comando); + perc=perc->prox; + } while(perc!=xdesktop->lista_caixas->prox); + printf("\n"); /*a fim de posicionar o cursor*/ + no_ativo = busca_por_ativo(xdesktop->lista_caixas); + if (!no_ativo) { /*1a vez q desenhamos*/ + lista *aux = xdesktop->lista_caixas->prox; + if (aux->comando->disponibilidade == false) + aux = proxima_caixa_disp(perc); + aux->comando->ativado = true; + goto_xy(aux->comando->x, aux->comando->y); + } else + trata_cursor(no_ativo->comando); + + } else { + puts("Nao ha controles neste desktop. O programa será abortado."); + free_lista(&(xdesktop->lista_caixas)); + free(xdesktop); + restaura_tela(); + exit(0); + } + return xdesktop; +} + +desktop *monitora_desktop(desktop *xdesktop) { + if (xdesktop->lista_caixas->prox) { + lista *no_ativo = busca_por_ativo(xdesktop->lista_caixas); + struct termios conf; + int carac; + + tcgetattr (0, &conf); + sem_enter(conf); + carac = le_caracter(); + if (carac == TAB) { + no_ativo->comando->ativado = false; + no_ativo->comando = garante_invisib_itens(no_ativo->comando); + no_ativo = proxima_caixa_disp(no_ativo); + no_ativo->comando->ativado = true; + } + tcsetattr(0, TCSANOW, &conf); + if (carac == ESC) { + free_lista(&(xdesktop->lista_caixas)); + free(xdesktop); + restaura_tela(); + exit(0); + } + if (carac == DEL) { + clrscr(); + xdesktop = gerencia_remocao(xdesktop); + } + no_ativo->comando->monitora(no_ativo->comando, carac); + } + return xdesktop; +} + +desktop *atualiza_desktop(desktop *xdesktop) { + return xdesktop; +} diff --git a/pool/shard006/C/0120248_tree.c b/pool/shard006/C/0120248_tree.c new file mode 100644 index 0000000000000000000000000000000000000000..f612c48ddbb6d23b4b2600720455e0e6ac9013b1 --- /dev/null +++ b/pool/shard006/C/0120248_tree.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include "algo.h" + +typedef struct s_node { + int value; + struct s_node *left; + struct s_node *right; +} node; + +node *create_node(int value) { + node *ret = malloc(sizeof(*ret)); + + ret->right = ret->left = NULL; + ret->value = value; + return ret; +} + +void add_node(node *n, int value) { + if (value > n->value) { + if (n->right) + add_node(n->right, value); + else { + n->right = create_node(value); + } + } else { + if (n->left) + add_node(n->left, value); + else + n->left = create_node(value); + } +} + +void recreate_array(int *array, int *i, node **n) { + if ((*n)->left) { + recreate_array(array, i, &((*n)->left)); + } else { + array[(*i)++] = (*n)->value; + } + if ((*n)->right) { + recreate_array(array, i, &((*n)->right)); + } + free(*n); +} + +void tree_sort(int *array, int size) { + node *head = create_node(array[0]); + int i = 1; + + while (i < size) { + add_node(head, array[i++]); + } + i = 0; + recreate_array(array, &i, &head); +} \ No newline at end of file diff --git a/pool/shard006/C/0120253_exipe.c b/pool/shard006/C/0120253_exipe.c new file mode 100644 index 0000000000000000000000000000000000000000..45565b178c0f190be0c73fe25463b1aef1acb89c --- /dev/null +++ b/pool/shard006/C/0120253_exipe.c @@ -0,0 +1,172 @@ +/*==================================================================*\ +| EXIP - Embeddable EXI Processor in C | +|--------------------------------------------------------------------| +| This work is licensed under BSD 3-Clause License | +| The full license terms and conditions are located in LICENSE.txt | +\===================================================================*/ + +/** + * @file exipe.c + * @brief Command-line utility for testing the EXI encoder + * + * @date Nov 5, 2012 + * @author Rumen Kyusakov + * @version 0.5 + * @par[Revision] $Id$ + */ + +#include "encodeTestEXI.h" +#include "grammarGenerator.h" + +#define MAX_XSD_FILES_COUNT 10 // up to 10 XSD files + +static void printfHelp(); +size_t writeFileOutputStream(void* buf, size_t readSize, void* stream); +static void parseSchema(char* xsdList, EXIPSchema* schema); + +int main(int argc, char *argv[]) +{ + errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; + FILE *outfile = stdout; // Default is the standard output + char sourceFile[500]; + EXIPSchema schema; + EXIPSchema* schemaPtr = NULL; + int argIndex = 1; + + strcpy(sourceFile, "stdout"); + + if(argc >= 2) + { + if(strcmp(argv[argIndex], "-help") == 0) + { + printfHelp(); + return 0; + } + else if(strstr(argv[argIndex], "-schema") != NULL) + { + // Schema enabled encoding is requested. + // All the xsd files should be passed as comma-separated list + char* xsdList = argv[argIndex] + 7; + + parseSchema(xsdList, &schema); + + schemaPtr = &schema; + argIndex++; + } + } + + if(argIndex < argc) + { + strcpy(sourceFile, argv[argIndex]); + + outfile = fopen(sourceFile, "wb" ); + if(!outfile) + { + fprintf(stderr, "Unable to open file %s", sourceFile); + return 1; + } + } + + tmp_err_code = encode(schemaPtr, outfile, writeFileOutputStream); + + if(schemaPtr != NULL) + destroySchema(schemaPtr); + + if(tmp_err_code != EXIP_OK) + printf("\nError (code: %d) during encoding of: %s\n", tmp_err_code, sourceFile); + else + printf("\nSuccessful encoding in %s\n", sourceFile); + + fclose(outfile); + + return 0; +} + +static void printfHelp() +{ + printf("\n" ); + printf(" EXIP Copyright (c) 2010 - 2012, EISLAB - Luleå University of Technology Version 0.4 \n"); + printf(" Author: Rumen Kyusakov\n"); + printf(" Usage: exipe [options] [exi_out]\n\n"); + printf(" Options: [-help | -schema=] \n"); + printf(" -schema : uses schema defined in for encoding. All referenced schema files should be included in \n"); + printf(" : Comma-separated list of schema documents encoded in EXI with Preserve.prefixes. The first schema is the\n"); + printf(" main one and the rest are schemas that are referenced from the main one through the statement.\n"); + printf(" -help : Prints this help message\n\n"); + printf(" exi_out : output file for the EXI stream (stdout if none specified)\n\n"); + printf(" Purpose: This program tests the EXIP encoding functionality\n"); + printf("\n" ); +} + +size_t writeFileOutputStream(void* buf, size_t readSize, void* stream) +{ + FILE *outfile = (FILE*) stream; + return fwrite(buf, 1, readSize, outfile); +} + +static void parseSchema(char* xsdList, EXIPSchema* schema) +{ + errorCode tmp_err_code = EXIP_UNEXPECTED_ERROR; + FILE *schemaFile; + BinaryBuffer buffer[MAX_XSD_FILES_COUNT]; // up to 10 XSD files + char schemaFileName[500]; + unsigned int schemaFilesCount = 0; + unsigned int i; + char *token; + + for (token = strtok(xsdList, "=,"), i = 0; token != NULL; token = strtok(NULL, "=,"), i++) + { + schemaFilesCount++; + if(schemaFilesCount > MAX_XSD_FILES_COUNT) + { + fprintf(stderr, "Too many xsd files given as an input: %d", schemaFilesCount); + exit(1); + } + + strcpy(schemaFileName, token); + schemaFile = fopen(schemaFileName, "rb" ); + if(!schemaFile) + { + fprintf(stderr, "Unable to open file %s", schemaFileName); + exit(1); + } + else + { + //Get file length + fseek(schemaFile, 0, SEEK_END); + buffer[i].bufLen = ftell(schemaFile) + 1; + fseek(schemaFile, 0, SEEK_SET); + + //Allocate memory + buffer[i].buf = (char *) malloc(buffer[i].bufLen); + if (!buffer[i].buf) + { + fprintf(stderr, "Memory allocation error!"); + fclose(schemaFile); + exit(1); + } + + //Read file contents into buffer + fread(buffer[i].buf, buffer[i].bufLen, 1, schemaFile); + fclose(schemaFile); + + buffer[i].bufContent = buffer[i].bufLen; + buffer[i].ioStrm.readWriteToStream = NULL; + buffer[i].ioStrm.stream = NULL; + } + } + + // Generate the EXI grammars based on the schema information + tmp_err_code = generateSchemaInformedGrammars(buffer, schemaFilesCount, SCHEMA_FORMAT_XSD_EXI, NULL, schema, NULL); + + for(i = 0; i < schemaFilesCount; i++) + { + free(buffer[i].buf); + } + + if(tmp_err_code != EXIP_OK) + { + printf("\nGrammar generation error occurred: %d", tmp_err_code); + exit(1); + } +} diff --git a/pool/shard006/C/0120255_test_Symm_rl.c b/pool/shard006/C/0120255_test_Symm_rl.c new file mode 100644 index 0000000000000000000000000000000000000000..0b97eaedaf7b3ec4a1c9764bc3f16342c3329f65 --- /dev/null +++ b/pool/shard006/C/0120255_test_Symm_rl.c @@ -0,0 +1,216 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ +#include "FLAME.h" + + + +#define N_VARIANTS 10 + +#define FLA_ALG_REFERENCE 0 +#define FLA_ALG_UNBLOCKED 1 +#define FLA_ALG_BLOCKED 2 + + +void time_Symm_rl( + int variant, int type, int n_repeats, int n, int nb_alg, + FLA_Obj A, FLA_Obj B, FLA_Obj C, FLA_Obj C_ref, + double *dtime, double *diff, double *gflops ); + + +int main(int argc, char *argv[]) +{ + int + m_input, n_input, + m, n, + p_first, p_last, p_inc, + p, + nb_alg, + n_repeats, + variant, + i, j, + datatype, + n_variants = N_VARIANTS; + + char *colors = "brkgmcbrkg"; + char *ticks = "o+*xso+*xs"; + char m_dim_desc[14]; + char n_dim_desc[14]; + char m_dim_tag[10]; + char n_dim_tag[10]; + + double max_gflops=6.0; + + double + dtime, + gflops, + diff, + d_n; + + FLA_Obj + A, B, C, C_ref; + + /* Initialize FLAME */ + FLA_Init( ); + + + fprintf( stdout, "%c number of repeats: ", '%' ); + scanf( "%d", &n_repeats ); + fprintf( stdout, "%c %d\n", '%', n_repeats ); + + fprintf( stdout, "%c Enter blocking size: ", '%' ); + scanf( "%d", &nb_alg ); + fprintf( stdout, "%c %d\n", '%', nb_alg ); + + fprintf( stdout, "%c enter problem size first, last, inc: ", '%' ); + scanf( "%d%d%d", &p_first, &p_last, &p_inc ); + fprintf( stdout, "%c %d %d %d\n", '%', p_first, p_last, p_inc ); + + fprintf( stdout, "%c enter m n (-1 means bind to problem size): ", '%' ); + scanf( "%d%d", &m_input, &n_input ); + fprintf( stdout, "%c %d %d\n", '%', m_input, n_input ); + + + /* Delete all existing data structures */ + fprintf( stdout, "\nclear all;\n\n" ); + + + if ( m_input > 0 ) { + sprintf( m_dim_desc, "m = %d", m_input ); + sprintf( m_dim_tag, "m%dc", m_input); + } + else if( m_input < -1 ) { + sprintf( m_dim_desc, "m = p/%d", -m_input ); + sprintf( m_dim_tag, "m%dp", -m_input ); + } + else if( m_input == -1 ) { + sprintf( m_dim_desc, "m = p" ); + sprintf( m_dim_tag, "m%dp", 1 ); + } + if ( n_input > 0 ) { + sprintf( n_dim_desc, "n = %d", n_input ); + sprintf( n_dim_tag, "n%dc", n_input); + } + else if( n_input < -1 ) { + sprintf( n_dim_desc, "n = p/%d", -n_input ); + sprintf( n_dim_tag, "n%dp", -n_input ); + } + else if( n_input == -1 ) { + sprintf( n_dim_desc, "n = p" ); + sprintf( n_dim_tag, "n%dp", 1 ); + } + + + + for ( p = p_first, i = 1; p <= p_last; p += p_inc, i += 1 ) + { + + m = m_input; + n = n_input; + + if( m < 0 ) m = p / abs(m_input); + if( n < 0 ) n = p / abs(n_input); + + //datatype = FLA_FLOAT; + datatype = FLA_DOUBLE; + //datatype = FLA_COMPLEX; + //datatype = FLA_DOUBLE_COMPLEX; + + /* Allocate space for the matrices */ + FLA_Obj_create( datatype, n, n, &A ); + FLA_Obj_create( datatype, m, n, &B ); + FLA_Obj_create( datatype, m, n, &C ); + FLA_Obj_create( datatype, m, n, &C_ref ); + + /* Generate random matrices A, C */ + FLA_Random_matrix( A ); + FLA_Random_matrix( B ); + FLA_Random_matrix( C ); + + FLA_Copy_external( C, C_ref ); + + + /* Time the reference implementation */ + time_Symm_rl( 0, FLA_ALG_REFERENCE, n_repeats, p, nb_alg, + A, B, C, C_ref, &dtime, &diff, &gflops ); + + fprintf( stdout, "data_REF( %d, 1:2 ) = [ %d %6.3lf ]; \n", i, p, gflops ); + fflush( stdout ); + + for ( variant = 1; variant <= n_variants; variant++ ){ + + fprintf( stdout, "data_var%d( %d, 1:5 ) = [ %d ", variant, i, p ); + fflush( stdout ); + + + time_Symm_rl( variant, FLA_ALG_UNBLOCKED, n_repeats, p, nb_alg, + A, B, C, C_ref, &dtime, &diff, &gflops ); + + fprintf( stdout, "%6.3lf %6.2le ", gflops, diff ); + fflush( stdout ); + + time_Symm_rl( variant, FLA_ALG_BLOCKED, n_repeats, p, nb_alg, + A, B, C, C_ref, &dtime, &diff, &gflops ); + + fprintf( stdout, "%6.3lf %6.2le ", gflops, diff ); + fflush( stdout ); + + + fprintf( stdout, " ]; \n" ); + fflush( stdout ); + } + fprintf( stdout, "\n" ); + + FLA_Obj_free( &A ); + FLA_Obj_free( &B ); + FLA_Obj_free( &C ); + FLA_Obj_free( &C_ref ); + } + + /* Print the MATLAB commands to plot the data */ + + /* Delete all existing figures */ + fprintf( stdout, "figure;\n" ); + + /* Plot the performance of the reference implementation */ + fprintf( stdout, "plot( data_REF( :,1 ), data_REF( :, 2 ), '-' ); \n" ); + + /* Indicate that you want to add to the existing plot */ + fprintf( stdout, "hold on;\n" ); + + /* Plot the data for the other numbers of threads */ + for ( i = 1; i <= n_variants; i++ ){ + fprintf( stdout, "plot( data_var%d( :,1 ), data_var%d( :, 2 ), '%c:%c' ); \n", + i, i, colors[ i-1 ], ticks[ i-1 ] ); + fprintf( stdout, "plot( data_var%d( :,1 ), data_var%d( :, 4 ), '%c-.%c' ); \n", + i, i, colors[ i-1 ], ticks[ i-1 ] ); + } + + fprintf( stdout, "legend( ... \n" ); + fprintf( stdout, "'Reference', ... \n" ); + + for ( i = 1; i < n_variants; i++ ) + fprintf( stdout, "'unb\\_var%d', 'blk\\_var%d', ... \n", i, i ); + + i = n_variants; + fprintf( stdout, "'unb\\_var%d', 'blk\\_var%d' ); \n", i, i ); + + + fprintf( stdout, "xlabel( 'problem size p' );\n" ); + fprintf( stdout, "ylabel( 'GFLOPS/sec.' );\n" ); + fprintf( stdout, "axis( [ 0 %d 0 %.2f ] ); \n", p_last, max_gflops ); + fprintf( stdout, "title( 'FLAME symm\\_rl performance (%s, %s)' );\n", + m_dim_desc, n_dim_desc ); + fprintf( stdout, "print -depsc symm_rl_%s_%s.eps\n", m_dim_tag, n_dim_tag ); + fprintf( stdout, "hold off;\n"); + fflush( stdout ); + + FLA_Finalize( ); +} + diff --git a/pool/shard006/C/0120259_dvfs.c b/pool/shard006/C/0120259_dvfs.c new file mode 100644 index 0000000000000000000000000000000000000000..ab0aa66a8901677c83801c33be800f61daada05f --- /dev/null +++ b/pool/shard006/C/0120259_dvfs.c @@ -0,0 +1,48 @@ +#include "sim_api.h" + +#define __STDC_LIMIT_MACROS +#define __STDC_CONSTANT_MACROS +#include +#include + +int value; + +int loop() { + + int i; + for (i = 0 ; i < 10000; i++) { + value += i; + } + return value; +} + +int main() { + + SimRoiStart(); + + value = 0; + loop(); + + unsigned long freq = SimGetOwnFreqMHz(); + printf("Current Freq = %lu MHz\n", freq); + + freq = 5000; + printf("Setting frequency to %lu MHz\n", freq); + SimSetOwnFreqMHz(freq); + freq = SimGetOwnFreqMHz(); + printf("Current Freq = %lu MHz\n", freq); + + value = 0; + loop(); + + freq = 1000; + printf("Setting frequency to %lu MHz\n", freq); + SimSetFreqMHz(1, freq); + freq = SimGetFreqMHz(1); + printf("Current Freq = %lu MHz\n", freq); + + value = 0; + loop(); + + SimRoiEnd(); +} diff --git a/pool/shard006/C/0120263_license.c b/pool/shard006/C/0120263_license.c new file mode 100644 index 0000000000000000000000000000000000000000..29fc8aa9a41fba47c0851680ec6a2c0fc2470f21 --- /dev/null +++ b/pool/shard006/C/0120263_license.c @@ -0,0 +1,45 @@ +/* + * (C) Copyright 2007 by OpenMoko, Inc. + * Author: Harald Welte + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include + +#include "license_data_gz.h" +#include "license_data_size.h" + +static int do_license(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + char *dst; + unsigned long len = data_size; + int ret = CMD_RET_SUCCESS; + + dst = malloc(data_size + 1); + if (!dst) + return CMD_RET_FAILURE; + + ret = gunzip(dst, data_size, (unsigned char *)data_gz, &len); + if (ret) { + printf("Error uncompressing license text\n"); + ret = CMD_RET_FAILURE; + goto free; + } + + dst[data_size] = 0; + puts(dst); + +free: + free(dst); + + return ret; +} + +U_BOOT_CMD( + license, 1, 1, do_license, + "print GPL license text", + "" +); diff --git a/pool/shard006/C/0120265_rmi_f55.c b/pool/shard006/C/0120265_rmi_f55.c new file mode 100644 index 0000000000000000000000000000000000000000..37390ca6a9249788820b41a6cc3855065f8ffefb --- /dev/null +++ b/pool/shard006/C/0120265_rmi_f55.c @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2012-2015 Synaptics Incorporated + * Copyright (C) 2016 Zodiac Inflight Innovations + * + * 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 +#include +#include +#include +#include "rmi_driver.h" + +#define F55_NAME "rmi4_f55" + +/* F55 data offsets */ +#define F55_NUM_RX_OFFSET 0 +#define F55_NUM_TX_OFFSET 1 +#define F55_PHYS_CHAR_OFFSET 2 + +/* Only read required query registers */ +#define F55_QUERY_LEN 3 + +/* F55 capabilities */ +#define F55_CAP_SENSOR_ASSIGN BIT(0) + +struct f55_data { + struct rmi_function *fn; + + u8 qry[F55_QUERY_LEN]; + u8 num_rx_electrodes; + u8 cfg_num_rx_electrodes; + u8 num_tx_electrodes; + u8 cfg_num_tx_electrodes; +}; + +static int rmi_f55_detect(struct rmi_function *fn) +{ + struct rmi_device *rmi_dev = fn->rmi_dev; + struct rmi_driver_data *drv_data = dev_get_drvdata(&rmi_dev->dev); + struct f55_data *f55; + int error; + + f55 = dev_get_drvdata(&fn->dev); + + error = rmi_read_block(fn->rmi_dev, fn->fd.query_base_addr, + &f55->qry, sizeof(f55->qry)); + if (error) { + dev_err(&fn->dev, "%s: Failed to query F55 properties\n", + __func__); + return error; + } + + f55->num_rx_electrodes = f55->qry[F55_NUM_RX_OFFSET]; + f55->num_tx_electrodes = f55->qry[F55_NUM_TX_OFFSET]; + + f55->cfg_num_rx_electrodes = f55->num_rx_electrodes; + f55->cfg_num_tx_electrodes = f55->num_rx_electrodes; + + drv_data->num_rx_electrodes = f55->cfg_num_rx_electrodes; + drv_data->num_tx_electrodes = f55->cfg_num_rx_electrodes; + + if (f55->qry[F55_PHYS_CHAR_OFFSET] & F55_CAP_SENSOR_ASSIGN) { + int i, total; + u8 buf[256]; + + /* + * Calculate the number of enabled receive and transmit + * electrodes by reading F55:Ctrl1 (sensor receiver assignment) + * and F55:Ctrl2 (sensor transmitter assignment). The number of + * enabled electrodes is the sum of all field entries with a + * value other than 0xff. + */ + error = rmi_read_block(fn->rmi_dev, + fn->fd.control_base_addr + 1, + buf, f55->num_rx_electrodes); + if (!error) { + total = 0; + for (i = 0; i < f55->num_rx_electrodes; i++) { + if (buf[i] != 0xff) + total++; + } + f55->cfg_num_rx_electrodes = total; + drv_data->num_rx_electrodes = total; + } + + error = rmi_read_block(fn->rmi_dev, + fn->fd.control_base_addr + 2, + buf, f55->num_tx_electrodes); + if (!error) { + total = 0; + for (i = 0; i < f55->num_tx_electrodes; i++) { + if (buf[i] != 0xff) + total++; + } + f55->cfg_num_tx_electrodes = total; + drv_data->num_tx_electrodes = total; + } + } + + rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F55 num_rx_electrodes: %d (raw %d)\n", + f55->cfg_num_rx_electrodes, f55->num_rx_electrodes); + rmi_dbg(RMI_DEBUG_FN, &fn->dev, "F55 num_tx_electrodes: %d (raw %d)\n", + f55->cfg_num_tx_electrodes, f55->num_tx_electrodes); + + return 0; +} + +static int rmi_f55_probe(struct rmi_function *fn) +{ + struct f55_data *f55; + + f55 = devm_kzalloc(&fn->dev, sizeof(struct f55_data), GFP_KERNEL); + if (!f55) + return -ENOMEM; + + f55->fn = fn; + dev_set_drvdata(&fn->dev, f55); + + return rmi_f55_detect(fn); +} + +struct rmi_function_handler rmi_f55_handler = { + .driver = { + .name = F55_NAME, + }, + .func = 0x55, + .probe = rmi_f55_probe, +}; diff --git a/pool/shard006/C/0120266_time.c b/pool/shard006/C/0120266_time.c new file mode 100644 index 0000000000000000000000000000000000000000..5facc9bff4ef68b584aa32fb263b99461e90eb77 --- /dev/null +++ b/pool/shard006/C/0120266_time.c @@ -0,0 +1,259 @@ +/* + * linux/arch/parisc/kernel/time.c + * + * Copyright (C) 1991, 1992, 1995 Linus Torvalds + * Modifications for ARM (C) 1994, 1995, 1996,1997 Russell King + * Copyright (C) 1999 SuSE GmbH, (Philipp Rumpf, prumpf@tux.org) + * + * 1994-07-02 Alan Modra + * fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime + * 1998-12-20 Updated NTP code according to technical memorandum Jan '96 + * "A Kernel Model for Precision Timekeeping" by Dave Mills + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +/* xtime and wall_jiffies keep wall-clock time */ +extern unsigned long wall_jiffies; + +static long clocktick __read_mostly; /* timer cycles per tick */ +static long halftick __read_mostly; + +#ifdef CONFIG_SMP +extern void smp_do_timer(struct pt_regs *regs); +#endif + +irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs *regs) +{ + long now; + long next_tick; + int nticks; + int cpu = smp_processor_id(); + + profile_tick(CPU_PROFILING, regs); + + now = mfctl(16); + /* initialize next_tick to time at last clocktick */ + next_tick = cpu_data[cpu].it_value; + + /* since time passes between the interrupt and the mfctl() + * above, it is never true that last_tick + clocktick == now. If we + * never miss a clocktick, we could set next_tick = last_tick + clocktick + * but maybe we'll miss ticks, hence the loop. + * + * Variables are *signed*. + */ + + nticks = 0; + while((next_tick - now) < halftick) { + next_tick += clocktick; + nticks++; + } + mtctl(next_tick, 16); + cpu_data[cpu].it_value = next_tick; + + while (nticks--) { +#ifdef CONFIG_SMP + smp_do_timer(regs); +#else + update_process_times(user_mode(regs)); +#endif + if (cpu == 0) { + write_seqlock(&xtime_lock); + do_timer(regs); + write_sequnlock(&xtime_lock); + } + } + + /* check soft power switch status */ + if (cpu == 0 && !atomic_read(&power_tasklet.count)) + tasklet_schedule(&power_tasklet); + + return IRQ_HANDLED; +} + + +unsigned long profile_pc(struct pt_regs *regs) +{ + unsigned long pc = instruction_pointer(regs); + + if (regs->gr[0] & PSW_N) + pc -= 4; + +#ifdef CONFIG_SMP + if (in_lock_functions(pc)) + pc = regs->gr[2]; +#endif + + return pc; +} +EXPORT_SYMBOL(profile_pc); + + +/*** converted from ia64 ***/ +/* + * Return the number of micro-seconds that elapsed since the last + * update to wall time (aka xtime aka wall_jiffies). The xtime_lock + * must be at least read-locked when calling this routine. + */ +static inline unsigned long +gettimeoffset (void) +{ +#ifndef CONFIG_SMP + /* + * FIXME: This won't work on smp because jiffies are updated by cpu 0. + * Once parisc-linux learns the cr16 difference between processors, + * this could be made to work. + */ + long last_tick; + long elapsed_cycles; + + /* it_value is the intended time of the next tick */ + last_tick = cpu_data[smp_processor_id()].it_value; + + /* Subtract one tick and account for possible difference between + * when we expected the tick and when it actually arrived. + * (aka wall vs real) + */ + last_tick -= clocktick * (jiffies - wall_jiffies + 1); + elapsed_cycles = mfctl(16) - last_tick; + + /* the precision of this math could be improved */ + return elapsed_cycles / (PAGE0->mem_10msec / 10000); +#else + return 0; +#endif +} + +void +do_gettimeofday (struct timeval *tv) +{ + unsigned long flags, seq, usec, sec; + + do { + seq = read_seqbegin_irqsave(&xtime_lock, flags); + usec = gettimeoffset(); + sec = xtime.tv_sec; + usec += (xtime.tv_nsec / 1000); + } while (read_seqretry_irqrestore(&xtime_lock, seq, flags)); + + if (unlikely(usec > LONG_MAX)) { + /* This can happen if the gettimeoffset adjustment is + * negative and xtime.tv_nsec is smaller than the + * adjustment */ + printk(KERN_ERR "do_gettimeofday() spurious xtime.tv_nsec of %ld\n", usec); + usec += USEC_PER_SEC; + --sec; + /* This should never happen, it means the negative + * time adjustment was more than a second, so there's + * something seriously wrong */ + BUG_ON(usec > LONG_MAX); + } + + + while (usec >= USEC_PER_SEC) { + usec -= USEC_PER_SEC; + ++sec; + } + + tv->tv_sec = sec; + tv->tv_usec = usec; +} + +EXPORT_SYMBOL(do_gettimeofday); + +int +do_settimeofday (struct timespec *tv) +{ + time_t wtm_sec, sec = tv->tv_sec; + long wtm_nsec, nsec = tv->tv_nsec; + + if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC) + return -EINVAL; + + write_seqlock_irq(&xtime_lock); + { + /* + * This is revolting. We need to set "xtime" + * correctly. However, the value in this location is + * the value at the most recent update of wall time. + * Discover what correction gettimeofday would have + * done, and then undo it! + */ + nsec -= gettimeoffset() * 1000; + + wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec); + wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec); + + set_normalized_timespec(&xtime, sec, nsec); + set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec); + + ntp_clear(); + } + write_sequnlock_irq(&xtime_lock); + clock_was_set(); + return 0; +} +EXPORT_SYMBOL(do_settimeofday); + +/* + * XXX: We can do better than this. + * Returns nanoseconds + */ + +unsigned long long sched_clock(void) +{ + return (unsigned long long)jiffies * (1000000000 / HZ); +} + + +void __init time_init(void) +{ + unsigned long next_tick; + static struct pdc_tod tod_data; + + clocktick = (100 * PAGE0->mem_10msec) / HZ; + halftick = clocktick / 2; + + /* Setup clock interrupt timing */ + + next_tick = mfctl(16); + next_tick += clocktick; + cpu_data[smp_processor_id()].it_value = next_tick; + + /* kick off Itimer (CR16) */ + mtctl(next_tick, 16); + + if(pdc_tod_read(&tod_data) == 0) { + write_seqlock_irq(&xtime_lock); + xtime.tv_sec = tod_data.tod_sec; + xtime.tv_nsec = tod_data.tod_usec * 1000; + set_normalized_timespec(&wall_to_monotonic, + -xtime.tv_sec, -xtime.tv_nsec); + write_sequnlock_irq(&xtime_lock); + } else { + printk(KERN_ERR "Error reading tod clock\n"); + xtime.tv_sec = 0; + xtime.tv_nsec = 0; + } +} + diff --git a/pool/shard006/C/0120268_arm_mat_scale_q15.c b/pool/shard006/C/0120268_arm_mat_scale_q15.c new file mode 100644 index 0000000000000000000000000000000000000000..58011254c8b7e539c996f9d1c184e080404eab4f --- /dev/null +++ b/pool/shard006/C/0120268_arm_mat_scale_q15.c @@ -0,0 +1,181 @@ +/* ---------------------------------------------------------------------- +* Copyright (C) 2010 ARM Limited. All rights reserved. +* +* $Date: 15. February 2012 +* $Revision: V1.1.0 +* +* Project: CMSIS DSP Library +* Title: arm_mat_scale_q15.c +* +* Description: Multiplies a Q15 matrix by a scalar. +* +* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 +* +* Version 1.1.0 2012/02/15 +* Updated with more optimizations, bug fixes and minor API changes. +* +* Version 1.0.10 2011/7/15 +* Big Endian support added and Merged M0 and M3/M4 Source code. +* +* Version 1.0.3 2010/11/29 +* Re-organized the CMSIS folders and updated documentation. +* +* Version 1.0.2 2010/11/11 +* Documentation updated. +* +* Version 1.0.1 2010/10/05 +* Production release and review comments incorporated. +* +* Version 1.0.0 2010/09/20 +* Production release and review comments incorporated. +* +* Version 0.0.5 2010/04/26 +* incorporated review comments and updated with latest CMSIS layer +* +* Version 0.0.3 2010/03/10 +* Initial version +* -------------------------------------------------------------------- */ + +#include "arm_math.h" + +/** + * @ingroup groupMatrix + */ + +/** + * @addtogroup MatrixScale + * @{ + */ + +/** + * @brief Q15 matrix scaling. + * @param[in] *pSrc points to input matrix + * @param[in] scaleFract fractional portion of the scale factor + * @param[in] shift number of bits to shift the result by + * @param[out] *pDst points to output matrix structure + * @return The function returns either + * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking. + * + * @details + * Scaling and Overflow Behavior: + * \par + * The input data *pSrc and scaleFract are in 1.15 format. + * These are multiplied to yield a 2.30 intermediate result and this is shifted with saturation to 1.15 format. + */ + +arm_status arm_mat_scale_q15( + const arm_matrix_instance_q15 * pSrc, + q15_t scaleFract, + int32_t shift, + arm_matrix_instance_q15 * pDst) +{ + q15_t *pIn = pSrc->pData; /* input data matrix pointer */ + q15_t *pOut = pDst->pData; /* output data matrix pointer */ + uint32_t numSamples; /* total number of elements in the matrix */ + int32_t totShift = 15 - shift; /* total shift to apply after scaling */ + uint32_t blkCnt; /* loop counters */ + arm_status status; /* status of matrix scaling */ + +#ifndef ARM_MATH_CM0 + + q15_t in1, in2, in3, in4; + q31_t out1, out2, out3, out4; + q31_t inA1, inA2; + +#endif // #ifndef ARM_MATH_CM0 + +#ifdef ARM_MATH_MATRIX_CHECK + /* Check for matrix mismatch */ + if((pSrc->numRows != pDst->numRows) || (pSrc->numCols != pDst->numCols)) + { + /* Set status as ARM_MATH_SIZE_MISMATCH */ + status = ARM_MATH_SIZE_MISMATCH; + } + else +#endif // #ifdef ARM_MATH_MATRIX_CHECK + { + /* Total number of samples in the input matrix */ + numSamples = (uint32_t) pSrc->numRows * pSrc->numCols; + +#ifndef ARM_MATH_CM0 + + /* Run the below code for Cortex-M4 and Cortex-M3 */ + /* Loop Unrolling */ + blkCnt = numSamples >> 2; + + /* First part of the processing with loop unrolling. Compute 4 outputs at a time. + ** a second loop below computes the remaining 1 to 3 samples. */ + while(blkCnt > 0u) + { + /* C(m,n) = A(m,n) * k */ + /* Scale, saturate and then store the results in the destination buffer. */ + /* Reading 2 inputs from memory */ + inA1 = _SIMD32_OFFSET(pIn); + inA2 = _SIMD32_OFFSET(pIn + 2); + + /* C = A * scale */ + /* Scale the inputs and then store the 2 results in the destination buffer + * in single cycle by packing the outputs */ + out1 = (q31_t) ((q15_t) (inA1 >> 16) * scaleFract); + out2 = (q31_t) ((q15_t) inA1 * scaleFract); + out3 = (q31_t) ((q15_t) (inA2 >> 16) * scaleFract); + out4 = (q31_t) ((q15_t) inA2 * scaleFract); + + out1 = out1 >> totShift; + inA1 = _SIMD32_OFFSET(pIn + 4); + out2 = out2 >> totShift; + inA2 = _SIMD32_OFFSET(pIn + 6); + out3 = out3 >> totShift; + out4 = out4 >> totShift; + + in1 = (q15_t) (__SSAT(out1, 16)); + in2 = (q15_t) (__SSAT(out2, 16)); + in3 = (q15_t) (__SSAT(out3, 16)); + in4 = (q15_t) (__SSAT(out4, 16)); + + _SIMD32_OFFSET(pOut) = __PKHBT(in2, in1, 16); + _SIMD32_OFFSET(pOut + 2) = __PKHBT(in4, in3, 16); + + /* update pointers to process next sampels */ + pIn += 4u; + pOut += 4u; + + + /* Decrement the numSamples loop counter */ + blkCnt--; + } + + /* If the numSamples is not a multiple of 4, compute any remaining output samples here. + ** No loop unrolling is used. */ + blkCnt = numSamples % 0x4u; + +#else + + /* Run the below code for Cortex-M0 */ + + /* Initialize blkCnt with number of samples */ + blkCnt = numSamples; + +#endif /* #ifndef ARM_MATH_CM0 */ + + while(blkCnt > 0u) + { + /* C(m,n) = A(m,n) * k */ + /* Scale, saturate and then store the results in the destination buffer. */ + *pOut++ = + (q15_t) (__SSAT(((q31_t) (*pIn++) * scaleFract) >> totShift, 16)); + + /* Decrement the numSamples loop counter */ + blkCnt--; + } + /* Set status as ARM_MATH_SUCCESS */ + status = ARM_MATH_SUCCESS; + } + + /* Return to application */ + return (status); +} + +/** + * @} end of MatrixScale group + */ diff --git a/pool/shard006/C/0120272_s_rintf.c b/pool/shard006/C/0120272_s_rintf.c new file mode 100644 index 0000000000000000000000000000000000000000..bef417a7d1254092c60c00462e571d9bcbea0908 --- /dev/null +++ b/pool/shard006/C/0120272_s_rintf.c @@ -0,0 +1,59 @@ +/* s_rintf.c -- float version of s_rint.c. + * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. + */ + +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include "math.h" +#include "math_private.h" + +static const float +TWO23[2]={ + 8.3886080000e+06, /* 0x4b000000 */ + -8.3886080000e+06, /* 0xcb000000 */ +}; + +float +rintf(float x) +{ + int32_t i0,jj0,sx; + u_int32_t i,i1; + float w,t; + GET_FLOAT_WORD(i0,x); + sx = (i0>>31)&1; + jj0 = ((i0>>23)&0xff)-0x7f; + if(jj0<23) { + if(jj0<0) { + if((i0&0x7fffffff)==0) return x; + i1 = (i0&0x07fffff); + i0 &= 0xfff00000; + i0 |= ((i1|-i1)>>9)&0x400000; + SET_FLOAT_WORD(x,i0); + w = TWO23[sx]+x; + t = w-TWO23[sx]; + GET_FLOAT_WORD(i0,t); + SET_FLOAT_WORD(t,(i0&0x7fffffff)|(sx<<31)); + return t; + } else { + i = (0x007fffff)>>jj0; + if((i0&i)==0) return x; /* x is integral */ + i>>=1; + if((i0&i)!=0) i0 = (i0&(~i))|((0x100000)>>jj0); + } + } else { + if(jj0==0x80) return x+x; /* inf or NaN */ + else return x; /* x is integral */ + } + SET_FLOAT_WORD(x,i0); + w = TWO23[sx]+x; + return w-TWO23[sx]; +} diff --git a/pool/shard006/C/0120274_PAL_get_stderr.c b/pool/shard006/C/0120274_PAL_get_stderr.c new file mode 100644 index 0000000000000000000000000000000000000000..0b4761353b6177c7a71e8117ec47c6606f195395 --- /dev/null +++ b/pool/shard006/C/0120274_PAL_get_stderr.c @@ -0,0 +1,53 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +/*============================================================= +** +** Source: pal_get_stderr.c +** +** Purpose: Positive test the PAL_get_stderr API. +** Call PAL_get_stderr to retrieve the PAL standard error +** output stream pointer. +** This test case should be run manually and automatically. +** + +** +**============================================================*/ +#include + +int __cdecl main(int argc, char *argv[]) +{ + int err; + FILE *pPAL_stderr = NULL; + const char *pMsg = "\nThis is a PAL_get_stderr test message, " + "not an error message!\n"; + + /*Initialize the PAL environment*/ + err = PAL_Initialize(argc, argv); + if(0 != err) + { + return FAIL; + } + + /*retrieve the PAL standard error output stream pointer*/ + pPAL_stderr = PAL_get_stderr(); + + if(NULL == pPAL_stderr) + { + Fail("\nFailed to call PAL_get_stderr API, error code = %u\n", + GetLastError()); + } + + /*output a test message through PAL standard error stream*/ + err = fputs(pMsg, pPAL_stderr); + if(EOF == err) + { + Fail("\nFailed to call fputs to output message to PAL stdandard " + "error stream, error code=%u\n", GetLastError()); + } + + PAL_Terminate(); + return PASS; +} diff --git a/pool/shard006/C/0120278_testeBizarro.c b/pool/shard006/C/0120278_testeBizarro.c new file mode 100644 index 0000000000000000000000000000000000000000..d47433796b64fcecb5e44661ca8419c881125ffc --- /dev/null +++ b/pool/shard006/C/0120278_testeBizarro.c @@ -0,0 +1,13 @@ +#include + +int main(){ + + printf("[data]: %s\n", __DATE__); + printf("[data]: %s\n", __FILE__); + printf("[data]: %s\n", __TIME__); + unsigned int v = (3>>9); + double val = (999999999999999999<<63); + long bigV = val*4; + printf("bitwise:%d\n",bigV); + +} diff --git a/pool/shard006/C/0120283_dz3z9.c b/pool/shard006/C/0120283_dz3z9.c new file mode 100644 index 0000000000000000000000000000000000000000..d68399fbf305cf13a71ea4632e56e0407c74c802 --- /dev/null +++ b/pool/shard006/C/0120283_dz3z9.c @@ -0,0 +1,124 @@ +/****************************** + * Tisma Miroslav 2006/0395 + * Multiprocesorski sistemi + * domaci zadatak 3 - 9. zadatak + *******************************/ + +/** + * 9. Sastaviti program koji racuna treci koren svakog elementa niza realnih brojeva. Proces sa rangom 0 + * (upravljac) treba da obavlja svu komunikaciju sa korisnikom i raspodelu poslova ostalim procesima + * (radnicima). Upravljac treba da salje neobradjene elemente niza slobodnim radnicima i da prihvata + * rezultate od radnika, sve dok ima neobradjenih elemenata. Radnici treba da prihvataju po jedan + * element niza, obradjuju i vracaju nazad sve dok ih upravljac ne obavesti da vise nema posla. + */ + +#include "mpi.h" +#include +#include +#include + +#define N 6 // maksimalan broj procesa u sistemu +#define FINISH 100 + +int main(int argc, char *argv[]) { + + int i, n, size, rank, msg = 0; + double *array; + int sent = 0, received = 0; + + MPI_Init(&argc, &argv); + + MPI_Comm_size(MPI_COMM_WORLD, &size); + + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + + if (size < 2 || size > N) { + MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); + exit(EXIT_FAILURE); + } + + if (rank == 0) { + printf("00:001:Unesite velicinu niza:\n"); + scanf("%d", &n); + array = (double *) malloc(n*sizeof(double)); + + for (i = 0; i < n; i++) { + ++msg; + printf("00:00%d:Unesite %d. element niza:\n", msg, i); + scanf("%lf", &array[i]); + } + + ++msg; + printf("00:00%d:Originalni niz:\n", msg); + for (i = 0; i < n; i++) + printf("%lf ", array[i]); + + printf("\n"); + + MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); + + if (n <= size-1) { + for (i = 0; i < n; i++) + MPI_Send(&array[i], 1, MPI_DOUBLE, i+1, 0, MPI_COMM_WORLD); + + for (i = n; i < size; i++) + MPI_Send(&i, 1, MPI_INT, i, FINISH, MPI_COMM_WORLD); + + ++msg; + printf("00:00%d:Korenovani niz:\n", msg); + for (i = 0; i < n; i++) { + MPI_Recv(&array[i], 1, MPI_DOUBLE, i+1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + printf("%lf ", array[i]); + } + } else { + int dest = 1; + while (sent <= n) { + MPI_Send(&array[sent], 1, MPI_DOUBLE, dest, 0, MPI_COMM_WORLD); + sent++; + dest = (dest + 1) % size; + if (dest == 0) + dest = 1; + } + while(sent > 0) { + MPI_Recv(&array[sent], 1, MPI_DOUBLE, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); + sent--; + } + for (i = 0; i < size; i++) + MPI_Send(&i, 1, MPI_INT, i+1, FINISH, MPI_COMM_WORLD); + + ++msg; + printf("00:00%d:Korenovani niz:\n", msg); + for (i = 0; i < n; i++) + printf("%lf ", array[i]); + printf("\n"); + } + + free(array); + } + else { + double root; + MPI_Status status; + + MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); + + if (n <= size-1) { + MPI_Recv(&root, 1, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); + if (status.MPI_TAG != FINISH) { + root = pow(root, 1.0/3.0); + MPI_Send(&root, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); + } + } else { + while (1) { + MPI_Recv(&root, 1, MPI_DOUBLE, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); + if (status.MPI_TAG != FINISH) { + root = pow(root, 1.0/3.0); + MPI_Send(&root, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD); + } else break; + } + } + } + + MPI_Finalize(); + + return EXIT_SUCCESS; +} diff --git a/pool/shard006/C/0120285_options.c b/pool/shard006/C/0120285_options.c new file mode 100644 index 0000000000000000000000000000000000000000..74f01471607c297c022da6e1861074036f275095 --- /dev/null +++ b/pool/shard006/C/0120285_options.c @@ -0,0 +1,137 @@ +#include "options.h" + +#define NO_MORE_OPTIONS -1 +#define OPTLIST "l:P:p:r:t:T:n:N:s:S:" + +void printUsage(void) +{ + printf("\n\nValid options are:\n" + "\t-l : type of lattice (site OR bond)\n" + "\t-P <0-1 float> : chance of allocation\n" + "\t-p <0, 1, OR 2> : whether percolation does UD, LR, or both\n" + "\t-r : how many runs per size for averaging\n" + "\t-t : min number of threads to use\n" + "\t-T : max number of threads to use\n" + "\t-n : min number of nodes to use\n" + "\t-N : max number of nodes to use\n" + "\t-s : min lattice size\n" + "\t-S : max lattice size\n\n"); + exit(EXIT_FAILURE); +} + +int readOptions(int argc, char *argv[], OPTIONS *options) +{ + int opt; + opterr = 0; + while((opt = getopt(argc, argv, OPTLIST)) != NO_MORE_OPTIONS) { + switch(opt) { + case 'l' : + if (optarg[0] == 's' || optarg[0] == 'b') { + options->type = optarg[0]; + } else { + argc = -1; + } break; + case 'P' : + if (atof(optarg) >= 0.0 && atof(optarg) <= 1.0) { + options->probability = atof(optarg); + } else { + argc = -1; + } break; + case 'p' : + if (atoi(optarg) >= 0 || atoi(optarg) <= 2) { + options->perlocationType = atoi(optarg); + } else { + argc = -1; + } break; + case 'r' : + if (atoi(optarg) > 0) { + options->runs = atoi(optarg); + } else { + argc = -1; + } break; + case 't' : + if (atoi(optarg) > 0) { + options->minThreadNum = atoi(optarg); + } else { + argc = -1; + } break; + case 'T' : + if (atoi(optarg) > 0) { + options->maxThreadNum = atoi(optarg); + } else { + argc = -1; + } break; + case 'n' : + if (atoi(optarg) > 0) { + options->minNodeNum = atoi(optarg); + } else { + argc = -1; + } break; + case 'N' : + if (atoi(optarg) > 0) { + options->maxNodeNum = atoi(optarg); + } else { + argc = -1; + } break; + case 's' : + if (atoi(optarg) > 0 && atoi(optarg) % 2 == 0) { + options->minSize = atoi(optarg); + } else { + argc = -1; + } break; + case 'S' : + if (atoi(optarg) >= options->minSize && atoi(optarg) % 2 == 0) { + options->maxSize = atoi(optarg); + } else { + argc = -1; + } break; + default : argc = -1; + } + if(argc < 0) { + fprintf(stderr, "\nError with options at: %c. : %s", optopt, strerror(opterr)); + printUsage(); + exit(EXIT_FAILURE); + } + } + return optind; //the index of the first non-option +} + +void printOptions(OPTIONS *options) +{ + printf("\n\n"); + printf("l : %c\n", options->type); + printf("P : %f\n", options->probability); + printf("p : %d\n", options->perlocationType); + printf("r : %d\n", options->runs); + printf("t : %d\n", options->minThreadNum); + printf("T : %d\n", options->maxThreadNum); + printf("n : %d\n", options->minNodeNum); + printf("N : %d\n", options->maxNodeNum); + printf("m : %d\n", options->minSize); + printf("M : %d\n", options->maxSize); +} + +void initialiseOptionsStruct(OPTIONS *options) +{ + options->type = 's'; + options->probability = 0.6; + options->perlocationType = 2; //-1 indicates to search ALL subdirectories + options->runs = 1; + options->minThreadNum = 4; + options->maxThreadNum = 4; + options->minNodeNum = 1; + options->maxNodeNum = 1; + options->minSize = 16; + options->maxSize = 8192; +} + +OPTIONS *createOptionsStruct(void) +{ + OPTIONS *options = (OPTIONS *)calloc(1, sizeof(OPTIONS)); + if(options == NULL) { + perror("initialiseOptionsStruct"); + exit(EXIT_FAILURE); + } + initialiseOptionsStruct(options); + return options; +} diff --git a/pool/shard006/C/0120288_ewah_rlw.c b/pool/shard006/C/0120288_ewah_rlw.c new file mode 100644 index 0000000000000000000000000000000000000000..9a6727f14e14d731bc571b73df2d82802c9677fe --- /dev/null +++ b/pool/shard006/C/0120288_ewah_rlw.c @@ -0,0 +1,120 @@ +/** + * Copyright 2013, GitHub, Inc + * Copyright 2009-2013, Daniel Lemire, Cliff Moon, + * David McIntosh, Robert Becho, Google Inc. and Veronika Zenz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +#include +#include +#include +#include + +#include "ewok.h" +#include "ewok_rlw.h" + +static inline bool next_word(struct rlw_iterator *it) +{ + if (it->pointer >= it->size) + return false; + + it->rlw.word = &it->buffer[it->pointer]; + it->pointer += rlw_get_literal_words(it->rlw.word) + 1; + + it->rlw.literal_words = rlw_get_literal_words(it->rlw.word); + it->rlw.running_len = rlw_get_running_len(it->rlw.word); + it->rlw.running_bit = rlw_get_run_bit(it->rlw.word); + it->rlw.literal_word_offset = 0; + + return true; +} + +void rlwit_init(struct rlw_iterator *it, struct ewah_bitmap *bitmap) +{ + it->buffer = bitmap->buffer; + it->size = bitmap->buffer_size; + it->pointer = 0; + + next_word(it); + + it->literal_word_start = rlwit_literal_words(it) + it->rlw.literal_word_offset; +} + +void rlwit_discard_first_words(struct rlw_iterator *it, size_t x) +{ + while (x > 0) { + size_t discard; + + if (it->rlw.running_len > x) { + it->rlw.running_len -= x; + return; + } + + x -= it->rlw.running_len; + it->rlw.running_len = 0; + + discard = (x > it->rlw.literal_words) ? it->rlw.literal_words : x; + + it->literal_word_start += discard; + it->rlw.literal_words -= discard; + x -= discard; + + if (x > 0 || rlwit_word_size(it) == 0) { + if (!next_word(it)) + break; + + it->literal_word_start = + rlwit_literal_words(it) + it->rlw.literal_word_offset; + } + } +} + +size_t rlwit_discharge( + struct rlw_iterator *it, struct ewah_bitmap *out, size_t max, bool negate) +{ + size_t index = 0; + + while (index < max && rlwit_word_size(it) > 0) { + size_t pd, pl = it->rlw.running_len; + + if (index + pl > max) { + pl = max - index; + } + + ewah_add_empty_words(out, it->rlw.running_bit ^ negate, pl); + index += pl; + + pd = it->rlw.literal_words; + if (pd + index > max) { + pd = max - index; + } + + ewah_add_dirty_words(out, + it->buffer + it->literal_word_start, pd, negate); + + rlwit_discard_first_words(it, pd + pl); + index += pd; + } + + return index; +} + +void rlwit_discharge_empty(struct rlw_iterator *it, struct ewah_bitmap *out) +{ + while (rlwit_word_size(it) > 0) { + ewah_add_empty_words(out, false, rlwit_word_size(it)); + rlwit_discard_first_words(it, rlwit_word_size(it)); + } +} diff --git a/pool/shard006/C/0120290_logging.c b/pool/shard006/C/0120290_logging.c new file mode 100644 index 0000000000000000000000000000000000000000..5bd777380871938bed87be596cc8cd3340102084 --- /dev/null +++ b/pool/shard006/C/0120290_logging.c @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2012, Daniel Willmann + * 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 Institute 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 INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is part of the Contiki operating system. + * + * @(#)$Id:$ + */ + +/** + * \addtogroup logging + * @{ + */ + +/** + * \file + * Implementation of the logging subsystem + * \author + * Daniel Willmann + * + */ + + +#include "logging.h" +#include "list.h" +#include "contiki-conf.h" +#include +#include + +#ifndef LOGL_DEFAULT +#define LOGL_DEFAULT LOGL_WRN +#endif + +struct log_cfg log_d[LOGD_NUM]; + +static char *logdomains[LOGD_NUM] = { + [LOGD_CORE] = "COR", /* Contiki core */ + [LOGD_CPU] = "CPU", /* CPU */ + [LOGD_INGA] = "PLA", /* Platform */ + [LOGD_DTN] = "DTN", /* uDTN */ + [LOGD_APP] = "APP", /* Application */ +}; + +static char *loglevels[LOGL_NUM] = { + [LOGL_DBG] = "DBG", + [LOGL_INF] = "INF", + [LOGL_WRN] = "WRN", + [LOGL_ERR] = "ERR", + [LOGL_CRI] = "CRI", +}; + +struct log_cfg log_d[LOGD_NUM]; +static uint8_t inited = 0; + +/*---------------------------------------------------------------------------*/ +/** + * \brief Convert the log domain symbol to a string + * \param logdom the log domain + * \return String of the log domain + * \author Daniel Willmann + * + * The function returns a three letter acronym + * used in the log messages to identify the + * different log domains. + * + */ +const char *logging_dom2str(uint8_t logdom) +{ + if (logdom >= LOGD_NUM) + return "UNK"; + return logdomains[logdom]; +} + +/*---------------------------------------------------------------------------*/ +/** + * \brief Convert the log level symbol to a string + * \param logl the log level + * \return String of the log level + * \author Daniel Willmann + * + * The function returns a three letter acronym + * used in the log messages to identify the + * different log levels. + * + */ +const char *logging_level2str(uint8_t logl) +{ + if (logl >= LOGL_NUM) + return "UNK"; + return loglevels[logl]; +} + +/*---------------------------------------------------------------------------*/ +/** + * \brief Initialize the logging subsystem + * \author Daniel Willmann + * + * This function initializes the logging subsystem and + * should be called before any other function from the + * module. + * + */ +void logging_init(void) +{ + int i, j; + if (inited) + return; + + for(i=0; i= LOGD_NUM)||(logl >= LOGL_NUM)||(sdom >= SUBDOMS)) + return; + + log_d[logdom].subl[sdom] = logl; +} + +/*---------------------------------------------------------------------------*/ +/** + * \brief Log a message + * \param logdom the logdomain of the message + * \param sdom the subdomain + * \param logl the loglevel of the mesage + * \param fmt the format string of the message + * \param ... any parameters that are needed for the format string + * \author Daniel Willmann + * + * This is the actual logging function that decides whether + * the message should be printed or not. Do not use this + * function, instead use the LOGGING_LOG macro as this + * includes source file and line number inside the message. + * + */ +void logging_logfn(uint8_t logdom, uint8_t sdom, uint8_t logl, const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + + if (logdom >= LOGD_NUM) { + printf("Unknown log domain %d (", logdom); + vprintf(fmt, ap); + printf(")\r\n"); + va_end(ap); + return; + } + + if (logl >= LOGL_NUM) + logl = LOGL_ERR; + if (sdom >= SUBDOMS) + sdom = 0; + if (logl >= log_d[logdom].subl[sdom]) { + vprintf(fmt, ap); + printf("\r\n"); + } + + va_end(ap); +} + +/*---------------------------------------------------------------------------*/ + +void logging_hexdump(uint8_t *data, unsigned int len) +{ + unsigned int i; + + for (i=0; i < len; i++) { + if (i % 16 == 0) + printf("\n%02X: ", i); + + printf(" %02X", data[i]); + } + printf("\n"); +} + +/** @} */ diff --git a/pool/shard006/C/0120294_lz4-packer.c b/pool/shard006/C/0120294_lz4-packer.c new file mode 100644 index 0000000000000000000000000000000000000000..c9af14e2601819765f4a99e1734bf442d53d5cfb --- /dev/null +++ b/pool/shard006/C/0120294_lz4-packer.c @@ -0,0 +1,41 @@ +/* + * PS2-Packer + * Copyright (C) 2004-2005 Nicolas "Pixel" Noble + * + * 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 +#include +#include +#include "lz4.h" +#include "lz4hc.h" +#include "common.h" + +int pack_section(const u8 * source, u8 ** dest, u32 source_size) { + char *packed; + int packed_size; + + packed_size = LZ4_compressBound(source_size); + packed = malloc(packed_size); + packed_size = LZ4_compress_HC((const char *)source, packed, source_size, packed_size, LZ4HC_CLEVEL_MAX); + *dest = realloc(packed, packed_size); + + return packed_size; +} + +u32 signature() { + return 0x314fffff; +} diff --git a/pool/shard006/C/0120295_executor.c b/pool/shard006/C/0120295_executor.c new file mode 100644 index 0000000000000000000000000000000000000000..acd1de436f59a65487fb2818e4ecc8374a627325 --- /dev/null +++ b/pool/shard006/C/0120295_executor.c @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include +#include +#include + +/* + * These symbols point to the .kunit_test_suites section and are defined in + * include/asm-generic/vmlinux.lds.h, and consequently must be extern. + */ +extern struct kunit_suite * const * const __kunit_suites_start[]; +extern struct kunit_suite * const * const __kunit_suites_end[]; + +#if IS_BUILTIN(CONFIG_KUNIT) + +static char *filter_glob_param; +module_param_named(filter_glob, filter_glob_param, charp, 0); +MODULE_PARM_DESC(filter_glob, + "Filter which KUnit test suites run at boot-time, e.g. list*"); + +static char *kunit_shutdown; +core_param(kunit_shutdown, kunit_shutdown, charp, 0644); + +static struct kunit_suite * const * +kunit_filter_subsuite(struct kunit_suite * const * const subsuite, + const char *filter_glob) +{ + int i, n = 0; + struct kunit_suite **filtered; + + n = 0; + for (i = 0; subsuite[i] != NULL; ++i) { + if (glob_match(filter_glob, subsuite[i]->name)) + ++n; + } + + if (n == 0) + return NULL; + + filtered = kmalloc_array(n + 1, sizeof(*filtered), GFP_KERNEL); + if (!filtered) + return NULL; + + n = 0; + for (i = 0; subsuite[i] != NULL; ++i) { + if (glob_match(filter_glob, subsuite[i]->name)) + filtered[n++] = subsuite[i]; + } + filtered[n] = NULL; + + return filtered; +} + +struct suite_set { + struct kunit_suite * const * const *start; + struct kunit_suite * const * const *end; +}; + +static struct suite_set kunit_filter_suites(const struct suite_set *suite_set, + const char *filter_glob) +{ + int i; + struct kunit_suite * const **copy, * const *filtered_subsuite; + struct suite_set filtered; + + const size_t max = suite_set->end - suite_set->start; + + copy = kmalloc_array(max, sizeof(*filtered.start), GFP_KERNEL); + filtered.start = copy; + if (!copy) { /* won't be able to run anything, return an empty set */ + filtered.end = copy; + return filtered; + } + + for (i = 0; i < max; ++i) { + filtered_subsuite = kunit_filter_subsuite(suite_set->start[i], filter_glob); + if (filtered_subsuite) + *copy++ = filtered_subsuite; + } + filtered.end = copy; + return filtered; +} + +static void kunit_handle_shutdown(void) +{ + if (!kunit_shutdown) + return; + + if (!strcmp(kunit_shutdown, "poweroff")) + kernel_power_off(); + else if (!strcmp(kunit_shutdown, "halt")) + kernel_halt(); + else if (!strcmp(kunit_shutdown, "reboot")) + kernel_restart(NULL); + +} + +static void kunit_print_tap_header(struct suite_set *suite_set) +{ + struct kunit_suite * const * const *suites, * const *subsuite; + int num_of_suites = 0; + + for (suites = suite_set->start; suites < suite_set->end; suites++) + for (subsuite = *suites; *subsuite != NULL; subsuite++) + num_of_suites++; + + pr_info("TAP version 14\n"); + pr_info("1..%d\n", num_of_suites); +} + +int kunit_run_all_tests(void) +{ + struct kunit_suite * const * const *suites; + struct suite_set suite_set = { + .start = __kunit_suites_start, + .end = __kunit_suites_end, + }; + + if (filter_glob_param) + suite_set = kunit_filter_suites(&suite_set, filter_glob_param); + + kunit_print_tap_header(&suite_set); + + for (suites = suite_set.start; suites < suite_set.end; suites++) + __kunit_test_suites_init(*suites); + + if (filter_glob_param) { /* a copy was made of each array */ + for (suites = suite_set.start; suites < suite_set.end; suites++) + kfree(*suites); + kfree(suite_set.start); + } + + kunit_handle_shutdown(); + + return 0; +} + +#if IS_BUILTIN(CONFIG_KUNIT_TEST) +#include "executor_test.c" +#endif + +#endif /* IS_BUILTIN(CONFIG_KUNIT) */