code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
# Comment/uncomment the following line to disable/enable debugging MAKE = make RM = rm MV = mv ECHO = echo CP = cp #DEBUG = y # Add your debugging flag (or not) to CFLAGS ifeq ($(DEBUG),y) DEBFLAGS = -O -g else DEBFLAGS = -O2 endif #Use external 1.4V VCO EXTRA_CFLAGS += -DVCO_14_SUPPLY #EXTRA_CFLAGS += -DREG_0XF6_NOT_CLEAR_BUG_FIX EXTRA_CFLAGS += -DDISABLE_PWRSAVE_AND_SCAN_DURING_IP EXTRA_CFLAGS += -DAGING_ALG #Default to NMI=EVAL if NMI isn't defined ifeq ($(strip $(NMI)),) NMI=EVAL endif ifeq ($(NMI),EVAL) EXTRA_CFLAGS += -DNMC_ASIC_A0 else ifeq ($(NMI),FPGA) endif EXTRA_CFLAGS += -DCONNECT_DIRECT -DNMI_PARSE_SCAN_IN_HOST ifeq ($(BUS),SDIO) EXTRA_CFLAGS += -DNMI_SDIO endif ifeq ($(SDIO_IRQ),GPIO) EXTRA_CFLAGS += -DNMI_SDIO_IRQ_GPIO endif ifeq ($(DMA_VER),VER_1) EXTRA_CFLAGS += -DUSE_DMA_VER_1 endif ifeq ($(TARGET),SIMULATION) KERNELDIR ?= /lib/modules/$(shell uname -r)/build TARGET=SIMULATION EXTRA_CFLAGS += -DSIMULATION -g OUT_ARCH = x86 else ifeq ($(TARGET),PANDA) KERNELDIR ?= $(DEV_TREE)/kernel/omap EXTRA_CFLAGS += -DPANDA_BOARD -DUSE_WIRELESS ifeq ($(ANDR_VER),4.3) MAKE_FLAGS := CROSS_COMPILE=$(DEV_TREE)/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7/bin/arm-eabi- ARCH=arm else ifeq ($(ANDR_VER),4.2) MAKE_FLAGS := CROSS_COMPILE=$(DEV_TREE)/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi- ARCH=arm else MAKE_FLAGS := CROSS_COMPILE=$(DEV_TREE)/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi- ARCH=arm endif OUT_ARCH = ARM-3.0 #EXTRA_CFLAGS += -DSIMULATION else ifeq ($(TARGET),BEAGLE) KERNELDIR ?= $(DEV_TREE) OUT_ARCH = ARM-2.6.39 MAKE_FLAGS := CROSS_COMPILE=arm-arago-linux-gnueabi- ARCH=arm EXTRA_CFLAGS += -DBEAGLE_BOARD KERNELDIR ?= $(DEV_TREE) else ifeq ($(TARGET),NM73131) KERNELDIR ?= $(DEV_TREE_LPC) OUT_ARCH = ARM-2.6.28.2 MAKE_FLAGS := CROSS_COMPILE=arm-linux- ARCH=arm EXTRA_CFLAGS += -DNM73131_0_BOARD else ifeq ($(TARGET),ALLWINNER) KERNELDIR ?= $(DEV_TREE)/linux-3.0 MAKE_FLAGS := CROSS_COMPILE=$(DEV_TREE)/buildroot/output/external-toolchain/bin/arm-none-linux-gnueabi- ARCH=arm EXTRA_CFLAGS += -DALLWINNER_BOARD -DUSE_WIRELESS OUT_ARCH = ARM-3.0 else ifeq ($(TARGET),ALLWINNER_A20) KERNELDIR ?= $(DEV_TREE)/linux-3.3 MAKE_FLAGS := CROSS_COMPILE=$(DEV_TREE)/out/android/common/buildroot/external-toolchain/bin/arm-linux-gnueabi- ARCH=arm EXTRA_CFLAGS += -DPLAT_ALLWINNER_A20 -DUSE_WIRELESS OUT_ARCH = ARM-3.3 else ifeq ($(TARGET),ALLWINNER_A23) KERNELDIR ?= $(DEV_TREE)/linux-3.4 MAKE_FLAGS := CROSS_COMPILE=$(DEV_TREE)/out/android/common/buildroot/external-toolchain/bin/arm-linux-gnueabi- ARCH=arm EXTRA_CFLAGS += -DPLAT_ALLWINNER_A23 -DUSE_WIRELESS OUT_ARCH = ARM-3.4 else KERNELDIR ?= /lib/modules/$(shell uname -r)/build OUT_ARCH = x86 TARGET=SIMULATION EXTRA_CFLAGS += -DSIMULATION endif ifeq ($(FIRMLOG),HOST) EXTRA_CFLAGS += -DSWITCH_LOG_TERMINAL endif EXTRA_CFLAGS += $(DEBFLAGS) -I $(PWD)/../../NMI_OsWrapper/include/ EXTRA_CFLAGS += -I $(PWD)/../../ -I $(PWD)/../include -I $(PWD)/../ -I $(PWD)/include EXTRA_CFLAGS += -DNMI_PLATFORM=NMI_LINUXKERNEL EXTRA_CFLAGS += -Wno-unused-function obj-m := nmi_wifi.o ifeq ($(TARGET),NM73131) ifeq ($(BUS),SDIO) nmi_wifi-objs := source/linux_wlan.o source/linux_wlan_sdio.o\ source/nmi_debugfs.o source/nmi_queue.o\ ../binary/linux/$(OUT_ARCH)/NMI_WiFi_Driver.a\ ../../NMI_OsWrapper/binary/linux/$(OUT_ARCH)/NMI_OsWrapper.a else nmi_wifi-objs := source/linux_wlan.o source/linux_wlan_spi.o\ source/nmi_debugfs.o source/nmi_queue.o\ ../binary/linux/$(OUT_ARCH)/NMI_WiFi_Driver.a\ ../../NMI_OsWrapper/binary/linux/$(OUT_ARCH)/NMI_OsWrapper.a endif else ifeq ($(BUS),SDIO) nmi_wifi-objs := source/NMI_WFI_NetDevice.o source/NMI_WFI_CfgOperations.o\ source/linux_wlan.o source/linux_wlan_sdio.o source/linux_mon.o\ source/nmi_debugfs.o source/nmi_queue.o\ ../binary/linux/$(OUT_ARCH)/NMI_WiFi_Driver.a\ ../../NMI_OsWrapper/binary/linux/$(OUT_ARCH)/NMI_OsWrapper.a else nmi_wifi-objs := source/NMI_WFI_NetDevice.o source/NMI_WFI_CfgOperations.o\ source/linux_wlan.o source/linux_wlan_spi.o source/linux_mon.o\ source/nmi_debugfs.o source/nmi_queue.o\ ../binary/linux/$(OUT_ARCH)/NMI_WiFi_Driver.a\ ../../NMI_OsWrapper/binary/linux/$(OUT_ARCH)/NMI_OsWrapper.a endif endif ifneq ($(KERNELRELEASE),) # call from kernel build system else #KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: echo KERNELDIR = $(KERNELDIR) $(MAKE) TARGET=$(TARGET) NMI=$(NMI) BUS=$(BUS) FULLY_HOSTING_AP=$(FULLY_HOSTING_AP) -C ../ @$(ECHO) "###########################################" @$(ECHO) "##### Building NMI WiFi for Linux ######" @$(ECHO) "##### TARGET =" $(TARGET) "######" $(MAKE) -C $(KERNELDIR) M=$(PWD) modules $(MAKE_FLAGS) mkdir -p binary/linux/$(OUT_ARCH) $(MV) -f $(PWD)/nmi_wifi.ko binary/linux/$(OUT_ARCH)/nmi_wifi.ko endif clean: $(MAKE) TARGET=$(TARGET) NMI=$(NMI) BUS=$(BUS) -C ../ clean @$(ECHO) "###########################################" @$(ECHO) "##### Cleaning NMI WiFi for Linux ######" @$(ECHO) "##### TARGET =" $(TARGET) "######" $(MAKE) -C $(KERNELDIR) SUBDIRS=$(PWD) clean rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions rm -rf binary/linux/$(OUT_ARCH)/nmi_wifi.ko depend .depend dep: $(CC) $(CFLAGS) -M *.c > .depend ifeq (.depend,$(wildcard .depend)) include .depend endif
FOSSEE/FOSSEE-netbook-kernel-source
drivers/net/wireless/nmi_android4.4_driver/src/driver/linux/Makefile
Makefile
gpl-2.0
5,303
<?php /** * PHPMailer SPL autoloader. * PHP Version 5 * @package PHPMailer * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project * @author Marcus Bointon (Synchro/coolbru) <[email protected]> * @author Jim Jagielski (jimjag) <[email protected]> * @author Andy Prevost (codeworxtech) <[email protected]> * @author Brent R. Matzelle (original founder) * @copyright 2012 - 2014 Marcus Bointon * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License * @note This program is distributed in the hope that it will be useful - WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. */ /** * PHPMailer SPL autoloader. * @param string $classname The name of the class to load */ function PHPMailerAutoload($classname) { //Can't use __DIR__ as it's only in PHP 5.3+ $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php'; if (is_readable($filename)) { require $filename; } } if (version_compare(PHP_VERSION, '5.1.2', '>=')) { //SPL autoloading was introduced in PHP 5.1.2 if (version_compare(PHP_VERSION, '5.3.0', '>=')) { spl_autoload_register('PHPMailerAutoload', true, true); } else { spl_autoload_register('PHPMailerAutoload'); } } /* This section customized for XOOPS for compatibility with PHP 5.3-8.0 */ //else { /** * Fall back to traditional autoload for old PHP versions * @param string $classname The name of the class to load */ // function __autoload($classname) // { // PHPMailerAutoload($classname); // } //}
mambax7/XoopsCore25
htdocs/class/mail/phpmailer/PHPMailerAutoload.php
PHP
gpl-2.0
1,776
/* Copyright (C) 2002-2017 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 2002. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <errno.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/mman.h> #include <sys/wait.h> static sigset_t ss; static pthread_barrier_t *b; static void * tf (void *arg) { sigdelset (&ss, SIGINT); if (pthread_sigmask (SIG_SETMASK, &ss, NULL) != 0) { puts ("2nd pthread_sigmask failed"); exit (1); } pthread_barrier_wait (b); int sig; int res = sigwait (&ss, &sig); if (res == 0) { printf ("sigwait returned successfully with signal %d\n", sig); exit (1); } printf ("sigwait returned with %s (%d)\n", strerror (res), res); return NULL; } static void receiver (void) { pthread_t th; /* Make sure the process doesn't run forever. */ alarm (10); sigfillset (&ss); if (pthread_sigmask (SIG_SETMASK, &ss, NULL) != 0) { puts ("1st pthread_sigmask failed"); exit (1); } if (pthread_create (&th, NULL, tf, NULL) != 0) { puts ("pthread_create failed"); exit (1); } if (pthread_join (th, NULL) == 0) { puts ("thread joined?!"); exit (1); } _exit (0); } static int do_test (void) { char tmp[] = "/tmp/tst-signal1-XXXXXX"; int fd = mkstemp (tmp); if (fd == -1) { puts ("mkstemp failed"); exit (1); } unlink (tmp); int i; for (i = 0; i < 20; ++i) write (fd, "foobar xyzzy", 12); b = mmap (NULL, sizeof (pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (b == MAP_FAILED) { puts ("mmap failed"); exit (1); } pthread_barrierattr_t ba; if (pthread_barrierattr_init (&ba) != 0) { puts ("barrierattr_init failed"); exit (1); } if (pthread_barrierattr_setpshared (&ba, PTHREAD_PROCESS_SHARED) != 0) { puts ("barrierattr_setpshared failed"); exit (1); } if (pthread_barrier_init (b, &ba, 2) != 0) { puts ("barrier_init failed"); exit (1); } if (pthread_barrierattr_destroy (&ba) != 0) { puts ("barrierattr_destroy failed"); exit (1); } pid_t pid = fork (); if (pid == -1) { puts ("fork failed"); exit (1); } if (pid == 0) receiver (); pthread_barrier_wait (b); /* Wait a bit more. */ struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 }; nanosleep (&ts, NULL); /* Send the signal. */ puts ("sending the signal now"); kill (pid, SIGINT); /* Wait for the process to terminate. */ int status; if (TEMP_FAILURE_RETRY (waitpid (pid, &status, 0)) != pid) { puts ("wrong child reported terminated"); exit (1); } if (!WIFSIGNALED (status)) { puts ("child wasn't signalled"); exit (1); } if (WTERMSIG (status) != SIGINT) { puts ("child not terminated with SIGINT"); exit (1); } return 0; } #define TEST_FUNCTION do_test () #include "../test-skeleton.c"
norov/glibc
nptl/tst-signal1.c
C
gpl-2.0
3,830
/* * tclIntDecls.h -- * * This file contains the declarations for all unsupported * functions that are exported by the Tcl library. These * interfaces are not guaranteed to remain the same between * versions. Use at your own risk. * * Copyright (c) 1998-1999 by Scriptics Corporation. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tclIntDecls.h,v 1.49.2.9 2007/04/21 19:52:14 kennykb Exp $ */ #ifndef _TCLINTDECLS #define _TCLINTDECLS /* * WARNING: This file is automatically generated by the tools/genStubs.tcl * script. Any modifications to the function declarations below should be made * in the generic/tclInt.decls script. */ /* !BEGIN!: Do not edit below this line. */ /* * Exported function declarations: */ /* Slot 0 is reserved */ /* 1 */ EXTERN int TclAccessDeleteProc _ANSI_ARGS_(( TclAccessProc_ * proc)); /* 2 */ EXTERN int TclAccessInsertProc _ANSI_ARGS_(( TclAccessProc_ * proc)); /* 3 */ EXTERN void TclAllocateFreeObjects _ANSI_ARGS_((void)); /* Slot 4 is reserved */ #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ /* 5 */ EXTERN int TclCleanupChildren _ANSI_ARGS_((Tcl_Interp * interp, int numPids, Tcl_Pid * pidPtr, Tcl_Channel errorChan)); #endif /* UNIX */ #ifdef __WIN32__ /* 5 */ EXTERN int TclCleanupChildren _ANSI_ARGS_((Tcl_Interp * interp, int numPids, Tcl_Pid * pidPtr, Tcl_Channel errorChan)); #endif /* __WIN32__ */ /* 6 */ EXTERN void TclCleanupCommand _ANSI_ARGS_((Command * cmdPtr)); /* 7 */ EXTERN int TclCopyAndCollapse _ANSI_ARGS_((int count, CONST char * src, char * dst)); /* 8 */ EXTERN int TclCopyChannel _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Channel inChan, Tcl_Channel outChan, int toRead, Tcl_Obj * cmdPtr)); #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ /* 9 */ EXTERN int TclCreatePipeline _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST char ** argv, Tcl_Pid ** pidArrayPtr, TclFile * inPipePtr, TclFile * outPipePtr, TclFile * errFilePtr)); #endif /* UNIX */ #ifdef __WIN32__ /* 9 */ EXTERN int TclCreatePipeline _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST char ** argv, Tcl_Pid ** pidArrayPtr, TclFile * inPipePtr, TclFile * outPipePtr, TclFile * errFilePtr)); #endif /* __WIN32__ */ /* 10 */ EXTERN int TclCreateProc _ANSI_ARGS_((Tcl_Interp * interp, Namespace * nsPtr, CONST char * procName, Tcl_Obj * argsPtr, Tcl_Obj * bodyPtr, Proc ** procPtrPtr)); /* 11 */ EXTERN void TclDeleteCompiledLocalVars _ANSI_ARGS_(( Interp * iPtr, CallFrame * framePtr)); /* 12 */ EXTERN void TclDeleteVars _ANSI_ARGS_((Interp * iPtr, Tcl_HashTable * tablePtr)); /* 13 */ EXTERN int TclDoGlob _ANSI_ARGS_((Tcl_Interp * interp, char * separators, Tcl_DString * headPtr, char * tail, Tcl_GlobTypeData * types)); /* 14 */ EXTERN void TclDumpMemoryInfo _ANSI_ARGS_((FILE * outFile)); /* Slot 15 is reserved */ /* 16 */ EXTERN void TclExprFloatError _ANSI_ARGS_((Tcl_Interp * interp, double value)); /* Slot 17 is reserved */ /* Slot 18 is reserved */ /* Slot 19 is reserved */ /* Slot 20 is reserved */ /* Slot 21 is reserved */ /* 22 */ EXTERN int TclFindElement _ANSI_ARGS_((Tcl_Interp * interp, CONST char * listStr, int listLength, CONST char ** elementPtr, CONST char ** nextPtr, int * sizePtr, int * bracePtr)); /* 23 */ EXTERN Proc * TclFindProc _ANSI_ARGS_((Interp * iPtr, CONST char * procName)); /* 24 */ EXTERN int TclFormatInt _ANSI_ARGS_((char * buffer, long n)); /* 25 */ EXTERN void TclFreePackageInfo _ANSI_ARGS_((Interp * iPtr)); /* Slot 26 is reserved */ /* 27 */ EXTERN int TclGetDate _ANSI_ARGS_((char * p, Tcl_WideInt now, long zone, Tcl_WideInt * timePtr)); /* 28 */ EXTERN Tcl_Channel TclpGetDefaultStdChannel _ANSI_ARGS_((int type)); /* Slot 29 is reserved */ /* Slot 30 is reserved */ /* 31 */ EXTERN char * TclGetExtension _ANSI_ARGS_((char * name)); /* 32 */ EXTERN int TclGetFrame _ANSI_ARGS_((Tcl_Interp * interp, CONST char * str, CallFrame ** framePtrPtr)); /* 33 */ EXTERN TclCmdProcType TclGetInterpProc _ANSI_ARGS_((void)); /* 34 */ EXTERN int TclGetIntForIndex _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * objPtr, int endValue, int * indexPtr)); /* Slot 35 is reserved */ /* 36 */ EXTERN int TclGetLong _ANSI_ARGS_((Tcl_Interp * interp, CONST char * str, long * longPtr)); /* 37 */ EXTERN int TclGetLoadedPackages _ANSI_ARGS_(( Tcl_Interp * interp, char * targetName)); /* 38 */ EXTERN int TclGetNamespaceForQualName _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * qualName, Namespace * cxtNsPtr, int flags, Namespace ** nsPtrPtr, Namespace ** altNsPtrPtr, Namespace ** actualCxtPtrPtr, CONST char ** simpleNamePtr)); /* 39 */ EXTERN TclObjCmdProcType TclGetObjInterpProc _ANSI_ARGS_((void)); /* 40 */ EXTERN int TclGetOpenMode _ANSI_ARGS_((Tcl_Interp * interp, CONST char * str, int * seekFlagPtr)); /* 41 */ EXTERN Tcl_Command TclGetOriginalCommand _ANSI_ARGS_(( Tcl_Command command)); /* 42 */ EXTERN char * TclpGetUserHome _ANSI_ARGS_((CONST char * name, Tcl_DString * bufferPtr)); /* 43 */ EXTERN int TclGlobalInvoke _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST84 char ** argv, int flags)); /* 44 */ EXTERN int TclGuessPackageName _ANSI_ARGS_(( CONST char * fileName, Tcl_DString * bufPtr)); /* 45 */ EXTERN int TclHideUnsafeCommands _ANSI_ARGS_(( Tcl_Interp * interp)); /* 46 */ EXTERN int TclInExit _ANSI_ARGS_((void)); /* Slot 47 is reserved */ /* Slot 48 is reserved */ /* 49 */ EXTERN Tcl_Obj * TclIncrVar2 _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * part1Ptr, Tcl_Obj * part2Ptr, long incrAmount, int part1NotParsed)); /* 50 */ EXTERN void TclInitCompiledLocals _ANSI_ARGS_(( Tcl_Interp * interp, CallFrame * framePtr, Namespace * nsPtr)); /* 51 */ EXTERN int TclInterpInit _ANSI_ARGS_((Tcl_Interp * interp)); /* 52 */ EXTERN int TclInvoke _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST84 char ** argv, int flags)); /* 53 */ EXTERN int TclInvokeObjectCommand _ANSI_ARGS_(( ClientData clientData, Tcl_Interp * interp, int argc, CONST84 char ** argv)); /* 54 */ EXTERN int TclInvokeStringCommand _ANSI_ARGS_(( ClientData clientData, Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[])); /* 55 */ EXTERN Proc * TclIsProc _ANSI_ARGS_((Command * cmdPtr)); /* Slot 56 is reserved */ /* Slot 57 is reserved */ /* 58 */ EXTERN Var * TclLookupVar _ANSI_ARGS_((Tcl_Interp * interp, CONST char * part1, CONST char * part2, int flags, CONST char * msg, int createPart1, int createPart2, Var ** arrayPtrPtr)); /* Slot 59 is reserved */ /* 60 */ EXTERN int TclNeedSpace _ANSI_ARGS_((CONST char * start, CONST char * end)); /* 61 */ EXTERN Tcl_Obj * TclNewProcBodyObj _ANSI_ARGS_((Proc * procPtr)); /* 62 */ EXTERN int TclObjCommandComplete _ANSI_ARGS_((Tcl_Obj * cmdPtr)); /* 63 */ EXTERN int TclObjInterpProc _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[])); /* 64 */ EXTERN int TclObjInvoke _ANSI_ARGS_((Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[], int flags)); /* 65 */ EXTERN int TclObjInvokeGlobal _ANSI_ARGS_((Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[], int flags)); /* 66 */ EXTERN int TclOpenFileChannelDeleteProc _ANSI_ARGS_(( TclOpenFileChannelProc_ * proc)); /* 67 */ EXTERN int TclOpenFileChannelInsertProc _ANSI_ARGS_(( TclOpenFileChannelProc_ * proc)); /* Slot 68 is reserved */ /* 69 */ EXTERN char * TclpAlloc _ANSI_ARGS_((unsigned int size)); /* Slot 70 is reserved */ /* Slot 71 is reserved */ /* Slot 72 is reserved */ /* Slot 73 is reserved */ /* 74 */ EXTERN void TclpFree _ANSI_ARGS_((char * ptr)); /* 75 */ EXTERN unsigned long TclpGetClicks _ANSI_ARGS_((void)); /* 76 */ EXTERN unsigned long TclpGetSeconds _ANSI_ARGS_((void)); /* 77 */ EXTERN void TclpGetTime _ANSI_ARGS_((Tcl_Time * time)); /* 78 */ EXTERN int TclpGetTimeZone _ANSI_ARGS_((Tcl_WideInt time)); /* Slot 79 is reserved */ /* Slot 80 is reserved */ /* 81 */ EXTERN char * TclpRealloc _ANSI_ARGS_((char * ptr, unsigned int size)); /* Slot 82 is reserved */ /* Slot 83 is reserved */ /* Slot 84 is reserved */ /* Slot 85 is reserved */ /* Slot 86 is reserved */ /* Slot 87 is reserved */ /* 88 */ EXTERN char * TclPrecTraceProc _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, CONST char * name1, CONST char * name2, int flags)); /* 89 */ EXTERN int TclPreventAliasLoop _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Interp * cmdInterp, Tcl_Command cmd)); /* Slot 90 is reserved */ /* 91 */ EXTERN void TclProcCleanupProc _ANSI_ARGS_((Proc * procPtr)); /* 92 */ EXTERN int TclProcCompileProc _ANSI_ARGS_((Tcl_Interp * interp, Proc * procPtr, Tcl_Obj * bodyPtr, Namespace * nsPtr, CONST char * description, CONST char * procName)); /* 93 */ EXTERN void TclProcDeleteProc _ANSI_ARGS_((ClientData clientData)); /* 94 */ EXTERN int TclProcInterpProc _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, int argc, CONST84 char ** argv)); /* Slot 95 is reserved */ /* 96 */ EXTERN int TclRenameCommand _ANSI_ARGS_((Tcl_Interp * interp, char * oldName, char * newName)); /* 97 */ EXTERN void TclResetShadowedCmdRefs _ANSI_ARGS_(( Tcl_Interp * interp, Command * newCmdPtr)); /* 98 */ EXTERN int TclServiceIdle _ANSI_ARGS_((void)); /* Slot 99 is reserved */ /* Slot 100 is reserved */ /* 101 */ EXTERN char * TclSetPreInitScript _ANSI_ARGS_((char * string)); /* 102 */ EXTERN void TclSetupEnv _ANSI_ARGS_((Tcl_Interp * interp)); /* 103 */ EXTERN int TclSockGetPort _ANSI_ARGS_((Tcl_Interp * interp, char * str, char * proto, int * portPtr)); #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ /* 104 */ EXTERN int TclSockMinimumBuffers _ANSI_ARGS_((int sock, int size)); #endif /* UNIX */ #ifdef __WIN32__ /* 104 */ EXTERN int TclSockMinimumBuffers _ANSI_ARGS_((int sock, int size)); #endif /* __WIN32__ */ /* Slot 105 is reserved */ /* 106 */ EXTERN int TclStatDeleteProc _ANSI_ARGS_((TclStatProc_ * proc)); /* 107 */ EXTERN int TclStatInsertProc _ANSI_ARGS_((TclStatProc_ * proc)); /* 108 */ EXTERN void TclTeardownNamespace _ANSI_ARGS_((Namespace * nsPtr)); /* 109 */ EXTERN int TclUpdateReturnInfo _ANSI_ARGS_((Interp * iPtr)); /* Slot 110 is reserved */ /* 111 */ EXTERN void Tcl_AddInterpResolvers _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * name, Tcl_ResolveCmdProc * cmdProc, Tcl_ResolveVarProc * varProc, Tcl_ResolveCompiledVarProc * compiledVarProc)); /* 112 */ EXTERN int Tcl_AppendExportList _ANSI_ARGS_(( Tcl_Interp * interp, Tcl_Namespace * nsPtr, Tcl_Obj * objPtr)); /* 113 */ EXTERN Tcl_Namespace * Tcl_CreateNamespace _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, ClientData clientData, Tcl_NamespaceDeleteProc * deleteProc)); /* 114 */ EXTERN void Tcl_DeleteNamespace _ANSI_ARGS_(( Tcl_Namespace * nsPtr)); /* 115 */ EXTERN int Tcl_Export _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, CONST char * pattern, int resetListFirst)); /* 116 */ EXTERN Tcl_Command Tcl_FindCommand _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_Namespace * contextNsPtr, int flags)); /* 117 */ EXTERN Tcl_Namespace * Tcl_FindNamespace _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_Namespace * contextNsPtr, int flags)); /* 118 */ EXTERN int Tcl_GetInterpResolvers _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * name, Tcl_ResolverInfo * resInfo)); /* 119 */ EXTERN int Tcl_GetNamespaceResolvers _ANSI_ARGS_(( Tcl_Namespace * namespacePtr, Tcl_ResolverInfo * resInfo)); /* 120 */ EXTERN Tcl_Var Tcl_FindNamespaceVar _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * name, Tcl_Namespace * contextNsPtr, int flags)); /* 121 */ EXTERN int Tcl_ForgetImport _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, CONST char * pattern)); /* 122 */ EXTERN Tcl_Command Tcl_GetCommandFromObj _ANSI_ARGS_(( Tcl_Interp * interp, Tcl_Obj * objPtr)); /* 123 */ EXTERN void Tcl_GetCommandFullName _ANSI_ARGS_(( Tcl_Interp * interp, Tcl_Command command, Tcl_Obj * objPtr)); /* 124 */ EXTERN Tcl_Namespace * Tcl_GetCurrentNamespace _ANSI_ARGS_(( Tcl_Interp * interp)); /* 125 */ EXTERN Tcl_Namespace * Tcl_GetGlobalNamespace _ANSI_ARGS_(( Tcl_Interp * interp)); /* 126 */ EXTERN void Tcl_GetVariableFullName _ANSI_ARGS_(( Tcl_Interp * interp, Tcl_Var variable, Tcl_Obj * objPtr)); /* 127 */ EXTERN int Tcl_Import _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, CONST char * pattern, int allowOverwrite)); /* 128 */ EXTERN void Tcl_PopCallFrame _ANSI_ARGS_((Tcl_Interp* interp)); /* 129 */ EXTERN int Tcl_PushCallFrame _ANSI_ARGS_((Tcl_Interp* interp, Tcl_CallFrame * framePtr, Tcl_Namespace * nsPtr, int isProcCallFrame)); /* 130 */ EXTERN int Tcl_RemoveInterpResolvers _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * name)); /* 131 */ EXTERN void Tcl_SetNamespaceResolvers _ANSI_ARGS_(( Tcl_Namespace * namespacePtr, Tcl_ResolveCmdProc * cmdProc, Tcl_ResolveVarProc * varProc, Tcl_ResolveCompiledVarProc * compiledVarProc)); /* 132 */ EXTERN int TclpHasSockets _ANSI_ARGS_((Tcl_Interp * interp)); /* 133 */ EXTERN struct tm * TclpGetDate _ANSI_ARGS_((TclpTime_t time, int useGMT)); /* 134 */ EXTERN size_t TclpStrftime _ANSI_ARGS_((char * s, size_t maxsize, CONST char * format, CONST struct tm * t, int useGMT)); /* 135 */ EXTERN int TclpCheckStackSpace _ANSI_ARGS_((void)); /* Slot 136 is reserved */ /* Slot 137 is reserved */ /* 138 */ EXTERN CONST84_RETURN char * TclGetEnv _ANSI_ARGS_((CONST char * name, Tcl_DString * valuePtr)); /* Slot 139 is reserved */ /* 140 */ EXTERN int TclLooksLikeInt _ANSI_ARGS_((CONST char * bytes, int length)); /* 141 */ EXTERN CONST84_RETURN char * TclpGetCwd _ANSI_ARGS_((Tcl_Interp * interp, Tcl_DString * cwdPtr)); /* 142 */ EXTERN int TclSetByteCodeFromAny _ANSI_ARGS_(( Tcl_Interp * interp, Tcl_Obj * objPtr, CompileHookProc * hookProc, ClientData clientData)); /* 143 */ EXTERN int TclAddLiteralObj _ANSI_ARGS_(( struct CompileEnv * envPtr, Tcl_Obj * objPtr, LiteralEntry ** litPtrPtr)); /* 144 */ EXTERN void TclHideLiteral _ANSI_ARGS_((Tcl_Interp * interp, struct CompileEnv * envPtr, int index)); /* 145 */ EXTERN struct AuxDataType * TclGetAuxDataType _ANSI_ARGS_((char * typeName)); /* 146 */ EXTERN TclHandle TclHandleCreate _ANSI_ARGS_((VOID * ptr)); /* 147 */ EXTERN void TclHandleFree _ANSI_ARGS_((TclHandle handle)); /* 148 */ EXTERN TclHandle TclHandlePreserve _ANSI_ARGS_((TclHandle handle)); /* 149 */ EXTERN void TclHandleRelease _ANSI_ARGS_((TclHandle handle)); /* 150 */ EXTERN int TclRegAbout _ANSI_ARGS_((Tcl_Interp * interp, Tcl_RegExp re)); /* 151 */ EXTERN void TclRegExpRangeUniChar _ANSI_ARGS_((Tcl_RegExp re, int index, int * startPtr, int * endPtr)); /* 152 */ EXTERN void TclSetLibraryPath _ANSI_ARGS_((Tcl_Obj * pathPtr)); /* 153 */ EXTERN Tcl_Obj * TclGetLibraryPath _ANSI_ARGS_((void)); /* Slot 154 is reserved */ /* Slot 155 is reserved */ /* 156 */ EXTERN void TclRegError _ANSI_ARGS_((Tcl_Interp * interp, CONST char * msg, int status)); /* 157 */ EXTERN Var * TclVarTraceExists _ANSI_ARGS_((Tcl_Interp * interp, CONST char * varName)); /* 158 */ EXTERN void TclSetStartupScriptFileName _ANSI_ARGS_(( CONST char * filename)); /* 159 */ EXTERN CONST84_RETURN char * TclGetStartupScriptFileName _ANSI_ARGS_((void)); /* Slot 160 is reserved */ /* 161 */ EXTERN int TclChannelTransform _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Channel chan, Tcl_Obj * cmdObjPtr)); /* 162 */ EXTERN void TclChannelEventScriptInvoker _ANSI_ARGS_(( ClientData clientData, int flags)); /* 163 */ EXTERN void * TclGetInstructionTable _ANSI_ARGS_((void)); /* 164 */ EXTERN void TclExpandCodeArray _ANSI_ARGS_((void * envPtr)); /* 165 */ EXTERN void TclpSetInitialEncodings _ANSI_ARGS_((void)); /* 166 */ EXTERN int TclListObjSetElement _ANSI_ARGS_(( Tcl_Interp * interp, Tcl_Obj * listPtr, int index, Tcl_Obj * valuePtr)); /* 167 */ EXTERN void TclSetStartupScriptPath _ANSI_ARGS_(( Tcl_Obj * pathPtr)); /* 168 */ EXTERN Tcl_Obj * TclGetStartupScriptPath _ANSI_ARGS_((void)); /* 169 */ EXTERN int TclpUtfNcmp2 _ANSI_ARGS_((CONST char * s1, CONST char * s2, unsigned long n)); /* 170 */ EXTERN int TclCheckInterpTraces _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * command, int numChars, Command * cmdPtr, int result, int traceFlags, int objc, Tcl_Obj *CONST objv[])); /* 171 */ EXTERN int TclCheckExecutionTraces _ANSI_ARGS_(( Tcl_Interp * interp, CONST char * command, int numChars, Command * cmdPtr, int result, int traceFlags, int objc, Tcl_Obj *CONST objv[])); /* 172 */ EXTERN int TclInThreadExit _ANSI_ARGS_((void)); /* 173 */ EXTERN int TclUniCharMatch _ANSI_ARGS_(( CONST Tcl_UniChar * string, int strLen, CONST Tcl_UniChar * pattern, int ptnLen, int nocase)); /* Slot 174 is reserved */ /* Slot 175 is reserved */ /* Slot 176 is reserved */ /* Slot 177 is reserved */ /* Slot 178 is reserved */ /* Slot 179 is reserved */ /* Slot 180 is reserved */ /* Slot 181 is reserved */ /* 182 */ EXTERN struct tm * TclpLocaltime _ANSI_ARGS_((TclpTime_t_CONST clock)); /* 183 */ EXTERN struct tm * TclpGmtime _ANSI_ARGS_((TclpTime_t_CONST clock)); /* Slot 184 is reserved */ /* Slot 185 is reserved */ /* Slot 186 is reserved */ /* Slot 187 is reserved */ /* Slot 188 is reserved */ /* Slot 189 is reserved */ /* Slot 190 is reserved */ /* Slot 191 is reserved */ /* Slot 192 is reserved */ /* Slot 193 is reserved */ /* Slot 194 is reserved */ /* Slot 195 is reserved */ /* Slot 196 is reserved */ /* Slot 197 is reserved */ /* Slot 198 is reserved */ /* 199 */ EXTERN int TclMatchIsTrivial _ANSI_ARGS_((CONST char * pattern)); typedef struct TclIntStubs { int magic; struct TclIntStubHooks *hooks; void *reserved0; int (*tclAccessDeleteProc) _ANSI_ARGS_((TclAccessProc_ * proc)); /* 1 */ int (*tclAccessInsertProc) _ANSI_ARGS_((TclAccessProc_ * proc)); /* 2 */ void (*tclAllocateFreeObjects) _ANSI_ARGS_((void)); /* 3 */ void *reserved4; #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ int (*tclCleanupChildren) _ANSI_ARGS_((Tcl_Interp * interp, int numPids, Tcl_Pid * pidPtr, Tcl_Channel errorChan)); /* 5 */ #endif /* UNIX */ #ifdef __WIN32__ int (*tclCleanupChildren) _ANSI_ARGS_((Tcl_Interp * interp, int numPids, Tcl_Pid * pidPtr, Tcl_Channel errorChan)); /* 5 */ #endif /* __WIN32__ */ #ifdef MAC_TCL void *reserved5; #endif /* MAC_TCL */ void (*tclCleanupCommand) _ANSI_ARGS_((Command * cmdPtr)); /* 6 */ int (*tclCopyAndCollapse) _ANSI_ARGS_((int count, CONST char * src, char * dst)); /* 7 */ int (*tclCopyChannel) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Channel inChan, Tcl_Channel outChan, int toRead, Tcl_Obj * cmdPtr)); /* 8 */ #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ int (*tclCreatePipeline) _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST char ** argv, Tcl_Pid ** pidArrayPtr, TclFile * inPipePtr, TclFile * outPipePtr, TclFile * errFilePtr)); /* 9 */ #endif /* UNIX */ #ifdef __WIN32__ int (*tclCreatePipeline) _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST char ** argv, Tcl_Pid ** pidArrayPtr, TclFile * inPipePtr, TclFile * outPipePtr, TclFile * errFilePtr)); /* 9 */ #endif /* __WIN32__ */ #ifdef MAC_TCL void *reserved9; #endif /* MAC_TCL */ int (*tclCreateProc) _ANSI_ARGS_((Tcl_Interp * interp, Namespace * nsPtr, CONST char * procName, Tcl_Obj * argsPtr, Tcl_Obj * bodyPtr, Proc ** procPtrPtr)); /* 10 */ void (*tclDeleteCompiledLocalVars) _ANSI_ARGS_((Interp * iPtr, CallFrame * framePtr)); /* 11 */ void (*tclDeleteVars) _ANSI_ARGS_((Interp * iPtr, Tcl_HashTable * tablePtr)); /* 12 */ int (*tclDoGlob) _ANSI_ARGS_((Tcl_Interp * interp, char * separators, Tcl_DString * headPtr, char * tail, Tcl_GlobTypeData * types)); /* 13 */ void (*tclDumpMemoryInfo) _ANSI_ARGS_((FILE * outFile)); /* 14 */ void *reserved15; void (*tclExprFloatError) _ANSI_ARGS_((Tcl_Interp * interp, double value)); /* 16 */ void *reserved17; void *reserved18; void *reserved19; void *reserved20; void *reserved21; int (*tclFindElement) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * listStr, int listLength, CONST char ** elementPtr, CONST char ** nextPtr, int * sizePtr, int * bracePtr)); /* 22 */ Proc * (*tclFindProc) _ANSI_ARGS_((Interp * iPtr, CONST char * procName)); /* 23 */ int (*tclFormatInt) _ANSI_ARGS_((char * buffer, long n)); /* 24 */ void (*tclFreePackageInfo) _ANSI_ARGS_((Interp * iPtr)); /* 25 */ void *reserved26; int (*tclGetDate) _ANSI_ARGS_((char * p, Tcl_WideInt now, long zone, Tcl_WideInt * timePtr)); /* 27 */ Tcl_Channel (*tclpGetDefaultStdChannel) _ANSI_ARGS_((int type)); /* 28 */ void *reserved29; void *reserved30; char * (*tclGetExtension) _ANSI_ARGS_((char * name)); /* 31 */ int (*tclGetFrame) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * str, CallFrame ** framePtrPtr)); /* 32 */ TclCmdProcType (*tclGetInterpProc) _ANSI_ARGS_((void)); /* 33 */ int (*tclGetIntForIndex) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * objPtr, int endValue, int * indexPtr)); /* 34 */ void *reserved35; int (*tclGetLong) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * str, long * longPtr)); /* 36 */ int (*tclGetLoadedPackages) _ANSI_ARGS_((Tcl_Interp * interp, char * targetName)); /* 37 */ int (*tclGetNamespaceForQualName) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * qualName, Namespace * cxtNsPtr, int flags, Namespace ** nsPtrPtr, Namespace ** altNsPtrPtr, Namespace ** actualCxtPtrPtr, CONST char ** simpleNamePtr)); /* 38 */ TclObjCmdProcType (*tclGetObjInterpProc) _ANSI_ARGS_((void)); /* 39 */ int (*tclGetOpenMode) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * str, int * seekFlagPtr)); /* 40 */ Tcl_Command (*tclGetOriginalCommand) _ANSI_ARGS_((Tcl_Command command)); /* 41 */ char * (*tclpGetUserHome) _ANSI_ARGS_((CONST char * name, Tcl_DString * bufferPtr)); /* 42 */ int (*tclGlobalInvoke) _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST84 char ** argv, int flags)); /* 43 */ int (*tclGuessPackageName) _ANSI_ARGS_((CONST char * fileName, Tcl_DString * bufPtr)); /* 44 */ int (*tclHideUnsafeCommands) _ANSI_ARGS_((Tcl_Interp * interp)); /* 45 */ int (*tclInExit) _ANSI_ARGS_((void)); /* 46 */ void *reserved47; void *reserved48; Tcl_Obj * (*tclIncrVar2) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * part1Ptr, Tcl_Obj * part2Ptr, long incrAmount, int part1NotParsed)); /* 49 */ void (*tclInitCompiledLocals) _ANSI_ARGS_((Tcl_Interp * interp, CallFrame * framePtr, Namespace * nsPtr)); /* 50 */ int (*tclInterpInit) _ANSI_ARGS_((Tcl_Interp * interp)); /* 51 */ int (*tclInvoke) _ANSI_ARGS_((Tcl_Interp * interp, int argc, CONST84 char ** argv, int flags)); /* 52 */ int (*tclInvokeObjectCommand) _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, int argc, CONST84 char ** argv)); /* 53 */ int (*tclInvokeStringCommand) _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[])); /* 54 */ Proc * (*tclIsProc) _ANSI_ARGS_((Command * cmdPtr)); /* 55 */ void *reserved56; void *reserved57; Var * (*tclLookupVar) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * part1, CONST char * part2, int flags, CONST char * msg, int createPart1, int createPart2, Var ** arrayPtrPtr)); /* 58 */ void *reserved59; int (*tclNeedSpace) _ANSI_ARGS_((CONST char * start, CONST char * end)); /* 60 */ Tcl_Obj * (*tclNewProcBodyObj) _ANSI_ARGS_((Proc * procPtr)); /* 61 */ int (*tclObjCommandComplete) _ANSI_ARGS_((Tcl_Obj * cmdPtr)); /* 62 */ int (*tclObjInterpProc) _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[])); /* 63 */ int (*tclObjInvoke) _ANSI_ARGS_((Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[], int flags)); /* 64 */ int (*tclObjInvokeGlobal) _ANSI_ARGS_((Tcl_Interp * interp, int objc, Tcl_Obj *CONST objv[], int flags)); /* 65 */ int (*tclOpenFileChannelDeleteProc) _ANSI_ARGS_((TclOpenFileChannelProc_ * proc)); /* 66 */ int (*tclOpenFileChannelInsertProc) _ANSI_ARGS_((TclOpenFileChannelProc_ * proc)); /* 67 */ void *reserved68; char * (*tclpAlloc) _ANSI_ARGS_((unsigned int size)); /* 69 */ void *reserved70; void *reserved71; void *reserved72; void *reserved73; void (*tclpFree) _ANSI_ARGS_((char * ptr)); /* 74 */ unsigned long (*tclpGetClicks) _ANSI_ARGS_((void)); /* 75 */ unsigned long (*tclpGetSeconds) _ANSI_ARGS_((void)); /* 76 */ void (*tclpGetTime) _ANSI_ARGS_((Tcl_Time * time)); /* 77 */ int (*tclpGetTimeZone) _ANSI_ARGS_((Tcl_WideInt time)); /* 78 */ void *reserved79; void *reserved80; char * (*tclpRealloc) _ANSI_ARGS_((char * ptr, unsigned int size)); /* 81 */ void *reserved82; void *reserved83; void *reserved84; void *reserved85; void *reserved86; void *reserved87; char * (*tclPrecTraceProc) _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, CONST char * name1, CONST char * name2, int flags)); /* 88 */ int (*tclPreventAliasLoop) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Interp * cmdInterp, Tcl_Command cmd)); /* 89 */ void *reserved90; void (*tclProcCleanupProc) _ANSI_ARGS_((Proc * procPtr)); /* 91 */ int (*tclProcCompileProc) _ANSI_ARGS_((Tcl_Interp * interp, Proc * procPtr, Tcl_Obj * bodyPtr, Namespace * nsPtr, CONST char * description, CONST char * procName)); /* 92 */ void (*tclProcDeleteProc) _ANSI_ARGS_((ClientData clientData)); /* 93 */ int (*tclProcInterpProc) _ANSI_ARGS_((ClientData clientData, Tcl_Interp * interp, int argc, CONST84 char ** argv)); /* 94 */ void *reserved95; int (*tclRenameCommand) _ANSI_ARGS_((Tcl_Interp * interp, char * oldName, char * newName)); /* 96 */ void (*tclResetShadowedCmdRefs) _ANSI_ARGS_((Tcl_Interp * interp, Command * newCmdPtr)); /* 97 */ int (*tclServiceIdle) _ANSI_ARGS_((void)); /* 98 */ void *reserved99; void *reserved100; char * (*tclSetPreInitScript) _ANSI_ARGS_((char * string)); /* 101 */ void (*tclSetupEnv) _ANSI_ARGS_((Tcl_Interp * interp)); /* 102 */ int (*tclSockGetPort) _ANSI_ARGS_((Tcl_Interp * interp, char * str, char * proto, int * portPtr)); /* 103 */ #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ int (*tclSockMinimumBuffers) _ANSI_ARGS_((int sock, int size)); /* 104 */ #endif /* UNIX */ #ifdef __WIN32__ int (*tclSockMinimumBuffers) _ANSI_ARGS_((int sock, int size)); /* 104 */ #endif /* __WIN32__ */ #ifdef MAC_TCL void *reserved104; #endif /* MAC_TCL */ void *reserved105; int (*tclStatDeleteProc) _ANSI_ARGS_((TclStatProc_ * proc)); /* 106 */ int (*tclStatInsertProc) _ANSI_ARGS_((TclStatProc_ * proc)); /* 107 */ void (*tclTeardownNamespace) _ANSI_ARGS_((Namespace * nsPtr)); /* 108 */ int (*tclUpdateReturnInfo) _ANSI_ARGS_((Interp * iPtr)); /* 109 */ void *reserved110; void (*tcl_AddInterpResolvers) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_ResolveCmdProc * cmdProc, Tcl_ResolveVarProc * varProc, Tcl_ResolveCompiledVarProc * compiledVarProc)); /* 111 */ int (*tcl_AppendExportList) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, Tcl_Obj * objPtr)); /* 112 */ Tcl_Namespace * (*tcl_CreateNamespace) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, ClientData clientData, Tcl_NamespaceDeleteProc * deleteProc)); /* 113 */ void (*tcl_DeleteNamespace) _ANSI_ARGS_((Tcl_Namespace * nsPtr)); /* 114 */ int (*tcl_Export) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, CONST char * pattern, int resetListFirst)); /* 115 */ Tcl_Command (*tcl_FindCommand) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_Namespace * contextNsPtr, int flags)); /* 116 */ Tcl_Namespace * (*tcl_FindNamespace) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_Namespace * contextNsPtr, int flags)); /* 117 */ int (*tcl_GetInterpResolvers) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_ResolverInfo * resInfo)); /* 118 */ int (*tcl_GetNamespaceResolvers) _ANSI_ARGS_((Tcl_Namespace * namespacePtr, Tcl_ResolverInfo * resInfo)); /* 119 */ Tcl_Var (*tcl_FindNamespaceVar) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name, Tcl_Namespace * contextNsPtr, int flags)); /* 120 */ int (*tcl_ForgetImport) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, CONST char * pattern)); /* 121 */ Tcl_Command (*tcl_GetCommandFromObj) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * objPtr)); /* 122 */ void (*tcl_GetCommandFullName) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Command command, Tcl_Obj * objPtr)); /* 123 */ Tcl_Namespace * (*tcl_GetCurrentNamespace) _ANSI_ARGS_((Tcl_Interp * interp)); /* 124 */ Tcl_Namespace * (*tcl_GetGlobalNamespace) _ANSI_ARGS_((Tcl_Interp * interp)); /* 125 */ void (*tcl_GetVariableFullName) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Var variable, Tcl_Obj * objPtr)); /* 126 */ int (*tcl_Import) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Namespace * nsPtr, CONST char * pattern, int allowOverwrite)); /* 127 */ void (*tcl_PopCallFrame) _ANSI_ARGS_((Tcl_Interp* interp)); /* 128 */ int (*tcl_PushCallFrame) _ANSI_ARGS_((Tcl_Interp* interp, Tcl_CallFrame * framePtr, Tcl_Namespace * nsPtr, int isProcCallFrame)); /* 129 */ int (*tcl_RemoveInterpResolvers) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * name)); /* 130 */ void (*tcl_SetNamespaceResolvers) _ANSI_ARGS_((Tcl_Namespace * namespacePtr, Tcl_ResolveCmdProc * cmdProc, Tcl_ResolveVarProc * varProc, Tcl_ResolveCompiledVarProc * compiledVarProc)); /* 131 */ int (*tclpHasSockets) _ANSI_ARGS_((Tcl_Interp * interp)); /* 132 */ struct tm * (*tclpGetDate) _ANSI_ARGS_((TclpTime_t time, int useGMT)); /* 133 */ size_t (*tclpStrftime) _ANSI_ARGS_((char * s, size_t maxsize, CONST char * format, CONST struct tm * t, int useGMT)); /* 134 */ int (*tclpCheckStackSpace) _ANSI_ARGS_((void)); /* 135 */ void *reserved136; void *reserved137; CONST84_RETURN char * (*tclGetEnv) _ANSI_ARGS_((CONST char * name, Tcl_DString * valuePtr)); /* 138 */ void *reserved139; int (*tclLooksLikeInt) _ANSI_ARGS_((CONST char * bytes, int length)); /* 140 */ CONST84_RETURN char * (*tclpGetCwd) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_DString * cwdPtr)); /* 141 */ int (*tclSetByteCodeFromAny) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * objPtr, CompileHookProc * hookProc, ClientData clientData)); /* 142 */ int (*tclAddLiteralObj) _ANSI_ARGS_((struct CompileEnv * envPtr, Tcl_Obj * objPtr, LiteralEntry ** litPtrPtr)); /* 143 */ void (*tclHideLiteral) _ANSI_ARGS_((Tcl_Interp * interp, struct CompileEnv * envPtr, int index)); /* 144 */ struct AuxDataType * (*tclGetAuxDataType) _ANSI_ARGS_((char * typeName)); /* 145 */ TclHandle (*tclHandleCreate) _ANSI_ARGS_((VOID * ptr)); /* 146 */ void (*tclHandleFree) _ANSI_ARGS_((TclHandle handle)); /* 147 */ TclHandle (*tclHandlePreserve) _ANSI_ARGS_((TclHandle handle)); /* 148 */ void (*tclHandleRelease) _ANSI_ARGS_((TclHandle handle)); /* 149 */ int (*tclRegAbout) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_RegExp re)); /* 150 */ void (*tclRegExpRangeUniChar) _ANSI_ARGS_((Tcl_RegExp re, int index, int * startPtr, int * endPtr)); /* 151 */ void (*tclSetLibraryPath) _ANSI_ARGS_((Tcl_Obj * pathPtr)); /* 152 */ Tcl_Obj * (*tclGetLibraryPath) _ANSI_ARGS_((void)); /* 153 */ void *reserved154; void *reserved155; void (*tclRegError) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * msg, int status)); /* 156 */ Var * (*tclVarTraceExists) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * varName)); /* 157 */ void (*tclSetStartupScriptFileName) _ANSI_ARGS_((CONST char * filename)); /* 158 */ CONST84_RETURN char * (*tclGetStartupScriptFileName) _ANSI_ARGS_((void)); /* 159 */ void *reserved160; int (*tclChannelTransform) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Channel chan, Tcl_Obj * cmdObjPtr)); /* 161 */ void (*tclChannelEventScriptInvoker) _ANSI_ARGS_((ClientData clientData, int flags)); /* 162 */ void * (*tclGetInstructionTable) _ANSI_ARGS_((void)); /* 163 */ void (*tclExpandCodeArray) _ANSI_ARGS_((void * envPtr)); /* 164 */ void (*tclpSetInitialEncodings) _ANSI_ARGS_((void)); /* 165 */ int (*tclListObjSetElement) _ANSI_ARGS_((Tcl_Interp * interp, Tcl_Obj * listPtr, int index, Tcl_Obj * valuePtr)); /* 166 */ void (*tclSetStartupScriptPath) _ANSI_ARGS_((Tcl_Obj * pathPtr)); /* 167 */ Tcl_Obj * (*tclGetStartupScriptPath) _ANSI_ARGS_((void)); /* 168 */ int (*tclpUtfNcmp2) _ANSI_ARGS_((CONST char * s1, CONST char * s2, unsigned long n)); /* 169 */ int (*tclCheckInterpTraces) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * command, int numChars, Command * cmdPtr, int result, int traceFlags, int objc, Tcl_Obj *CONST objv[])); /* 170 */ int (*tclCheckExecutionTraces) _ANSI_ARGS_((Tcl_Interp * interp, CONST char * command, int numChars, Command * cmdPtr, int result, int traceFlags, int objc, Tcl_Obj *CONST objv[])); /* 171 */ int (*tclInThreadExit) _ANSI_ARGS_((void)); /* 172 */ int (*tclUniCharMatch) _ANSI_ARGS_((CONST Tcl_UniChar * string, int strLen, CONST Tcl_UniChar * pattern, int ptnLen, int nocase)); /* 173 */ void *reserved174; void *reserved175; void *reserved176; void *reserved177; void *reserved178; void *reserved179; void *reserved180; void *reserved181; struct tm * (*tclpLocaltime) _ANSI_ARGS_((TclpTime_t_CONST clock)); /* 182 */ struct tm * (*tclpGmtime) _ANSI_ARGS_((TclpTime_t_CONST clock)); /* 183 */ void *reserved184; void *reserved185; void *reserved186; void *reserved187; void *reserved188; void *reserved189; void *reserved190; void *reserved191; void *reserved192; void *reserved193; void *reserved194; void *reserved195; void *reserved196; void *reserved197; void *reserved198; int (*tclMatchIsTrivial) _ANSI_ARGS_((CONST char * pattern)); /* 199 */ } TclIntStubs; #ifdef __cplusplus extern "C" { #endif extern TclIntStubs *tclIntStubsPtr; #ifdef __cplusplus } #endif #if defined(USE_TCL_STUBS) && !defined(USE_TCL_STUB_PROCS) /* * Inline function declarations: */ /* Slot 0 is reserved */ #ifndef TclAccessDeleteProc #define TclAccessDeleteProc \ (tclIntStubsPtr->tclAccessDeleteProc) /* 1 */ #endif #ifndef TclAccessInsertProc #define TclAccessInsertProc \ (tclIntStubsPtr->tclAccessInsertProc) /* 2 */ #endif #ifndef TclAllocateFreeObjects #define TclAllocateFreeObjects \ (tclIntStubsPtr->tclAllocateFreeObjects) /* 3 */ #endif /* Slot 4 is reserved */ #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ #ifndef TclCleanupChildren #define TclCleanupChildren \ (tclIntStubsPtr->tclCleanupChildren) /* 5 */ #endif #endif /* UNIX */ #ifdef __WIN32__ #ifndef TclCleanupChildren #define TclCleanupChildren \ (tclIntStubsPtr->tclCleanupChildren) /* 5 */ #endif #endif /* __WIN32__ */ #ifndef TclCleanupCommand #define TclCleanupCommand \ (tclIntStubsPtr->tclCleanupCommand) /* 6 */ #endif #ifndef TclCopyAndCollapse #define TclCopyAndCollapse \ (tclIntStubsPtr->tclCopyAndCollapse) /* 7 */ #endif #ifndef TclCopyChannel #define TclCopyChannel \ (tclIntStubsPtr->tclCopyChannel) /* 8 */ #endif #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ #ifndef TclCreatePipeline #define TclCreatePipeline \ (tclIntStubsPtr->tclCreatePipeline) /* 9 */ #endif #endif /* UNIX */ #ifdef __WIN32__ #ifndef TclCreatePipeline #define TclCreatePipeline \ (tclIntStubsPtr->tclCreatePipeline) /* 9 */ #endif #endif /* __WIN32__ */ #ifndef TclCreateProc #define TclCreateProc \ (tclIntStubsPtr->tclCreateProc) /* 10 */ #endif #ifndef TclDeleteCompiledLocalVars #define TclDeleteCompiledLocalVars \ (tclIntStubsPtr->tclDeleteCompiledLocalVars) /* 11 */ #endif #ifndef TclDeleteVars #define TclDeleteVars \ (tclIntStubsPtr->tclDeleteVars) /* 12 */ #endif #ifndef TclDoGlob #define TclDoGlob \ (tclIntStubsPtr->tclDoGlob) /* 13 */ #endif #ifndef TclDumpMemoryInfo #define TclDumpMemoryInfo \ (tclIntStubsPtr->tclDumpMemoryInfo) /* 14 */ #endif /* Slot 15 is reserved */ #ifndef TclExprFloatError #define TclExprFloatError \ (tclIntStubsPtr->tclExprFloatError) /* 16 */ #endif /* Slot 17 is reserved */ /* Slot 18 is reserved */ /* Slot 19 is reserved */ /* Slot 20 is reserved */ /* Slot 21 is reserved */ #ifndef TclFindElement #define TclFindElement \ (tclIntStubsPtr->tclFindElement) /* 22 */ #endif #ifndef TclFindProc #define TclFindProc \ (tclIntStubsPtr->tclFindProc) /* 23 */ #endif #ifndef TclFormatInt #define TclFormatInt \ (tclIntStubsPtr->tclFormatInt) /* 24 */ #endif #ifndef TclFreePackageInfo #define TclFreePackageInfo \ (tclIntStubsPtr->tclFreePackageInfo) /* 25 */ #endif /* Slot 26 is reserved */ #ifndef TclGetDate #define TclGetDate \ (tclIntStubsPtr->tclGetDate) /* 27 */ #endif #ifndef TclpGetDefaultStdChannel #define TclpGetDefaultStdChannel \ (tclIntStubsPtr->tclpGetDefaultStdChannel) /* 28 */ #endif /* Slot 29 is reserved */ /* Slot 30 is reserved */ #ifndef TclGetExtension #define TclGetExtension \ (tclIntStubsPtr->tclGetExtension) /* 31 */ #endif #ifndef TclGetFrame #define TclGetFrame \ (tclIntStubsPtr->tclGetFrame) /* 32 */ #endif #ifndef TclGetInterpProc #define TclGetInterpProc \ (tclIntStubsPtr->tclGetInterpProc) /* 33 */ #endif #ifndef TclGetIntForIndex #define TclGetIntForIndex \ (tclIntStubsPtr->tclGetIntForIndex) /* 34 */ #endif /* Slot 35 is reserved */ #ifndef TclGetLong #define TclGetLong \ (tclIntStubsPtr->tclGetLong) /* 36 */ #endif #ifndef TclGetLoadedPackages #define TclGetLoadedPackages \ (tclIntStubsPtr->tclGetLoadedPackages) /* 37 */ #endif #ifndef TclGetNamespaceForQualName #define TclGetNamespaceForQualName \ (tclIntStubsPtr->tclGetNamespaceForQualName) /* 38 */ #endif #ifndef TclGetObjInterpProc #define TclGetObjInterpProc \ (tclIntStubsPtr->tclGetObjInterpProc) /* 39 */ #endif #ifndef TclGetOpenMode #define TclGetOpenMode \ (tclIntStubsPtr->tclGetOpenMode) /* 40 */ #endif #ifndef TclGetOriginalCommand #define TclGetOriginalCommand \ (tclIntStubsPtr->tclGetOriginalCommand) /* 41 */ #endif #ifndef TclpGetUserHome #define TclpGetUserHome \ (tclIntStubsPtr->tclpGetUserHome) /* 42 */ #endif #ifndef TclGlobalInvoke #define TclGlobalInvoke \ (tclIntStubsPtr->tclGlobalInvoke) /* 43 */ #endif #ifndef TclGuessPackageName #define TclGuessPackageName \ (tclIntStubsPtr->tclGuessPackageName) /* 44 */ #endif #ifndef TclHideUnsafeCommands #define TclHideUnsafeCommands \ (tclIntStubsPtr->tclHideUnsafeCommands) /* 45 */ #endif #ifndef TclInExit #define TclInExit \ (tclIntStubsPtr->tclInExit) /* 46 */ #endif /* Slot 47 is reserved */ /* Slot 48 is reserved */ #ifndef TclIncrVar2 #define TclIncrVar2 \ (tclIntStubsPtr->tclIncrVar2) /* 49 */ #endif #ifndef TclInitCompiledLocals #define TclInitCompiledLocals \ (tclIntStubsPtr->tclInitCompiledLocals) /* 50 */ #endif #ifndef TclInterpInit #define TclInterpInit \ (tclIntStubsPtr->tclInterpInit) /* 51 */ #endif #ifndef TclInvoke #define TclInvoke \ (tclIntStubsPtr->tclInvoke) /* 52 */ #endif #ifndef TclInvokeObjectCommand #define TclInvokeObjectCommand \ (tclIntStubsPtr->tclInvokeObjectCommand) /* 53 */ #endif #ifndef TclInvokeStringCommand #define TclInvokeStringCommand \ (tclIntStubsPtr->tclInvokeStringCommand) /* 54 */ #endif #ifndef TclIsProc #define TclIsProc \ (tclIntStubsPtr->tclIsProc) /* 55 */ #endif /* Slot 56 is reserved */ /* Slot 57 is reserved */ #ifndef TclLookupVar #define TclLookupVar \ (tclIntStubsPtr->tclLookupVar) /* 58 */ #endif /* Slot 59 is reserved */ #ifndef TclNeedSpace #define TclNeedSpace \ (tclIntStubsPtr->tclNeedSpace) /* 60 */ #endif #ifndef TclNewProcBodyObj #define TclNewProcBodyObj \ (tclIntStubsPtr->tclNewProcBodyObj) /* 61 */ #endif #ifndef TclObjCommandComplete #define TclObjCommandComplete \ (tclIntStubsPtr->tclObjCommandComplete) /* 62 */ #endif #ifndef TclObjInterpProc #define TclObjInterpProc \ (tclIntStubsPtr->tclObjInterpProc) /* 63 */ #endif #ifndef TclObjInvoke #define TclObjInvoke \ (tclIntStubsPtr->tclObjInvoke) /* 64 */ #endif #ifndef TclObjInvokeGlobal #define TclObjInvokeGlobal \ (tclIntStubsPtr->tclObjInvokeGlobal) /* 65 */ #endif #ifndef TclOpenFileChannelDeleteProc #define TclOpenFileChannelDeleteProc \ (tclIntStubsPtr->tclOpenFileChannelDeleteProc) /* 66 */ #endif #ifndef TclOpenFileChannelInsertProc #define TclOpenFileChannelInsertProc \ (tclIntStubsPtr->tclOpenFileChannelInsertProc) /* 67 */ #endif /* Slot 68 is reserved */ #ifndef TclpAlloc #define TclpAlloc \ (tclIntStubsPtr->tclpAlloc) /* 69 */ #endif /* Slot 70 is reserved */ /* Slot 71 is reserved */ /* Slot 72 is reserved */ /* Slot 73 is reserved */ #ifndef TclpFree #define TclpFree \ (tclIntStubsPtr->tclpFree) /* 74 */ #endif #ifndef TclpGetClicks #define TclpGetClicks \ (tclIntStubsPtr->tclpGetClicks) /* 75 */ #endif #ifndef TclpGetSeconds #define TclpGetSeconds \ (tclIntStubsPtr->tclpGetSeconds) /* 76 */ #endif #ifndef TclpGetTime #define TclpGetTime \ (tclIntStubsPtr->tclpGetTime) /* 77 */ #endif #ifndef TclpGetTimeZone #define TclpGetTimeZone \ (tclIntStubsPtr->tclpGetTimeZone) /* 78 */ #endif /* Slot 79 is reserved */ /* Slot 80 is reserved */ #ifndef TclpRealloc #define TclpRealloc \ (tclIntStubsPtr->tclpRealloc) /* 81 */ #endif /* Slot 82 is reserved */ /* Slot 83 is reserved */ /* Slot 84 is reserved */ /* Slot 85 is reserved */ /* Slot 86 is reserved */ /* Slot 87 is reserved */ #ifndef TclPrecTraceProc #define TclPrecTraceProc \ (tclIntStubsPtr->tclPrecTraceProc) /* 88 */ #endif #ifndef TclPreventAliasLoop #define TclPreventAliasLoop \ (tclIntStubsPtr->tclPreventAliasLoop) /* 89 */ #endif /* Slot 90 is reserved */ #ifndef TclProcCleanupProc #define TclProcCleanupProc \ (tclIntStubsPtr->tclProcCleanupProc) /* 91 */ #endif #ifndef TclProcCompileProc #define TclProcCompileProc \ (tclIntStubsPtr->tclProcCompileProc) /* 92 */ #endif #ifndef TclProcDeleteProc #define TclProcDeleteProc \ (tclIntStubsPtr->tclProcDeleteProc) /* 93 */ #endif #ifndef TclProcInterpProc #define TclProcInterpProc \ (tclIntStubsPtr->tclProcInterpProc) /* 94 */ #endif /* Slot 95 is reserved */ #ifndef TclRenameCommand #define TclRenameCommand \ (tclIntStubsPtr->tclRenameCommand) /* 96 */ #endif #ifndef TclResetShadowedCmdRefs #define TclResetShadowedCmdRefs \ (tclIntStubsPtr->tclResetShadowedCmdRefs) /* 97 */ #endif #ifndef TclServiceIdle #define TclServiceIdle \ (tclIntStubsPtr->tclServiceIdle) /* 98 */ #endif /* Slot 99 is reserved */ /* Slot 100 is reserved */ #ifndef TclSetPreInitScript #define TclSetPreInitScript \ (tclIntStubsPtr->tclSetPreInitScript) /* 101 */ #endif #ifndef TclSetupEnv #define TclSetupEnv \ (tclIntStubsPtr->tclSetupEnv) /* 102 */ #endif #ifndef TclSockGetPort #define TclSockGetPort \ (tclIntStubsPtr->tclSockGetPort) /* 103 */ #endif #if !defined(__WIN32__) && !defined(MAC_TCL) /* UNIX */ #ifndef TclSockMinimumBuffers #define TclSockMinimumBuffers \ (tclIntStubsPtr->tclSockMinimumBuffers) /* 104 */ #endif #endif /* UNIX */ #ifdef __WIN32__ #ifndef TclSockMinimumBuffers #define TclSockMinimumBuffers \ (tclIntStubsPtr->tclSockMinimumBuffers) /* 104 */ #endif #endif /* __WIN32__ */ /* Slot 105 is reserved */ #ifndef TclStatDeleteProc #define TclStatDeleteProc \ (tclIntStubsPtr->tclStatDeleteProc) /* 106 */ #endif #ifndef TclStatInsertProc #define TclStatInsertProc \ (tclIntStubsPtr->tclStatInsertProc) /* 107 */ #endif #ifndef TclTeardownNamespace #define TclTeardownNamespace \ (tclIntStubsPtr->tclTeardownNamespace) /* 108 */ #endif #ifndef TclUpdateReturnInfo #define TclUpdateReturnInfo \ (tclIntStubsPtr->tclUpdateReturnInfo) /* 109 */ #endif /* Slot 110 is reserved */ #ifndef Tcl_AddInterpResolvers #define Tcl_AddInterpResolvers \ (tclIntStubsPtr->tcl_AddInterpResolvers) /* 111 */ #endif #ifndef Tcl_AppendExportList #define Tcl_AppendExportList \ (tclIntStubsPtr->tcl_AppendExportList) /* 112 */ #endif #ifndef Tcl_CreateNamespace #define Tcl_CreateNamespace \ (tclIntStubsPtr->tcl_CreateNamespace) /* 113 */ #endif #ifndef Tcl_DeleteNamespace #define Tcl_DeleteNamespace \ (tclIntStubsPtr->tcl_DeleteNamespace) /* 114 */ #endif #ifndef Tcl_Export #define Tcl_Export \ (tclIntStubsPtr->tcl_Export) /* 115 */ #endif #ifndef Tcl_FindCommand #define Tcl_FindCommand \ (tclIntStubsPtr->tcl_FindCommand) /* 116 */ #endif #ifndef Tcl_FindNamespace #define Tcl_FindNamespace \ (tclIntStubsPtr->tcl_FindNamespace) /* 117 */ #endif #ifndef Tcl_GetInterpResolvers #define Tcl_GetInterpResolvers \ (tclIntStubsPtr->tcl_GetInterpResolvers) /* 118 */ #endif #ifndef Tcl_GetNamespaceResolvers #define Tcl_GetNamespaceResolvers \ (tclIntStubsPtr->tcl_GetNamespaceResolvers) /* 119 */ #endif #ifndef Tcl_FindNamespaceVar #define Tcl_FindNamespaceVar \ (tclIntStubsPtr->tcl_FindNamespaceVar) /* 120 */ #endif #ifndef Tcl_ForgetImport #define Tcl_ForgetImport \ (tclIntStubsPtr->tcl_ForgetImport) /* 121 */ #endif #ifndef Tcl_GetCommandFromObj #define Tcl_GetCommandFromObj \ (tclIntStubsPtr->tcl_GetCommandFromObj) /* 122 */ #endif #ifndef Tcl_GetCommandFullName #define Tcl_GetCommandFullName \ (tclIntStubsPtr->tcl_GetCommandFullName) /* 123 */ #endif #ifndef Tcl_GetCurrentNamespace #define Tcl_GetCurrentNamespace \ (tclIntStubsPtr->tcl_GetCurrentNamespace) /* 124 */ #endif #ifndef Tcl_GetGlobalNamespace #define Tcl_GetGlobalNamespace \ (tclIntStubsPtr->tcl_GetGlobalNamespace) /* 125 */ #endif #ifndef Tcl_GetVariableFullName #define Tcl_GetVariableFullName \ (tclIntStubsPtr->tcl_GetVariableFullName) /* 126 */ #endif #ifndef Tcl_Import #define Tcl_Import \ (tclIntStubsPtr->tcl_Import) /* 127 */ #endif #ifndef Tcl_PopCallFrame #define Tcl_PopCallFrame \ (tclIntStubsPtr->tcl_PopCallFrame) /* 128 */ #endif #ifndef Tcl_PushCallFrame #define Tcl_PushCallFrame \ (tclIntStubsPtr->tcl_PushCallFrame) /* 129 */ #endif #ifndef Tcl_RemoveInterpResolvers #define Tcl_RemoveInterpResolvers \ (tclIntStubsPtr->tcl_RemoveInterpResolvers) /* 130 */ #endif #ifndef Tcl_SetNamespaceResolvers #define Tcl_SetNamespaceResolvers \ (tclIntStubsPtr->tcl_SetNamespaceResolvers) /* 131 */ #endif #ifndef TclpHasSockets #define TclpHasSockets \ (tclIntStubsPtr->tclpHasSockets) /* 132 */ #endif #ifndef TclpGetDate #define TclpGetDate \ (tclIntStubsPtr->tclpGetDate) /* 133 */ #endif #ifndef TclpStrftime #define TclpStrftime \ (tclIntStubsPtr->tclpStrftime) /* 134 */ #endif #ifndef TclpCheckStackSpace #define TclpCheckStackSpace \ (tclIntStubsPtr->tclpCheckStackSpace) /* 135 */ #endif /* Slot 136 is reserved */ /* Slot 137 is reserved */ #ifndef TclGetEnv #define TclGetEnv \ (tclIntStubsPtr->tclGetEnv) /* 138 */ #endif /* Slot 139 is reserved */ #ifndef TclLooksLikeInt #define TclLooksLikeInt \ (tclIntStubsPtr->tclLooksLikeInt) /* 140 */ #endif #ifndef TclpGetCwd #define TclpGetCwd \ (tclIntStubsPtr->tclpGetCwd) /* 141 */ #endif #ifndef TclSetByteCodeFromAny #define TclSetByteCodeFromAny \ (tclIntStubsPtr->tclSetByteCodeFromAny) /* 142 */ #endif #ifndef TclAddLiteralObj #define TclAddLiteralObj \ (tclIntStubsPtr->tclAddLiteralObj) /* 143 */ #endif #ifndef TclHideLiteral #define TclHideLiteral \ (tclIntStubsPtr->tclHideLiteral) /* 144 */ #endif #ifndef TclGetAuxDataType #define TclGetAuxDataType \ (tclIntStubsPtr->tclGetAuxDataType) /* 145 */ #endif #ifndef TclHandleCreate #define TclHandleCreate \ (tclIntStubsPtr->tclHandleCreate) /* 146 */ #endif #ifndef TclHandleFree #define TclHandleFree \ (tclIntStubsPtr->tclHandleFree) /* 147 */ #endif #ifndef TclHandlePreserve #define TclHandlePreserve \ (tclIntStubsPtr->tclHandlePreserve) /* 148 */ #endif #ifndef TclHandleRelease #define TclHandleRelease \ (tclIntStubsPtr->tclHandleRelease) /* 149 */ #endif #ifndef TclRegAbout #define TclRegAbout \ (tclIntStubsPtr->tclRegAbout) /* 150 */ #endif #ifndef TclRegExpRangeUniChar #define TclRegExpRangeUniChar \ (tclIntStubsPtr->tclRegExpRangeUniChar) /* 151 */ #endif #ifndef TclSetLibraryPath #define TclSetLibraryPath \ (tclIntStubsPtr->tclSetLibraryPath) /* 152 */ #endif #ifndef TclGetLibraryPath #define TclGetLibraryPath \ (tclIntStubsPtr->tclGetLibraryPath) /* 153 */ #endif /* Slot 154 is reserved */ /* Slot 155 is reserved */ #ifndef TclRegError #define TclRegError \ (tclIntStubsPtr->tclRegError) /* 156 */ #endif #ifndef TclVarTraceExists #define TclVarTraceExists \ (tclIntStubsPtr->tclVarTraceExists) /* 157 */ #endif #ifndef TclSetStartupScriptFileName #define TclSetStartupScriptFileName \ (tclIntStubsPtr->tclSetStartupScriptFileName) /* 158 */ #endif #ifndef TclGetStartupScriptFileName #define TclGetStartupScriptFileName \ (tclIntStubsPtr->tclGetStartupScriptFileName) /* 159 */ #endif /* Slot 160 is reserved */ #ifndef TclChannelTransform #define TclChannelTransform \ (tclIntStubsPtr->tclChannelTransform) /* 161 */ #endif #ifndef TclChannelEventScriptInvoker #define TclChannelEventScriptInvoker \ (tclIntStubsPtr->tclChannelEventScriptInvoker) /* 162 */ #endif #ifndef TclGetInstructionTable #define TclGetInstructionTable \ (tclIntStubsPtr->tclGetInstructionTable) /* 163 */ #endif #ifndef TclExpandCodeArray #define TclExpandCodeArray \ (tclIntStubsPtr->tclExpandCodeArray) /* 164 */ #endif #ifndef TclpSetInitialEncodings #define TclpSetInitialEncodings \ (tclIntStubsPtr->tclpSetInitialEncodings) /* 165 */ #endif #ifndef TclListObjSetElement #define TclListObjSetElement \ (tclIntStubsPtr->tclListObjSetElement) /* 166 */ #endif #ifndef TclSetStartupScriptPath #define TclSetStartupScriptPath \ (tclIntStubsPtr->tclSetStartupScriptPath) /* 167 */ #endif #ifndef TclGetStartupScriptPath #define TclGetStartupScriptPath \ (tclIntStubsPtr->tclGetStartupScriptPath) /* 168 */ #endif #ifndef TclpUtfNcmp2 #define TclpUtfNcmp2 \ (tclIntStubsPtr->tclpUtfNcmp2) /* 169 */ #endif #ifndef TclCheckInterpTraces #define TclCheckInterpTraces \ (tclIntStubsPtr->tclCheckInterpTraces) /* 170 */ #endif #ifndef TclCheckExecutionTraces #define TclCheckExecutionTraces \ (tclIntStubsPtr->tclCheckExecutionTraces) /* 171 */ #endif #ifndef TclInThreadExit #define TclInThreadExit \ (tclIntStubsPtr->tclInThreadExit) /* 172 */ #endif #ifndef TclUniCharMatch #define TclUniCharMatch \ (tclIntStubsPtr->tclUniCharMatch) /* 173 */ #endif /* Slot 174 is reserved */ /* Slot 175 is reserved */ /* Slot 176 is reserved */ /* Slot 177 is reserved */ /* Slot 178 is reserved */ /* Slot 179 is reserved */ /* Slot 180 is reserved */ /* Slot 181 is reserved */ #ifndef TclpLocaltime #define TclpLocaltime \ (tclIntStubsPtr->tclpLocaltime) /* 182 */ #endif #ifndef TclpGmtime #define TclpGmtime \ (tclIntStubsPtr->tclpGmtime) /* 183 */ #endif /* Slot 184 is reserved */ /* Slot 185 is reserved */ /* Slot 186 is reserved */ /* Slot 187 is reserved */ /* Slot 188 is reserved */ /* Slot 189 is reserved */ /* Slot 190 is reserved */ /* Slot 191 is reserved */ /* Slot 192 is reserved */ /* Slot 193 is reserved */ /* Slot 194 is reserved */ /* Slot 195 is reserved */ /* Slot 196 is reserved */ /* Slot 197 is reserved */ /* Slot 198 is reserved */ #ifndef TclMatchIsTrivial #define TclMatchIsTrivial \ (tclIntStubsPtr->tclMatchIsTrivial) /* 199 */ #endif #endif /* defined(USE_TCL_STUBS) && !defined(USE_TCL_STUB_PROCS) */ /* !END!: Do not edit above this line. */ #endif /* _TCLINTDECLS */
danieljoppi/AntHocNet
ns-allinone-2.34/tcl8.4.18/generic/tclIntDecls.h
C
gpl-2.0
51,778
/* * IPv6 output functions * Linux INET6 implementation * * Authors: * Pedro Roque <[email protected]> * * Based on linux/net/ipv4/ip_output.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * A.N.Kuznetsov : airthmetics in fragmentation. * extension headers are implemented. * route changes now work. * ip6_forward does not confuse sniffers. * etc. * * H. von Brand : Added missing #include <linux/string.h> * Imran Patel : frag id should be in NBO * Kazunori MIYAZAWA @USAGI * : add ip6_append_data and related functions * for datagram xmit */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/route.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/rawv6.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/checksum.h> #include <linux/mroute6.h> int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *)); int __ip6_local_out(struct sk_buff *skb) { int len; len = skb->len - sizeof(struct ipv6hdr); if (len > IPV6_MAXPLEN) len = 0; ipv6_hdr(skb)->payload_len = htons(len); return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, skb_dst(skb)->dev, dst_output); } int ip6_local_out(struct sk_buff *skb) { int err; err = __ip6_local_out(skb); if (likely(err == 1)) err = dst_output(skb); return err; } EXPORT_SYMBOL_GPL(ip6_local_out); /* dev_loopback_xmit for use with netfilter. */ static int ip6_dev_loopback_xmit(struct sk_buff *newskb) { skb_reset_mac_header(newskb); __skb_pull(newskb, skb_network_offset(newskb)); newskb->pkt_type = PACKET_LOOPBACK; newskb->ip_summed = CHECKSUM_UNNECESSARY; WARN_ON(!skb_dst(newskb)); netif_rx_ni(newskb); return 0; } static int ip6_finish_output2(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) && ((mroute6_socket(dev_net(dev), skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, ip6_dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST, skb->len); } rcu_read_lock(); neigh = dst_get_neighbour_noref(dst); if (neigh) { int res = neigh_output(neigh, skb); rcu_read_unlock(); return res; } rcu_read_unlock(); IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } static int ip6_finish_output(struct sk_buff *skb) { if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) || dst_allfrag(skb_dst(skb))) return ip6_fragment(skb, ip6_finish_output2); else return ip6_finish_output2(skb); } int ip6_output(struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (unlikely(idev->cnf.disable_ipv6)) { IP6_INC_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, skb, NULL, dev, ip6_finish_output, !(IP6CB(skb)->flags & IP6SKB_REROUTED)); } /* * xmit an sk_buff (used by TCP, SCTP and DCCP) */ int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; if (opt) { unsigned int head_room; /* First: exthdrs may take lots of space (~8K for now) MAX_HEADER is not enough. */ head_room = opt->opt_nflen + opt->opt_flen; seg_len += head_room; head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (skb_headroom(skb) < head_room) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (skb2 == NULL) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } kfree_skb(skb); skb = skb2; skb_set_owner_w(skb, sk); } if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); *(__be32 *)hdr = htonl(0x60000000 | (tclass << 20)) | fl6->flowlabel; hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->local_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, dst->dev, dst_output); } if (net_ratelimit()) printk(KERN_DEBUG "IPv6: sending pkt_too_big to self\n"); skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } EXPORT_SYMBOL(ip6_xmit); /* * To avoid extra problems ND packets are send through this * routine. It's code duplication but I really want to avoid * extra checks since ipv6_build_header is used by TCP (which * is for us performance critical) */ int ip6_nd_hdr(struct sock *sk, struct sk_buff *skb, struct net_device *dev, const struct in6_addr *saddr, const struct in6_addr *daddr, int proto, int len) { struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6hdr *hdr; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; skb_reset_network_header(skb); skb_put(skb, sizeof(struct ipv6hdr)); hdr = ipv6_hdr(skb); *(__be32*)hdr = htonl(0x60000000); hdr->payload_len = htons(len); hdr->nexthdr = proto; hdr->hop_limit = np->hop_limit; hdr->saddr = *saddr; hdr->daddr = *daddr; return 0; } static int ip6_call_ra_chain(struct sk_buff *skb, int sel) { struct ip6_ra_chain *ra; struct sock *last = NULL; read_lock(&ip6_ra_lock); for (ra = ip6_ra_chain; ra; ra = ra->next) { struct sock *sk = ra->sk; if (sk && ra->sel == sel && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == skb->dev->ifindex)) { if (last) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) rawv6_rcv(last, skb2); } last = sk; } } if (last) { rawv6_rcv(last, skb); read_unlock(&ip6_ra_lock); return 1; } read_unlock(&ip6_ra_lock); return 0; } static int ip6_forward_proxy_check(struct sk_buff *skb) { struct ipv6hdr *hdr = ipv6_hdr(skb); u8 nexthdr = hdr->nexthdr; __be16 frag_off; int offset; if (ipv6_ext_hdr(nexthdr)) { offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off); if (offset < 0) return 0; } else offset = sizeof(struct ipv6hdr); if (nexthdr == IPPROTO_ICMPV6) { struct icmp6hdr *icmp6; if (!pskb_may_pull(skb, (skb_network_header(skb) + offset + 1 - skb->data))) return 0; icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset); switch (icmp6->icmp6_type) { case NDISC_ROUTER_SOLICITATION: case NDISC_ROUTER_ADVERTISEMENT: case NDISC_NEIGHBOUR_SOLICITATION: case NDISC_NEIGHBOUR_ADVERTISEMENT: case NDISC_REDIRECT: /* For reaction involving unicast neighbor discovery * message destined to the proxied address, pass it to * input function. */ return 1; default: break; } } /* * The proxying router can't forward traffic sent to a link-local * address, so signal the sender and discard the packet. This * behavior is clarified by the MIPv6 specification. */ if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) { dst_link_failure(skb); return -1; } return 0; } static inline int ip6_forward_finish(struct sk_buff *skb) { return dst_output(skb); } int ip6_forward(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr = ipv6_hdr(skb); struct inet6_skb_parm *opt = IP6CB(skb); struct net *net = dev_net(dst->dev); u32 mtu; if (net->ipv6.devconf_all->forwarding == 0) goto error; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) { IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } if (skb->pkt_type != PACKET_HOST) goto drop; skb_forward_csum(skb); /* * We DO NOT make any processing on * RA packets, pushing them to user level AS IS * without ane WARRANTY that application will be able * to interpret them. The reason is that we * cannot make anything clever here. * * We are not end-node, so that if packet contains * AH/ESP, we cannot make anything. * Defragmentation also would be mistake, RA packets * cannot be fragmented, because there is no warranty * that different fragments will go along one path. --ANK */ if (opt->ra) { u8 *ptr = skb_network_header(skb) + opt->ra; if (ip6_call_ra_chain(skb, (ptr[2]<<8) + ptr[3])) return 0; } /* * check and decrement ttl */ if (hdr->hop_limit <= 1) { /* Force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0); IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS); kfree_skb(skb); return -ETIMEDOUT; } /* XXX: idev->cnf.proxy_ndp? */ if ((net->ipv6.devconf_all->proxy_ndp == 1 && pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) || net->ipv6.devconf_all->proxy_ndp >= 2) { int proxied = ip6_forward_proxy_check(skb); if (proxied > 0) return ip6_input(skb); else if (proxied < 0) { IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } } if (!xfrm6_route_forward(skb)) { IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } dst = skb_dst(skb); /* IPv6 specs say nothing about it, but it is clear that we cannot send redirects to source routed frames. We don't send redirects to frames decapsulated from IPsec. */ if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) { struct in6_addr *target = NULL; struct rt6_info *rt; /* * incoming and outgoing devices are the same * send a redirect. */ rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) target = &rt->rt6i_gateway; else target = &hdr->daddr; if (!rt->rt6i_peer) rt6_bind_peer(rt, 1); /* Limit redirects both by destination (here) and by source (inside ndisc_send_redirect) */ if (inet_peer_xrlim_allow(rt->rt6i_peer, 1*HZ)) ndisc_send_redirect(skb, target); } else { int addrtype = ipv6_addr_type(&hdr->saddr); /* This check is security critical. */ if (addrtype == IPV6_ADDR_ANY || addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK)) goto error; if (addrtype & IPV6_ADDR_LINKLOCAL) { icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_NOT_NEIGHBOUR, 0); goto error; } } mtu = dst_mtu(dst); if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (skb->len > mtu && !skb_is_gso(skb)) { /* Again, force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS); IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (skb_cow(skb, dst->dev->hard_header_len)) { IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS); goto drop; } hdr = ipv6_hdr(skb); /* Mangling hops number delayed to point after skb COW */ hdr->hop_limit--; IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS); return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dst->dev, ip6_forward_finish); error: IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS); drop: kfree_skb(skb); return -EINVAL; } static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from) { to->pkt_type = from->pkt_type; to->priority = from->priority; to->protocol = from->protocol; skb_dst_drop(to); skb_dst_set(to, dst_clone(skb_dst(from))); to->dev = from->dev; to->mark = from->mark; #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); #if defined(CONFIG_NETFILTER_XT_TARGET_TRACE) || \ defined(CONFIG_NETFILTER_XT_TARGET_TRACE_MODULE) to->nf_trace = from->nf_trace; #endif skb_copy_secmark(to, from); } int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); struct ipv6_opt_hdr *exthdr = (struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1); unsigned int packet_len = skb->tail - skb->network_header; int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset + 1 <= packet_len) { switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default : return offset; } offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); } return offset; } void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt) { static u32 ip6_idents_hashrnd __read_mostly; static bool hashrnd_initialized = false; u32 hash, id; if (unlikely(!hashrnd_initialized)) { hashrnd_initialized = true; get_random_bytes(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); } hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd); hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash); id = ip_idents_reserve(hash, 1); fhdr->identification = htonl(id); } int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info*)skb_dst(skb); struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id = 0; int ptr, offset = 0, err=0; u8 *prevhdr, nexthdr = 0; struct net *net = dev_net(skb_dst(skb)->dev); hlen = ip6_find_1stfragopt(skb, &prevhdr); nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (!skb->local_df && skb->len > mtu) { skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } mtu -= hlen + sizeof(struct frag_hdr); if (skb_has_frag_list(skb)) { int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb)) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < hlen) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); return -ENOMEM; } __skb_pull(skb, hlen); fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); ipv6_select_ident(fh, rt); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); frag_id = fh->identification; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next != NULL) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(skb); if(!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); dst_release(&rt->dst); return 0; } while (frag) { skb = frag->next; kfree_skb(frag); frag = skb; } IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); dst_release(&rt->dst); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ *prevhdr = NEXTHDR_FRAGMENT; hroom = LL_RESERVED_SPACE(rt->dst.dev); troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while(left > 0) { len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* * Allocate buffer. */ if ((frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC)) == NULL) { NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n"); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; if (!frag_id) { ipv6_select_ident(fh, rt); frag_id = fh->identification; } else fh->identification = frag_id; /* * Copy a block of the IP datagram. */ if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len)) BUG(); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); kfree_skb(skb); return err; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } static inline int ip6_rt_check(const struct rt6key *rt_key, const struct in6_addr *fl_addr, const struct in6_addr *addr_cache) { return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) && (addr_cache == NULL || !ipv6_addr_equal(fl_addr, addr_cache)); } static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) { dst_release(dst); dst = NULL; } out: return dst; } static int ip6_dst_lookup_tail(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { struct net *net = sock_net(sk); #ifdef CONFIG_IPV6_OPTIMISTIC_DAD struct neighbour *n; #endif int err; if (*dst == NULL) *dst = ip6_route_output(net, sk, fl6); if ((err = (*dst)->error)) goto out_err_release; if (ipv6_addr_any(&fl6->saddr)) { struct rt6_info *rt = (struct rt6_info *) *dst; err = ip6_route_get_saddr(net, rt, &fl6->daddr, sk ? inet6_sk(sk)->srcprefs : 0, &fl6->saddr); if (err) goto out_err_release; } #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * Here if the dst entry we've looked up * has a neighbour entry that is in the INCOMPLETE * state and the src address from the flow is * marked as OPTIMISTIC, we release the found * dst entry and replace it instead with the * dst entry of the nexthop router */ rcu_read_lock(); n = dst_get_neighbour_noref(*dst); if (n && !(n->nud_state & NUD_VALID)) { struct inet6_ifaddr *ifp; struct flowi6 fl_gw6; int redirect; rcu_read_unlock(); ifp = ipv6_get_ifaddr(net, &fl6->saddr, (*dst)->dev, 1); redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC); if (ifp) in6_ifa_put(ifp); if (redirect) { /* * We need to get the dst entry for the * default router instead */ dst_release(*dst); memcpy(&fl_gw6, fl6, sizeof(struct flowi6)); memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr)); *dst = ip6_route_output(net, sk, &fl_gw6); if ((err = (*dst)->error)) goto out_err_release; } } else { rcu_read_unlock(); } #endif return 0; out_err_release: if (err == -ENETUNREACH) IP6_INC_STATS_BH(net, NULL, IPSTATS_MIB_OUTNOROUTES); dst_release(*dst); *dst = NULL; return err; } /** * ip6_dst_lookup - perform route lookup on flow * @sk: socket which provides route info * @dst: pointer to dst_entry * for result * @fl6: flow to lookup * * This function performs a route lookup on the given flow. * * It returns zero on success, or a standard errno code on error. */ int ip6_dst_lookup(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { *dst = NULL; return ip6_dst_lookup_tail(sk, dst, fl6); } EXPORT_SYMBOL_GPL(ip6_dst_lookup); /** * ip6_dst_lookup_flow - perform route lookup on flow with ipsec * @sk: socket which provides route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * @can_sleep: we are in a sleepable context * * This function performs a route lookup on the given flow. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst, bool can_sleep) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; if (can_sleep) fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP; return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); /** * ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * @can_sleep: we are in a sleepable context * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. * It will take the socket dst lock when operating on the dst cache. * As a result, this function can only be used in process context. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst, bool can_sleep) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); int err; dst = ip6_sk_dst_check(sk, dst, fl6); err = ip6_dst_lookup_tail(sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; if (can_sleep) fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP; return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow); static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { struct frag_hdr fhdr; skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); } return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, unsigned int orig_mtu) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (skb == NULL) { /* first fragment, reserve header_len */ *mtu = orig_mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = orig_mtu; } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, int dontfrag) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct inet_cork *cork; struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu; int exthdrlen; int dst_exthdrlen; int hh_len; int copy; int err; int offset = 0; int csummode = CHECKSUM_NONE; __u8 tx_flags = 0; if (flags&MSG_PROBE) return 0; cork = &inet->cork.base; if (skb_queue_empty(&sk->sk_write_queue)) { /* * setup for corking */ if (opt) { if (WARN_ON(np->cork.opt)) return -EINVAL; np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation); if (unlikely(np->cork.opt == NULL)) return -ENOBUFS; np->cork.opt->tot_len = opt->tot_len; np->cork.opt->opt_flen = opt->opt_flen; np->cork.opt->opt_nflen = opt->opt_nflen; np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation); if (opt->dst0opt && !np->cork.opt->dst0opt) return -ENOBUFS; np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation); if (opt->dst1opt && !np->cork.opt->dst1opt) return -ENOBUFS; np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation); if (opt->hopopt && !np->cork.opt->hopopt) return -ENOBUFS; np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation); if (opt->srcrt && !np->cork.opt->srcrt) return -ENOBUFS; /* need source address above miyazawa*/ } dst_hold(&rt->dst); cork->dst = &rt->dst; inet->cork.fl.u.ip6 = *fl6; np->cork.hop_limit = hlimit; np->cork.tclass = tclass; if (rt->dst.flags & DST_XFRM_TUNNEL) mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(&rt->dst); else mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ? rt->dst.dev->mtu : dst_mtu(rt->dst.path); if (np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } cork->fragsize = mtu; if (dst_allfrag(rt->dst.path)) cork->flags |= IPCORK_ALLFRAG; cork->length = 0; sk->sk_sndmsg_page = NULL; sk->sk_sndmsg_off = 0; exthdrlen = (opt ? opt->opt_flen : 0); length += exthdrlen; transhdrlen += exthdrlen; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } else { rt = (struct rt6_info *)cork->dst; fl6 = &inet->cork.fl.u.ip6; opt = np->cork.opt; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; mtu = cork->fragsize; } orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) { if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) { ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen); return -EMSGSIZE; } } /* For UDP, check if TX timestamp is enabled */ if (sk->sk_type == SOCK_DGRAM) { err = sock_tx_timestamp(sk, &tx_flags); if (err) goto error; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ if ((length > mtu) && dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen); return -EMSGSIZE; } skb = skb_peek_tail(&sk->sk_write_queue); cork->length += length; if (((length > mtu) || (skb && skb_has_frags(skb))) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO)) { err = ip6_ufo_append_data(sk, getfrag, from, length, hh_len, fragheaderlen, transhdrlen, mtu, flags, rt); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (skb == NULL || skb_prev == NULL) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; goto error; } if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(skb == NULL)) err = -ENOBUFS; else { /* Only the initial fragment * is time stamped. */ tx_flags = 0; } } if (skb == NULL) goto error; /* * Fill in the control structures */ skb->ip_summed = csummode; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); if (sk->sk_type == SOCK_DGRAM) skb_shinfo(skb)->tx_flags = tx_flags; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; csummode = CHECKSUM_NONE; /* * Put the packet on the pending queue */ __skb_queue_tail(&sk->sk_write_queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG)) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; skb_frag_t *frag = &skb_shinfo(skb)->frags[i-1]; struct page *page = sk->sk_sndmsg_page; int off = sk->sk_sndmsg_off; unsigned int left; if (page && (left = PAGE_SIZE - off) > 0) { if (copy >= left) copy = left; if (page != skb_frag_page(frag)) { if (i == MAX_SKB_FRAGS) { err = -EMSGSIZE; goto error; } skb_fill_page_desc(skb, i, page, sk->sk_sndmsg_off, 0); skb_frag_ref(skb, i); frag = &skb_shinfo(skb)->frags[i]; } } else if(i < MAX_SKB_FRAGS) { if (copy > PAGE_SIZE) copy = PAGE_SIZE; page = alloc_pages(sk->sk_allocation, 0); if (page == NULL) { err = -ENOMEM; goto error; } sk->sk_sndmsg_page = page; sk->sk_sndmsg_off = 0; skb_fill_page_desc(skb, i, page, 0, 0); frag = &skb_shinfo(skb)->frags[i]; } else { err = -EMSGSIZE; goto error; } if (getfrag(from, skb_frag_address(frag) + skb_frag_size(frag), offset, copy, skb->len, skb) < 0) { err = -EFAULT; goto error; } sk->sk_sndmsg_off += copy; skb_frag_size_add(frag, copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; } static void ip6_cork_release(struct inet_sock *inet, struct ipv6_pinfo *np) { if (np->cork.opt) { kfree(np->cork.opt->dst0opt); kfree(np->cork.opt->dst1opt); kfree(np->cork.opt->hopopt); kfree(np->cork.opt->srcrt); kfree(np->cork.opt); np->cork.opt = NULL; } if (inet->cork.base.dst) { dst_release(inet->cork.base.dst); inet->cork.base.dst = NULL; inet->cork.base.flags &= ~IPCORK_ALLFRAG; } memset(&inet->cork.fl, 0, sizeof(inet->cork.fl)); } int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = np->cork.opt; struct rt6_info *rt = (struct rt6_info *)inet->cork.base.dst; struct flowi6 *fl6 = &inet->cork.fl.u.ip6; unsigned char proto = fl6->flowi6_proto; int err = 0; if ((skb = __skb_dequeue(&sk->sk_write_queue)) == NULL) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ if (np->pmtudisc < IPV6_PMTUDISC_DO) skb->local_df = 1; *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); *(__be32*)hdr = fl6->flowlabel | htonl(0x60000000 | ((int)np->cork.tclass << 20)); hdr->hop_limit = np->cork.hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } err = ip6_local_out(skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) goto error; } out: ip6_cork_release(inet, np); return err; error: IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); goto out; } void ip6_flush_pending_frames(struct sock *sk) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) { if (skb_dst(skb)) IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); } ip6_cork_release(inet_sk(sk), inet6_sk(sk)); }
DirtyUnicorns/android_kernel_lge_msm8974
net/ipv6/ip6_output.c
C
gpl-2.0
42,864
/*****************************************************************************/ /* */ /* Copyright (c) 1989-2008 Morgan Stanley All rights reserved.*/ /* See .../src/LICENSE for terms of distribution. */ /* */ /* */ /*****************************************************************************/ /* contributed by Daniel F. Fisher */ /* * The conn functions will allow for maintenance of a TCP connection with a * given port, across failures of the connection. The address of the other * end of the connection is specified as an opaque object and an * interpretation function. The interpretation function is used translate * the opaque object into an address for use in a connection request. * Several interpetation functions are provided and others may be supplied * for a specific purpose by a user module. The parameters and control * structures for the are initally established using the connalloc() * function. This allocates and initalizes a control block for the * connection. The inputs to connalloc() include certain parameters used in * establishment and maintenance of a connection. The connopen() function is * used to initiate connection connection establishment. connopen will * intepret the remote address information and the establish a connection. * If connection establishment fails, then connopen will reschedule it for * sometime in the future. If it succeeds, then connopen will call theuser * provided state change notification function, to indicate that the * connection is now active. If connection establishment is initiated but is * not yet complete, connopen sets up a write channel that will notify the * user when the connection is established. Once the connection is * established and the user is notified, it is up to the user to set up the * appropriate channels for reading and writing information on the * connection. The user may elect to use other dap provided functions which * will read and write as necessary. The connection may be closed at any time * by calling connclose(). Connclose will reschedule a connopen() call at * sometime in the future, unless the connection's retry flag is off. Thus, * exceptions while reading or writing on the connection maybne handled by * closing the connection, which automatically schedule reestablishment of * the connection. The user is responsible for ensuring that data transfer * buffers are kept in a consistent state between instances of the * connection. When the connection has outlived its usefulness, it is * removed using connfree(). This will free all resources allocated to the * connection, including closing the file descriptor, clearing the retry * timer, etc. */ /* header file inclusions */ #include <sys/types.h> #include <sys/uio.h> #include <dap/notsunos4.h> #ifdef PRESUNOS4 #ifndef _SOCKET_ #define _SOCKET_ #include <sys/socket.h> #endif #else #include <sys/socket.h> #endif #include <dap/balloc.h> #include <dap/tod.h> #include <dap/chan.h> #include <dap/timer.h> #include <dap/exbo.h> #include <dap/conn.h> /* external function definitions */ struct conn *connalloc(char *name, int pri, int retry, int retry_time_first, int retry_time_last, int domain, int type, int protocol, void *r_nameinfo, int (*setupfunc) (), struct sockaddr * (*r_namefunc) (), int (*estbfunc) (), void *acb) { struct conn *p = (struct conn *) balloc(sizeof(*p)); if (name == (char *) (0)) name = "<UNKNOWN>"; p->name = bstring(name); p->pri = pri; if (retry == CONN_RETRY_NO) p->retry = CONN_RETRY_NO; else p->retry = CONN_RETRY_YES; p->domain = domain; p->type = type; p->protocol = protocol; p->r_nameinfo = r_nameinfo; p->setupfunc = setupfunc; p->r_namefunc = r_namefunc; p->estbfunc = estbfunc; p->acb = acb; p->retry_time = exboalloc(retry_time_first, retry_time_last); p->retry_tp = (struct timer *) (0); p->fd = -1; p->r_namelen = 0; p->r_name = (struct sockaddr *) (0); p->estbchan = (struct chan *) (0); p->estbd = 0; p->alloctod = todsec(); p->opentod = (time_t) (0); p->conntod = (time_t) (0); p->estbtod = (time_t) (0); p->disctod = (time_t) (0); p->closetod = (time_t) (0); p->opendtime = (time_t) (0); p->estbdtime = (time_t) (0); p->opencount = (unsigned) (0); p->conncount = (unsigned) (0); p->estbcount = (unsigned) (0); p->disccount = (unsigned) (0); p->closecount = (unsigned) (0); return p; }
rdm/aplus-fsf
src/dap/connalloc.c
C
gpl-2.0
4,678
module Ohcount module Gestalt # Triggers if a matching C# 'using' library include statement is present class CSharpUsingRule < FileRule def initialize(*args) @regex = args.shift super(args) end def process_source_file(source_file) return false unless source_file.language_breakdown('csharp') source_file.language_breakdown('csharp').code.scan(using_regexp).each do |match| @count += 1 if match[0] =~ @regex end end def using_regexp @@using_regexp ||= /^\s*using\s+([a-zA-Z][\w\.\*\-]*)\s*;/ end end end end
codeimpossible/ohcount
ruby/gestalt/rules/csharp_using_rule.rb
Ruby
gpl-2.0
580
;; Expander definitions for vector support between altivec & vsx. No ;; instructions are in this file, this file provides the generic vector ;; expander, and the actual vector instructions will be in altivec.md and ;; vsx.md ;; Copyright (C) 2009-2015 Free Software Foundation, Inc. ;; Contributed by Michael Meissner <[email protected]> ;; This file is part of GCC. ;; GCC is free software; you can redistribute it and/or modify it ;; under the terms of the GNU General Public License as published ;; by the Free Software Foundation; either version 3, or (at your ;; option) any later version. ;; GCC is distributed in the hope that it will be useful, but WITHOUT ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public ;; License for more details. ;; You should have received a copy of the GNU General Public License ;; along with GCC; see the file COPYING3. If not see ;; <http://www.gnu.org/licenses/>. ;; Vector int modes (define_mode_iterator VEC_I [V16QI V8HI V4SI V2DI]) ;; Vector float modes (define_mode_iterator VEC_F [V4SF V2DF]) ;; Vector arithmetic modes (define_mode_iterator VEC_A [V16QI V8HI V4SI V2DI V4SF V2DF]) ;; Vector modes that need alginment via permutes (define_mode_iterator VEC_K [V16QI V8HI V4SI V4SF]) ;; Vector logical modes (define_mode_iterator VEC_L [V16QI V8HI V4SI V2DI V4SF V2DF V1TI TI KF TF]) ;; Vector modes for moves. Don't do TImode or TFmode here, since their ;; moves are handled elsewhere. (define_mode_iterator VEC_M [V16QI V8HI V4SI V2DI V4SF V2DF V1TI KF]) ;; Vector modes for types that don't need a realignment under VSX (define_mode_iterator VEC_N [V4SI V4SF V2DI V2DF V1TI KF TF]) ;; Vector comparison modes (define_mode_iterator VEC_C [V16QI V8HI V4SI V2DI V4SF V2DF]) ;; Vector init/extract modes (define_mode_iterator VEC_E [V16QI V8HI V4SI V2DI V4SF V2DF]) ;; Vector modes for 64-bit base types (define_mode_iterator VEC_64 [V2DI V2DF]) ;; Base type from vector mode (define_mode_attr VEC_base [(V16QI "QI") (V8HI "HI") (V4SI "SI") (V2DI "DI") (V4SF "SF") (V2DF "DF") (V1TI "TI") (TI "TI")]) ;; Same size integer type for floating point data (define_mode_attr VEC_int [(V4SF "v4si") (V2DF "v2di")]) (define_mode_attr VEC_INT [(V4SF "V4SI") (V2DF "V2DI")]) ;; constants for unspec (define_c_enum "unspec" [UNSPEC_PREDICATE UNSPEC_REDUC]) ;; Vector reduction code iterators (define_code_iterator VEC_reduc [plus smin smax]) (define_code_attr VEC_reduc_name [(plus "splus") (smin "smin") (smax "smax")]) (define_code_attr VEC_reduc_rtx [(plus "add") (smin "smin") (smax "smax")]) ;; Vector move instructions. Little-endian VSX loads and stores require ;; special handling to circumvent "element endianness." (define_expand "mov<mode>" [(set (match_operand:VEC_M 0 "nonimmediate_operand" "") (match_operand:VEC_M 1 "any_operand" ""))] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" { if (can_create_pseudo_p ()) { if (CONSTANT_P (operands[1])) { if (FLOAT128_VECTOR_P (<MODE>mode)) { if (!easy_fp_constant (operands[1], <MODE>mode)) operands[1] = force_const_mem (<MODE>mode, operands[1]); } else if (!easy_vector_constant (operands[1], <MODE>mode)) operands[1] = force_const_mem (<MODE>mode, operands[1]); } if (!vlogical_operand (operands[0], <MODE>mode) && !vlogical_operand (operands[1], <MODE>mode)) operands[1] = force_reg (<MODE>mode, operands[1]); } if (!BYTES_BIG_ENDIAN && VECTOR_MEM_VSX_P (<MODE>mode) && !gpr_or_gpr_p (operands[0], operands[1]) && (memory_operand (operands[0], <MODE>mode) ^ memory_operand (operands[1], <MODE>mode))) { rs6000_emit_le_vsx_move (operands[0], operands[1], <MODE>mode); DONE; } }) ;; Generic vector floating point load/store instructions. These will match ;; insns defined in vsx.md or altivec.md depending on the switches. (define_expand "vector_load_<mode>" [(set (match_operand:VEC_M 0 "vfloat_operand" "") (match_operand:VEC_M 1 "memory_operand" ""))] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_store_<mode>" [(set (match_operand:VEC_M 0 "memory_operand" "") (match_operand:VEC_M 1 "vfloat_operand" ""))] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ;; Splits if a GPR register was chosen for the move (define_split [(set (match_operand:VEC_L 0 "nonimmediate_operand" "") (match_operand:VEC_L 1 "input_operand" ""))] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode) && reload_completed && gpr_or_gpr_p (operands[0], operands[1]) && !direct_move_p (operands[0], operands[1]) && !quad_load_store_p (operands[0], operands[1])" [(pc)] { rs6000_split_multireg_move (operands[0], operands[1]); DONE; }) ;; Vector floating point load/store instructions that uses the Altivec ;; instructions even if we are compiling for VSX, since the Altivec ;; instructions silently ignore the bottom 3 bits of the address, and VSX does ;; not. (define_expand "vector_altivec_load_<mode>" [(set (match_operand:VEC_M 0 "vfloat_operand" "") (match_operand:VEC_M 1 "memory_operand" ""))] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" " { gcc_assert (VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)); if (VECTOR_MEM_VSX_P (<MODE>mode)) { operands[1] = rs6000_address_for_altivec (operands[1]); emit_insn (gen_altivec_lvx_<mode> (operands[0], operands[1])); DONE; } }") (define_expand "vector_altivec_store_<mode>" [(set (match_operand:VEC_M 0 "memory_operand" "") (match_operand:VEC_M 1 "vfloat_operand" ""))] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" " { gcc_assert (VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)); if (VECTOR_MEM_VSX_P (<MODE>mode)) { operands[0] = rs6000_address_for_altivec (operands[0]); emit_insn (gen_altivec_stvx_<mode> (operands[0], operands[1])); DONE; } }") ;; Generic floating point vector arithmetic support (define_expand "add<mode>3" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (plus:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "sub<mode>3" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (minus:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "mul<mode>3" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (mult:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_mulv4sf3 (operands[0], operands[1], operands[2])); DONE; } }) (define_expand "div<mode>3" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (div:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_VSX_P (<MODE>mode)" "") (define_expand "neg<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (neg:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_negv4sf2 (operands[0], operands[1])); DONE; } }") (define_expand "abs<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (abs:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_absv4sf2 (operands[0], operands[1])); DONE; } }") (define_expand "smin<mode>3" [(set (match_operand:VEC_F 0 "register_operand" "") (smin:VEC_F (match_operand:VEC_F 1 "register_operand" "") (match_operand:VEC_F 2 "register_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "smax<mode>3" [(set (match_operand:VEC_F 0 "register_operand" "") (smax:VEC_F (match_operand:VEC_F 1 "register_operand" "") (match_operand:VEC_F 2 "register_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "sqrt<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (sqrt:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_VSX_P (<MODE>mode)" "") (define_expand "rsqrte<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unspec:VEC_F [(match_operand:VEC_F 1 "vfloat_operand" "")] UNSPEC_RSQRT))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "re<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unspec:VEC_F [(match_operand:VEC_F 1 "vfloat_operand" "f")] UNSPEC_FRES))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "ftrunc<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (fix:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_ceil<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unspec:VEC_F [(match_operand:VEC_F 1 "vfloat_operand" "")] UNSPEC_FRIP))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_floor<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unspec:VEC_F [(match_operand:VEC_F 1 "vfloat_operand" "")] UNSPEC_FRIM))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_btrunc<mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (fix:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_copysign<mode>3" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unspec:VEC_F [(match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")] UNSPEC_COPYSIGN))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_copysign_v4sf3 (operands[0], operands[1], operands[2])); DONE; } }") ;; Vector comparisons (define_expand "vcond<mode><mode>" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (if_then_else:VEC_F (match_operator 3 "comparison_operator" [(match_operand:VEC_F 4 "vfloat_operand" "") (match_operand:VEC_F 5 "vfloat_operand" "")]) (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (rs6000_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; }") (define_expand "vcond<mode><mode>" [(set (match_operand:VEC_I 0 "vint_operand" "") (if_then_else:VEC_I (match_operator 3 "comparison_operator" [(match_operand:VEC_I 4 "vint_operand" "") (match_operand:VEC_I 5 "vint_operand" "")]) (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (rs6000_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; }") (define_expand "vcondv4sfv4si" [(set (match_operand:V4SF 0 "vfloat_operand" "") (if_then_else:V4SF (match_operator 3 "comparison_operator" [(match_operand:V4SI 4 "vint_operand" "") (match_operand:V4SI 5 "vint_operand" "")]) (match_operand:V4SF 1 "vfloat_operand" "") (match_operand:V4SF 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode) && VECTOR_UNIT_ALTIVEC_P (V4SImode)" " { if (rs6000_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; }") (define_expand "vcondv4siv4sf" [(set (match_operand:V4SI 0 "vint_operand" "") (if_then_else:V4SI (match_operator 3 "comparison_operator" [(match_operand:V4SF 4 "vfloat_operand" "") (match_operand:V4SF 5 "vfloat_operand" "")]) (match_operand:V4SI 1 "vint_operand" "") (match_operand:V4SI 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode) && VECTOR_UNIT_ALTIVEC_P (V4SImode)" " { if (rs6000_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; }") (define_expand "vcondu<mode><mode>" [(set (match_operand:VEC_I 0 "vint_operand" "") (if_then_else:VEC_I (match_operator 3 "comparison_operator" [(match_operand:VEC_I 4 "vint_operand" "") (match_operand:VEC_I 5 "vint_operand" "")]) (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (rs6000_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; }") (define_expand "vconduv4sfv4si" [(set (match_operand:V4SF 0 "vfloat_operand" "") (if_then_else:V4SF (match_operator 3 "comparison_operator" [(match_operand:V4SI 4 "vint_operand" "") (match_operand:V4SI 5 "vint_operand" "")]) (match_operand:V4SF 1 "vfloat_operand" "") (match_operand:V4SF 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode) && VECTOR_UNIT_ALTIVEC_P (V4SImode)" " { if (rs6000_emit_vector_cond_expr (operands[0], operands[1], operands[2], operands[3], operands[4], operands[5])) DONE; else FAIL; }") (define_expand "vector_eq<mode>" [(set (match_operand:VEC_C 0 "vlogical_operand" "") (eq:VEC_C (match_operand:VEC_C 1 "vlogical_operand" "") (match_operand:VEC_C 2 "vlogical_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_gt<mode>" [(set (match_operand:VEC_C 0 "vlogical_operand" "") (gt:VEC_C (match_operand:VEC_C 1 "vlogical_operand" "") (match_operand:VEC_C 2 "vlogical_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_ge<mode>" [(set (match_operand:VEC_F 0 "vlogical_operand" "") (ge:VEC_F (match_operand:VEC_F 1 "vlogical_operand" "") (match_operand:VEC_F 2 "vlogical_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ; >= for integer vectors: swap operands and apply not-greater-than (define_expand "vector_nlt<mode>" [(set (match_operand:VEC_I 3 "vlogical_operand" "") (gt:VEC_I (match_operand:VEC_I 2 "vlogical_operand" "") (match_operand:VEC_I 1 "vlogical_operand" ""))) (set (match_operand:VEC_I 0 "vlogical_operand" "") (not:VEC_I (match_dup 3)))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { operands[3] = gen_reg_rtx_and_attrs (operands[0]); }") (define_expand "vector_gtu<mode>" [(set (match_operand:VEC_I 0 "vint_operand" "") (gtu:VEC_I (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ; >= for integer vectors: swap operands and apply not-greater-than (define_expand "vector_nltu<mode>" [(set (match_operand:VEC_I 3 "vlogical_operand" "") (gtu:VEC_I (match_operand:VEC_I 2 "vlogical_operand" "") (match_operand:VEC_I 1 "vlogical_operand" ""))) (set (match_operand:VEC_I 0 "vlogical_operand" "") (not:VEC_I (match_dup 3)))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { operands[3] = gen_reg_rtx_and_attrs (operands[0]); }") (define_expand "vector_geu<mode>" [(set (match_operand:VEC_I 0 "vint_operand" "") (geu:VEC_I (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ; <= for integer vectors: apply not-greater-than (define_expand "vector_ngt<mode>" [(set (match_operand:VEC_I 3 "vlogical_operand" "") (gt:VEC_I (match_operand:VEC_I 1 "vlogical_operand" "") (match_operand:VEC_I 2 "vlogical_operand" ""))) (set (match_operand:VEC_I 0 "vlogical_operand" "") (not:VEC_I (match_dup 3)))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { operands[3] = gen_reg_rtx_and_attrs (operands[0]); }") (define_expand "vector_ngtu<mode>" [(set (match_operand:VEC_I 3 "vlogical_operand" "") (gtu:VEC_I (match_operand:VEC_I 1 "vlogical_operand" "") (match_operand:VEC_I 2 "vlogical_operand" ""))) (set (match_operand:VEC_I 0 "vlogical_operand" "") (not:VEC_I (match_dup 3)))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { operands[3] = gen_reg_rtx_and_attrs (operands[0]); }") (define_insn_and_split "*vector_uneq<mode>" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (uneq:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "#" "" [(set (match_dup 3) (gt:VEC_F (match_dup 1) (match_dup 2))) (set (match_dup 4) (gt:VEC_F (match_dup 2) (match_dup 1))) (set (match_dup 0) (not:VEC_F (ior:VEC_F (match_dup 3) (match_dup 4))))] " { operands[3] = gen_reg_rtx (<MODE>mode); operands[4] = gen_reg_rtx (<MODE>mode); }") (define_insn_and_split "*vector_ltgt<mode>" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (ltgt:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "#" "" [(set (match_dup 3) (gt:VEC_F (match_dup 1) (match_dup 2))) (set (match_dup 4) (gt:VEC_F (match_dup 2) (match_dup 1))) (set (match_dup 0) (ior:VEC_F (match_dup 3) (match_dup 4)))] " { operands[3] = gen_reg_rtx (<MODE>mode); operands[4] = gen_reg_rtx (<MODE>mode); }") (define_insn_and_split "*vector_ordered<mode>" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (ordered:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "#" "" [(set (match_dup 3) (ge:VEC_F (match_dup 1) (match_dup 2))) (set (match_dup 4) (ge:VEC_F (match_dup 2) (match_dup 1))) (set (match_dup 0) (ior:VEC_F (match_dup 3) (match_dup 4)))] " { operands[3] = gen_reg_rtx (<MODE>mode); operands[4] = gen_reg_rtx (<MODE>mode); }") (define_insn_and_split "*vector_unordered<mode>" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unordered:VEC_F (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "#" "" [(set (match_dup 3) (ge:VEC_F (match_dup 1) (match_dup 2))) (set (match_dup 4) (ge:VEC_F (match_dup 2) (match_dup 1))) (set (match_dup 0) (and:VEC_F (not:VEC_F (match_dup 3)) (not:VEC_F (match_dup 4))))] " { operands[3] = gen_reg_rtx (<MODE>mode); operands[4] = gen_reg_rtx (<MODE>mode); }") ;; Note the arguments for __builtin_altivec_vsel are op2, op1, mask ;; which is in the reverse order that we want (define_expand "vector_select_<mode>" [(set (match_operand:VEC_L 0 "vlogical_operand" "") (if_then_else:VEC_L (ne:CC (match_operand:VEC_L 3 "vlogical_operand" "") (match_dup 4)) (match_operand:VEC_L 2 "vlogical_operand" "") (match_operand:VEC_L 1 "vlogical_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "operands[4] = CONST0_RTX (<MODE>mode);") (define_expand "vector_select_<mode>_uns" [(set (match_operand:VEC_L 0 "vlogical_operand" "") (if_then_else:VEC_L (ne:CCUNS (match_operand:VEC_L 3 "vlogical_operand" "") (match_dup 4)) (match_operand:VEC_L 2 "vlogical_operand" "") (match_operand:VEC_L 1 "vlogical_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "operands[4] = CONST0_RTX (<MODE>mode);") ;; Expansions that compare vectors producing a vector result and a predicate, ;; setting CR6 to indicate a combined status (define_expand "vector_eq_<mode>_p" [(parallel [(set (reg:CC 74) (unspec:CC [(eq:CC (match_operand:VEC_A 1 "vlogical_operand" "") (match_operand:VEC_A 2 "vlogical_operand" ""))] UNSPEC_PREDICATE)) (set (match_operand:VEC_A 0 "vlogical_operand" "") (eq:VEC_A (match_dup 1) (match_dup 2)))])] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_gt_<mode>_p" [(parallel [(set (reg:CC 74) (unspec:CC [(gt:CC (match_operand:VEC_A 1 "vlogical_operand" "") (match_operand:VEC_A 2 "vlogical_operand" ""))] UNSPEC_PREDICATE)) (set (match_operand:VEC_A 0 "vlogical_operand" "") (gt:VEC_A (match_dup 1) (match_dup 2)))])] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_ge_<mode>_p" [(parallel [(set (reg:CC 74) (unspec:CC [(ge:CC (match_operand:VEC_F 1 "vfloat_operand" "") (match_operand:VEC_F 2 "vfloat_operand" ""))] UNSPEC_PREDICATE)) (set (match_operand:VEC_F 0 "vfloat_operand" "") (ge:VEC_F (match_dup 1) (match_dup 2)))])] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") (define_expand "vector_gtu_<mode>_p" [(parallel [(set (reg:CC 74) (unspec:CC [(gtu:CC (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" ""))] UNSPEC_PREDICATE)) (set (match_operand:VEC_I 0 "vlogical_operand" "") (gtu:VEC_I (match_dup 1) (match_dup 2)))])] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ;; AltiVec/VSX predicates. (define_expand "cr6_test_for_zero" [(set (match_operand:SI 0 "register_operand" "=r") (eq:SI (reg:CC 74) (const_int 0)))] "TARGET_ALTIVEC || TARGET_VSX" "") (define_expand "cr6_test_for_zero_reverse" [(set (match_operand:SI 0 "register_operand" "=r") (eq:SI (reg:CC 74) (const_int 0))) (set (match_dup 0) (xor:SI (match_dup 0) (const_int 1)))] "TARGET_ALTIVEC || TARGET_VSX" "") (define_expand "cr6_test_for_lt" [(set (match_operand:SI 0 "register_operand" "=r") (lt:SI (reg:CC 74) (const_int 0)))] "TARGET_ALTIVEC || TARGET_VSX" "") (define_expand "cr6_test_for_lt_reverse" [(set (match_operand:SI 0 "register_operand" "=r") (lt:SI (reg:CC 74) (const_int 0))) (set (match_dup 0) (xor:SI (match_dup 0) (const_int 1)))] "TARGET_ALTIVEC || TARGET_VSX" "") ;; Vector count leading zeros (define_expand "clz<mode>2" [(set (match_operand:VEC_I 0 "register_operand" "") (clz:VEC_I (match_operand:VEC_I 1 "register_operand" "")))] "TARGET_P8_VECTOR") ;; Vector population count (define_expand "popcount<mode>2" [(set (match_operand:VEC_I 0 "register_operand" "") (popcount:VEC_I (match_operand:VEC_I 1 "register_operand" "")))] "TARGET_P8_VECTOR") ;; Same size conversions (define_expand "float<VEC_int><mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (float:VEC_F (match_operand:<VEC_INT> 1 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_vcfsx (operands[0], operands[1], const0_rtx)); DONE; } }") (define_expand "floatuns<VEC_int><mode>2" [(set (match_operand:VEC_F 0 "vfloat_operand" "") (unsigned_float:VEC_F (match_operand:<VEC_INT> 1 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_vcfux (operands[0], operands[1], const0_rtx)); DONE; } }") (define_expand "fix_trunc<mode><VEC_int>2" [(set (match_operand:<VEC_INT> 0 "vint_operand" "") (fix:<VEC_INT> (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_vctsxs (operands[0], operands[1], const0_rtx)); DONE; } }") (define_expand "fixuns_trunc<mode><VEC_int>2" [(set (match_operand:<VEC_INT> 0 "vint_operand" "") (unsigned_fix:<VEC_INT> (match_operand:VEC_F 1 "vfloat_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" " { if (<MODE>mode == V4SFmode && VECTOR_UNIT_ALTIVEC_P (<MODE>mode)) { emit_insn (gen_altivec_vctuxs (operands[0], operands[1], const0_rtx)); DONE; } }") ;; Vector initialization, set, extract (define_expand "vec_init<mode>" [(match_operand:VEC_E 0 "vlogical_operand" "") (match_operand:VEC_E 1 "" "")] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" { rs6000_expand_vector_init (operands[0], operands[1]); DONE; }) (define_expand "vec_set<mode>" [(match_operand:VEC_E 0 "vlogical_operand" "") (match_operand:<VEC_base> 1 "register_operand" "") (match_operand 2 "const_int_operand" "")] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" { rs6000_expand_vector_set (operands[0], operands[1], INTVAL (operands[2])); DONE; }) (define_expand "vec_extract<mode>" [(match_operand:<VEC_base> 0 "register_operand" "") (match_operand:VEC_E 1 "vlogical_operand" "") (match_operand 2 "const_int_operand" "")] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" { rs6000_expand_vector_extract (operands[0], operands[1], INTVAL (operands[2])); DONE; }) ;; Convert double word types to single word types (define_expand "vec_pack_trunc_v2df" [(match_operand:V4SF 0 "vfloat_operand" "") (match_operand:V2DF 1 "vfloat_operand" "") (match_operand:V2DF 2 "vfloat_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && TARGET_ALTIVEC" { rtx r1 = gen_reg_rtx (V4SFmode); rtx r2 = gen_reg_rtx (V4SFmode); emit_insn (gen_vsx_xvcvdpsp (r1, operands[1])); emit_insn (gen_vsx_xvcvdpsp (r2, operands[2])); rs6000_expand_extract_even (operands[0], r1, r2); DONE; }) (define_expand "vec_pack_sfix_trunc_v2df" [(match_operand:V4SI 0 "vint_operand" "") (match_operand:V2DF 1 "vfloat_operand" "") (match_operand:V2DF 2 "vfloat_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && TARGET_ALTIVEC" { rtx r1 = gen_reg_rtx (V4SImode); rtx r2 = gen_reg_rtx (V4SImode); emit_insn (gen_vsx_xvcvdpsxws (r1, operands[1])); emit_insn (gen_vsx_xvcvdpsxws (r2, operands[2])); rs6000_expand_extract_even (operands[0], r1, r2); DONE; }) (define_expand "vec_pack_ufix_trunc_v2df" [(match_operand:V4SI 0 "vint_operand" "") (match_operand:V2DF 1 "vfloat_operand" "") (match_operand:V2DF 2 "vfloat_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && TARGET_ALTIVEC" { rtx r1 = gen_reg_rtx (V4SImode); rtx r2 = gen_reg_rtx (V4SImode); emit_insn (gen_vsx_xvcvdpuxws (r1, operands[1])); emit_insn (gen_vsx_xvcvdpuxws (r2, operands[2])); rs6000_expand_extract_even (operands[0], r1, r2); DONE; }) ;; Convert single word types to double word (define_expand "vec_unpacks_hi_v4sf" [(match_operand:V2DF 0 "vfloat_operand" "") (match_operand:V4SF 1 "vfloat_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode)" { rtx reg = gen_reg_rtx (V4SFmode); rs6000_expand_interleave (reg, operands[1], operands[1], BYTES_BIG_ENDIAN); emit_insn (gen_vsx_xvcvspdp (operands[0], reg)); DONE; }) (define_expand "vec_unpacks_lo_v4sf" [(match_operand:V2DF 0 "vfloat_operand" "") (match_operand:V4SF 1 "vfloat_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SFmode)" { rtx reg = gen_reg_rtx (V4SFmode); rs6000_expand_interleave (reg, operands[1], operands[1], !BYTES_BIG_ENDIAN); emit_insn (gen_vsx_xvcvspdp (operands[0], reg)); DONE; }) (define_expand "vec_unpacks_float_hi_v4si" [(match_operand:V2DF 0 "vfloat_operand" "") (match_operand:V4SI 1 "vint_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SImode)" { rtx reg = gen_reg_rtx (V4SImode); rs6000_expand_interleave (reg, operands[1], operands[1], BYTES_BIG_ENDIAN); emit_insn (gen_vsx_xvcvsxwdp (operands[0], reg)); DONE; }) (define_expand "vec_unpacks_float_lo_v4si" [(match_operand:V2DF 0 "vfloat_operand" "") (match_operand:V4SI 1 "vint_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SImode)" { rtx reg = gen_reg_rtx (V4SImode); rs6000_expand_interleave (reg, operands[1], operands[1], !BYTES_BIG_ENDIAN); emit_insn (gen_vsx_xvcvsxwdp (operands[0], reg)); DONE; }) (define_expand "vec_unpacku_float_hi_v4si" [(match_operand:V2DF 0 "vfloat_operand" "") (match_operand:V4SI 1 "vint_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SImode)" { rtx reg = gen_reg_rtx (V4SImode); rs6000_expand_interleave (reg, operands[1], operands[1], BYTES_BIG_ENDIAN); emit_insn (gen_vsx_xvcvuxwdp (operands[0], reg)); DONE; }) (define_expand "vec_unpacku_float_lo_v4si" [(match_operand:V2DF 0 "vfloat_operand" "") (match_operand:V4SI 1 "vint_operand" "")] "VECTOR_UNIT_VSX_P (V2DFmode) && VECTOR_UNIT_ALTIVEC_OR_VSX_P (V4SImode)" { rtx reg = gen_reg_rtx (V4SImode); rs6000_expand_interleave (reg, operands[1], operands[1], !BYTES_BIG_ENDIAN); emit_insn (gen_vsx_xvcvuxwdp (operands[0], reg)); DONE; }) ;; Align vector loads with a permute. (define_expand "vec_realign_load_<mode>" [(match_operand:VEC_K 0 "vlogical_operand" "") (match_operand:VEC_K 1 "vlogical_operand" "") (match_operand:VEC_K 2 "vlogical_operand" "") (match_operand:V16QI 3 "vlogical_operand" "")] "VECTOR_MEM_ALTIVEC_OR_VSX_P (<MODE>mode)" { if (BYTES_BIG_ENDIAN) emit_insn (gen_altivec_vperm_<mode> (operands[0], operands[1], operands[2], operands[3])); else { /* We have changed lvsr to lvsl, so to complete the transformation of vperm for LE, we must swap the inputs. */ rtx unspec = gen_rtx_UNSPEC (<MODE>mode, gen_rtvec (3, operands[2], operands[1], operands[3]), UNSPEC_VPERM); emit_move_insn (operands[0], unspec); } DONE; }) ;; Under VSX, vectors of 4/8 byte alignments do not need to be aligned ;; since the load already handles it. (define_expand "movmisalign<mode>" [(set (match_operand:VEC_N 0 "nonimmediate_operand" "") (match_operand:VEC_N 1 "any_operand" ""))] "VECTOR_MEM_VSX_P (<MODE>mode) && TARGET_ALLOW_MOVMISALIGN" "") ;; Vector shift right in bits. Currently supported ony for shift ;; amounts that can be expressed as byte shifts (divisible by 8). ;; General shift amounts can be supported using vsro + vsr. We're ;; not expecting to see these yet (the vectorizer currently ;; generates only shifts by a whole number of vector elements). ;; Note that the vec_shr operation is actually defined as ;; 'shift toward element 0' so is a shr for LE and shl for BE. (define_expand "vec_shr_<mode>" [(match_operand:VEC_L 0 "vlogical_operand" "") (match_operand:VEC_L 1 "vlogical_operand" "") (match_operand:QI 2 "reg_or_short_operand" "")] "TARGET_ALTIVEC" " { rtx bitshift = operands[2]; rtx shift; rtx insn; rtx zero_reg, op1, op2; HOST_WIDE_INT bitshift_val; HOST_WIDE_INT byteshift_val; if (! CONSTANT_P (bitshift)) FAIL; bitshift_val = INTVAL (bitshift); if (bitshift_val & 0x7) FAIL; byteshift_val = (bitshift_val >> 3); zero_reg = gen_reg_rtx (<MODE>mode); emit_move_insn (zero_reg, CONST0_RTX (<MODE>mode)); if (!BYTES_BIG_ENDIAN) { byteshift_val = 16 - byteshift_val; op1 = zero_reg; op2 = operands[1]; } else { op1 = operands[1]; op2 = zero_reg; } if (TARGET_VSX && (byteshift_val & 0x3) == 0) { shift = gen_rtx_CONST_INT (QImode, byteshift_val >> 2); insn = gen_vsx_xxsldwi_<mode> (operands[0], op1, op2, shift); } else { shift = gen_rtx_CONST_INT (QImode, byteshift_val); insn = gen_altivec_vsldoi_<mode> (operands[0], op1, op2, shift); } emit_insn (insn); DONE; }") ;; Expanders for rotate each element in a vector (define_expand "vrotl<mode>3" [(set (match_operand:VEC_I 0 "vint_operand" "") (rotate:VEC_I (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ;; Expanders for arithmetic shift left on each vector element (define_expand "vashl<mode>3" [(set (match_operand:VEC_I 0 "vint_operand" "") (ashift:VEC_I (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ;; Expanders for logical shift right on each vector element (define_expand "vlshr<mode>3" [(set (match_operand:VEC_I 0 "vint_operand" "") (lshiftrt:VEC_I (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ;; Expanders for arithmetic shift right on each vector element (define_expand "vashr<mode>3" [(set (match_operand:VEC_I 0 "vint_operand" "") (ashiftrt:VEC_I (match_operand:VEC_I 1 "vint_operand" "") (match_operand:VEC_I 2 "vint_operand" "")))] "VECTOR_UNIT_ALTIVEC_OR_VSX_P (<MODE>mode)" "") ;; Vector reduction expanders for VSX (define_expand "reduc_<VEC_reduc_name>_v2df" [(parallel [(set (match_operand:V2DF 0 "vfloat_operand" "") (VEC_reduc:V2DF (vec_concat:V2DF (vec_select:DF (match_operand:V2DF 1 "vfloat_operand" "") (parallel [(const_int 1)])) (vec_select:DF (match_dup 1) (parallel [(const_int 0)]))) (match_dup 1))) (clobber (match_scratch:V2DF 2 ""))])] "VECTOR_UNIT_VSX_P (V2DFmode)" "") ; The (VEC_reduc:V4SF ; (op1) ; (unspec:V4SF [(const_int 0)] UNSPEC_REDUC)) ; ; is to allow us to use a code iterator, but not completely list all of the ; vector rotates, etc. to prevent canonicalization (define_expand "reduc_<VEC_reduc_name>_v4sf" [(parallel [(set (match_operand:V4SF 0 "vfloat_operand" "") (VEC_reduc:V4SF (unspec:V4SF [(const_int 0)] UNSPEC_REDUC) (match_operand:V4SF 1 "vfloat_operand" ""))) (clobber (match_scratch:V4SF 2 "")) (clobber (match_scratch:V4SF 3 ""))])] "VECTOR_UNIT_VSX_P (V4SFmode)" "") ;;; Expanders for vector insn patterns shared between the SPE and TARGET_PAIRED systems. (define_expand "absv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "") (abs:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "")))] "TARGET_PAIRED_FLOAT || TARGET_SPE" "") (define_expand "negv2sf2" [(set (match_operand:V2SF 0 "gpc_reg_operand" "") (neg:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "")))] "TARGET_PAIRED_FLOAT || TARGET_SPE" "") (define_expand "addv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "") (plus:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "") (match_operand:V2SF 2 "gpc_reg_operand" "")))] "TARGET_PAIRED_FLOAT || TARGET_SPE" " { if (TARGET_SPE) { /* We need to make a note that we clobber SPEFSCR. */ rtx par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (2)); XVECEXP (par, 0, 0) = gen_rtx_SET (operands[0], gen_rtx_PLUS (V2SFmode, operands[1], operands[2])); XVECEXP (par, 0, 1) = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, SPEFSCR_REGNO)); emit_insn (par); DONE; } }") (define_expand "subv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "") (minus:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "") (match_operand:V2SF 2 "gpc_reg_operand" "")))] "TARGET_PAIRED_FLOAT || TARGET_SPE" " { if (TARGET_SPE) { /* We need to make a note that we clobber SPEFSCR. */ rtx par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (2)); XVECEXP (par, 0, 0) = gen_rtx_SET (operands[0], gen_rtx_MINUS (V2SFmode, operands[1], operands[2])); XVECEXP (par, 0, 1) = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, SPEFSCR_REGNO)); emit_insn (par); DONE; } }") (define_expand "mulv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "") (mult:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "") (match_operand:V2SF 2 "gpc_reg_operand" "")))] "TARGET_PAIRED_FLOAT || TARGET_SPE" " { if (TARGET_SPE) { /* We need to make a note that we clobber SPEFSCR. */ rtx par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (2)); XVECEXP (par, 0, 0) = gen_rtx_SET (operands[0], gen_rtx_MULT (V2SFmode, operands[1], operands[2])); XVECEXP (par, 0, 1) = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, SPEFSCR_REGNO)); emit_insn (par); DONE; } }") (define_expand "divv2sf3" [(set (match_operand:V2SF 0 "gpc_reg_operand" "") (div:V2SF (match_operand:V2SF 1 "gpc_reg_operand" "") (match_operand:V2SF 2 "gpc_reg_operand" "")))] "TARGET_PAIRED_FLOAT || TARGET_SPE" " { if (TARGET_SPE) { /* We need to make a note that we clobber SPEFSCR. */ rtx par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (2)); XVECEXP (par, 0, 0) = gen_rtx_SET (operands[0], gen_rtx_DIV (V2SFmode, operands[1], operands[2])); XVECEXP (par, 0, 1) = gen_rtx_CLOBBER (VOIDmode, gen_rtx_REG (SImode, SPEFSCR_REGNO)); emit_insn (par); DONE; } }")
Vitancourt/gcc
gcc/config/rs6000/vector.md
Markdown
gpl-2.0
37,398
/* Generic symbol file reading for the GNU debugger, GDB. Copyright (C) 1990-2013 Free Software Foundation, Inc. Contributed by Cygnus Support, using pieces from other GDB modules. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "arch-utils.h" #include "bfdlink.h" #include "symtab.h" #include "gdbtypes.h" #include "gdbcore.h" #include "frame.h" #include "target.h" #include "value.h" #include "symfile.h" #include "objfiles.h" #include "source.h" #include "gdbcmd.h" #include "breakpoint.h" #include "language.h" #include "complaints.h" #include "demangle.h" #include "inferior.h" #include "regcache.h" #include "filenames.h" /* for DOSish file names */ #include "gdb-stabs.h" #include "gdb_obstack.h" #include "completer.h" #include "bcache.h" #include "hashtab.h" #include "readline/readline.h" #include "gdb_assert.h" #include "block.h" #include "observer.h" #include "exec.h" #include "parser-defs.h" #include "varobj.h" #include "elf-bfd.h" #include "solib.h" #include "remote.h" #include "stack.h" #include "gdb_bfd.h" #include "cli/cli-utils.h" #include <sys/types.h> #include <fcntl.h> #include "gdb_string.h" #include "gdb_stat.h" #include <ctype.h> #include <time.h> #include <sys/time.h> #include "psymtab.h" int (*deprecated_ui_load_progress_hook) (const char *section, unsigned long num); void (*deprecated_show_load_progress) (const char *section, unsigned long section_sent, unsigned long section_size, unsigned long total_sent, unsigned long total_size); void (*deprecated_pre_add_symbol_hook) (const char *); void (*deprecated_post_add_symbol_hook) (void); static void clear_symtab_users_cleanup (void *ignore); /* Global variables owned by this file. */ int readnow_symbol_files; /* Read full symbols immediately. */ /* Functions this file defines. */ static void load_command (char *, int); static void symbol_file_add_main_1 (const char *args, int from_tty, int flags); static void add_symbol_file_command (char *, int); static const struct sym_fns *find_sym_fns (bfd *); static void decrement_reading_symtab (void *); static void overlay_invalidate_all (void); static void overlay_auto_command (char *, int); static void overlay_manual_command (char *, int); static void overlay_off_command (char *, int); static void overlay_load_command (char *, int); static void overlay_command (char *, int); static void simple_free_overlay_table (void); static void read_target_long_array (CORE_ADDR, unsigned int *, int, int, enum bfd_endian); static int simple_read_overlay_table (void); static int simple_overlay_update_1 (struct obj_section *); static void add_filename_language (char *ext, enum language lang); static void info_ext_lang_command (char *args, int from_tty); static void init_filename_language_table (void); static void symfile_find_segment_sections (struct objfile *objfile); void _initialize_symfile (void); /* List of all available sym_fns. On gdb startup, each object file reader calls add_symtab_fns() to register information on each format it is prepared to read. */ typedef struct { /* BFD flavour that we handle. */ enum bfd_flavour sym_flavour; /* The "vtable" of symbol functions. */ const struct sym_fns *sym_fns; } registered_sym_fns; DEF_VEC_O (registered_sym_fns); static VEC (registered_sym_fns) *symtab_fns = NULL; /* If non-zero, shared library symbols will be added automatically when the inferior is created, new libraries are loaded, or when attaching to the inferior. This is almost always what users will want to have happen; but for very large programs, the startup time will be excessive, and so if this is a problem, the user can clear this flag and then add the shared library symbols as needed. Note that there is a potential for confusion, since if the shared library symbols are not loaded, commands like "info fun" will *not* report all the functions that are actually present. */ int auto_solib_add = 1; /* True if we are reading a symbol table. */ int currently_reading_symtab = 0; static void decrement_reading_symtab (void *dummy) { currently_reading_symtab--; gdb_assert (currently_reading_symtab >= 0); } /* Increment currently_reading_symtab and return a cleanup that can be used to decrement it. */ struct cleanup * increment_reading_symtab (void) { ++currently_reading_symtab; gdb_assert (currently_reading_symtab > 0); return make_cleanup (decrement_reading_symtab, NULL); } /* Remember the lowest-addressed loadable section we've seen. This function is called via bfd_map_over_sections. In case of equal vmas, the section with the largest size becomes the lowest-addressed loadable section. If the vmas and sizes are equal, the last section is considered the lowest-addressed loadable section. */ void find_lowest_section (bfd *abfd, asection *sect, void *obj) { asection **lowest = (asection **) obj; if (0 == (bfd_get_section_flags (abfd, sect) & (SEC_ALLOC | SEC_LOAD))) return; if (!*lowest) *lowest = sect; /* First loadable section */ else if (bfd_section_vma (abfd, *lowest) > bfd_section_vma (abfd, sect)) *lowest = sect; /* A lower loadable section */ else if (bfd_section_vma (abfd, *lowest) == bfd_section_vma (abfd, sect) && (bfd_section_size (abfd, (*lowest)) <= bfd_section_size (abfd, sect))) *lowest = sect; } /* Create a new section_addr_info, with room for NUM_SECTIONS. The new object's 'num_sections' field is set to 0; it must be updated by the caller. */ struct section_addr_info * alloc_section_addr_info (size_t num_sections) { struct section_addr_info *sap; size_t size; size = (sizeof (struct section_addr_info) + sizeof (struct other_sections) * (num_sections - 1)); sap = (struct section_addr_info *) xmalloc (size); memset (sap, 0, size); return sap; } /* Build (allocate and populate) a section_addr_info struct from an existing section table. */ extern struct section_addr_info * build_section_addr_info_from_section_table (const struct target_section *start, const struct target_section *end) { struct section_addr_info *sap; const struct target_section *stp; int oidx; sap = alloc_section_addr_info (end - start); for (stp = start, oidx = 0; stp != end; stp++) { struct bfd_section *asect = stp->the_bfd_section; bfd *abfd = asect->owner; if (bfd_get_section_flags (abfd, asect) & (SEC_ALLOC | SEC_LOAD) && oidx < end - start) { sap->other[oidx].addr = stp->addr; sap->other[oidx].name = xstrdup (bfd_section_name (abfd, asect)); sap->other[oidx].sectindex = gdb_bfd_section_index (abfd, asect); oidx++; } } sap->num_sections = oidx; return sap; } /* Create a section_addr_info from section offsets in ABFD. */ static struct section_addr_info * build_section_addr_info_from_bfd (bfd *abfd) { struct section_addr_info *sap; int i; struct bfd_section *sec; sap = alloc_section_addr_info (bfd_count_sections (abfd)); for (i = 0, sec = abfd->sections; sec != NULL; sec = sec->next) if (bfd_get_section_flags (abfd, sec) & (SEC_ALLOC | SEC_LOAD)) { sap->other[i].addr = bfd_get_section_vma (abfd, sec); sap->other[i].name = xstrdup (bfd_get_section_name (abfd, sec)); sap->other[i].sectindex = gdb_bfd_section_index (abfd, sec); i++; } sap->num_sections = i; return sap; } /* Create a section_addr_info from section offsets in OBJFILE. */ struct section_addr_info * build_section_addr_info_from_objfile (const struct objfile *objfile) { struct section_addr_info *sap; int i; /* Before reread_symbols gets rewritten it is not safe to call: gdb_assert (objfile->num_sections == bfd_count_sections (objfile->obfd)); */ sap = build_section_addr_info_from_bfd (objfile->obfd); for (i = 0; i < sap->num_sections; i++) { int sectindex = sap->other[i].sectindex; sap->other[i].addr += objfile->section_offsets->offsets[sectindex]; } return sap; } /* Free all memory allocated by build_section_addr_info_from_section_table. */ extern void free_section_addr_info (struct section_addr_info *sap) { int idx; for (idx = 0; idx < sap->num_sections; idx++) xfree (sap->other[idx].name); xfree (sap); } /* Initialize OBJFILE's sect_index_* members. */ static void init_objfile_sect_indices (struct objfile *objfile) { asection *sect; int i; sect = bfd_get_section_by_name (objfile->obfd, ".text"); if (sect) objfile->sect_index_text = sect->index; sect = bfd_get_section_by_name (objfile->obfd, ".data"); if (sect) objfile->sect_index_data = sect->index; sect = bfd_get_section_by_name (objfile->obfd, ".bss"); if (sect) objfile->sect_index_bss = sect->index; sect = bfd_get_section_by_name (objfile->obfd, ".rodata"); if (sect) objfile->sect_index_rodata = sect->index; /* This is where things get really weird... We MUST have valid indices for the various sect_index_* members or gdb will abort. So if for example, there is no ".text" section, we have to accomodate that. First, check for a file with the standard one or two segments. */ symfile_find_segment_sections (objfile); /* Except when explicitly adding symbol files at some address, section_offsets contains nothing but zeros, so it doesn't matter which slot in section_offsets the individual sect_index_* members index into. So if they are all zero, it is safe to just point all the currently uninitialized indices to the first slot. But beware: if this is the main executable, it may be relocated later, e.g. by the remote qOffsets packet, and then this will be wrong! That's why we try segments first. */ for (i = 0; i < objfile->num_sections; i++) { if (ANOFFSET (objfile->section_offsets, i) != 0) { break; } } if (i == objfile->num_sections) { if (objfile->sect_index_text == -1) objfile->sect_index_text = 0; if (objfile->sect_index_data == -1) objfile->sect_index_data = 0; if (objfile->sect_index_bss == -1) objfile->sect_index_bss = 0; if (objfile->sect_index_rodata == -1) objfile->sect_index_rodata = 0; } } /* The arguments to place_section. */ struct place_section_arg { struct section_offsets *offsets; CORE_ADDR lowest; }; /* Find a unique offset to use for loadable section SECT if the user did not provide an offset. */ static void place_section (bfd *abfd, asection *sect, void *obj) { struct place_section_arg *arg = obj; CORE_ADDR *offsets = arg->offsets->offsets, start_addr; int done; ULONGEST align = ((ULONGEST) 1) << bfd_get_section_alignment (abfd, sect); /* We are only interested in allocated sections. */ if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0) return; /* If the user specified an offset, honor it. */ if (offsets[gdb_bfd_section_index (abfd, sect)] != 0) return; /* Otherwise, let's try to find a place for the section. */ start_addr = (arg->lowest + align - 1) & -align; do { asection *cur_sec; done = 1; for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next) { int indx = cur_sec->index; /* We don't need to compare against ourself. */ if (cur_sec == sect) continue; /* We can only conflict with allocated sections. */ if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0) continue; /* If the section offset is 0, either the section has not been placed yet, or it was the lowest section placed (in which case LOWEST will be past its end). */ if (offsets[indx] == 0) continue; /* If this section would overlap us, then we must move up. */ if (start_addr + bfd_get_section_size (sect) > offsets[indx] && start_addr < offsets[indx] + bfd_get_section_size (cur_sec)) { start_addr = offsets[indx] + bfd_get_section_size (cur_sec); start_addr = (start_addr + align - 1) & -align; done = 0; break; } /* Otherwise, we appear to be OK. So far. */ } } while (!done); offsets[gdb_bfd_section_index (abfd, sect)] = start_addr; arg->lowest = start_addr + bfd_get_section_size (sect); } /* Store struct section_addr_info as prepared (made relative and with SECTINDEX filled-in) by addr_info_make_relative into SECTION_OFFSETS of NUM_SECTIONS entries. */ void relative_addr_info_to_section_offsets (struct section_offsets *section_offsets, int num_sections, const struct section_addr_info *addrs) { int i; memset (section_offsets, 0, SIZEOF_N_SECTION_OFFSETS (num_sections)); /* Now calculate offsets for section that were specified by the caller. */ for (i = 0; i < addrs->num_sections; i++) { const struct other_sections *osp; osp = &addrs->other[i]; if (osp->sectindex == -1) continue; /* Record all sections in offsets. */ /* The section_offsets in the objfile are here filled in using the BFD index. */ section_offsets->offsets[osp->sectindex] = osp->addr; } } /* Transform section name S for a name comparison. prelink can split section `.bss' into two sections `.dynbss' and `.bss' (in this order). Similarly prelink can split `.sbss' into `.sdynbss' and `.sbss'. Use virtual address of the new `.dynbss' (`.sdynbss') section as the adjacent new `.bss' (`.sbss') section has invalid (increased) virtual address. */ static const char * addr_section_name (const char *s) { if (strcmp (s, ".dynbss") == 0) return ".bss"; if (strcmp (s, ".sdynbss") == 0) return ".sbss"; return s; } /* qsort comparator for addrs_section_sort. Sort entries in ascending order by their (name, sectindex) pair. sectindex makes the sort by name stable. */ static int addrs_section_compar (const void *ap, const void *bp) { const struct other_sections *a = *((struct other_sections **) ap); const struct other_sections *b = *((struct other_sections **) bp); int retval; retval = strcmp (addr_section_name (a->name), addr_section_name (b->name)); if (retval) return retval; return a->sectindex - b->sectindex; } /* Provide sorted array of pointers to sections of ADDRS. The array is terminated by NULL. Caller is responsible to call xfree for it. */ static struct other_sections ** addrs_section_sort (struct section_addr_info *addrs) { struct other_sections **array; int i; /* `+ 1' for the NULL terminator. */ array = xmalloc (sizeof (*array) * (addrs->num_sections + 1)); for (i = 0; i < addrs->num_sections; i++) array[i] = &addrs->other[i]; array[i] = NULL; qsort (array, i, sizeof (*array), addrs_section_compar); return array; } /* Relativize absolute addresses in ADDRS into offsets based on ABFD. Fill-in also SECTINDEXes specific to ABFD there. This function can be used to rebase ADDRS to start referencing different BFD than before. */ void addr_info_make_relative (struct section_addr_info *addrs, bfd *abfd) { asection *lower_sect; CORE_ADDR lower_offset; int i; struct cleanup *my_cleanup; struct section_addr_info *abfd_addrs; struct other_sections **addrs_sorted, **abfd_addrs_sorted; struct other_sections **addrs_to_abfd_addrs; /* Find lowest loadable section to be used as starting point for continguous sections. */ lower_sect = NULL; bfd_map_over_sections (abfd, find_lowest_section, &lower_sect); if (lower_sect == NULL) { warning (_("no loadable sections found in added symbol-file %s"), bfd_get_filename (abfd)); lower_offset = 0; } else lower_offset = bfd_section_vma (bfd_get_filename (abfd), lower_sect); /* Create ADDRS_TO_ABFD_ADDRS array to map the sections in ADDRS to sections in ABFD. Section names are not unique - there can be multiple sections of the same name. Also the sections of the same name do not have to be adjacent to each other. Some sections may be present only in one of the files. Even sections present in both files do not have to be in the same order. Use stable sort by name for the sections in both files. Then linearly scan both lists matching as most of the entries as possible. */ addrs_sorted = addrs_section_sort (addrs); my_cleanup = make_cleanup (xfree, addrs_sorted); abfd_addrs = build_section_addr_info_from_bfd (abfd); make_cleanup_free_section_addr_info (abfd_addrs); abfd_addrs_sorted = addrs_section_sort (abfd_addrs); make_cleanup (xfree, abfd_addrs_sorted); /* Now create ADDRS_TO_ABFD_ADDRS from ADDRS_SORTED and ABFD_ADDRS_SORTED. */ addrs_to_abfd_addrs = xzalloc (sizeof (*addrs_to_abfd_addrs) * addrs->num_sections); make_cleanup (xfree, addrs_to_abfd_addrs); while (*addrs_sorted) { const char *sect_name = addr_section_name ((*addrs_sorted)->name); while (*abfd_addrs_sorted && strcmp (addr_section_name ((*abfd_addrs_sorted)->name), sect_name) < 0) abfd_addrs_sorted++; if (*abfd_addrs_sorted && strcmp (addr_section_name ((*abfd_addrs_sorted)->name), sect_name) == 0) { int index_in_addrs; /* Make the found item directly addressable from ADDRS. */ index_in_addrs = *addrs_sorted - addrs->other; gdb_assert (addrs_to_abfd_addrs[index_in_addrs] == NULL); addrs_to_abfd_addrs[index_in_addrs] = *abfd_addrs_sorted; /* Never use the same ABFD entry twice. */ abfd_addrs_sorted++; } addrs_sorted++; } /* Calculate offsets for the loadable sections. FIXME! Sections must be in order of increasing loadable section so that contiguous sections can use the lower-offset!!! Adjust offsets if the segments are not contiguous. If the section is contiguous, its offset should be set to the offset of the highest loadable section lower than it (the loadable section directly below it in memory). this_offset = lower_offset = lower_addr - lower_orig_addr */ for (i = 0; i < addrs->num_sections; i++) { struct other_sections *sect = addrs_to_abfd_addrs[i]; if (sect) { /* This is the index used by BFD. */ addrs->other[i].sectindex = sect->sectindex; if (addrs->other[i].addr != 0) { addrs->other[i].addr -= sect->addr; lower_offset = addrs->other[i].addr; } else addrs->other[i].addr = lower_offset; } else { /* addr_section_name transformation is not used for SECT_NAME. */ const char *sect_name = addrs->other[i].name; /* This section does not exist in ABFD, which is normally unexpected and we want to issue a warning. However, the ELF prelinker does create a few sections which are marked in the main executable as loadable (they are loaded in memory from the DYNAMIC segment) and yet are not present in separate debug info files. This is fine, and should not cause a warning. Shared libraries contain just the section ".gnu.liblist" but it is not marked as loadable there. There is no other way to identify them than by their name as the sections created by prelink have no special flags. For the sections `.bss' and `.sbss' see addr_section_name. */ if (!(strcmp (sect_name, ".gnu.liblist") == 0 || strcmp (sect_name, ".gnu.conflict") == 0 || (strcmp (sect_name, ".bss") == 0 && i > 0 && strcmp (addrs->other[i - 1].name, ".dynbss") == 0 && addrs_to_abfd_addrs[i - 1] != NULL) || (strcmp (sect_name, ".sbss") == 0 && i > 0 && strcmp (addrs->other[i - 1].name, ".sdynbss") == 0 && addrs_to_abfd_addrs[i - 1] != NULL))) warning (_("section %s not found in %s"), sect_name, bfd_get_filename (abfd)); addrs->other[i].addr = 0; addrs->other[i].sectindex = -1; } } do_cleanups (my_cleanup); } /* Parse the user's idea of an offset for dynamic linking, into our idea of how to represent it for fast symbol reading. This is the default version of the sym_fns.sym_offsets function for symbol readers that don't need to do anything special. It allocates a section_offsets table for the objectfile OBJFILE and stuffs ADDR into all of the offsets. */ void default_symfile_offsets (struct objfile *objfile, const struct section_addr_info *addrs) { objfile->num_sections = gdb_bfd_count_sections (objfile->obfd); objfile->section_offsets = (struct section_offsets *) obstack_alloc (&objfile->objfile_obstack, SIZEOF_N_SECTION_OFFSETS (objfile->num_sections)); relative_addr_info_to_section_offsets (objfile->section_offsets, objfile->num_sections, addrs); /* For relocatable files, all loadable sections will start at zero. The zero is meaningless, so try to pick arbitrary addresses such that no loadable sections overlap. This algorithm is quadratic, but the number of sections in a single object file is generally small. */ if ((bfd_get_file_flags (objfile->obfd) & (EXEC_P | DYNAMIC)) == 0) { struct place_section_arg arg; bfd *abfd = objfile->obfd; asection *cur_sec; for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next) /* We do not expect this to happen; just skip this step if the relocatable file has a section with an assigned VMA. */ if (bfd_section_vma (abfd, cur_sec) != 0) break; if (cur_sec == NULL) { CORE_ADDR *offsets = objfile->section_offsets->offsets; /* Pick non-overlapping offsets for sections the user did not place explicitly. */ arg.offsets = objfile->section_offsets; arg.lowest = 0; bfd_map_over_sections (objfile->obfd, place_section, &arg); /* Correctly filling in the section offsets is not quite enough. Relocatable files have two properties that (most) shared objects do not: - Their debug information will contain relocations. Some shared libraries do also, but many do not, so this can not be assumed. - If there are multiple code sections they will be loaded at different relative addresses in memory than they are in the objfile, since all sections in the file will start at address zero. Because GDB has very limited ability to map from an address in debug info to the correct code section, it relies on adding SECT_OFF_TEXT to things which might be code. If we clear all the section offsets, and set the section VMAs instead, then symfile_relocate_debug_section will return meaningful debug information pointing at the correct sections. GDB has too many different data structures for section addresses - a bfd, objfile, and so_list all have section tables, as does exec_ops. Some of these could probably be eliminated. */ for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next) { if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0) continue; bfd_set_section_vma (abfd, cur_sec, offsets[cur_sec->index]); exec_set_section_address (bfd_get_filename (abfd), cur_sec->index, offsets[cur_sec->index]); offsets[cur_sec->index] = 0; } } } /* Remember the bfd indexes for the .text, .data, .bss and .rodata sections. */ init_objfile_sect_indices (objfile); } /* Divide the file into segments, which are individual relocatable units. This is the default version of the sym_fns.sym_segments function for symbol readers that do not have an explicit representation of segments. It assumes that object files do not have segments, and fully linked files have a single segment. */ struct symfile_segment_data * default_symfile_segments (bfd *abfd) { int num_sections, i; asection *sect; struct symfile_segment_data *data; CORE_ADDR low, high; /* Relocatable files contain enough information to position each loadable section independently; they should not be relocated in segments. */ if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC)) == 0) return NULL; /* Make sure there is at least one loadable section in the file. */ for (sect = abfd->sections; sect != NULL; sect = sect->next) { if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0) continue; break; } if (sect == NULL) return NULL; low = bfd_get_section_vma (abfd, sect); high = low + bfd_get_section_size (sect); data = XZALLOC (struct symfile_segment_data); data->num_segments = 1; data->segment_bases = XCALLOC (1, CORE_ADDR); data->segment_sizes = XCALLOC (1, CORE_ADDR); num_sections = bfd_count_sections (abfd); data->segment_info = XCALLOC (num_sections, int); for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next) { CORE_ADDR vma; if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0) continue; vma = bfd_get_section_vma (abfd, sect); if (vma < low) low = vma; if (vma + bfd_get_section_size (sect) > high) high = vma + bfd_get_section_size (sect); data->segment_info[i] = 1; } data->segment_bases[0] = low; data->segment_sizes[0] = high - low; return data; } /* This is a convenience function to call sym_read for OBJFILE and possibly force the partial symbols to be read. */ static void read_symbols (struct objfile *objfile, int add_flags) { (*objfile->sf->sym_read) (objfile, add_flags); /* find_separate_debug_file_in_section should be called only if there is single binary with no existing separate debug info file. */ if (!objfile_has_partial_symbols (objfile) && objfile->separate_debug_objfile == NULL && objfile->separate_debug_objfile_backlink == NULL) { bfd *abfd = find_separate_debug_file_in_section (objfile); struct cleanup *cleanup = make_cleanup_bfd_unref (abfd); if (abfd != NULL) { /* find_separate_debug_file_in_section uses the same filename for the virtual section-as-bfd like the bfd filename containing the section. Therefore use also non-canonical name form for the same file containing the section. */ symbol_file_add_separate (abfd, objfile->original_name, add_flags, objfile); } do_cleanups (cleanup); } if ((add_flags & SYMFILE_NO_READ) == 0) require_partial_symbols (objfile, 0); } /* Initialize entry point information for this objfile. */ static void init_entry_point_info (struct objfile *objfile) { /* Save startup file's range of PC addresses to help blockframe.c decide where the bottom of the stack is. */ if (bfd_get_file_flags (objfile->obfd) & EXEC_P) { /* Executable file -- record its entry point so we'll recognize the startup file because it contains the entry point. */ objfile->ei.entry_point = bfd_get_start_address (objfile->obfd); objfile->ei.entry_point_p = 1; } else if (bfd_get_file_flags (objfile->obfd) & DYNAMIC && bfd_get_start_address (objfile->obfd) != 0) { /* Some shared libraries may have entry points set and be runnable. There's no clear way to indicate this, so just check for values other than zero. */ objfile->ei.entry_point = bfd_get_start_address (objfile->obfd); objfile->ei.entry_point_p = 1; } else { /* Examination of non-executable.o files. Short-circuit this stuff. */ objfile->ei.entry_point_p = 0; } if (objfile->ei.entry_point_p) { CORE_ADDR entry_point = objfile->ei.entry_point; /* Make certain that the address points at real code, and not a function descriptor. */ entry_point = gdbarch_convert_from_func_ptr_addr (get_objfile_arch (objfile), entry_point, &current_target); /* Remove any ISA markers, so that this matches entries in the symbol table. */ objfile->ei.entry_point = gdbarch_addr_bits_remove (get_objfile_arch (objfile), entry_point); } } /* Process a symbol file, as either the main file or as a dynamically loaded file. This function does not set the OBJFILE's entry-point info. OBJFILE is where the symbols are to be read from. ADDRS is the list of section load addresses. If the user has given an 'add-symbol-file' command, then this is the list of offsets and addresses he or she provided as arguments to the command; or, if we're handling a shared library, these are the actual addresses the sections are loaded at, according to the inferior's dynamic linker (as gleaned by GDB's shared library code). We convert each address into an offset from the section VMA's as it appears in the object file, and then call the file's sym_offsets function to convert this into a format-specific offset table --- a `struct section_offsets'. ADD_FLAGS encodes verbosity level, whether this is main symbol or an extra symbol file such as dynamically loaded code, and wether breakpoint reset should be deferred. */ static void syms_from_objfile_1 (struct objfile *objfile, struct section_addr_info *addrs, int add_flags) { struct section_addr_info *local_addr = NULL; struct cleanup *old_chain; const int mainline = add_flags & SYMFILE_MAINLINE; objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd)); if (objfile->sf == NULL) { /* No symbols to load, but we still need to make sure that the section_offsets table is allocated. */ int num_sections = gdb_bfd_count_sections (objfile->obfd); size_t size = SIZEOF_N_SECTION_OFFSETS (num_sections); objfile->num_sections = num_sections; objfile->section_offsets = obstack_alloc (&objfile->objfile_obstack, size); memset (objfile->section_offsets, 0, size); return; } /* Make sure that partially constructed symbol tables will be cleaned up if an error occurs during symbol reading. */ old_chain = make_cleanup_free_objfile (objfile); /* If ADDRS is NULL, put together a dummy address list. We now establish the convention that an addr of zero means no load address was specified. */ if (! addrs) { local_addr = alloc_section_addr_info (1); make_cleanup (xfree, local_addr); addrs = local_addr; } if (mainline) { /* We will modify the main symbol table, make sure that all its users will be cleaned up if an error occurs during symbol reading. */ make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/); /* Since no error yet, throw away the old symbol table. */ if (symfile_objfile != NULL) { free_objfile (symfile_objfile); gdb_assert (symfile_objfile == NULL); } /* Currently we keep symbols from the add-symbol-file command. If the user wants to get rid of them, they should do "symbol-file" without arguments first. Not sure this is the best behavior (PR 2207). */ (*objfile->sf->sym_new_init) (objfile); } /* Convert addr into an offset rather than an absolute address. We find the lowest address of a loaded segment in the objfile, and assume that <addr> is where that got loaded. We no longer warn if the lowest section is not a text segment (as happens for the PA64 port. */ if (addrs->num_sections > 0) addr_info_make_relative (addrs, objfile->obfd); /* Initialize symbol reading routines for this objfile, allow complaints to appear for this new file, and record how verbose to be, then do the initial symbol reading for this file. */ (*objfile->sf->sym_init) (objfile); clear_complaints (&symfile_complaints, 1, add_flags & SYMFILE_VERBOSE); (*objfile->sf->sym_offsets) (objfile, addrs); read_symbols (objfile, add_flags); /* Discard cleanups as symbol reading was successful. */ discard_cleanups (old_chain); xfree (local_addr); } /* Same as syms_from_objfile_1, but also initializes the objfile entry-point info. */ static void syms_from_objfile (struct objfile *objfile, struct section_addr_info *addrs, int add_flags) { syms_from_objfile_1 (objfile, addrs, add_flags); init_entry_point_info (objfile); } /* Perform required actions after either reading in the initial symbols for a new objfile, or mapping in the symbols from a reusable objfile. ADD_FLAGS is a bitmask of enum symfile_add_flags. */ void new_symfile_objfile (struct objfile *objfile, int add_flags) { /* If this is the main symbol file we have to clean up all users of the old main symbol file. Otherwise it is sufficient to fixup all the breakpoints that may have been redefined by this symbol file. */ if (add_flags & SYMFILE_MAINLINE) { /* OK, make it the "real" symbol file. */ symfile_objfile = objfile; clear_symtab_users (add_flags); } else if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0) { breakpoint_re_set (); } /* We're done reading the symbol file; finish off complaints. */ clear_complaints (&symfile_complaints, 0, add_flags & SYMFILE_VERBOSE); } /* Process a symbol file, as either the main file or as a dynamically loaded file. ABFD is a BFD already open on the file, as from symfile_bfd_open. A new reference is acquired by this function. For NAME description see allocate_objfile's definition. ADD_FLAGS encodes verbosity, whether this is main symbol file or extra, such as dynamically loaded code, and what to do with breakpoins. ADDRS is as described for syms_from_objfile_1, above. ADDRS is ignored when SYMFILE_MAINLINE bit is set in ADD_FLAGS. PARENT is the original objfile if ABFD is a separate debug info file. Otherwise PARENT is NULL. Upon success, returns a pointer to the objfile that was added. Upon failure, jumps back to command level (never returns). */ static struct objfile * symbol_file_add_with_addrs (bfd *abfd, const char *name, int add_flags, struct section_addr_info *addrs, int flags, struct objfile *parent) { struct objfile *objfile; const int from_tty = add_flags & SYMFILE_VERBOSE; const int mainline = add_flags & SYMFILE_MAINLINE; const int should_print = ((from_tty || info_verbose) && (readnow_symbol_files || (add_flags & SYMFILE_NO_READ) == 0)); if (readnow_symbol_files) { flags |= OBJF_READNOW; add_flags &= ~SYMFILE_NO_READ; } /* Give user a chance to burp if we'd be interactively wiping out any existing symbols. */ if ((have_full_symbols () || have_partial_symbols ()) && mainline && from_tty && !query (_("Load new symbol table from \"%s\"? "), name)) error (_("Not confirmed.")); objfile = allocate_objfile (abfd, name, flags | (mainline ? OBJF_MAINLINE : 0)); if (parent) add_separate_debug_objfile (objfile, parent); /* We either created a new mapped symbol table, mapped an existing symbol table file which has not had initial symbol reading performed, or need to read an unmapped symbol table. */ if (should_print) { if (deprecated_pre_add_symbol_hook) deprecated_pre_add_symbol_hook (name); else { printf_unfiltered (_("Reading symbols from %s..."), name); wrap_here (""); gdb_flush (gdb_stdout); } } syms_from_objfile (objfile, addrs, add_flags); /* We now have at least a partial symbol table. Check to see if the user requested that all symbols be read on initial access via either the gdb startup command line or on a per symbol file basis. Expand all partial symbol tables for this objfile if so. */ if ((flags & OBJF_READNOW)) { if (should_print) { printf_unfiltered (_("expanding to full symbols...")); wrap_here (""); gdb_flush (gdb_stdout); } if (objfile->sf) objfile->sf->qf->expand_all_symtabs (objfile); } if (should_print && !objfile_has_symbols (objfile)) { wrap_here (""); printf_unfiltered (_("(no debugging symbols found)...")); wrap_here (""); } if (should_print) { if (deprecated_post_add_symbol_hook) deprecated_post_add_symbol_hook (); else printf_unfiltered (_("done.\n")); } /* We print some messages regardless of whether 'from_tty || info_verbose' is true, so make sure they go out at the right time. */ gdb_flush (gdb_stdout); if (objfile->sf == NULL) { observer_notify_new_objfile (objfile); return objfile; /* No symbols. */ } new_symfile_objfile (objfile, add_flags); observer_notify_new_objfile (objfile); bfd_cache_close_all (); return (objfile); } /* Add BFD as a separate debug file for OBJFILE. For NAME description see allocate_objfile's definition. */ void symbol_file_add_separate (bfd *bfd, const char *name, int symfile_flags, struct objfile *objfile) { struct objfile *new_objfile; struct section_addr_info *sap; struct cleanup *my_cleanup; /* Create section_addr_info. We can't directly use offsets from OBJFILE because sections of BFD may not match sections of OBJFILE and because vma may have been modified by tools such as prelink. */ sap = build_section_addr_info_from_objfile (objfile); my_cleanup = make_cleanup_free_section_addr_info (sap); new_objfile = symbol_file_add_with_addrs (bfd, name, symfile_flags, sap, objfile->flags & (OBJF_REORDERED | OBJF_SHARED | OBJF_READNOW | OBJF_USERLOADED), objfile); do_cleanups (my_cleanup); } /* Process the symbol file ABFD, as either the main file or as a dynamically loaded file. See symbol_file_add_with_addrs's comments for details. */ struct objfile * symbol_file_add_from_bfd (bfd *abfd, const char *name, int add_flags, struct section_addr_info *addrs, int flags, struct objfile *parent) { return symbol_file_add_with_addrs (abfd, name, add_flags, addrs, flags, parent); } /* Process a symbol file, as either the main file or as a dynamically loaded file. See symbol_file_add_with_addrs's comments for details. */ struct objfile * symbol_file_add (const char *name, int add_flags, struct section_addr_info *addrs, int flags) { bfd *bfd = symfile_bfd_open (name); struct cleanup *cleanup = make_cleanup_bfd_unref (bfd); struct objfile *objf; objf = symbol_file_add_from_bfd (bfd, name, add_flags, addrs, flags, NULL); do_cleanups (cleanup); return objf; } /* Call symbol_file_add() with default values and update whatever is affected by the loading of a new main(). Used when the file is supplied in the gdb command line and by some targets with special loading requirements. The auxiliary function, symbol_file_add_main_1(), has the flags argument for the switches that can only be specified in the symbol_file command itself. */ void symbol_file_add_main (const char *args, int from_tty) { symbol_file_add_main_1 (args, from_tty, 0); } static void symbol_file_add_main_1 (const char *args, int from_tty, int flags) { const int add_flags = (current_inferior ()->symfile_flags | SYMFILE_MAINLINE | (from_tty ? SYMFILE_VERBOSE : 0)); symbol_file_add (args, add_flags, NULL, flags); /* Getting new symbols may change our opinion about what is frameless. */ reinit_frame_cache (); if ((flags & SYMFILE_NO_READ) == 0) set_initial_language (); } void symbol_file_clear (int from_tty) { if ((have_full_symbols () || have_partial_symbols ()) && from_tty && (symfile_objfile ? !query (_("Discard symbol table from `%s'? "), objfile_name (symfile_objfile)) : !query (_("Discard symbol table? ")))) error (_("Not confirmed.")); /* solib descriptors may have handles to objfiles. Wipe them before their objfiles get stale by free_all_objfiles. */ no_shared_libraries (NULL, from_tty); free_all_objfiles (); gdb_assert (symfile_objfile == NULL); if (from_tty) printf_unfiltered (_("No symbol file now.\n")); } static int separate_debug_file_exists (const char *name, unsigned long crc, struct objfile *parent_objfile) { unsigned long file_crc; int file_crc_p; bfd *abfd; struct stat parent_stat, abfd_stat; int verified_as_different; /* Find a separate debug info file as if symbols would be present in PARENT_OBJFILE itself this function would not be called. .gnu_debuglink section can contain just the basename of PARENT_OBJFILE without any ".debug" suffix as "/usr/lib/debug/path/to/file" is a separate tree where the separate debug infos with the same basename can exist. */ if (filename_cmp (name, objfile_name (parent_objfile)) == 0) return 0; abfd = gdb_bfd_open_maybe_remote (name); if (!abfd) return 0; /* Verify symlinks were not the cause of filename_cmp name difference above. Some operating systems, e.g. Windows, do not provide a meaningful st_ino; they always set it to zero. (Windows does provide a meaningful st_dev.) Do not indicate a duplicate library in that case. While there is no guarantee that a system that provides meaningful inode numbers will never set st_ino to zero, this is merely an optimization, so we do not need to worry about false negatives. */ if (bfd_stat (abfd, &abfd_stat) == 0 && abfd_stat.st_ino != 0 && bfd_stat (parent_objfile->obfd, &parent_stat) == 0) { if (abfd_stat.st_dev == parent_stat.st_dev && abfd_stat.st_ino == parent_stat.st_ino) { gdb_bfd_unref (abfd); return 0; } verified_as_different = 1; } else verified_as_different = 0; file_crc_p = gdb_bfd_crc (abfd, &file_crc); gdb_bfd_unref (abfd); if (!file_crc_p) return 0; if (crc != file_crc) { unsigned long parent_crc; /* If one (or both) the files are accessed for example the via "remote:" gdbserver way it does not support the bfd_stat operation. Verify whether those two files are not the same manually. */ if (!verified_as_different) { if (!gdb_bfd_crc (parent_objfile->obfd, &parent_crc)) return 0; } if (verified_as_different || parent_crc != file_crc) warning (_("the debug information found in \"%s\"" " does not match \"%s\" (CRC mismatch).\n"), name, objfile_name (parent_objfile)); return 0; } return 1; } char *debug_file_directory = NULL; static void show_debug_file_directory (struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value) { fprintf_filtered (file, _("The directory where separate debug " "symbols are searched for is \"%s\".\n"), value); } #if ! defined (DEBUG_SUBDIRECTORY) #define DEBUG_SUBDIRECTORY ".debug" #endif /* Find a separate debuginfo file for OBJFILE, using DIR as the directory where the original file resides (may not be the same as dirname(objfile->name) due to symlinks), and DEBUGLINK as the file we are looking for. CANON_DIR is the "realpath" form of DIR. DIR must contain a trailing '/'. Returns the path of the file with separate debug info, of NULL. */ static char * find_separate_debug_file (const char *dir, const char *canon_dir, const char *debuglink, unsigned long crc32, struct objfile *objfile) { char *debugdir; char *debugfile; int i; VEC (char_ptr) *debugdir_vec; struct cleanup *back_to; int ix; /* Set I to max (strlen (canon_dir), strlen (dir)). */ i = strlen (dir); if (canon_dir != NULL && strlen (canon_dir) > i) i = strlen (canon_dir); debugfile = xmalloc (strlen (debug_file_directory) + 1 + i + strlen (DEBUG_SUBDIRECTORY) + strlen ("/") + strlen (debuglink) + 1); /* First try in the same directory as the original file. */ strcpy (debugfile, dir); strcat (debugfile, debuglink); if (separate_debug_file_exists (debugfile, crc32, objfile)) return debugfile; /* Then try in the subdirectory named DEBUG_SUBDIRECTORY. */ strcpy (debugfile, dir); strcat (debugfile, DEBUG_SUBDIRECTORY); strcat (debugfile, "/"); strcat (debugfile, debuglink); if (separate_debug_file_exists (debugfile, crc32, objfile)) return debugfile; /* Then try in the global debugfile directories. Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will cause "/..." lookups. */ debugdir_vec = dirnames_to_char_ptr_vec (debug_file_directory); back_to = make_cleanup_free_char_ptr_vec (debugdir_vec); for (ix = 0; VEC_iterate (char_ptr, debugdir_vec, ix, debugdir); ++ix) { strcpy (debugfile, debugdir); strcat (debugfile, "/"); strcat (debugfile, dir); strcat (debugfile, debuglink); if (separate_debug_file_exists (debugfile, crc32, objfile)) { do_cleanups (back_to); return debugfile; } /* If the file is in the sysroot, try using its base path in the global debugfile directory. */ if (canon_dir != NULL && filename_ncmp (canon_dir, gdb_sysroot, strlen (gdb_sysroot)) == 0 && IS_DIR_SEPARATOR (canon_dir[strlen (gdb_sysroot)])) { strcpy (debugfile, debugdir); strcat (debugfile, canon_dir + strlen (gdb_sysroot)); strcat (debugfile, "/"); strcat (debugfile, debuglink); if (separate_debug_file_exists (debugfile, crc32, objfile)) { do_cleanups (back_to); return debugfile; } } } do_cleanups (back_to); xfree (debugfile); return NULL; } /* Modify PATH to contain only "[/]directory/" part of PATH. If there were no directory separators in PATH, PATH will be empty string on return. */ static void terminate_after_last_dir_separator (char *path) { int i; /* Strip off the final filename part, leaving the directory name, followed by a slash. The directory can be relative or absolute. */ for (i = strlen(path) - 1; i >= 0; i--) if (IS_DIR_SEPARATOR (path[i])) break; /* If I is -1 then no directory is present there and DIR will be "". */ path[i + 1] = '\0'; } /* Find separate debuginfo for OBJFILE (using .gnu_debuglink section). Returns pathname, or NULL. */ char * find_separate_debug_file_by_debuglink (struct objfile *objfile) { char *debuglink; char *dir, *canon_dir; char *debugfile; unsigned long crc32; struct cleanup *cleanups; debuglink = bfd_get_debug_link_info (objfile->obfd, &crc32); if (debuglink == NULL) { /* There's no separate debug info, hence there's no way we could load it => no warning. */ return NULL; } cleanups = make_cleanup (xfree, debuglink); dir = xstrdup (objfile_name (objfile)); make_cleanup (xfree, dir); terminate_after_last_dir_separator (dir); canon_dir = lrealpath (dir); debugfile = find_separate_debug_file (dir, canon_dir, debuglink, crc32, objfile); xfree (canon_dir); if (debugfile == NULL) { #ifdef HAVE_LSTAT /* For PR gdb/9538, try again with realpath (if different from the original). */ struct stat st_buf; if (lstat (objfile_name (objfile), &st_buf) == 0 && S_ISLNK (st_buf.st_mode)) { char *symlink_dir; symlink_dir = lrealpath (objfile_name (objfile)); if (symlink_dir != NULL) { make_cleanup (xfree, symlink_dir); terminate_after_last_dir_separator (symlink_dir); if (strcmp (dir, symlink_dir) != 0) { /* Different directory, so try using it. */ debugfile = find_separate_debug_file (symlink_dir, symlink_dir, debuglink, crc32, objfile); } } } #endif /* HAVE_LSTAT */ } do_cleanups (cleanups); return debugfile; } /* This is the symbol-file command. Read the file, analyze its symbols, and add a struct symtab to a symtab list. The syntax of the command is rather bizarre: 1. The function buildargv implements various quoting conventions which are undocumented and have little or nothing in common with the way things are quoted (or not quoted) elsewhere in GDB. 2. Options are used, which are not generally used in GDB (perhaps "set mapped on", "set readnow on" would be better) 3. The order of options matters, which is contrary to GNU conventions (because it is confusing and inconvenient). */ void symbol_file_command (char *args, int from_tty) { dont_repeat (); if (args == NULL) { symbol_file_clear (from_tty); } else { char **argv = gdb_buildargv (args); int flags = OBJF_USERLOADED; struct cleanup *cleanups; char *name = NULL; cleanups = make_cleanup_freeargv (argv); while (*argv != NULL) { if (strcmp (*argv, "-readnow") == 0) flags |= OBJF_READNOW; else if (**argv == '-') error (_("unknown option `%s'"), *argv); else { symbol_file_add_main_1 (*argv, from_tty, flags); name = *argv; } argv++; } if (name == NULL) error (_("no symbol file name was specified")); do_cleanups (cleanups); } } /* Set the initial language. FIXME: A better solution would be to record the language in the psymtab when reading partial symbols, and then use it (if known) to set the language. This would be a win for formats that encode the language in an easily discoverable place, such as DWARF. For stabs, we can jump through hoops looking for specially named symbols or try to intuit the language from the specific type of stabs we find, but we can't do that until later when we read in full symbols. */ void set_initial_language (void) { enum language lang = language_unknown; if (language_of_main != language_unknown) lang = language_of_main; else { char *name = main_name (); struct symbol *sym = lookup_symbol (name, NULL, VAR_DOMAIN, NULL); if (sym != NULL) lang = SYMBOL_LANGUAGE (sym); } if (lang == language_unknown) { /* Make C the default language */ lang = language_c; } set_language (lang); expected_language = current_language; /* Don't warn the user. */ } /* If NAME is a remote name open the file using remote protocol, otherwise open it normally. Returns a new reference to the BFD. On error, returns NULL with the BFD error set. */ bfd * gdb_bfd_open_maybe_remote (const char *name) { bfd *result; if (remote_filename_p (name)) result = remote_bfd_open (name, gnutarget); else result = gdb_bfd_open (name, gnutarget, -1); return result; } /* Open the file specified by NAME and hand it off to BFD for preliminary analysis. Return a newly initialized bfd *, which includes a newly malloc'd` copy of NAME (tilde-expanded and made absolute). In case of trouble, error() is called. */ bfd * symfile_bfd_open (const char *cname) { bfd *sym_bfd; int desc; char *name, *absolute_name; struct cleanup *back_to; if (remote_filename_p (cname)) { sym_bfd = remote_bfd_open (cname, gnutarget); if (!sym_bfd) error (_("`%s': can't open to read symbols: %s."), cname, bfd_errmsg (bfd_get_error ())); if (!bfd_check_format (sym_bfd, bfd_object)) { make_cleanup_bfd_unref (sym_bfd); error (_("`%s': can't read symbols: %s."), cname, bfd_errmsg (bfd_get_error ())); } return sym_bfd; } name = tilde_expand (cname); /* Returns 1st new malloc'd copy. */ /* Look down path for it, allocate 2nd new malloc'd copy. */ desc = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, name, O_RDONLY | O_BINARY, &absolute_name); #if defined(__GO32__) || defined(_WIN32) || defined (__CYGWIN__) if (desc < 0) { char *exename = alloca (strlen (name) + 5); strcat (strcpy (exename, name), ".exe"); desc = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST | OPF_RETURN_REALPATH, exename, O_RDONLY | O_BINARY, &absolute_name); } #endif if (desc < 0) { make_cleanup (xfree, name); perror_with_name (name); } xfree (name); name = absolute_name; back_to = make_cleanup (xfree, name); sym_bfd = gdb_bfd_open (name, gnutarget, desc); if (!sym_bfd) error (_("`%s': can't open to read symbols: %s."), name, bfd_errmsg (bfd_get_error ())); bfd_set_cacheable (sym_bfd, 1); if (!bfd_check_format (sym_bfd, bfd_object)) { make_cleanup_bfd_unref (sym_bfd); error (_("`%s': can't read symbols: %s."), name, bfd_errmsg (bfd_get_error ())); } do_cleanups (back_to); return sym_bfd; } /* Return the section index for SECTION_NAME on OBJFILE. Return -1 if the section was not found. */ int get_section_index (struct objfile *objfile, char *section_name) { asection *sect = bfd_get_section_by_name (objfile->obfd, section_name); if (sect) return sect->index; else return -1; } /* Link SF into the global symtab_fns list. FLAVOUR is the file format that SF handles. Called on startup by the _initialize routine in each object file format reader, to register information about each format the reader is prepared to handle. */ void add_symtab_fns (enum bfd_flavour flavour, const struct sym_fns *sf) { registered_sym_fns fns = { flavour, sf }; VEC_safe_push (registered_sym_fns, symtab_fns, &fns); } /* Initialize OBJFILE to read symbols from its associated BFD. It either returns or calls error(). The result is an initialized struct sym_fns in the objfile structure, that contains cached information about the symbol file. */ static const struct sym_fns * find_sym_fns (bfd *abfd) { registered_sym_fns *rsf; enum bfd_flavour our_flavour = bfd_get_flavour (abfd); int i; if (our_flavour == bfd_target_srec_flavour || our_flavour == bfd_target_ihex_flavour || our_flavour == bfd_target_tekhex_flavour) return NULL; /* No symbols. */ for (i = 0; VEC_iterate (registered_sym_fns, symtab_fns, i, rsf); ++i) if (our_flavour == rsf->sym_flavour) return rsf->sym_fns; error (_("I'm sorry, Dave, I can't do that. Symbol format `%s' unknown."), bfd_get_target (abfd)); } /* This function runs the load command of our current target. */ static void load_command (char *arg, int from_tty) { struct cleanup *cleanup = make_cleanup (null_cleanup, NULL); dont_repeat (); /* The user might be reloading because the binary has changed. Take this opportunity to check. */ reopen_exec_file (); reread_symbols (); if (arg == NULL) { char *parg; int count = 0; parg = arg = get_exec_file (1); /* Count how many \ " ' tab space there are in the name. */ while ((parg = strpbrk (parg, "\\\"'\t "))) { parg++; count++; } if (count) { /* We need to quote this string so buildargv can pull it apart. */ char *temp = xmalloc (strlen (arg) + count + 1 ); char *ptemp = temp; char *prev; make_cleanup (xfree, temp); prev = parg = arg; while ((parg = strpbrk (parg, "\\\"'\t "))) { strncpy (ptemp, prev, parg - prev); ptemp += parg - prev; prev = parg++; *ptemp++ = '\\'; } strcpy (ptemp, prev); arg = temp; } } target_load (arg, from_tty); /* After re-loading the executable, we don't really know which overlays are mapped any more. */ overlay_cache_invalid = 1; do_cleanups (cleanup); } /* This version of "load" should be usable for any target. Currently it is just used for remote targets, not inftarg.c or core files, on the theory that only in that case is it useful. Avoiding xmodem and the like seems like a win (a) because we don't have to worry about finding it, and (b) On VMS, fork() is very slow and so we don't want to run a subprocess. On the other hand, I'm not sure how performance compares. */ static int validate_download = 0; /* Callback service function for generic_load (bfd_map_over_sections). */ static void add_section_size_callback (bfd *abfd, asection *asec, void *data) { bfd_size_type *sum = data; *sum += bfd_get_section_size (asec); } /* Opaque data for load_section_callback. */ struct load_section_data { CORE_ADDR load_offset; struct load_progress_data *progress_data; VEC(memory_write_request_s) *requests; }; /* Opaque data for load_progress. */ struct load_progress_data { /* Cumulative data. */ unsigned long write_count; unsigned long data_count; bfd_size_type total_size; }; /* Opaque data for load_progress for a single section. */ struct load_progress_section_data { struct load_progress_data *cumulative; /* Per-section data. */ const char *section_name; ULONGEST section_sent; ULONGEST section_size; CORE_ADDR lma; gdb_byte *buffer; }; /* Target write callback routine for progress reporting. */ static void load_progress (ULONGEST bytes, void *untyped_arg) { struct load_progress_section_data *args = untyped_arg; struct load_progress_data *totals; if (args == NULL) /* Writing padding data. No easy way to get at the cumulative stats, so just ignore this. */ return; totals = args->cumulative; if (bytes == 0 && args->section_sent == 0) { /* The write is just starting. Let the user know we've started this section. */ ui_out_message (current_uiout, 0, "Loading section %s, size %s lma %s\n", args->section_name, hex_string (args->section_size), paddress (target_gdbarch (), args->lma)); return; } if (validate_download) { /* Broken memories and broken monitors manifest themselves here when bring new computers to life. This doubles already slow downloads. */ /* NOTE: cagney/1999-10-18: A more efficient implementation might add a verify_memory() method to the target vector and then use that. remote.c could implement that method using the ``qCRC'' packet. */ gdb_byte *check = xmalloc (bytes); struct cleanup *verify_cleanups = make_cleanup (xfree, check); if (target_read_memory (args->lma, check, bytes) != 0) error (_("Download verify read failed at %s"), paddress (target_gdbarch (), args->lma)); if (memcmp (args->buffer, check, bytes) != 0) error (_("Download verify compare failed at %s"), paddress (target_gdbarch (), args->lma)); do_cleanups (verify_cleanups); } totals->data_count += bytes; args->lma += bytes; args->buffer += bytes; totals->write_count += 1; args->section_sent += bytes; if (check_quit_flag () || (deprecated_ui_load_progress_hook != NULL && deprecated_ui_load_progress_hook (args->section_name, args->section_sent))) error (_("Canceled the download")); if (deprecated_show_load_progress != NULL) deprecated_show_load_progress (args->section_name, args->section_sent, args->section_size, totals->data_count, totals->total_size); } /* Callback service function for generic_load (bfd_map_over_sections). */ static void load_section_callback (bfd *abfd, asection *asec, void *data) { struct memory_write_request *new_request; struct load_section_data *args = data; struct load_progress_section_data *section_data; bfd_size_type size = bfd_get_section_size (asec); gdb_byte *buffer; const char *sect_name = bfd_get_section_name (abfd, asec); if ((bfd_get_section_flags (abfd, asec) & SEC_LOAD) == 0) return; if (size == 0) return; new_request = VEC_safe_push (memory_write_request_s, args->requests, NULL); memset (new_request, 0, sizeof (struct memory_write_request)); section_data = xcalloc (1, sizeof (struct load_progress_section_data)); new_request->begin = bfd_section_lma (abfd, asec) + args->load_offset; new_request->end = new_request->begin + size; /* FIXME Should size be in instead? */ new_request->data = xmalloc (size); new_request->baton = section_data; buffer = new_request->data; section_data->cumulative = args->progress_data; section_data->section_name = sect_name; section_data->section_size = size; section_data->lma = new_request->begin; section_data->buffer = buffer; bfd_get_section_contents (abfd, asec, buffer, 0, size); } /* Clean up an entire memory request vector, including load data and progress records. */ static void clear_memory_write_data (void *arg) { VEC(memory_write_request_s) **vec_p = arg; VEC(memory_write_request_s) *vec = *vec_p; int i; struct memory_write_request *mr; for (i = 0; VEC_iterate (memory_write_request_s, vec, i, mr); ++i) { xfree (mr->data); xfree (mr->baton); } VEC_free (memory_write_request_s, vec); } void generic_load (char *args, int from_tty) { bfd *loadfile_bfd; struct timeval start_time, end_time; char *filename; struct cleanup *old_cleanups = make_cleanup (null_cleanup, 0); struct load_section_data cbdata; struct load_progress_data total_progress; struct ui_out *uiout = current_uiout; CORE_ADDR entry; char **argv; memset (&cbdata, 0, sizeof (cbdata)); memset (&total_progress, 0, sizeof (total_progress)); cbdata.progress_data = &total_progress; make_cleanup (clear_memory_write_data, &cbdata.requests); if (args == NULL) error_no_arg (_("file to load")); argv = gdb_buildargv (args); make_cleanup_freeargv (argv); filename = tilde_expand (argv[0]); make_cleanup (xfree, filename); if (argv[1] != NULL) { const char *endptr; cbdata.load_offset = strtoulst (argv[1], &endptr, 0); /* If the last word was not a valid number then treat it as a file name with spaces in. */ if (argv[1] == endptr) error (_("Invalid download offset:%s."), argv[1]); if (argv[2] != NULL) error (_("Too many parameters.")); } /* Open the file for loading. */ loadfile_bfd = gdb_bfd_open (filename, gnutarget, -1); if (loadfile_bfd == NULL) { perror_with_name (filename); return; } make_cleanup_bfd_unref (loadfile_bfd); if (!bfd_check_format (loadfile_bfd, bfd_object)) { error (_("\"%s\" is not an object file: %s"), filename, bfd_errmsg (bfd_get_error ())); } bfd_map_over_sections (loadfile_bfd, add_section_size_callback, (void *) &total_progress.total_size); bfd_map_over_sections (loadfile_bfd, load_section_callback, &cbdata); gettimeofday (&start_time, NULL); if (target_write_memory_blocks (cbdata.requests, flash_discard, load_progress) != 0) error (_("Load failed")); gettimeofday (&end_time, NULL); entry = bfd_get_start_address (loadfile_bfd); entry = gdbarch_addr_bits_remove (target_gdbarch (), entry); ui_out_text (uiout, "Start address "); ui_out_field_fmt (uiout, "address", "%s", paddress (target_gdbarch (), entry)); ui_out_text (uiout, ", load size "); ui_out_field_fmt (uiout, "load-size", "%lu", total_progress.data_count); ui_out_text (uiout, "\n"); /* We were doing this in remote-mips.c, I suspect it is right for other targets too. */ regcache_write_pc (get_current_regcache (), entry); /* Reset breakpoints, now that we have changed the load image. For instance, breakpoints may have been set (or reset, by post_create_inferior) while connected to the target but before we loaded the program. In that case, the prologue analyzer could have read instructions from the target to find the right breakpoint locations. Loading has changed the contents of that memory. */ breakpoint_re_set (); /* FIXME: are we supposed to call symbol_file_add or not? According to a comment from remote-mips.c (where a call to symbol_file_add was commented out), making the call confuses GDB if more than one file is loaded in. Some targets do (e.g., remote-vx.c) but others don't (or didn't - perhaps they have all been deleted). */ print_transfer_performance (gdb_stdout, total_progress.data_count, total_progress.write_count, &start_time, &end_time); do_cleanups (old_cleanups); } /* Report how fast the transfer went. */ void print_transfer_performance (struct ui_file *stream, unsigned long data_count, unsigned long write_count, const struct timeval *start_time, const struct timeval *end_time) { ULONGEST time_count; struct ui_out *uiout = current_uiout; /* Compute the elapsed time in milliseconds, as a tradeoff between accuracy and overflow. */ time_count = (end_time->tv_sec - start_time->tv_sec) * 1000; time_count += (end_time->tv_usec - start_time->tv_usec) / 1000; ui_out_text (uiout, "Transfer rate: "); if (time_count > 0) { unsigned long rate = ((ULONGEST) data_count * 1000) / time_count; if (ui_out_is_mi_like_p (uiout)) { ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate * 8); ui_out_text (uiout, " bits/sec"); } else if (rate < 1024) { ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate); ui_out_text (uiout, " bytes/sec"); } else { ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate / 1024); ui_out_text (uiout, " KB/sec"); } } else { ui_out_field_fmt (uiout, "transferred-bits", "%lu", (data_count * 8)); ui_out_text (uiout, " bits in <1 sec"); } if (write_count > 0) { ui_out_text (uiout, ", "); ui_out_field_fmt (uiout, "write-rate", "%lu", data_count / write_count); ui_out_text (uiout, " bytes/write"); } ui_out_text (uiout, ".\n"); } /* This function allows the addition of incrementally linked object files. It does not modify any state in the target, only in the debugger. */ /* Note: ezannoni 2000-04-13 This function/command used to have a special case syntax for the rombug target (Rombug is the boot monitor for Microware's OS-9 / OS-9000, see remote-os9k.c). In the rombug case, the user doesn't need to supply a text address, instead a call to target_link() (in target.c) would supply the value to use. We are now discontinuing this type of ad hoc syntax. */ static void add_symbol_file_command (char *args, int from_tty) { struct gdbarch *gdbarch = get_current_arch (); char *filename = NULL; int flags = OBJF_USERLOADED; char *arg; int section_index = 0; int argcnt = 0; int sec_num = 0; int i; int expecting_sec_name = 0; int expecting_sec_addr = 0; char **argv; struct sect_opt { char *name; char *value; }; struct section_addr_info *section_addrs; struct sect_opt *sect_opts = NULL; size_t num_sect_opts = 0; struct cleanup *my_cleanups = make_cleanup (null_cleanup, NULL); num_sect_opts = 16; sect_opts = (struct sect_opt *) xmalloc (num_sect_opts * sizeof (struct sect_opt)); dont_repeat (); if (args == NULL) error (_("add-symbol-file takes a file name and an address")); argv = gdb_buildargv (args); make_cleanup_freeargv (argv); for (arg = argv[0], argcnt = 0; arg != NULL; arg = argv[++argcnt]) { /* Process the argument. */ if (argcnt == 0) { /* The first argument is the file name. */ filename = tilde_expand (arg); make_cleanup (xfree, filename); } else if (argcnt == 1) { /* The second argument is always the text address at which to load the program. */ sect_opts[section_index].name = ".text"; sect_opts[section_index].value = arg; if (++section_index >= num_sect_opts) { num_sect_opts *= 2; sect_opts = ((struct sect_opt *) xrealloc (sect_opts, num_sect_opts * sizeof (struct sect_opt))); } } else { /* It's an option (starting with '-') or it's an argument to an option. */ if (expecting_sec_name) { sect_opts[section_index].name = arg; expecting_sec_name = 0; } else if (expecting_sec_addr) { sect_opts[section_index].value = arg; expecting_sec_addr = 0; if (++section_index >= num_sect_opts) { num_sect_opts *= 2; sect_opts = ((struct sect_opt *) xrealloc (sect_opts, num_sect_opts * sizeof (struct sect_opt))); } } else if (strcmp (arg, "-readnow") == 0) flags |= OBJF_READNOW; else if (strcmp (arg, "-s") == 0) { expecting_sec_name = 1; expecting_sec_addr = 1; } else error (_("USAGE: add-symbol-file <filename> <textaddress>" " [-readnow] [-s <secname> <addr>]*")); } } /* This command takes at least two arguments. The first one is a filename, and the second is the address where this file has been loaded. Abort now if this address hasn't been provided by the user. */ if (section_index < 1) error (_("The address where %s has been loaded is missing"), filename); /* Print the prompt for the query below. And save the arguments into a sect_addr_info structure to be passed around to other functions. We have to split this up into separate print statements because hex_string returns a local static string. */ printf_unfiltered (_("add symbol table from file \"%s\" at\n"), filename); section_addrs = alloc_section_addr_info (section_index); make_cleanup (xfree, section_addrs); for (i = 0; i < section_index; i++) { CORE_ADDR addr; char *val = sect_opts[i].value; char *sec = sect_opts[i].name; addr = parse_and_eval_address (val); /* Here we store the section offsets in the order they were entered on the command line. */ section_addrs->other[sec_num].name = sec; section_addrs->other[sec_num].addr = addr; printf_unfiltered ("\t%s_addr = %s\n", sec, paddress (gdbarch, addr)); sec_num++; /* The object's sections are initialized when a call is made to build_objfile_section_table (objfile). This happens in reread_symbols. At this point, we don't know what file type this is, so we can't determine what section names are valid. */ } section_addrs->num_sections = sec_num; if (from_tty && (!query ("%s", ""))) error (_("Not confirmed.")); symbol_file_add (filename, from_tty ? SYMFILE_VERBOSE : 0, section_addrs, flags); /* Getting new symbols may change our opinion about what is frameless. */ reinit_frame_cache (); do_cleanups (my_cleanups); } typedef struct objfile *objfilep; DEF_VEC_P (objfilep); /* Re-read symbols if a symbol-file has changed. */ void reread_symbols (void) { struct objfile *objfile; long new_modtime; struct stat new_statbuf; int res; VEC (objfilep) *new_objfiles = NULL; struct cleanup *all_cleanups; all_cleanups = make_cleanup (VEC_cleanup (objfilep), &new_objfiles); /* With the addition of shared libraries, this should be modified, the load time should be saved in the partial symbol tables, since different tables may come from different source files. FIXME. This routine should then walk down each partial symbol table and see if the symbol table that it originates from has been changed. */ for (objfile = object_files; objfile; objfile = objfile->next) { if (objfile->obfd == NULL) continue; /* Separate debug objfiles are handled in the main objfile. */ if (objfile->separate_debug_objfile_backlink) continue; /* If this object is from an archive (what you usually create with `ar', often called a `static library' on most systems, though a `shared library' on AIX is also an archive), then you should stat on the archive name, not member name. */ if (objfile->obfd->my_archive) res = stat (objfile->obfd->my_archive->filename, &new_statbuf); else res = stat (objfile_name (objfile), &new_statbuf); if (res != 0) { /* FIXME, should use print_sys_errmsg but it's not filtered. */ printf_unfiltered (_("`%s' has disappeared; keeping its symbols.\n"), objfile_name (objfile)); continue; } new_modtime = new_statbuf.st_mtime; if (new_modtime != objfile->mtime) { struct cleanup *old_cleanups; struct section_offsets *offsets; int num_offsets; char *original_name; printf_unfiltered (_("`%s' has changed; re-reading symbols.\n"), objfile_name (objfile)); /* There are various functions like symbol_file_add, symfile_bfd_open, syms_from_objfile, etc., which might appear to do what we want. But they have various other effects which we *don't* want. So we just do stuff ourselves. We don't worry about mapped files (for one thing, any mapped file will be out of date). */ /* If we get an error, blow away this objfile (not sure if that is the correct response for things like shared libraries). */ old_cleanups = make_cleanup_free_objfile (objfile); /* We need to do this whenever any symbols go away. */ make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/); if (exec_bfd != NULL && filename_cmp (bfd_get_filename (objfile->obfd), bfd_get_filename (exec_bfd)) == 0) { /* Reload EXEC_BFD without asking anything. */ exec_file_attach (bfd_get_filename (objfile->obfd), 0); } /* Keep the calls order approx. the same as in free_objfile. */ /* Free the separate debug objfiles. It will be automatically recreated by sym_read. */ free_objfile_separate_debug (objfile); /* Remove any references to this objfile in the global value lists. */ preserve_values (objfile); /* Nuke all the state that we will re-read. Much of the following code which sets things to NULL really is necessary to tell other parts of GDB that there is nothing currently there. Try to keep the freeing order compatible with free_objfile. */ if (objfile->sf != NULL) { (*objfile->sf->sym_finish) (objfile); } clear_objfile_data (objfile); /* Clean up any state BFD has sitting around. */ { struct bfd *obfd = objfile->obfd; char *obfd_filename; obfd_filename = bfd_get_filename (objfile->obfd); /* Open the new BFD before freeing the old one, so that the filename remains live. */ objfile->obfd = gdb_bfd_open_maybe_remote (obfd_filename); if (objfile->obfd == NULL) { /* We have to make a cleanup and error here, rather than erroring later, because once we unref OBFD, OBFD_FILENAME will be freed. */ make_cleanup_bfd_unref (obfd); error (_("Can't open %s to read symbols."), obfd_filename); } gdb_bfd_unref (obfd); } original_name = xstrdup (objfile->original_name); make_cleanup (xfree, original_name); /* bfd_openr sets cacheable to true, which is what we want. */ if (!bfd_check_format (objfile->obfd, bfd_object)) error (_("Can't read symbols from %s: %s."), objfile_name (objfile), bfd_errmsg (bfd_get_error ())); /* Save the offsets, we will nuke them with the rest of the objfile_obstack. */ num_offsets = objfile->num_sections; offsets = ((struct section_offsets *) alloca (SIZEOF_N_SECTION_OFFSETS (num_offsets))); memcpy (offsets, objfile->section_offsets, SIZEOF_N_SECTION_OFFSETS (num_offsets)); /* FIXME: Do we have to free a whole linked list, or is this enough? */ if (objfile->global_psymbols.list) xfree (objfile->global_psymbols.list); memset (&objfile->global_psymbols, 0, sizeof (objfile->global_psymbols)); if (objfile->static_psymbols.list) xfree (objfile->static_psymbols.list); memset (&objfile->static_psymbols, 0, sizeof (objfile->static_psymbols)); /* Free the obstacks for non-reusable objfiles. */ psymbol_bcache_free (objfile->psymbol_cache); objfile->psymbol_cache = psymbol_bcache_init (); obstack_free (&objfile->objfile_obstack, 0); objfile->sections = NULL; objfile->symtabs = NULL; objfile->psymtabs = NULL; objfile->psymtabs_addrmap = NULL; objfile->free_psymtabs = NULL; objfile->template_symbols = NULL; objfile->msymbols = NULL; objfile->minimal_symbol_count = 0; memset (&objfile->msymbol_hash, 0, sizeof (objfile->msymbol_hash)); memset (&objfile->msymbol_demangled_hash, 0, sizeof (objfile->msymbol_demangled_hash)); set_objfile_per_bfd (objfile); /* obstack_init also initializes the obstack so it is empty. We could use obstack_specify_allocation but gdb_obstack.h specifies the alloc/dealloc functions. */ obstack_init (&objfile->objfile_obstack); objfile->original_name = obstack_copy0 (&objfile->objfile_obstack, original_name, strlen (original_name)); /* Reset the sym_fns pointer. The ELF reader can change it based on whether .gdb_index is present, and we need it to start over. PR symtab/15885 */ objfile_set_sym_fns (objfile, find_sym_fns (objfile->obfd)); build_objfile_section_table (objfile); terminate_minimal_symbol_table (objfile); /* We use the same section offsets as from last time. I'm not sure whether that is always correct for shared libraries. */ objfile->section_offsets = (struct section_offsets *) obstack_alloc (&objfile->objfile_obstack, SIZEOF_N_SECTION_OFFSETS (num_offsets)); memcpy (objfile->section_offsets, offsets, SIZEOF_N_SECTION_OFFSETS (num_offsets)); objfile->num_sections = num_offsets; /* What the hell is sym_new_init for, anyway? The concept of distinguishing between the main file and additional files in this way seems rather dubious. */ if (objfile == symfile_objfile) { (*objfile->sf->sym_new_init) (objfile); } (*objfile->sf->sym_init) (objfile); clear_complaints (&symfile_complaints, 1, 1); objfile->flags &= ~OBJF_PSYMTABS_READ; read_symbols (objfile, 0); if (!objfile_has_symbols (objfile)) { wrap_here (""); printf_unfiltered (_("(no debugging symbols found)\n")); wrap_here (""); } /* We're done reading the symbol file; finish off complaints. */ clear_complaints (&symfile_complaints, 0, 1); /* Getting new symbols may change our opinion about what is frameless. */ reinit_frame_cache (); /* Discard cleanups as symbol reading was successful. */ discard_cleanups (old_cleanups); /* If the mtime has changed between the time we set new_modtime and now, we *want* this to be out of date, so don't call stat again now. */ objfile->mtime = new_modtime; init_entry_point_info (objfile); VEC_safe_push (objfilep, new_objfiles, objfile); } } if (new_objfiles) { int ix; /* Notify objfiles that we've modified objfile sections. */ objfiles_changed (); clear_symtab_users (0); /* clear_objfile_data for each objfile was called before freeing it and observer_notify_new_objfile (NULL) has been called by clear_symtab_users above. Notify the new files now. */ for (ix = 0; VEC_iterate (objfilep, new_objfiles, ix, objfile); ix++) observer_notify_new_objfile (objfile); /* At least one objfile has changed, so we can consider that the executable we're debugging has changed too. */ observer_notify_executable_changed (); } do_cleanups (all_cleanups); } typedef struct { char *ext; enum language lang; } filename_language; static filename_language *filename_language_table; static int fl_table_size, fl_table_next; static void add_filename_language (char *ext, enum language lang) { if (fl_table_next >= fl_table_size) { fl_table_size += 10; filename_language_table = xrealloc (filename_language_table, fl_table_size * sizeof (*filename_language_table)); } filename_language_table[fl_table_next].ext = xstrdup (ext); filename_language_table[fl_table_next].lang = lang; fl_table_next++; } static char *ext_args; static void show_ext_args (struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value) { fprintf_filtered (file, _("Mapping between filename extension " "and source language is \"%s\".\n"), value); } static void set_ext_lang_command (char *args, int from_tty, struct cmd_list_element *e) { int i; char *cp = ext_args; enum language lang; /* First arg is filename extension, starting with '.' */ if (*cp != '.') error (_("'%s': Filename extension must begin with '.'"), ext_args); /* Find end of first arg. */ while (*cp && !isspace (*cp)) cp++; if (*cp == '\0') error (_("'%s': two arguments required -- " "filename extension and language"), ext_args); /* Null-terminate first arg. */ *cp++ = '\0'; /* Find beginning of second arg, which should be a source language. */ cp = skip_spaces (cp); if (*cp == '\0') error (_("'%s': two arguments required -- " "filename extension and language"), ext_args); /* Lookup the language from among those we know. */ lang = language_enum (cp); /* Now lookup the filename extension: do we already know it? */ for (i = 0; i < fl_table_next; i++) if (0 == strcmp (ext_args, filename_language_table[i].ext)) break; if (i >= fl_table_next) { /* New file extension. */ add_filename_language (ext_args, lang); } else { /* Redefining a previously known filename extension. */ /* if (from_tty) */ /* query ("Really make files of type %s '%s'?", */ /* ext_args, language_str (lang)); */ xfree (filename_language_table[i].ext); filename_language_table[i].ext = xstrdup (ext_args); filename_language_table[i].lang = lang; } } static void info_ext_lang_command (char *args, int from_tty) { int i; printf_filtered (_("Filename extensions and the languages they represent:")); printf_filtered ("\n\n"); for (i = 0; i < fl_table_next; i++) printf_filtered ("\t%s\t- %s\n", filename_language_table[i].ext, language_str (filename_language_table[i].lang)); } static void init_filename_language_table (void) { if (fl_table_size == 0) /* Protect against repetition. */ { fl_table_size = 20; fl_table_next = 0; filename_language_table = xmalloc (fl_table_size * sizeof (*filename_language_table)); add_filename_language (".c", language_c); add_filename_language (".d", language_d); add_filename_language (".C", language_cplus); add_filename_language (".cc", language_cplus); add_filename_language (".cp", language_cplus); add_filename_language (".cpp", language_cplus); add_filename_language (".cxx", language_cplus); add_filename_language (".c++", language_cplus); add_filename_language (".java", language_java); add_filename_language (".class", language_java); add_filename_language (".m", language_objc); add_filename_language (".f", language_fortran); add_filename_language (".F", language_fortran); add_filename_language (".for", language_fortran); add_filename_language (".FOR", language_fortran); add_filename_language (".ftn", language_fortran); add_filename_language (".FTN", language_fortran); add_filename_language (".fpp", language_fortran); add_filename_language (".FPP", language_fortran); add_filename_language (".f90", language_fortran); add_filename_language (".F90", language_fortran); add_filename_language (".f95", language_fortran); add_filename_language (".F95", language_fortran); add_filename_language (".f03", language_fortran); add_filename_language (".F03", language_fortran); add_filename_language (".f08", language_fortran); add_filename_language (".F08", language_fortran); add_filename_language (".s", language_asm); add_filename_language (".sx", language_asm); add_filename_language (".S", language_asm); add_filename_language (".pas", language_pascal); add_filename_language (".p", language_pascal); add_filename_language (".pp", language_pascal); add_filename_language (".adb", language_ada); add_filename_language (".ads", language_ada); add_filename_language (".a", language_ada); add_filename_language (".ada", language_ada); add_filename_language (".dg", language_ada); } } enum language deduce_language_from_filename (const char *filename) { int i; char *cp; if (filename != NULL) if ((cp = strrchr (filename, '.')) != NULL) for (i = 0; i < fl_table_next; i++) if (strcmp (cp, filename_language_table[i].ext) == 0) return filename_language_table[i].lang; return language_unknown; } /* allocate_symtab: Allocate and partly initialize a new symbol table. Return a pointer to it. error() if no space. Caller must set these fields: LINETABLE(symtab) symtab->blockvector symtab->dirname symtab->free_code symtab->free_ptr */ struct symtab * allocate_symtab (const char *filename, struct objfile *objfile) { struct symtab *symtab; symtab = (struct symtab *) obstack_alloc (&objfile->objfile_obstack, sizeof (struct symtab)); memset (symtab, 0, sizeof (*symtab)); symtab->filename = (char *) bcache (filename, strlen (filename) + 1, objfile->per_bfd->filename_cache); symtab->fullname = NULL; symtab->language = deduce_language_from_filename (filename); symtab->debugformat = "unknown"; /* Hook it to the objfile it comes from. */ symtab->objfile = objfile; symtab->next = objfile->symtabs; objfile->symtabs = symtab; if (symtab_create_debug) { /* Be a bit clever with debugging messages, and don't print objfile every time, only when it changes. */ static char *last_objfile_name = NULL; if (last_objfile_name == NULL || strcmp (last_objfile_name, objfile_name (objfile)) != 0) { xfree (last_objfile_name); last_objfile_name = xstrdup (objfile_name (objfile)); fprintf_unfiltered (gdb_stdlog, "Creating one or more symtabs for objfile %s ...\n", last_objfile_name); } fprintf_unfiltered (gdb_stdlog, "Created symtab %s for module %s.\n", host_address_to_string (symtab), filename); } return (symtab); } /* Reset all data structures in gdb which may contain references to symbol table data. ADD_FLAGS is a bitmask of enum symfile_add_flags. */ void clear_symtab_users (int add_flags) { /* Someday, we should do better than this, by only blowing away the things that really need to be blown. */ /* Clear the "current" symtab first, because it is no longer valid. breakpoint_re_set may try to access the current symtab. */ clear_current_source_symtab_and_line (); clear_displays (); if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0) breakpoint_re_set (); clear_last_displayed_sal (); clear_pc_function_cache (); observer_notify_new_objfile (NULL); /* Clear globals which might have pointed into a removed objfile. FIXME: It's not clear which of these are supposed to persist between expressions and which ought to be reset each time. */ expression_context_block = NULL; innermost_block = NULL; /* Varobj may refer to old symbols, perform a cleanup. */ varobj_invalidate (); } static void clear_symtab_users_cleanup (void *ignore) { clear_symtab_users (0); } /* OVERLAYS: The following code implements an abstraction for debugging overlay sections. The target model is as follows: 1) The gnu linker will permit multiple sections to be mapped into the same VMA, each with its own unique LMA (or load address). 2) It is assumed that some runtime mechanism exists for mapping the sections, one by one, from the load address into the VMA address. 3) This code provides a mechanism for gdb to keep track of which sections should be considered to be mapped from the VMA to the LMA. This information is used for symbol lookup, and memory read/write. For instance, if a section has been mapped then its contents should be read from the VMA, otherwise from the LMA. Two levels of debugger support for overlays are available. One is "manual", in which the debugger relies on the user to tell it which overlays are currently mapped. This level of support is implemented entirely in the core debugger, and the information about whether a section is mapped is kept in the objfile->obj_section table. The second level of support is "automatic", and is only available if the target-specific code provides functionality to read the target's overlay mapping table, and translate its contents for the debugger (by updating the mapped state information in the obj_section tables). The interface is as follows: User commands: overlay map <name> -- tell gdb to consider this section mapped overlay unmap <name> -- tell gdb to consider this section unmapped overlay list -- list the sections that GDB thinks are mapped overlay read-target -- get the target's state of what's mapped overlay off/manual/auto -- set overlay debugging state Functional interface: find_pc_mapped_section(pc): if the pc is in the range of a mapped section, return that section. find_pc_overlay(pc): find any overlay section that contains the pc, either in its VMA or its LMA section_is_mapped(sect): true if overlay is marked as mapped section_is_overlay(sect): true if section's VMA != LMA pc_in_mapped_range(pc,sec): true if pc belongs to section's VMA pc_in_unmapped_range(...): true if pc belongs to section's LMA sections_overlap(sec1, sec2): true if mapped sec1 and sec2 ranges overlap overlay_mapped_address(...): map an address from section's LMA to VMA overlay_unmapped_address(...): map an address from section's VMA to LMA symbol_overlayed_address(...): Return a "current" address for symbol: either in VMA or LMA depending on whether the symbol's section is currently mapped. */ /* Overlay debugging state: */ enum overlay_debugging_state overlay_debugging = ovly_off; int overlay_cache_invalid = 0; /* True if need to refresh mapped state. */ /* Function: section_is_overlay (SECTION) Returns true if SECTION has VMA not equal to LMA, ie. SECTION is loaded at an address different from where it will "run". */ int section_is_overlay (struct obj_section *section) { if (overlay_debugging && section) { bfd *abfd = section->objfile->obfd; asection *bfd_section = section->the_bfd_section; if (bfd_section_lma (abfd, bfd_section) != 0 && bfd_section_lma (abfd, bfd_section) != bfd_section_vma (abfd, bfd_section)) return 1; } return 0; } /* Function: overlay_invalidate_all (void) Invalidate the mapped state of all overlay sections (mark it as stale). */ static void overlay_invalidate_all (void) { struct objfile *objfile; struct obj_section *sect; ALL_OBJSECTIONS (objfile, sect) if (section_is_overlay (sect)) sect->ovly_mapped = -1; } /* Function: section_is_mapped (SECTION) Returns true if section is an overlay, and is currently mapped. Access to the ovly_mapped flag is restricted to this function, so that we can do automatic update. If the global flag OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call overlay_invalidate_all. If the mapped state of the particular section is stale, then call TARGET_OVERLAY_UPDATE to refresh it. */ int section_is_mapped (struct obj_section *osect) { struct gdbarch *gdbarch; if (osect == 0 || !section_is_overlay (osect)) return 0; switch (overlay_debugging) { default: case ovly_off: return 0; /* overlay debugging off */ case ovly_auto: /* overlay debugging automatic */ /* Unles there is a gdbarch_overlay_update function, there's really nothing useful to do here (can't really go auto). */ gdbarch = get_objfile_arch (osect->objfile); if (gdbarch_overlay_update_p (gdbarch)) { if (overlay_cache_invalid) { overlay_invalidate_all (); overlay_cache_invalid = 0; } if (osect->ovly_mapped == -1) gdbarch_overlay_update (gdbarch, osect); } /* fall thru to manual case */ case ovly_on: /* overlay debugging manual */ return osect->ovly_mapped == 1; } } /* Function: pc_in_unmapped_range If PC falls into the lma range of SECTION, return true, else false. */ CORE_ADDR pc_in_unmapped_range (CORE_ADDR pc, struct obj_section *section) { if (section_is_overlay (section)) { bfd *abfd = section->objfile->obfd; asection *bfd_section = section->the_bfd_section; /* We assume the LMA is relocated by the same offset as the VMA. */ bfd_vma size = bfd_get_section_size (bfd_section); CORE_ADDR offset = obj_section_offset (section); if (bfd_get_section_lma (abfd, bfd_section) + offset <= pc && pc < bfd_get_section_lma (abfd, bfd_section) + offset + size) return 1; } return 0; } /* Function: pc_in_mapped_range If PC falls into the vma range of SECTION, return true, else false. */ CORE_ADDR pc_in_mapped_range (CORE_ADDR pc, struct obj_section *section) { if (section_is_overlay (section)) { if (obj_section_addr (section) <= pc && pc < obj_section_endaddr (section)) return 1; } return 0; } /* Return true if the mapped ranges of sections A and B overlap, false otherwise. */ static int sections_overlap (struct obj_section *a, struct obj_section *b) { CORE_ADDR a_start = obj_section_addr (a); CORE_ADDR a_end = obj_section_endaddr (a); CORE_ADDR b_start = obj_section_addr (b); CORE_ADDR b_end = obj_section_endaddr (b); return (a_start < b_end && b_start < a_end); } /* Function: overlay_unmapped_address (PC, SECTION) Returns the address corresponding to PC in the unmapped (load) range. May be the same as PC. */ CORE_ADDR overlay_unmapped_address (CORE_ADDR pc, struct obj_section *section) { if (section_is_overlay (section) && pc_in_mapped_range (pc, section)) { bfd *abfd = section->objfile->obfd; asection *bfd_section = section->the_bfd_section; return pc + bfd_section_lma (abfd, bfd_section) - bfd_section_vma (abfd, bfd_section); } return pc; } /* Function: overlay_mapped_address (PC, SECTION) Returns the address corresponding to PC in the mapped (runtime) range. May be the same as PC. */ CORE_ADDR overlay_mapped_address (CORE_ADDR pc, struct obj_section *section) { if (section_is_overlay (section) && pc_in_unmapped_range (pc, section)) { bfd *abfd = section->objfile->obfd; asection *bfd_section = section->the_bfd_section; return pc + bfd_section_vma (abfd, bfd_section) - bfd_section_lma (abfd, bfd_section); } return pc; } /* Function: symbol_overlayed_address Return one of two addresses (relative to the VMA or to the LMA), depending on whether the section is mapped or not. */ CORE_ADDR symbol_overlayed_address (CORE_ADDR address, struct obj_section *section) { if (overlay_debugging) { /* If the symbol has no section, just return its regular address. */ if (section == 0) return address; /* If the symbol's section is not an overlay, just return its address. */ if (!section_is_overlay (section)) return address; /* If the symbol's section is mapped, just return its address. */ if (section_is_mapped (section)) return address; /* * HOWEVER: if the symbol is in an overlay section which is NOT mapped, * then return its LOADED address rather than its vma address!! */ return overlay_unmapped_address (address, section); } return address; } /* Function: find_pc_overlay (PC) Return the best-match overlay section for PC: If PC matches a mapped overlay section's VMA, return that section. Else if PC matches an unmapped section's VMA, return that section. Else if PC matches an unmapped section's LMA, return that section. */ struct obj_section * find_pc_overlay (CORE_ADDR pc) { struct objfile *objfile; struct obj_section *osect, *best_match = NULL; if (overlay_debugging) ALL_OBJSECTIONS (objfile, osect) if (section_is_overlay (osect)) { if (pc_in_mapped_range (pc, osect)) { if (section_is_mapped (osect)) return osect; else best_match = osect; } else if (pc_in_unmapped_range (pc, osect)) best_match = osect; } return best_match; } /* Function: find_pc_mapped_section (PC) If PC falls into the VMA address range of an overlay section that is currently marked as MAPPED, return that section. Else return NULL. */ struct obj_section * find_pc_mapped_section (CORE_ADDR pc) { struct objfile *objfile; struct obj_section *osect; if (overlay_debugging) ALL_OBJSECTIONS (objfile, osect) if (pc_in_mapped_range (pc, osect) && section_is_mapped (osect)) return osect; return NULL; } /* Function: list_overlays_command Print a list of mapped sections and their PC ranges. */ static void list_overlays_command (char *args, int from_tty) { int nmapped = 0; struct objfile *objfile; struct obj_section *osect; if (overlay_debugging) ALL_OBJSECTIONS (objfile, osect) if (section_is_mapped (osect)) { struct gdbarch *gdbarch = get_objfile_arch (objfile); const char *name; bfd_vma lma, vma; int size; vma = bfd_section_vma (objfile->obfd, osect->the_bfd_section); lma = bfd_section_lma (objfile->obfd, osect->the_bfd_section); size = bfd_get_section_size (osect->the_bfd_section); name = bfd_section_name (objfile->obfd, osect->the_bfd_section); printf_filtered ("Section %s, loaded at ", name); fputs_filtered (paddress (gdbarch, lma), gdb_stdout); puts_filtered (" - "); fputs_filtered (paddress (gdbarch, lma + size), gdb_stdout); printf_filtered (", mapped at "); fputs_filtered (paddress (gdbarch, vma), gdb_stdout); puts_filtered (" - "); fputs_filtered (paddress (gdbarch, vma + size), gdb_stdout); puts_filtered ("\n"); nmapped++; } if (nmapped == 0) printf_filtered (_("No sections are mapped.\n")); } /* Function: map_overlay_command Mark the named section as mapped (ie. residing at its VMA address). */ static void map_overlay_command (char *args, int from_tty) { struct objfile *objfile, *objfile2; struct obj_section *sec, *sec2; if (!overlay_debugging) error (_("Overlay debugging not enabled. Use " "either the 'overlay auto' or\n" "the 'overlay manual' command.")); if (args == 0 || *args == 0) error (_("Argument required: name of an overlay section")); /* First, find a section matching the user supplied argument. */ ALL_OBJSECTIONS (objfile, sec) if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args)) { /* Now, check to see if the section is an overlay. */ if (!section_is_overlay (sec)) continue; /* not an overlay section */ /* Mark the overlay as "mapped". */ sec->ovly_mapped = 1; /* Next, make a pass and unmap any sections that are overlapped by this new section: */ ALL_OBJSECTIONS (objfile2, sec2) if (sec2->ovly_mapped && sec != sec2 && sections_overlap (sec, sec2)) { if (info_verbose) printf_unfiltered (_("Note: section %s unmapped by overlap\n"), bfd_section_name (objfile->obfd, sec2->the_bfd_section)); sec2->ovly_mapped = 0; /* sec2 overlaps sec: unmap sec2. */ } return; } error (_("No overlay section called %s"), args); } /* Function: unmap_overlay_command Mark the overlay section as unmapped (ie. resident in its LMA address range, rather than the VMA range). */ static void unmap_overlay_command (char *args, int from_tty) { struct objfile *objfile; struct obj_section *sec; if (!overlay_debugging) error (_("Overlay debugging not enabled. " "Use either the 'overlay auto' or\n" "the 'overlay manual' command.")); if (args == 0 || *args == 0) error (_("Argument required: name of an overlay section")); /* First, find a section matching the user supplied argument. */ ALL_OBJSECTIONS (objfile, sec) if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args)) { if (!sec->ovly_mapped) error (_("Section %s is not mapped"), args); sec->ovly_mapped = 0; return; } error (_("No overlay section called %s"), args); } /* Function: overlay_auto_command A utility command to turn on overlay debugging. Possibly this should be done via a set/show command. */ static void overlay_auto_command (char *args, int from_tty) { overlay_debugging = ovly_auto; enable_overlay_breakpoints (); if (info_verbose) printf_unfiltered (_("Automatic overlay debugging enabled.")); } /* Function: overlay_manual_command A utility command to turn on overlay debugging. Possibly this should be done via a set/show command. */ static void overlay_manual_command (char *args, int from_tty) { overlay_debugging = ovly_on; disable_overlay_breakpoints (); if (info_verbose) printf_unfiltered (_("Overlay debugging enabled.")); } /* Function: overlay_off_command A utility command to turn on overlay debugging. Possibly this should be done via a set/show command. */ static void overlay_off_command (char *args, int from_tty) { overlay_debugging = ovly_off; disable_overlay_breakpoints (); if (info_verbose) printf_unfiltered (_("Overlay debugging disabled.")); } static void overlay_load_command (char *args, int from_tty) { struct gdbarch *gdbarch = get_current_arch (); if (gdbarch_overlay_update_p (gdbarch)) gdbarch_overlay_update (gdbarch, NULL); else error (_("This target does not know how to read its overlay state.")); } /* Function: overlay_command A place-holder for a mis-typed command. */ /* Command list chain containing all defined "overlay" subcommands. */ static struct cmd_list_element *overlaylist; static void overlay_command (char *args, int from_tty) { printf_unfiltered ("\"overlay\" must be followed by the name of an overlay command.\n"); help_list (overlaylist, "overlay ", -1, gdb_stdout); } /* Target Overlays for the "Simplest" overlay manager: This is GDB's default target overlay layer. It works with the minimal overlay manager supplied as an example by Cygnus. The entry point is via a function pointer "gdbarch_overlay_update", so targets that use a different runtime overlay manager can substitute their own overlay_update function and take over the function pointer. The overlay_update function pokes around in the target's data structures to see what overlays are mapped, and updates GDB's overlay mapping with this information. In this simple implementation, the target data structures are as follows: unsigned _novlys; /# number of overlay sections #/ unsigned _ovly_table[_novlys][4] = { {VMA, SIZE, LMA, MAPPED}, /# one entry per overlay section #/ {..., ..., ..., ...}, } unsigned _novly_regions; /# number of overlay regions #/ unsigned _ovly_region_table[_novly_regions][3] = { {VMA, SIZE, MAPPED_TO_LMA}, /# one entry per overlay region #/ {..., ..., ...}, } These functions will attempt to update GDB's mappedness state in the symbol section table, based on the target's mappedness state. To do this, we keep a cached copy of the target's _ovly_table, and attempt to detect when the cached copy is invalidated. The main entry point is "simple_overlay_update(SECT), which looks up SECT in the cached table and re-reads only the entry for that section from the target (whenever possible). */ /* Cached, dynamically allocated copies of the target data structures: */ static unsigned (*cache_ovly_table)[4] = 0; static unsigned cache_novlys = 0; static CORE_ADDR cache_ovly_table_base = 0; enum ovly_index { VMA, SIZE, LMA, MAPPED }; /* Throw away the cached copy of _ovly_table. */ static void simple_free_overlay_table (void) { if (cache_ovly_table) xfree (cache_ovly_table); cache_novlys = 0; cache_ovly_table = NULL; cache_ovly_table_base = 0; } /* Read an array of ints of size SIZE from the target into a local buffer. Convert to host order. int LEN is number of ints. */ static void read_target_long_array (CORE_ADDR memaddr, unsigned int *myaddr, int len, int size, enum bfd_endian byte_order) { /* FIXME (alloca): Not safe if array is very large. */ gdb_byte *buf = alloca (len * size); int i; read_memory (memaddr, buf, len * size); for (i = 0; i < len; i++) myaddr[i] = extract_unsigned_integer (size * i + buf, size, byte_order); } /* Find and grab a copy of the target _ovly_table (and _novlys, which is needed for the table's size). */ static int simple_read_overlay_table (void) { struct minimal_symbol *novlys_msym; struct bound_minimal_symbol ovly_table_msym; struct gdbarch *gdbarch; int word_size; enum bfd_endian byte_order; simple_free_overlay_table (); novlys_msym = lookup_minimal_symbol ("_novlys", NULL, NULL); if (! novlys_msym) { error (_("Error reading inferior's overlay table: " "couldn't find `_novlys' variable\n" "in inferior. Use `overlay manual' mode.")); return 0; } ovly_table_msym = lookup_bound_minimal_symbol ("_ovly_table"); if (! ovly_table_msym.minsym) { error (_("Error reading inferior's overlay table: couldn't find " "`_ovly_table' array\n" "in inferior. Use `overlay manual' mode.")); return 0; } gdbarch = get_objfile_arch (ovly_table_msym.objfile); word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT; byte_order = gdbarch_byte_order (gdbarch); cache_novlys = read_memory_integer (SYMBOL_VALUE_ADDRESS (novlys_msym), 4, byte_order); cache_ovly_table = (void *) xmalloc (cache_novlys * sizeof (*cache_ovly_table)); cache_ovly_table_base = SYMBOL_VALUE_ADDRESS (ovly_table_msym.minsym); read_target_long_array (cache_ovly_table_base, (unsigned int *) cache_ovly_table, cache_novlys * 4, word_size, byte_order); return 1; /* SUCCESS */ } /* Function: simple_overlay_update_1 A helper function for simple_overlay_update. Assuming a cached copy of _ovly_table exists, look through it to find an entry whose vma, lma and size match those of OSECT. Re-read the entry and make sure it still matches OSECT (else the table may no longer be valid). Set OSECT's mapped state to match the entry. Return: 1 for success, 0 for failure. */ static int simple_overlay_update_1 (struct obj_section *osect) { int i, size; bfd *obfd = osect->objfile->obfd; asection *bsect = osect->the_bfd_section; struct gdbarch *gdbarch = get_objfile_arch (osect->objfile); int word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT; enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); size = bfd_get_section_size (osect->the_bfd_section); for (i = 0; i < cache_novlys; i++) if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect) && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect) /* && cache_ovly_table[i][SIZE] == size */ ) { read_target_long_array (cache_ovly_table_base + i * word_size, (unsigned int *) cache_ovly_table[i], 4, word_size, byte_order); if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect) && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect) /* && cache_ovly_table[i][SIZE] == size */ ) { osect->ovly_mapped = cache_ovly_table[i][MAPPED]; return 1; } else /* Warning! Warning! Target's ovly table has changed! */ return 0; } return 0; } /* Function: simple_overlay_update If OSECT is NULL, then update all sections' mapped state (after re-reading the entire target _ovly_table). If OSECT is non-NULL, then try to find a matching entry in the cached ovly_table and update only OSECT's mapped state. If a cached entry can't be found or the cache isn't valid, then re-read the entire cache, and go ahead and update all sections. */ void simple_overlay_update (struct obj_section *osect) { struct objfile *objfile; /* Were we given an osect to look up? NULL means do all of them. */ if (osect) /* Have we got a cached copy of the target's overlay table? */ if (cache_ovly_table != NULL) { /* Does its cached location match what's currently in the symtab? */ struct minimal_symbol *minsym = lookup_minimal_symbol ("_ovly_table", NULL, NULL); if (minsym == NULL) error (_("Error reading inferior's overlay table: couldn't " "find `_ovly_table' array\n" "in inferior. Use `overlay manual' mode.")); if (cache_ovly_table_base == SYMBOL_VALUE_ADDRESS (minsym)) /* Then go ahead and try to look up this single section in the cache. */ if (simple_overlay_update_1 (osect)) /* Found it! We're done. */ return; } /* Cached table no good: need to read the entire table anew. Or else we want all the sections, in which case it's actually more efficient to read the whole table in one block anyway. */ if (! simple_read_overlay_table ()) return; /* Now may as well update all sections, even if only one was requested. */ ALL_OBJSECTIONS (objfile, osect) if (section_is_overlay (osect)) { int i, size; bfd *obfd = osect->objfile->obfd; asection *bsect = osect->the_bfd_section; size = bfd_get_section_size (bsect); for (i = 0; i < cache_novlys; i++) if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect) && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect) /* && cache_ovly_table[i][SIZE] == size */ ) { /* obj_section matches i'th entry in ovly_table. */ osect->ovly_mapped = cache_ovly_table[i][MAPPED]; break; /* finished with inner for loop: break out. */ } } } /* Set the output sections and output offsets for section SECTP in ABFD. The relocation code in BFD will read these offsets, so we need to be sure they're initialized. We map each section to itself, with no offset; this means that SECTP->vma will be honored. */ static void symfile_dummy_outputs (bfd *abfd, asection *sectp, void *dummy) { sectp->output_section = sectp; sectp->output_offset = 0; } /* Default implementation for sym_relocate. */ bfd_byte * default_symfile_relocate (struct objfile *objfile, asection *sectp, bfd_byte *buf) { /* Use sectp->owner instead of objfile->obfd. sectp may point to a DWO file. */ bfd *abfd = sectp->owner; /* We're only interested in sections with relocation information. */ if ((sectp->flags & SEC_RELOC) == 0) return NULL; /* We will handle section offsets properly elsewhere, so relocate as if all sections begin at 0. */ bfd_map_over_sections (abfd, symfile_dummy_outputs, NULL); return bfd_simple_get_relocated_section_contents (abfd, sectp, buf, NULL); } /* Relocate the contents of a debug section SECTP in ABFD. The contents are stored in BUF if it is non-NULL, or returned in a malloc'd buffer otherwise. For some platforms and debug info formats, shared libraries contain relocations against the debug sections (particularly for DWARF-2; one affected platform is PowerPC GNU/Linux, although it depends on the version of the linker in use). Also, ELF object files naturally have unresolved relocations for their debug sections. We need to apply the relocations in order to get the locations of symbols correct. Another example that may require relocation processing, is the DWARF-2 .eh_frame section in .o files, although it isn't strictly a debug section. */ bfd_byte * symfile_relocate_debug_section (struct objfile *objfile, asection *sectp, bfd_byte *buf) { gdb_assert (objfile->sf->sym_relocate); return (*objfile->sf->sym_relocate) (objfile, sectp, buf); } struct symfile_segment_data * get_symfile_segment_data (bfd *abfd) { const struct sym_fns *sf = find_sym_fns (abfd); if (sf == NULL) return NULL; return sf->sym_segments (abfd); } void free_symfile_segment_data (struct symfile_segment_data *data) { xfree (data->segment_bases); xfree (data->segment_sizes); xfree (data->segment_info); xfree (data); } /* Given: - DATA, containing segment addresses from the object file ABFD, and the mapping from ABFD's sections onto the segments that own them, and - SEGMENT_BASES[0 .. NUM_SEGMENT_BASES - 1], holding the actual segment addresses reported by the target, store the appropriate offsets for each section in OFFSETS. If there are fewer entries in SEGMENT_BASES than there are segments in DATA, then apply SEGMENT_BASES' last entry to all the segments. If there are more entries, then ignore the extra. The target may not be able to distinguish between an empty data segment and a missing data segment; a missing text segment is less plausible. */ int symfile_map_offsets_to_segments (bfd *abfd, const struct symfile_segment_data *data, struct section_offsets *offsets, int num_segment_bases, const CORE_ADDR *segment_bases) { int i; asection *sect; /* It doesn't make sense to call this function unless you have some segment base addresses. */ gdb_assert (num_segment_bases > 0); /* If we do not have segment mappings for the object file, we can not relocate it by segments. */ gdb_assert (data != NULL); gdb_assert (data->num_segments > 0); for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next) { int which = data->segment_info[i]; gdb_assert (0 <= which && which <= data->num_segments); /* Don't bother computing offsets for sections that aren't loaded as part of any segment. */ if (! which) continue; /* Use the last SEGMENT_BASES entry as the address of any extra segments mentioned in DATA->segment_info. */ if (which > num_segment_bases) which = num_segment_bases; offsets->offsets[i] = (segment_bases[which - 1] - data->segment_bases[which - 1]); } return 1; } static void symfile_find_segment_sections (struct objfile *objfile) { bfd *abfd = objfile->obfd; int i; asection *sect; struct symfile_segment_data *data; data = get_symfile_segment_data (objfile->obfd); if (data == NULL) return; if (data->num_segments != 1 && data->num_segments != 2) { free_symfile_segment_data (data); return; } for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next) { int which = data->segment_info[i]; if (which == 1) { if (objfile->sect_index_text == -1) objfile->sect_index_text = sect->index; if (objfile->sect_index_rodata == -1) objfile->sect_index_rodata = sect->index; } else if (which == 2) { if (objfile->sect_index_data == -1) objfile->sect_index_data = sect->index; if (objfile->sect_index_bss == -1) objfile->sect_index_bss = sect->index; } } free_symfile_segment_data (data); } void _initialize_symfile (void) { struct cmd_list_element *c; c = add_cmd ("symbol-file", class_files, symbol_file_command, _("\ Load symbol table from executable file FILE.\n\ The `file' command can also load symbol tables, as well as setting the file\n\ to execute."), &cmdlist); set_cmd_completer (c, filename_completer); c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command, _("\ Load symbols from FILE, assuming FILE has been dynamically loaded.\n\ Usage: add-symbol-file FILE ADDR [-s <SECT> <SECT_ADDR> -s <SECT> <SECT_ADDR>\ ...]\nADDR is the starting address of the file's text.\n\ The optional arguments are section-name section-address pairs and\n\ should be specified if the data and bss segments are not contiguous\n\ with the text. SECT is a section name to be loaded at SECT_ADDR."), &cmdlist); set_cmd_completer (c, filename_completer); c = add_cmd ("load", class_files, load_command, _("\ Dynamically load FILE into the running program, and record its symbols\n\ for access from GDB.\n\ A load OFFSET may also be given."), &cmdlist); set_cmd_completer (c, filename_completer); add_prefix_cmd ("overlay", class_support, overlay_command, _("Commands for debugging overlays."), &overlaylist, "overlay ", 0, &cmdlist); add_com_alias ("ovly", "overlay", class_alias, 1); add_com_alias ("ov", "overlay", class_alias, 1); add_cmd ("map-overlay", class_support, map_overlay_command, _("Assert that an overlay section is mapped."), &overlaylist); add_cmd ("unmap-overlay", class_support, unmap_overlay_command, _("Assert that an overlay section is unmapped."), &overlaylist); add_cmd ("list-overlays", class_support, list_overlays_command, _("List mappings of overlay sections."), &overlaylist); add_cmd ("manual", class_support, overlay_manual_command, _("Enable overlay debugging."), &overlaylist); add_cmd ("off", class_support, overlay_off_command, _("Disable overlay debugging."), &overlaylist); add_cmd ("auto", class_support, overlay_auto_command, _("Enable automatic overlay debugging."), &overlaylist); add_cmd ("load-target", class_support, overlay_load_command, _("Read the overlay mapping state from the target."), &overlaylist); /* Filename extension to source language lookup table: */ init_filename_language_table (); add_setshow_string_noescape_cmd ("extension-language", class_files, &ext_args, _("\ Set mapping between filename extension and source language."), _("\ Show mapping between filename extension and source language."), _("\ Usage: set extension-language .foo bar"), set_ext_lang_command, show_ext_args, &setlist, &showlist); add_info ("extensions", info_ext_lang_command, _("All filename extensions associated with a source language.")); add_setshow_optional_filename_cmd ("debug-file-directory", class_support, &debug_file_directory, _("\ Set the directories where separate debug symbols are searched for."), _("\ Show the directories where separate debug symbols are searched for."), _("\ Separate debug symbols are first searched for in the same\n\ directory as the binary, then in the `" DEBUG_SUBDIRECTORY "' subdirectory,\n\ and lastly at the path of the directory of the binary with\n\ each global debug-file-directory component prepended."), NULL, show_debug_file_directory, &setlist, &showlist); }
mirror/cygwin
gdb/symfile.c
C
gpl-2.0
119,493
/* * Copyright (c) 2001, 2012, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1MMUTRACKER_HPP #define SHARE_VM_GC_IMPLEMENTATION_G1_G1MMUTRACKER_HPP #include "memory/allocation.hpp" #include "utilities/debug.hpp" // Keeps track of the GC work and decides when it is OK to do GC work // and for how long so that the MMU invariants are maintained. /***** ALL TIMES ARE IN SECS!!!!!!! *****/ // this is the "interface" class G1MMUTracker: public CHeapObj<mtGC> { protected: double _time_slice; double _max_gc_time; // this is per time slice public: G1MMUTracker(double time_slice, double max_gc_time); virtual void add_pause(double start, double end, bool gc_thread) = 0; virtual double longest_pause(double current_time) = 0; virtual double when_sec(double current_time, double pause_time) = 0; double max_gc_time() { return _max_gc_time; } inline bool now_max_gc(double current_time) { return when_sec(current_time, max_gc_time()) < 0.00001; } inline double when_max_gc_sec(double current_time) { return when_sec(current_time, max_gc_time()); } inline jlong when_max_gc_ms(double current_time) { double when = when_max_gc_sec(current_time); return (jlong) (when * 1000.0); } inline jlong when_ms(double current_time, double pause_time) { double when = when_sec(current_time, pause_time); return (jlong) (when * 1000.0); } }; class G1MMUTrackerQueueElem VALUE_OBJ_CLASS_SPEC { private: double _start_time; double _end_time; public: inline double start_time() { return _start_time; } inline double end_time() { return _end_time; } inline double duration() { return _end_time - _start_time; } G1MMUTrackerQueueElem() { _start_time = 0.0; _end_time = 0.0; } G1MMUTrackerQueueElem(double start_time, double end_time) { _start_time = start_time; _end_time = end_time; } }; // this is an implementation of the MMUTracker using a (fixed-size) queue // that keeps track of all the recent pause times class G1MMUTrackerQueue: public G1MMUTracker { private: enum PrivateConstants { QueueLength = 64 }; // The array keeps track of all the pauses that fall within a time // slice (the last time slice during which pauses took place). // The data structure implemented is a circular queue. // Head "points" to the most recent addition, tail to the oldest one. // The array is of fixed size and I don't think we'll need more than // two or three entries with the current behavior of G1 pauses. // If the array is full, an easy fix is to look for the pauses with // the shortest gap between them and consolidate them. // For now, we have taken the expedient alternative of forgetting // the oldest entry in the event that +G1UseFixedWindowMMUTracker, thus // potentially violating MMU specs for some time thereafter. G1MMUTrackerQueueElem _array[QueueLength]; int _head_index; int _tail_index; int _no_entries; inline int trim_index(int index) { return (index + QueueLength) % QueueLength; } void remove_expired_entries(double current_time); double calculate_gc_time(double current_time); double longest_pause_internal(double current_time); double when_internal(double current_time, double pause_time); public: G1MMUTrackerQueue(double time_slice, double max_gc_time); virtual void add_pause(double start, double end, bool gc_thread); virtual double longest_pause(double current_time); virtual double when_sec(double current_time, double pause_time); }; #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1MMUTRACKER_HPP
netroby/jdk9-shenandoah-hotspot
src/share/vm/gc_implementation/g1/g1MMUTracker.hpp
C++
gpl-2.0
4,677
/* * linux/arch/x86_64/mm/init.c * * Copyright (C) 1995 Linus Torvalds * Copyright (C) 2000 Pavel Machek <[email protected]> * Copyright (C) 2002,2003 Andi Kleen <[email protected]> */ #include <linux/config.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/types.h> #include <linux/ptrace.h> #include <linux/mman.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/smp.h> #include <linux/init.h> #include <linux/pagemap.h> #include <linux/bootmem.h> #include <linux/proc_fs.h> #include <asm/processor.h> #include <asm/system.h> #include <asm/uaccess.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/dma.h> #include <asm/fixmap.h> #include <asm/e820.h> #include <asm/apic.h> #include <asm/tlb.h> #include <asm/mmu_context.h> #include <asm/proto.h> #include <asm/smp.h> #ifndef Dprintk #define Dprintk(x...) #endif #ifdef CONFIG_GART_IOMMU extern int swiotlb; #endif extern char _stext[]; DEFINE_PER_CPU(struct mmu_gather, mmu_gathers); /* * NOTE: pagetable_init alloc all the fixmap pagetables contiguous on the * physical space so we can cache the place of the first one and move * around without checking the pgd every time. */ void show_mem(void) { int i, total = 0, reserved = 0; int shared = 0, cached = 0; pg_data_t *pgdat; struct page *page; printk("Mem-info:\n"); show_free_areas(); printk("Free swap: %6ldkB\n", nr_swap_pages<<(PAGE_SHIFT-10)); for_each_pgdat(pgdat) { for (i = 0; i < pgdat->node_spanned_pages; ++i) { page = pfn_to_page(pgdat->node_start_pfn + i); total++; if (PageReserved(page)) reserved++; else if (PageSwapCache(page)) cached++; else if (page_count(page)) shared += page_count(page) - 1; } } printk("%d pages of RAM\n", total); printk("%d reserved pages\n",reserved); printk("%d pages shared\n",shared); printk("%d pages swap cached\n",cached); } /* References to section boundaries */ extern char _text, _etext, _edata, __bss_start, _end[]; extern char __init_begin, __init_end; int after_bootmem; static void *spp_getpage(void) { void *ptr; if (after_bootmem) ptr = (void *) get_zeroed_page(GFP_ATOMIC); else ptr = alloc_bootmem_pages(PAGE_SIZE); if (!ptr || ((unsigned long)ptr & ~PAGE_MASK)) panic("set_pte_phys: cannot allocate page data %s\n", after_bootmem?"after bootmem":""); Dprintk("spp_getpage %p\n", ptr); return ptr; } static void set_pte_phys(unsigned long vaddr, unsigned long phys, pgprot_t prot) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte, new_pte; Dprintk("set_pte_phys %lx to %lx\n", vaddr, phys); pgd = pgd_offset_k(vaddr); if (pgd_none(*pgd)) { printk("PGD FIXMAP MISSING, it should be setup in head.S!\n"); return; } pud = pud_offset(pgd, vaddr); if (pud_none(*pud)) { pmd = (pmd_t *) spp_getpage(); set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE | _PAGE_USER)); if (pmd != pmd_offset(pud, 0)) { printk("PAGETABLE BUG #01! %p <-> %p\n", pmd, pmd_offset(pud,0)); return; } } pmd = pmd_offset(pud, vaddr); if (pmd_none(*pmd)) { pte = (pte_t *) spp_getpage(); set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE | _PAGE_USER)); if (pte != pte_offset_kernel(pmd, 0)) { printk("PAGETABLE BUG #02!\n"); return; } } new_pte = pfn_pte(phys >> PAGE_SHIFT, prot); pte = pte_offset_kernel(pmd, vaddr); if (!pte_none(*pte) && pte_val(*pte) != (pte_val(new_pte) & __supported_pte_mask)) pte_ERROR(*pte); set_pte(pte, new_pte); /* * It's enough to flush this one mapping. * (PGE mappings get flushed as well) */ __flush_tlb_one(vaddr); } /* NOTE: this is meant to be run only at boot */ void __set_fixmap (enum fixed_addresses idx, unsigned long phys, pgprot_t prot) { unsigned long address = __fix_to_virt(idx); if (idx >= __end_of_fixed_addresses) { printk("Invalid __set_fixmap\n"); return; } set_pte_phys(address, phys, prot); } unsigned long __initdata table_start, table_end; extern pmd_t temp_boot_pmds[]; static struct temp_map { pmd_t *pmd; void *address; int allocated; } temp_mappings[] __initdata = { { &temp_boot_pmds[0], (void *)(40UL * 1024 * 1024) }, { &temp_boot_pmds[1], (void *)(42UL * 1024 * 1024) }, {} }; static __init void *alloc_low_page(int *index, unsigned long *phys) { struct temp_map *ti; int i; unsigned long pfn = table_end++, paddr; void *adr; if (pfn >= end_pfn) panic("alloc_low_page: ran out of memory"); for (i = 0; temp_mappings[i].allocated; i++) { if (!temp_mappings[i].pmd) panic("alloc_low_page: ran out of temp mappings"); } ti = &temp_mappings[i]; paddr = (pfn << PAGE_SHIFT) & PMD_MASK; set_pmd(ti->pmd, __pmd(paddr | _KERNPG_TABLE | _PAGE_PSE)); ti->allocated = 1; __flush_tlb(); adr = ti->address + ((pfn << PAGE_SHIFT) & ~PMD_MASK); *index = i; *phys = pfn * PAGE_SIZE; return adr; } static __init void unmap_low_page(int i) { struct temp_map *ti = &temp_mappings[i]; set_pmd(ti->pmd, __pmd(0)); ti->allocated = 0; } static void __init phys_pud_init(pud_t *pud, unsigned long address, unsigned long end) { long i, j; i = pud_index(address); pud = pud + i; for (; i < PTRS_PER_PUD; pud++, i++) { int map; unsigned long paddr, pmd_phys; pmd_t *pmd; paddr = address + i*PUD_SIZE; if (paddr >= end) { for (; i < PTRS_PER_PUD; i++, pud++) set_pud(pud, __pud(0)); break; } if (!e820_mapped(paddr, paddr+PUD_SIZE, 0)) { set_pud(pud, __pud(0)); continue; } pmd = alloc_low_page(&map, &pmd_phys); set_pud(pud, __pud(pmd_phys | _KERNPG_TABLE)); for (j = 0; j < PTRS_PER_PMD; pmd++, j++, paddr += PMD_SIZE) { unsigned long pe; if (paddr >= end) { for (; j < PTRS_PER_PMD; j++, pmd++) set_pmd(pmd, __pmd(0)); break; } pe = _PAGE_NX|_PAGE_PSE | _KERNPG_TABLE | _PAGE_GLOBAL | paddr; pe &= __supported_pte_mask; set_pmd(pmd, __pmd(pe)); } unmap_low_page(map); } __flush_tlb(); } static void __init find_early_table_space(unsigned long end) { unsigned long puds, pmds, tables; puds = (end + PUD_SIZE - 1) >> PUD_SHIFT; pmds = (end + PMD_SIZE - 1) >> PMD_SHIFT; tables = round_up(puds * sizeof(pud_t), PAGE_SIZE) + round_up(pmds * sizeof(pmd_t), PAGE_SIZE); table_start = find_e820_area(0x8000, __pa_symbol(&_text), tables); if (table_start == -1UL) panic("Cannot find space for the kernel page tables"); table_start >>= PAGE_SHIFT; table_end = table_start; } /* Setup the direct mapping of the physical memory at PAGE_OFFSET. This runs before bootmem is initialized and gets pages directly from the physical memory. To access them they are temporarily mapped. */ void __init init_memory_mapping(unsigned long start, unsigned long end) { unsigned long next; Dprintk("init_memory_mapping\n"); /* * Find space for the kernel direct mapping tables. * Later we should allocate these tables in the local node of the memory * mapped. Unfortunately this is done currently before the nodes are * discovered. */ find_early_table_space(end); start = (unsigned long)__va(start); end = (unsigned long)__va(end); for (; start < end; start = next) { int map; unsigned long pud_phys; pud_t *pud = alloc_low_page(&map, &pud_phys); next = start + PGDIR_SIZE; if (next > end) next = end; phys_pud_init(pud, __pa(start), __pa(next)); set_pgd(pgd_offset_k(start), mk_kernel_pgd(pud_phys)); unmap_low_page(map); } asm volatile("movq %%cr4,%0" : "=r" (mmu_cr4_features)); __flush_tlb_all(); early_printk("kernel direct mapping tables upto %lx @ %lx-%lx\n", end, table_start<<PAGE_SHIFT, table_end<<PAGE_SHIFT); } extern struct x8664_pda cpu_pda[NR_CPUS]; /* Assumes all CPUs still execute in init_mm */ void zap_low_mappings(void) { pgd_t *pgd = pgd_offset_k(0UL); pgd_clear(pgd); flush_tlb_all(); } #ifndef CONFIG_DISCONTIGMEM void __init paging_init(void) { { unsigned long zones_size[MAX_NR_ZONES] = {0, 0, 0}; unsigned int max_dma; max_dma = virt_to_phys((char *)MAX_DMA_ADDRESS) >> PAGE_SHIFT; if (end_pfn < max_dma) zones_size[ZONE_DMA] = end_pfn; else { zones_size[ZONE_DMA] = max_dma; zones_size[ZONE_NORMAL] = end_pfn - max_dma; } free_area_init(zones_size); } return; } #endif /* Unmap a kernel mapping if it exists. This is useful to avoid prefetches from the CPU leading to inconsistent cache lines. address and size must be aligned to 2MB boundaries. Does nothing when the mapping doesn't exist. */ void __init clear_kernel_mapping(unsigned long address, unsigned long size) { unsigned long end = address + size; BUG_ON(address & ~LARGE_PAGE_MASK); BUG_ON(size & ~LARGE_PAGE_MASK); for (; address < end; address += LARGE_PAGE_SIZE) { pgd_t *pgd = pgd_offset_k(address); pud_t *pud; pmd_t *pmd; if (pgd_none(*pgd)) continue; pud = pud_offset(pgd, address); if (pud_none(*pud)) continue; pmd = pmd_offset(pud, address); if (!pmd || pmd_none(*pmd)) continue; if (0 == (pmd_val(*pmd) & _PAGE_PSE)) { /* Could handle this, but it should not happen currently. */ printk(KERN_ERR "clear_kernel_mapping: mapping has been split. will leak memory\n"); pmd_ERROR(*pmd); } set_pmd(pmd, __pmd(0)); } __flush_tlb_all(); } static inline int page_is_ram (unsigned long pagenr) { int i; for (i = 0; i < e820.nr_map; i++) { unsigned long addr, end; if (e820.map[i].type != E820_RAM) /* not usable memory */ continue; /* * !!!FIXME!!! Some BIOSen report areas as RAM that * are not. Notably the 640->1Mb area. We need a sanity * check here. */ addr = (e820.map[i].addr+PAGE_SIZE-1) >> PAGE_SHIFT; end = (e820.map[i].addr+e820.map[i].size) >> PAGE_SHIFT; if ((pagenr >= addr) && (pagenr < end)) return 1; } return 0; } extern int swiotlb_force; static struct kcore_list kcore_mem, kcore_vmalloc, kcore_kernel, kcore_modules, kcore_vsyscall; void __init mem_init(void) { int codesize, reservedpages, datasize, initsize; int tmp; #ifdef CONFIG_SWIOTLB if (swiotlb_force) swiotlb = 1; if (!iommu_aperture && (end_pfn >= 0xffffffff>>PAGE_SHIFT || force_iommu)) swiotlb = 1; if (swiotlb) swiotlb_init(); #endif /* How many end-of-memory variables you have, grandma! */ max_low_pfn = end_pfn; max_pfn = end_pfn; num_physpages = end_pfn; high_memory = (void *) __va(end_pfn * PAGE_SIZE); /* clear the zero-page */ memset(empty_zero_page, 0, PAGE_SIZE); reservedpages = 0; /* this will put all low memory onto the freelists */ #ifdef CONFIG_DISCONTIGMEM totalram_pages += numa_free_all_bootmem(); tmp = 0; /* should count reserved pages here for all nodes */ #else max_mapnr = end_pfn; if (!mem_map) BUG(); totalram_pages += free_all_bootmem(); for (tmp = 0; tmp < end_pfn; tmp++) /* * Only count reserved RAM pages */ if (page_is_ram(tmp) && PageReserved(pfn_to_page(tmp))) reservedpages++; #endif after_bootmem = 1; codesize = (unsigned long) &_etext - (unsigned long) &_text; datasize = (unsigned long) &_edata - (unsigned long) &_etext; initsize = (unsigned long) &__init_end - (unsigned long) &__init_begin; /* Register memory areas for /proc/kcore */ kclist_add(&kcore_mem, __va(0), max_low_pfn << PAGE_SHIFT); kclist_add(&kcore_vmalloc, (void *)VMALLOC_START, VMALLOC_END-VMALLOC_START); kclist_add(&kcore_kernel, &_stext, _end - _stext); kclist_add(&kcore_modules, (void *)MODULES_VADDR, MODULES_LEN); kclist_add(&kcore_vsyscall, (void *)VSYSCALL_START, VSYSCALL_END - VSYSCALL_START); printk("Memory: %luk/%luk available (%dk kernel code, %dk reserved, %dk data, %dk init)\n", (unsigned long) nr_free_pages() << (PAGE_SHIFT-10), end_pfn << (PAGE_SHIFT-10), codesize >> 10, reservedpages << (PAGE_SHIFT-10), datasize >> 10, initsize >> 10); /* * Subtle. SMP is doing its boot stuff late (because it has to * fork idle threads) - but it also needs low mappings for the * protected-mode entry to work. We zap these entries only after * the WP-bit has been tested. */ #ifndef CONFIG_SMP zap_low_mappings(); #endif } extern char __initdata_begin[], __initdata_end[]; void free_initmem(void) { unsigned long addr; addr = (unsigned long)(&__init_begin); for (; addr < (unsigned long)(&__init_end); addr += PAGE_SIZE) { ClearPageReserved(virt_to_page(addr)); set_page_count(virt_to_page(addr), 1); memset((void *)(addr & ~(PAGE_SIZE-1)), 0xcc, PAGE_SIZE); free_page(addr); totalram_pages++; } memset(__initdata_begin, 0xba, __initdata_end - __initdata_begin); printk ("Freeing unused kernel memory: %luk freed\n", (&__init_end - &__init_begin) >> 10); } #ifdef CONFIG_BLK_DEV_INITRD void free_initrd_mem(unsigned long start, unsigned long end) { if (start < (unsigned long)&_end) return; printk ("Freeing initrd memory: %ldk freed\n", (end - start) >> 10); for (; start < end; start += PAGE_SIZE) { ClearPageReserved(virt_to_page(start)); set_page_count(virt_to_page(start), 1); free_page(start); totalram_pages++; } } #endif void __init reserve_bootmem_generic(unsigned long phys, unsigned len) { /* Should check here against the e820 map to avoid double free */ #ifdef CONFIG_DISCONTIGMEM int nid = phys_to_nid(phys); reserve_bootmem_node(NODE_DATA(nid), phys, len); #else reserve_bootmem(phys, len); #endif } int kern_addr_valid(unsigned long addr) { unsigned long above = ((long)addr) >> __VIRTUAL_MASK_SHIFT; pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (above != 0 && above != -1UL) return 0; pgd = pgd_offset_k(addr); if (pgd_none(*pgd)) return 0; pud = pud_offset(pgd, addr); if (pud_none(*pud)) return 0; pmd = pmd_offset(pud, addr); if (pmd_none(*pmd)) return 0; if (pmd_large(*pmd)) return pfn_valid(pmd_pfn(*pmd)); pte = pte_offset_kernel(pmd, addr); if (pte_none(*pte)) return 0; return pfn_valid(pte_pfn(*pte)); } #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> extern int exception_trace, page_fault_trace; static ctl_table debug_table2[] = { { 99, "exception-trace", &exception_trace, sizeof(int), 0644, NULL, proc_dointvec }, #ifdef CONFIG_CHECKING { 100, "page-fault-trace", &page_fault_trace, sizeof(int), 0644, NULL, proc_dointvec }, #endif { 0, } }; static ctl_table debug_root_table2[] = { { .ctl_name = CTL_DEBUG, .procname = "debug", .mode = 0555, .child = debug_table2 }, { 0 }, }; static __init int x8664_sysctl_init(void) { register_sysctl_table(debug_root_table2, 1); return 0; } __initcall(x8664_sysctl_init); #endif /* A pseudo VMAs to allow ptrace access for the vsyscall page. This only covers the 64bit vsyscall page now. 32bit has a real VMA now and does not need special handling anymore. */ static struct vm_area_struct gate_vma = { .vm_start = VSYSCALL_START, .vm_end = VSYSCALL_END, .vm_page_prot = PAGE_READONLY }; struct vm_area_struct *get_gate_vma(struct task_struct *tsk) { #ifdef CONFIG_IA32_EMULATION if (test_tsk_thread_flag(tsk, TIF_IA32)) return NULL; #endif return &gate_vma; } int in_gate_area(struct task_struct *task, unsigned long addr) { struct vm_area_struct *vma = get_gate_vma(task); if (!vma) return 0; return (addr >= vma->vm_start) && (addr < vma->vm_end); } /* Use this when you have no reliable task/vma, typically from interrupt * context. It is less reliable than using the task's vma and may give * false positives. */ int in_gate_area_no_task(unsigned long addr) { return (addr >= VSYSCALL_START) && (addr < VSYSCALL_END); }
xtreamerdev/linux-xtr
arch/x86_64/mm/init.c
C
gpl-2.0
15,773
/* Copyright (C) 2006 - 2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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 */ /* ScriptData SDName: Boss_Doctor_Theolen_Krastinov SD%Complete: 100 SDComment: SDCategory: Scholomance EndScriptData */ #include "precompiled.h" #include "def_scholomance.h" #define SPELL_REND 18106 #define SPELL_CLEAVE 15584 #define SPELL_FRENZY 28371 struct TRINITY_DLL_DECL boss_theolenkrastinovAI : public ScriptedAI { boss_theolenkrastinovAI(Creature *c) : ScriptedAI(c) {} uint32 Rend_Timer; uint32 Cleave_Timer; uint32 Frenzy_Timer; void Reset() { Rend_Timer = 8000; Cleave_Timer = 9000; Frenzy_Timer =0; } void JustDied(Unit *killer) { ScriptedInstance *pInstance = (m_creature->GetInstanceData()) ? ((ScriptedInstance*)m_creature->GetInstanceData()) : NULL; if(pInstance) { pInstance->SetData(DATA_DOCTORTHEOLENKRASTINOV_DEATH, 0); if(pInstance->GetData(DATA_CANSPAWNGANDLING)) m_creature->SummonCreature(1853, 180.73, -9.43856, 75.507, 1.61399, TEMPSUMMON_DEAD_DESPAWN, 0); } } void Aggro(Unit *who) { } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; //Rend_Timer if (Rend_Timer < diff) { DoCast(m_creature->getVictim(),SPELL_REND); Rend_Timer = 10000; }else Rend_Timer -= diff; //Cleave_Timer if (Cleave_Timer < diff) { DoCast(m_creature->getVictim(),SPELL_CLEAVE); Cleave_Timer = 10000; }else Cleave_Timer -= diff; //Frenzy_Timer if ( m_creature->GetHealth()*100 / m_creature->GetMaxHealth() < 26 ) { if (Frenzy_Timer < diff) { DoCast(m_creature,SPELL_FRENZY); DoTextEmote("goes into a killing frenzy!",NULL); Frenzy_Timer = 8000; }else Frenzy_Timer -= diff; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_theolenkrastinov(Creature *_Creature) { return new boss_theolenkrastinovAI (_Creature); } void AddSC_boss_theolenkrastinov() { Script *newscript; newscript = new Script; newscript->Name="boss_doctor_theolen_krastinov"; newscript->GetAI = &GetAI_boss_theolenkrastinov; newscript->RegisterSelf(); }
ForsakenMyst/trinityzero
src/bindings/scripts/scripts/zone/scholomance/boss_doctor_theolen_krastinov.cpp
C++
gpl-2.0
3,128
<?php /** * NoNumber Framework Helper File: Assignments: PHP * * @package NoNumber Framework * @version 15.4.3 * * @author Peter van Westen <[email protected]> * @link http://www.nonumber.nl * @copyright Copyright © 2015 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; require_once JPATH_PLUGINS . '/system/nnframework/helpers/assignment.php'; class nnFrameworkAssignmentsPHP extends nnFrameworkAssignment { function passPHP() { $article = $this->article; if (!is_array($this->selection)) { $this->selection = array($this->selection); } $pass = false; foreach ($this->selection as $php) { // replace \n with newline and other fix stuff $php = str_replace('\|', '|', $php); $php = preg_replace('#(?<!\\\)\\\n#', "\n", $php); $php = trim(str_replace('[:REGEX_ENTER:]', '\n', $php)); if ($php == '') { $pass = true; break; } if (!$article && strpos($php, '$article') !== false) { $article = ''; if ($this->request->option == 'com_content' && $this->request->view == 'article') { require_once JPATH_SITE . '/components/com_content/models/article.php'; $model = JModelLegacy::getInstance('article', 'contentModel'); $article = $model->getItem($this->request->id); } } if (!isset($Itemid)) { $Itemid = JFactory::getApplication()->input->getInt('Itemid', 0); } if (!isset($mainframe)) { $mainframe = JFactory::getApplication(); } if (!isset($app)) { $app = JFactory::getApplication(); } if (!isset($document)) { $document = JFactory::getDocument(); } if (!isset($doc)) { $doc = JFactory::getDocument(); } if (!isset($database)) { $database = JFactory::getDBO(); } if (!isset($db)) { $db = JFactory::getDBO(); } if (!isset($user)) { $user = JFactory::getUser(); } $php .= ';return true;'; $temp_PHP_func = create_function('&$article, &$Itemid, &$mainframe, &$app, &$document, &$doc, &$database, &$db, &$user', $php); // evaluate the script ob_start(); $pass = (bool) $temp_PHP_func($article, $Itemid, $mainframe, $app, $document, $doc, $database, $db, $user); unset($temp_PHP_func); ob_end_clean(); if ($pass) { break; } } return $this->pass($pass); } }
marcialsoto/cienciactiva
plugins/system/nnframework/helpers/assignments/php.php
PHP
gpl-2.0
2,419
/* * android vibrator driver (msm7x27, Motor IC) * * Copyright (C) 2009 LGE, Inc. * * Author: Jinkyu Choi <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/platform_device.h> #include <mach/gpio.h> #include <linux/of_gpio.h> #include <linux/delay.h> #include <linux/timer.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/stat.h> #include "../staging/android/timed_output.h" #include <linux/lge_sm100.h> #include <mach/msm_iomap.h> #include <linux/io.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/regulator/machine.h> /* gpio and clock control for vibrator */ #define REG_WRITEL(value, reg) writel(value, reg) #define REG_READL(reg) readl(reg) static int mmss_cc_n_default; static int mmss_cc_d_max; static int mmss_cc_d_half; static void __iomem *virt_bases_v; #define MMSS_CC_GP1_CMD_RCGR(x) (void __iomem *)(virt_bases_v + (x)) #define MMSS_CC_PWM_SET 0xFC401984 #define MMSS_CC_PWM_SIZE SZ_1K #define DEVICE_NAME "lge_sm100" static DEFINE_MUTEX(vib_lock); struct timed_vibrator_data { struct timed_output_dev dev; struct hrtimer timer; spinlock_t lock; int max_timeout; atomic_t ms_time; /* vibrator duration */ atomic_t vib_status; /* on/off */ atomic_t vibe_gain; /* default max gain */ atomic_t vibe_pwm; atomic_t gp3_clk_flag; int amp; int vibe_n_value; int haptic_en_gpio; int motor_pwm_gpio; int vibe_warmup_delay; /* in ms */ int vpwr_on; struct regulator *vreg_l19; struct work_struct work_vibrator_off; struct work_struct work_vibrator_on; }; static struct clk *gp3_clk; static int vibrator_ic_enable_set(int enable, struct timed_vibrator_data *vib_data) { int gpio; INFO_MSG("[sm100] ic_enable=%d\n", enable); if (enable) gpio_direction_output(vib_data->haptic_en_gpio, 1); else gpio_direction_output(vib_data->haptic_en_gpio, 0); gpio = gpio_get_value(vib_data->haptic_en_gpio); INFO_MSG("[sm100] Haptic_EN_GPIO Value : %d\n", gpio); return 0; } static int vibrator_power_set(int enable, struct timed_vibrator_data *vib_data) { int rc; INFO_MSG("[sm100] pwr_enable = %d\n", enable); mutex_lock(&vib_lock); if (enable) { rc = regulator_enable(vib_data->vreg_l19); if (rc < 0) ERR_MSG("%s: regulator_enable failed\n", __func__); } else { if (regulator_is_enabled(vib_data->vreg_l19) > 0) { rc = regulator_disable(vib_data->vreg_l19); if (rc < 0) ERR_MSG("%s: regulator_disable failed\n", __func__); } } mutex_unlock(&vib_lock); return 0; } static int vibrator_pwm_set(int enable, int amp, int n_value) { /* TODO: set clk for amp */ uint d_val; INFO_MSG("[sm100] amp=%d, n_value=%d\n", amp, n_value); //d_val = ((MMSS_CC_N_DEFAULT * amp) >> 7); d_val = mmss_cc_d_half + (mmss_cc_n_default-1)*amp/256; if (virt_bases_v == NULL) virt_bases_v = ioremap(MMSS_CC_PWM_SET, MMSS_CC_PWM_SIZE); if (enable) { REG_WRITEL( ((~(d_val << 1)) & 0xffU), /* D[7:0] */ MMSS_CC_GP1_CMD_RCGR(0x10)); REG_WRITEL( (1 << 1U) + /* ROOT_EN[1] */ (1), /* UPDATE[0] */ MMSS_CC_GP1_CMD_RCGR(0)); } else { REG_WRITEL( (0 << 1U) + /* ROOT_EN[1] */ (0), /* UPDATE[0] */ MMSS_CC_GP1_CMD_RCGR(0)); } return 0; } #ifdef ANDROID_VIBRATOR_USE_WORKQUEUE static inline void vibrator_work_on(struct work_struct *work) { queue_work(vibrator_workqueue, work); } static inline void vibrator_work_off(struct work_struct *work) { if (!work_pending(work)) queue_work(vibrator_workqueue, work); } #else static inline void vibrator_work_on(struct work_struct *work) { schedule_work(work); } static inline void vibrator_work_off(struct work_struct *work) { if (!work_pending(work)) schedule_work(work); } #endif static int android_vibrator_force_set(struct timed_vibrator_data *vib, int nForce, int n_value) { /* Check the Force value with Max and Min force value */ int vib_duration_ms = 0; INFO_MSG("[sm100] nForce : %d\n", nForce); #if 1 if (nForce > 127) nForce = 127; if (nForce < 0) nForce = 0; #endif if (vib->vibe_warmup_delay > 0) { if (atomic_read(&vib->vib_status)) msleep(vib->vibe_warmup_delay); } /* TODO: control the gain of vibrator */ if (nForce == 0) { vibrator_ic_enable_set(0, vib); vibrator_pwm_set(0, 0, n_value); /* should be checked for vibrator response time */ if (vib->vpwr_on != 1) vibrator_power_set(0, vib); atomic_set(&vib->vib_status, false); } else { if (work_pending(&vib->work_vibrator_off)) cancel_work_sync(&vib->work_vibrator_off); hrtimer_cancel(&vib->timer); vib_duration_ms = atomic_read(&vib->ms_time); /* should be checked for vibrator response time */ if (vib->vpwr_on != 1) vibrator_power_set(1, vib); vibrator_pwm_set(1, nForce, n_value); vibrator_ic_enable_set(1, vib); atomic_set(&vib->vib_status, true); hrtimer_start(&vib->timer, ns_to_ktime((u64)vib_duration_ms * NSEC_PER_MSEC), HRTIMER_MODE_REL); } return 0; } static void android_vibrator_on(struct work_struct *work) { struct timed_vibrator_data *vib = container_of(work, struct timed_vibrator_data, work_vibrator_on); int gain = atomic_read(&vib->vibe_gain); int pwm = atomic_read(&vib->vibe_pwm); /* suspend /resume logging test */ pr_debug("%s: gain = %d pwm = %d\n", __func__, gain, pwm); android_vibrator_force_set(vib, gain, pwm); } static void android_vibrator_off(struct work_struct *work) { struct timed_vibrator_data *vib = container_of(work, struct timed_vibrator_data, work_vibrator_off); android_vibrator_force_set(vib, 0, vib->vibe_n_value); } static enum hrtimer_restart vibrator_timer_func(struct hrtimer *timer) { struct timed_vibrator_data *vib = container_of(timer, struct timed_vibrator_data, timer); vibrator_work_off(&vib->work_vibrator_off); return HRTIMER_NORESTART; } static int vibrator_get_time(struct timed_output_dev *dev) { struct timed_vibrator_data *vib = container_of(dev, struct timed_vibrator_data, dev); if (hrtimer_active(&vib->timer)) { ktime_t r = hrtimer_get_remaining(&vib->timer); return ktime_to_ms(r); } return 0; } static void vibrator_enable(struct timed_output_dev *dev, int value) { struct timed_vibrator_data *vib = container_of(dev, struct timed_vibrator_data, dev); unsigned long flags; spin_lock_irqsave(&vib->lock, flags); if (value > 0) { if (atomic_read(&vib->gp3_clk_flag) == 0) { clk_prepare_enable(gp3_clk); atomic_set(&vib->gp3_clk_flag, 1); } if (value > vib->max_timeout) value = vib->max_timeout; atomic_set(&vib->ms_time, value); vibrator_work_on(&vib->work_vibrator_on); } else { if (atomic_read(&vib->gp3_clk_flag) == 1) { clk_disable_unprepare(gp3_clk); atomic_set(&vib->gp3_clk_flag, 0); } vibrator_work_off(&vib->work_vibrator_off); } spin_unlock_irqrestore(&vib->lock, flags); } static int vibrator_gpio_init(struct timed_vibrator_data *vib_data) { int rc; INFO_MSG("[sm100] vibrator gpio init\n"); rc = gpio_request(vib_data->haptic_en_gpio, "lin_motor_en"); if (rc) { ERR_MSG("GPIO_LIN_MOTOR_EN %d request failed\n", vib_data->haptic_en_gpio); return 0; } /* gpio init */ rc = gpio_request(vib_data->motor_pwm_gpio, "lin_motor_pwm"); if (unlikely(rc < 0)) { ERR_MSG("not able to get gpio %d\n", vib_data->motor_pwm_gpio); return 0; } return 0; } #ifdef CONFIG_OF static void vibrator_parse_dt(struct device *dev, struct timed_vibrator_data *vib_data) { struct device_node *np = dev->of_node; of_property_read_u32(np, "syncoam,vpwr-on", &vib_data->vpwr_on); INFO_MSG("[sm100] vib->vpwr_on : %d!!\n", vib_data->vpwr_on); vib_data->haptic_en_gpio = of_get_named_gpio_flags(np, "syncoam,haptic-pwr-gpio", 0, NULL); vib_data->motor_pwm_gpio = of_get_named_gpio_flags(np, "syncoam,motor-pwm-gpio", 0, NULL); //of_property_read_u32(np, "syncoam,motor-amp", &vib_data->amp); of_property_read_u32(np, "syncoam,n-value", &vib_data->vibe_n_value); INFO_MSG("[sm100] gpio en : %d, pwm : %d, amp : %d, n_value : %d\n", vib_data->haptic_en_gpio, vib_data->motor_pwm_gpio, vib_data->amp, vib_data->vibe_n_value); } #endif static ssize_t vibrator_amp_show(struct device *dev, struct device_attribute *attr, char *buf) { struct timed_output_dev *dev_ = (struct timed_output_dev *)dev_get_drvdata(dev); struct timed_vibrator_data *vib = container_of(dev_, struct timed_vibrator_data, dev); int gain = atomic_read(&(vib->vibe_gain)); return sprintf(buf, "%d\n", gain); } static ssize_t vibrator_amp_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct timed_output_dev *dev_ = (struct timed_output_dev *)dev_get_drvdata(dev); struct timed_vibrator_data *vib = container_of(dev_, struct timed_vibrator_data, dev); int gain; sscanf(buf, "%d", &gain); #if 0 if (gain > 128 || gain < -128) { printk(KERN_ERR "%s invalid value: should be -128 ~ +128\n", __func__); return -EINVAL; } #endif atomic_set(&vib->vibe_gain, gain); return size; } static ssize_t vibrator_pwm_show(struct device *dev, struct device_attribute *attr, char *buf) { struct timed_output_dev *dev_ = (struct timed_output_dev *)dev_get_drvdata(dev); struct timed_vibrator_data *vib = container_of(dev_, struct timed_vibrator_data, dev); int gain = atomic_read(&(vib->vibe_pwm)); return sprintf(buf, "%d\n", gain); } static ssize_t vibrator_pwm_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct timed_output_dev *dev_ = (struct timed_output_dev *)dev_get_drvdata(dev); struct timed_vibrator_data *vib = container_of(dev_, struct timed_vibrator_data, dev); int gain; sscanf(buf, "%d", &gain); atomic_set(&vib->vibe_pwm, gain); return size; } static struct device_attribute sm100_device_attrs[] = { __ATTR(amp, S_IRUGO | S_IWUSR, vibrator_amp_show, vibrator_amp_store), __ATTR(n_val, S_IRUGO | S_IWUSR, vibrator_pwm_show, vibrator_pwm_store), }; struct timed_vibrator_data android_vibrator_data = { .dev.name = "vibrator", .dev.enable = vibrator_enable, .dev.get_time = vibrator_get_time, .max_timeout = 30000, /* max time for vibrator enable 30 sec. */ }; static int android_vibrator_probe(struct platform_device *pdev) { int i, ret = 0; struct timed_vibrator_data *vib; INFO_MSG("[sm100]vibrator probe!\n"); platform_set_drvdata(pdev, &android_vibrator_data); vib = (struct timed_vibrator_data *)platform_get_drvdata(pdev); if (pdev->dev.of_node) { INFO_MSG("[sm100] probe : pdev->dev.of_node\n"); vibrator_parse_dt(&pdev->dev, vib); } if (vib->vpwr_on != 1) { if (!(vib->vreg_l19)) { vib->vreg_l19 = regulator_get(&pdev->dev, "vdd_ana"); if (IS_ERR(vib->vreg_l19)) { ERR_MSG("[sm100] %s: regulator get of pm8941_l21 failed (%ld)\n", __func__, PTR_ERR(vib->vreg_l19)); vib->vreg_l19 = NULL; } } } pdev->dev.init_name = vib->dev.name; INFO_MSG("[sm100] dev->init_name : %s, dev->kobj : %s\n", pdev->dev.init_name, pdev->dev.kobj.name); if (vibrator_gpio_init(vib) < 0) { ERR_MSG("[sm100] Android Vreg, GPIO set failed\n"); return -ENODEV; } mmss_cc_n_default = vib->vibe_n_value; mmss_cc_d_max = mmss_cc_n_default; mmss_cc_d_half = (mmss_cc_n_default >> 1); //vibrator_pwm_set(1, 117, 166); gp3_clk = clk_get(&pdev->dev, "gp3_clk"); clk_set_rate(gp3_clk, 29813); atomic_set(&vib->vibe_gain, vib->amp); /* max value is 128 */ atomic_set(&vib->vibe_pwm, vib->vibe_n_value); atomic_set(&vib->vib_status, false); atomic_set(&vib->gp3_clk_flag, 0); INIT_WORK(&vib->work_vibrator_off, android_vibrator_off); INIT_WORK(&vib->work_vibrator_on, android_vibrator_on); hrtimer_init(&vib->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); vib->timer.function = vibrator_timer_func; spin_lock_init(&vib->lock); ret = timed_output_dev_register(&vib->dev); if (ret < 0) { timed_output_dev_unregister(&vib->dev); return -ENODEV; } for (i = 0; i < ARRAY_SIZE(sm100_device_attrs); i++) { ret = device_create_file(vib->dev.dev, &sm100_device_attrs[i]); if (ret < 0) { timed_output_dev_unregister(&vib->dev); device_remove_file(vib->dev.dev, &sm100_device_attrs[i]); return -ENODEV; } } INFO_MSG("Android Vibrator Initialization was done\n"); return 0; } static int android_vibrator_remove(struct platform_device *pdev) { struct timed_vibrator_data *vib = (struct timed_vibrator_data *)platform_get_drvdata(pdev); INFO_MSG("Android Vibrator Driver Shutdown\n"); android_vibrator_force_set(vib, 0, vib->vibe_n_value); timed_output_dev_unregister(&vib->dev); return 0; } static int android_vibrator_suspend(struct platform_device *pdev, pm_message_t state) { struct timed_vibrator_data *vib; INFO_MSG("Android Vibrator Driver Suspend\n"); vib = (struct timed_vibrator_data *)platform_get_drvdata(pdev); android_vibrator_force_set(vib, 0, vib->vibe_n_value); /* it will be applied after calendar-noti test */ if (atomic_read(&vib->gp3_clk_flag) == 1) { clk_disable_unprepare(gp3_clk); atomic_set(&vib->gp3_clk_flag, 0); } gpio_tlmm_config(GPIO_CFG(vib->motor_pwm_gpio, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(vib->haptic_en_gpio, 0, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), GPIO_CFG_ENABLE); return 0; } static int android_vibrator_resume(struct platform_device *pdev) { struct timed_vibrator_data *vib; INFO_MSG("Android Vibrator Driver Resume\n"); vib = (struct timed_vibrator_data *)platform_get_drvdata(pdev); android_vibrator_force_set(vib, 0, vib->vibe_n_value); gpio_tlmm_config(GPIO_CFG(vib->motor_pwm_gpio, 6, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE); gpio_tlmm_config(GPIO_CFG(vib->haptic_en_gpio, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE); return 0; } static void android_vibrator_shutdown(struct platform_device *pdev) { struct timed_vibrator_data *vib; INFO_MSG("Android Vibrator Driver Shutdown\n"); vib = (struct timed_vibrator_data *)platform_get_drvdata(pdev); android_vibrator_force_set(vib, 0, vib->vibe_n_value); } #ifdef CONFIG_OF static struct of_device_id sm100_match_table[] = { { .compatible = "syncoam,sm100",}, { }, }; #endif static struct platform_driver android_vibrator_driver = { .probe = android_vibrator_probe, .remove = android_vibrator_remove, .shutdown = android_vibrator_shutdown, .suspend = android_vibrator_suspend, .resume = android_vibrator_resume, .driver = { .name = DEVICE_NAME, #ifdef CONFIG_OF .of_match_table = sm100_match_table, #endif }, }; static int __init android_vibrator_init(void) { INFO_MSG("Android Vibrator Driver Init\n"); #ifdef ANDROID_VIBRATOR_USE_WORKQUEUE vibrator_workqueue = create_workqueue("vibrator"); if (!vibrator_workqueue) { ERR_MSG("%s: out of memory\n", __func__); return -ENOMEM; } #endif return platform_driver_register(&android_vibrator_driver); } static void __exit android_vibrator_exit(void) { INFO_MSG("Android Vibrator Driver Exit\n"); #ifdef ANDROID_VIBRATOR_USE_WORKQUEUE if (vibrator_workqueue) destroy_workqueue(vibrator_workqueue); vibrator_workqueue = NULL; #endif platform_driver_unregister(&android_vibrator_driver); } /* to let init lately */ late_initcall_sync(android_vibrator_init); module_exit(android_vibrator_exit); /* MODULE_AUTHOR("LG Electronics Inc."); MODULE_DESCRIPTION("Android Common Vibrator Driver"); MODULE_LICENSE("GPL"); */
siminles/LG-f460s
drivers/misc/lge_sm100.c
C
gpl-2.0
16,056
/***************************************************************************** Copyright (c) 1995, 2009, Innobase Oy. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ /**************************************************//** @file os/os0proc.c The interface to the operating system process control primitives Created 9/30/1995 Heikki Tuuri *******************************************************/ #include "os0proc.h" #ifdef UNIV_NONINL #include "os0proc.ic" #endif #include "ut0mem.h" #include "ut0byte.h" /* FreeBSD for example has only MAP_ANON, Linux has MAP_ANONYMOUS and MAP_ANON but MAP_ANON is marked as deprecated */ #if defined(MAP_ANONYMOUS) #define OS_MAP_ANON MAP_ANONYMOUS #elif defined(MAP_ANON) #define OS_MAP_ANON MAP_ANON #endif UNIV_INTERN ibool os_use_large_pages; /* Large page size. This may be a boot-time option on some platforms */ UNIV_INTERN ulint os_large_page_size; /****************************************************************//** Converts the current process id to a number. It is not guaranteed that the number is unique. In Linux returns the 'process number' of the current thread. That number is the same as one sees in 'top', for example. In Linux the thread id is not the same as one sees in 'top'. @return process id as a number */ UNIV_INTERN ulint os_proc_get_number(void) /*====================*/ { #ifdef __WIN__ return((ulint)GetCurrentProcessId()); #else return((ulint)getpid()); #endif } /****************************************************************//** Allocates large pages memory. @return allocated memory */ UNIV_INTERN void* os_mem_alloc_large( /*===============*/ ulint* n) /*!< in/out: number of bytes */ { void* ptr; ulint size; #if defined HAVE_LARGE_PAGES && defined UNIV_LINUX int shmid; struct shmid_ds buf; if (!os_use_large_pages || !os_large_page_size) { goto skip; } /* Align block size to os_large_page_size */ ut_ad(ut_is_2pow(os_large_page_size)); size = ut_2pow_round(*n + (os_large_page_size - 1), os_large_page_size); shmid = shmget(IPC_PRIVATE, (size_t)size, SHM_HUGETLB | SHM_R | SHM_W); if (shmid < 0) { fprintf(stderr, "InnoDB: HugeTLB: Warning: Failed to allocate" " %lu bytes. errno %d\n", size, errno); ptr = NULL; } else { ptr = shmat(shmid, NULL, 0); if (ptr == (void *)-1) { fprintf(stderr, "InnoDB: HugeTLB: Warning: Failed to" " attach shared memory segment, errno %d\n", errno); ptr = NULL; } /* Remove the shared memory segment so that it will be automatically freed after memory is detached or process exits */ shmctl(shmid, IPC_RMID, &buf); } if (ptr) { *n = size; os_fast_mutex_lock(&ut_list_mutex); ut_total_allocated_memory += size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_ALLOC(ptr, size); return(ptr); } fprintf(stderr, "InnoDB HugeTLB: Warning: Using conventional" " memory pool\n"); skip: #endif /* HAVE_LARGE_PAGES && UNIV_LINUX */ #ifdef __WIN__ SYSTEM_INFO system_info; GetSystemInfo(&system_info); /* Align block size to system page size */ ut_ad(ut_is_2pow(system_info.dwPageSize)); /* system_info.dwPageSize is only 32-bit. Casting to ulint is required on 64-bit Windows. */ size = *n = ut_2pow_round(*n + (system_info.dwPageSize - 1), (ulint) system_info.dwPageSize); ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!ptr) { fprintf(stderr, "InnoDB: VirtualAlloc(%lu bytes) failed;" " Windows error %lu\n", (ulong) size, (ulong) GetLastError()); } else { os_fast_mutex_lock(&ut_list_mutex); ut_total_allocated_memory += size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_ALLOC(ptr, size); } #elif defined __NETWARE__ || !defined OS_MAP_ANON size = *n; ptr = ut_malloc_low(size, TRUE, FALSE); #else # ifdef HAVE_GETPAGESIZE size = getpagesize(); # else size = UNIV_PAGE_SIZE; # endif /* Align block size to system page size */ ut_ad(ut_is_2pow(size)); size = *n = ut_2pow_round(*n + (size - 1), size); ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, -1, 0); if (UNIV_UNLIKELY(ptr == (void*) -1)) { fprintf(stderr, "InnoDB: mmap(%lu bytes) failed;" " errno %lu\n", (ulong) size, (ulong) errno); ptr = NULL; } else { os_fast_mutex_lock(&ut_list_mutex); ut_total_allocated_memory += size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_ALLOC(ptr, size); } #endif return(ptr); } /****************************************************************//** Frees large pages memory. */ UNIV_INTERN void os_mem_free_large( /*==============*/ void *ptr, /*!< in: pointer returned by os_mem_alloc_large() */ ulint size) /*!< in: size returned by os_mem_alloc_large() */ { os_fast_mutex_lock(&ut_list_mutex); ut_a(ut_total_allocated_memory >= size); os_fast_mutex_unlock(&ut_list_mutex); #if defined HAVE_LARGE_PAGES && defined UNIV_LINUX if (os_use_large_pages && os_large_page_size && !shmdt(ptr)) { os_fast_mutex_lock(&ut_list_mutex); ut_a(ut_total_allocated_memory >= size); ut_total_allocated_memory -= size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_FREE(ptr, size); return; } #endif /* HAVE_LARGE_PAGES && UNIV_LINUX */ #ifdef __WIN__ /* When RELEASE memory, the size parameter must be 0. Do not use MEM_RELEASE with MEM_DECOMMIT. */ if (!VirtualFree(ptr, 0, MEM_RELEASE)) { fprintf(stderr, "InnoDB: VirtualFree(%p, %lu) failed;" " Windows error %lu\n", ptr, (ulong) size, (ulong) GetLastError()); } else { os_fast_mutex_lock(&ut_list_mutex); ut_a(ut_total_allocated_memory >= size); ut_total_allocated_memory -= size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_FREE(ptr, size); } #elif defined __NETWARE__ || !defined OS_MAP_ANON ut_free(ptr); #else if (munmap(ptr, size)) { fprintf(stderr, "InnoDB: munmap(%p, %lu) failed;" " errno %lu\n", ptr, (ulong) size, (ulong) errno); } else { os_fast_mutex_lock(&ut_list_mutex); ut_a(ut_total_allocated_memory >= size); ut_total_allocated_memory -= size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_FREE(ptr, size); } #endif }
Abner-Sun/vx_mysql5.1_git
storage/innodb_plugin/os/os0proc.c
C
gpl-2.0
6,771
/* ** Copyright (C) 1998-2006 George Tzanetakis <[email protected]> ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef MARSYAS_NOISESOURCE_H #define MARSYAS_NOISESOURCE_H #include <marsyas/system/MarSystem.h> #include <cstdlib> namespace Marsyas { /** \class NoiseSource \ingroup Synthesis \brief Creates noise */ class NoiseSource: public MarSystem { private: realvec wavetable_; mrs_real wavetableSize_; mrs_real index_; mrs_real mode_; void addControls(); void myUpdate(MarControlPtr sender); public: NoiseSource(std::string name); ~NoiseSource(); MarSystem* clone() const; void myProcess(realvec& in, realvec& out); }; }//namespace Marsyas #endif /* !MARSYAS_NOISESOURCE_H */
eriser/marsyas
src/marsyas/marsystems/NoiseSource.h
C
gpl-2.0
1,399
/** * @file * * IPv6 version of ICMP, as per RFC 4443. */ /* * Copyright (c) 2010 Inico Technologies Ltd. * 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. * * This file is part of the lwIP TCP/IP stack. * * Author: Ivan Delamer <[email protected]> * * * Please coordinate changes and requests with Ivan Delamer * <[email protected]> */ #include "lwip/opt.h" #if LWIP_ICMP6 && LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */ #include "lwip/icmp6.h" #include "lwip/ip6.h" #include "lwip/ip6_addr.h" #include "lwip/inet_chksum.h" #include "lwip/pbuf.h" #include "lwip/netif.h" #include "lwip/nd6.h" #include "lwip/mld6.h" #include "lwip/stats.h" #include <string.h> #ifndef LWIP_ICMP6_DATASIZE #define LWIP_ICMP6_DATASIZE 8 #endif #if LWIP_ICMP6_DATASIZE == 0 #define LWIP_ICMP6_DATASIZE 8 #endif /* Forward declarations */ static void icmp6_send_response(struct pbuf *p, u8_t code, u32_t data, u8_t type); /** * Process an input ICMPv6 message. Called by ip6_input. * * Will generate a reply for echo requests. Other messages are forwarded * to nd6_input, or mld6_input. * * @param p the mld packet, p->payload pointing to the icmpv6 header * @param inp the netif on which this packet was received */ void icmp6_input(struct pbuf *p, struct netif *inp) { struct icmp6_hdr *icmp6hdr; struct pbuf * r; ip6_addr_t * reply_src; ICMP6_STATS_INC(icmp6.recv); /* Check that ICMPv6 header fits in payload */ if (p->len < sizeof(struct icmp6_hdr)) { /* drop short packets */ pbuf_free(p); ICMP6_STATS_INC(icmp6.lenerr); ICMP6_STATS_INC(icmp6.drop); return; } icmp6hdr = (struct icmp6_hdr *)p->payload; #if LWIP_ICMP6_CHECKSUM_CHECK if (ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->tot_len, ip6_current_src_addr(), ip6_current_dest_addr()) != 0) { /* Checksum failed */ pbuf_free(p); ICMP6_STATS_INC(icmp6.chkerr); ICMP6_STATS_INC(icmp6.drop); return; } #endif /* LWIP_ICMP6_CHECKSUM_CHECK */ switch (icmp6hdr->type) { case ICMP6_TYPE_NA: /* Neighbor advertisement */ case ICMP6_TYPE_NS: /* Neighbor solicitation */ case ICMP6_TYPE_RA: /* Router advertisement */ case ICMP6_TYPE_RD: /* Redirect */ case ICMP6_TYPE_PTB: /* Packet too big */ nd6_input(p, inp); return; break; case ICMP6_TYPE_RS: #if LWIP_IPV6_FORWARD /* TODO implement router functionality */ #endif break; #if LWIP_IPV6_MLD case ICMP6_TYPE_MLQ: case ICMP6_TYPE_MLR: case ICMP6_TYPE_MLD: mld6_input(p, inp); return; break; #endif case ICMP6_TYPE_EREQ: #if !LWIP_MULTICAST_PING /* multicast destination address? */ if (ip6_addr_ismulticast(ip6_current_dest_addr())) { /* drop */ pbuf_free(p); ICMP6_STATS_INC(icmp6.drop); return; } #endif /* LWIP_MULTICAST_PING */ /* Allocate reply. */ r = pbuf_alloc(PBUF_IP, p->tot_len, PBUF_RAM); if (r == NULL) { /* drop */ pbuf_free(p); ICMP6_STATS_INC(icmp6.memerr); return; } /* Copy echo request. */ if (pbuf_copy(r, p) != ERR_OK) { /* drop */ pbuf_free(p); pbuf_free(r); ICMP6_STATS_INC(icmp6.err); return; } /* Determine reply source IPv6 address. */ reply_src = ip6_select_source_address(inp, ip6_current_src_addr()); if (reply_src == NULL) { /* drop */ pbuf_free(p); pbuf_free(r); ICMP6_STATS_INC(icmp6.rterr); return; } /* Set fields in reply. */ ((struct icmp6_echo_hdr *)(r->payload))->type = ICMP6_TYPE_EREP; ((struct icmp6_echo_hdr *)(r->payload))->chksum = 0; ((struct icmp6_echo_hdr *)(r->payload))->chksum = ip6_chksum_pseudo(r, IP6_NEXTH_ICMP6, r->tot_len, reply_src, ip6_current_src_addr()); /* Send reply. */ ICMP6_STATS_INC(icmp6.xmit); ip6_output_if(r, reply_src, ip6_current_src_addr(), LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6, inp); pbuf_free(r); break; default: ICMP6_STATS_INC(icmp6.proterr); ICMP6_STATS_INC(icmp6.drop); break; } pbuf_free(p); } /** * Send an icmpv6 'destination unreachable' packet. * * @param p the input packet for which the 'unreachable' should be sent, * p->payload pointing to the IPv6 header * @param c ICMPv6 code for the unreachable type */ void icmp6_dest_unreach(struct pbuf *p, enum icmp6_dur_code c) { icmp6_send_response(p, c, 0, ICMP6_TYPE_DUR); } /** * Send an icmpv6 'packet too big' packet. * * @param p the input packet for which the 'packet too big' should be sent, * p->payload pointing to the IPv6 header * @param mtu the maximum mtu that we can accept */ void icmp6_packet_too_big(struct pbuf *p, u32_t mtu) { icmp6_send_response(p, 0, mtu, ICMP6_TYPE_PTB); } /** * Send an icmpv6 'time exceeded' packet. * * @param p the input packet for which the 'unreachable' should be sent, * p->payload pointing to the IPv6 header * @param c ICMPv6 code for the time exceeded type */ void icmp6_time_exceeded(struct pbuf *p, enum icmp6_te_code c) { icmp6_send_response(p, c, 0, ICMP6_TYPE_TE); } /** * Send an icmpv6 'parameter problem' packet. * * @param p the input packet for which the 'param problem' should be sent, * p->payload pointing to the IP header * @param c ICMPv6 code for the param problem type * @param pointer the pointer to the byte where the parameter is found */ void icmp6_param_problem(struct pbuf *p, enum icmp6_pp_code c, u32_t pointer) { icmp6_send_response(p, c, pointer, ICMP6_TYPE_PP); } /** * Send an ICMPv6 packet in response to an incoming packet. * * @param p the input packet for which the response should be sent, * p->payload pointing to the IPv6 header * @param code Code of the ICMPv6 header * @param data Additional 32-bit parameter in the ICMPv6 header * @param type Type of the ICMPv6 header */ static void icmp6_send_response(struct pbuf *p, u8_t code, u32_t data, u8_t type) { struct pbuf *q; struct icmp6_hdr *icmp6hdr; ip6_addr_t * reply_src; /* ICMPv6 header + IPv6 header + data */ q = pbuf_alloc(PBUF_IP, sizeof(struct icmp6_hdr) + IP6_HLEN + LWIP_ICMP6_DATASIZE, PBUF_RAM); if (q == NULL) { LWIP_DEBUGF(ICMP_DEBUG, ("icmp_time_exceeded: failed to allocate pbuf for ICMPv6 packet.\n")); ICMP6_STATS_INC(icmp6.memerr); return; } LWIP_ASSERT("check that first pbuf can hold icmp 6message", (q->len >= (sizeof(struct icmp6_hdr) + IP6_HLEN + LWIP_ICMP6_DATASIZE))); icmp6hdr = (struct icmp6_hdr *)q->payload; icmp6hdr->type = type; icmp6hdr->code = code; icmp6hdr->data = data; /* copy fields from original packet */ SMEMCPY((u8_t *)q->payload + sizeof(struct icmp6_hdr), (u8_t *)p->payload, IP6_HLEN + LWIP_ICMP6_DATASIZE); /* Select an address to use as source. */ reply_src = ip6_select_source_address(ip_current_netif(), ip6_current_src_addr()); if (reply_src == NULL) { /* drop */ pbuf_free(q); ICMP6_STATS_INC(icmp6.rterr); return; } /* calculate checksum */ icmp6hdr->chksum = 0; icmp6hdr->chksum = ip6_chksum_pseudo(q, IP6_NEXTH_ICMP6, q->tot_len, reply_src, ip6_current_src_addr()); ICMP6_STATS_INC(icmp6.xmit); ip6_output(q, reply_src, ip6_current_src_addr(), LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6); pbuf_free(q); } #endif /* LWIP_ICMP6 && LWIP_IPV6 */
MicroTrustRepos/microkernel
src/l4/pkg/lwip/lib/contrib/src/core/ipv6/icmp6.c
C
gpl-2.0
8,780
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en_GB" xml:lang="en_GB"> <head> <title>Custom QuickIcons - Individual Icons/Menus</title> <link href="help.css" rel="stylesheet" type="text/css" media="all" /> <meta name="copyright" content="(C) 2006/07/08 www.joomx.com All rights reserved." /> <meta name="license" content="http://www.joomx.com GNU/GPL" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <div id="jxbody"> <h1 class="jx_h1">Custom QuickIcons - Overview</h1> <div class="jx_close"> <a href="http://joomlacode.org/gf/project/joomx/" target="_blank" title="CQI-Project">Latest Version</a> </div> <div class="jx_spacer"></div> <div class="jx_tip"> CQI exists of 2 parts: this component <strong>and</strong> the module. <br /> The module can be published at 2 positions: <ol> <li>icon (replaces the original module quickicons and is standard)</li> <li>cpanel (is then visible with other modules at the right side)</li> </ol> An additional way of publishing is, to copy the module and publish both (at icon and cpanel), but with diferent icons and access levels. </div> <div class="jx_header">Toolbar</div> <div class="jx_text"> <ul> <li> <span class="li_header">Save</span> <br /> Save actual projet and go back to overview </li> <li> <span class="li_header">Apply</span> <br /> Save actual project but stay in same site </li> <li> <span class="li_header">Cancel</span> <br /> Back to previous menu - without saving! </li> <li> <span class="li_header">MediaMgr</span> <br /> Upload images with the mediamanager </li> <li> <span class="li_header">Help</span> <br /> This document </li> </ul> </div> <div class="jx_header">Menutabs</div> <div class="jx_text">Settings can be defined in following menus:</div> <div class="jx_text"> <ul> <li> <span class="li_header">General</span> <ul> <li> <span class="li_header">Target</span> <br /> Define here the target (link) for the menuitem (after index2.php) - will be automatically finished by the system<br /> <div class="jx_tip">If external links shall be called only absolute Links are allowed (like: http://www.link.xxx)</div> </li> <li> <span class="li_header">New Window</span> <br /> Shall the link be opened in a new window </li> <li> <span class="li_header">Activated</span> <br /> Is this menu published? </li> <li> <span class="li_header">Order</span> <br /> New menus will be <strong>automatically</strong> at first position (not changeable!). <br /> After saving the reordering can be made </li> <li> <span class="li_header">Access</span> <br /> Define here which usergroups have access to this menuitem - access levels can be redefinded <div class="jx_tip">Only usergroups with access to the backend are visible.</div> <div class="jx_warning"><span class="jx_warningHeader">Warning:</span> After installing this component, all menuitems have access only for the Superadmin, which means only the menuitems are only visible and clickable for the Superadmin </div> </li> <li> <span class="li_header">User</span> <br /> You can define this icon to only one (1) user, it will be usable further only for this user <div class="jx_warning"><span class="jx_warningHeader">Attention:</span> This setting has priority against the group! </div> </li> </ul> </li> </ul> </div> <div class="jx_spacer"></div> <div class="jx_text"> <ul> <li> <span class="li_header">Text</span> <ul> <li> <span class="li_header">Prefix</span> <br /> Each menuitem can be defined with a text prefix (bold, italian, underline, etc. </li> <li> <span class="li_header">Text</span> <br /> Text as it will appear within the module. Shorter is better! Additional text can be defined under Title </li> <li> <span class="li_header">Predefined formats for the text</span> <br /> <strong>Bold</strong>, <em>Italian</em>, <span style="text-decoration:underline;">Underline</span> <div class="jx_tip">Every combination of valid HTML.tags can be used</div> </li> <li> <span class="li_header">Suffix</span> <br /> Final suffix for the text <div class="jx_warning"><span class="jx_warningHeader">Warning:</span> Wrong settings can block the display of the menu item! </div> </li> <li> <span class="li_header">Shortcut</span> <br /> For users with disabilities a shortcut (or access key) should be defined. To be used also instead of clicking the menu item with the mouse<br /> Shortcuts will be called by the keyboard with ALT + [character]<br /> These shortcuts must be unique - avoid to define 2 menus with the same shortcut </li> <li> <span class="li_header">Title</span> <br /> Text which will be shown if you hoover over the menuitem You can define additional text with a description to the menuitem - not longer than 60 chars </li> </ul> </li> </ul> </div> <div class="jx_spacer"></div> <div class="jx_text"> <ul> <li> <span class="li_header">View</span> <ul> <li> <span class="li_header">View as</span> <br /> 3 settings are possible: <ul> <li>Icon &amp; Text (Standard)</li> <li>Only Icon</li> <li>Only Text</li> </ul> </li> <li> <span class="li_header">Imagefolder</span> <br /> Here you can see all image folder found in your CMS as selectable dropdown <li> <span class="li_header">Icon</span> <br /> Choose which icon shall be displayed (opens new window)<br /> <div class="jx_tip">With the dropdown <strong>Imagefolder</strong> you can choose the directory. <br /> <strong>Tip</strong>: use the Mediamanager to create an own directory with your icons</div> <div class="jx_warning"><span class="jx_warningHeader">Attention:</span> If you called the mediamanager to create (and upload new images), you have to call CQI egain from the menu otherwise you will not see the new directory in the dropdown list! </div> </li> </ul> </li> </ul> </div> <div class="jx_spacer"></div> <div class="jx_text"> <ul> <li> <span class="li_header">Check</span> <ul> <li> <span class="li_header">Check Component</span> <br /> If a component is deleted, with this check an error can be avoided.<br /> If set to Yes, before the link (icon) is displayed the component will be checked if valid and installed </li> <li> <span class="li_header">Name &amp; Path</span> <br /> If previous setting is set to yes, define here the internal path to this component, e.g. customquickicons/admin.custumquickicons.php will be finished by the system to:<br /> <em>../administrator/components/com_customquickicons/admin.customquickicons.php</em> </li> </ul> </li> </ul> </div> <div class="jx_text"> <ul> <li> <span class="li_header">About</span> <br /> Some about this component </li> </ul> </div> <div class="jx_docinfo">Doc.Info: v.1.5 - 2008.09.18</div> <div class="jx_close"> <a href="javascript:void(0);" onClick="window.close();" title="Close Window">Close Window</a> &nbsp;|&nbsp; <a href="http://joomlacode.org/gf/project/joomx/" target="_blank" title="CQI-Project">Latest Version</a> </div> </div> </body> </html>
rafarubert/megafiltros
administrator/components/com_customquickicons/help/en-GB/screen.cquickicons.config.html
HTML
gpl-2.0
8,484
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, [email protected] Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Ray Shan (SNL) ------------------------------------------------------------------------- */ #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include "pair_coul_debye_kokkos.h" #include "kokkos.h" #include "atom_kokkos.h" #include "comm.h" #include "force.h" #include "neighbor.h" #include "neigh_list.h" #include "neigh_request.h" #include "update.h" #include "integrate.h" #include "respa.h" #include "math_const.h" #include "memory_kokkos.h" #include "error.h" #include "atom_masks.h" using namespace LAMMPS_NS; using namespace MathConst; #define KOKKOS_CUDA_MAX_THREADS 256 #define KOKKOS_CUDA_MIN_BLOCKS 8 /* ---------------------------------------------------------------------- */ template<class DeviceType> PairCoulDebyeKokkos<DeviceType>::PairCoulDebyeKokkos(LAMMPS *lmp):PairCoulDebye(lmp) { respa_enable = 0; atomKK = (AtomKokkos *) atom; execution_space = ExecutionSpaceFromDevice<DeviceType>::space; datamask_read = X_MASK | F_MASK | TYPE_MASK | Q_MASK | ENERGY_MASK | VIRIAL_MASK; datamask_modify = F_MASK | ENERGY_MASK | VIRIAL_MASK; cutsq = NULL; } /* ---------------------------------------------------------------------- */ template<class DeviceType> PairCoulDebyeKokkos<DeviceType>::~PairCoulDebyeKokkos() { if (!copymode) { memoryKK->destroy_kokkos(k_cutsq, cutsq); } } /* ---------------------------------------------------------------------- */ template<class DeviceType> void PairCoulDebyeKokkos<DeviceType>::cleanup_copy() { // WHY needed: this prevents parent copy from deallocating any arrays allocated = 0; cutsq = NULL; eatom = NULL; vatom = NULL; } /* ---------------------------------------------------------------------- */ template<class DeviceType> void PairCoulDebyeKokkos<DeviceType>::compute(int eflag_in, int vflag_in) { eflag = eflag_in; vflag = vflag_in; if (neighflag == FULL) no_virial_fdotr_compute = 1; if (eflag || vflag) ev_setup(eflag,vflag,0); else evflag = vflag_fdotr = 0; // reallocate per-atom arrays if necessary if (eflag_atom) { memoryKK->destroy_kokkos(k_eatom,eatom); memoryKK->create_kokkos(k_eatom,eatom,maxeatom,"pair:eatom"); d_eatom = k_eatom.view<DeviceType>(); } if (vflag_atom) { memoryKK->destroy_kokkos(k_vatom,vatom); memoryKK->create_kokkos(k_vatom,vatom,maxvatom,6,"pair:vatom"); d_vatom = k_vatom.view<DeviceType>(); } atomKK->sync(execution_space,datamask_read); k_cutsq.template sync<DeviceType>(); k_cut_ljsq.template sync<DeviceType>(); k_cut_coulsq.template sync<DeviceType>(); k_params.template sync<DeviceType>(); if (eflag || vflag) atomKK->modified(execution_space,datamask_modify); else atomKK->modified(execution_space,F_MASK); x = atomKK->k_x.view<DeviceType>(); c_x = atomKK->k_x.view<DeviceType>(); f = atomKK->k_f.view<DeviceType>(); q = atomKK->k_q.view<DeviceType>(); type = atomKK->k_type.view<DeviceType>(); nlocal = atom->nlocal; nall = atom->nlocal + atom->nghost; special_lj[0] = force->special_lj[0]; special_lj[1] = force->special_lj[1]; special_lj[2] = force->special_lj[2]; special_lj[3] = force->special_lj[3]; special_coul[0] = force->special_coul[0]; special_coul[1] = force->special_coul[1]; special_coul[2] = force->special_coul[2]; special_coul[3] = force->special_coul[3]; qqrd2e = force->qqrd2e; newton_pair = force->newton_pair; // loop over neighbors of my atoms copymode = 1; EV_FLOAT ev = pair_compute<PairCoulDebyeKokkos<DeviceType>,void > (this,(NeighListKokkos<DeviceType>*)list); if (eflag) { eng_vdwl += ev.evdwl; eng_coul += ev.ecoul; } if (vflag_global) { virial[0] += ev.v[0]; virial[1] += ev.v[1]; virial[2] += ev.v[2]; virial[3] += ev.v[3]; virial[4] += ev.v[4]; virial[5] += ev.v[5]; } if (eflag_atom) { k_eatom.template modify<DeviceType>(); k_eatom.template sync<LMPHostType>(); } if (vflag_atom) { k_vatom.template modify<DeviceType>(); k_vatom.template sync<LMPHostType>(); } if (vflag_fdotr) pair_virial_fdotr_compute(this); copymode = 0; } /* ---------------------------------------------------------------------- compute coulomb pair force between atoms i and j ---------------------------------------------------------------------- */ template<class DeviceType> template<bool STACKPARAMS, class Specialisation> KOKKOS_INLINE_FUNCTION F_FLOAT PairCoulDebyeKokkos<DeviceType>:: compute_fcoul(const F_FLOAT& rsq, const int& i, const int&j, const int& itype, const int& jtype, const F_FLOAT& factor_coul, const F_FLOAT& qtmp) const { const F_FLOAT r2inv = 1.0/rsq; const F_FLOAT rinv = sqrt(r2inv); const F_FLOAT r = 1.0/rinv; const F_FLOAT screening = exp(-kappa*r); F_FLOAT forcecoul; forcecoul = qqrd2e * qtmp * q(j) * screening * (kappa + rinv) * (STACKPARAMS?m_params[itype][jtype].scale:params(itype,jtype).scale); return factor_coul*forcecoul*r2inv; } /* ---------------------------------------------------------------------- compute coulomb pair potential energy between atoms i and j ---------------------------------------------------------------------- */ template<class DeviceType> template<bool STACKPARAMS, class Specialisation> KOKKOS_INLINE_FUNCTION F_FLOAT PairCoulDebyeKokkos<DeviceType>:: compute_ecoul(const F_FLOAT& rsq, const int& i, const int&j, const int& itype, const int& jtype, const F_FLOAT& factor_coul, const F_FLOAT& qtmp) const { const F_FLOAT r2inv = 1.0/rsq; const F_FLOAT rinv = sqrt(r2inv); const F_FLOAT r = 1.0/rinv; const F_FLOAT screening = exp(-kappa*r); return factor_coul * qqrd2e * qtmp * q(j) * rinv * screening * (STACKPARAMS?m_params[itype][jtype].scale:params(itype,jtype).scale); } /* ---------------------------------------------------------------------- allocate all arrays ------------------------------------------------------------------------- */ template<class DeviceType> void PairCoulDebyeKokkos<DeviceType>::allocate() { PairCoulDebye::allocate(); int n = atom->ntypes; memory->destroy(cutsq); memoryKK->create_kokkos(k_cutsq,cutsq,n+1,n+1,"pair:cutsq"); d_cutsq = k_cutsq.template view<DeviceType>(); k_params = Kokkos::DualView<params_coul**,Kokkos::LayoutRight,DeviceType>("PairCoulDebye::params",n+1,n+1); params = k_params.template view<DeviceType>(); } /* ---------------------------------------------------------------------- global settings ------------------------------------------------------------------------- */ template<class DeviceType> void PairCoulDebyeKokkos<DeviceType>::settings(int narg, char **arg) { if (narg > 2) error->all(FLERR,"Illegal pair_style command"); kappa = force->numeric(FLERR,arg[0]); cut_global = force->numeric(FLERR,arg[1]); // reset cutoffs that have been explicitly set if (allocated) { int i,j; for (i = 1; i <= atom->ntypes; i++) for (j = i; j <= atom->ntypes; j++) if (setflag[i][j]) cut[i][j] = cut_global; } } /* ---------------------------------------------------------------------- init specific to this pair style ------------------------------------------------------------------------- */ template<class DeviceType> void PairCoulDebyeKokkos<DeviceType>::init_style() { PairCoulDebye::init_style(); // error if rRESPA with inner levels if (update->whichflag == 1 && strstr(update->integrate_style,"respa")) { int respa = 0; if (((Respa *) update->integrate)->level_inner >= 0) respa = 1; if (((Respa *) update->integrate)->level_middle >= 0) respa = 2; if (respa) error->all(FLERR,"Cannot use Kokkos pair style with rRESPA inner/middle"); } // irequest = neigh request made by parent class neighflag = lmp->kokkos->neighflag; int irequest = neighbor->nrequest - 1; neighbor->requests[irequest]-> kokkos_host = Kokkos::Impl::is_same<DeviceType,LMPHostType>::value && !Kokkos::Impl::is_same<DeviceType,LMPDeviceType>::value; neighbor->requests[irequest]-> kokkos_device = Kokkos::Impl::is_same<DeviceType,LMPDeviceType>::value; if (neighflag == FULL) { neighbor->requests[irequest]->full = 1; neighbor->requests[irequest]->half = 0; } else if (neighflag == HALF || neighflag == HALFTHREAD) { neighbor->requests[irequest]->full = 0; neighbor->requests[irequest]->half = 1; } else if (neighflag == N2) { neighbor->requests[irequest]->full = 0; neighbor->requests[irequest]->half = 0; } else { error->all(FLERR,"Cannot use chosen neighbor list style with coul/debye/kk"); } } /* ---------------------------------------------------------------------- init for one type pair i,j and corresponding j,i ------------------------------------------------------------------------- */ template<class DeviceType> double PairCoulDebyeKokkos<DeviceType>::init_one(int i, int j) { double cutone = PairCoulDebye::init_one(i,j); k_params.h_view(i,j).scale = scale[i][j]; k_params.h_view(i,j).cutsq = cutone*cutone; k_params.h_view(j,i) = k_params.h_view(i,j); if(i<MAX_TYPES_STACKPARAMS+1 && j<MAX_TYPES_STACKPARAMS+1) { m_params[i][j] = m_params[j][i] = k_params.h_view(i,j); m_cutsq[j][i] = m_cutsq[i][j] = cutone*cutone; m_cut_ljsq[j][i] = m_cut_ljsq[i][j] = cutone*cutone; m_cut_coulsq[j][i] = m_cut_coulsq[i][j] = cutone*cutone; } k_cutsq.h_view(i,j) = cutone*cutone; k_cutsq.template modify<LMPHostType>(); //k_cut_ljsq.h_view(i,j) = cutone*cutone; k_cut_ljsq.template modify<LMPHostType>(); //k_cut_coulsq.h_view(i,j) = cutone*cutone; k_cut_coulsq.template modify<LMPHostType>(); k_params.template modify<LMPHostType>(); return cutone; } namespace LAMMPS_NS { template class PairCoulDebyeKokkos<LMPDeviceType>; #ifdef KOKKOS_HAVE_CUDA template class PairCoulDebyeKokkos<LMPHostType>; #endif }
junghans/lammps
src/KOKKOS/pair_coul_debye_kokkos.cpp
C++
gpl-2.0
10,603
/* * strcspn */ #include "strxspn.h" size_t strcspn(const char *s, const char *reject) { return __strxspn(s, reject, 1); }
carlobar/uclinux_leon3_UD
user/klibc/usr/klibc/strcspn.c
C
gpl-2.0
128
/* Multiple versions of lrintf. Copyright (C) 2013-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 <http://www.gnu.org/licenses/>. */ #include <math.h> #include "init-arch.h" /* It's safe to use double-precision implementation for single-precision. */ extern __typeof (__lrintf) __lrint_ppc32 attribute_hidden; extern __typeof (__lrintf) __lrint_power6x attribute_hidden; libc_ifunc (__lrintf, (hwcap & PPC_FEATURE_POWER6_EXT) ? __lrint_power6x : __lrint_ppc32); weak_alias (__lrintf, lrintf)
norov/glibc
sysdeps/powerpc/powerpc32/power4/fpu/multiarch/s_lrintf.c
C
gpl-2.0
1,208
/* Original copyright header listed below. This comes via rsync. Any additional changes are provided via the same license as the original. Copyright (C) 2011 Muhammad Umair */ /* * Copyright (C) 1996-2001 Internet Software Consortium. * * 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 INTERNET SOFTWARE CONSORTIUM * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * INTERNET SOFTWARE CONSORTIUM 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. */ #pragma once #include <cstdio> #include <cstring> #include <iostream> namespace drizzled { namespace type { class IPv6 { struct ipv6_ds { unsigned short ip6[8]; } str; //Function to store the IPv4 address in IPv6 Data Structure int ipv4_inet_pton(const char *src) { char *ptr_src ; char ipv4_map_ipv6[20], ipv4[16], octet_1[5], octet_2[5], concat_octets[20]; int octet[4], octet_index = 0 , dot_count = 0; static const char hex[] = "0123456789"; const char * char_ptr_src; memset(ipv4_map_ipv6, 0, sizeof(ipv4_map_ipv6)); strcpy(ipv4_map_ipv6, src); memset(octet, 0, sizeof(octet)); memset(ipv4, 0, sizeof(ipv4)); memset(octet_1, 0, sizeof(octet_1)); memset(octet_2, 0, sizeof(octet_2)); memset(concat_octets, 0, sizeof(concat_octets)); ptr_src = ipv4_map_ipv6; if (*ptr_src == ':' && *++ptr_src != ':') return 0; // Invalid IP Address if (*ptr_src == ':' && *++ptr_src == ':') ++ptr_src; strcpy(ipv4,ptr_src); ptr_src = ipv4; while(*ptr_src != '\0') { dot_count++; if (*ptr_src == '.' && *++ptr_src != '.') { if (dot_count == 1) return 0; // Invalid IP Address } char_ptr_src = strchr (hex, *ptr_src); if(char_ptr_src == NULL) { return 0; // Invalid IP Address } ++ptr_src; } ptr_src = ipv4; while(*ptr_src != '\0') { if ( *ptr_src == ':' && *++ptr_src == '\0') { return 0; // Invalid IP Address } if ( *ptr_src == '.' && *++ptr_src == '\0') { return 0; // Invalid IP Address } ++ptr_src; } ptr_src = strtok(ipv4,"."); while (ptr_src != '\0') { sscanf(ptr_src, "%d", &octet[octet_index]); if(octet[octet_index++] > 255) { return 0; // Invalid IP Address } ptr_src = strtok (NULL, "."); }// end of main while loop if(octet[3] == 0) { octet[3] = octet[2]; octet[2] = octet[1]; octet[1] = octet[0]; octet[0] = 0; } if(octet_index < 3 || octet_index > 4) { return 0; // Invalid IP Address } octet_index = 0; str.ip6[0] = str.ip6[1] = str.ip6[2] = str.ip6[3] = str.ip6[4] = str.ip6[5] = 0; for (int i=6 ; i <= 7; i++) { if (i == 7) { ++octet_index; } sprintf(octet_1, "%02x", octet[octet_index]); sprintf(octet_2, "%02x", octet[++octet_index]); strcpy(concat_octets,octet_1); strcat(concat_octets,octet_2); sscanf(concat_octets,"%x",(unsigned int *)&str.ip6[i]); memset(octet_1, 0, sizeof(octet_1)); memset(octet_2, 0, sizeof(octet_2)); memset(concat_octets, 0, sizeof(concat_octets)); } return 1; }//end of ipv4_inet_pton() function //Function to retain the IPv4 address from IPv6 Data Structure char * ipv4_inet_ntop(char *destination) { memset(destination, 0, sizeof(destination)); snprintf(destination, IPV6_BUFFER_LENGTH, "%03x:%03x:%03x:%03x:%03x:%03x:%03d.%03d.%03d.%03d" , str.ip6[0],str.ip6[1],str.ip6[2],str.ip6[3],str.ip6[4],str.ip6[5], (((unsigned int )str.ip6[6]>>8) & 0xFF), ((unsigned int )str.ip6[6] & 0xFF), (((unsigned int )str.ip6[7]>>8) & 0xFF), ((unsigned int )str.ip6[7] & 0xFF)); return destination; }// end of ipv4_inet_ntop function //Function to store the IPv6 address in IPv6 Data Structure int ipv6_inet_pton(const char *src) { if (strlen(src)> IPV6_DISPLAY_LENGTH) { return 0; //Invalid IPaddress } //Local variables char ipv6[IPV6_BUFFER_LENGTH]; memset(ipv6, 0, IPV6_BUFFER_LENGTH); strcpy(ipv6,src); char ipv6_temp[IPV6_BUFFER_LENGTH], ipv6_temp1[IPV6_BUFFER_LENGTH], ipv6_temp2[IPV6_BUFFER_LENGTH]; memset(ipv6_temp, 0, IPV6_BUFFER_LENGTH); strcpy(ipv6_temp, ipv6); memset(ipv6_temp1, 0, IPV6_BUFFER_LENGTH); strcpy(ipv6_temp1, ipv6); memset(ipv6_temp2, 0, IPV6_BUFFER_LENGTH); strcpy(ipv6_temp2,ipv6); static const char hex[] = "0123456789abcdef"; char temp[IPV6_BUFFER_LENGTH]; char *ptr_src ,*ptr_char, *ptr_src1; const char *char_ptr_src; // get the src char int char_int = 0, index_ip6 = 0, octet_count = 0, not_colon = 0, colon = 0, count_colon = 0; char temp_first[IPV6_BUFFER_LENGTH],temp_end[IPV6_BUFFER_LENGTH]; memset(temp_first, 0, IPV6_BUFFER_LENGTH); memset(temp_end, 0, IPV6_BUFFER_LENGTH); ptr_src = ipv6; //while loop check three consective colons while (*ptr_src != '\0') { if (*ptr_src == ':' && *++ptr_src == ':' && *++ptr_src == ':') { return 0; // Invalid IP Address } ++ptr_src; } ptr_src = ipv6; //Check first colon position while (*ptr_src != '\0') { count_colon++; if (*ptr_src == ':' && *++ptr_src != ':') { if (count_colon == 1) return 0; // Invalid IP Address } ++ptr_src; } ptr_src = ipv6; //Check last colon position while (*ptr_src != '\0') { if ( *ptr_src == ':' && *++ptr_src == '\0') { return 0; // Invalid IP Address } ++ptr_src; } count_colon = 0; //while loop count the total number of octets ptr_src = strtok (ipv6_temp2,":"); while (ptr_src != NULL) { octet_count++; ptr_src = strtok (NULL, ":"); } //Retrun zero if total number of octets are greater than 8 if(octet_count > 8) { return 0 ; // Invalid IP Address } bool colon_flag = true; ptr_src = ipv6; //Check the existance of consective two colons while (*ptr_src != '\0') { if (*ptr_src == ':' && *++ptr_src == ':') { colon_flag = false; } ++ptr_src; } if (colon_flag == true && octet_count < 8) { return 0; } int num_miss_octet =0; num_miss_octet = 8 - octet_count; #if 0 size = 2*num_miss_octet +1; #endif std::string zero_append; ptr_src = ipv6_temp; //while loop locate the "::" position (start,middle or end) while(*ptr_src != '\0') { if(*ptr_src == ':' && *++ptr_src == ':') { if (*++ptr_src=='\0') { colon =2; } else if (not_colon == 0) { colon=1; } else { colon=3; } count_colon++; if(count_colon == 2) { return 0; // Invalid IP Address. Ther must be single time double colon '::' } } ptr_src++; not_colon++; }// end of while loop // if colon = 0 means the IPv6 Address string is in presffered form otherwise first it covert it into prefeered form if(colon>0) { //zero padding format according to the '::' position zero_append+= ""; for (int i= 0; i < num_miss_octet; i++) { if(colon==1) // start { zero_append+= "0:"; } if(colon==2 || colon==3) //middle or end colon =2 shows at end { zero_append+= ":0"; } } if(colon==3) { zero_append+= ":"; } ptr_src = temp_end; if(colon==1 || colon==3) { //only for start and middle ptr_src1 = strstr (ipv6_temp,"::"); ptr_src1 = ptr_src1+2; while(*ptr_src1 != '\0') { *ptr_src++ = *ptr_src1++; if(*ptr_src1 == '\0') { *ptr_src ='\0'; } } } //copy the input IPv6 string before and after '::' ptr_src1 = strstr (ipv6_temp1,"::"); *ptr_src1 ='\0'; strcpy(temp_first,ipv6_temp1); if(colon==2) // end { strcat(temp_first, zero_append.c_str()); } else { strcat(temp_first, zero_append.c_str()); strcat(temp_first,temp_end); } memset(ipv6, 0, IPV6_BUFFER_LENGTH); strcpy(ipv6,temp_first); }// end of main if statement //while loop store each octet on ipv6 struture in decimal value of hexadecimal digits ptr_char = temp; ptr_src = strtok (ipv6,":"); while (ptr_src != NULL) { strcpy(temp, ptr_src); ptr_char = temp; int octet_length = strlen(ptr_char); *(ptr_char + octet_length) = '\0'; while(*ptr_char != '\0') { char_int = tolower(*ptr_char); char_ptr_src = strchr (hex, char_int); if(char_ptr_src == NULL) { return 0; // Invalid IP Address } *ptr_char = *char_ptr_src; ptr_char++; }//end of inner while loop ptr_char -= octet_length; unsigned int ptr_char_val = 0; sscanf(ptr_char, "%x", (unsigned int *)&ptr_char_val); //check if "xxxx" value greater than "ffff=65535" if (ptr_char_val > 65535) { str.ip6[0] = str.ip6[1] = str.ip6[2] = str.ip6[3] = str.ip6[4] = str.ip6[5] = str.ip6[6] = str.ip6[7] = 0; return 0; } unsigned int *ptr = (unsigned int *)&(str.ip6[index_ip6++]); sscanf(ptr_char, "%x", ptr); memset(temp, 0, IPV6_BUFFER_LENGTH); ptr_src = strtok (NULL, ":"); }// end of main while loop return 1; }// end of Ipv6_Inet_pton function //Function to retain the IPv6 address from IPv6 Data Structure char* ipv6_inet_ntop(char *destination) { char temp[10]; memset(temp, 0, sizeof(temp)); memset(destination, 0, IPV6_BUFFER_LENGTH); for (int i= 0; i <= 7; i++) { if(i==7) { sprintf(temp,"%04x",str.ip6[i]); strcat(destination,temp); } else { sprintf(temp,"%04x:",str.ip6[i]); strcat(destination,temp); } memset(temp, 0, sizeof(temp)); } return destination; }// end of Ipv6_Inet_ntop function public: IPv6() { str.ip6[0] = str.ip6[1] = str.ip6[2] = str.ip6[3] = str.ip6[4] = str.ip6[5] = str.ip6[6] = str.ip6[7] = 0; } void store_object(unsigned char *out) { memcpy(out, (unsigned char *)&str, sizeof(str)); } void restore_object(const unsigned char * in) { memcpy(&str, (struct ipv6_ds *)in, sizeof(str)); } int inet_pton(const char *ip) { char * pch; pch=strchr((char *)ip,'.'); if(pch == NULL) { return ipv6_inet_pton(ip); } else { return ipv4_inet_pton(ip); } } char * inet_ntop(char *dest) { if (str.ip6[0]==0 && str.ip6[1]==0 && str.ip6[2]==0 && str.ip6[3]==0 && str.ip6[4]==0 && str.ip6[5]==0 && str.ip6[6]!=0) { return ipv4_inet_ntop(dest); } else { return ipv6_inet_ntop(dest); } } static const size_t LENGTH= 16; static const size_t IPV6_DISPLAY_LENGTH= 39; static const size_t IPV6_BUFFER_LENGTH= IPV6_DISPLAY_LENGTH+1; }; // endof class } /* namespace type */ } /* namespace drizzled */
0xffea/drizzle
drizzled/type/ipv6.h
C
gpl-2.0
13,568
<?php /** * @package Joomla.Platform * @subpackage Form * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Form Rule class for the Joomla Platform. * * @package Joomla.Platform * @subpackage Form * @since 11.1 */ class JFormRuleRules extends JdomClassFormRule { /** * Method to test the value. * * @param SimpleXMLElement $element The SimpleXMLElement object representing the <field /> tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * @param JRegistry $input An optional JRegistry object with the entire data set to validate against the entire form. * @param JForm $form The form object for which the field is being tested. * * @return boolean True if the value is valid, false otherwise. * * @since 11.1 */ public function test(SimpleXMLElement $element, $value, $group = null, JRegistry $input = null, JForm $form = null) { // Get the possible field actions and the ones posted to validate them. $fieldActions = self::getFieldActions($element); $valueActions = self::getValueActions($value); // Make sure that all posted actions are in the list of possible actions for the field. foreach ($valueActions as $action) { if (!in_array($action, $fieldActions)) { return false; } } return true; } /** * Method to get the list of permission action names from the form field value. * * @param mixed $value The form field value to validate. * * @return array A list of permission action names from the form field value. * * @since 11.1 */ protected function getValueActions($value) { $actions = array(); // Iterate over the asset actions and add to the actions. foreach ((array) $value as $name => $rules) { $actions[] = $name; } return $actions; } /** * Method to get the list of possible permission action names for the form field. * * @param SimpleXMLElement $element The SimpleXMLElement object representing the <field /> tag for the * form field object. * * @return array A list of permission action names from the form field element definition. * * @since 11.1 */ protected function getFieldActions(SimpleXMLElement $element) { $actions = array(); // Initialise some field attributes. $section = $element['section'] ? (string) $element['section'] : ''; $component = $element['component'] ? (string) $element['component'] : ''; // Get the asset actions for the element. $elActions = self::getAclActions($component, $section); // Iterate over the asset actions and add to the actions. foreach ($elActions as $item) { $actions[] = $item->name; } // Iterate over the children and add to the actions. foreach ($element->children() as $el) { if ($el->getName() == 'action') { $actions[] = (string) $el['name']; } } return $actions; } /** * Method to return a list of actions for which permissions can be set given a component and section. * * @param string $component The component from which to retrieve the actions. * @param string $section The name of the section within the component from which to retrieve the actions. * * @return array List of actions available for the given component and section. * @since 11.1 */ function getAclActions($component, $section = 'component') { $getAll = $section == '*'; if(strpos($section, ',') !== false){ $section = explode(',',$section); } if(!is_array($section)){ $section = array($section); } $actions = array(); if (is_file(JPATH_ADMINISTRATOR.'/components/'.$component.'/access.xml')) { $xml = simplexml_load_file(JPATH_ADMINISTRATOR.'/components/'.$component.'/access.xml'); foreach ($xml->children() as $child) { $sectionTitle = (string)$child['title']; $sectionTitle = !empty($sectionTitle) ? $sectionTitle : (string) $child['name']; if ($getAll OR in_array((string) $child['name'],$section)) { foreach ($child->children() as $action) { $actions[] = (object) array( 'name' => (string) $action['name'], 'title' => (string) $action['title'], 'description' => (string) $action['description'], 'section' => (string) $child['name'], 'sectionTitle' => $sectionTitle, 'sectionDescription' => (string) $child['description'] ); } } } } return $actions; } }
cifren/blogEnterprise
libraries/jdom/jform/rules/rules.php
PHP
gpl-2.0
4,985
<?php /** * @version: $Id: spinstall.php 4387 2015-02-19 12:24:35Z Radek Suski $ * @package: SobiPro Component for Joomla! * @author * Name: Sigrid Suski & Radek Suski, Sigsiu.NET GmbH * Email: sobi[at]sigsiu.net * Url: http://www.Sigsiu.NET * @copyright Copyright (C) 2006 - 2015 Sigsiu.NET GmbH (http://www.sigsiu.net). All rights reserved. * @license GNU/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 version 3 * as published by the Free Software Foundation, and under the additional terms according section 7 of GPL v3. * See http://www.gnu.org/licenses/gpl.html and http://sobipro.sigsiu.net/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. * $Date: 2015-02-19 13:24:35 +0100 (Thu, 19 Feb 2015) $ * $Revision: 4387 $ * $Author: Radek Suski $ * $HeadURL: file:///opt/svn/SobiPro/Component/branches/SobiPro-1.1/spinstall.php $ */ defined( '_JEXEC' ) || exit( 'Restricted access' ); class com_sobiproInstallerScript { /** * Called before any type of action * * @param string $route Which action is happening (install|uninstall|discover_install) * @param JAdapterInstance $adapter The object responsible for running this script * * @return boolean True on success */ function preflight( $route, JAdapterInstance $adapter ) { if ( $adapter instanceof JInstallerAdapterComponent ) { $this->installPlugins( $adapter->get( 'parent' )->get( 'paths' ) ); } elseif ( $adapter instanceof JInstallerComponent ) { $this->installPlugins( $adapter->get( 'parent' )->get( '_paths' ) ); } // Installing component manifest file version $this->release = $adapter->get( 'manifest' )->version; // Show the essential information at the install/update back-end echo '<h3>Installing SobiPro version ' . $this->release . ' ...'; } /** * method to update the component * @param JAdapterInstance $adapter * @return void */ function update( JAdapterInstance $adapter ) { if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'usr', 'locale' ) ) ) ) { JFolder::delete( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'usr', 'locale' ) ) ); } if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'services', 'installers', 'schemas', 'application.xsd' ) ) ) ) { JFolder::delete( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'services', 'installers', 'schemas', 'application.xsd' ) ) ); } if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'media' ) ) ) ) { JFolder::delete( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'media' ) ) ); } $srcpath = JPATH_ROOT . '/media/sobipro/icons'; if ( file_exists( $srcpath ) ) { $files = scandir( $srcpath ); $dest = JPATH_ROOT . '/media/sobipro/images'; if ( count( $files ) ) { foreach ( $files as $file ) { if ( $file != '.' && $file != '..' ) { if ( is_dir( $srcpath . '/' . $file ) ) { JFolder::copy( $srcpath . '/' . $file, $dest . '/' . $file, '', true ); } elseif ( !( file_exists( $dest . '/' . $file ) ) ) { JFile::copy( $srcpath . '/' . $file, $dest . '/' . $file ); } } } } } $db = JFactory::getDBO(); $db->setQuery( 'CREATE TABLE IF NOT EXISTS `#__sobipro_view_cache` ( `cid` int(11) NOT NULL AUTO_INCREMENT, `section` int(11) NOT NULL, `sid` int(11) NOT NULL, `fileName` varchar(100) NOT NULL, `task` varchar(100) NOT NULL, `site` int(11) NOT NULL, `request` varchar(255) NOT NULL, `language` varchar(15) NOT NULL, `template` varchar(150) NOT NULL, `configFile` text NOT NULL, `userGroups` varchar(200) NOT NULL, `created` datetime NOT NULL,PRIMARY KEY (`cid`),KEY `sid` (`sid`),KEY `section` (`section`),KEY `language` (`language`),KEY `task` (`task`),KEY `request` (`request`),KEY `site` (`site`),KEY `userGroups` (`userGroups`));' ); $db->query(); $db->setQuery( 'CREATE TABLE IF NOT EXISTS `#__sobipro_view_cache_relation` (`cid` int(11) NOT NULL,`sid` int(11) NOT NULL,PRIMARY KEY (`cid`,`sid`));' ); $db->query(); $db->setQuery( "UPDATE #__sobipro_permissions SET value = '*' WHERE pid = 18;" ); $db->query(); $db->setQuery( 'CREATE TABLE IF NOT EXISTS `#__sobipro_user_group` (`description` text,`gid` int(11) NOT NULL AUTO_INCREMENT,`enabled` int(11) NOT NULL,`pid` int(11) NOT NULL,`groupName` varchar(150) NOT NULL,PRIMARY KEY (`gid`) ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=5000 ;' ); $db->query(); $db->setQuery( 'CREATE TABLE IF NOT EXISTS `#__sobipro_counter` ( `sid` INT(11) NOT NULL, `counter` INT(11) NOT NULL, `lastUpdate` DATETIME NOT NULL, PRIMARY KEY (`sid`) );' ); $db->query(); $db->setQuery( 'CREATE TABLE IF NOT EXISTS `#__sobipro_history` ( `revision` varchar(150) NOT NULL, `changedAt` datetime NOT NULL, `uid` int(11) NOT NULL, `userName` varchar(150) NOT NULL, `userEmail` varchar(150) NOT NULL, `change` varchar(150) NOT NULL, `site` enum(\'site\',\'adm\') NOT NULL, `sid` int(11) NOT NULL, `changes` text NOT NULL, `params` text NOT NULL, `reason` text NOT NULL, `language` varchar(50) NOT NULL, PRIMARY KEY (`revision`) ) DEFAULT CHARSET=utf8;' ); $db->query(); $db->setQuery( "INSERT IGNORE INTO `#__sobipro_config` ( `sKey` , `sValue` , `section` , `critical` , `cSection` ) VALUES ( 'engb_preload', '1', '0', NULL , 'lang' )" ); $db->query(); $db->setQuery( "UPDATE #__sobipro_field_option_selected SET `optValue` = REPLACE (`optValue`, '_', '-')" ); $db->query(); $db->setQuery( "UPDATE #__sobipro_field_option SET `optValue` = REPLACE (`optValue`, '_', '-')" ); $db->query(); $db->setQuery( "UPDATE #__sobipro_language SET `sKey` = REPLACE( `sKey` , '_', '-' ) WHERE `oType` = 'field_option'" ); $db->query(); try { $db->setQuery( 'DELETE FROM `#__sobipro_permissions` WHERE `pid` = 5;' ); $db->query(); } catch ( Exception $x ) { } $db->setQuery( 'SHOW INDEX FROM #__sobipro_permissions' ); $cols = $db->loadAssocList(); $skip = false; foreach ( $cols as $col ) { if ( $col[ 'Key_name' ] == 'uniquePermission' ) { $skip = true; continue; } } if ( !( $skip ) ) { $db->setQuery( 'ALTER TABLE `#__sobipro_permissions` ADD UNIQUE `uniquePermission` ( `subject` , `action` , `value` , `site` );' ); $db->query(); } try { $db->setQuery( 'SHOW INDEX FROM #__sobipro_field_data' ); $cols = $db->loadAssocList(); $skip = false; foreach ( $cols as $col ) { if ( $col[ 'Key_name' ] == 'baseData' ) { $skip = true; continue; } } if ( !( $skip ) ) { try { $db->setQuery( 'ALTER TABLE #__sobipro_field_data ENGINE = MYISAM;;' ); $db->query(); } catch ( Exception $x ) { } $db->setQuery( 'ALTER TABLE `#__sobipro_field_data` ADD FULLTEXT `baseData` (`baseData`);' ); $db->query(); } } catch ( Exception $x ) { } $db->setQuery( 'SHOW INDEX FROM #__sobipro_language' ); $cols = $db->loadAssocList(); $skip = false; foreach ( $cols as $col ) { if ( $col[ 'Key_name' ] == 'sValue' ) { $skip = true; continue; } } if ( !( $skip ) ) { try { $db->setQuery( 'ALTER TABLE #__sobipro_language ENGINE = MYISAM;;' ); $db->query(); } catch ( Exception $x ) { } $db->setQuery( 'ALTER TABLE `#__sobipro_language` ADD FULLTEXT `sValue` (`sValue`);' ); $db->query(); } $db->setQuery( "INSERT IGNORE INTO `#__sobipro_registry` (`section`, `key`, `value`, `params`, `description`, `options`) VALUES ('rejections-templates', 'rejection-of-a-new-entry', 'Rejection of a new entry', 'YTo0OntzOjE3OiJ0cmlnZ2VyLnVucHVibGlzaCI7YjoxO3M6MTc6InRyaWdnZXIudW5hcHByb3ZlIjtiOjA7czo5OiJ1bnB1Ymxpc2giO2I6MTtzOjc6ImRpc2NhcmQiO2I6MDt9', '', ''), ('rejections-templates', 'rejection-of-changes', 'Rejection of changes', 'YTo0OntzOjE3OiJ0cmlnZ2VyLnVucHVibGlzaCI7YjowO3M6MTc6InRyaWdnZXIudW5hcHByb3ZlIjtiOjE7czo5OiJ1bnB1Ymxpc2giO2I6MDtzOjc6ImRpc2NhcmQiO2I6MTt9', '', '');" ); $db->query(); $db->setQuery( "INSERT IGNORE INTO `#__sobipro_permissions` (`pid`, `subject`, `action`, `value`, `site`, `published`) VALUES (NULL, 'section', 'search', '*', 'front', 1), (NULL, 'entry', 'delete', 'own', 'front', 1),(NULL, 'entry', 'delete', '*', 'front', 1);" ); $db->query(); $db->setQuery( "INSERT IGNORE INTO `#__sobipro_field_types` (`tid`, `fType`, `tGroup`, `fPos`) VALUES ('category', 'Category', 'special', 11);" ); $db->query(); $db->setQuery( 'CREATE TABLE IF NOT EXISTS `#__sobipro_field_url_clicks` ( `date` datetime NOT NULL, `uid` int(11) NOT NULL, `sid` int(11) NOT NULL, `fid` varchar(50) NOT NULL, `ip` varchar(15) NOT NULL, `section` int(11) NOT NULL, `browserData` text NOT NULL, `osData` text NOT NULL, `humanity` int(3) NOT NULL, PRIMARY KEY (`date`,`sid`,`fid`,`ip`,`section`) );' ); $db->query(); $db->setQuery( "INSERT IGNORE INTO `#__sobipro_plugins` (`pid`, `name`, `version`, `description`, `author`, `authorURL`, `authorMail`, `enabled`, `type`, `depend`) VALUES ('category', 'Category', '1.1', NULL, 'Sigsiu.NET GmbH', 'http://www.sigsiu.net/', '[email protected]', 1, 'field', '');" ); $db->query(); $db->setQuery( "CREATE TABLE IF NOT EXISTS `#__sobipro_crawler` ( `url` varchar(255) NOT NULL,`crid` int(11) NOT NULL AUTO_INCREMENT,`state` tinyint(1) NOT NULL, PRIMARY KEY (`crid`), UNIQUE KEY `url` (`url`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;" ); $db->query(); $db->setQuery( "CREATE TABLE IF NOT EXISTS `#__sobipro_crawler` ( `url` varchar(255) NOT NULL,`crid` int(11) NOT NULL AUTO_INCREMENT,`state` tinyint(1) NOT NULL, PRIMARY KEY (`crid`), UNIQUE KEY `url` (`url`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;" ); $db->query(); $db->setQuery( "INSERT IGNORE INTO `#__sobipro_language` (`sKey`, `sValue`, `section`, `language`, `oType`, `fid`, `id`, `params`, `options`, `explanation`) VALUES ('rejection-of-a-new-entry', 'Entry {entry.name} has been rejected as it does not comply with the rules.\n\n<br/>Rejected by {user.name}\n<br/>at {date%d F Y H:i:s}\n', 0, 'en-GB', 'rejections-templates', 0, 1, '', '', ''), ('rejection-of-changes', 'Changes in {entry.name} discarded as these changes violating rules.\n\n<br/>Rejected by {user.name}\n<br/>at {date%d F Y H:i:s}\n', 0, 'en-GB', 'rejections-templates', 0, 1, '', '', '');" ); $db->query(); // $db->setQuery( 'SELECT pid FROM `#__sobipro_permissions` WHERE subject = "section" AND action = "search";' ); // $pid = $db->loadResult(); // // $db->setQuery( 'SELECT rid FROM #__sobipro_permissions_rules' ); // $rids = $db->loadRowList(); // if ( count( $rids ) ) { // $insert = array(); // foreach ( $rids as $rid ) { // // } // } JFile::move( JPATH_ROOT . '/components/com_sobipro/etc/repos/sobipro_core/repository.1.1.9.xml', JPATH_ROOT . '/components/com_sobipro/etc/repos/sobipro_core/repository.xml' ); echo '<iframe src="index.php?option=com_sobipro&task=requirements&init=1&tmpl=component" style="border: 1px solid #e0e0e0; border-radius: 5px; height: 900px; min-width: 1000px; width: 99%; margin-bottom: 50px; padding-left: 10px;"></iframe>'; } /** * Called on installation * * @param JAdapterInstance $adapter The object responsible for running this script * * @return boolean True on success */ public function install( JAdapterInstance $adapter ) { if ( !( file_exists( implode( '/', array( JPATH_ROOT, 'images', 'sobipro' ) ) ) ) ) { JFolder::create( implode( '/', array( JPATH_ROOT, 'images', 'sobipro' ) ) ); } if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'tmp', 'SampleData', 'entries' ) ) ) ) { JFolder::move( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'tmp', 'SampleData', 'entries' ) ), implode( '/', array( JPATH_ROOT, 'images', 'sobipro', 'entries' ) ) ); } if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'usr', 'locale' ) ) ) ) { JFolder::delete( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'usr', 'locale' ) ) ); } if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'services', 'installers', 'schemas', 'application.xsd' ) ) ) ) { JFolder::delete( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'services', 'installers', 'schemas', 'application.xsd' ) ) ); } if ( file_exists( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'media' ) ) ) ) { JFolder::delete( implode( '/', array( JPATH_ROOT, 'components', 'com_sobipro', 'media' ) ) ); } JFile::move( JPATH_ROOT . '/components/com_sobipro/etc/repos/sobipro_core/repository.1.1.9.xml', JPATH_ROOT . '/components/com_sobipro/etc/repos/sobipro_core/repository.xml' ); $db = JFactory::getDBO(); $db->setQuery( 'SHOW COLUMNS FROM #__sobipro_field_data' ); $cols = $db->loadAssocList( 'Field' ); if ( !( isset( $cols[ 'editLimit' ] ) ) ) { $db->setQuery( 'ALTER TABLE `#__sobipro_field_data` ADD `editLimit` INT( 11 );' ); $db->query(); } echo '<iframe src="index.php?option=com_sobipro&task=requirements&init=1&tmpl=component" style="border: 1px solid #e0e0e0; border-radius: 5px; height: 900px; min-width: 1000px; width: 99%; margin-bottom: 50px; padding-left: 10px;"></iframe>'; } protected function installPlugins( $source ) { $source = $source[ 'source' ]; $plugins = array( 'Header' ); $path = $source . '/Plugins'; $installer = new JInstaller; $db = JFactory::getDBO(); foreach ( $plugins as $plugin ) { $dir = $path . '/' . $plugin; $installer->install( $dir ); $db->setQuery( "UPDATE #__extensions SET enabled = '1' WHERE element = 'sp{$plugin}';" ); $db->query(); } } /** * Called on uninstallation * * @param JAdapterInstance $adapter The object responsible for running this script */ public function uninstall( JAdapterInstance $adapter ) { $db = JFactory::getDBO(); $query = "show tables like '" . $db->getPrefix() . "sobipro_%'"; $db->setQuery( $query ); $tables = $db->loadColumn(); foreach ( $tables as $table ) { $db->setQuery( "DROP TABLE {$table};" ); $db->query(); } JFolder::delete( implode( '/', array( JPATH_ROOT, 'images', 'sobipro' ) ) ); } }
ranrolls/ras-full-portal
administrator/components/com_sobipro/spinstall.php
PHP
gpl-2.0
14,465
/* * libkmod - interface to kernel module operations * * Copyright (C) 2011-2012 ProFUSION embedded systems * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <arpa/inet.h> /* htonl */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <fnmatch.h> #include <assert.h> #include <inttypes.h> #include "libkmod-private.h" #include "libkmod-index.h" #include "macro.h" /* index.c: module index file shared functions for modprobe and depmod */ #define INDEX_CHILDMAX 128 /* Disk format: uint32_t magic = INDEX_MAGIC; uint32_t version = INDEX_VERSION; uint32_t root_offset; (node_offset & INDEX_NODE_MASK) specifies the file offset of nodes: char[] prefix; // nul terminated char first; char last; uint32_t children[last - first + 1]; uint32_t value_count; struct { uint32_t priority; char[] value; // nul terminated } values[value_count]; (node_offset & INDEX_NODE_FLAGS) indicates which fields are present. Empty prefixes are omitted, leaf nodes omit the three child-related fields. This could be optimised further by adding a sparse child format (indicated using a new flag). */ /* Format of node offsets within index file */ enum node_offset { INDEX_NODE_FLAGS = 0xF0000000, /* Flags in high nibble */ INDEX_NODE_PREFIX = 0x80000000, INDEX_NODE_VALUES = 0x40000000, INDEX_NODE_CHILDS = 0x20000000, INDEX_NODE_MASK = 0x0FFFFFFF, /* Offset value */ }; void index_values_free(struct index_value *values) { while (values) { struct index_value *value = values; values = value->next; free(value); } } static int add_value(struct index_value **values, const char *value, unsigned len, unsigned int priority) { struct index_value *v; /* find position to insert value */ while (*values && (*values)->priority < priority) values = &(*values)->next; v = malloc(sizeof(struct index_value) + len + 1); if (!v) return -1; v->next = *values; v->priority = priority; v->len = len; memcpy(v->value, value, len); v->value[len] = '\0'; *values = v; return 0; } static void read_error(void) { fatal("Module index: unexpected error: %s\n" "Try re-running depmod\n", errno ? strerror(errno) : "EOF"); } static int read_char(FILE *in) { int ch; errno = 0; ch = getc_unlocked(in); if (ch == EOF) read_error(); return ch; } static uint32_t read_long(FILE *in) { uint32_t l; errno = 0; if (fread(&l, sizeof(uint32_t), 1, in) <= 0) read_error(); return ntohl(l); } /* * Buffer abstract data type * * Used internally to store the current path during tree traversal. * They help build wildcard key strings to pass to fnmatch(), * as well as building values of matching keys. */ struct buffer { char *bytes; unsigned size; unsigned used; }; #define BUF_STEP (2048) static bool buf_grow(struct buffer *buf, size_t newsize) { void *tmp; size_t sz; if (newsize % BUF_STEP == 0) sz = newsize; else sz = ((newsize / BUF_STEP) + 1) * BUF_STEP; if (buf->size == sz) return true; tmp = realloc(buf->bytes, sz); if (sz > 0 && tmp == NULL) return false; buf->bytes = tmp; buf->size = sz; return true; } static void buf_init(struct buffer *buf) { buf->bytes = NULL; buf->size = 0; buf->used = 0; } static void buf_release(struct buffer *buf) { free(buf->bytes); } /* Destroy buffer and return a copy as a C string */ static char *buf_steal(struct buffer *buf) { char *bytes; bytes = realloc(buf->bytes, buf->used + 1); if (!bytes) { free(buf->bytes); return NULL; } bytes[buf->used] = '\0'; return bytes; } /* Return a C string owned by the buffer (invalidated if the buffer is changed). */ static const char *buf_str(struct buffer *buf) { if (!buf_grow(buf, buf->used + 1)) return NULL; buf->bytes[buf->used] = '\0'; return buf->bytes; } static bool buf_pushchar(struct buffer *buf, char ch) { if (!buf_grow(buf, buf->used + 1)) return false; buf->bytes[buf->used] = ch; buf->used++; return true; } static unsigned buf_pushchars(struct buffer *buf, const char *str) { unsigned i = 0; int ch; while ((ch = str[i])) { buf_pushchar(buf, ch); i++; } return i; } static unsigned buf_freadchars(struct buffer *buf, FILE *in) { unsigned i = 0; int ch; while ((ch = read_char(in))) { if (!buf_pushchar(buf, ch)) break; i++; } return i; } static void buf_popchar(struct buffer *buf) { assert(buf->used > 0); buf->used--; } static void buf_popchars(struct buffer *buf, unsigned n) { assert(buf->used >= n); buf->used -= n; } static void buf_clear(struct buffer *buf) { buf->used = 0; } /* * Index file searching */ struct index_node_f { FILE *file; char *prefix; /* path compression */ struct index_value *values; unsigned char first; /* range of child nodes */ unsigned char last; uint32_t children[0]; }; static struct index_node_f *index_read(FILE *in, uint32_t offset) { struct index_node_f *node; char *prefix; int i, child_count = 0; if ((offset & INDEX_NODE_MASK) == 0) return NULL; fseek(in, offset & INDEX_NODE_MASK, SEEK_SET); if (offset & INDEX_NODE_PREFIX) { struct buffer buf; buf_init(&buf); buf_freadchars(&buf, in); prefix = buf_steal(&buf); } else prefix = NOFAIL(strdup("")); if (offset & INDEX_NODE_CHILDS) { char first = read_char(in); char last = read_char(in); child_count = last - first + 1; node = NOFAIL(malloc(sizeof(struct index_node_f) + sizeof(uint32_t) * child_count)); node->first = first; node->last = last; for (i = 0; i < child_count; i++) node->children[i] = read_long(in); } else { node = NOFAIL(malloc(sizeof(struct index_node_f))); node->first = INDEX_CHILDMAX; node->last = 0; } node->values = NULL; if (offset & INDEX_NODE_VALUES) { int value_count; struct buffer buf; const char *value; unsigned int priority; value_count = read_long(in); buf_init(&buf); while (value_count--) { priority = read_long(in); buf_freadchars(&buf, in); value = buf_str(&buf); add_value(&node->values, value, buf.used, priority); buf_clear(&buf); } buf_release(&buf); } node->prefix = prefix; node->file = in; return node; } static void index_close(struct index_node_f *node) { free(node->prefix); index_values_free(node->values); free(node); } struct index_file { FILE *file; uint32_t root_offset; }; /* Failures are silent; modprobe will fall back to text files */ struct index_file *index_file_open(const char *filename) { FILE *file; uint32_t magic, version; struct index_file *new; file = fopen(filename, "re"); if (!file) return NULL; errno = EINVAL; magic = read_long(file); if (magic != INDEX_MAGIC) { fclose(file); return NULL; } version = read_long(file); if (version >> 16 != INDEX_VERSION_MAJOR) { fclose(file); return NULL; } new = NOFAIL(malloc(sizeof(struct index_file))); new->file = file; new->root_offset = read_long(new->file); errno = 0; return new; } void index_file_close(struct index_file *idx) { fclose(idx->file); free(idx); } static struct index_node_f *index_readroot(struct index_file *in) { return index_read(in->file, in->root_offset); } static struct index_node_f *index_readchild(const struct index_node_f *parent, int ch) { if (parent->first <= ch && ch <= parent->last) { return index_read(parent->file, parent->children[ch - parent->first]); } return NULL; } static void index_dump_node(struct index_node_f *node, struct buffer *buf, int fd) { struct index_value *v; int ch, pushed; pushed = buf_pushchars(buf, node->prefix); for (v = node->values; v != NULL; v = v->next) { write_str_safe(fd, buf->bytes, buf->used); write_str_safe(fd, " ", 1); write_str_safe(fd, v->value, strlen(v->value)); write_str_safe(fd, "\n", 1); } for (ch = node->first; ch <= node->last; ch++) { struct index_node_f *child = index_readchild(node, ch); if (!child) continue; buf_pushchar(buf, ch); index_dump_node(child, buf, fd); buf_popchar(buf); } buf_popchars(buf, pushed); index_close(node); } void index_dump(struct index_file *in, int fd, const char *prefix) { struct index_node_f *root; struct buffer buf; buf_init(&buf); buf_pushchars(&buf, prefix); root = index_readroot(in); index_dump_node(root, &buf, fd); buf_release(&buf); } static char *index_search__node(struct index_node_f *node, const char *key, int i) { char *value; struct index_node_f *child; int ch; int j; while(node) { for (j = 0; node->prefix[j]; j++) { ch = node->prefix[j]; if (ch != key[i+j]) { index_close(node); return NULL; } } i += j; if (key[i] == '\0') { value = node->values != NULL ? strdup(node->values[0].value) : NULL; index_close(node); return value; } child = index_readchild(node, key[i]); index_close(node); node = child; i++; } return NULL; } /* * Search the index for a key * * Returns the value of the first match * * The recursive functions free their node argument (using index_close). */ char *index_search(struct index_file *in, const char *key) { // FIXME: return value by reference instead of strdup struct index_node_f *root; char *value; root = index_readroot(in); value = index_search__node(root, key, 0); return value; } /* Level 4: add all the values from a matching node */ static void index_searchwild__allvalues(struct index_node_f *node, struct index_value **out) { struct index_value *v; for (v = node->values; v != NULL; v = v->next) add_value(out, v->value, v->len, v->priority); index_close(node); } /* * Level 3: traverse a sub-keyspace which starts with a wildcard, * looking for matches. */ static void index_searchwild__all(struct index_node_f *node, int j, struct buffer *buf, const char *subkey, struct index_value **out) { int pushed = 0; int ch; while (node->prefix[j]) { ch = node->prefix[j]; buf_pushchar(buf, ch); pushed++; j++; } for (ch = node->first; ch <= node->last; ch++) { struct index_node_f *child = index_readchild(node, ch); if (!child) continue; buf_pushchar(buf, ch); index_searchwild__all(child, 0, buf, subkey, out); buf_popchar(buf); } if (node->values) { if (fnmatch(buf_str(buf), subkey, 0) == 0) index_searchwild__allvalues(node, out); else index_close(node); } else { index_close(node); } buf_popchars(buf, pushed); } /* Level 2: descend the tree (until we hit a wildcard) */ static void index_searchwild__node(struct index_node_f *node, struct buffer *buf, const char *key, int i, struct index_value **out) { struct index_node_f *child; int j; int ch; while(node) { for (j = 0; node->prefix[j]; j++) { ch = node->prefix[j]; if (ch == '*' || ch == '?' || ch == '[') { index_searchwild__all(node, j, buf, &key[i+j], out); return; } if (ch != key[i+j]) { index_close(node); return; } } i += j; child = index_readchild(node, '*'); if (child) { buf_pushchar(buf, '*'); index_searchwild__all(child, 0, buf, &key[i], out); buf_popchar(buf); } child = index_readchild(node, '?'); if (child) { buf_pushchar(buf, '?'); index_searchwild__all(child, 0, buf, &key[i], out); buf_popchar(buf); } child = index_readchild(node, '['); if (child) { buf_pushchar(buf, '['); index_searchwild__all(child, 0, buf, &key[i], out); buf_popchar(buf); } if (key[i] == '\0') { index_searchwild__allvalues(node, out); return; } child = index_readchild(node, key[i]); index_close(node); node = child; i++; } } /* * Search the index for a key. The index may contain wildcards. * * Returns a list of all the values of matching keys. */ struct index_value *index_searchwild(struct index_file *in, const char *key) { struct index_node_f *root = index_readroot(in); struct buffer buf; struct index_value *out = NULL; buf_init(&buf); index_searchwild__node(root, &buf, key, 0, &out); buf_release(&buf); return out; } #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> static const char _idx_empty_str[] = ""; /**************************************************************************/ /* * Alternative implementation, using mmap to map all the file to memory when * starting */ struct index_mm { struct kmod_ctx *ctx; void *mm; uint32_t root_offset; size_t size; }; struct index_mm_value { unsigned int priority; unsigned int len; const char *value; }; struct index_mm_value_array { struct index_mm_value *values; unsigned int len; }; struct index_mm_node { struct index_mm *idx; const char *prefix; /* mmape'd value */ struct index_mm_value_array values; unsigned char first; unsigned char last; uint32_t children[]; }; static inline uint32_t read_long_mm(void **p) { uint8_t *addr = *(uint8_t **)p; uint32_t v; /* addr may be unalined to uint32_t */ v = get_unaligned((uint32_t *) addr); *p = addr + sizeof(uint32_t); return ntohl(v); } static inline uint8_t read_char_mm(void **p) { uint8_t *addr = *(uint8_t **)p; uint8_t v = *addr; *p = addr + sizeof(uint8_t); return v; } static inline char *read_chars_mm(void **p, unsigned *rlen) { char *addr = *(char **)p; size_t len = *rlen = strlen(addr); *p = addr + len + 1; return addr; } static struct index_mm_node *index_mm_read_node(struct index_mm *idx, uint32_t offset) { void *p = idx->mm; struct index_mm_node *node; const char *prefix; int i, child_count, value_count, children_padding; uint32_t children[INDEX_CHILDMAX]; char first, last; if ((offset & INDEX_NODE_MASK) == 0) return NULL; p = (char *)p + (offset & INDEX_NODE_MASK); if (offset & INDEX_NODE_PREFIX) { unsigned len; prefix = read_chars_mm(&p, &len); } else prefix = _idx_empty_str; if (offset & INDEX_NODE_CHILDS) { first = read_char_mm(&p); last = read_char_mm(&p); child_count = last - first + 1; for (i = 0; i < child_count; i++) children[i] = read_long_mm(&p); } else { first = INDEX_CHILDMAX; last = 0; child_count = 0; } children_padding = (sizeof(struct index_mm_node) + (sizeof(uint32_t) * child_count)) % sizeof(void *); if (offset & INDEX_NODE_VALUES) value_count = read_long_mm(&p); else value_count = 0; node = malloc(sizeof(struct index_mm_node) + sizeof(uint32_t) * child_count + children_padding + sizeof(struct index_mm_value) * value_count); if (node == NULL) return NULL; node->idx = idx; node->prefix = prefix; if (value_count == 0) node->values.values = NULL; else { node->values.values = (struct index_mm_value *) ((char *)node + sizeof(struct index_mm_node) + sizeof(uint32_t) * child_count + children_padding); } node->values.len = value_count; node->first = first; node->last = last; memcpy(node->children, children, sizeof(uint32_t) * child_count); for (i = 0; i < value_count; i++) { struct index_mm_value *v = node->values.values + i; v->priority = read_long_mm(&p); v->value = read_chars_mm(&p, &v->len); } return node; } static void index_mm_free_node(struct index_mm_node *node) { free(node); } struct index_mm *index_mm_open(struct kmod_ctx *ctx, const char *filename, unsigned long long *stamp) { int fd; struct stat st; struct index_mm *idx; struct { uint32_t magic; uint32_t version; uint32_t root_offset; } hdr; void *p; DBG(ctx, "file=%s\n", filename); idx = malloc(sizeof(*idx)); if (idx == NULL) { ERR(ctx, "malloc: %m\n"); return NULL; } if ((fd = open(filename, O_RDONLY|O_CLOEXEC)) < 0) { DBG(ctx, "open(%s, O_RDONLY|O_CLOEXEC): %m\n", filename); goto fail_open; } fstat(fd, &st); if ((size_t) st.st_size < sizeof(hdr)) goto fail_nommap; if ((idx->mm = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) == MAP_FAILED) { ERR(ctx, "mmap(0, %"PRIu64", PROT_READ, %d, MAP_PRIVATE, 0): %m\n", st.st_size, fd); goto fail_nommap; } p = idx->mm; hdr.magic = read_long_mm(&p); hdr.version = read_long_mm(&p); hdr.root_offset = read_long_mm(&p); if (hdr.magic != INDEX_MAGIC) { ERR(ctx, "magic check fail: %x instead of %x\n", hdr.magic, INDEX_MAGIC); goto fail; } if (hdr.version >> 16 != INDEX_VERSION_MAJOR) { ERR(ctx, "major version check fail: %u instead of %u\n", hdr.version, INDEX_MAGIC); goto fail; } idx->root_offset = hdr.root_offset; idx->size = st.st_size; idx->ctx = ctx; close(fd); *stamp = stat_mstamp(&st); return idx; fail: munmap(idx->mm, st.st_size); fail_nommap: close(fd); fail_open: free(idx); return NULL; } void index_mm_close(struct index_mm *idx) { munmap(idx->mm, idx->size); free(idx); } static struct index_mm_node *index_mm_readroot(struct index_mm *idx) { return index_mm_read_node(idx, idx->root_offset); } static struct index_mm_node *index_mm_readchild(const struct index_mm_node *parent, int ch) { if (parent->first <= ch && ch <= parent->last) { return index_mm_read_node(parent->idx, parent->children[ch - parent->first]); } return NULL; } static void index_mm_dump_node(struct index_mm_node *node, struct buffer *buf, int fd) { struct index_mm_value *itr, *itr_end; int ch, pushed; pushed = buf_pushchars(buf, node->prefix); itr = node->values.values; itr_end = itr + node->values.len; for (; itr < itr_end; itr++) { write_str_safe(fd, buf->bytes, buf->used); write_str_safe(fd, " ", 1); write_str_safe(fd, itr->value, itr->len); write_str_safe(fd, "\n", 1); } for (ch = node->first; ch <= node->last; ch++) { struct index_mm_node *child = index_mm_readchild(node, ch); if (child == NULL) continue; buf_pushchar(buf, ch); index_mm_dump_node(child, buf, fd); buf_popchar(buf); } buf_popchars(buf, pushed); index_mm_free_node(node); } void index_mm_dump(struct index_mm *idx, int fd, const char *prefix) { struct index_mm_node *root; struct buffer buf; buf_init(&buf); buf_pushchars(&buf, prefix); root = index_mm_readroot(idx); index_mm_dump_node(root, &buf, fd); buf_release(&buf); } static char *index_mm_search_node(struct index_mm_node *node, const char *key, int i) { char *value; struct index_mm_node *child; int ch; int j; while(node) { for (j = 0; node->prefix[j]; j++) { ch = node->prefix[j]; if (ch != key[i+j]) { index_mm_free_node(node); return NULL; } } i += j; if (key[i] == '\0') { value = node->values.len > 0 ? strdup(node->values.values[0].value) : NULL; index_mm_free_node(node); return value; } child = index_mm_readchild(node, key[i]); index_mm_free_node(node); node = child; i++; } return NULL; } /* * Search the index for a key * * Returns the value of the first match * * The recursive functions free their node argument (using index_close). */ char *index_mm_search(struct index_mm *idx, const char *key) { // FIXME: return value by reference instead of strdup struct index_mm_node *root; char *value; root = index_mm_readroot(idx); value = index_mm_search_node(root, key, 0); return value; } /* Level 4: add all the values from a matching node */ static void index_mm_searchwild_allvalues(struct index_mm_node *node, struct index_value **out) { struct index_mm_value *itr, *itr_end; itr = node->values.values; itr_end = itr + node->values.len; for (; itr < itr_end; itr++) add_value(out, itr->value, itr->len, itr->priority); index_mm_free_node(node); } /* * Level 3: traverse a sub-keyspace which starts with a wildcard, * looking for matches. */ static void index_mm_searchwild_all(struct index_mm_node *node, int j, struct buffer *buf, const char *subkey, struct index_value **out) { int pushed = 0; int ch; while (node->prefix[j]) { ch = node->prefix[j]; buf_pushchar(buf, ch); pushed++; j++; } for (ch = node->first; ch <= node->last; ch++) { struct index_mm_node *child = index_mm_readchild(node, ch); if (!child) continue; buf_pushchar(buf, ch); index_mm_searchwild_all(child, 0, buf, subkey, out); buf_popchar(buf); } if (node->values.len > 0) { if (fnmatch(buf_str(buf), subkey, 0) == 0) index_mm_searchwild_allvalues(node, out); else index_mm_free_node(node); } else { index_mm_free_node(node); } buf_popchars(buf, pushed); } /* Level 2: descend the tree (until we hit a wildcard) */ static void index_mm_searchwild_node(struct index_mm_node *node, struct buffer *buf, const char *key, int i, struct index_value **out) { struct index_mm_node *child; int j; int ch; while(node) { for (j = 0; node->prefix[j]; j++) { ch = node->prefix[j]; if (ch == '*' || ch == '?' || ch == '[') { index_mm_searchwild_all(node, j, buf, &key[i+j], out); return; } if (ch != key[i+j]) { index_mm_free_node(node); return; } } i += j; child = index_mm_readchild(node, '*'); if (child) { buf_pushchar(buf, '*'); index_mm_searchwild_all(child, 0, buf, &key[i], out); buf_popchar(buf); } child = index_mm_readchild(node, '?'); if (child) { buf_pushchar(buf, '?'); index_mm_searchwild_all(child, 0, buf, &key[i], out); buf_popchar(buf); } child = index_mm_readchild(node, '['); if (child) { buf_pushchar(buf, '['); index_mm_searchwild_all(child, 0, buf, &key[i], out); buf_popchar(buf); } if (key[i] == '\0') { index_mm_searchwild_allvalues(node, out); return; } child = index_mm_readchild(node, key[i]); index_mm_free_node(node); node = child; i++; } } /* * Search the index for a key. The index may contain wildcards. * * Returns a list of all the values of matching keys. */ struct index_value *index_mm_searchwild(struct index_mm *idx, const char *key) { struct index_mm_node *root = index_mm_readroot(idx); struct buffer buf; struct index_value *out = NULL; buf_init(&buf); index_mm_searchwild_node(root, &buf, key, 0, &out); buf_release(&buf); return out; }
SanDisk-Open-Source/SSD_Dashboard
uefi/userspace/kmod/libkmod/libkmod-index.c
C
gpl-2.0
22,798
/* $Id$ */ /** @file * Load Generator. */ /* * Copyright (C) 2007-2014 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #include <iprt/thread.h> #include <iprt/time.h> #include <iprt/initterm.h> #include <iprt/string.h> #include <iprt/stream.h> #include <iprt/param.h> #include <iprt/path.h> #include <iprt/process.h> #include <iprt/mp.h> #include <iprt/asm.h> #include <iprt/getopt.h> #include <VBox/sup.h> /******************************************************************************* * Global Variables * *******************************************************************************/ /** Whether the threads should quit or not. */ static bool volatile g_fQuit = false; static const char *g_pszProgramName = NULL; /******************************************************************************* * Internal Functions * *******************************************************************************/ static int Error(const char *pszFormat, ...); static void LoadGenSpin(uint64_t cNanoSeconds) { const uint64_t u64StartTS = RTTimeNanoTS(); do { for (uint32_t volatile i = 0; i < 10240 && !g_fQuit; i++) i++; } while (RTTimeNanoTS() - u64StartTS < cNanoSeconds && !g_fQuit); } static DECLCALLBACK(int) LoadGenSpinThreadFunction(RTTHREAD hThreadSelf, void *pvUser) { NOREF(hThreadSelf); LoadGenSpin(*(uint64_t *)pvUser); return VINF_SUCCESS; } static int LoadGenIpiInit(void) { /* * Try make sure the support library is initialized... */ SUPR3Init(NULL); /* * Load the module. */ char szPath[RTPATH_MAX]; int rc = RTPathAppPrivateArchTop(szPath, sizeof(szPath) - sizeof("/loadgenerator.r0")); if (RT_SUCCESS(rc)) { strcat(szPath, "/loadgeneratorR0.r0"); void *pvImageBase; rc = SUPR3LoadServiceModule(szPath, "loadgeneratorR0", "LoadGenR0ServiceReqHandler", &pvImageBase); if (RT_SUCCESS(rc)) { /* done */ } else Error("SUPR3LoadServiceModule(%s): %Rrc\n", szPath, rc); } else Error("RTPathAppPrivateArch: %Rrc\n", rc); return rc; } static void LoadGenIpi(uint64_t cNanoSeconds) { const uint64_t u64StartTS = RTTimeNanoTS(); do { int rc = SUPR3CallR0Service("loadgeneratorR0", sizeof("loadgeneratorR0") - 1, 0 /* uOperation */, 1 /* cIpis */, NULL /* pReqHdr */); if (RT_FAILURE(rc)) { Error("SUPR3CallR0Service: %Rrc\n", rc); break; } } while (RTTimeNanoTS() - u64StartTS < cNanoSeconds && !g_fQuit); } static DECLCALLBACK(int) LoadGenIpiThreadFunction(RTTHREAD hThreadSelf, void *pvUser) { LoadGenIpi(*(uint64_t *)pvUser); NOREF(hThreadSelf); return VINF_SUCCESS; } static int Error(const char *pszFormat, ...) { va_list va; RTStrmPrintf(g_pStdErr, "%s: error: ", g_pszProgramName); va_start(va, pszFormat); RTStrmPrintfV(g_pStdErr, pszFormat, va); va_end(va); return 1; } static int SyntaxError(const char *pszFormat, ...) { va_list va; RTStrmPrintf(g_pStdErr, "%s: syntax error: ", g_pszProgramName); va_start(va, pszFormat); RTStrmPrintfV(g_pStdErr, pszFormat, va); va_end(va); return 1; } int main(int argc, char **argv) { static const struct LOADGENTYPE { const char *pszName; int (*pfnInit)(void); PFNRTTHREAD pfnThread; } s_aLoadTypes[] = { { "spin", NULL, LoadGenSpinThreadFunction }, { "ipi", LoadGenIpiInit, LoadGenIpiThreadFunction }, }; unsigned iLoadType = 0; static RTTHREAD s_aThreads[256]; int rc; uint32_t cThreads = 1; bool fScaleByCpus = false; RTTHREADTYPE enmThreadType = RTTHREADTYPE_DEFAULT; RTPROCPRIORITY enmProcPriority = RTPROCPRIORITY_DEFAULT; uint64_t cNanoSeconds = UINT64_MAX; RTR3InitExe(argc, &argv, 0); /* * Set program name. */ g_pszProgramName = RTPathFilename(argv[0]); /* * Parse arguments. */ static const RTGETOPTDEF s_aOptions[] = { { "--number-of-threads", 'n', RTGETOPT_REQ_UINT32 }, { "--timeout", 't', RTGETOPT_REQ_STRING }, { "--thread-type", 'p', RTGETOPT_REQ_STRING }, { "--scale-by-cpus", 'c', RTGETOPT_REQ_NOTHING }, { "--load", 'l', RTGETOPT_REQ_STRING }, }; int ch; RTGETOPTUNION ValueUnion; RTGETOPTSTATE GetState; RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0 /* fFlags */); while ((ch = RTGetOpt(&GetState, &ValueUnion))) { switch (ch) { case 'n': cThreads = ValueUnion.u64; if (cThreads == 0 || cThreads > RT_ELEMENTS(s_aThreads)) return SyntaxError("Requested number of threads, %RU32, is out of range (1..%d).\n", cThreads, RT_ELEMENTS(s_aThreads) - 1); break; case 't': { char *psz; rc = RTStrToUInt64Ex(ValueUnion.psz, &psz, 0, &cNanoSeconds); if (RT_FAILURE(rc)) return SyntaxError("Failed reading the alleged number '%s' (option '%s', rc=%Rrc).\n", ValueUnion.psz, rc); while (*psz == ' ' || *psz == '\t') psz++; if (*psz) { uint64_t u64Factor = 1; if (!strcmp(psz, "ns")) u64Factor = 1; else if (!strcmp(psz, "ms")) u64Factor = 1000; else if (!strcmp(psz, "s")) u64Factor = 1000000000; else if (!strcmp(psz, "m")) u64Factor = UINT64_C(60000000000); else if (!strcmp(psz, "h")) u64Factor = UINT64_C(3600000000000); else return SyntaxError("Unknown time suffix '%s'\n", psz); uint64_t u64 = cNanoSeconds * u64Factor; if (u64 < cNanoSeconds || (u64 < u64Factor && u64)) return SyntaxError("Time representation overflowed! (%RU64 * %RU64)\n", psz, cNanoSeconds, u64Factor); cNanoSeconds = u64; } break; } case 'p': { enmProcPriority = RTPROCPRIORITY_NORMAL; uint32_t u32 = RTTHREADTYPE_INVALID; char *psz; rc = RTStrToUInt32Ex(ValueUnion.psz, &psz, 0, &u32); if (RT_FAILURE(rc) || *psz) { if (!strcmp(ValueUnion.psz, "default")) { enmProcPriority = RTPROCPRIORITY_DEFAULT; enmThreadType = RTTHREADTYPE_DEFAULT; } else if (!strcmp(ValueUnion.psz, "idle")) { enmProcPriority = RTPROCPRIORITY_LOW; enmThreadType = RTTHREADTYPE_INFREQUENT_POLLER; } else if (!strcmp(ValueUnion.psz, "high")) { enmProcPriority = RTPROCPRIORITY_HIGH; enmThreadType = RTTHREADTYPE_IO; } else return SyntaxError("can't grok thread type '%s'\n", ValueUnion.psz); } else { enmThreadType = (RTTHREADTYPE)u32; if (enmThreadType <= RTTHREADTYPE_INVALID || enmThreadType >= RTTHREADTYPE_END) return SyntaxError("thread type '%d' is out of range (%d..%d)\n", ValueUnion.psz, RTTHREADTYPE_INVALID + 1, RTTHREADTYPE_END - 1); } break; } case 'c': fScaleByCpus = true; break; case 'l': { for (unsigned i = 0; i < RT_ELEMENTS(s_aLoadTypes); i++) if (!strcmp(s_aLoadTypes[i].pszName, ValueUnion.psz)) { ValueUnion.psz = NULL; iLoadType = i; break; } if (ValueUnion.psz) return SyntaxError("Unknown load type '%s'.\n", ValueUnion.psz); break; } case 'h': RTStrmPrintf(g_pStdOut, "Usage: %s [-p|--thread-type <type>] [-t|--timeout <sec|xxx[h|m|s|ms|ns]>] \\\n" " %*s [-n|--number-of-threads <threads>] [-l|--load <loadtype>]\n" "\n" "Load types: spin, ipi.\n" , g_pszProgramName, strlen(g_pszProgramName), ""); return 1; case 'V': RTPrintf("$Revision$\n"); return 0; case VINF_GETOPT_NOT_OPTION: return SyntaxError("Unknown argument #%d: '%s'\n", GetState.iNext-1, ValueUnion.psz); default: return RTGetOptPrintError(ch, &ValueUnion); } } /* * Scale thread count by host cpu count. */ if (fScaleByCpus) { const unsigned cCpus = RTMpGetOnlineCount(); if (cCpus * cThreads > RT_ELEMENTS(s_aThreads)) return SyntaxError("Requested number of threads, %RU32, is out of range (1..%d) when scaled by %d.\n", cThreads, RT_ELEMENTS(s_aThreads) - 1, cCpus); cThreads *= cCpus; } /* * Modify process and thread priority? (ignore failure) */ if (enmProcPriority != RTPROCPRIORITY_DEFAULT) RTProcSetPriority(enmProcPriority); if (enmThreadType != RTTHREADTYPE_DEFAULT) RTThreadSetType(RTThreadSelf(), enmThreadType); /* * Load type specific init. */ if (s_aLoadTypes[iLoadType].pfnInit) { rc = s_aLoadTypes[iLoadType].pfnInit(); if (RT_FAILURE(rc)) return 1; } /* * Start threads. */ for (unsigned i = 1; i < cThreads; i++) { s_aThreads[i] = NIL_RTTHREAD; rc = RTThreadCreate(&s_aThreads[i], s_aLoadTypes[iLoadType].pfnThread, &cNanoSeconds, 128*1024, enmThreadType, RTTHREADFLAGS_WAITABLE, "spinner"); if (RT_FAILURE(rc)) { ASMAtomicXchgBool(&g_fQuit, true); RTStrmPrintf(g_pStdErr, "%s: failed to create thread #%d, rc=%Rrc\n", g_pszProgramName, i, rc); while (i-- > 1) RTThreadWait(s_aThreads[i], 1500, NULL); return 1; } } /* our selves */ s_aLoadTypes[iLoadType].pfnThread(RTThreadSelf(), &cNanoSeconds); /* * Wait for threads. */ ASMAtomicXchgBool(&g_fQuit, true); for (unsigned i = 1; i < cThreads; i++) RTThreadWait(s_aThreads[i], 1500, NULL); return 0; }
svn2github/vbox
src/VBox/ValidationKit/utils/misc/loadgenerator.cpp
C++
gpl-2.0
12,772
// Compiler options: -unsafe using System; using System.Runtime.InteropServices; class UnsafeTest { [StructLayout (LayoutKind.Sequential)] public unsafe struct Foo { public Bar* bar; } [StructLayout (LayoutKind.Sequential)] public struct Bar { public Foo foo; } unsafe public static void Main () { Console.WriteLine (sizeof (Foo)); } }
xen2/mcs
tests/test-756.cs
C#
gpl-2.0
357
/* * OpenWIPS-ng server plugin: Fragmentation detection. * Copyright (C) 2011 Thomas d'Otreppe de Bouvette * * 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. * * Author: Thomas d'Otreppe de Bouvette */ #include <stdlib.h> #include <string.h> #include "frame_plugin_header.h" #define NB_ADDRESSES 4 struct frag_attack { unsigned int nb_frames; // TODO: Handle more than one frame and several attacks at the same time unsigned char **addresses; int nb_mac; }; void * init_plugin(char * config_line, int version) { int i; struct frag_attack * fa = (struct frag_attack *)malloc(sizeof(struct frag_attack)); fa->nb_frames = 1; // By default 1 frame is enough (frag should never happen on any network // Allocate memory at startup fa->addresses = (unsigned char **)malloc(sizeof(unsigned char *) * NB_ADDRESSES); for (i = 0; i < NB_ADDRESSES; i++) { fa->addresses[i] = (unsigned char *)malloc(sizeof(unsigned char) * MAC_LEN); } fa->nb_mac = 0; /* if (config_line) { fa->nb_frames = atoi(config_line); if (fa->nb_frames == 0) { fa->nb_frames = 1; } } */ return fa; } void free_memory_and_unload(void * data) { int i; struct frag_attack * fa; if (!data) { return; } fa = (struct frag_attack *)data; for (i = 0; i < NB_ADDRESSES; i++) { free(fa->addresses[i]); } free(fa->addresses); free(fa); } char plugin_type(void) { return PLUGIN_TYPE_FRAME; } int min_supported_version() { return 100; } int max_supported_version() { return 0; } char * init_text(void * config) { struct frag_attack * fa; char * ret = (char *)calloc(1, 80 * sizeof(char)); if (config) { fa = (struct frag_attack *)config; sprintf(ret, "Fragmentation attack detection (with %u frame%s) v1.0", fa->nb_frames, (fa->nb_frames > 1) ? "s" : ""); } else { strcpy(ret, "Fragmentation attack detection v1.0"); } return ret; } int static_frame_type() { // It should only be data frames with data but there can be // an idiot out there to try it on control/management frames too (more frag bit on control) return -1; } int static_frame_subtype() { return -1; } int need_all_frames() { return 0; } int is_single_frame_attack() { // No because it depends on the config but currently it is return 1; } int require_packet_parsed() { return 1; } int can_use_frame(struct pcap_packet * packet, void * config) { if (packet == NULL || packet->info == NULL || config == NULL) { return 0; } return 1; } int analyze(struct pcap_packet * packet, void * config) { if (packet == NULL || packet->info == NULL || config == NULL) { return 0; } return packet->info->fragment_nr || packet->info->more_frag; } int nb_frames_before_analyzing(void * config) { struct frag_attack * fa; if (config) { fa = (struct frag_attack *)config; return fa->nb_frames; } return 1; } int time_ms_before_analyzing(void * config) { if (config) { } return NO_TIME_CONSTRAINT; } int is_attacked(struct pcap_packet * packet_list, void * config) { int counter; struct frag_attack * fa; int ret = analyze(packet_list, config); if (packet_list == NULL || packet_list->info == NULL || config == NULL || ret == 0) { return 0; } // TODO: Make sure we can handle multiple attacks at the same time when more than 1 frame is required (the amount of frame PER attack). // Do a chained list and same logic like another plugin. // Keep attacker info in the structure counter = 0; fa = (struct frag_attack *)config; // Copy MACs if (packet_list->info->address1) { memcpy(fa->addresses[counter++], packet_list->info->address1, MAC_LEN); } if (packet_list->info->address2) { memcpy(fa->addresses[counter++], packet_list->info->address2, MAC_LEN); } if (packet_list->info->address3) { memcpy(fa->addresses[counter++], packet_list->info->address3, MAC_LEN); } if (packet_list->info->address4) { memcpy(fa->addresses[counter++], packet_list->info->address4, MAC_LEN); } fa->nb_mac = counter; return ret; } char * attack_details(void * config) { int i; struct frag_attack * fa; char * ret; if (config == NULL) { return NULL; } fa = (struct frag_attack *)config; ret = (char *)calloc(1, 100 + (fa->nb_mac * 3 * MAC_LEN)); strcpy(ret, "ALERT - Fragmentation attack in progress"); if (fa->nb_mac) { // TODO: Only the calling thread should reveal the mac since the plugin doesn't do any check on it. strcat(ret, ". MAC Addresses involved:"); for (i = 0; i < fa->nb_mac; i++) { sprintf(ret + strlen(ret), " %02X:%02X:%02X:%02X:%02X:%02X", fa->addresses[i][0], fa->addresses[i][1], fa->addresses[i][2], fa->addresses[i][3], fa->addresses[i][4], fa->addresses[i][5]); } } return ret; } unsigned char ** get_attacker_macs(void * config, int * nb_mac, int * deauth) { int i; unsigned char ** macs; struct frag_attack * fa; int counter = 0; if (config == NULL) { return NULL; } fa = (struct frag_attack *)config; if (deauth) { *deauth = 1; } if (nb_mac) { *nb_mac = fa->nb_mac; } // Copy the mac addresses macs = (unsigned char **)malloc(sizeof(unsigned char *) * (fa->nb_mac)); for (i = 0; i < fa->nb_mac; i++) { COPY_MAC(fa->addresses[i], macs, counter) } return fa->addresses; } void clear_attack(void * config) { struct frag_attack * fa; if (config) { fa = (struct frag_attack *)config; // Do not free, memory (since we know how much we allocated at startup, we know what to free at exit). fa->nb_mac = 0; } } #undef NB_ADDRESSES
vaginessa/openwips-ng
server/plugin/frag_detection.c
C
gpl-2.0
6,143
/* * arch/ppc64/kernel/u3_iommu.c * * Copyright (C) 2004 Olof Johansson <[email protected]>, IBM Corporation * * Based on pSeries_iommu.c: * Copyright (C) 2001 Mike Corrigan & Dave Engebretsen, IBM Corporation * Copyright (C) 2004 Olof Johansson <[email protected]>, IBM Corporation * * Dynamic DMA mapping support, Apple U3 & IBM CPC925 "DART" iommu. * * * 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 <linux/config.h> #include <linux/init.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <linux/string.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/vmalloc.h> #include <asm/io.h> #include <asm/prom.h> #include <asm/ppcdebug.h> #include <asm/iommu.h> #include <asm/pci-bridge.h> #include <asm/machdep.h> #include <asm/abs_addr.h> #include <asm/cacheflush.h> #include <asm/lmb.h> #include "pci.h" extern int iommu_force_on; /* physical base of DART registers */ #define DART_BASE 0xf8033000UL /* Offset from base to control register */ #define DARTCNTL 0 /* Offset from base to exception register */ #define DARTEXCP 0x10 /* Offset from base to TLB tag registers */ #define DARTTAG 0x1000 /* Control Register fields */ /* base address of table (pfn) */ #define DARTCNTL_BASE_MASK 0xfffff #define DARTCNTL_BASE_SHIFT 12 #define DARTCNTL_FLUSHTLB 0x400 #define DARTCNTL_ENABLE 0x200 /* size of table in pages */ #define DARTCNTL_SIZE_MASK 0x1ff #define DARTCNTL_SIZE_SHIFT 0 /* DART table fields */ #define DARTMAP_VALID 0x80000000 #define DARTMAP_RPNMASK 0x00ffffff /* Physical base address and size of the DART table */ unsigned long dart_tablebase; /* exported to htab_initialize */ static unsigned long dart_tablesize; /* Virtual base address of the DART table */ static u32 *dart_vbase; /* Mapped base address for the dart */ static unsigned int *dart; /* Dummy val that entries are set to when unused */ static unsigned int dart_emptyval; static struct iommu_table iommu_table_u3; static int dart_dirty; #define DBG(...) static inline void dart_tlb_invalidate_all(void) { unsigned long l = 0; unsigned int reg; unsigned long limit; DBG("dart: flush\n"); /* To invalidate the DART, set the DARTCNTL_FLUSHTLB bit in the * control register and wait for it to clear. * * Gotcha: Sometimes, the DART won't detect that the bit gets * set. If so, clear it and set it again. */ limit = 0; retry: reg = in_be32((unsigned int *)dart+DARTCNTL); reg |= DARTCNTL_FLUSHTLB; out_be32((unsigned int *)dart+DARTCNTL, reg); l = 0; while ((in_be32((unsigned int *)dart+DARTCNTL) & DARTCNTL_FLUSHTLB) && l < (1L<<limit)) { l++; } if (l == (1L<<limit)) { if (limit < 4) { limit++; reg = in_be32((unsigned int *)dart+DARTCNTL); reg &= ~DARTCNTL_FLUSHTLB; out_be32((unsigned int *)dart+DARTCNTL, reg); goto retry; } else panic("U3-DART: TLB did not flush after waiting a long " "time. Buggy U3 ?"); } } static void dart_flush(struct iommu_table *tbl) { if (dart_dirty) dart_tlb_invalidate_all(); dart_dirty = 0; } static void dart_build(struct iommu_table *tbl, long index, long npages, unsigned long uaddr, enum dma_data_direction direction) { unsigned int *dp; unsigned int rpn; DBG("dart: build at: %lx, %lx, addr: %x\n", index, npages, uaddr); dp = ((unsigned int*)tbl->it_base) + index; /* On U3, all memory is contigous, so we can move this * out of the loop. */ while (npages--) { rpn = virt_to_abs(uaddr) >> PAGE_SHIFT; *(dp++) = DARTMAP_VALID | (rpn & DARTMAP_RPNMASK); rpn++; uaddr += PAGE_SIZE; } dart_dirty = 1; } static void dart_free(struct iommu_table *tbl, long index, long npages) { unsigned int *dp; /* We don't worry about flushing the TLB cache. The only drawback of * not doing it is that we won't catch buggy device drivers doing * bad DMAs, but then no 32-bit architecture ever does either. */ DBG("dart: free at: %lx, %lx\n", index, npages); dp = ((unsigned int *)tbl->it_base) + index; while (npages--) *(dp++) = dart_emptyval; } static int dart_init(struct device_node *dart_node) { unsigned int regword; unsigned int i; unsigned long tmp; struct page *p; if (dart_tablebase == 0 || dart_tablesize == 0) { printk(KERN_INFO "U3-DART: table not allocated, using direct DMA\n"); return -ENODEV; } /* Make sure nothing from the DART range remains in the CPU cache * from a previous mapping that existed before the kernel took * over */ flush_dcache_phys_range(dart_tablebase, dart_tablebase + dart_tablesize); /* Allocate a spare page to map all invalid DART pages. We need to do * that to work around what looks like a problem with the HT bridge * prefetching into invalid pages and corrupting data */ tmp = __get_free_pages(GFP_ATOMIC, 1); if (tmp == 0) panic("U3-DART: Cannot allocate spare page !"); dart_emptyval = DARTMAP_VALID | ((virt_to_abs(tmp) >> PAGE_SHIFT) & DARTMAP_RPNMASK); /* Map in DART registers. FIXME: Use device node to get base address */ dart = ioremap(DART_BASE, 0x7000); if (dart == NULL) panic("U3-DART: Cannot map registers !"); /* Set initial control register contents: table base, * table size and enable bit */ regword = DARTCNTL_ENABLE | ((dart_tablebase >> PAGE_SHIFT) << DARTCNTL_BASE_SHIFT) | (((dart_tablesize >> PAGE_SHIFT) & DARTCNTL_SIZE_MASK) << DARTCNTL_SIZE_SHIFT); p = virt_to_page(dart_tablebase); dart_vbase = ioremap(virt_to_abs(dart_tablebase), dart_tablesize); /* Fill initial table */ for (i = 0; i < dart_tablesize/4; i++) dart_vbase[i] = dart_emptyval; /* Initialize DART with table base and enable it. */ out_be32((unsigned int *)dart, regword); /* Invalidate DART to get rid of possible stale TLBs */ dart_tlb_invalidate_all(); iommu_table_u3.it_busno = 0; /* Units of tce entries */ iommu_table_u3.it_offset = 0; /* Set the tce table size - measured in pages */ iommu_table_u3.it_size = dart_tablesize >> PAGE_SHIFT; /* Initialize the common IOMMU code */ iommu_table_u3.it_base = (unsigned long)dart_vbase; iommu_table_u3.it_index = 0; iommu_table_u3.it_blocksize = 1; iommu_table_u3.it_entrysize = sizeof(u32); iommu_init_table(&iommu_table_u3); /* Reserve the last page of the DART to avoid possible prefetch * past the DART mapped area */ set_bit(iommu_table_u3.it_mapsize - 1, iommu_table_u3.it_map); printk(KERN_INFO "U3/CPC925 DART IOMMU initialized\n"); return 0; } void iommu_setup_u3(void) { struct pci_dev *dev = NULL; struct device_node *dn; /* Find the DART in the device-tree */ dn = of_find_compatible_node(NULL, "dart", "u3-dart"); if (dn == NULL) return; /* Setup low level TCE operations for the core IOMMU code */ ppc_md.tce_build = dart_build; ppc_md.tce_free = dart_free; ppc_md.tce_flush = dart_flush; /* Initialize the DART HW */ if (dart_init(dn)) return; /* Setup pci_dma ops */ pci_iommu_init(); /* We only have one iommu table on the mac for now, which makes * things simple. Setup all PCI devices to point to this table */ while ((dev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, dev)) != NULL) { /* We must use pci_device_to_OF_node() to make sure that * we get the real "final" pointer to the device in the * pci_dev sysdata and not the temporary PHB one */ struct device_node *dn = pci_device_to_OF_node(dev); if (dn) dn->iommu_table = &iommu_table_u3; } } void __init alloc_u3_dart_table(void) { /* Only reserve DART space if machine has more than 2GB of RAM * or if requested with iommu=on on cmdline. */ if (lmb_end_of_DRAM() <= 0x80000000ull && !iommu_force_on) return; /* 512 pages (2MB) is max DART tablesize. */ dart_tablesize = 1UL << 21; /* 16MB (1 << 24) alignment. We allocate a full 16Mb chuck since we * will blow up an entire large page anyway in the kernel mapping */ dart_tablebase = (unsigned long) abs_to_virt(lmb_alloc_base(1UL<<24, 1UL<<24, 0x80000000L)); printk(KERN_INFO "U3-DART allocated at: %lx\n", dart_tablebase); }
tianya3796/linux2.6.9
arch/ppc64/kernel/u3_iommu.c
C
gpl-2.0
8,802
<?php /* * This file is part of EC-CUBE * * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved. * * http://www.lockon.co.jp/ * * 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. */ namespace Eccube\Tests\Form\Type\Front; class NonMemberTypeTest extends \Eccube\Tests\Form\Type\AbstractTypeTestCase { /** @var \Eccube\Application */ protected $app; /** @var \Symfony\Component\Form\FormInterface */ protected $form; /** @var array デフォルト値(正常系)を設定 */ protected $formData = array( 'name' => array( 'name01' => 'たかはし', 'name02' => 'しんいち', ), 'kana' => array( 'kana01' => 'タカハシ', 'kana02' => 'シンイチ', ), 'company_name' => '', 'zip' => array( 'zip01' => '530', 'zip02' => '0001', ), 'address' => array( 'pref' => '5', 'addr01' => '北区', 'addr02' => '梅田', ), 'tel' => array( 'tel01' => '03', 'tel02' => '1111', 'tel03' => '1111', ), 'email' => array( 'first' =>'[email protected]', 'second' =>'[email protected]', ), ); public function setUp() { parent::setUp(); // CSRF tokenを無効にしてFormを作成 $this->form = $this->app['form.factory'] ->createBuilder('nonmember', null, array( 'csrf_protection' => false, )) ->getForm(); } public function testValidData() { $this->form->submit($this->formData); $this->assertTrue($this->form->isValid()); } public function testInvalidTel_Blank() { $this->formData['tel']['tel01'] = ''; $this->formData['tel']['tel02'] = ''; $this->formData['tel']['tel03'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidName01_Blank() { $this->formData['name']['name01'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidName02_Blank() { $this->formData['name']['name02'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidKana01_Blank() { $this->formData['kana']['kana01'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidKana02_Blank() { $this->formData['kana']['kana02'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidKana01_NotKana() { $this->formData['kana']['kana01'] = 'aaaa'; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidKana02_NotKana() { $this->formData['kana']['kana02'] = 'aaaaa'; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testValidCompanyName_Blank() { $this->formData['company_name'] = ''; $this->form->submit($this->formData); $this->assertTrue($this->form->isValid()); } public function testInvalidZip01_Blank() { $this->formData['zip']['zip01'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidZip02_Blank() { $this->formData['zip']['zip02'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidPref_Blank() { $this->formData['address']['pref'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidAddr01_Blank() { $this->formData['address']['addr01'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidAddr02_Blank() { $this->formData['address']['addr02'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } public function testInvalidemail_Blank() { $this->formData['email']['first'] = ''; $this->formData['email']['second'] = ''; $this->form->submit($this->formData); $this->assertFalse($this->form->isValid()); } }
lammn/amazone
tests/Eccube/Tests/Form/Type/Front/NonMemberTypeTest.php
PHP
gpl-2.0
5,449
/* * 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. */ package org.apache.commons.math3.optimization.direct; import org.apache.commons.math3.util.FastMath; import org.apache.commons.math3.util.MathArrays; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.MultivariateFunction; import org.apache.commons.math3.exception.NumberIsTooSmallException; import org.apache.commons.math3.exception.NotStrictlyPositiveException; import org.apache.commons.math3.optimization.GoalType; import org.apache.commons.math3.optimization.PointValuePair; import org.apache.commons.math3.optimization.ConvergenceChecker; import org.apache.commons.math3.optimization.MultivariateOptimizer; import org.apache.commons.math3.optimization.univariate.BracketFinder; import org.apache.commons.math3.optimization.univariate.BrentOptimizer; import org.apache.commons.math3.optimization.univariate.UnivariatePointValuePair; import org.apache.commons.math3.optimization.univariate.SimpleUnivariateValueChecker; /** * Powell algorithm. * This code is translated and adapted from the Python version of this * algorithm (as implemented in module {@code optimize.py} v0.5 of * <em>SciPy</em>). * <br/> * The default stopping criterion is based on the differences of the * function value between two successive iterations. It is however possible * to define a custom convergence checker that might terminate the algorithm * earlier. * * @version $Id$ * @since 2.2 */ public class PowellOptimizer extends BaseAbstractMultivariateOptimizer<MultivariateFunction> implements MultivariateOptimizer { /** * Minimum relative tolerance. */ private static final double MIN_RELATIVE_TOLERANCE = 2 * FastMath.ulp(1d); /** * Relative threshold. */ private final double relativeThreshold; /** * Absolute threshold. */ private final double absoluteThreshold; /** * Line search. */ private final LineSearch line; /** * This constructor allows to specify a user-defined convergence checker, * in addition to the parameters that control the default convergence * checking procedure and the line search tolerances. * * @param rel Relative threshold. * @param abs Absolute threshold. * @param checker Convergence checker. * @throws NotStrictlyPositiveException if {@code abs <= 0}. * @throws NumberIsTooSmallException if {@code rel < 2 * Math.ulp(1d)}. */ public PowellOptimizer(double rel, double abs, ConvergenceChecker<PointValuePair> checker) { super(checker); if (rel < MIN_RELATIVE_TOLERANCE) { throw new NumberIsTooSmallException(rel, MIN_RELATIVE_TOLERANCE, true); } if (abs <= 0) { throw new NotStrictlyPositiveException(abs); } relativeThreshold = rel; absoluteThreshold = abs; // Line search tolerances can be much less stringent than the tolerances // required for the optimizer itself. line = new LineSearch(FastMath.sqrt(rel), FastMath.sqrt(abs)); } /** * The parameters control the default convergence checking procedure, and * the line search tolerances. * * @param rel Relative threshold. * @param abs Absolute threshold. * @throws NotStrictlyPositiveException if {@code abs <= 0}. * @throws NumberIsTooSmallException if {@code rel < 2 * Math.ulp(1d)}. */ public PowellOptimizer(double rel, double abs) { this(rel, abs, null); } /** {@inheritDoc} */ @Override protected PointValuePair doOptimize() { final GoalType goal = getGoalType(); final double[] guess = getStartPoint(); final int n = guess.length; final double[][] direc = new double[n][n]; for (int i = 0; i < n; i++) { direc[i][i] = 1; } final ConvergenceChecker<PointValuePair> checker = getConvergenceChecker(); double[] x = guess; double fVal = computeObjectiveValue(x); double[] x1 = x.clone(); int iter = 0; while (true) { ++iter; double fX = fVal; double fX2 = 0; double delta = 0; int bigInd = 0; double alphaMin = 0; for (int i = 0; i < n; i++) { final double[] d = MathArrays.copyOf(direc[i]); fX2 = fVal; final UnivariatePointValuePair optimum = line.search(x, d); fVal = optimum.getValue(); alphaMin = optimum.getPoint(); final double[][] result = newPointAndDirection(x, d, alphaMin); x = result[0]; if ((fX2 - fVal) > delta) { delta = fX2 - fVal; bigInd = i; } } // Default convergence check. boolean stop = 2 * (fX - fVal) <= (relativeThreshold * (FastMath.abs(fX) + FastMath.abs(fVal)) + absoluteThreshold); final PointValuePair previous = new PointValuePair(x1, fX); final PointValuePair current = new PointValuePair(x, fVal); if (!stop) { // User-defined stopping criteria. if (checker != null) { stop = checker.converged(iter, previous, current); } } if (stop) { if (goal == GoalType.MINIMIZE) { return (fVal < fX) ? current : previous; } else { return (fVal > fX) ? current : previous; } } final double[] d = new double[n]; final double[] x2 = new double[n]; for (int i = 0; i < n; i++) { d[i] = x[i] - x1[i]; x2[i] = 2 * x[i] - x1[i]; } x1 = x.clone(); fX2 = computeObjectiveValue(x2); if (fX > fX2) { double t = 2 * (fX + fX2 - 2 * fVal); double temp = fX - fVal - delta; t *= temp * temp; temp = fX - fX2; t -= delta * temp * temp; if (t < 0.0) { final UnivariatePointValuePair optimum = line.search(x, d); fVal = optimum.getValue(); alphaMin = optimum.getPoint(); final double[][] result = newPointAndDirection(x, d, alphaMin); x = result[0]; final int lastInd = n - 1; direc[bigInd] = direc[lastInd]; direc[lastInd] = result[1]; } } } } /** * Compute a new point (in the original space) and a new direction * vector, resulting from the line search. * The parameters {@code p} and {@code d} will be changed in-place. * * @param p Point used in the line search. * @param d Direction used in the line search. * @param optimum Optimum found by the line search. * @return a 2-element array containing the new point (at index 0) and * the new direction (at index 1). */ private double[][] newPointAndDirection(double[] p, double[] d, double optimum) { final int n = p.length; final double[][] result = new double[2][n]; final double[] nP = result[0]; final double[] nD = result[1]; for (int i = 0; i < n; i++) { nD[i] = d[i] * optimum; nP[i] = p[i] + nD[i]; } return result; } /** * Class for finding the minimum of the objective function along a given * direction. */ private class LineSearch extends BrentOptimizer { /** * Value that will pass the precondition check for {@link BrentOptimizer} * but will not pass the convergence check, so that the custom checker * will always decide when to stop the line search. */ private static final double REL_TOL_UNUSED = 1e-15; /** * Value that will pass the precondition check for {@link BrentOptimizer} * but will not pass the convergence check, so that the custom checker * will always decide when to stop the line search. */ private static final double ABS_TOL_UNUSED = Double.MIN_VALUE; /** * Automatic bracketing. */ private final BracketFinder bracket = new BracketFinder(); /** * The "BrentOptimizer" default stopping criterion uses the tolerances * to check the domain (point) values, not the function values. * We thus create a custom checker to use function values. * * @param rel Relative threshold. * @param abs Absolute threshold. */ LineSearch(double rel, double abs) { super(REL_TOL_UNUSED, ABS_TOL_UNUSED, new SimpleUnivariateValueChecker(rel, abs)); } /** * Find the minimum of the function {@code f(p + alpha * d)}. * * @param p Starting point. * @param d Search direction. * @return the optimum. * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the number of evaluations is exceeded. */ public UnivariatePointValuePair search(final double[] p, final double[] d) { final int n = p.length; final UnivariateFunction f = new UnivariateFunction() { public double value(double alpha) { final double[] x = new double[n]; for (int i = 0; i < n; i++) { x[i] = p[i] + alpha * d[i]; } final double obj = PowellOptimizer.this.computeObjectiveValue(x); return obj; } }; final GoalType goal = PowellOptimizer.this.getGoalType(); bracket.search(f, goal, 0, 1); // Passing "MAX_VALUE" as a dummy value because it is the enclosing // class that counts the number of evaluations (and will eventually // generate the exception). return optimize(Integer.MAX_VALUE, f, goal, bracket.getLo(), bracket.getHi(), bracket.getMid()); } } }
SpoonLabs/astor
examples/math_32/src/main/java/org/apache/commons/math3/optimization/direct/PowellOptimizer.java
Java
gpl-2.0
11,467
<?php /** * * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Catalog\Controller\Adminhtml\Product\Attribute; class Validate extends \Magento\Catalog\Controller\Adminhtml\Product\Attribute { /** * @var \Magento\Framework\Controller\Result\JsonFactory */ protected $resultJsonFactory; /** * @var \Magento\Framework\View\LayoutFactory */ protected $layoutFactory; /** * Constructor * * @param \Magento\Backend\App\Action\Context $context * @param \Magento\Framework\Cache\FrontendInterface $attributeLabelCache * @param \Magento\Framework\Registry $coreRegistry * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory * @param \Magento\Framework\View\LayoutFactory $layoutFactory */ public function __construct( \Magento\Backend\App\Action\Context $context, \Magento\Framework\Cache\FrontendInterface $attributeLabelCache, \Magento\Framework\Registry $coreRegistry, \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\View\LayoutFactory $layoutFactory ) { parent::__construct($context, $attributeLabelCache, $coreRegistry, $resultPageFactory); $this->resultJsonFactory = $resultJsonFactory; $this->layoutFactory = $layoutFactory; } /** * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { $response = new \Magento\Framework\DataObject(); $response->setError(false); $attributeCode = $this->getRequest()->getParam('attribute_code'); $frontendLabel = $this->getRequest()->getParam('frontend_label'); $attributeCode = $attributeCode ?: $this->generateCode($frontendLabel[0]); $attributeId = $this->getRequest()->getParam('attribute_id'); $attribute = $this->_objectManager->create( 'Magento\Catalog\Model\ResourceModel\Eav\Attribute' )->loadByCode( $this->_entityTypeId, $attributeCode ); if ($attribute->getId() && !$attributeId) { if (strlen($this->getRequest()->getParam('attribute_code'))) { $response->setMessage( __('An attribute with this code already exists.') ); } else { $response->setMessage( __('An attribute with the same code (%1) already exists.', $attributeCode) ); } $response->setError(true); } if ($this->getRequest()->has('new_attribute_set_name')) { $setName = $this->getRequest()->getParam('new_attribute_set_name'); /** @var $attributeSet \Magento\Eav\Model\Entity\Attribute\Set */ $attributeSet = $this->_objectManager->create('Magento\Eav\Model\Entity\Attribute\Set'); $attributeSet->setEntityTypeId($this->_entityTypeId)->load($setName, 'attribute_set_name'); if ($attributeSet->getId()) { $setName = $this->_objectManager->get('Magento\Framework\Escaper')->escapeHtml($setName); $this->messageManager->addError(__('An attribute set named \'%1\' already exists.', $setName)); $layout = $this->layoutFactory->create(); $layout->initMessages(); $response->setError(true); $response->setHtmlMessage($layout->getMessagesBlock()->getGroupedHtml()); } } return $this->resultJsonFactory->create()->setJsonData($response->toJson()); } }
FPLD/project0
vendor/magento/module-catalog/Controller/Adminhtml/Product/Attribute/Validate.php
PHP
gpl-2.0
3,809
/* packet-cmstatus.c * Routines for DOCSIS 3.0 CM-STATUS Report Message dissection. * Copyright 2011, Hendrik Robbel <hendrik.robbel[AT]kabeldeutschland.de> * * $Id$ * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #define SEC_CH_MDD_TIMEOUT 1 #define QAM_FEC_LOCK_FAILURE 2 #define SEQ_OUT_OF_RANGE 3 #define SEC_CH_MDD_RECOVERY 4 #define QAM_FEC_LOCK_RECOVERY 5 #define T4_TIMEOUT 6 #define T3_RETRIES_EXCEEDED 7 #define SUCCESS_RANGING_AFTER_T3_RETRIES_EXCEEDED 8 #define CM_ON_BATTERY 9 #define CM_ON_AC_POWER 10 #define EVENT_DESCR 2 #define EVENT_DS_CH_ID 4 #define EVENT_US_CH_ID 5 #define EVENT_DSID 6 /* Initialize the protocol and registered fields */ static int proto_docsis_cmstatus = -1; static int hf_docsis_cmstatus_tranid = -1; static int hf_docsis_cmstatus_e_t_mdd_t = -1; static int hf_docsis_cmstatus_e_t_qfl_f = -1; static int hf_docsis_cmstatus_e_t_s_o = -1; static int hf_docsis_cmstatus_e_t_mdd_r = -1; static int hf_docsis_cmstatus_e_t_qfl_r = -1; static int hf_docsis_cmstatus_e_t_t4_t = -1; static int hf_docsis_cmstatus_e_t_t3_e = -1; static int hf_docsis_cmstatus_e_t_rng_s = -1; static int hf_docsis_cmstatus_e_t_cm_b = -1; static int hf_docsis_cmstatus_e_t_cm_a = -1; static int hf_docsis_cmstatus_ds_ch_id = -1; static int hf_docsis_cmstatus_us_ch_id = -1; static int hf_docsis_cmstatus_dsid = -1; static int hf_docsis_cmstatus_descr = -1; /* Initialize the subtree pointers */ static gint ett_docsis_cmstatus = -1; static gint ett_docsis_cmstatus_tlv = -1; /* See Table 6-52 in CM-SP-MULPIv3.0-I14-101008 */ static void dissect_cmstatus_tlv (tvbuff_t * tvb, proto_tree * tree, guint8 start, guint16 len) { proto_item *it; proto_tree *tlv_tree; guint16 pos = start + 1; guint8 type, length; it = proto_tree_add_protocol_format (tree, proto_docsis_cmstatus, tvb, 0, len, "TLV Data"); tlv_tree = proto_item_add_subtree (it, ett_docsis_cmstatus_tlv); while (pos < (len + start + 1)) { length = tvb_get_guint8 (tvb, pos++); type = tvb_get_guint8 (tvb, pos++); switch (type) { case EVENT_DS_CH_ID: if (length == 3) { proto_tree_add_item (tlv_tree, hf_docsis_cmstatus_ds_ch_id, tvb, pos + 1, 1, ENC_BIG_ENDIAN); } else { THROW (ReportedBoundsError); } break; case EVENT_US_CH_ID: if (length == 3) { proto_tree_add_item (tlv_tree, hf_docsis_cmstatus_us_ch_id, tvb, pos + 1, 1, ENC_BIG_ENDIAN); } else { THROW (ReportedBoundsError); } break; case EVENT_DSID: if (length == 5) { proto_tree_add_item (tlv_tree, hf_docsis_cmstatus_dsid, tvb, pos + 1, 3, ENC_BIG_ENDIAN); } else { THROW (ReportedBoundsError); } break; case EVENT_DESCR: if (length >= 3 && length <= 82) { proto_tree_add_item (tlv_tree, hf_docsis_cmstatus_descr, tvb, pos + 1, length - 2, ENC_NA); } else { THROW (ReportedBoundsError); } break; } /* switch */ pos = pos + length; } /* while */ } static void dissect_cmstatus (tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree) { proto_item *it; proto_tree *cmstatus_tree = NULL; guint16 transid; guint8 event_type; guint16 len; transid = tvb_get_ntohs (tvb, 0); event_type = tvb_get_guint8 (tvb, 2); len = tvb_reported_length_remaining (tvb, 3); col_clear (pinfo->cinfo, COL_INFO); col_add_fstr (pinfo->cinfo, COL_INFO, "CM-STATUS Report: Transaction ID = %u", transid); if (tree) { it = proto_tree_add_protocol_format (tree, proto_docsis_cmstatus, tvb, 0, -1, "CM-STATUS Report"); cmstatus_tree = proto_item_add_subtree (it, ett_docsis_cmstatus); proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_tranid, tvb, 0, 2, ENC_BIG_ENDIAN); switch (event_type) { case SEC_CH_MDD_TIMEOUT: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_mdd_t, tvb, 2, 1, ENC_BIG_ENDIAN); break; case QAM_FEC_LOCK_FAILURE: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_qfl_f, tvb, 2, 1, ENC_BIG_ENDIAN); break; case SEQ_OUT_OF_RANGE: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_s_o, tvb, 2, 1, ENC_BIG_ENDIAN); break; case SEC_CH_MDD_RECOVERY: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_mdd_r, tvb, 2, 1, ENC_BIG_ENDIAN); break; case QAM_FEC_LOCK_RECOVERY: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_qfl_r, tvb, 2, 1, ENC_BIG_ENDIAN); break; case T4_TIMEOUT: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_t4_t, tvb, 2, 1, ENC_BIG_ENDIAN); break; case T3_RETRIES_EXCEEDED: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_t3_e, tvb, 2, 1, ENC_BIG_ENDIAN); break; case SUCCESS_RANGING_AFTER_T3_RETRIES_EXCEEDED: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_rng_s, tvb, 2, 1, ENC_BIG_ENDIAN); break; case CM_ON_BATTERY: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_cm_b, tvb, 2, 1, ENC_BIG_ENDIAN); break; case CM_ON_AC_POWER: proto_tree_add_item (cmstatus_tree, hf_docsis_cmstatus_e_t_cm_a, tvb, 2, 1, ENC_BIG_ENDIAN); break; } /* switch */ } /* Call Dissector TLV's */ dissect_cmstatus_tlv(tvb, cmstatus_tree, 3, len); } /* Register the protocol with Wireshark */ /* this format is require because a script is used to build the C function that calls all the protocol registration. */ void proto_register_docsis_cmstatus (void) { /* Setup list of header fields See Section 1.6.1 for details*/ static hf_register_info hf[] = { {&hf_docsis_cmstatus_tranid, {"Transaction ID", "docsis_cmstatus.tranid",FT_UINT16, BASE_DEC, NULL, 0x0,NULL, HFILL} }, /* See Table 10-3 in CM-SP-MULPIv3.0-I14-101008 */ {&hf_docsis_cmstatus_e_t_mdd_t, {"Secondary Channel MDD timeout", "docsis_cmstatus.mdd_timeout", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_qfl_f, {"QAM/FEC lock failure", "docsis_cmstatus.qam_fec_lock_failure", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_s_o, {"Sequence out-of-range", "docsis_cmstatus.sequence_out_of_range", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_mdd_r, {"Secondary Channel MDD Recovery", "docsis_cmstatus.mdd_recovery", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_qfl_r, {"QAM/FEC Lock Recovery", "docsis_cmstatus.qam_fec_lock_recovery", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_t4_t, {"T4 timeout", "docsis_cmstatus.t4_timeout", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_t3_e, {"T3 retries exceeded", "docsis_cmstatus.t3_retries_exceeded", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_rng_s, {"Successful ranging after T3 retries exceeded", "docsis_cmstatus.successful_ranging_after_t3_retries_exceeded", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_cm_b, {"CM operating on battery backup", "docsis_cmstatus.cm_on_battery", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_e_t_cm_a, {"CM returned to A/C power", "docsis_cmstatus.cm_on_ac_power", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_cmstatus_descr, {"1.2 Description", "docsis_cmstatus.description",FT_BYTES, BASE_NONE, NULL, 0x0,"Description", HFILL} }, {&hf_docsis_cmstatus_ds_ch_id, {"1.4 Downstream Channel ID", "docsis_cmstatus.ds_chid",FT_UINT8, BASE_DEC, NULL, 0x0, "Downstream Channel ID", HFILL} }, {&hf_docsis_cmstatus_us_ch_id, {"1.5 Upstream Channel ID", "docsis_cmstatus.us_chid",FT_UINT8, BASE_DEC, NULL, 0x0, "Upstream Channel ID", HFILL} }, {&hf_docsis_cmstatus_dsid, {"1.6 DSID", "docsis_cmstatus.dsid", FT_UINT24, BASE_DEC, NULL, 0x0, "DSID", HFILL} } }; /* Setup protocol subtree array */ static gint *ett[] = { &ett_docsis_cmstatus, &ett_docsis_cmstatus_tlv }; /* Register the protocol name and description */ proto_docsis_cmstatus = proto_register_protocol ("DOCSIS CM-STATUS Report", "DOCSIS CM-STATUS", "docsis_cmstatus"); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array (proto_docsis_cmstatus, hf, array_length (hf)); proto_register_subtree_array (ett, array_length (ett)); register_dissector ("docsis_cmstatus", dissect_cmstatus, proto_docsis_cmstatus); } /* If this dissector uses sub-dissector registration add a registration routine. This format is required because a script is used to find these routines and create the code that calls these routines. */ void proto_reg_handoff_docsis_cmstatus (void) { dissector_handle_t docsis_cmstatus_handle; docsis_cmstatus_handle = find_dissector ("docsis_cmstatus"); dissector_add_uint ("docsis_mgmt", 0x29, docsis_cmstatus_handle); }
boundary/wireshark
plugins/docsis/packet-cmstatus.c
C
gpl-2.0
10,072
#!/system/bin/sh # Copyright (c) 2009-2013, The Linux Foundation. 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 Linux 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NON-INFRINGEMENT 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 to start sensors for DSPS enabled platforms # start_sensors() { if [ -c /dev/msm_dsps -o -c /dev/sensors ]; then mkdir -p /data/system/sensors touch /data/system/sensors/settings chmod 775 /data/system/sensors chmod 664 /data/system/sensors/settings chown system /data/system/sensors/settings mkdir -p /data/misc/sensors chmod 775 /data/misc/sensors if [ ! -s /data/system/sensors/settings ]; then # If the settings file is empty, enable sensors HAL # Otherwise leave the file with it's current contents echo 1 > /data/system/sensors/settings fi start sensors fi } start_sensors
whdgmawkd/furnace_kk_lge_msm8974
ramdisk_aosp/sensors.sh
Shell
gpl-2.0
2,344
/* * arch/um/drivers/mmapper_kern.c * * BRIEF MODULE DESCRIPTION * * Copyright (C) 2000 RidgeRun, Inc. * Author: RidgeRun, Inc. * Greg Lonnon [email protected] or [email protected] * */ #include <linux/types.h> #include <linux/kdev_t.h> #include <linux/time.h> #include <linux/devfs_fs_kernel.h> #include <linux/module.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/smp_lock.h> #include <linux/miscdevice.h> #include <asm/uaccess.h> #include <asm/irq.h> #include <asm/pgtable.h> #include "mem_user.h" #include "user_util.h" /* These are set in mmapper_init, which is called at boot time */ static unsigned long mmapper_size; static unsigned long p_buf = 0; static char *v_buf = NULL; static ssize_t mmapper_read(struct file *file, char *buf, size_t count, loff_t *ppos) { if(*ppos > mmapper_size) return -EINVAL; if(count + *ppos > mmapper_size) count = count + *ppos - mmapper_size; if(count < 0) return -EINVAL; copy_to_user(buf,&v_buf[*ppos],count); return count; } static ssize_t mmapper_write(struct file *file, const char *buf, size_t count, loff_t *ppos) { if(*ppos > mmapper_size) return -EINVAL; if(count + *ppos > mmapper_size) count = count + *ppos - mmapper_size; if(count < 0) return -EINVAL; copy_from_user(&v_buf[*ppos],buf,count); return count; } static int mmapper_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg) { return(-ENOIOCTLCMD); } static int mmapper_mmap(struct file *file, struct vm_area_struct * vma) { int ret = -EINVAL; int size; lock_kernel(); if (vma->vm_pgoff != 0) goto out; size = vma->vm_end - vma->vm_start; if(size > mmapper_size) return(-EFAULT); /* XXX A comment above remap_pfn_range says it should only be * called when the mm semaphore is held */ if (remap_pfn_range(vma, vma->vm_start, p_buf >> PAGE_SHIFT, size, vma->vm_page_prot)) goto out; ret = 0; out: unlock_kernel(); return ret; } static int mmapper_open(struct inode *inode, struct file *file) { return 0; } static int mmapper_release(struct inode *inode, struct file *file) { return 0; } static struct file_operations mmapper_fops = { .owner = THIS_MODULE, .read = mmapper_read, .write = mmapper_write, .ioctl = mmapper_ioctl, .mmap = mmapper_mmap, .open = mmapper_open, .release = mmapper_release, }; static struct miscdevice mmapper_dev = { .minor = MISC_DYNAMIC_MINOR, .name = "mmapper", .fops = &mmapper_fops }; static int __init mmapper_init(void) { int err; printk(KERN_INFO "Mapper v0.1\n"); v_buf = (char *) find_iomem("mmapper", &mmapper_size); if(mmapper_size == 0){ printk(KERN_ERR "mmapper_init - find_iomem failed\n"); goto out; } err = misc_register(&mmapper_dev); if(err){ printk(KERN_ERR "mmapper - misc_register failed, err = %d\n", err); goto out; } p_buf = __pa(v_buf); out: return 0; } static void mmapper_exit(void) { misc_deregister(&mmapper_dev); } module_init(mmapper_init); module_exit(mmapper_exit); MODULE_AUTHOR("Greg Lonnon <[email protected]>"); MODULE_DESCRIPTION("DSPLinux simulator mmapper driver"); /* * --------------------------------------------------------------------------- * Local variables: * c-file-style: "linux" * End: */
foxsat-hdr/linux-kernel
arch/um/drivers/mmapper_kern.c
C
gpl-2.0
3,314
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2014 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Device/Driver/CAI302/Internal.hpp" #include "Device/Port/Port.hpp" #include "Device/Port/ConfiguredPort.hpp" #include "Device/Config.hpp" #include "DebugPort.hpp" #include "OS/Args.hpp" #include "Operation/ConsoleOperationEnvironment.hpp" #include "Util/Macros.hpp" #include "IO/Async/GlobalIOThread.hpp" #include <stdio.h> gcc_pure static int StringBufferLength(const char *buffer, size_t size) { const char *z = (const char *)memchr(buffer, 0, size); if (z == NULL) z = buffer + size; while (z > buffer && z[-1] == ' ') --z; return z - buffer; } static bool PrintInfo(CAI302Device &device, OperationEnvironment &env) { CAI302::GeneralInfo info; if (!device.ReadGeneralInfo(info, env)) return false; printf("id: %.*s\n", StringBufferLength(info.id, ARRAY_SIZE(info.id)), info.id); printf("firmward: %.*s (%s)\n", StringBufferLength(info.version, ARRAY_SIZE(info.version)), info.version, info.type == 'F' ? "production" : (info.type == 'P' ? "prototype" : "unknown")); return true; } static bool ListPilots(CAI302Device &device, OperationEnvironment &env) { std::vector<CAI302::Pilot> pilots; unsigned active; if (!device.ReadPilotList(pilots, active, env)) return false; unsigned index = 0; for (auto i = pilots.begin(), end = pilots.end(); i != end; ++i) printf("%u: '%.*s'\n", index++, StringBufferLength(i->name, ARRAY_SIZE(i->name)), i->name); printf("active=%u\n", active); return true; } static bool ListNavpoints(CAI302Device &device, OperationEnvironment &env) { const int count = device.ReadNavpointCount(env); if (count < 0) return false; printf("count=%u\n", count); for (int i = 0; i < count; ++i) { CAI302::Navpoint n; if (!device.ReadNavpoint(i, n, env)) return false; int32_t latitude = FromBE32(n.latitude) - 54000000; char latitude_letter = latitude >= 0 ? 'N' : 'S'; if (latitude < 0) latitude = -latitude; int32_t longitude = FromBE32(n.longitude) - 108000000; char longitude_letter = longitude >= 0 ? 'E' : 'W'; if (longitude < 0) longitude = -longitude; printf("%u: %u:%02u:%02u%c %u:%02u:%02u%c '%.*s' '%.*s'\n", i, latitude / 10000 / 60, latitude / 10000 % 60, latitude * 6 / 1000 % 60, latitude_letter, longitude / 10000 / 60, longitude / 10000 % 60, longitude * 6 / 1000 % 60, longitude_letter, StringBufferLength(n.name, ARRAY_SIZE(n.name)), n.name, StringBufferLength(n.remark, ARRAY_SIZE(n.remark)), n.remark); } return true; } static bool RunCommand(CAI302Device &device, const char *command, OperationEnvironment &env) { if (strcmp(command, "info") == 0) return PrintInfo(device, env); else if (strcmp(command, "reboot") == 0) return device.Reboot(env); else if (strcmp(command, "poweroff") == 0) return device.PowerOff(env); else if (strcmp(command, "startlogger") == 0) return device.StartLogging(env); else if (strcmp(command, "stoplogger") == 0) return device.StopLogging(env); else if (strcmp(command, "clearlog") == 0) return device.ClearLog(env); else if (strcmp(command, "pilots") == 0) return ListPilots(device, env); else if (strcmp(command, "navpoints") == 0) return ListNavpoints(device, env); else { fprintf(stderr, "Unknown command: %s\n", command); return false; } } int main(int argc, char **argv) { const char *const usage = "PORT BAUD COMMAND\n\n" "Where COMMAND is one of:" "\n\tinfo" "\n\treboot" "\n\tpoweroff" "\n\tstartlogger" "\n\tstoplogger" "\n\tpilots" "\n\tnavpoints" ; Args args(argc, argv, usage); const DeviceConfig config = ParsePortArgs(args); const char *command = args.ExpectNext(); args.ExpectEnd(); InitialiseIOThread(); Port *port = OpenPort(config, *(DataHandler *)NULL); if (port == NULL) { fprintf(stderr, "Failed to open port\n"); return EXIT_FAILURE; } ConsoleOperationEnvironment env; if (!port->WaitConnected(env)) { delete port; DeinitialiseIOThread(); fprintf(stderr, "Failed to connect the port\n"); return EXIT_FAILURE; } CAI302Device device(config, *port); if (!RunCommand(device, command, env)) { fprintf(stderr, "error\n"); return EXIT_FAILURE; } delete port; DeinitialiseIOThread(); return EXIT_SUCCESS; }
CnZoom/XcSoarWork
test/src/CAI302Tool.cpp
C++
gpl-2.0
5,388
// JavaScript Document /* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or <a href="http://ckeditor.com/license */ /* " title="http://ckeditor.com/license */ /* " rel="nofollow">http://ckeditor.com/license */ /* </a> WARNING: clear browser's cache after you modify this file. If you don't do this, you may notice that browser is ignoring all your changes. */ CKEDITOR.editorConfig = function(config) { config.indentClasses = [ 'rteindent1', 'rteindent2', 'rteindent3', 'rteindent4' ]; // [ Left, Center, Right, Justified ] config.justifyClasses = [ 'rteleft', 'rtecenter', 'rteright', 'rtejustify' ]; // The minimum editor width, in pixels, when resizing it with the resize handle. config.resize_minWidth = 450; // Protect PHP code tags (<?...?>) so CKEditor will not break them when // switching from Source to WYSIWYG. // Uncommenting this line doesn't mean the user will not be able to type PHP // code in the source. This kind of prevention must be done in the server // side // (as does Drupal), so just leave this line as is. config.protectedSource.push(/<\?[\s\S]*?\?>/g); // PHP Code config.protectedSource.push(/<code>[\s\S]*?<\/code>/gi); // Code tags config.extraPlugins = ''; // ALLOW <i></i> config.protectedSource.push( /<i[^>]*><\/i>/g ); //allows beginning <i> tag config.protectedSource.push( /<\/i>/g ); //allows ending </i> tag /* * Append here extra CSS rules that should be applied into the editing area. * Example: * config.extraCss = 'body {color:#FF0000;}'; */ config.extraCss = ''; /** * Sample extraCss code for the "marinelli" theme. */ if (Drupal.settings.ckeditor.theme == "marinelli") { config.extraCss += "body{background:#FFF;text-align:left;font-size:0.8em;}"; config.extraCss += "#primary ol, #primary ul{margin:10px 0 10px 25px;}"; } if (Drupal.settings.ckeditor.theme == "newsflash") { config.extraCss = "body{min-width:400px}"; } /** * CKEditor's editing area body ID & class. * See http://drupal.ckeditor.com/tricks * This setting can be used if CKEditor does not work well with your theme by default. */ config.bodyClass = ''; config.bodyId = ''; /** * Sample bodyClass and BodyId for the "marinelli" theme. */ if (Drupal.settings.ckeditor.theme == "marinelli") { config.bodyClass = 'singlepage'; config.bodyId = 'primary'; } } /* * Sample toolbars */ //Toolbar definition for basic buttons Drupal.settings.cke_toolbar_DrupalBasic = [ [ 'Format', 'Bold', 'Italic', '-', 'NumberedList','BulletedList', '-', 'Link', 'Unlink', 'Image' ] ]; //Toolbar definition for Advanced buttons Drupal.settings.cke_toolbar_DrupalAdvanced = [ ['Source'], ['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker', 'Scayt'], ['Undo','Redo','Find','Replace','-','SelectAll','RemoveFormat'], ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar'], ['Maximize', 'ShowBlocks'], '/', ['Format'], ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiRtl','BidiLtr'], ['Link','Unlink','Anchor','Linkit','LinkToNode','LinkToMenu'], ['DrupalBreak', 'DrupalPageBreak'] ]; // Toolbar definiton for all buttons Drupal.settings.cke_toolbar_DrupalFull = [ ['Source'], ['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker', 'Scayt'], ['Undo','Redo','Find','Replace','-','SelectAll','RemoveFormat'], ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','Iframe'], '/', ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiRtl','BidiLtr'], ['Link','Unlink','Anchor','Linkit','LinkToNode', 'LinkToMenu'], '/', ['Format','Font','FontSize'], ['TextColor','BGColor'], ['Maximize', 'ShowBlocks'], ['DrupalBreak', 'DrupalPageBreak'] ];
tazik047/Smartqueue
themes/helpdesk/ckeditor.config.js
JavaScript
gpl-2.0
4,161
/* Copyright (C) 1996-1997 Id 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 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. */ // conproc.c #include <windows.h> #include "conproc.h" #include "quakedef.h" HANDLE heventDone; HANDLE hfileBuffer; HANDLE heventChildSend; HANDLE heventParentSend; HANDLE hStdout; HANDLE hStdin; DWORD RequestProc (DWORD dwNichts); LPVOID GetMappedBuffer (HANDLE hfileBuffer); void ReleaseMappedBuffer (LPVOID pBuffer); BOOL GetScreenBufferLines (int *piLines); BOOL SetScreenBufferLines (int iLines); BOOL ReadText (LPTSTR pszText, int iBeginLine, int iEndLine); BOOL WriteText (LPCTSTR szText); int CharToCode (char c); BOOL SetConsoleCXCY(HANDLE hStdout, int cx, int cy); void InitConProc (HANDLE hFile, HANDLE heventParent, HANDLE heventChild) { DWORD dwID; CONSOLE_SCREEN_BUFFER_INFO info; int wheight, wwidth; // ignore if we don't have all the events. if (!hFile || !heventParent || !heventChild) return; hfileBuffer = hFile; heventParentSend = heventParent; heventChildSend = heventChild; // so we'll know when to go away. heventDone = CreateEvent (NULL, FALSE, FALSE, NULL); if (!heventDone) { Con_SafePrintf ("Couldn't create heventDone\n"); return; } if (!CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) RequestProc, 0, 0, &dwID)) { CloseHandle (heventDone); Con_SafePrintf ("Couldn't create QHOST thread\n"); return; } // save off the input/output handles. hStdout = GetStdHandle (STD_OUTPUT_HANDLE); hStdin = GetStdHandle (STD_INPUT_HANDLE); // force 80 character width, at least 25 character height SetConsoleCXCY (hStdout, 80, 25); } void DeinitConProc (void) { if (heventDone) SetEvent (heventDone); } DWORD RequestProc (DWORD dwNichts) { int *pBuffer; DWORD dwRet; HANDLE heventWait[2]; int iBeginLine, iEndLine; heventWait[0] = heventParentSend; heventWait[1] = heventDone; while (1) { dwRet = WaitForMultipleObjects (2, heventWait, FALSE, INFINITE); // heventDone fired, so we're exiting. if (dwRet == WAIT_OBJECT_0 + 1) break; pBuffer = (int *) GetMappedBuffer (hfileBuffer); // hfileBuffer is invalid. Just leave. if (!pBuffer) { Con_SafePrintf ("Invalid hfileBuffer\n"); break; } switch (pBuffer[0]) { case CCOM_WRITE_TEXT: // Param1 : Text pBuffer[0] = WriteText ((LPCTSTR) (pBuffer + 1)); break; case CCOM_GET_TEXT: // Param1 : Begin line // Param2 : End line iBeginLine = pBuffer[1]; iEndLine = pBuffer[2]; pBuffer[0] = ReadText ((LPTSTR) (pBuffer + 1), iBeginLine, iEndLine); break; case CCOM_GET_SCR_LINES: // No params pBuffer[0] = GetScreenBufferLines (&pBuffer[1]); break; case CCOM_SET_SCR_LINES: // Param1 : Number of lines pBuffer[0] = SetScreenBufferLines (pBuffer[1]); break; } ReleaseMappedBuffer (pBuffer); SetEvent (heventChildSend); } return 0; } LPVOID GetMappedBuffer (HANDLE hfileBuffer) { LPVOID pBuffer; pBuffer = MapViewOfFile (hfileBuffer, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); return pBuffer; } void ReleaseMappedBuffer (LPVOID pBuffer) { UnmapViewOfFile (pBuffer); } BOOL GetScreenBufferLines (int *piLines) { CONSOLE_SCREEN_BUFFER_INFO info; BOOL bRet; bRet = GetConsoleScreenBufferInfo (hStdout, &info); if (bRet) *piLines = info.dwSize.Y; return bRet; } BOOL SetScreenBufferLines (int iLines) { return SetConsoleCXCY (hStdout, 80, iLines); } BOOL ReadText (LPTSTR pszText, int iBeginLine, int iEndLine) { COORD coord; DWORD dwRead; BOOL bRet; coord.X = 0; coord.Y = iBeginLine; bRet = ReadConsoleOutputCharacter( hStdout, pszText, 80 * (iEndLine - iBeginLine + 1), coord, &dwRead); // Make sure it's null terminated. if (bRet) pszText[dwRead] = '\0'; return bRet; } BOOL WriteText (LPCTSTR szText) { DWORD dwWritten; INPUT_RECORD rec; char upper, *sz; sz = (LPTSTR) szText; while (*sz) { // 13 is the code for a carriage return (\n) instead of 10. if (*sz == 10) *sz = 13; upper = toupper(*sz); rec.EventType = KEY_EVENT; rec.Event.KeyEvent.bKeyDown = TRUE; rec.Event.KeyEvent.wRepeatCount = 1; rec.Event.KeyEvent.wVirtualKeyCode = upper; rec.Event.KeyEvent.wVirtualScanCode = CharToCode (*sz); rec.Event.KeyEvent.uChar.AsciiChar = *sz; rec.Event.KeyEvent.uChar.UnicodeChar = *sz; rec.Event.KeyEvent.dwControlKeyState = isupper(*sz) ? 0x80 : 0x0; WriteConsoleInput( hStdin, &rec, 1, &dwWritten); rec.Event.KeyEvent.bKeyDown = FALSE; WriteConsoleInput( hStdin, &rec, 1, &dwWritten); sz++; } return TRUE; } int CharToCode (char c) { char upper; upper = toupper(c); switch (c) { case 13: return 28; default: break; } if (isalpha(c)) return (30 + upper - 65); if (isdigit(c)) return (1 + upper - 47); return c; } BOOL SetConsoleCXCY(HANDLE hStdout, int cx, int cy) { CONSOLE_SCREEN_BUFFER_INFO info; COORD coordMax; coordMax = GetLargestConsoleWindowSize(hStdout); if (cy > coordMax.Y) cy = coordMax.Y; if (cx > coordMax.X) cx = coordMax.X; if (!GetConsoleScreenBufferInfo(hStdout, &info)) return FALSE; // height info.srWindow.Left = 0; info.srWindow.Right = info.dwSize.X - 1; info.srWindow.Top = 0; info.srWindow.Bottom = cy - 1; if (cy < info.dwSize.Y) { if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow)) return FALSE; info.dwSize.Y = cy; if (!SetConsoleScreenBufferSize(hStdout, info.dwSize)) return FALSE; } else if (cy > info.dwSize.Y) { info.dwSize.Y = cy; if (!SetConsoleScreenBufferSize(hStdout, info.dwSize)) return FALSE; if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow)) return FALSE; } if (!GetConsoleScreenBufferInfo(hStdout, &info)) return FALSE; // width info.srWindow.Left = 0; info.srWindow.Right = cx - 1; info.srWindow.Top = 0; info.srWindow.Bottom = info.dwSize.Y - 1; if (cx < info.dwSize.X) { if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow)) return FALSE; info.dwSize.X = cx; if (!SetConsoleScreenBufferSize(hStdout, info.dwSize)) return FALSE; } else if (cx > info.dwSize.X) { info.dwSize.X = cx; if (!SetConsoleScreenBufferSize(hStdout, info.dwSize)) return FALSE; if (!SetConsoleWindowInfo(hStdout, TRUE, &info.srWindow)) return FALSE; } return TRUE; }
fruitz-of-dojo/TenebraeQuake
tenebrae/conproc.c
C
gpl-2.0
7,487
--墓守の長 function c62473983.initial_effect(c) c:SetUniqueOnField(1,0,62473983) --immune to necro valley local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetCode(EFFECT_NECRO_VALLEY_IM) e1:SetRange(LOCATION_MZONE) e1:SetTargetRange(1,0) c:RegisterEffect(e1) --summon success local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCondition(c62473983.spcon) e2:SetTarget(c62473983.sptg) e2:SetOperation(c62473983.spop) c:RegisterEffect(e2) end function c62473983.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsSummonType(SUMMON_TYPE_ADVANCE) end function c62473983.filter(c,e,tp) return c:IsSetCard(0x2e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c62473983.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c62473983.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c62473983.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c62473983.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c62473983.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
mercury233/ygopro-scripts
c62473983.lua
Lua
gpl-2.0
1,579
#import "NMSSH.h" @class NMSSHSession, NMSFTPFile; /** NMSFTP provides functionality for working with SFTP servers. */ @interface NMSFTP : NSObject /** A valid NMSSHSession instance */ @property (nonatomic, nonnull, readonly) NMSSHSession *session; /** Property that keeps track of connection status to the server */ @property (nonatomic, readonly, getter = isConnected) BOOL connected; /** Property that set/get read buffer size */ @property (nonatomic) NSUInteger bufferSize; ///----------------------------------------------------------------------------- /// @name Initializer /// ---------------------------------------------------------------------------- /** Create a new NMSFTP instance and connect it. @param session A valid, connected, NMSSHSession instance @returns Connected NMSFTP instance */ + (nonnull instancetype)connectWithSession:(nonnull NMSSHSession *)session; /** Create a new NMSFTP instance. @param session A valid, connected, NMSSHSession instance @returns New NMSFTP instance */ - (nonnull instancetype)initWithSession:(nonnull NMSSHSession *)session; /// ---------------------------------------------------------------------------- /// @name Connection /// ---------------------------------------------------------------------------- /** Create and connect to a SFTP session @returns Connection status */ - (BOOL)connect; /** Disconnect SFTP session */ - (void)disconnect; /// ---------------------------------------------------------------------------- /// @name Manipulate file system entries /// ---------------------------------------------------------------------------- /** Move or rename an item @param sourcePath Item to move @param destPath Destination to move to @returns Move success */ - (BOOL)moveItemAtPath:(nonnull NSString *)sourcePath toPath:(nonnull NSString *)destPath; /// ---------------------------------------------------------------------------- /// @name Manipulate directories /// ---------------------------------------------------------------------------- /** Test if a directory exists at the specified path. Note: Will return NO if a file exists at the path, but not a directory. @param path Path to check @returns YES if file exists */ - (BOOL)directoryExistsAtPath:(nonnull NSString *)path; /** Create a directory at path @param path Path to directory @returns Creation success */ - (BOOL)createDirectoryAtPath:(nonnull NSString *)path; /** Remove directory at path @param path Existing directory @returns Remove success */ - (BOOL)removeDirectoryAtPath:(nonnull NSString *)path; /** Get a list of files for a directory path @param path Existing directory to list items from @returns List of relative paths */ - (nullable NSArray<NMSFTPFile *> *)contentsOfDirectoryAtPath:(nonnull NSString *)path; /// ---------------------------------------------------------------------------- /// @name Manipulate symlinks and files /// ---------------------------------------------------------------------------- /** Reads the attributes from a file. @param path An existing file path @return A NMSFTPFile that contains the fetched file attributes. */ - (nullable NMSFTPFile *)infoForFileAtPath:(nonnull NSString *)path; /** Test if a file exists at the specified path. Note: Will return NO if a directory exists at the path, but not a file. @param path Path to check @returns YES if file exists */ - (BOOL)fileExistsAtPath:(nonnull NSString *)path; /** Create a symbolic link @param linkPath Path that will be linked to @param destPath Path the link will be created at @returns Creation success */ - (BOOL)createSymbolicLinkAtPath:(nonnull NSString *)linkPath withDestinationPath:(nonnull NSString *)destPath; /** Remove file at path @param path Path to existing file @returns Remove success */ - (BOOL)removeFileAtPath:(nonnull NSString *)path; /** Read the contents of a file @param path An existing file path @returns File contents */ - (nullable NSData *)contentsAtPath:(nonnull NSString *)path; /** Refer to contentsAtPath: This adds the ability to get periodic updates to bytes received. @param path An existing file path @param progress Method called periodically with number of bytes downloaded and total file size. Returns NO to abort. @returns File contents */ - (nullable NSData *)contentsAtPath:(nonnull NSString *)path progress:(BOOL (^_Nullable)(NSUInteger got, NSUInteger totalBytes))progress; /** Refer to contentsAtPath: This adds the ability to get periodic updates to bytes received. @param path An existing file path @param stream Stream to write bytes to @param progress Method called periodically with number of bytes downloaded and total file size. Returns NO to abort. @return File read success */ - (BOOL)contentsAtPath:(nonnull NSString *)path toStream:(nonnull NSOutputStream *)stream progress:(BOOL (^_Nullable)(NSUInteger, NSUInteger))progress; /** Overwrite the contents of a file If no file exists, one is created. @param contents Bytes to write @param path File path to write bytes at @returns Write success */ - (BOOL)writeContents:(nonnull NSData *)contents toFileAtPath:(nonnull NSString *)path; /** Refer to writeContents:toFileAtPath: This adds the ability to get periodic updates to bytes sent. @param contents Bytes to write @param path File path to write bytes at @param progress Method called periodically with number of bytes sent. Returns NO to abort. @returns Write success */ - (BOOL)writeContents:(nonnull NSData *)contents toFileAtPath:(nonnull NSString *)path progress:(BOOL (^_Nullable)(NSUInteger sent))progress; /** Overwrite the contents of a file If no file exists, one is created. @param localPath File path to read bytes at @param path File path to write bytes at @returns Write success */ - (BOOL)writeFileAtPath:(nonnull NSString *)localPath toFileAtPath:(nonnull NSString *)path; /** Refer to writeFileAtPath:toFileAtPath: This adds the ability to get periodic updates to bytes sent. @param localPath File path to read bytes at @param path File path to write bytes at @param progress Method called periodically with number of bytes sent. Returns NO to abort. @returns Write success */ - (BOOL)writeFileAtPath:(nonnull NSString *)localPath toFileAtPath:(nonnull NSString *)path progress:(BOOL (^_Nullable)(NSUInteger sent))progress; /** Overwrite the contents of a file If no file exists, one is created. @param inputStream Stream to read bytes from @param path File path to write bytes at @returns Write success */ - (BOOL)writeStream:(nonnull NSInputStream *)inputStream toFileAtPath:(nonnull NSString *)path; /** Refer to writeStream:toFileAtPath: This adds the ability to get periodic updates to bytes sent. @param inputStream Stream to read bytes from @param path File path to write bytes at @param progress Method called periodically with number of bytes sent. Returns NO to abort. @returns Write success */ - (BOOL)writeStream:(nonnull NSInputStream *)inputStream toFileAtPath:(nonnull NSString *)path progress:(BOOL (^_Nullable)(NSUInteger sent))progress; /** Start or resume writing the contents of a file If no file exists, one is created. If the file already exists the size of the output file will be used as offset and the input file will be appended to the output file, starting at that offset. @param localPath File path to read bytes at @param path File path to write bytes at @param progress Method called periodically with number of bytes appended and total bytes. Returns NO to abort. @returns Write success */ - (BOOL)resumeFileAtPath:(nonnull NSString *)localPath toFileAtPath:(nonnull NSString *)path progress:(BOOL (^_Nullable)(NSUInteger delta, NSUInteger totalBytes))progress; /** Start or resume writing the contents of a file If no file exists, one is created. If the file already exists the size of the output file will be used as offset and the inputstream will be appended to the output file, starting at that offset. @param inputStream Stream to read bytes from @param path File path to write bytes at @param progress Method called periodically with number of bytes appended and total bytes. Returns NO to abort. @returns Write success */ - (BOOL)resumeStream:(nonnull NSInputStream *)inputStream toFileAtPath:(nonnull NSString *)path progress:(BOOL (^_Nullable)(NSUInteger delta, NSUInteger totalBytes))progress; /** Append contents to the end of a file If no file exists, one is created. @param contents Bytes to write @param path File path to write bytes at @returns Append success */ - (BOOL)appendContents:(nonnull NSData *)contents toFileAtPath:(nonnull NSString *)path; /** Append contents to the end of a file If no file exists, one is created. @param inputStream Stream to write bytes from @param path File path to write bytes at @returns Append success */ - (BOOL)appendStream:(nonnull NSInputStream *)inputStream toFileAtPath:(nonnull NSString *)path; /** Copy a file remotely. @param fromPath Path to copy from @param toPath Path to copy to */ - (BOOL)copyContentsOfPath:(nonnull NSString *)fromPath toFileAtPath:(nonnull NSString *)toPath progress:(BOOL (^_Nullable)(NSUInteger copied, NSUInteger totalBytes))progress; @end
lgouger/iTerm2
ThirdParty/NMSSH.framework/Versions/A/Headers/NMSFTP.h
C
gpl-2.0
9,367
/* vi: set sw=4 ts=4: */ /* * swapon() for uClibc * * Copyright (C) 2000-2004 by Erik Andersen <[email protected]> * * GNU Library General Public License (LGPL) version 2 or later. */ #include "syscalls.h" #include <sys/swap.h> _syscall2(int, swapon, const char *, path, int, swapflags);
ipwndev/DSLinux-Mirror
uClibc/libc/sysdeps/linux/common/swapon.c
C
gpl-2.0
299
namespace WikiFunctions.Profiles { partial class AWBProfilesForm { /// <summary> /// Required designer variable. /// </summary> //private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> //protected override void Dispose(bool disposing) //{ // if (disposing && (components != null)) // { // components.Dispose(); // } // base.Dispose(disposing); //} #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> protected void InitializeComponent() { this.SuspendLayout(); // // lvAccounts // this.lvAccounts.Size = new System.Drawing.Size(494, 170); this.lvAccounts.DoubleClick += new System.EventHandler(this.lvAccounts_DoubleClick); // // colAccountName // this.colAccountName.Width = 60; // // colPasswordSaved // this.colPasswordSaved.Width = 96; // // colProfileSettings // this.colProfileSettings.Width = 161; // // colNotes // this.colNotes.Width = 51; // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(93, 188); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(255, 188); // // colID // this.colID.Width = 27; // // btnClose // this.btnClose.Location = new System.Drawing.Point(431, 188); // // colUsedForUpload // this.colUsedForUpload.Width = 95; // // btnLogin // this.btnLogin.Location = new System.Drawing.Point(12, 188); this.btnLogin.Visible = true; this.btnLogin.Click += new System.EventHandler(this.btnLogin_Click); // // BtnEdit // this.BtnEdit.Location = new System.Drawing.Point(174, 188); // // AWBProfilesForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.ClientSize = new System.Drawing.Size(518, 223); this.Name = "AWBProfilesForm"; this.Controls.SetChildIndex(this.btnAdd, 0); this.Controls.SetChildIndex(this.btnClose, 0); this.Controls.SetChildIndex(this.btnDelete, 0); this.Controls.SetChildIndex(this.BtnEdit, 0); this.Controls.SetChildIndex(this.btnLogin, 0); this.Controls.SetChildIndex(this.lvAccounts, 0); this.ResumeLayout(false); } #endregion } }
svn2github/autowikibrowser
tags/REL_4_4_1/WikiFunctions/AWBProfiles/AWBProfilesForm.Designer.cs
C#
gpl-2.0
3,379
/************************************************************************** * This file is part of Celera Assembler, a software program that * assembles whole-genome shotgun reads into contigs and scaffolds. * Copyright (C) 1999-2004, Applera Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received (LICENSE.txt) 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 *************************************************************************/ static char const *rcsid = "$Id: AS_GKP_checkPlace.C 4371 2013-08-01 17:19:47Z brianwalenz $"; #include <stdio.h> #include <stdlib.h> #include "AS_global.H" #include "AS_GKP_include.H" #include "AS_PER_gkpStore.H" int Check_PlacementMesg(PlacementMesg *plc_mesg) { gkPlacement gkpl; AS_IID fragIID; AS_IID frag1IID; AS_IID frag2IID; if (plc_mesg->action == AS_ADD) gkpStore->inf.plcInput++; if (plc_mesg->action == AS_IGNORE) return 0; // Check that the bounding fragments are different // if (AS_UID_compare(plc_mesg->bound1, plc_mesg->bound2) == 0) { AS_GKP_reportError(AS_GKP_PLC_SAME_CONSTRAINT, 0, AS_UID_toString(plc_mesg->frag), AS_UID_toString(plc_mesg->bound1)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } // Check that the bounded fragment is different from the bounding fragments // if (AS_UID_compare(plc_mesg->frag, plc_mesg->bound1) == 0 || AS_UID_compare(plc_mesg->frag, plc_mesg->bound2) == 0) { AS_GKP_reportError(AS_GKP_PLC_SELF_CONSTRAINT, 0, AS_UID_toString(plc_mesg->frag)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } // Check that the three fragments are alive and well // fragIID = gkpStore->gkStore_getUIDtoIID(plc_mesg->frag, NULL); if (fragIID == 0) { AS_GKP_reportError(AS_GKP_PLC_FRG_DOESNT_EXIST, 0, AS_UID_toString(plc_mesg->frag)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } frag1IID = gkpStore->gkStore_getUIDtoIID(plc_mesg->bound1, NULL); if (frag1IID == 0) { AS_GKP_reportError(AS_GKP_PLC_FRG_DOESNT_EXIST, 0, AS_UID_toString(plc_mesg->bound1)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } frag2IID = gkpStore->gkStore_getUIDtoIID(plc_mesg->bound2, NULL); if (frag2IID == 0) { AS_GKP_reportError(AS_GKP_PLC_FRG_DOESNT_EXIST, 0, AS_UID_toString(plc_mesg->bound2)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } // Now grab the reads, we'll need them soon enough anyway. // // Make sure they're not deleted // gkpStore->gkStore_getFragment(fragIID, gkFrag1, GKFRAGMENT_INF); if (gkFrag1->gkFragment_getIsDeleted()) { AS_GKP_reportError(AS_GKP_PLC_FRG_DELETED, 0, AS_UID_toString(plc_mesg->frag)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } gkpStore->gkStore_getFragment(frag1IID, gkFrag1, GKFRAGMENT_INF); gkpStore->gkStore_getFragment(frag2IID, gkFrag2, GKFRAGMENT_INF); if (gkFrag1->gkFragment_getIsDeleted()) { AS_GKP_reportError(AS_GKP_PLC_FRG_DELETED, 0, AS_UID_toString(plc_mesg->bound1)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } if (gkFrag2->gkFragment_getIsDeleted()) { AS_GKP_reportError(AS_GKP_PLC_FRG_DELETED, 0, AS_UID_toString(plc_mesg->bound2)); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } // Make sure the fragment is not already bounded // // if already bounded, error gkPlacement *oldGkpl = gkpStore->gkStore_getReadPlacement(fragIID); if (oldGkpl != NULL) { gkpStore->gkStore_getFragment(oldGkpl->bound1, gkFrag1, GKFRAGMENT_INF); gkpStore->gkStore_getFragment(oldGkpl->bound2, gkFrag2, GKFRAGMENT_INF); AS_GKP_reportError(AS_GKP_PLC_ALREADY_CONSTRAINED, 0, AS_UID_toString(plc_mesg->frag), fragIID, AS_UID_toString(gkFrag1->gkFragment_getReadUID()), gkFrag1->gkFragment_getReadIID(), AS_UID_toString(gkFrag2->gkFragment_getReadUID()), gkFrag1->gkFragment_getReadIID(), AS_UID_toString(plc_mesg->bound1), frag1IID, AS_UID_toString(plc_mesg->bound2), frag2IID); if (plc_mesg->action == AS_ADD) gkpStore->inf.plcErrors++; return(1); } // And commit the change. if (plc_mesg->action == AS_ADD) { // store in gkp store gkpl.frag = fragIID; gkpl.bound1 = frag1IID; gkpl.bound2 = frag2IID; gkpStore->gkStore_addPlacement(&gkpl); } else { AS_GKP_reportError(AS_GKP_PLC_UNKNOWN_ACTION, 0); return 1; } return 0; }
macmanes-lab/wgs-assembler
src/AS_GKP/AS_GKP_checkPlace.C
C++
gpl-2.0
5,596
/* * tcpprobe - Observe the TCP flow with kprobes. * * The idea for this came from Werner Almesberger's umlsim * Copyright (C) 2004, Stephen Hemminger <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License. * * 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 <linux/kernel.h> #include <linux/kprobes.h> #include <linux/socket.h> #include <linux/tcp.h> #include <linux/proc_fs.h> #include <linux/module.h> #include <linux/ktime.h> #include <linux/time.h> #include <net/net_namespace.h> #include <net/tcp.h> MODULE_AUTHOR("Stephen Hemminger <[email protected]>"); MODULE_DESCRIPTION("TCP cwnd snooper"); MODULE_LICENSE("GPL"); MODULE_VERSION("1.1"); static int port __read_mostly = 0; MODULE_PARM_DESC(port, "Port to match (0=all)"); module_param(port, int, 0); static unsigned int bufsize __read_mostly = 4096; MODULE_PARM_DESC(bufsize, "Log buffer size in packets (4096)"); module_param(bufsize, uint, 0); static int full __read_mostly; MODULE_PARM_DESC(full, "Full log (1=every ack packet received, 0=only cwnd changes)"); module_param(full, int, 0); static const char procname[] = "tcpprobe"; struct tcp_log { ktime_t tstamp; __be32 saddr, daddr; __be16 sport, dport; u16 length; u32 snd_nxt; u32 snd_una; u32 snd_wnd; u32 snd_cwnd; u32 ssthresh; u32 srtt; }; static struct { spinlock_t lock; wait_queue_head_t wait; ktime_t start; u32 lastcwnd; unsigned long head, tail; struct tcp_log *log; } tcp_probe; static inline int tcp_probe_used(void) { return (tcp_probe.head - tcp_probe.tail) & (bufsize - 1); } static inline int tcp_probe_avail(void) { return bufsize - tcp_probe_used() - 1; } /* * Hook inserted to be called before each receive packet. * Note: arguments must match tcp_rcv_established()! */ static int jtcp_rcv_established(struct sock *sk, struct sk_buff *skb, struct tcphdr *th, unsigned len) { const struct tcp_sock *tp = tcp_sk(sk); const struct inet_sock *inet = inet_sk(sk); /* Only update if port matches */ if ((port == 0 || ntohs(inet->dport) == port || ntohs(inet->sport) == port) && (full || tp->snd_cwnd != tcp_probe.lastcwnd)) { spin_lock(&tcp_probe.lock); /* If log fills, just silently drop */ if (tcp_probe_avail() > 1) { struct tcp_log *p = tcp_probe.log + tcp_probe.head; p->tstamp = ktime_get(); p->saddr = inet->saddr; p->sport = inet->sport; p->daddr = inet->daddr; p->dport = inet->dport; p->length = skb->len; p->snd_nxt = tp->snd_nxt; p->snd_una = tp->snd_una; p->snd_cwnd = tp->snd_cwnd; p->snd_wnd = tp->snd_wnd; p->ssthresh = tcp_current_ssthresh(sk); p->srtt = tp->srtt >> 3; tcp_probe.head = (tcp_probe.head + 1) & (bufsize - 1); } tcp_probe.lastcwnd = tp->snd_cwnd; spin_unlock(&tcp_probe.lock); wake_up(&tcp_probe.wait); } jprobe_return(); return 0; } static struct jprobe tcp_jprobe = { .kp = { .symbol_name = "tcp_rcv_established", }, .entry = jtcp_rcv_established, }; static int tcpprobe_open(struct inode * inode, struct file * file) { /* Reset (empty) log */ spin_lock_bh(&tcp_probe.lock); tcp_probe.head = tcp_probe.tail = 0; tcp_probe.start = ktime_get(); spin_unlock_bh(&tcp_probe.lock); return 0; } static int tcpprobe_sprint(char *tbuf, int n) { const struct tcp_log *p = tcp_probe.log + tcp_probe.tail; struct timespec tv = ktime_to_timespec(ktime_sub(p->tstamp, tcp_probe.start)); return snprintf(tbuf, n, "%lu.%09lu %pI4:%u %pI4:%u %d %#x %#x %u %u %u %u\n", (unsigned long) tv.tv_sec, (unsigned long) tv.tv_nsec, &p->saddr, ntohs(p->sport), &p->daddr, ntohs(p->dport), p->length, p->snd_nxt, p->snd_una, p->snd_cwnd, p->ssthresh, p->snd_wnd, p->srtt); } static ssize_t tcpprobe_read(struct file *file, char __user *buf, size_t len, loff_t *ppos) { int error = 0; size_t cnt = 0; if (!buf) return -EINVAL; while (cnt < len) { char tbuf[128]; int width; /* Wait for data in buffer */ error = wait_event_interruptible(tcp_probe.wait, tcp_probe_used() > 0); if (error) break; spin_lock_bh(&tcp_probe.lock); if (tcp_probe.head == tcp_probe.tail) { /* multiple readers race? */ spin_unlock_bh(&tcp_probe.lock); continue; } width = tcpprobe_sprint(tbuf, sizeof(tbuf)); if (cnt + width < len) tcp_probe.tail = (tcp_probe.tail + 1) & (bufsize - 1); spin_unlock_bh(&tcp_probe.lock); /* if record greater than space available return partial buffer (so far) */ if (cnt + width >= len) break; if (copy_to_user(buf + cnt, tbuf, width)) return -EFAULT; cnt += width; } return cnt == 0 ? error : cnt; } static const struct file_operations tcpprobe_fops = { .owner = THIS_MODULE, .open = tcpprobe_open, .read = tcpprobe_read, }; static __init int tcpprobe_init(void) { int ret = -ENOMEM; init_waitqueue_head(&tcp_probe.wait); spin_lock_init(&tcp_probe.lock); if (bufsize == 0) return -EINVAL; bufsize = roundup_pow_of_two(bufsize); tcp_probe.log = kcalloc(bufsize, sizeof(struct tcp_log), GFP_KERNEL); if (!tcp_probe.log) goto err0; if (!proc_net_fops_create(&init_net, procname, S_IRUSR, &tcpprobe_fops)) goto err0; ret = register_jprobe(&tcp_jprobe); if (ret) goto err1; pr_info("TCP probe registered (port=%d) bufsize=%u\n", port, bufsize); return 0; err1: proc_net_remove(&init_net, procname); err0: kfree(tcp_probe.log); return ret; } module_init(tcpprobe_init); static __exit void tcpprobe_exit(void) { proc_net_remove(&init_net, procname); unregister_jprobe(&tcp_jprobe); kfree(tcp_probe.log); } module_exit(tcpprobe_exit);
ravikwow/jordan-kernel
net/ipv4/tcp_probe.c
C
gpl-2.0
6,178
// Copyright (C) 2017-2021 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ 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. // 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-do compile } // { dg-options "-std=c++11" } #include <set> void test01() { std::multiset<int, std::less<int>, std::allocator<long>> c; } // { dg-error "same value_type as its allocator" "" { target *-*-* } 0 }
Gurgel100/gcc
libstdc++-v3/testsuite/23_containers/multiset/48101-2_neg.cc
C++
gpl-2.0
987
<?php /** * Class AdminFlagsModel */ class AdminFlagsModel extends RoxModelBase { public function checkScopeWellFormed($scope) { $countQuotes = substr_count($scope, '"'); $countSemiColons = substr_count($scope, ';'); if ($countQuotes % 2 == 1) { return false; } if ($countQuotes > 2 && $countSemiColons <> ($countQuotes / 2)) { return false; } return true; } /** * @param $vars * @return array */ public function checkAssignVarsOk($vars) { $errors = array(); if (empty($vars['username'])) { $errors[] = 'AdminFlagsUsernameEmpty'; } else { // check if user name exists $member = new Member(); $member = $member->findByUsername($vars['username']); if (!$member) { $errors[] = 'AdminFlagsUsernameNotExisting'; } } if ($vars['flagid'] == 0) { $errors[] = 'AdminFlagsNoFlagSelected'; } else { // check if flag is already assigned if (isset($member)) { $flag = new Flag($vars['flagid']); $assigned = $flag->getFlagForMember($member); if ($assigned) { $errors[] = 'AdminFlagsAlreadyAssigned'; } } } if ($vars['level'] == 0) { $errors[] = 'AdminFlagsNoLevelSelected'; } if (empty($vars['comment'])) { $errors[] = 'AdminFlagsCommentEmpty'; } return $errors; } /** * @param $vars */ public function assignFlag($vars) { $member = new Member(); $member = $member->findByUsername($vars['username']); $query = " INSERT INTO flagsmembers SET IdFlag = '" . $this->dao->escape($vars['flagid']) . "', IdMember = '" . $member->id . "', Scope = '" . $this->dao->escape($vars['scope']) . "', Level = '" . $this->dao->escape($vars['level']) . "', Comment = '" . $this->dao->escape($vars['comment']) . "', created = NOW()"; $this->dao->query($query); } /** * get list of members with all assigned flags * * @access public * @return list of members with flags */ public function getMembersWithFlags($member = false, $includeLevelZero = false) { $query = ' SELECT m.Username, m.id as id, m.status, m.LastLogin, g.Name as PlaceName, gc.Name as CountryName, f.id flagId, fm.Level, fm.Scope, fm.Comment FROM flags f, flagsmembers fm, members m, geonames g, geonamescountries gc WHERE m.Status in (' . Member::ACTIVE_ALL . ')'; if ($member) { $query .= ' AND m.id = ' . $member->id; } $query .= ' AND fm.IdMember = m.id AND fm.IdFlag = f.id AND f.Relevance <> 0 AND m.IdCity = g.geonameid AND g.country = gc.country '; if (!$includeLevelZero) { $query .= ' AND fm.Level <> 0'; } $query .= ' ORDER BY f.Relevance DESC, m.Username, f.Name '; $result = $this->bulkLookup($query); $membersWithFlags = array(); foreach ($result as $mwr) { if (!isset($membersWithFlags[$mwr->Username])) { $memberDetails = new StdClass(); $memberDetails->id = $mwr->id; $memberDetails->Status = $mwr->status; $memberDetails->LastLogin = date('Y-m-d', strtotime($mwr->LastLogin)); $memberDetails->PlaceName = $mwr->PlaceName; $memberDetails->CountryName = $mwr->CountryName; $memberDetails->Flags = array(); $membersWithFlags[$mwr->Username] = $memberDetails; } $flagDetails = new StdClass(); $flagDetails->level = $mwr->Level; $flagDetails->scope = $mwr->Scope; $flagDetails->comment = $mwr->Comment; $membersWithFlags[$mwr->Username]->Flags[$mwr->flagId] = $flagDetails; } return $membersWithFlags; } /** * get list of flags with members with that flag * * @access public * @return list of flags with members */ public function getFlagsWithMembers($flagId = false, $includeLevelZero = false) { $query = ' SELECT f.id flagId, fm.Level, fm.Scope, fm.Comment, m.Username, m.id as id, m.status, m.LastLogin, g.Name as PlaceName, gc.Name as CountryName FROM flags f, flagsmembers fm, members m, geonames g, geonamescountries gc WHERE m.Status in (' . Member::ACTIVE_ALL . ') AND fm.IdMember = m.id AND fm.IdFlag = f.id AND f.Relevance <> 0'; if ($flagId) { $query .= ' AND f.id = ' . $flagId; } $query .= ' AND m.IdCity = g.geonameid AND g.country = gc.country '; if (!$includeLevelZero) { $query .= ' AND fm.Level <> 0'; } $query .= ' ORDER BY f.Relevance DESC, f.Name, m.Username '; $result = $this->bulkLookup($query); $flagsWithMembers = array(); foreach ($result as $rwm) { if (!isset($flagsWithMembers[$rwm->flagId])) { $flagDetails = new StdClass(); $flagDetails->Members = array(); $flagsWithMembers[$rwm->flagId] = $flagDetails; } $memberDetails = new StdClass(); $memberDetails->Status = $rwm->status; $memberDetails->LastLogin = date('Y-m-d', strtotime($rwm->LastLogin)); $memberDetails->Username = $rwm->Username; $memberDetails->PlaceName = $rwm->PlaceName; $memberDetails->CountryName = $rwm->CountryName; $memberDetails->level = $rwm->Level; $memberDetails->scope = $rwm->Scope; $memberDetails->comment = $rwm->Comment; $flagsWithMembers[$rwm->flagId]->Members[$rwm->id] = $memberDetails; } return $flagsWithMembers; } /** * get all flags defined or flags allowed for member * * @access public * @return array list of flags */ public function getFlags($memberFlagsOnly = false, $member = false) { $query = " SELECT * FROM flags f WHERE f.Relevance <> 0"; if ($memberFlagsOnly) { } $query .= " ORDER BY f.Relevance DESC, f.Name "; $memberFlags = array(); if ($member) { $memberFlags = $member->getOldFlags(); } $result = $this->bulkLookup($query, array('id')); foreach($memberFlags as $flag) { if (isset($result[$flag['id']])) { unset($result[$flag['id']]); } } return $result; } public function checkEditVarsOk($vars) { $errors = array(); if (empty($vars['comment'])) { $errors[] = 'AdminFlagsCommentEmpty'; } return $errors; } public function edit($vars) { $temp = new Member(); $member = $temp->findByUsername($vars['username']); $query = " UPDATE flagsmembers fm SET fm.Level = '" . $this->dao->escape($vars['level']) . "', fm.Scope = '" . $this->dao->escape($vars['scope']) . "', fm.Comment = '" . $this->dao->escape($vars['comment']) . "', fm.Updated = NOW() WHERE fm.IdMember = " . $member->id . " AND fm.IdFlag = " . $this->dao->escape($vars['flagid']) . " "; $this->dao->query($query); return true; } /** * Removes a flag from a member * Keeps the history by setting the level to 0 and updating the comment * with a note when the removal happened and by whom * * @param $vars * @return bool */ public function remove($vars) { $temp = new Member(); $member = $temp->findByUsername($vars['username']); $loggedInMember = $this->getLoggedInMember(); $comment = $vars['comment'] . "\n\nRemoved by " .$loggedInMember->Username . " on " . date('Y-m-d'); $query = " UPDATE flagsmembers fm SET fm.Level = '0', fm.Scope = '" . $this->dao->escape($vars['scope']) . "', fm.Comment = '" . $this->dao->escape( $comment ) . "', fm.Updated = NOW() WHERE fm.IdMember = " . $member->id . " AND fm.IdFlag = " . $this->dao->escape($vars['flagid']) . " "; $this->dao->query($query); return true; } public function checkCreateVarsOk($vars) { $errors = array(); if (empty($vars['name'])) { $errors[] = 'AdminFlagsNameEmpty'; } else { $query = " SELECT * FROM flags f WHERE f.Name LIKE '" . $this->dao->escape($vars['name']) . "'"; $name = $this->singleLookup($query); if ($name) { $errors[] = 'AdminFlagsFlagExists'; } } if (empty($vars['description'])) { $errors[] = 'AdminFlagsDescriptionEmpty'; } if (empty($vars['relevance'])) { $errors[] = 'AdminFlagsRelevance'; } return $errors; } public function createFlag($vars) { $query = " INSERT INTO flags SET `Name` = '" . $this->dao->escape($vars['name']) . "', `Description` = '" . $this->dao->escape($vars['description']) . "', `Relevance` = '100' "; $this->dao->query($query); return true; } }
thisismeonmounteverest/rox
build/admin/flags/adminflags.model.php
PHP
gpl-2.0
10,955
/* * Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. * Copyright (C) 2004-2007 Red Hat, Inc. 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 General Public License version 2. */ /* * Quota change tags are associated with each transaction that allocates or * deallocates space. Those changes are accumulated locally to each node (in a * per-node file) and then are periodically synced to the quota file. This * avoids the bottleneck of constantly touching the quota file, but introduces * fuzziness in the current usage value of IDs that are being used on different * nodes in the cluster simultaneously. So, it is possible for a user on * multiple nodes to overrun their quota, but that overrun is controlable. * Since quota tags are part of transactions, there is no need for a quota check * program to be run on node crashes or anything like that. * * There are couple of knobs that let the administrator manage the quota * fuzziness. "quota_quantum" sets the maximum time a quota change can be * sitting on one node before being synced to the quota file. (The default is * 60 seconds.) Another knob, "quota_scale" controls how quickly the frequency * of quota file syncs increases as the user moves closer to their limit. The * more frequent the syncs, the more accurate the quota enforcement, but that * means that there is more contention between the nodes for the quota file. * The default value is one. This sets the maximum theoretical quota overrun * (with infinite node with infinite bandwidth) to twice the user's limit. (In * practice, the maximum overrun you see should be much less.) A "quota_scale" * number greater than one makes quota syncs more frequent and reduces the * maximum overrun. Numbers less than one (but greater than zero) make quota * syncs less frequent. * * GFS quotas also use per-ID Lock Value Blocks (LVBs) to cache the contents of * the quota file, so it is not being constantly read. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/sched.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/spinlock.h> #include <linux/completion.h> #include <linux/buffer_head.h> #include <linux/sort.h> #include <linux/fs.h> #include <linux/bio.h> #include <linux/gfs2_ondisk.h> #include <linux/kthread.h> #include <linux/freezer.h> #include <linux/quota.h> #include <linux/dqblk_xfs.h> #include <linux/lockref.h> #include <linux/list_lru.h> #include <linux/rcupdate.h> #include <linux/rculist_bl.h> #include <linux/bit_spinlock.h> #include <linux/jhash.h> #include <linux/vmalloc.h> #include "gfs2.h" #include "incore.h" #include "bmap.h" #include "glock.h" #include "glops.h" #include "log.h" #include "meta_io.h" #include "quota.h" #include "rgrp.h" #include "super.h" #include "trans.h" #include "inode.h" #include "util.h" #define GFS2_QD_HASH_SHIFT 12 #define GFS2_QD_HASH_SIZE BIT(GFS2_QD_HASH_SHIFT) #define GFS2_QD_HASH_MASK (GFS2_QD_HASH_SIZE - 1) /* Lock order: qd_lock -> bucket lock -> qd->lockref.lock -> lru lock */ /* -> sd_bitmap_lock */ static DEFINE_SPINLOCK(qd_lock); struct list_lru gfs2_qd_lru; static struct hlist_bl_head qd_hash_table[GFS2_QD_HASH_SIZE]; static unsigned int gfs2_qd_hash(const struct gfs2_sbd *sdp, const struct kqid qid) { unsigned int h; h = jhash(&sdp, sizeof(struct gfs2_sbd *), 0); h = jhash(&qid, sizeof(struct kqid), h); return h & GFS2_QD_HASH_MASK; } static inline void spin_lock_bucket(unsigned int hash) { hlist_bl_lock(&qd_hash_table[hash]); } static inline void spin_unlock_bucket(unsigned int hash) { hlist_bl_unlock(&qd_hash_table[hash]); } static void gfs2_qd_dealloc(struct rcu_head *rcu) { struct gfs2_quota_data *qd = container_of(rcu, struct gfs2_quota_data, qd_rcu); kmem_cache_free(gfs2_quotad_cachep, qd); } static void gfs2_qd_dispose(struct list_head *list) { struct gfs2_quota_data *qd; struct gfs2_sbd *sdp; while (!list_empty(list)) { qd = list_entry(list->next, struct gfs2_quota_data, qd_lru); sdp = qd->qd_gl->gl_name.ln_sbd; list_del(&qd->qd_lru); /* Free from the filesystem-specific list */ spin_lock(&qd_lock); list_del(&qd->qd_list); spin_unlock(&qd_lock); spin_lock_bucket(qd->qd_hash); hlist_bl_del_rcu(&qd->qd_hlist); spin_unlock_bucket(qd->qd_hash); gfs2_assert_warn(sdp, !qd->qd_change); gfs2_assert_warn(sdp, !qd->qd_slot_count); gfs2_assert_warn(sdp, !qd->qd_bh_count); gfs2_glock_put(qd->qd_gl); atomic_dec(&sdp->sd_quota_count); /* Delete it from the common reclaim list */ call_rcu(&qd->qd_rcu, gfs2_qd_dealloc); } } static enum lru_status gfs2_qd_isolate(struct list_head *item, struct list_lru_one *lru, spinlock_t *lru_lock, void *arg) { struct list_head *dispose = arg; struct gfs2_quota_data *qd = list_entry(item, struct gfs2_quota_data, qd_lru); if (!spin_trylock(&qd->qd_lockref.lock)) return LRU_SKIP; if (qd->qd_lockref.count == 0) { lockref_mark_dead(&qd->qd_lockref); list_lru_isolate_move(lru, &qd->qd_lru, dispose); } spin_unlock(&qd->qd_lockref.lock); return LRU_REMOVED; } static unsigned long gfs2_qd_shrink_scan(struct shrinker *shrink, struct shrink_control *sc) { LIST_HEAD(dispose); unsigned long freed; if (!(sc->gfp_mask & __GFP_FS)) return SHRINK_STOP; freed = list_lru_shrink_walk(&gfs2_qd_lru, sc, gfs2_qd_isolate, &dispose); gfs2_qd_dispose(&dispose); return freed; } static unsigned long gfs2_qd_shrink_count(struct shrinker *shrink, struct shrink_control *sc) { return vfs_pressure_ratio(list_lru_shrink_count(&gfs2_qd_lru, sc)); } struct shrinker gfs2_qd_shrinker = { .count_objects = gfs2_qd_shrink_count, .scan_objects = gfs2_qd_shrink_scan, .seeks = DEFAULT_SEEKS, .flags = SHRINKER_NUMA_AWARE, }; static u64 qd2index(struct gfs2_quota_data *qd) { struct kqid qid = qd->qd_id; return (2 * (u64)from_kqid(&init_user_ns, qid)) + ((qid.type == USRQUOTA) ? 0 : 1); } static u64 qd2offset(struct gfs2_quota_data *qd) { u64 offset; offset = qd2index(qd); offset *= sizeof(struct gfs2_quota); return offset; } static struct gfs2_quota_data *qd_alloc(unsigned hash, struct gfs2_sbd *sdp, struct kqid qid) { struct gfs2_quota_data *qd; int error; qd = kmem_cache_zalloc(gfs2_quotad_cachep, GFP_NOFS); if (!qd) return NULL; qd->qd_sbd = sdp; qd->qd_lockref.count = 1; spin_lock_init(&qd->qd_lockref.lock); qd->qd_id = qid; qd->qd_slot = -1; INIT_LIST_HEAD(&qd->qd_lru); qd->qd_hash = hash; error = gfs2_glock_get(sdp, qd2index(qd), &gfs2_quota_glops, CREATE, &qd->qd_gl); if (error) goto fail; return qd; fail: kmem_cache_free(gfs2_quotad_cachep, qd); return NULL; } static struct gfs2_quota_data *gfs2_qd_search_bucket(unsigned int hash, const struct gfs2_sbd *sdp, struct kqid qid) { struct gfs2_quota_data *qd; struct hlist_bl_node *h; hlist_bl_for_each_entry_rcu(qd, h, &qd_hash_table[hash], qd_hlist) { if (!qid_eq(qd->qd_id, qid)) continue; if (qd->qd_sbd != sdp) continue; if (lockref_get_not_dead(&qd->qd_lockref)) { list_lru_del(&gfs2_qd_lru, &qd->qd_lru); return qd; } } return NULL; } static int qd_get(struct gfs2_sbd *sdp, struct kqid qid, struct gfs2_quota_data **qdp) { struct gfs2_quota_data *qd, *new_qd; unsigned int hash = gfs2_qd_hash(sdp, qid); rcu_read_lock(); *qdp = qd = gfs2_qd_search_bucket(hash, sdp, qid); rcu_read_unlock(); if (qd) return 0; new_qd = qd_alloc(hash, sdp, qid); if (!new_qd) return -ENOMEM; spin_lock(&qd_lock); spin_lock_bucket(hash); *qdp = qd = gfs2_qd_search_bucket(hash, sdp, qid); if (qd == NULL) { *qdp = new_qd; list_add(&new_qd->qd_list, &sdp->sd_quota_list); hlist_bl_add_head_rcu(&new_qd->qd_hlist, &qd_hash_table[hash]); atomic_inc(&sdp->sd_quota_count); } spin_unlock_bucket(hash); spin_unlock(&qd_lock); if (qd) { gfs2_glock_put(new_qd->qd_gl); kmem_cache_free(gfs2_quotad_cachep, new_qd); } return 0; } static void qd_hold(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; gfs2_assert(sdp, !__lockref_is_dead(&qd->qd_lockref)); lockref_get(&qd->qd_lockref); } static void qd_put(struct gfs2_quota_data *qd) { if (lockref_put_or_lock(&qd->qd_lockref)) return; qd->qd_lockref.count = 0; list_lru_add(&gfs2_qd_lru, &qd->qd_lru); spin_unlock(&qd->qd_lockref.lock); } static int slot_get(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_sbd; unsigned int bit; int error = 0; spin_lock(&sdp->sd_bitmap_lock); if (qd->qd_slot_count != 0) goto out; error = -ENOSPC; bit = find_first_zero_bit(sdp->sd_quota_bitmap, sdp->sd_quota_slots); if (bit < sdp->sd_quota_slots) { set_bit(bit, sdp->sd_quota_bitmap); qd->qd_slot = bit; error = 0; out: qd->qd_slot_count++; } spin_unlock(&sdp->sd_bitmap_lock); return error; } static void slot_hold(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_sbd; spin_lock(&sdp->sd_bitmap_lock); gfs2_assert(sdp, qd->qd_slot_count); qd->qd_slot_count++; spin_unlock(&sdp->sd_bitmap_lock); } static void slot_put(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_sbd; spin_lock(&sdp->sd_bitmap_lock); gfs2_assert(sdp, qd->qd_slot_count); if (!--qd->qd_slot_count) { BUG_ON(!test_and_clear_bit(qd->qd_slot, sdp->sd_quota_bitmap)); qd->qd_slot = -1; } spin_unlock(&sdp->sd_bitmap_lock); } static int bh_get(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode); unsigned int block, offset; struct buffer_head *bh; int error; struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; mutex_lock(&sdp->sd_quota_mutex); if (qd->qd_bh_count++) { mutex_unlock(&sdp->sd_quota_mutex); return 0; } block = qd->qd_slot / sdp->sd_qc_per_block; offset = qd->qd_slot % sdp->sd_qc_per_block; bh_map.b_size = BIT(ip->i_inode.i_blkbits); error = gfs2_block_map(&ip->i_inode, block, &bh_map, 0); if (error) goto fail; error = gfs2_meta_read(ip->i_gl, bh_map.b_blocknr, DIO_WAIT, 0, &bh); if (error) goto fail; error = -EIO; if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_QC)) goto fail_brelse; qd->qd_bh = bh; qd->qd_bh_qc = (struct gfs2_quota_change *) (bh->b_data + sizeof(struct gfs2_meta_header) + offset * sizeof(struct gfs2_quota_change)); mutex_unlock(&sdp->sd_quota_mutex); return 0; fail_brelse: brelse(bh); fail: qd->qd_bh_count--; mutex_unlock(&sdp->sd_quota_mutex); return error; } static void bh_put(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; mutex_lock(&sdp->sd_quota_mutex); gfs2_assert(sdp, qd->qd_bh_count); if (!--qd->qd_bh_count) { brelse(qd->qd_bh); qd->qd_bh = NULL; qd->qd_bh_qc = NULL; } mutex_unlock(&sdp->sd_quota_mutex); } static int qd_check_sync(struct gfs2_sbd *sdp, struct gfs2_quota_data *qd, u64 *sync_gen) { if (test_bit(QDF_LOCKED, &qd->qd_flags) || !test_bit(QDF_CHANGE, &qd->qd_flags) || (sync_gen && (qd->qd_sync_gen >= *sync_gen))) return 0; if (!lockref_get_not_dead(&qd->qd_lockref)) return 0; list_move_tail(&qd->qd_list, &sdp->sd_quota_list); set_bit(QDF_LOCKED, &qd->qd_flags); qd->qd_change_sync = qd->qd_change; slot_hold(qd); return 1; } static int qd_fish(struct gfs2_sbd *sdp, struct gfs2_quota_data **qdp) { struct gfs2_quota_data *qd = NULL; int error; int found = 0; *qdp = NULL; if (sdp->sd_vfs->s_flags & MS_RDONLY) return 0; spin_lock(&qd_lock); list_for_each_entry(qd, &sdp->sd_quota_list, qd_list) { found = qd_check_sync(sdp, qd, &sdp->sd_quota_sync_gen); if (found) break; } if (!found) qd = NULL; spin_unlock(&qd_lock); if (qd) { gfs2_assert_warn(sdp, qd->qd_change_sync); error = bh_get(qd); if (error) { clear_bit(QDF_LOCKED, &qd->qd_flags); slot_put(qd); qd_put(qd); return error; } } *qdp = qd; return 0; } static void qd_unlock(struct gfs2_quota_data *qd) { gfs2_assert_warn(qd->qd_gl->gl_name.ln_sbd, test_bit(QDF_LOCKED, &qd->qd_flags)); clear_bit(QDF_LOCKED, &qd->qd_flags); bh_put(qd); slot_put(qd); qd_put(qd); } static int qdsb_get(struct gfs2_sbd *sdp, struct kqid qid, struct gfs2_quota_data **qdp) { int error; error = qd_get(sdp, qid, qdp); if (error) return error; error = slot_get(*qdp); if (error) goto fail; error = bh_get(*qdp); if (error) goto fail_slot; return 0; fail_slot: slot_put(*qdp); fail: qd_put(*qdp); return error; } static void qdsb_put(struct gfs2_quota_data *qd) { bh_put(qd); slot_put(qd); qd_put(qd); } /** * gfs2_qa_alloc - make sure we have a quota allocations data structure, * if necessary * @ip: the inode for this reservation */ int gfs2_qa_alloc(struct gfs2_inode *ip) { int error = 0; struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF) return 0; down_write(&ip->i_rw_mutex); if (ip->i_qadata == NULL) { ip->i_qadata = kmem_cache_zalloc(gfs2_qadata_cachep, GFP_NOFS); if (!ip->i_qadata) error = -ENOMEM; } up_write(&ip->i_rw_mutex); return error; } void gfs2_qa_delete(struct gfs2_inode *ip, atomic_t *wcount) { down_write(&ip->i_rw_mutex); if (ip->i_qadata && ((wcount == NULL) || (atomic_read(wcount) <= 1))) { kmem_cache_free(gfs2_qadata_cachep, ip->i_qadata); ip->i_qadata = NULL; } up_write(&ip->i_rw_mutex); } int gfs2_quota_hold(struct gfs2_inode *ip, kuid_t uid, kgid_t gid) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct gfs2_quota_data **qd; int error; if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF) return 0; if (ip->i_qadata == NULL) { error = gfs2_rsqa_alloc(ip); if (error) return error; } qd = ip->i_qadata->qa_qd; if (gfs2_assert_warn(sdp, !ip->i_qadata->qa_qd_num) || gfs2_assert_warn(sdp, !test_bit(GIF_QD_LOCKED, &ip->i_flags))) return -EIO; error = qdsb_get(sdp, make_kqid_uid(ip->i_inode.i_uid), qd); if (error) goto out; ip->i_qadata->qa_qd_num++; qd++; error = qdsb_get(sdp, make_kqid_gid(ip->i_inode.i_gid), qd); if (error) goto out; ip->i_qadata->qa_qd_num++; qd++; if (!uid_eq(uid, NO_UID_QUOTA_CHANGE) && !uid_eq(uid, ip->i_inode.i_uid)) { error = qdsb_get(sdp, make_kqid_uid(uid), qd); if (error) goto out; ip->i_qadata->qa_qd_num++; qd++; } if (!gid_eq(gid, NO_GID_QUOTA_CHANGE) && !gid_eq(gid, ip->i_inode.i_gid)) { error = qdsb_get(sdp, make_kqid_gid(gid), qd); if (error) goto out; ip->i_qadata->qa_qd_num++; qd++; } out: if (error) gfs2_quota_unhold(ip); return error; } void gfs2_quota_unhold(struct gfs2_inode *ip) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); u32 x; if (ip->i_qadata == NULL) return; gfs2_assert_warn(sdp, !test_bit(GIF_QD_LOCKED, &ip->i_flags)); for (x = 0; x < ip->i_qadata->qa_qd_num; x++) { qdsb_put(ip->i_qadata->qa_qd[x]); ip->i_qadata->qa_qd[x] = NULL; } ip->i_qadata->qa_qd_num = 0; } static int sort_qd(const void *a, const void *b) { const struct gfs2_quota_data *qd_a = *(const struct gfs2_quota_data **)a; const struct gfs2_quota_data *qd_b = *(const struct gfs2_quota_data **)b; if (qid_lt(qd_a->qd_id, qd_b->qd_id)) return -1; if (qid_lt(qd_b->qd_id, qd_a->qd_id)) return 1; return 0; } static void do_qc(struct gfs2_quota_data *qd, s64 change) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode); struct gfs2_quota_change *qc = qd->qd_bh_qc; s64 x; mutex_lock(&sdp->sd_quota_mutex); gfs2_trans_add_meta(ip->i_gl, qd->qd_bh); if (!test_bit(QDF_CHANGE, &qd->qd_flags)) { qc->qc_change = 0; qc->qc_flags = 0; if (qd->qd_id.type == USRQUOTA) qc->qc_flags = cpu_to_be32(GFS2_QCF_USER); qc->qc_id = cpu_to_be32(from_kqid(&init_user_ns, qd->qd_id)); } x = be64_to_cpu(qc->qc_change) + change; qc->qc_change = cpu_to_be64(x); spin_lock(&qd_lock); qd->qd_change = x; spin_unlock(&qd_lock); if (!x) { gfs2_assert_warn(sdp, test_bit(QDF_CHANGE, &qd->qd_flags)); clear_bit(QDF_CHANGE, &qd->qd_flags); qc->qc_flags = 0; qc->qc_id = 0; slot_put(qd); qd_put(qd); } else if (!test_and_set_bit(QDF_CHANGE, &qd->qd_flags)) { qd_hold(qd); slot_hold(qd); } if (change < 0) /* Reset quiet flag if we freed some blocks */ clear_bit(QDF_QMSG_QUIET, &qd->qd_flags); mutex_unlock(&sdp->sd_quota_mutex); } static int gfs2_write_buf_to_page(struct gfs2_inode *ip, unsigned long index, unsigned off, void *buf, unsigned bytes) { struct inode *inode = &ip->i_inode; struct gfs2_sbd *sdp = GFS2_SB(inode); struct address_space *mapping = inode->i_mapping; struct page *page; struct buffer_head *bh; void *kaddr; u64 blk; unsigned bsize = sdp->sd_sb.sb_bsize, bnum = 0, boff = 0; unsigned to_write = bytes, pg_off = off; int done = 0; blk = index << (PAGE_SHIFT - sdp->sd_sb.sb_bsize_shift); boff = off % bsize; page = find_or_create_page(mapping, index, GFP_NOFS); if (!page) return -ENOMEM; if (!page_has_buffers(page)) create_empty_buffers(page, bsize, 0); bh = page_buffers(page); while (!done) { /* Find the beginning block within the page */ if (pg_off >= ((bnum * bsize) + bsize)) { bh = bh->b_this_page; bnum++; blk++; continue; } if (!buffer_mapped(bh)) { gfs2_block_map(inode, blk, bh, 1); if (!buffer_mapped(bh)) goto unlock_out; /* If it's a newly allocated disk block, zero it */ if (buffer_new(bh)) zero_user(page, bnum * bsize, bh->b_size); } if (PageUptodate(page)) set_buffer_uptodate(bh); if (!buffer_uptodate(bh)) { ll_rw_block(REQ_OP_READ, REQ_META, 1, &bh); wait_on_buffer(bh); if (!buffer_uptodate(bh)) goto unlock_out; } gfs2_trans_add_data(ip->i_gl, bh); /* If we need to write to the next block as well */ if (to_write > (bsize - boff)) { pg_off += (bsize - boff); to_write -= (bsize - boff); boff = pg_off % bsize; continue; } done = 1; } /* Write to the page, now that we have setup the buffer(s) */ kaddr = kmap_atomic(page); memcpy(kaddr + off, buf, bytes); flush_dcache_page(page); kunmap_atomic(kaddr); unlock_page(page); put_page(page); return 0; unlock_out: unlock_page(page); put_page(page); return -EIO; } static int gfs2_write_disk_quota(struct gfs2_inode *ip, struct gfs2_quota *qp, loff_t loc) { unsigned long pg_beg; unsigned pg_off, nbytes, overflow = 0; int pg_oflow = 0, error; void *ptr; nbytes = sizeof(struct gfs2_quota); pg_beg = loc >> PAGE_SHIFT; pg_off = loc % PAGE_SIZE; /* If the quota straddles a page boundary, split the write in two */ if ((pg_off + nbytes) > PAGE_SIZE) { pg_oflow = 1; overflow = (pg_off + nbytes) - PAGE_SIZE; } ptr = qp; error = gfs2_write_buf_to_page(ip, pg_beg, pg_off, ptr, nbytes - overflow); /* If there's an overflow, write the remaining bytes to the next page */ if (!error && pg_oflow) error = gfs2_write_buf_to_page(ip, pg_beg + 1, 0, ptr + nbytes - overflow, overflow); return error; } /** * gfs2_adjust_quota - adjust record of current block usage * @ip: The quota inode * @loc: Offset of the entry in the quota file * @change: The amount of usage change to record * @qd: The quota data * @fdq: The updated limits to record * * This function was mostly borrowed from gfs2_block_truncate_page which was * in turn mostly borrowed from ext3 * * Returns: 0 or -ve on error */ static int gfs2_adjust_quota(struct gfs2_inode *ip, loff_t loc, s64 change, struct gfs2_quota_data *qd, struct qc_dqblk *fdq) { struct inode *inode = &ip->i_inode; struct gfs2_sbd *sdp = GFS2_SB(inode); struct gfs2_quota q; int err; u64 size; if (gfs2_is_stuffed(ip)) { err = gfs2_unstuff_dinode(ip, NULL); if (err) return err; } memset(&q, 0, sizeof(struct gfs2_quota)); err = gfs2_internal_read(ip, (char *)&q, &loc, sizeof(q)); if (err < 0) return err; loc -= sizeof(q); /* gfs2_internal_read would've advanced the loc ptr */ err = -EIO; be64_add_cpu(&q.qu_value, change); if (((s64)be64_to_cpu(q.qu_value)) < 0) q.qu_value = 0; /* Never go negative on quota usage */ qd->qd_qb.qb_value = q.qu_value; if (fdq) { if (fdq->d_fieldmask & QC_SPC_SOFT) { q.qu_warn = cpu_to_be64(fdq->d_spc_softlimit >> sdp->sd_sb.sb_bsize_shift); qd->qd_qb.qb_warn = q.qu_warn; } if (fdq->d_fieldmask & QC_SPC_HARD) { q.qu_limit = cpu_to_be64(fdq->d_spc_hardlimit >> sdp->sd_sb.sb_bsize_shift); qd->qd_qb.qb_limit = q.qu_limit; } if (fdq->d_fieldmask & QC_SPACE) { q.qu_value = cpu_to_be64(fdq->d_space >> sdp->sd_sb.sb_bsize_shift); qd->qd_qb.qb_value = q.qu_value; } } err = gfs2_write_disk_quota(ip, &q, loc); if (!err) { size = loc + sizeof(struct gfs2_quota); if (size > inode->i_size) i_size_write(inode, size); inode->i_mtime = inode->i_atime = CURRENT_TIME; mark_inode_dirty(inode); set_bit(QDF_REFRESH, &qd->qd_flags); } return err; } static int do_sync(unsigned int num_qd, struct gfs2_quota_data **qda) { struct gfs2_sbd *sdp = (*qda)->qd_gl->gl_name.ln_sbd; struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode); struct gfs2_alloc_parms ap = { .aflags = 0, }; unsigned int data_blocks, ind_blocks; struct gfs2_holder *ghs, i_gh; unsigned int qx, x; struct gfs2_quota_data *qd; unsigned reserved; loff_t offset; unsigned int nalloc = 0, blocks; int error; error = gfs2_rsqa_alloc(ip); if (error) return error; gfs2_write_calc_reserv(ip, sizeof(struct gfs2_quota), &data_blocks, &ind_blocks); ghs = kmalloc(num_qd * sizeof(struct gfs2_holder), GFP_NOFS); if (!ghs) return -ENOMEM; sort(qda, num_qd, sizeof(struct gfs2_quota_data *), sort_qd, NULL); inode_lock(&ip->i_inode); for (qx = 0; qx < num_qd; qx++) { error = gfs2_glock_nq_init(qda[qx]->qd_gl, LM_ST_EXCLUSIVE, GL_NOCACHE, &ghs[qx]); if (error) goto out; } error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh); if (error) goto out; for (x = 0; x < num_qd; x++) { offset = qd2offset(qda[x]); if (gfs2_write_alloc_required(ip, offset, sizeof(struct gfs2_quota))) nalloc++; } /* * 1 blk for unstuffing inode if stuffed. We add this extra * block to the reservation unconditionally. If the inode * doesn't need unstuffing, the block will be released to the * rgrp since it won't be allocated during the transaction */ /* +3 in the end for unstuffing block, inode size update block * and another block in case quota straddles page boundary and * two blocks need to be updated instead of 1 */ blocks = num_qd * data_blocks + RES_DINODE + num_qd + 3; reserved = 1 + (nalloc * (data_blocks + ind_blocks)); ap.target = reserved; error = gfs2_inplace_reserve(ip, &ap); if (error) goto out_alloc; if (nalloc) blocks += gfs2_rg_blocks(ip, reserved) + nalloc * ind_blocks + RES_STATFS; error = gfs2_trans_begin(sdp, blocks, 0); if (error) goto out_ipres; for (x = 0; x < num_qd; x++) { qd = qda[x]; offset = qd2offset(qd); error = gfs2_adjust_quota(ip, offset, qd->qd_change_sync, qd, NULL); if (error) goto out_end_trans; do_qc(qd, -qd->qd_change_sync); set_bit(QDF_REFRESH, &qd->qd_flags); } error = 0; out_end_trans: gfs2_trans_end(sdp); out_ipres: gfs2_inplace_release(ip); out_alloc: gfs2_glock_dq_uninit(&i_gh); out: while (qx--) gfs2_glock_dq_uninit(&ghs[qx]); inode_unlock(&ip->i_inode); kfree(ghs); gfs2_log_flush(ip->i_gl->gl_name.ln_sbd, ip->i_gl, NORMAL_FLUSH); return error; } static int update_qd(struct gfs2_sbd *sdp, struct gfs2_quota_data *qd) { struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode); struct gfs2_quota q; struct gfs2_quota_lvb *qlvb; loff_t pos; int error; memset(&q, 0, sizeof(struct gfs2_quota)); pos = qd2offset(qd); error = gfs2_internal_read(ip, (char *)&q, &pos, sizeof(q)); if (error < 0) return error; qlvb = (struct gfs2_quota_lvb *)qd->qd_gl->gl_lksb.sb_lvbptr; qlvb->qb_magic = cpu_to_be32(GFS2_MAGIC); qlvb->__pad = 0; qlvb->qb_limit = q.qu_limit; qlvb->qb_warn = q.qu_warn; qlvb->qb_value = q.qu_value; qd->qd_qb = *qlvb; return 0; } static int do_glock(struct gfs2_quota_data *qd, int force_refresh, struct gfs2_holder *q_gh) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode); struct gfs2_holder i_gh; int error; restart: error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_SHARED, 0, q_gh); if (error) return error; if (test_and_clear_bit(QDF_REFRESH, &qd->qd_flags)) force_refresh = FORCE; qd->qd_qb = *(struct gfs2_quota_lvb *)qd->qd_gl->gl_lksb.sb_lvbptr; if (force_refresh || qd->qd_qb.qb_magic != cpu_to_be32(GFS2_MAGIC)) { gfs2_glock_dq_uninit(q_gh); error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_EXCLUSIVE, GL_NOCACHE, q_gh); if (error) return error; error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, 0, &i_gh); if (error) goto fail; error = update_qd(sdp, qd); if (error) goto fail_gunlock; gfs2_glock_dq_uninit(&i_gh); gfs2_glock_dq_uninit(q_gh); force_refresh = 0; goto restart; } return 0; fail_gunlock: gfs2_glock_dq_uninit(&i_gh); fail: gfs2_glock_dq_uninit(q_gh); return error; } int gfs2_quota_lock(struct gfs2_inode *ip, kuid_t uid, kgid_t gid) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct gfs2_quota_data *qd; u32 x; int error = 0; if (capable(CAP_SYS_RESOURCE) || sdp->sd_args.ar_quota != GFS2_QUOTA_ON) return 0; error = gfs2_quota_hold(ip, uid, gid); if (error) return error; sort(ip->i_qadata->qa_qd, ip->i_qadata->qa_qd_num, sizeof(struct gfs2_quota_data *), sort_qd, NULL); for (x = 0; x < ip->i_qadata->qa_qd_num; x++) { qd = ip->i_qadata->qa_qd[x]; error = do_glock(qd, NO_FORCE, &ip->i_qadata->qa_qd_ghs[x]); if (error) break; } if (!error) set_bit(GIF_QD_LOCKED, &ip->i_flags); else { while (x--) gfs2_glock_dq_uninit(&ip->i_qadata->qa_qd_ghs[x]); gfs2_quota_unhold(ip); } return error; } static int need_sync(struct gfs2_quota_data *qd) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; struct gfs2_tune *gt = &sdp->sd_tune; s64 value; unsigned int num, den; int do_sync = 1; if (!qd->qd_qb.qb_limit) return 0; spin_lock(&qd_lock); value = qd->qd_change; spin_unlock(&qd_lock); spin_lock(&gt->gt_spin); num = gt->gt_quota_scale_num; den = gt->gt_quota_scale_den; spin_unlock(&gt->gt_spin); if (value < 0) do_sync = 0; else if ((s64)be64_to_cpu(qd->qd_qb.qb_value) >= (s64)be64_to_cpu(qd->qd_qb.qb_limit)) do_sync = 0; else { value *= gfs2_jindex_size(sdp) * num; value = div_s64(value, den); value += (s64)be64_to_cpu(qd->qd_qb.qb_value); if (value < (s64)be64_to_cpu(qd->qd_qb.qb_limit)) do_sync = 0; } return do_sync; } void gfs2_quota_unlock(struct gfs2_inode *ip) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct gfs2_quota_data *qda[4]; unsigned int count = 0; u32 x; int found; if (!test_and_clear_bit(GIF_QD_LOCKED, &ip->i_flags)) goto out; for (x = 0; x < ip->i_qadata->qa_qd_num; x++) { struct gfs2_quota_data *qd; int sync; qd = ip->i_qadata->qa_qd[x]; sync = need_sync(qd); gfs2_glock_dq_uninit(&ip->i_qadata->qa_qd_ghs[x]); if (!sync) continue; spin_lock(&qd_lock); found = qd_check_sync(sdp, qd, NULL); spin_unlock(&qd_lock); if (!found) continue; gfs2_assert_warn(sdp, qd->qd_change_sync); if (bh_get(qd)) { clear_bit(QDF_LOCKED, &qd->qd_flags); slot_put(qd); qd_put(qd); continue; } qda[count++] = qd; } if (count) { do_sync(count, qda); for (x = 0; x < count; x++) qd_unlock(qda[x]); } out: gfs2_quota_unhold(ip); } #define MAX_LINE 256 static int print_message(struct gfs2_quota_data *qd, char *type) { struct gfs2_sbd *sdp = qd->qd_gl->gl_name.ln_sbd; fs_info(sdp, "quota %s for %s %u\n", type, (qd->qd_id.type == USRQUOTA) ? "user" : "group", from_kqid(&init_user_ns, qd->qd_id)); return 0; } /** * gfs2_quota_check - check if allocating new blocks will exceed quota * @ip: The inode for which this check is being performed * @uid: The uid to check against * @gid: The gid to check against * @ap: The allocation parameters. ap->target contains the requested * blocks. ap->min_target, if set, contains the minimum blks * requested. * * Returns: 0 on success. * min_req = ap->min_target ? ap->min_target : ap->target; * quota must allow atleast min_req blks for success and * ap->allowed is set to the number of blocks allowed * * -EDQUOT otherwise, quota violation. ap->allowed is set to number * of blocks available. */ int gfs2_quota_check(struct gfs2_inode *ip, kuid_t uid, kgid_t gid, struct gfs2_alloc_parms *ap) { struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); struct gfs2_quota_data *qd; s64 value, warn, limit; u32 x; int error = 0; ap->allowed = UINT_MAX; /* Assume we are permitted a whole lot */ if (!test_bit(GIF_QD_LOCKED, &ip->i_flags)) return 0; if (sdp->sd_args.ar_quota != GFS2_QUOTA_ON) return 0; for (x = 0; x < ip->i_qadata->qa_qd_num; x++) { qd = ip->i_qadata->qa_qd[x]; if (!(qid_eq(qd->qd_id, make_kqid_uid(uid)) || qid_eq(qd->qd_id, make_kqid_gid(gid)))) continue; warn = (s64)be64_to_cpu(qd->qd_qb.qb_warn); limit = (s64)be64_to_cpu(qd->qd_qb.qb_limit); value = (s64)be64_to_cpu(qd->qd_qb.qb_value); spin_lock(&qd_lock); value += qd->qd_change; spin_unlock(&qd_lock); if (limit > 0 && (limit - value) < ap->allowed) ap->allowed = limit - value; /* If we can't meet the target */ if (limit && limit < (value + (s64)ap->target)) { /* If no min_target specified or we don't meet * min_target, return -EDQUOT */ if (!ap->min_target || ap->min_target > ap->allowed) { if (!test_and_set_bit(QDF_QMSG_QUIET, &qd->qd_flags)) { print_message(qd, "exceeded"); quota_send_warning(qd->qd_id, sdp->sd_vfs->s_dev, QUOTA_NL_BHARDWARN); } error = -EDQUOT; break; } } else if (warn && warn < value && time_after_eq(jiffies, qd->qd_last_warn + gfs2_tune_get(sdp, gt_quota_warn_period) * HZ)) { quota_send_warning(qd->qd_id, sdp->sd_vfs->s_dev, QUOTA_NL_BSOFTWARN); error = print_message(qd, "warning"); qd->qd_last_warn = jiffies; } } return error; } void gfs2_quota_change(struct gfs2_inode *ip, s64 change, kuid_t uid, kgid_t gid) { struct gfs2_quota_data *qd; u32 x; struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode); if (sdp->sd_args.ar_quota != GFS2_QUOTA_ON || gfs2_assert_warn(sdp, change)) return; if (ip->i_diskflags & GFS2_DIF_SYSTEM) return; for (x = 0; x < ip->i_qadata->qa_qd_num; x++) { qd = ip->i_qadata->qa_qd[x]; if (qid_eq(qd->qd_id, make_kqid_uid(uid)) || qid_eq(qd->qd_id, make_kqid_gid(gid))) { do_qc(qd, change); } } } int gfs2_quota_sync(struct super_block *sb, int type) { struct gfs2_sbd *sdp = sb->s_fs_info; struct gfs2_quota_data **qda; unsigned int max_qd = PAGE_SIZE/sizeof(struct gfs2_holder); unsigned int num_qd; unsigned int x; int error = 0; qda = kcalloc(max_qd, sizeof(struct gfs2_quota_data *), GFP_KERNEL); if (!qda) return -ENOMEM; mutex_lock(&sdp->sd_quota_sync_mutex); sdp->sd_quota_sync_gen++; do { num_qd = 0; for (;;) { error = qd_fish(sdp, qda + num_qd); if (error || !qda[num_qd]) break; if (++num_qd == max_qd) break; } if (num_qd) { if (!error) error = do_sync(num_qd, qda); if (!error) for (x = 0; x < num_qd; x++) qda[x]->qd_sync_gen = sdp->sd_quota_sync_gen; for (x = 0; x < num_qd; x++) qd_unlock(qda[x]); } } while (!error && num_qd == max_qd); mutex_unlock(&sdp->sd_quota_sync_mutex); kfree(qda); return error; } int gfs2_quota_refresh(struct gfs2_sbd *sdp, struct kqid qid) { struct gfs2_quota_data *qd; struct gfs2_holder q_gh; int error; error = qd_get(sdp, qid, &qd); if (error) return error; error = do_glock(qd, FORCE, &q_gh); if (!error) gfs2_glock_dq_uninit(&q_gh); qd_put(qd); return error; } int gfs2_quota_init(struct gfs2_sbd *sdp) { struct gfs2_inode *ip = GFS2_I(sdp->sd_qc_inode); u64 size = i_size_read(sdp->sd_qc_inode); unsigned int blocks = size >> sdp->sd_sb.sb_bsize_shift; unsigned int x, slot = 0; unsigned int found = 0; unsigned int hash; unsigned int bm_size; u64 dblock; u32 extlen = 0; int error; if (gfs2_check_internal_file_size(sdp->sd_qc_inode, 1, 64 << 20)) return -EIO; sdp->sd_quota_slots = blocks * sdp->sd_qc_per_block; bm_size = DIV_ROUND_UP(sdp->sd_quota_slots, 8 * sizeof(unsigned long)); bm_size *= sizeof(unsigned long); error = -ENOMEM; sdp->sd_quota_bitmap = kzalloc(bm_size, GFP_NOFS | __GFP_NOWARN); if (sdp->sd_quota_bitmap == NULL) sdp->sd_quota_bitmap = __vmalloc(bm_size, GFP_NOFS | __GFP_ZERO, PAGE_KERNEL); if (!sdp->sd_quota_bitmap) return error; for (x = 0; x < blocks; x++) { struct buffer_head *bh; const struct gfs2_quota_change *qc; unsigned int y; if (!extlen) { int new = 0; error = gfs2_extent_map(&ip->i_inode, x, &new, &dblock, &extlen); if (error) goto fail; } error = -EIO; bh = gfs2_meta_ra(ip->i_gl, dblock, extlen); if (!bh) goto fail; if (gfs2_metatype_check(sdp, bh, GFS2_METATYPE_QC)) { brelse(bh); goto fail; } qc = (const struct gfs2_quota_change *)(bh->b_data + sizeof(struct gfs2_meta_header)); for (y = 0; y < sdp->sd_qc_per_block && slot < sdp->sd_quota_slots; y++, slot++) { struct gfs2_quota_data *qd; s64 qc_change = be64_to_cpu(qc->qc_change); u32 qc_flags = be32_to_cpu(qc->qc_flags); enum quota_type qtype = (qc_flags & GFS2_QCF_USER) ? USRQUOTA : GRPQUOTA; struct kqid qc_id = make_kqid(&init_user_ns, qtype, be32_to_cpu(qc->qc_id)); qc++; if (!qc_change) continue; hash = gfs2_qd_hash(sdp, qc_id); qd = qd_alloc(hash, sdp, qc_id); if (qd == NULL) { brelse(bh); goto fail; } set_bit(QDF_CHANGE, &qd->qd_flags); qd->qd_change = qc_change; qd->qd_slot = slot; qd->qd_slot_count = 1; spin_lock(&qd_lock); BUG_ON(test_and_set_bit(slot, sdp->sd_quota_bitmap)); list_add(&qd->qd_list, &sdp->sd_quota_list); atomic_inc(&sdp->sd_quota_count); spin_unlock(&qd_lock); spin_lock_bucket(hash); hlist_bl_add_head_rcu(&qd->qd_hlist, &qd_hash_table[hash]); spin_unlock_bucket(hash); found++; } brelse(bh); dblock++; extlen--; } if (found) fs_info(sdp, "found %u quota changes\n", found); return 0; fail: gfs2_quota_cleanup(sdp); return error; } void gfs2_quota_cleanup(struct gfs2_sbd *sdp) { struct list_head *head = &sdp->sd_quota_list; struct gfs2_quota_data *qd; spin_lock(&qd_lock); while (!list_empty(head)) { qd = list_entry(head->prev, struct gfs2_quota_data, qd_list); list_del(&qd->qd_list); /* Also remove if this qd exists in the reclaim list */ list_lru_del(&gfs2_qd_lru, &qd->qd_lru); atomic_dec(&sdp->sd_quota_count); spin_unlock(&qd_lock); spin_lock_bucket(qd->qd_hash); hlist_bl_del_rcu(&qd->qd_hlist); spin_unlock_bucket(qd->qd_hash); gfs2_assert_warn(sdp, !qd->qd_change); gfs2_assert_warn(sdp, !qd->qd_slot_count); gfs2_assert_warn(sdp, !qd->qd_bh_count); gfs2_glock_put(qd->qd_gl); call_rcu(&qd->qd_rcu, gfs2_qd_dealloc); spin_lock(&qd_lock); } spin_unlock(&qd_lock); gfs2_assert_warn(sdp, !atomic_read(&sdp->sd_quota_count)); kvfree(sdp->sd_quota_bitmap); sdp->sd_quota_bitmap = NULL; } static void quotad_error(struct gfs2_sbd *sdp, const char *msg, int error) { if (error == 0 || error == -EROFS) return; if (!test_bit(SDF_SHUTDOWN, &sdp->sd_flags)) fs_err(sdp, "gfs2_quotad: %s error %d\n", msg, error); } static void quotad_check_timeo(struct gfs2_sbd *sdp, const char *msg, int (*fxn)(struct super_block *sb, int type), unsigned long t, unsigned long *timeo, unsigned int *new_timeo) { if (t >= *timeo) { int error = fxn(sdp->sd_vfs, 0); quotad_error(sdp, msg, error); *timeo = gfs2_tune_get_i(&sdp->sd_tune, new_timeo) * HZ; } else { *timeo -= t; } } static void quotad_check_trunc_list(struct gfs2_sbd *sdp) { struct gfs2_inode *ip; while(1) { ip = NULL; spin_lock(&sdp->sd_trunc_lock); if (!list_empty(&sdp->sd_trunc_list)) { ip = list_entry(sdp->sd_trunc_list.next, struct gfs2_inode, i_trunc_list); list_del_init(&ip->i_trunc_list); } spin_unlock(&sdp->sd_trunc_lock); if (ip == NULL) return; gfs2_glock_finish_truncate(ip); } } void gfs2_wake_up_statfs(struct gfs2_sbd *sdp) { if (!sdp->sd_statfs_force_sync) { sdp->sd_statfs_force_sync = 1; wake_up(&sdp->sd_quota_wait); } } /** * gfs2_quotad - Write cached quota changes into the quota file * @sdp: Pointer to GFS2 superblock * */ int gfs2_quotad(void *data) { struct gfs2_sbd *sdp = data; struct gfs2_tune *tune = &sdp->sd_tune; unsigned long statfs_timeo = 0; unsigned long quotad_timeo = 0; unsigned long t = 0; DEFINE_WAIT(wait); int empty; while (!kthread_should_stop()) { /* Update the master statfs file */ if (sdp->sd_statfs_force_sync) { int error = gfs2_statfs_sync(sdp->sd_vfs, 0); quotad_error(sdp, "statfs", error); statfs_timeo = gfs2_tune_get(sdp, gt_statfs_quantum) * HZ; } else quotad_check_timeo(sdp, "statfs", gfs2_statfs_sync, t, &statfs_timeo, &tune->gt_statfs_quantum); /* Update quota file */ quotad_check_timeo(sdp, "sync", gfs2_quota_sync, t, &quotad_timeo, &tune->gt_quota_quantum); /* Check for & recover partially truncated inodes */ quotad_check_trunc_list(sdp); try_to_freeze(); t = min(quotad_timeo, statfs_timeo); prepare_to_wait(&sdp->sd_quota_wait, &wait, TASK_INTERRUPTIBLE); spin_lock(&sdp->sd_trunc_lock); empty = list_empty(&sdp->sd_trunc_list); spin_unlock(&sdp->sd_trunc_lock); if (empty && !sdp->sd_statfs_force_sync) t -= schedule_timeout(t); else t = 0; finish_wait(&sdp->sd_quota_wait, &wait); } return 0; } static int gfs2_quota_get_state(struct super_block *sb, struct qc_state *state) { struct gfs2_sbd *sdp = sb->s_fs_info; memset(state, 0, sizeof(*state)); switch (sdp->sd_args.ar_quota) { case GFS2_QUOTA_ON: state->s_state[USRQUOTA].flags |= QCI_LIMITS_ENFORCED; state->s_state[GRPQUOTA].flags |= QCI_LIMITS_ENFORCED; /*FALLTHRU*/ case GFS2_QUOTA_ACCOUNT: state->s_state[USRQUOTA].flags |= QCI_ACCT_ENABLED | QCI_SYSFILE; state->s_state[GRPQUOTA].flags |= QCI_ACCT_ENABLED | QCI_SYSFILE; break; case GFS2_QUOTA_OFF: break; } if (sdp->sd_quota_inode) { state->s_state[USRQUOTA].ino = GFS2_I(sdp->sd_quota_inode)->i_no_addr; state->s_state[USRQUOTA].blocks = sdp->sd_quota_inode->i_blocks; } state->s_state[USRQUOTA].nextents = 1; /* unsupported */ state->s_state[GRPQUOTA] = state->s_state[USRQUOTA]; state->s_incoredqs = list_lru_count(&gfs2_qd_lru); return 0; } static int gfs2_get_dqblk(struct super_block *sb, struct kqid qid, struct qc_dqblk *fdq) { struct gfs2_sbd *sdp = sb->s_fs_info; struct gfs2_quota_lvb *qlvb; struct gfs2_quota_data *qd; struct gfs2_holder q_gh; int error; memset(fdq, 0, sizeof(*fdq)); if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF) return -ESRCH; /* Crazy XFS error code */ if ((qid.type != USRQUOTA) && (qid.type != GRPQUOTA)) return -EINVAL; error = qd_get(sdp, qid, &qd); if (error) return error; error = do_glock(qd, FORCE, &q_gh); if (error) goto out; qlvb = (struct gfs2_quota_lvb *)qd->qd_gl->gl_lksb.sb_lvbptr; fdq->d_spc_hardlimit = be64_to_cpu(qlvb->qb_limit) << sdp->sd_sb.sb_bsize_shift; fdq->d_spc_softlimit = be64_to_cpu(qlvb->qb_warn) << sdp->sd_sb.sb_bsize_shift; fdq->d_space = be64_to_cpu(qlvb->qb_value) << sdp->sd_sb.sb_bsize_shift; gfs2_glock_dq_uninit(&q_gh); out: qd_put(qd); return error; } /* GFS2 only supports a subset of the XFS fields */ #define GFS2_FIELDMASK (QC_SPC_SOFT|QC_SPC_HARD|QC_SPACE) static int gfs2_set_dqblk(struct super_block *sb, struct kqid qid, struct qc_dqblk *fdq) { struct gfs2_sbd *sdp = sb->s_fs_info; struct gfs2_inode *ip = GFS2_I(sdp->sd_quota_inode); struct gfs2_quota_data *qd; struct gfs2_holder q_gh, i_gh; unsigned int data_blocks, ind_blocks; unsigned int blocks = 0; int alloc_required; loff_t offset; int error; if (sdp->sd_args.ar_quota == GFS2_QUOTA_OFF) return -ESRCH; /* Crazy XFS error code */ if ((qid.type != USRQUOTA) && (qid.type != GRPQUOTA)) return -EINVAL; if (fdq->d_fieldmask & ~GFS2_FIELDMASK) return -EINVAL; error = qd_get(sdp, qid, &qd); if (error) return error; error = gfs2_rsqa_alloc(ip); if (error) goto out_put; inode_lock(&ip->i_inode); error = gfs2_glock_nq_init(qd->qd_gl, LM_ST_EXCLUSIVE, 0, &q_gh); if (error) goto out_unlockput; error = gfs2_glock_nq_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &i_gh); if (error) goto out_q; /* Check for existing entry, if none then alloc new blocks */ error = update_qd(sdp, qd); if (error) goto out_i; /* If nothing has changed, this is a no-op */ if ((fdq->d_fieldmask & QC_SPC_SOFT) && ((fdq->d_spc_softlimit >> sdp->sd_sb.sb_bsize_shift) == be64_to_cpu(qd->qd_qb.qb_warn))) fdq->d_fieldmask ^= QC_SPC_SOFT; if ((fdq->d_fieldmask & QC_SPC_HARD) && ((fdq->d_spc_hardlimit >> sdp->sd_sb.sb_bsize_shift) == be64_to_cpu(qd->qd_qb.qb_limit))) fdq->d_fieldmask ^= QC_SPC_HARD; if ((fdq->d_fieldmask & QC_SPACE) && ((fdq->d_space >> sdp->sd_sb.sb_bsize_shift) == be64_to_cpu(qd->qd_qb.qb_value))) fdq->d_fieldmask ^= QC_SPACE; if (fdq->d_fieldmask == 0) goto out_i; offset = qd2offset(qd); alloc_required = gfs2_write_alloc_required(ip, offset, sizeof(struct gfs2_quota)); if (gfs2_is_stuffed(ip)) alloc_required = 1; if (alloc_required) { struct gfs2_alloc_parms ap = { .aflags = 0, }; gfs2_write_calc_reserv(ip, sizeof(struct gfs2_quota), &data_blocks, &ind_blocks); blocks = 1 + data_blocks + ind_blocks; ap.target = blocks; error = gfs2_inplace_reserve(ip, &ap); if (error) goto out_i; blocks += gfs2_rg_blocks(ip, blocks); } /* Some quotas span block boundaries and can update two blocks, adding an extra block to the transaction to handle such quotas */ error = gfs2_trans_begin(sdp, blocks + RES_DINODE + 2, 0); if (error) goto out_release; /* Apply changes */ error = gfs2_adjust_quota(ip, offset, 0, qd, fdq); if (!error) clear_bit(QDF_QMSG_QUIET, &qd->qd_flags); gfs2_trans_end(sdp); out_release: if (alloc_required) gfs2_inplace_release(ip); out_i: gfs2_glock_dq_uninit(&i_gh); out_q: gfs2_glock_dq_uninit(&q_gh); out_unlockput: inode_unlock(&ip->i_inode); out_put: qd_put(qd); return error; } const struct quotactl_ops gfs2_quotactl_ops = { .quota_sync = gfs2_quota_sync, .get_state = gfs2_quota_get_state, .get_dqblk = gfs2_get_dqblk, .set_dqblk = gfs2_set_dqblk, }; void __init gfs2_quota_hash_init(void) { unsigned i; for(i = 0; i < GFS2_QD_HASH_SIZE; i++) INIT_HLIST_BL_HEAD(&qd_hash_table[i]); }
dperezde/little-penguin
linux/fs/gfs2/quota.c
C
gpl-2.0
43,345
/* * linux/drivers/video/fbcon.c -- Low level frame buffer based console driver * * Copyright (C) 1995 Geert Uytterhoeven * * * This file is based on the original Amiga console driver (amicon.c): * * Copyright (C) 1993 Hamish Macdonald * Greg Harp * Copyright (C) 1994 David Carter [[email protected]] * * with work by William Rucklidge ([email protected]) * Geert Uytterhoeven * Jes Sorensen ([email protected]) * Martin Apel * * and on the original Atari console driver (atacon.c): * * Copyright (C) 1993 Bjoern Brauel * Roman Hodek * * with work by Guenther Kelleter * Martin Schaller * Andreas Schwab * * Hardware cursor support added by Emmanuel Marty ([email protected]) * Smart redraw scrolling, arbitrary font width support, 512char font support * and software scrollback added by * Jakub Jelinek ([email protected]) * * Random hacking by Martin Mares <[email protected]> * * 2001 - Documented with DocBook * - Brad Douglas <[email protected]> * * The low level operations for the various display memory organizations are * now in separate source files. * * Currently the following organizations are supported: * * o afb Amiga bitplanes * o cfb{2,4,8,16,24,32} Packed pixels * o ilbm Amiga interleaved bitplanes * o iplan2p[248] Atari interleaved bitplanes * o mfb Monochrome * o vga VGA characters/attributes * * To do: * * - Implement 16 plane mode (iplan2p16) * * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of this archive for * more details. */ #undef FBCONDEBUG #include <linux/module.h> #include <linux/types.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/delay.h> /* MSch: for IRQ probe */ #include <linux/console.h> #include <linux/string.h> #include <linux/kd.h> #include <linux/slab.h> #include <linux/fb.h> #include <linux/vt_kern.h> #include <linux/selection.h> #include <linux/font.h> #include <linux/smp.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/crc32.h> /* For counting font checksums */ #include <asm/fb.h> #include <asm/irq.h> #include <asm/system.h> #ifdef CONFIG_ATARI #include <asm/atariints.h> #endif #ifdef CONFIG_MAC #include <asm/macints.h> #endif #if defined(__mc68000__) #include <asm/machdep.h> #include <asm/setup.h> #endif #include "fbcon.h" #ifdef FBCONDEBUG # define DPRINTK(fmt, args...) printk(KERN_DEBUG "%s: " fmt, __func__ , ## args) #else # define DPRINTK(fmt, args...) #endif enum { FBCON_LOGO_CANSHOW = -1, /* the logo can be shown */ FBCON_LOGO_DRAW = -2, /* draw the logo to a console */ FBCON_LOGO_DONTSHOW = -3 /* do not show the logo */ }; static struct display fb_display[MAX_NR_CONSOLES]; static signed char con2fb_map[MAX_NR_CONSOLES]; static signed char con2fb_map_boot[MAX_NR_CONSOLES]; #ifndef MODULE static int logo_height; #endif static int logo_lines; /* logo_shown is an index to vc_cons when >= 0; otherwise follows FBCON_LOGO enums. */ static int logo_shown = FBCON_LOGO_CANSHOW; /* Software scrollback */ static int fbcon_softback_size = 32768; static unsigned long softback_buf, softback_curr; static unsigned long softback_in; static unsigned long softback_top, softback_end; static int softback_lines; /* console mappings */ static int first_fb_vc; static int last_fb_vc = MAX_NR_CONSOLES - 1; static int fbcon_is_default = 1; static int fbcon_has_exited; static int primary_device = -1; #ifdef CONFIG_FRAMEBUFFER_CONSOLE_DETECT_PRIMARY static int map_override; static inline void fbcon_map_override(void) { map_override = 1; } #else static inline void fbcon_map_override(void) { } #endif /* CONFIG_FRAMEBUFFER_CONSOLE_DETECT_PRIMARY */ /* font data */ static char fontname[40]; /* current fb_info */ static int info_idx = -1; /* console rotation */ static int initial_rotation; static int fbcon_has_sysfs; static const struct consw fb_con; #define CM_SOFTBACK (8) #define advance_row(p, delta) (unsigned short *)((unsigned long)(p) + (delta) * vc->vc_size_row) static int fbcon_set_origin(struct vc_data *); #define CURSOR_DRAW_DELAY (1) /* # VBL ints between cursor state changes */ #define ATARI_CURSOR_BLINK_RATE (42) #define MAC_CURSOR_BLINK_RATE (32) #define DEFAULT_CURSOR_BLINK_RATE (20) static int vbl_cursor_cnt; static int fbcon_cursor_noblink; #define divides(a, b) ((!(a) || (b)%(a)) ? 0 : 1) /* * Interface used by the world */ static const char *fbcon_startup(void); static void fbcon_init(struct vc_data *vc, int init); static void fbcon_deinit(struct vc_data *vc); static void fbcon_clear(struct vc_data *vc, int sy, int sx, int height, int width); static void fbcon_putc(struct vc_data *vc, int c, int ypos, int xpos); static void fbcon_putcs(struct vc_data *vc, const unsigned short *s, int count, int ypos, int xpos); static void fbcon_clear_margins(struct vc_data *vc, int bottom_only); static void fbcon_cursor(struct vc_data *vc, int mode); static int fbcon_scroll(struct vc_data *vc, int t, int b, int dir, int count); static void fbcon_bmove(struct vc_data *vc, int sy, int sx, int dy, int dx, int height, int width); static int fbcon_switch(struct vc_data *vc); static int fbcon_blank(struct vc_data *vc, int blank, int mode_switch); static int fbcon_set_palette(struct vc_data *vc, unsigned char *table); static int fbcon_scrolldelta(struct vc_data *vc, int lines); /* * Internal routines */ static __inline__ void ywrap_up(struct vc_data *vc, int count); static __inline__ void ywrap_down(struct vc_data *vc, int count); static __inline__ void ypan_up(struct vc_data *vc, int count); static __inline__ void ypan_down(struct vc_data *vc, int count); static void fbcon_bmove_rec(struct vc_data *vc, struct display *p, int sy, int sx, int dy, int dx, int height, int width, u_int y_break); static void fbcon_set_disp(struct fb_info *info, struct fb_var_screeninfo *var, int unit); static void fbcon_redraw_move(struct vc_data *vc, struct display *p, int line, int count, int dy); static void fbcon_modechanged(struct fb_info *info); static void fbcon_set_all_vcs(struct fb_info *info); static void fbcon_start(void); static void fbcon_exit(void); static struct device *fbcon_device; #ifdef CONFIG_MAC /* * On the Macintoy, there may or may not be a working VBL int. We need to probe */ static int vbl_detected; static irqreturn_t fb_vbl_detect(int irq, void *dummy) { vbl_detected++; return IRQ_HANDLED; } #endif #ifdef CONFIG_FRAMEBUFFER_CONSOLE_ROTATION static inline void fbcon_set_rotation(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; if (!(info->flags & FBINFO_MISC_TILEBLITTING) && ops->p->con_rotate < 4) ops->rotate = ops->p->con_rotate; else ops->rotate = 0; } static void fbcon_rotate(struct fb_info *info, u32 rotate) { struct fbcon_ops *ops= info->fbcon_par; struct fb_info *fb_info; if (!ops || ops->currcon == -1) return; fb_info = registered_fb[con2fb_map[ops->currcon]]; if (info == fb_info) { struct display *p = &fb_display[ops->currcon]; if (rotate < 4) p->con_rotate = rotate; else p->con_rotate = 0; fbcon_modechanged(info); } } static void fbcon_rotate_all(struct fb_info *info, u32 rotate) { struct fbcon_ops *ops = info->fbcon_par; struct vc_data *vc; struct display *p; int i; if (!ops || ops->currcon < 0 || rotate > 3) return; for (i = first_fb_vc; i <= last_fb_vc; i++) { vc = vc_cons[i].d; if (!vc || vc->vc_mode != KD_TEXT || registered_fb[con2fb_map[i]] != info) continue; p = &fb_display[vc->vc_num]; p->con_rotate = rotate; } fbcon_set_all_vcs(info); } #else static inline void fbcon_set_rotation(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; ops->rotate = FB_ROTATE_UR; } static void fbcon_rotate(struct fb_info *info, u32 rotate) { return; } static void fbcon_rotate_all(struct fb_info *info, u32 rotate) { return; } #endif /* CONFIG_FRAMEBUFFER_CONSOLE_ROTATION */ static int fbcon_get_rotate(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; return (ops) ? ops->rotate : 0; } static inline int fbcon_is_inactive(struct vc_data *vc, struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; return (info->state != FBINFO_STATE_RUNNING || vc->vc_mode != KD_TEXT || ops->graphics); } static inline int get_color(struct vc_data *vc, struct fb_info *info, u16 c, int is_fg) { int depth = fb_get_color_depth(&info->var, &info->fix); int color = 0; if (console_blanked) { unsigned short charmask = vc->vc_hi_font_mask ? 0x1ff : 0xff; c = vc->vc_video_erase_char & charmask; } if (depth != 1) color = (is_fg) ? attr_fgcol((vc->vc_hi_font_mask) ? 9 : 8, c) : attr_bgcol((vc->vc_hi_font_mask) ? 13 : 12, c); switch (depth) { case 1: { int col = mono_col(info); /* 0 or 1 */ int fg = (info->fix.visual != FB_VISUAL_MONO01) ? col : 0; int bg = (info->fix.visual != FB_VISUAL_MONO01) ? 0 : col; if (console_blanked) fg = bg; color = (is_fg) ? fg : bg; break; } case 2: /* * Scale down 16-colors to 4 colors. Default 4-color palette * is grayscale. However, simply dividing the values by 4 * will not work, as colors 1, 2 and 3 will be scaled-down * to zero rendering them invisible. So empirically convert * colors to a sane 4-level grayscale. */ switch (color) { case 0: color = 0; /* black */ break; case 1 ... 6: color = 2; /* white */ break; case 7 ... 8: color = 1; /* gray */ break; default: color = 3; /* intense white */ break; } break; case 3: /* * Last 8 entries of default 16-color palette is a more intense * version of the first 8 (i.e., same chrominance, different * luminance). */ color &= 7; break; } return color; } static void fbcon_update_softback(struct vc_data *vc) { int l = fbcon_softback_size / vc->vc_size_row; if (l > 5) softback_end = softback_buf + l * vc->vc_size_row; else /* Smaller scrollback makes no sense, and 0 would screw the operation totally */ softback_top = 0; } static void fb_flashcursor(struct work_struct *work) { struct fb_info *info = container_of(work, struct fb_info, queue); struct fbcon_ops *ops = info->fbcon_par; struct display *p; struct vc_data *vc = NULL; int c; int mode; acquire_console_sem(); if (ops && ops->currcon != -1) vc = vc_cons[ops->currcon].d; if (!vc || !CON_IS_VISIBLE(vc) || registered_fb[con2fb_map[vc->vc_num]] != info || vc->vc_deccm != 1) { release_console_sem(); return; } p = &fb_display[vc->vc_num]; c = scr_readw((u16 *) vc->vc_pos); mode = (!ops->cursor_flash || ops->cursor_state.enable) ? CM_ERASE : CM_DRAW; ops->cursor(vc, info, mode, softback_lines, get_color(vc, info, c, 1), get_color(vc, info, c, 0)); release_console_sem(); } #if defined(CONFIG_ATARI) || defined(CONFIG_MAC) static int cursor_blink_rate; static irqreturn_t fb_vbl_handler(int irq, void *dev_id) { struct fb_info *info = dev_id; if (vbl_cursor_cnt && --vbl_cursor_cnt == 0) { schedule_work(&info->queue); vbl_cursor_cnt = cursor_blink_rate; } return IRQ_HANDLED; } #endif static void cursor_timer_handler(unsigned long dev_addr) { struct fb_info *info = (struct fb_info *) dev_addr; struct fbcon_ops *ops = info->fbcon_par; schedule_work(&info->queue); mod_timer(&ops->cursor_timer, jiffies + HZ/5); } static void fbcon_add_cursor_timer(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; if ((!info->queue.func || info->queue.func == fb_flashcursor) && !(ops->flags & FBCON_FLAGS_CURSOR_TIMER) && !fbcon_cursor_noblink) { if (!info->queue.func) INIT_WORK(&info->queue, fb_flashcursor); init_timer(&ops->cursor_timer); ops->cursor_timer.function = cursor_timer_handler; ops->cursor_timer.expires = jiffies + HZ / 5; ops->cursor_timer.data = (unsigned long ) info; add_timer(&ops->cursor_timer); ops->flags |= FBCON_FLAGS_CURSOR_TIMER; } } static void fbcon_del_cursor_timer(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; if (info->queue.func == fb_flashcursor && ops->flags & FBCON_FLAGS_CURSOR_TIMER) { del_timer_sync(&ops->cursor_timer); ops->flags &= ~FBCON_FLAGS_CURSOR_TIMER; } } #ifndef MODULE static int __init fb_console_setup(char *this_opt) { char *options; int i, j; if (!this_opt || !*this_opt) return 1; while ((options = strsep(&this_opt, ",")) != NULL) { if (!strncmp(options, "font:", 5)) strcpy(fontname, options + 5); if (!strncmp(options, "scrollback:", 11)) { options += 11; if (*options) { fbcon_softback_size = simple_strtoul(options, &options, 0); if (*options == 'k' || *options == 'K') { fbcon_softback_size *= 1024; options++; } if (*options != ',') return 1; options++; } else return 1; } if (!strncmp(options, "map:", 4)) { options += 4; if (*options) { for (i = 0, j = 0; i < MAX_NR_CONSOLES; i++) { if (!options[j]) j = 0; con2fb_map_boot[i] = (options[j++]-'0') % FB_MAX; } fbcon_map_override(); } return 1; } if (!strncmp(options, "vc:", 3)) { options += 3; if (*options) first_fb_vc = simple_strtoul(options, &options, 10) - 1; if (first_fb_vc < 0) first_fb_vc = 0; if (*options++ == '-') last_fb_vc = simple_strtoul(options, &options, 10) - 1; fbcon_is_default = 0; } if (!strncmp(options, "rotate:", 7)) { options += 7; if (*options) initial_rotation = simple_strtoul(options, &options, 0); if (initial_rotation > 3) initial_rotation = 0; } } return 1; } __setup("fbcon=", fb_console_setup); #endif static int search_fb_in_map(int idx) { int i, retval = 0; for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map[i] == idx) retval = 1; } return retval; } static int search_for_mapped_con(void) { int i, retval = 0; for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map[i] != -1) retval = 1; } return retval; } static int fbcon_takeover(int show_logo) { int err, i; if (!num_registered_fb) return -ENODEV; if (!show_logo) logo_shown = FBCON_LOGO_DONTSHOW; for (i = first_fb_vc; i <= last_fb_vc; i++) con2fb_map[i] = info_idx; err = take_over_console(&fb_con, first_fb_vc, last_fb_vc, fbcon_is_default); if (err) { for (i = first_fb_vc; i <= last_fb_vc; i++) { con2fb_map[i] = -1; } info_idx = -1; } return err; } #ifdef MODULE static void fbcon_prepare_logo(struct vc_data *vc, struct fb_info *info, int cols, int rows, int new_cols, int new_rows) { logo_shown = FBCON_LOGO_DONTSHOW; } #else static void fbcon_prepare_logo(struct vc_data *vc, struct fb_info *info, int cols, int rows, int new_cols, int new_rows) { /* Need to make room for the logo */ struct fbcon_ops *ops = info->fbcon_par; int cnt, erase = vc->vc_video_erase_char, step; unsigned short *save = NULL, *r, *q; if (info->flags & FBINFO_MODULE) { logo_shown = FBCON_LOGO_DONTSHOW; return; } /* * remove underline attribute from erase character * if black and white framebuffer. */ if (fb_get_color_depth(&info->var, &info->fix) == 1) erase &= ~0x400; logo_height = fb_prepare_logo(info, ops->rotate); logo_lines = DIV_ROUND_UP(logo_height, vc->vc_font.height); q = (unsigned short *) (vc->vc_origin + vc->vc_size_row * rows); step = logo_lines * cols; for (r = q - logo_lines * cols; r < q; r++) if (scr_readw(r) != vc->vc_video_erase_char) break; if (r != q && new_rows >= rows + logo_lines) { save = kmalloc(logo_lines * new_cols * 2, GFP_KERNEL); if (save) { int i = cols < new_cols ? cols : new_cols; scr_memsetw(save, erase, logo_lines * new_cols * 2); r = q - step; for (cnt = 0; cnt < logo_lines; cnt++, r += i) scr_memcpyw(save + cnt * new_cols, r, 2 * i); r = q; } } if (r == q) { /* We can scroll screen down */ r = q - step - cols; for (cnt = rows - logo_lines; cnt > 0; cnt--) { scr_memcpyw(r + step, r, vc->vc_size_row); r -= cols; } if (!save) { int lines; if (vc->vc_y + logo_lines >= rows) lines = rows - vc->vc_y - 1; else lines = logo_lines; vc->vc_y += lines; vc->vc_pos += lines * vc->vc_size_row; } } scr_memsetw((unsigned short *) vc->vc_origin, erase, vc->vc_size_row * logo_lines); if (CON_IS_VISIBLE(vc) && vc->vc_mode == KD_TEXT) { fbcon_clear_margins(vc, 0); update_screen(vc); } if (save) { q = (unsigned short *) (vc->vc_origin + vc->vc_size_row * rows); scr_memcpyw(q, save, logo_lines * new_cols * 2); vc->vc_y += logo_lines; vc->vc_pos += logo_lines * vc->vc_size_row; kfree(save); } if (logo_lines > vc->vc_bottom) { logo_shown = FBCON_LOGO_CANSHOW; printk(KERN_INFO "fbcon_init: disable boot-logo (boot-logo bigger than screen).\n"); } else if (logo_shown != FBCON_LOGO_DONTSHOW) { logo_shown = FBCON_LOGO_DRAW; vc->vc_top = logo_lines; } } #endif /* MODULE */ #ifdef CONFIG_FB_TILEBLITTING static void set_blitting_type(struct vc_data *vc, struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; ops->p = &fb_display[vc->vc_num]; if ((info->flags & FBINFO_MISC_TILEBLITTING)) fbcon_set_tileops(vc, info); else { fbcon_set_rotation(info); fbcon_set_bitops(ops); } } static int fbcon_invalid_charcount(struct fb_info *info, unsigned charcount) { int err = 0; if (info->flags & FBINFO_MISC_TILEBLITTING && info->tileops->fb_get_tilemax(info) < charcount) err = 1; return err; } #else static void set_blitting_type(struct vc_data *vc, struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; info->flags &= ~FBINFO_MISC_TILEBLITTING; ops->p = &fb_display[vc->vc_num]; fbcon_set_rotation(info); fbcon_set_bitops(ops); } static int fbcon_invalid_charcount(struct fb_info *info, unsigned charcount) { return 0; } #endif /* CONFIG_MISC_TILEBLITTING */ static int con2fb_acquire_newinfo(struct vc_data *vc, struct fb_info *info, int unit, int oldidx) { struct fbcon_ops *ops = NULL; int err = 0; if (!try_module_get(info->fbops->owner)) err = -ENODEV; if (!err && info->fbops->fb_open && info->fbops->fb_open(info, 0)) err = -ENODEV; if (!err) { ops = kzalloc(sizeof(struct fbcon_ops), GFP_KERNEL); if (!ops) err = -ENOMEM; } if (!err) { info->fbcon_par = ops; if (vc) set_blitting_type(vc, info); } if (err) { con2fb_map[unit] = oldidx; module_put(info->fbops->owner); } return err; } static int con2fb_release_oldinfo(struct vc_data *vc, struct fb_info *oldinfo, struct fb_info *newinfo, int unit, int oldidx, int found) { struct fbcon_ops *ops = oldinfo->fbcon_par; int err = 0; if (oldinfo->fbops->fb_release && oldinfo->fbops->fb_release(oldinfo, 0)) { con2fb_map[unit] = oldidx; if (!found && newinfo->fbops->fb_release) newinfo->fbops->fb_release(newinfo, 0); if (!found) module_put(newinfo->fbops->owner); err = -ENODEV; } if (!err) { fbcon_del_cursor_timer(oldinfo); kfree(ops->cursor_state.mask); kfree(ops->cursor_data); kfree(ops->fontbuffer); kfree(oldinfo->fbcon_par); oldinfo->fbcon_par = NULL; module_put(oldinfo->fbops->owner); /* If oldinfo and newinfo are driving the same hardware, the fb_release() method of oldinfo may attempt to restore the hardware state. This will leave the newinfo in an undefined state. Thus, a call to fb_set_par() may be needed for the newinfo. */ if (newinfo->fbops->fb_set_par) newinfo->fbops->fb_set_par(newinfo); } return err; } static void con2fb_init_display(struct vc_data *vc, struct fb_info *info, int unit, int show_logo) { struct fbcon_ops *ops = info->fbcon_par; ops->currcon = fg_console; if (info->fbops->fb_set_par && !(ops->flags & FBCON_FLAGS_INIT)) info->fbops->fb_set_par(info); ops->flags |= FBCON_FLAGS_INIT; ops->graphics = 0; fbcon_set_disp(info, &info->var, unit); if (show_logo) { struct vc_data *fg_vc = vc_cons[fg_console].d; struct fb_info *fg_info = registered_fb[con2fb_map[fg_console]]; fbcon_prepare_logo(fg_vc, fg_info, fg_vc->vc_cols, fg_vc->vc_rows, fg_vc->vc_cols, fg_vc->vc_rows); } update_screen(vc_cons[fg_console].d); } /** * set_con2fb_map - map console to frame buffer device * @unit: virtual console number to map * @newidx: frame buffer index to map virtual console to * @user: user request * * Maps a virtual console @unit to a frame buffer device * @newidx. */ static int set_con2fb_map(int unit, int newidx, int user) { struct vc_data *vc = vc_cons[unit].d; int oldidx = con2fb_map[unit]; struct fb_info *info = registered_fb[newidx]; struct fb_info *oldinfo = NULL; int found, err = 0; if (oldidx == newidx) return 0; if (!info || fbcon_has_exited) return -EINVAL; if (!err && !search_for_mapped_con()) { info_idx = newidx; return fbcon_takeover(0); } if (oldidx != -1) oldinfo = registered_fb[oldidx]; found = search_fb_in_map(newidx); acquire_console_sem(); con2fb_map[unit] = newidx; if (!err && !found) err = con2fb_acquire_newinfo(vc, info, unit, oldidx); /* * If old fb is not mapped to any of the consoles, * fbcon should release it. */ if (!err && oldinfo && !search_fb_in_map(oldidx)) err = con2fb_release_oldinfo(vc, oldinfo, info, unit, oldidx, found); if (!err) { int show_logo = (fg_console == 0 && !user && logo_shown != FBCON_LOGO_DONTSHOW); if (!found) fbcon_add_cursor_timer(info); con2fb_map_boot[unit] = newidx; con2fb_init_display(vc, info, unit, show_logo); } if (!search_fb_in_map(info_idx)) info_idx = newidx; release_console_sem(); return err; } /* * Low Level Operations */ /* NOTE: fbcon cannot be __init: it may be called from take_over_console later */ static int var_to_display(struct display *disp, struct fb_var_screeninfo *var, struct fb_info *info) { disp->xres_virtual = var->xres_virtual; disp->yres_virtual = var->yres_virtual; disp->bits_per_pixel = var->bits_per_pixel; disp->grayscale = var->grayscale; disp->nonstd = var->nonstd; disp->accel_flags = var->accel_flags; disp->height = var->height; disp->width = var->width; disp->red = var->red; disp->green = var->green; disp->blue = var->blue; disp->transp = var->transp; disp->rotate = var->rotate; disp->mode = fb_match_mode(var, &info->modelist); if (disp->mode == NULL) /* This should not happen */ return -EINVAL; return 0; } static void display_to_var(struct fb_var_screeninfo *var, struct display *disp) { fb_videomode_to_var(var, disp->mode); var->xres_virtual = disp->xres_virtual; var->yres_virtual = disp->yres_virtual; var->bits_per_pixel = disp->bits_per_pixel; var->grayscale = disp->grayscale; var->nonstd = disp->nonstd; var->accel_flags = disp->accel_flags; var->height = disp->height; var->width = disp->width; var->red = disp->red; var->green = disp->green; var->blue = disp->blue; var->transp = disp->transp; var->rotate = disp->rotate; } static const char *fbcon_startup(void) { const char *display_desc = "frame buffer device"; struct display *p = &fb_display[fg_console]; struct vc_data *vc = vc_cons[fg_console].d; const struct font_desc *font = NULL; struct module *owner; struct fb_info *info = NULL; struct fbcon_ops *ops; int rows, cols; int irqres; irqres = 1; /* * If num_registered_fb is zero, this is a call for the dummy part. * The frame buffer devices weren't initialized yet. */ if (!num_registered_fb || info_idx == -1) return display_desc; /* * Instead of blindly using registered_fb[0], we use info_idx, set by * fb_console_init(); */ info = registered_fb[info_idx]; if (!info) return NULL; owner = info->fbops->owner; if (!try_module_get(owner)) return NULL; if (info->fbops->fb_open && info->fbops->fb_open(info, 0)) { module_put(owner); return NULL; } ops = kzalloc(sizeof(struct fbcon_ops), GFP_KERNEL); if (!ops) { module_put(owner); return NULL; } ops->currcon = -1; ops->graphics = 1; ops->cur_rotate = -1; info->fbcon_par = ops; p->con_rotate = initial_rotation; set_blitting_type(vc, info); if (info->fix.type != FB_TYPE_TEXT) { if (fbcon_softback_size) { if (!softback_buf) { softback_buf = (unsigned long) kmalloc(fbcon_softback_size, GFP_KERNEL); if (!softback_buf) { fbcon_softback_size = 0; softback_top = 0; } } } else { if (softback_buf) { kfree((void *) softback_buf); softback_buf = 0; softback_top = 0; } } if (softback_buf) softback_in = softback_top = softback_curr = softback_buf; softback_lines = 0; } /* Setup default font */ if (!p->fontdata) { if (!fontname[0] || !(font = find_font(fontname))) font = get_default_font(info->var.xres, info->var.yres, info->pixmap.blit_x, info->pixmap.blit_y); vc->vc_font.width = font->width; vc->vc_font.height = font->height; vc->vc_font.data = (void *)(p->fontdata = font->data); vc->vc_font.charcount = 256; /* FIXME Need to support more fonts */ } cols = FBCON_SWAP(ops->rotate, info->var.xres, info->var.yres); rows = FBCON_SWAP(ops->rotate, info->var.yres, info->var.xres); cols /= vc->vc_font.width; rows /= vc->vc_font.height; vc_resize(vc, cols, rows); DPRINTK("mode: %s\n", info->fix.id); DPRINTK("visual: %d\n", info->fix.visual); DPRINTK("res: %dx%d-%d\n", info->var.xres, info->var.yres, info->var.bits_per_pixel); #ifdef CONFIG_ATARI if (MACH_IS_ATARI) { cursor_blink_rate = ATARI_CURSOR_BLINK_RATE; irqres = request_irq(IRQ_AUTO_4, fb_vbl_handler, IRQ_TYPE_PRIO, "framebuffer vbl", info); } #endif /* CONFIG_ATARI */ #ifdef CONFIG_MAC /* * On a Macintoy, the VBL interrupt may or may not be active. * As interrupt based cursor is more reliable and race free, we * probe for VBL interrupts. */ if (MACH_IS_MAC) { int ct = 0; /* * Probe for VBL: set temp. handler ... */ irqres = request_irq(IRQ_MAC_VBL, fb_vbl_detect, 0, "framebuffer vbl", info); vbl_detected = 0; /* * ... and spin for 20 ms ... */ while (!vbl_detected && ++ct < 1000) udelay(20); if (ct == 1000) printk ("fbcon_startup: No VBL detected, using timer based cursor.\n"); free_irq(IRQ_MAC_VBL, fb_vbl_detect); if (vbl_detected) { /* * interrupt based cursor ok */ cursor_blink_rate = MAC_CURSOR_BLINK_RATE; irqres = request_irq(IRQ_MAC_VBL, fb_vbl_handler, 0, "framebuffer vbl", info); } else { /* * VBL not detected: fall through, use timer based cursor */ irqres = 1; } } #endif /* CONFIG_MAC */ fbcon_add_cursor_timer(info); fbcon_has_exited = 0; return display_desc; } static void fbcon_init(struct vc_data *vc, int init) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops; struct vc_data **default_mode = vc->vc_display_fg; struct vc_data *svc = *default_mode; struct display *t, *p = &fb_display[vc->vc_num]; int logo = 1, new_rows, new_cols, rows, cols, charcnt = 256; int cap; if (info_idx == -1 || info == NULL) return; cap = info->flags; if (vc != svc || logo_shown == FBCON_LOGO_DONTSHOW || (info->fix.type == FB_TYPE_TEXT)) logo = 0; if (var_to_display(p, &info->var, info)) return; if (!info->fbcon_par) con2fb_acquire_newinfo(vc, info, vc->vc_num, -1); /* If we are not the first console on this fb, copy the font from that console */ t = &fb_display[fg_console]; if (!p->fontdata) { if (t->fontdata) { struct vc_data *fvc = vc_cons[fg_console].d; vc->vc_font.data = (void *)(p->fontdata = fvc->vc_font.data); vc->vc_font.width = fvc->vc_font.width; vc->vc_font.height = fvc->vc_font.height; p->userfont = t->userfont; if (p->userfont) REFCOUNT(p->fontdata)++; } else { const struct font_desc *font = NULL; if (!fontname[0] || !(font = find_font(fontname))) font = get_default_font(info->var.xres, info->var.yres, info->pixmap.blit_x, info->pixmap.blit_y); vc->vc_font.width = font->width; vc->vc_font.height = font->height; vc->vc_font.data = (void *)(p->fontdata = font->data); vc->vc_font.charcount = 256; /* FIXME Need to support more fonts */ } } if (p->userfont) charcnt = FNTCHARCNT(p->fontdata); vc->vc_can_do_color = (fb_get_color_depth(&info->var, &info->fix)!=1); vc->vc_complement_mask = vc->vc_can_do_color ? 0x7700 : 0x0800; if (charcnt == 256) { vc->vc_hi_font_mask = 0; } else { vc->vc_hi_font_mask = 0x100; if (vc->vc_can_do_color) vc->vc_complement_mask <<= 1; } if (!*svc->vc_uni_pagedir_loc) con_set_default_unimap(svc); if (!*vc->vc_uni_pagedir_loc) con_copy_unimap(vc, svc); ops = info->fbcon_par; p->con_rotate = initial_rotation; set_blitting_type(vc, info); cols = vc->vc_cols; rows = vc->vc_rows; new_cols = FBCON_SWAP(ops->rotate, info->var.xres, info->var.yres); new_rows = FBCON_SWAP(ops->rotate, info->var.yres, info->var.xres); new_cols /= vc->vc_font.width; new_rows /= vc->vc_font.height; vc_resize(vc, new_cols, new_rows); /* * We must always set the mode. The mode of the previous console * driver could be in the same resolution but we are using different * hardware so we have to initialize the hardware. * * We need to do it in fbcon_init() to prevent screen corruption. */ if (CON_IS_VISIBLE(vc) && vc->vc_mode == KD_TEXT) { if (info->fbops->fb_set_par && !(ops->flags & FBCON_FLAGS_INIT)) info->fbops->fb_set_par(info); ops->flags |= FBCON_FLAGS_INIT; } ops->graphics = 0; if ((cap & FBINFO_HWACCEL_COPYAREA) && !(cap & FBINFO_HWACCEL_DISABLED)) p->scrollmode = SCROLL_MOVE; else /* default to something safe */ p->scrollmode = SCROLL_REDRAW; /* * ++guenther: console.c:vc_allocate() relies on initializing * vc_{cols,rows}, but we must not set those if we are only * resizing the console. */ if (!init) { vc->vc_cols = new_cols; vc->vc_rows = new_rows; } if (logo) fbcon_prepare_logo(vc, info, cols, rows, new_cols, new_rows); if (vc == svc && softback_buf) fbcon_update_softback(vc); if (ops->rotate_font && ops->rotate_font(info, vc)) { ops->rotate = FB_ROTATE_UR; set_blitting_type(vc, info); } ops->p = &fb_display[fg_console]; } static void fbcon_free_font(struct display *p) { if (p->userfont && p->fontdata && (--REFCOUNT(p->fontdata) == 0)) kfree(p->fontdata - FONT_EXTRA_WORDS * sizeof(int)); p->fontdata = NULL; p->userfont = 0; } static void fbcon_deinit(struct vc_data *vc) { struct display *p = &fb_display[vc->vc_num]; struct fb_info *info; struct fbcon_ops *ops; int idx; fbcon_free_font(p); idx = con2fb_map[vc->vc_num]; if (idx == -1) goto finished; info = registered_fb[idx]; if (!info) goto finished; ops = info->fbcon_par; if (!ops) goto finished; if (CON_IS_VISIBLE(vc)) fbcon_del_cursor_timer(info); ops->flags &= ~FBCON_FLAGS_INIT; finished: if (!con_is_bound(&fb_con)) fbcon_exit(); return; } /* ====================================================================== */ /* fbcon_XXX routines - interface used by the world * * This system is now divided into two levels because of complications * caused by hardware scrolling. Top level functions: * * fbcon_bmove(), fbcon_clear(), fbcon_putc(), fbcon_clear_margins() * * handles y values in range [0, scr_height-1] that correspond to real * screen positions. y_wrap shift means that first line of bitmap may be * anywhere on this display. These functions convert lineoffsets to * bitmap offsets and deal with the wrap-around case by splitting blits. * * fbcon_bmove_physical_8() -- These functions fast implementations * fbcon_clear_physical_8() -- of original fbcon_XXX fns. * fbcon_putc_physical_8() -- (font width != 8) may be added later * * WARNING: * * At the moment fbcon_putc() cannot blit across vertical wrap boundary * Implies should only really hardware scroll in rows. Only reason for * restriction is simplicity & efficiency at the moment. */ static void fbcon_clear(struct vc_data *vc, int sy, int sx, int height, int width) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; u_int y_break; if (fbcon_is_inactive(vc, info)) return; if (!height || !width) return; /* Split blits that cross physical y_wrap boundary */ y_break = p->vrows - p->yscroll; if (sy < y_break && sy + height - 1 >= y_break) { u_int b = y_break - sy; ops->clear(vc, info, real_y(p, sy), sx, b, width); ops->clear(vc, info, real_y(p, sy + b), sx, height - b, width); } else ops->clear(vc, info, real_y(p, sy), sx, height, width); } static void fbcon_putcs(struct vc_data *vc, const unsigned short *s, int count, int ypos, int xpos) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct display *p = &fb_display[vc->vc_num]; struct fbcon_ops *ops = info->fbcon_par; if (!fbcon_is_inactive(vc, info)) ops->putcs(vc, info, s, count, real_y(p, ypos), xpos, get_color(vc, info, scr_readw(s), 1), get_color(vc, info, scr_readw(s), 0)); } static void fbcon_putc(struct vc_data *vc, int c, int ypos, int xpos) { unsigned short chr; scr_writew(c, &chr); fbcon_putcs(vc, &chr, 1, ypos, xpos); } static void fbcon_clear_margins(struct vc_data *vc, int bottom_only) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; if (!fbcon_is_inactive(vc, info)) ops->clear_margins(vc, info, bottom_only); } static void fbcon_cursor(struct vc_data *vc, int mode) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; int y; int c = scr_readw((u16 *) vc->vc_pos); if (fbcon_is_inactive(vc, info) || vc->vc_deccm != 1) return; if (vc->vc_cursor_type & 0x10) fbcon_del_cursor_timer(info); else fbcon_add_cursor_timer(info); ops->cursor_flash = (mode == CM_ERASE) ? 0 : 1; if (mode & CM_SOFTBACK) { mode &= ~CM_SOFTBACK; y = softback_lines; } else { if (softback_lines) fbcon_set_origin(vc); y = 0; } ops->cursor(vc, info, mode, y, get_color(vc, info, c, 1), get_color(vc, info, c, 0)); vbl_cursor_cnt = CURSOR_DRAW_DELAY; } static int scrollback_phys_max = 0; static int scrollback_max = 0; static int scrollback_current = 0; static void fbcon_set_disp(struct fb_info *info, struct fb_var_screeninfo *var, int unit) { struct display *p, *t; struct vc_data **default_mode, *vc; struct vc_data *svc; struct fbcon_ops *ops = info->fbcon_par; int rows, cols, charcnt = 256; p = &fb_display[unit]; if (var_to_display(p, var, info)) return; vc = vc_cons[unit].d; if (!vc) return; default_mode = vc->vc_display_fg; svc = *default_mode; t = &fb_display[svc->vc_num]; if (!vc->vc_font.data) { vc->vc_font.data = (void *)(p->fontdata = t->fontdata); vc->vc_font.width = (*default_mode)->vc_font.width; vc->vc_font.height = (*default_mode)->vc_font.height; p->userfont = t->userfont; if (p->userfont) REFCOUNT(p->fontdata)++; } if (p->userfont) charcnt = FNTCHARCNT(p->fontdata); var->activate = FB_ACTIVATE_NOW; info->var.activate = var->activate; var->yoffset = info->var.yoffset; var->xoffset = info->var.xoffset; fb_set_var(info, var); ops->var = info->var; vc->vc_can_do_color = (fb_get_color_depth(&info->var, &info->fix)!=1); vc->vc_complement_mask = vc->vc_can_do_color ? 0x7700 : 0x0800; if (charcnt == 256) { vc->vc_hi_font_mask = 0; } else { vc->vc_hi_font_mask = 0x100; if (vc->vc_can_do_color) vc->vc_complement_mask <<= 1; } if (!*svc->vc_uni_pagedir_loc) con_set_default_unimap(svc); if (!*vc->vc_uni_pagedir_loc) con_copy_unimap(vc, svc); cols = FBCON_SWAP(ops->rotate, info->var.xres, info->var.yres); rows = FBCON_SWAP(ops->rotate, info->var.yres, info->var.xres); cols /= vc->vc_font.width; rows /= vc->vc_font.height; vc_resize(vc, cols, rows); if (CON_IS_VISIBLE(vc)) { update_screen(vc); if (softback_buf) fbcon_update_softback(vc); } } static __inline__ void ywrap_up(struct vc_data *vc, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; p->yscroll += count; if (p->yscroll >= p->vrows) /* Deal with wrap */ p->yscroll -= p->vrows; ops->var.xoffset = 0; ops->var.yoffset = p->yscroll * vc->vc_font.height; ops->var.vmode |= FB_VMODE_YWRAP; ops->update_start(info); scrollback_max += count; if (scrollback_max > scrollback_phys_max) scrollback_max = scrollback_phys_max; scrollback_current = 0; } static __inline__ void ywrap_down(struct vc_data *vc, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; p->yscroll -= count; if (p->yscroll < 0) /* Deal with wrap */ p->yscroll += p->vrows; ops->var.xoffset = 0; ops->var.yoffset = p->yscroll * vc->vc_font.height; ops->var.vmode |= FB_VMODE_YWRAP; ops->update_start(info); scrollback_max -= count; if (scrollback_max < 0) scrollback_max = 0; scrollback_current = 0; } static __inline__ void ypan_up(struct vc_data *vc, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct display *p = &fb_display[vc->vc_num]; struct fbcon_ops *ops = info->fbcon_par; p->yscroll += count; if (p->yscroll > p->vrows - vc->vc_rows) { ops->bmove(vc, info, p->vrows - vc->vc_rows, 0, 0, 0, vc->vc_rows, vc->vc_cols); p->yscroll -= p->vrows - vc->vc_rows; } ops->var.xoffset = 0; ops->var.yoffset = p->yscroll * vc->vc_font.height; ops->var.vmode &= ~FB_VMODE_YWRAP; ops->update_start(info); fbcon_clear_margins(vc, 1); scrollback_max += count; if (scrollback_max > scrollback_phys_max) scrollback_max = scrollback_phys_max; scrollback_current = 0; } static __inline__ void ypan_up_redraw(struct vc_data *vc, int t, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; p->yscroll += count; if (p->yscroll > p->vrows - vc->vc_rows) { p->yscroll -= p->vrows - vc->vc_rows; fbcon_redraw_move(vc, p, t + count, vc->vc_rows - count, t); } ops->var.xoffset = 0; ops->var.yoffset = p->yscroll * vc->vc_font.height; ops->var.vmode &= ~FB_VMODE_YWRAP; ops->update_start(info); fbcon_clear_margins(vc, 1); scrollback_max += count; if (scrollback_max > scrollback_phys_max) scrollback_max = scrollback_phys_max; scrollback_current = 0; } static __inline__ void ypan_down(struct vc_data *vc, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct display *p = &fb_display[vc->vc_num]; struct fbcon_ops *ops = info->fbcon_par; p->yscroll -= count; if (p->yscroll < 0) { ops->bmove(vc, info, 0, 0, p->vrows - vc->vc_rows, 0, vc->vc_rows, vc->vc_cols); p->yscroll += p->vrows - vc->vc_rows; } ops->var.xoffset = 0; ops->var.yoffset = p->yscroll * vc->vc_font.height; ops->var.vmode &= ~FB_VMODE_YWRAP; ops->update_start(info); fbcon_clear_margins(vc, 1); scrollback_max -= count; if (scrollback_max < 0) scrollback_max = 0; scrollback_current = 0; } static __inline__ void ypan_down_redraw(struct vc_data *vc, int t, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; p->yscroll -= count; if (p->yscroll < 0) { p->yscroll += p->vrows - vc->vc_rows; fbcon_redraw_move(vc, p, t, vc->vc_rows - count, t + count); } ops->var.xoffset = 0; ops->var.yoffset = p->yscroll * vc->vc_font.height; ops->var.vmode &= ~FB_VMODE_YWRAP; ops->update_start(info); fbcon_clear_margins(vc, 1); scrollback_max -= count; if (scrollback_max < 0) scrollback_max = 0; scrollback_current = 0; } static void fbcon_redraw_softback(struct vc_data *vc, struct display *p, long delta) { int count = vc->vc_rows; unsigned short *d, *s; unsigned long n; int line = 0; d = (u16 *) softback_curr; if (d == (u16 *) softback_in) d = (u16 *) vc->vc_origin; n = softback_curr + delta * vc->vc_size_row; softback_lines -= delta; if (delta < 0) { if (softback_curr < softback_top && n < softback_buf) { n += softback_end - softback_buf; if (n < softback_top) { softback_lines -= (softback_top - n) / vc->vc_size_row; n = softback_top; } } else if (softback_curr >= softback_top && n < softback_top) { softback_lines -= (softback_top - n) / vc->vc_size_row; n = softback_top; } } else { if (softback_curr > softback_in && n >= softback_end) { n += softback_buf - softback_end; if (n > softback_in) { n = softback_in; softback_lines = 0; } } else if (softback_curr <= softback_in && n > softback_in) { n = softback_in; softback_lines = 0; } } if (n == softback_curr) return; softback_curr = n; s = (u16 *) softback_curr; if (s == (u16 *) softback_in) s = (u16 *) vc->vc_origin; while (count--) { unsigned short *start; unsigned short *le; unsigned short c; int x = 0; unsigned short attr = 1; start = s; le = advance_row(s, 1); do { c = scr_readw(s); if (attr != (c & 0xff00)) { attr = c & 0xff00; if (s > start) { fbcon_putcs(vc, start, s - start, line, x); x += s - start; start = s; } } if (c == scr_readw(d)) { if (s > start) { fbcon_putcs(vc, start, s - start, line, x); x += s - start + 1; start = s + 1; } else { x++; start++; } } s++; d++; } while (s < le); if (s > start) fbcon_putcs(vc, start, s - start, line, x); line++; if (d == (u16 *) softback_end) d = (u16 *) softback_buf; if (d == (u16 *) softback_in) d = (u16 *) vc->vc_origin; if (s == (u16 *) softback_end) s = (u16 *) softback_buf; if (s == (u16 *) softback_in) s = (u16 *) vc->vc_origin; } } static void fbcon_redraw_move(struct vc_data *vc, struct display *p, int line, int count, int dy) { unsigned short *s = (unsigned short *) (vc->vc_origin + vc->vc_size_row * line); while (count--) { unsigned short *start = s; unsigned short *le = advance_row(s, 1); unsigned short c; int x = 0; unsigned short attr = 1; do { c = scr_readw(s); if (attr != (c & 0xff00)) { attr = c & 0xff00; if (s > start) { fbcon_putcs(vc, start, s - start, dy, x); x += s - start; start = s; } } console_conditional_schedule(); s++; } while (s < le); if (s > start) fbcon_putcs(vc, start, s - start, dy, x); console_conditional_schedule(); dy++; } } static void fbcon_redraw_blit(struct vc_data *vc, struct fb_info *info, struct display *p, int line, int count, int ycount) { int offset = ycount * vc->vc_cols; unsigned short *d = (unsigned short *) (vc->vc_origin + vc->vc_size_row * line); unsigned short *s = d + offset; struct fbcon_ops *ops = info->fbcon_par; while (count--) { unsigned short *start = s; unsigned short *le = advance_row(s, 1); unsigned short c; int x = 0; do { c = scr_readw(s); if (c == scr_readw(d)) { if (s > start) { ops->bmove(vc, info, line + ycount, x, line, x, 1, s-start); x += s - start + 1; start = s + 1; } else { x++; start++; } } scr_writew(c, d); console_conditional_schedule(); s++; d++; } while (s < le); if (s > start) ops->bmove(vc, info, line + ycount, x, line, x, 1, s-start); console_conditional_schedule(); if (ycount > 0) line++; else { line--; /* NOTE: We subtract two lines from these pointers */ s -= vc->vc_size_row; d -= vc->vc_size_row; } } } static void fbcon_redraw(struct vc_data *vc, struct display *p, int line, int count, int offset) { unsigned short *d = (unsigned short *) (vc->vc_origin + vc->vc_size_row * line); unsigned short *s = d + offset; while (count--) { unsigned short *start = s; unsigned short *le = advance_row(s, 1); unsigned short c; int x = 0; unsigned short attr = 1; do { c = scr_readw(s); if (attr != (c & 0xff00)) { attr = c & 0xff00; if (s > start) { fbcon_putcs(vc, start, s - start, line, x); x += s - start; start = s; } } if (c == scr_readw(d)) { if (s > start) { fbcon_putcs(vc, start, s - start, line, x); x += s - start + 1; start = s + 1; } else { x++; start++; } } scr_writew(c, d); console_conditional_schedule(); s++; d++; } while (s < le); if (s > start) fbcon_putcs(vc, start, s - start, line, x); console_conditional_schedule(); if (offset > 0) line++; else { line--; /* NOTE: We subtract two lines from these pointers */ s -= vc->vc_size_row; d -= vc->vc_size_row; } } } static inline void fbcon_softback_note(struct vc_data *vc, int t, int count) { unsigned short *p; if (vc->vc_num != fg_console) return; p = (unsigned short *) (vc->vc_origin + t * vc->vc_size_row); while (count) { scr_memcpyw((u16 *) softback_in, p, vc->vc_size_row); count--; p = advance_row(p, 1); softback_in += vc->vc_size_row; if (softback_in == softback_end) softback_in = softback_buf; if (softback_in == softback_top) { softback_top += vc->vc_size_row; if (softback_top == softback_end) softback_top = softback_buf; } } softback_curr = softback_in; } static int fbcon_scroll(struct vc_data *vc, int t, int b, int dir, int count) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct display *p = &fb_display[vc->vc_num]; int scroll_partial = info->flags & FBINFO_PARTIAL_PAN_OK; unsigned short saved_ec; int ret; if (fbcon_is_inactive(vc, info)) return -EINVAL; fbcon_cursor(vc, CM_ERASE); /* * ++Geert: Only use ywrap/ypan if the console is in text mode * ++Andrew: Only use ypan on hardware text mode when scrolling the * whole screen (prevents flicker). */ saved_ec = vc->vc_video_erase_char; vc->vc_video_erase_char = vc->vc_scrl_erase_char; ret = 0; switch (dir) { case SM_UP: if (count > vc->vc_rows) /* Maximum realistic size */ count = vc->vc_rows; if (softback_top) fbcon_softback_note(vc, t, count); if (logo_shown >= 0) goto redraw_up; switch (p->scrollmode) { case SCROLL_MOVE: fbcon_redraw_blit(vc, info, p, t, b - t - count, count); fbcon_clear(vc, b - count, 0, count, vc->vc_cols); scr_memsetw((unsigned short *) (vc->vc_origin + vc->vc_size_row * (b - count)), vc->vc_scrl_erase_char, vc->vc_size_row * count); ret = 1; break; case SCROLL_WRAP_MOVE: if (b - t - count > 3 * vc->vc_rows >> 2) { if (t > 0) fbcon_bmove(vc, 0, 0, count, 0, t, vc->vc_cols); ywrap_up(vc, count); if (vc->vc_rows - b > 0) fbcon_bmove(vc, b - count, 0, b, 0, vc->vc_rows - b, vc->vc_cols); } else if (info->flags & FBINFO_READS_FAST) fbcon_bmove(vc, t + count, 0, t, 0, b - t - count, vc->vc_cols); else goto redraw_up; fbcon_clear(vc, b - count, 0, count, vc->vc_cols); break; case SCROLL_PAN_REDRAW: if ((p->yscroll + count <= 2 * (p->vrows - vc->vc_rows)) && ((!scroll_partial && (b - t == vc->vc_rows)) || (scroll_partial && (b - t - count > 3 * vc->vc_rows >> 2)))) { if (t > 0) fbcon_redraw_move(vc, p, 0, t, count); ypan_up_redraw(vc, t, count); if (vc->vc_rows - b > 0) fbcon_redraw_move(vc, p, b, vc->vc_rows - b, b); } else fbcon_redraw_move(vc, p, t + count, b - t - count, t); fbcon_clear(vc, b - count, 0, count, vc->vc_cols); break; case SCROLL_PAN_MOVE: if ((p->yscroll + count <= 2 * (p->vrows - vc->vc_rows)) && ((!scroll_partial && (b - t == vc->vc_rows)) || (scroll_partial && (b - t - count > 3 * vc->vc_rows >> 2)))) { if (t > 0) fbcon_bmove(vc, 0, 0, count, 0, t, vc->vc_cols); ypan_up(vc, count); if (vc->vc_rows - b > 0) fbcon_bmove(vc, b - count, 0, b, 0, vc->vc_rows - b, vc->vc_cols); } else if (info->flags & FBINFO_READS_FAST) fbcon_bmove(vc, t + count, 0, t, 0, b - t - count, vc->vc_cols); else goto redraw_up; fbcon_clear(vc, b - count, 0, count, vc->vc_cols); break; case SCROLL_REDRAW: redraw_up: fbcon_redraw(vc, p, t, b - t - count, count * vc->vc_cols); fbcon_clear(vc, b - count, 0, count, vc->vc_cols); scr_memsetw((unsigned short *) (vc->vc_origin + vc->vc_size_row * (b - count)), vc->vc_scrl_erase_char, vc->vc_size_row * count); ret = 1; break; } break; case SM_DOWN: if (count > vc->vc_rows) /* Maximum realistic size */ count = vc->vc_rows; if (logo_shown >= 0) goto redraw_down; switch (p->scrollmode) { case SCROLL_MOVE: fbcon_redraw_blit(vc, info, p, b - 1, b - t - count, -count); fbcon_clear(vc, t, 0, count, vc->vc_cols); scr_memsetw((unsigned short *) (vc->vc_origin + vc->vc_size_row * t), vc->vc_scrl_erase_char, vc->vc_size_row * count); ret = 1; break; case SCROLL_WRAP_MOVE: if (b - t - count > 3 * vc->vc_rows >> 2) { if (vc->vc_rows - b > 0) fbcon_bmove(vc, b, 0, b - count, 0, vc->vc_rows - b, vc->vc_cols); ywrap_down(vc, count); if (t > 0) fbcon_bmove(vc, count, 0, 0, 0, t, vc->vc_cols); } else if (info->flags & FBINFO_READS_FAST) fbcon_bmove(vc, t, 0, t + count, 0, b - t - count, vc->vc_cols); else goto redraw_down; fbcon_clear(vc, t, 0, count, vc->vc_cols); break; case SCROLL_PAN_MOVE: if ((count - p->yscroll <= p->vrows - vc->vc_rows) && ((!scroll_partial && (b - t == vc->vc_rows)) || (scroll_partial && (b - t - count > 3 * vc->vc_rows >> 2)))) { if (vc->vc_rows - b > 0) fbcon_bmove(vc, b, 0, b - count, 0, vc->vc_rows - b, vc->vc_cols); ypan_down(vc, count); if (t > 0) fbcon_bmove(vc, count, 0, 0, 0, t, vc->vc_cols); } else if (info->flags & FBINFO_READS_FAST) fbcon_bmove(vc, t, 0, t + count, 0, b - t - count, vc->vc_cols); else goto redraw_down; fbcon_clear(vc, t, 0, count, vc->vc_cols); break; case SCROLL_PAN_REDRAW: if ((count - p->yscroll <= p->vrows - vc->vc_rows) && ((!scroll_partial && (b - t == vc->vc_rows)) || (scroll_partial && (b - t - count > 3 * vc->vc_rows >> 2)))) { if (vc->vc_rows - b > 0) fbcon_redraw_move(vc, p, b, vc->vc_rows - b, b - count); ypan_down_redraw(vc, t, count); if (t > 0) fbcon_redraw_move(vc, p, count, t, 0); } else fbcon_redraw_move(vc, p, t, b - t - count, t + count); fbcon_clear(vc, t, 0, count, vc->vc_cols); break; case SCROLL_REDRAW: redraw_down: fbcon_redraw(vc, p, b - 1, b - t - count, -count * vc->vc_cols); fbcon_clear(vc, t, 0, count, vc->vc_cols); scr_memsetw((unsigned short *) (vc->vc_origin + vc->vc_size_row * t), vc->vc_scrl_erase_char, vc->vc_size_row * count); ret = 1; break; } break; } vc->vc_video_erase_char = saved_ec; return ret; } static void fbcon_bmove(struct vc_data *vc, int sy, int sx, int dy, int dx, int height, int width) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct display *p = &fb_display[vc->vc_num]; if (fbcon_is_inactive(vc, info)) return; if (!width || !height) return; /* Split blits that cross physical y_wrap case. * Pathological case involves 4 blits, better to use recursive * code rather than unrolled case * * Recursive invocations don't need to erase the cursor over and * over again, so we use fbcon_bmove_rec() */ fbcon_bmove_rec(vc, p, sy, sx, dy, dx, height, width, p->vrows - p->yscroll); } static void fbcon_bmove_rec(struct vc_data *vc, struct display *p, int sy, int sx, int dy, int dx, int height, int width, u_int y_break) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; u_int b; if (sy < y_break && sy + height > y_break) { b = y_break - sy; if (dy < sy) { /* Avoid trashing self */ fbcon_bmove_rec(vc, p, sy, sx, dy, dx, b, width, y_break); fbcon_bmove_rec(vc, p, sy + b, sx, dy + b, dx, height - b, width, y_break); } else { fbcon_bmove_rec(vc, p, sy + b, sx, dy + b, dx, height - b, width, y_break); fbcon_bmove_rec(vc, p, sy, sx, dy, dx, b, width, y_break); } return; } if (dy < y_break && dy + height > y_break) { b = y_break - dy; if (dy < sy) { /* Avoid trashing self */ fbcon_bmove_rec(vc, p, sy, sx, dy, dx, b, width, y_break); fbcon_bmove_rec(vc, p, sy + b, sx, dy + b, dx, height - b, width, y_break); } else { fbcon_bmove_rec(vc, p, sy + b, sx, dy + b, dx, height - b, width, y_break); fbcon_bmove_rec(vc, p, sy, sx, dy, dx, b, width, y_break); } return; } ops->bmove(vc, info, real_y(p, sy), sx, real_y(p, dy), dx, height, width); } static __inline__ void updatescrollmode(struct display *p, struct fb_info *info, struct vc_data *vc) { struct fbcon_ops *ops = info->fbcon_par; int fh = vc->vc_font.height; int cap = info->flags; u16 t = 0; int ypan = FBCON_SWAP(ops->rotate, info->fix.ypanstep, info->fix.xpanstep); int ywrap = FBCON_SWAP(ops->rotate, info->fix.ywrapstep, t); int yres = FBCON_SWAP(ops->rotate, info->var.yres, info->var.xres); int vyres = FBCON_SWAP(ops->rotate, info->var.yres_virtual, info->var.xres_virtual); int good_pan = (cap & FBINFO_HWACCEL_YPAN) && divides(ypan, vc->vc_font.height) && vyres > yres; int good_wrap = (cap & FBINFO_HWACCEL_YWRAP) && divides(ywrap, vc->vc_font.height) && divides(vc->vc_font.height, vyres) && divides(vc->vc_font.height, yres); int reading_fast = cap & FBINFO_READS_FAST; int fast_copyarea = (cap & FBINFO_HWACCEL_COPYAREA) && !(cap & FBINFO_HWACCEL_DISABLED); int fast_imageblit = (cap & FBINFO_HWACCEL_IMAGEBLIT) && !(cap & FBINFO_HWACCEL_DISABLED); p->vrows = vyres/fh; if (yres > (fh * (vc->vc_rows + 1))) p->vrows -= (yres - (fh * vc->vc_rows)) / fh; if ((yres % fh) && (vyres % fh < yres % fh)) p->vrows--; if (good_wrap || good_pan) { if (reading_fast || fast_copyarea) p->scrollmode = good_wrap ? SCROLL_WRAP_MOVE : SCROLL_PAN_MOVE; else p->scrollmode = good_wrap ? SCROLL_REDRAW : SCROLL_PAN_REDRAW; } else { if (reading_fast || (fast_copyarea && !fast_imageblit)) p->scrollmode = SCROLL_MOVE; else p->scrollmode = SCROLL_REDRAW; } } static int fbcon_resize(struct vc_data *vc, unsigned int width, unsigned int height, unsigned int user) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; struct fb_var_screeninfo var = info->var; int x_diff, y_diff, virt_w, virt_h, virt_fw, virt_fh; virt_w = FBCON_SWAP(ops->rotate, width, height); virt_h = FBCON_SWAP(ops->rotate, height, width); virt_fw = FBCON_SWAP(ops->rotate, vc->vc_font.width, vc->vc_font.height); virt_fh = FBCON_SWAP(ops->rotate, vc->vc_font.height, vc->vc_font.width); var.xres = virt_w * virt_fw; var.yres = virt_h * virt_fh; x_diff = info->var.xres - var.xres; y_diff = info->var.yres - var.yres; if (x_diff < 0 || x_diff > virt_fw || y_diff < 0 || y_diff > virt_fh) { const struct fb_videomode *mode; DPRINTK("attempting resize %ix%i\n", var.xres, var.yres); mode = fb_find_best_mode(&var, &info->modelist); if (mode == NULL) return -EINVAL; display_to_var(&var, p); fb_videomode_to_var(&var, mode); if (virt_w > var.xres/virt_fw || virt_h > var.yres/virt_fh) return -EINVAL; DPRINTK("resize now %ix%i\n", var.xres, var.yres); if (CON_IS_VISIBLE(vc)) { var.activate = FB_ACTIVATE_NOW | FB_ACTIVATE_FORCE; fb_set_var(info, &var); } var_to_display(p, &info->var, info); ops->var = info->var; } updatescrollmode(p, info, vc); return 0; } static int fbcon_switch(struct vc_data *vc) { struct fb_info *info, *old_info = NULL; struct fbcon_ops *ops; struct display *p = &fb_display[vc->vc_num]; struct fb_var_screeninfo var; int i, prev_console, charcnt = 256; info = registered_fb[con2fb_map[vc->vc_num]]; ops = info->fbcon_par; if (softback_top) { if (softback_lines) fbcon_set_origin(vc); softback_top = softback_curr = softback_in = softback_buf; softback_lines = 0; fbcon_update_softback(vc); } if (logo_shown >= 0) { struct vc_data *conp2 = vc_cons[logo_shown].d; if (conp2->vc_top == logo_lines && conp2->vc_bottom == conp2->vc_rows) conp2->vc_top = 0; logo_shown = FBCON_LOGO_CANSHOW; } prev_console = ops->currcon; if (prev_console != -1) old_info = registered_fb[con2fb_map[prev_console]]; /* * FIXME: If we have multiple fbdev's loaded, we need to * update all info->currcon. Perhaps, we can place this * in a centralized structure, but this might break some * drivers. * * info->currcon = vc->vc_num; */ for (i = 0; i < FB_MAX; i++) { if (registered_fb[i] != NULL && registered_fb[i]->fbcon_par) { struct fbcon_ops *o = registered_fb[i]->fbcon_par; o->currcon = vc->vc_num; } } memset(&var, 0, sizeof(struct fb_var_screeninfo)); display_to_var(&var, p); var.activate = FB_ACTIVATE_NOW; /* * make sure we don't unnecessarily trip the memcmp() * in fb_set_var() */ info->var.activate = var.activate; var.vmode |= info->var.vmode & ~FB_VMODE_MASK; fb_set_var(info, &var); ops->var = info->var; if (old_info != NULL && (old_info != info || info->flags & FBINFO_MISC_ALWAYS_SETPAR)) { if (info->fbops->fb_set_par) info->fbops->fb_set_par(info); if (old_info != info) fbcon_del_cursor_timer(old_info); } if (fbcon_is_inactive(vc, info) || ops->blank_state != FB_BLANK_UNBLANK) fbcon_del_cursor_timer(info); else fbcon_add_cursor_timer(info); set_blitting_type(vc, info); ops->cursor_reset = 1; if (ops->rotate_font && ops->rotate_font(info, vc)) { ops->rotate = FB_ROTATE_UR; set_blitting_type(vc, info); } vc->vc_can_do_color = (fb_get_color_depth(&info->var, &info->fix)!=1); vc->vc_complement_mask = vc->vc_can_do_color ? 0x7700 : 0x0800; if (p->userfont) charcnt = FNTCHARCNT(vc->vc_font.data); if (charcnt > 256) vc->vc_complement_mask <<= 1; updatescrollmode(p, info, vc); switch (p->scrollmode) { case SCROLL_WRAP_MOVE: scrollback_phys_max = p->vrows - vc->vc_rows; break; case SCROLL_PAN_MOVE: case SCROLL_PAN_REDRAW: scrollback_phys_max = p->vrows - 2 * vc->vc_rows; if (scrollback_phys_max < 0) scrollback_phys_max = 0; break; default: scrollback_phys_max = 0; break; } scrollback_max = 0; scrollback_current = 0; if (!fbcon_is_inactive(vc, info)) { ops->var.xoffset = ops->var.yoffset = p->yscroll = 0; ops->update_start(info); } fbcon_set_palette(vc, color_table); fbcon_clear_margins(vc, 0); if (logo_shown == FBCON_LOGO_DRAW) { logo_shown = fg_console; /* This is protected above by initmem_freed */ fb_show_logo(info, ops->rotate); update_region(vc, vc->vc_origin + vc->vc_size_row * vc->vc_top, vc->vc_size_row * (vc->vc_bottom - vc->vc_top) / 2); return 0; } return 1; } static void fbcon_generic_blank(struct vc_data *vc, struct fb_info *info, int blank) { struct fb_event event; if (blank) { unsigned short charmask = vc->vc_hi_font_mask ? 0x1ff : 0xff; unsigned short oldc; oldc = vc->vc_video_erase_char; vc->vc_video_erase_char &= charmask; fbcon_clear(vc, 0, 0, vc->vc_rows, vc->vc_cols); vc->vc_video_erase_char = oldc; } event.info = info; event.data = &blank; fb_notifier_call_chain(FB_EVENT_CONBLANK, &event); } static int fbcon_blank(struct vc_data *vc, int blank, int mode_switch) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; if (mode_switch) { struct fb_var_screeninfo var = info->var; ops->graphics = 1; if (!blank) { if (info->fbops->fb_save_state) info->fbops->fb_save_state(info); var.activate = FB_ACTIVATE_NOW | FB_ACTIVATE_FORCE; fb_set_var(info, &var); ops->graphics = 0; ops->var = info->var; } else if (info->fbops->fb_restore_state) info->fbops->fb_restore_state(info); } if (!fbcon_is_inactive(vc, info)) { if (ops->blank_state != blank) { ops->blank_state = blank; fbcon_cursor(vc, blank ? CM_ERASE : CM_DRAW); ops->cursor_flash = (!blank); if (fb_blank(info, blank)) fbcon_generic_blank(vc, info, blank); } if (!blank) update_screen(vc); } if (mode_switch || fbcon_is_inactive(vc, info) || ops->blank_state != FB_BLANK_UNBLANK) fbcon_del_cursor_timer(info); else fbcon_add_cursor_timer(info); return 0; } static int fbcon_get_font(struct vc_data *vc, struct console_font *font) { u8 *fontdata = vc->vc_font.data; u8 *data = font->data; int i, j; font->width = vc->vc_font.width; font->height = vc->vc_font.height; font->charcount = vc->vc_hi_font_mask ? 512 : 256; if (!font->data) return 0; if (font->width <= 8) { j = vc->vc_font.height; for (i = 0; i < font->charcount; i++) { memcpy(data, fontdata, j); memset(data + j, 0, 32 - j); data += 32; fontdata += j; } } else if (font->width <= 16) { j = vc->vc_font.height * 2; for (i = 0; i < font->charcount; i++) { memcpy(data, fontdata, j); memset(data + j, 0, 64 - j); data += 64; fontdata += j; } } else if (font->width <= 24) { for (i = 0; i < font->charcount; i++) { for (j = 0; j < vc->vc_font.height; j++) { *data++ = fontdata[0]; *data++ = fontdata[1]; *data++ = fontdata[2]; fontdata += sizeof(u32); } memset(data, 0, 3 * (32 - j)); data += 3 * (32 - j); } } else { j = vc->vc_font.height * 4; for (i = 0; i < font->charcount; i++) { memcpy(data, fontdata, j); memset(data + j, 0, 128 - j); data += 128; fontdata += j; } } return 0; } static int fbcon_do_set_font(struct vc_data *vc, int w, int h, const u8 * data, int userfont) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; struct fbcon_ops *ops = info->fbcon_par; struct display *p = &fb_display[vc->vc_num]; int resize; int cnt; char *old_data = NULL; if (CON_IS_VISIBLE(vc) && softback_lines) fbcon_set_origin(vc); resize = (w != vc->vc_font.width) || (h != vc->vc_font.height); if (p->userfont) old_data = vc->vc_font.data; if (userfont) cnt = FNTCHARCNT(data); else cnt = 256; vc->vc_font.data = (void *)(p->fontdata = data); if ((p->userfont = userfont)) REFCOUNT(data)++; vc->vc_font.width = w; vc->vc_font.height = h; if (vc->vc_hi_font_mask && cnt == 256) { vc->vc_hi_font_mask = 0; if (vc->vc_can_do_color) { vc->vc_complement_mask >>= 1; vc->vc_s_complement_mask >>= 1; } /* ++Edmund: reorder the attribute bits */ if (vc->vc_can_do_color) { unsigned short *cp = (unsigned short *) vc->vc_origin; int count = vc->vc_screenbuf_size / 2; unsigned short c; for (; count > 0; count--, cp++) { c = scr_readw(cp); scr_writew(((c & 0xfe00) >> 1) | (c & 0xff), cp); } c = vc->vc_video_erase_char; vc->vc_video_erase_char = ((c & 0xfe00) >> 1) | (c & 0xff); c = vc->vc_def_color; vc->vc_scrl_erase_char = ((c & 0xFE00) >> 1) | (c & 0xFF); vc->vc_attr >>= 1; } } else if (!vc->vc_hi_font_mask && cnt == 512) { vc->vc_hi_font_mask = 0x100; if (vc->vc_can_do_color) { vc->vc_complement_mask <<= 1; vc->vc_s_complement_mask <<= 1; } /* ++Edmund: reorder the attribute bits */ { unsigned short *cp = (unsigned short *) vc->vc_origin; int count = vc->vc_screenbuf_size / 2; unsigned short c; for (; count > 0; count--, cp++) { unsigned short newc; c = scr_readw(cp); if (vc->vc_can_do_color) newc = ((c & 0xff00) << 1) | (c & 0xff); else newc = c & ~0x100; scr_writew(newc, cp); } c = vc->vc_video_erase_char; if (vc->vc_can_do_color) { vc->vc_video_erase_char = ((c & 0xff00) << 1) | (c & 0xff); c = vc->vc_def_color; vc->vc_scrl_erase_char = ((c & 0xFF00) << 1) | (c & 0xFF); vc->vc_attr <<= 1; } else { vc->vc_video_erase_char = c & ~0x100; vc->vc_scrl_erase_char = c & ~0x100; } } } if (resize) { int cols, rows; cols = FBCON_SWAP(ops->rotate, info->var.xres, info->var.yres); rows = FBCON_SWAP(ops->rotate, info->var.yres, info->var.xres); cols /= w; rows /= h; vc_resize(vc, cols, rows); if (CON_IS_VISIBLE(vc) && softback_buf) fbcon_update_softback(vc); } else if (CON_IS_VISIBLE(vc) && vc->vc_mode == KD_TEXT) { fbcon_clear_margins(vc, 0); update_screen(vc); } if (old_data && (--REFCOUNT(old_data) == 0)) kfree(old_data - FONT_EXTRA_WORDS * sizeof(int)); return 0; } static int fbcon_copy_font(struct vc_data *vc, int con) { struct display *od = &fb_display[con]; struct console_font *f = &vc->vc_font; if (od->fontdata == f->data) return 0; /* already the same font... */ return fbcon_do_set_font(vc, f->width, f->height, od->fontdata, od->userfont); } /* * User asked to set font; we are guaranteed that * a) width and height are in range 1..32 * b) charcount does not exceed 512 * but lets not assume that, since someone might someday want to use larger * fonts. And charcount of 512 is small for unicode support. * * However, user space gives the font in 32 rows , regardless of * actual font height. So a new API is needed if support for larger fonts * is ever implemented. */ static int fbcon_set_font(struct vc_data *vc, struct console_font *font, unsigned flags) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; unsigned charcount = font->charcount; int w = font->width; int h = font->height; int size; int i, csum; u8 *new_data, *data = font->data; int pitch = (font->width+7) >> 3; /* Is there a reason why fbconsole couldn't handle any charcount >256? * If not this check should be changed to charcount < 256 */ if (charcount != 256 && charcount != 512) return -EINVAL; /* Make sure drawing engine can handle the font */ if (!(info->pixmap.blit_x & (1 << (font->width - 1))) || !(info->pixmap.blit_y & (1 << (font->height - 1)))) return -EINVAL; /* Make sure driver can handle the font length */ if (fbcon_invalid_charcount(info, charcount)) return -EINVAL; size = h * pitch * charcount; new_data = kmalloc(FONT_EXTRA_WORDS * sizeof(int) + size, GFP_USER); if (!new_data) return -ENOMEM; new_data += FONT_EXTRA_WORDS * sizeof(int); FNTSIZE(new_data) = size; FNTCHARCNT(new_data) = charcount; REFCOUNT(new_data) = 0; /* usage counter */ for (i=0; i< charcount; i++) { memcpy(new_data + i*h*pitch, data + i*32*pitch, h*pitch); } /* Since linux has a nice crc32 function use it for counting font * checksums. */ csum = crc32(0, new_data, size); FNTSUM(new_data) = csum; /* Check if the same font is on some other console already */ for (i = first_fb_vc; i <= last_fb_vc; i++) { struct vc_data *tmp = vc_cons[i].d; if (fb_display[i].userfont && fb_display[i].fontdata && FNTSUM(fb_display[i].fontdata) == csum && FNTSIZE(fb_display[i].fontdata) == size && tmp->vc_font.width == w && !memcmp(fb_display[i].fontdata, new_data, size)) { kfree(new_data - FONT_EXTRA_WORDS * sizeof(int)); new_data = (u8 *)fb_display[i].fontdata; break; } } return fbcon_do_set_font(vc, font->width, font->height, new_data, 1); } static int fbcon_set_def_font(struct vc_data *vc, struct console_font *font, char *name) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; const struct font_desc *f; if (!name) f = get_default_font(info->var.xres, info->var.yres, info->pixmap.blit_x, info->pixmap.blit_y); else if (!(f = find_font(name))) return -ENOENT; font->width = f->width; font->height = f->height; return fbcon_do_set_font(vc, f->width, f->height, f->data, 0); } static u16 palette_red[16]; static u16 palette_green[16]; static u16 palette_blue[16]; static struct fb_cmap palette_cmap = { 0, 16, palette_red, palette_green, palette_blue, NULL }; static int fbcon_set_palette(struct vc_data *vc, unsigned char *table) { struct fb_info *info = registered_fb[con2fb_map[vc->vc_num]]; int i, j, k, depth; u8 val; if (fbcon_is_inactive(vc, info)) return -EINVAL; if (!CON_IS_VISIBLE(vc)) return 0; depth = fb_get_color_depth(&info->var, &info->fix); if (depth > 3) { for (i = j = 0; i < 16; i++) { k = table[i]; val = vc->vc_palette[j++]; palette_red[k] = (val << 8) | val; val = vc->vc_palette[j++]; palette_green[k] = (val << 8) | val; val = vc->vc_palette[j++]; palette_blue[k] = (val << 8) | val; } palette_cmap.len = 16; palette_cmap.start = 0; /* * If framebuffer is capable of less than 16 colors, * use default palette of fbcon. */ } else fb_copy_cmap(fb_default_cmap(1 << depth), &palette_cmap); return fb_set_cmap(&palette_cmap, info); } static u16 *fbcon_screen_pos(struct vc_data *vc, int offset) { unsigned long p; int line; if (vc->vc_num != fg_console || !softback_lines) return (u16 *) (vc->vc_origin + offset); line = offset / vc->vc_size_row; if (line >= softback_lines) return (u16 *) (vc->vc_origin + offset - softback_lines * vc->vc_size_row); p = softback_curr + offset; if (p >= softback_end) p += softback_buf - softback_end; return (u16 *) p; } static unsigned long fbcon_getxy(struct vc_data *vc, unsigned long pos, int *px, int *py) { unsigned long ret; int x, y; if (pos >= vc->vc_origin && pos < vc->vc_scr_end) { unsigned long offset = (pos - vc->vc_origin) / 2; x = offset % vc->vc_cols; y = offset / vc->vc_cols; if (vc->vc_num == fg_console) y += softback_lines; ret = pos + (vc->vc_cols - x) * 2; } else if (vc->vc_num == fg_console && softback_lines) { unsigned long offset = pos - softback_curr; if (pos < softback_curr) offset += softback_end - softback_buf; offset /= 2; x = offset % vc->vc_cols; y = offset / vc->vc_cols; ret = pos + (vc->vc_cols - x) * 2; if (ret == softback_end) ret = softback_buf; if (ret == softback_in) ret = vc->vc_origin; } else { /* Should not happen */ x = y = 0; ret = vc->vc_origin; } if (px) *px = x; if (py) *py = y; return ret; } /* As we might be inside of softback, we may work with non-contiguous buffer, that's why we have to use a separate routine. */ static void fbcon_invert_region(struct vc_data *vc, u16 * p, int cnt) { while (cnt--) { u16 a = scr_readw(p); if (!vc->vc_can_do_color) a ^= 0x0800; else if (vc->vc_hi_font_mask == 0x100) a = ((a) & 0x11ff) | (((a) & 0xe000) >> 4) | (((a) & 0x0e00) << 4); else a = ((a) & 0x88ff) | (((a) & 0x7000) >> 4) | (((a) & 0x0700) << 4); scr_writew(a, p++); if (p == (u16 *) softback_end) p = (u16 *) softback_buf; if (p == (u16 *) softback_in) p = (u16 *) vc->vc_origin; } } static int fbcon_scrolldelta(struct vc_data *vc, int lines) { struct fb_info *info = registered_fb[con2fb_map[fg_console]]; struct fbcon_ops *ops = info->fbcon_par; struct display *disp = &fb_display[fg_console]; int offset, limit, scrollback_old; if (softback_top) { if (vc->vc_num != fg_console) return 0; if (vc->vc_mode != KD_TEXT || !lines) return 0; if (logo_shown >= 0) { struct vc_data *conp2 = vc_cons[logo_shown].d; if (conp2->vc_top == logo_lines && conp2->vc_bottom == conp2->vc_rows) conp2->vc_top = 0; if (logo_shown == vc->vc_num) { unsigned long p, q; int i; p = softback_in; q = vc->vc_origin + logo_lines * vc->vc_size_row; for (i = 0; i < logo_lines; i++) { if (p == softback_top) break; if (p == softback_buf) p = softback_end; p -= vc->vc_size_row; q -= vc->vc_size_row; scr_memcpyw((u16 *) q, (u16 *) p, vc->vc_size_row); } softback_in = softback_curr = p; update_region(vc, vc->vc_origin, logo_lines * vc->vc_cols); } logo_shown = FBCON_LOGO_CANSHOW; } fbcon_cursor(vc, CM_ERASE | CM_SOFTBACK); fbcon_redraw_softback(vc, disp, lines); fbcon_cursor(vc, CM_DRAW | CM_SOFTBACK); return 0; } if (!scrollback_phys_max) return -ENOSYS; scrollback_old = scrollback_current; scrollback_current -= lines; if (scrollback_current < 0) scrollback_current = 0; else if (scrollback_current > scrollback_max) scrollback_current = scrollback_max; if (scrollback_current == scrollback_old) return 0; if (fbcon_is_inactive(vc, info)) return 0; fbcon_cursor(vc, CM_ERASE); offset = disp->yscroll - scrollback_current; limit = disp->vrows; switch (disp->scrollmode) { case SCROLL_WRAP_MOVE: info->var.vmode |= FB_VMODE_YWRAP; break; case SCROLL_PAN_MOVE: case SCROLL_PAN_REDRAW: limit -= vc->vc_rows; info->var.vmode &= ~FB_VMODE_YWRAP; break; } if (offset < 0) offset += limit; else if (offset >= limit) offset -= limit; ops->var.xoffset = 0; ops->var.yoffset = offset * vc->vc_font.height; ops->update_start(info); if (!scrollback_current) fbcon_cursor(vc, CM_DRAW); return 0; } static int fbcon_set_origin(struct vc_data *vc) { if (softback_lines) fbcon_scrolldelta(vc, softback_lines); return 0; } static void fbcon_suspended(struct fb_info *info) { struct vc_data *vc = NULL; struct fbcon_ops *ops = info->fbcon_par; if (!ops || ops->currcon < 0) return; vc = vc_cons[ops->currcon].d; /* Clear cursor, restore saved data */ fbcon_cursor(vc, CM_ERASE); } static void fbcon_resumed(struct fb_info *info) { struct vc_data *vc; struct fbcon_ops *ops = info->fbcon_par; if (!ops || ops->currcon < 0) return; vc = vc_cons[ops->currcon].d; update_screen(vc); } static void fbcon_modechanged(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; struct vc_data *vc; struct display *p; int rows, cols; if (!ops || ops->currcon < 0) return; vc = vc_cons[ops->currcon].d; if (vc->vc_mode != KD_TEXT || registered_fb[con2fb_map[ops->currcon]] != info) return; p = &fb_display[vc->vc_num]; set_blitting_type(vc, info); if (CON_IS_VISIBLE(vc)) { var_to_display(p, &info->var, info); cols = FBCON_SWAP(ops->rotate, info->var.xres, info->var.yres); rows = FBCON_SWAP(ops->rotate, info->var.yres, info->var.xres); cols /= vc->vc_font.width; rows /= vc->vc_font.height; vc_resize(vc, cols, rows); updatescrollmode(p, info, vc); scrollback_max = 0; scrollback_current = 0; if (!fbcon_is_inactive(vc, info)) { ops->var.xoffset = ops->var.yoffset = p->yscroll = 0; ops->update_start(info); } fbcon_set_palette(vc, color_table); update_screen(vc); if (softback_buf) fbcon_update_softback(vc); } } static void fbcon_set_all_vcs(struct fb_info *info) { struct fbcon_ops *ops = info->fbcon_par; struct vc_data *vc; struct display *p; int i, rows, cols, fg = -1; if (!ops || ops->currcon < 0) return; for (i = first_fb_vc; i <= last_fb_vc; i++) { vc = vc_cons[i].d; if (!vc || vc->vc_mode != KD_TEXT || registered_fb[con2fb_map[i]] != info) continue; if (CON_IS_VISIBLE(vc)) { fg = i; continue; } p = &fb_display[vc->vc_num]; set_blitting_type(vc, info); var_to_display(p, &info->var, info); cols = FBCON_SWAP(p->rotate, info->var.xres, info->var.yres); rows = FBCON_SWAP(p->rotate, info->var.yres, info->var.xres); cols /= vc->vc_font.width; rows /= vc->vc_font.height; vc_resize(vc, cols, rows); } if (fg != -1) fbcon_modechanged(info); } static int fbcon_mode_deleted(struct fb_info *info, struct fb_videomode *mode) { struct fb_info *fb_info; struct display *p; int i, j, found = 0; /* before deletion, ensure that mode is not in use */ for (i = first_fb_vc; i <= last_fb_vc; i++) { j = con2fb_map[i]; if (j == -1) continue; fb_info = registered_fb[j]; if (fb_info != info) continue; p = &fb_display[i]; if (!p || !p->mode) continue; if (fb_mode_is_equal(p->mode, mode)) { found = 1; break; } } return found; } #ifdef CONFIG_VT_HW_CONSOLE_BINDING static int fbcon_unbind(void) { int ret; ret = unbind_con_driver(&fb_con, first_fb_vc, last_fb_vc, fbcon_is_default); return ret; } #else static inline int fbcon_unbind(void) { return -EINVAL; } #endif /* CONFIG_VT_HW_CONSOLE_BINDING */ static int fbcon_fb_unbind(int idx) { int i, new_idx = -1, ret = 0; for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map[i] != idx && con2fb_map[i] != -1) { new_idx = i; break; } } if (new_idx != -1) { for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map[i] == idx) set_con2fb_map(i, new_idx, 0); } } else ret = fbcon_unbind(); return ret; } static int fbcon_fb_unregistered(struct fb_info *info) { int i, idx = info->node; for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map[i] == idx) con2fb_map[i] = -1; } if (idx == info_idx) { info_idx = -1; for (i = 0; i < FB_MAX; i++) { if (registered_fb[i] != NULL) { info_idx = i; break; } } } if (info_idx != -1) { for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map[i] == -1) con2fb_map[i] = info_idx; } } if (!num_registered_fb) unregister_con_driver(&fb_con); if (primary_device == idx) primary_device = -1; return 0; } #ifdef CONFIG_FRAMEBUFFER_CONSOLE_DETECT_PRIMARY static void fbcon_select_primary(struct fb_info *info) { if (!map_override && primary_device == -1 && fb_is_primary_device(info)) { int i; printk(KERN_INFO "fbcon: %s (fb%i) is primary device\n", info->fix.id, info->node); primary_device = info->node; for (i = first_fb_vc; i <= last_fb_vc; i++) con2fb_map_boot[i] = primary_device; if (con_is_bound(&fb_con)) { printk(KERN_INFO "fbcon: Remapping primary device, " "fb%i, to tty %i-%i\n", info->node, first_fb_vc + 1, last_fb_vc + 1); info_idx = primary_device; } } } #else static inline void fbcon_select_primary(struct fb_info *info) { return; } #endif /* CONFIG_FRAMEBUFFER_DETECT_PRIMARY */ static int fbcon_fb_registered(struct fb_info *info) { int ret = 0, i, idx = info->node; fbcon_select_primary(info); if (info_idx == -1) { for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map_boot[i] == idx) { info_idx = idx; break; } } if (info_idx != -1) ret = fbcon_takeover(1); } else { for (i = first_fb_vc; i <= last_fb_vc; i++) { if (con2fb_map_boot[i] == idx) set_con2fb_map(i, idx, 0); } } return ret; } static void fbcon_fb_blanked(struct fb_info *info, int blank) { struct fbcon_ops *ops = info->fbcon_par; struct vc_data *vc; if (!ops || ops->currcon < 0) return; vc = vc_cons[ops->currcon].d; if (vc->vc_mode != KD_TEXT || registered_fb[con2fb_map[ops->currcon]] != info) return; if (CON_IS_VISIBLE(vc)) { if (blank) do_blank_screen(0); else do_unblank_screen(0); } ops->blank_state = blank; } static void fbcon_new_modelist(struct fb_info *info) { int i; struct vc_data *vc; struct fb_var_screeninfo var; const struct fb_videomode *mode; for (i = first_fb_vc; i <= last_fb_vc; i++) { if (registered_fb[con2fb_map[i]] != info) continue; if (!fb_display[i].mode) continue; vc = vc_cons[i].d; display_to_var(&var, &fb_display[i]); mode = fb_find_nearest_mode(fb_display[i].mode, &info->modelist); fb_videomode_to_var(&var, mode); fbcon_set_disp(info, &var, vc->vc_num); } } static void fbcon_get_requirement(struct fb_info *info, struct fb_blit_caps *caps) { struct vc_data *vc; struct display *p; if (caps->flags) { int i, charcnt; for (i = first_fb_vc; i <= last_fb_vc; i++) { vc = vc_cons[i].d; if (vc && vc->vc_mode == KD_TEXT && info->node == con2fb_map[i]) { p = &fb_display[i]; caps->x |= 1 << (vc->vc_font.width - 1); caps->y |= 1 << (vc->vc_font.height - 1); charcnt = (p->userfont) ? FNTCHARCNT(p->fontdata) : 256; if (caps->len < charcnt) caps->len = charcnt; } } } else { vc = vc_cons[fg_console].d; if (vc && vc->vc_mode == KD_TEXT && info->node == con2fb_map[fg_console]) { p = &fb_display[fg_console]; caps->x = 1 << (vc->vc_font.width - 1); caps->y = 1 << (vc->vc_font.height - 1); caps->len = (p->userfont) ? FNTCHARCNT(p->fontdata) : 256; } } } static int fbcon_event_notify(struct notifier_block *self, unsigned long action, void *data) { struct fb_event *event = data; struct fb_info *info = event->info; struct fb_videomode *mode; struct fb_con2fbmap *con2fb; struct fb_blit_caps *caps; int ret = 0; /* * ignore all events except driver registration and deregistration * if fbcon is not active */ if (fbcon_has_exited && !(action == FB_EVENT_FB_REGISTERED || action == FB_EVENT_FB_UNREGISTERED)) goto done; switch(action) { case FB_EVENT_SUSPEND: fbcon_suspended(info); break; case FB_EVENT_RESUME: fbcon_resumed(info); break; case FB_EVENT_MODE_CHANGE: fbcon_modechanged(info); break; case FB_EVENT_MODE_CHANGE_ALL: fbcon_set_all_vcs(info); break; case FB_EVENT_MODE_DELETE: mode = event->data; ret = fbcon_mode_deleted(info, mode); break; case FB_EVENT_FB_UNBIND: ret = fbcon_fb_unbind(info->node); break; case FB_EVENT_FB_REGISTERED: ret = fbcon_fb_registered(info); break; case FB_EVENT_FB_UNREGISTERED: ret = fbcon_fb_unregistered(info); break; case FB_EVENT_SET_CONSOLE_MAP: con2fb = event->data; ret = set_con2fb_map(con2fb->console - 1, con2fb->framebuffer, 1); break; case FB_EVENT_GET_CONSOLE_MAP: con2fb = event->data; con2fb->framebuffer = con2fb_map[con2fb->console - 1]; break; case FB_EVENT_BLANK: fbcon_fb_blanked(info, *(int *)event->data); break; case FB_EVENT_NEW_MODELIST: fbcon_new_modelist(info); break; case FB_EVENT_GET_REQ: caps = event->data; fbcon_get_requirement(info, caps); break; } done: return ret; } /* * The console `switch' structure for the frame buffer based console */ static const struct consw fb_con = { .owner = THIS_MODULE, .con_startup = fbcon_startup, .con_init = fbcon_init, .con_deinit = fbcon_deinit, .con_clear = fbcon_clear, .con_putc = fbcon_putc, .con_putcs = fbcon_putcs, .con_cursor = fbcon_cursor, .con_scroll = fbcon_scroll, .con_bmove = fbcon_bmove, .con_switch = fbcon_switch, .con_blank = fbcon_blank, .con_font_set = fbcon_set_font, .con_font_get = fbcon_get_font, .con_font_default = fbcon_set_def_font, .con_font_copy = fbcon_copy_font, .con_set_palette = fbcon_set_palette, .con_scrolldelta = fbcon_scrolldelta, .con_set_origin = fbcon_set_origin, .con_invert_region = fbcon_invert_region, .con_screen_pos = fbcon_screen_pos, .con_getxy = fbcon_getxy, .con_resize = fbcon_resize, }; static struct notifier_block fbcon_event_notifier = { .notifier_call = fbcon_event_notify, }; static ssize_t store_rotate(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { struct fb_info *info; int rotate, idx; char **last = NULL; if (fbcon_has_exited) return count; acquire_console_sem(); idx = con2fb_map[fg_console]; if (idx == -1 || registered_fb[idx] == NULL) goto err; info = registered_fb[idx]; rotate = simple_strtoul(buf, last, 0); fbcon_rotate(info, rotate); err: release_console_sem(); return count; } static ssize_t store_rotate_all(struct device *device, struct device_attribute *attr,const char *buf, size_t count) { struct fb_info *info; int rotate, idx; char **last = NULL; if (fbcon_has_exited) return count; acquire_console_sem(); idx = con2fb_map[fg_console]; if (idx == -1 || registered_fb[idx] == NULL) goto err; info = registered_fb[idx]; rotate = simple_strtoul(buf, last, 0); fbcon_rotate_all(info, rotate); err: release_console_sem(); return count; } static ssize_t show_rotate(struct device *device, struct device_attribute *attr,char *buf) { struct fb_info *info; int rotate = 0, idx; if (fbcon_has_exited) return 0; acquire_console_sem(); idx = con2fb_map[fg_console]; if (idx == -1 || registered_fb[idx] == NULL) goto err; info = registered_fb[idx]; rotate = fbcon_get_rotate(info); err: release_console_sem(); return snprintf(buf, PAGE_SIZE, "%d\n", rotate); } static ssize_t show_cursor_blink(struct device *device, struct device_attribute *attr, char *buf) { struct fb_info *info; struct fbcon_ops *ops; int idx, blink = -1; if (fbcon_has_exited) return 0; acquire_console_sem(); idx = con2fb_map[fg_console]; if (idx == -1 || registered_fb[idx] == NULL) goto err; info = registered_fb[idx]; ops = info->fbcon_par; if (!ops) goto err; blink = (ops->flags & FBCON_FLAGS_CURSOR_TIMER) ? 1 : 0; err: release_console_sem(); return snprintf(buf, PAGE_SIZE, "%d\n", blink); } static ssize_t store_cursor_blink(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { struct fb_info *info; int blink, idx; char **last = NULL; if (fbcon_has_exited) return count; acquire_console_sem(); idx = con2fb_map[fg_console]; if (idx == -1 || registered_fb[idx] == NULL) goto err; info = registered_fb[idx]; if (!info->fbcon_par) goto err; blink = simple_strtoul(buf, last, 0); if (blink) { fbcon_cursor_noblink = 0; fbcon_add_cursor_timer(info); } else { fbcon_cursor_noblink = 1; fbcon_del_cursor_timer(info); } err: release_console_sem(); return count; } static struct device_attribute device_attrs[] = { __ATTR(rotate, S_IRUGO|S_IWUSR, show_rotate, store_rotate), __ATTR(rotate_all, S_IWUSR, NULL, store_rotate_all), __ATTR(cursor_blink, S_IRUGO|S_IWUSR, show_cursor_blink, store_cursor_blink), }; static int fbcon_init_device(void) { int i, error = 0; fbcon_has_sysfs = 1; for (i = 0; i < ARRAY_SIZE(device_attrs); i++) { error = device_create_file(fbcon_device, &device_attrs[i]); if (error) break; } if (error) { while (--i >= 0) device_remove_file(fbcon_device, &device_attrs[i]); fbcon_has_sysfs = 0; } return 0; } static void fbcon_start(void) { if (num_registered_fb) { int i; acquire_console_sem(); for (i = 0; i < FB_MAX; i++) { if (registered_fb[i] != NULL) { info_idx = i; break; } } release_console_sem(); fbcon_takeover(0); } } static void fbcon_exit(void) { struct fb_info *info; int i, j, mapped; if (fbcon_has_exited) return; #ifdef CONFIG_ATARI free_irq(IRQ_AUTO_4, fb_vbl_handler); #endif #ifdef CONFIG_MAC if (MACH_IS_MAC && vbl_detected) free_irq(IRQ_MAC_VBL, fb_vbl_handler); #endif kfree((void *)softback_buf); softback_buf = 0UL; for (i = 0; i < FB_MAX; i++) { mapped = 0; info = registered_fb[i]; if (info == NULL) continue; for (j = first_fb_vc; j <= last_fb_vc; j++) { if (con2fb_map[j] == i) mapped = 1; } if (mapped) { if (info->fbops->fb_release) info->fbops->fb_release(info, 0); module_put(info->fbops->owner); if (info->fbcon_par) { struct fbcon_ops *ops = info->fbcon_par; fbcon_del_cursor_timer(info); kfree(ops->cursor_src); kfree(info->fbcon_par); info->fbcon_par = NULL; } if (info->queue.func == fb_flashcursor) info->queue.func = NULL; } } fbcon_has_exited = 1; } static int __init fb_console_init(void) { int i; acquire_console_sem(); fb_register_client(&fbcon_event_notifier); fbcon_device = device_create(fb_class, NULL, MKDEV(0, 0), "fbcon"); if (IS_ERR(fbcon_device)) { printk(KERN_WARNING "Unable to create device " "for fbcon; errno = %ld\n", PTR_ERR(fbcon_device)); fbcon_device = NULL; } else fbcon_init_device(); for (i = 0; i < MAX_NR_CONSOLES; i++) con2fb_map[i] = -1; release_console_sem(); fbcon_start(); return 0; } module_init(fb_console_init); #ifdef MODULE static void __exit fbcon_deinit_device(void) { int i; if (fbcon_has_sysfs) { for (i = 0; i < ARRAY_SIZE(device_attrs); i++) device_remove_file(fbcon_device, &device_attrs[i]); fbcon_has_sysfs = 0; } } static void __exit fb_console_exit(void) { acquire_console_sem(); fb_unregister_client(&fbcon_event_notifier); fbcon_deinit_device(); device_destroy(fb_class, MKDEV(0, 0)); fbcon_exit(); release_console_sem(); unregister_con_driver(&fb_con); } module_exit(fb_console_exit); #endif MODULE_LICENSE("GPL");
janrinze/loox7xxport
drivers/video/console/fbcon.c
C
gpl-2.0
89,478
#include "cache.h" #include "submodule-config.h" #include "submodule.h" #include "strbuf.h" /* * submodule cache lookup structure * There is one shared set of 'struct submodule' entries which can be * looked up by their sha1 blob id of the .gitmodule file and either * using path or name as key. * for_path stores submodule entries with path as key * for_name stores submodule entries with name as key */ struct submodule_cache { struct hashmap for_path; struct hashmap for_name; }; /* * thin wrapper struct needed to insert 'struct submodule' entries to * the hashmap */ struct submodule_entry { struct hashmap_entry ent; struct submodule *config; }; enum lookup_type { lookup_name, lookup_path }; static struct submodule_cache the_submodule_cache; static int is_cache_init; static int config_path_cmp(const struct submodule_entry *a, const struct submodule_entry *b, const void *unused) { return strcmp(a->config->path, b->config->path) || hashcmp(a->config->gitmodules_sha1, b->config->gitmodules_sha1); } static int config_name_cmp(const struct submodule_entry *a, const struct submodule_entry *b, const void *unused) { return strcmp(a->config->name, b->config->name) || hashcmp(a->config->gitmodules_sha1, b->config->gitmodules_sha1); } static void cache_init(struct submodule_cache *cache) { hashmap_init(&cache->for_path, (hashmap_cmp_fn) config_path_cmp, 0); hashmap_init(&cache->for_name, (hashmap_cmp_fn) config_name_cmp, 0); } static void free_one_config(struct submodule_entry *entry) { free((void *) entry->config->path); free((void *) entry->config->name); free((void *) entry->config->branch); free((void *) entry->config->update_strategy.command); free(entry->config); } static void cache_free(struct submodule_cache *cache) { struct hashmap_iter iter; struct submodule_entry *entry; /* * We iterate over the name hash here to be symmetric with the * allocation of struct submodule entries. Each is allocated by * their .gitmodule blob sha1 and submodule name. */ hashmap_iter_init(&cache->for_name, &iter); while ((entry = hashmap_iter_next(&iter))) free_one_config(entry); hashmap_free(&cache->for_path, 1); hashmap_free(&cache->for_name, 1); } static unsigned int hash_sha1_string(const unsigned char *sha1, const char *string) { return memhash(sha1, 20) + strhash(string); } static void cache_put_path(struct submodule_cache *cache, struct submodule *submodule) { unsigned int hash = hash_sha1_string(submodule->gitmodules_sha1, submodule->path); struct submodule_entry *e = xmalloc(sizeof(*e)); hashmap_entry_init(e, hash); e->config = submodule; hashmap_put(&cache->for_path, e); } static void cache_remove_path(struct submodule_cache *cache, struct submodule *submodule) { unsigned int hash = hash_sha1_string(submodule->gitmodules_sha1, submodule->path); struct submodule_entry e; struct submodule_entry *removed; hashmap_entry_init(&e, hash); e.config = submodule; removed = hashmap_remove(&cache->for_path, &e, NULL); free(removed); } static void cache_add(struct submodule_cache *cache, struct submodule *submodule) { unsigned int hash = hash_sha1_string(submodule->gitmodules_sha1, submodule->name); struct submodule_entry *e = xmalloc(sizeof(*e)); hashmap_entry_init(e, hash); e->config = submodule; hashmap_add(&cache->for_name, e); } static const struct submodule *cache_lookup_path(struct submodule_cache *cache, const unsigned char *gitmodules_sha1, const char *path) { struct submodule_entry *entry; unsigned int hash = hash_sha1_string(gitmodules_sha1, path); struct submodule_entry key; struct submodule key_config; hashcpy(key_config.gitmodules_sha1, gitmodules_sha1); key_config.path = path; hashmap_entry_init(&key, hash); key.config = &key_config; entry = hashmap_get(&cache->for_path, &key, NULL); if (entry) return entry->config; return NULL; } static struct submodule *cache_lookup_name(struct submodule_cache *cache, const unsigned char *gitmodules_sha1, const char *name) { struct submodule_entry *entry; unsigned int hash = hash_sha1_string(gitmodules_sha1, name); struct submodule_entry key; struct submodule key_config; hashcpy(key_config.gitmodules_sha1, gitmodules_sha1); key_config.name = name; hashmap_entry_init(&key, hash); key.config = &key_config; entry = hashmap_get(&cache->for_name, &key, NULL); if (entry) return entry->config; return NULL; } static int name_and_item_from_var(const char *var, struct strbuf *name, struct strbuf *item) { const char *subsection, *key; int subsection_len, parse; parse = parse_config_key(var, "submodule", &subsection, &subsection_len, &key); if (parse < 0 || !subsection) return 0; strbuf_add(name, subsection, subsection_len); strbuf_addstr(item, key); return 1; } static struct submodule *lookup_or_create_by_name(struct submodule_cache *cache, const unsigned char *gitmodules_sha1, const char *name) { struct submodule *submodule; struct strbuf name_buf = STRBUF_INIT; submodule = cache_lookup_name(cache, gitmodules_sha1, name); if (submodule) return submodule; submodule = xmalloc(sizeof(*submodule)); strbuf_addstr(&name_buf, name); submodule->name = strbuf_detach(&name_buf, NULL); submodule->path = NULL; submodule->url = NULL; submodule->update_strategy.type = SM_UPDATE_UNSPECIFIED; submodule->update_strategy.command = NULL; submodule->fetch_recurse = RECURSE_SUBMODULES_NONE; submodule->ignore = NULL; submodule->branch = NULL; submodule->recommend_shallow = -1; hashcpy(submodule->gitmodules_sha1, gitmodules_sha1); cache_add(cache, submodule); return submodule; } static int parse_fetch_recurse(const char *opt, const char *arg, int die_on_error) { switch (git_config_maybe_bool(opt, arg)) { case 1: return RECURSE_SUBMODULES_ON; case 0: return RECURSE_SUBMODULES_OFF; default: if (!strcmp(arg, "on-demand")) return RECURSE_SUBMODULES_ON_DEMAND; if (die_on_error) die("bad %s argument: %s", opt, arg); else return RECURSE_SUBMODULES_ERROR; } } int parse_fetch_recurse_submodules_arg(const char *opt, const char *arg) { return parse_fetch_recurse(opt, arg, 1); } static int parse_push_recurse(const char *opt, const char *arg, int die_on_error) { switch (git_config_maybe_bool(opt, arg)) { case 1: /* There's no simple "on" value when pushing */ if (die_on_error) die("bad %s argument: %s", opt, arg); else return RECURSE_SUBMODULES_ERROR; case 0: return RECURSE_SUBMODULES_OFF; default: if (!strcmp(arg, "on-demand")) return RECURSE_SUBMODULES_ON_DEMAND; else if (!strcmp(arg, "check")) return RECURSE_SUBMODULES_CHECK; else if (die_on_error) die("bad %s argument: %s", opt, arg); else return RECURSE_SUBMODULES_ERROR; } } int parse_push_recurse_submodules_arg(const char *opt, const char *arg) { return parse_push_recurse(opt, arg, 1); } static void warn_multiple_config(const unsigned char *commit_sha1, const char *name, const char *option) { const char *commit_string = "WORKTREE"; if (commit_sha1) commit_string = sha1_to_hex(commit_sha1); warning("%s:.gitmodules, multiple configurations found for " "'submodule.%s.%s'. Skipping second one!", commit_string, name, option); } struct parse_config_parameter { struct submodule_cache *cache; const unsigned char *commit_sha1; const unsigned char *gitmodules_sha1; int overwrite; }; static int parse_config(const char *var, const char *value, void *data) { struct parse_config_parameter *me = data; struct submodule *submodule; struct strbuf name = STRBUF_INIT, item = STRBUF_INIT; int ret = 0; /* this also ensures that we only parse submodule entries */ if (!name_and_item_from_var(var, &name, &item)) return 0; submodule = lookup_or_create_by_name(me->cache, me->gitmodules_sha1, name.buf); if (!strcmp(item.buf, "path")) { if (!value) ret = config_error_nonbool(var); else if (!me->overwrite && submodule->path) warn_multiple_config(me->commit_sha1, submodule->name, "path"); else { if (submodule->path) cache_remove_path(me->cache, submodule); free((void *) submodule->path); submodule->path = xstrdup(value); cache_put_path(me->cache, submodule); } } else if (!strcmp(item.buf, "fetchrecursesubmodules")) { /* when parsing worktree configurations we can die early */ int die_on_error = is_null_sha1(me->gitmodules_sha1); if (!me->overwrite && submodule->fetch_recurse != RECURSE_SUBMODULES_NONE) warn_multiple_config(me->commit_sha1, submodule->name, "fetchrecursesubmodules"); else submodule->fetch_recurse = parse_fetch_recurse( var, value, die_on_error); } else if (!strcmp(item.buf, "ignore")) { if (!value) ret = config_error_nonbool(var); else if (!me->overwrite && submodule->ignore) warn_multiple_config(me->commit_sha1, submodule->name, "ignore"); else if (strcmp(value, "untracked") && strcmp(value, "dirty") && strcmp(value, "all") && strcmp(value, "none")) warning("Invalid parameter '%s' for config option " "'submodule.%s.ignore'", value, var); else { free((void *) submodule->ignore); submodule->ignore = xstrdup(value); } } else if (!strcmp(item.buf, "url")) { if (!value) { ret = config_error_nonbool(var); } else if (!me->overwrite && submodule->url) { warn_multiple_config(me->commit_sha1, submodule->name, "url"); } else { free((void *) submodule->url); submodule->url = xstrdup(value); } } else if (!strcmp(item.buf, "update")) { if (!value) ret = config_error_nonbool(var); else if (!me->overwrite && submodule->update_strategy.type != SM_UPDATE_UNSPECIFIED) warn_multiple_config(me->commit_sha1, submodule->name, "update"); else if (parse_submodule_update_strategy(value, &submodule->update_strategy) < 0) die(_("invalid value for %s"), var); } else if (!strcmp(item.buf, "shallow")) { if (!me->overwrite && submodule->recommend_shallow != -1) warn_multiple_config(me->commit_sha1, submodule->name, "shallow"); else submodule->recommend_shallow = git_config_bool(var, value); } else if (!strcmp(item.buf, "branch")) { if (!me->overwrite && submodule->branch) warn_multiple_config(me->commit_sha1, submodule->name, "branch"); else { free((void *)submodule->branch); submodule->branch = xstrdup(value); } } strbuf_release(&name); strbuf_release(&item); return ret; } static int gitmodule_sha1_from_commit(const unsigned char *commit_sha1, unsigned char *gitmodules_sha1, struct strbuf *rev) { int ret = 0; if (is_null_sha1(commit_sha1)) { hashclr(gitmodules_sha1); return 1; } strbuf_addf(rev, "%s:.gitmodules", sha1_to_hex(commit_sha1)); if (get_sha1(rev->buf, gitmodules_sha1) >= 0) ret = 1; return ret; } /* This does a lookup of a submodule configuration by name or by path * (key) with on-demand reading of the appropriate .gitmodules from * revisions. */ static const struct submodule *config_from(struct submodule_cache *cache, const unsigned char *commit_sha1, const char *key, enum lookup_type lookup_type) { struct strbuf rev = STRBUF_INIT; unsigned long config_size; char *config = NULL; unsigned char sha1[20]; enum object_type type; const struct submodule *submodule = NULL; struct parse_config_parameter parameter; /* * If any parameter except the cache is a NULL pointer just * return the first submodule. Can be used to check whether * there are any submodules parsed. */ if (!commit_sha1 || !key) { struct hashmap_iter iter; struct submodule_entry *entry; entry = hashmap_iter_first(&cache->for_name, &iter); if (!entry) return NULL; return entry->config; } if (!gitmodule_sha1_from_commit(commit_sha1, sha1, &rev)) goto out; switch (lookup_type) { case lookup_name: submodule = cache_lookup_name(cache, sha1, key); break; case lookup_path: submodule = cache_lookup_path(cache, sha1, key); break; } if (submodule) goto out; config = read_sha1_file(sha1, &type, &config_size); if (!config || type != OBJ_BLOB) goto out; /* fill the submodule config into the cache */ parameter.cache = cache; parameter.commit_sha1 = commit_sha1; parameter.gitmodules_sha1 = sha1; parameter.overwrite = 0; git_config_from_mem(parse_config, CONFIG_ORIGIN_SUBMODULE_BLOB, rev.buf, config, config_size, &parameter); strbuf_release(&rev); free(config); switch (lookup_type) { case lookup_name: return cache_lookup_name(cache, sha1, key); case lookup_path: return cache_lookup_path(cache, sha1, key); default: return NULL; } out: strbuf_release(&rev); free(config); return submodule; } static const struct submodule *config_from_path(struct submodule_cache *cache, const unsigned char *commit_sha1, const char *path) { return config_from(cache, commit_sha1, path, lookup_path); } static const struct submodule *config_from_name(struct submodule_cache *cache, const unsigned char *commit_sha1, const char *name) { return config_from(cache, commit_sha1, name, lookup_name); } static void ensure_cache_init(void) { if (is_cache_init) return; cache_init(&the_submodule_cache); is_cache_init = 1; } int parse_submodule_config_option(const char *var, const char *value) { struct parse_config_parameter parameter; parameter.cache = &the_submodule_cache; parameter.commit_sha1 = NULL; parameter.gitmodules_sha1 = null_sha1; parameter.overwrite = 1; ensure_cache_init(); return parse_config(var, value, &parameter); } const struct submodule *submodule_from_name(const unsigned char *commit_sha1, const char *name) { ensure_cache_init(); return config_from_name(&the_submodule_cache, commit_sha1, name); } const struct submodule *submodule_from_path(const unsigned char *commit_sha1, const char *path) { ensure_cache_init(); return config_from_path(&the_submodule_cache, commit_sha1, path); } void submodule_free(void) { cache_free(&the_submodule_cache); is_cache_init = 0; }
johnkeeping/git
submodule-config.c
C
gpl-2.0
14,166
ALTER TABLE character_db_version CHANGE COLUMN required_13977_01_characters_taxi_system_format_update required_13991_01_characters_skills_cleanup_1829 bit; DELETE a FROM character_skills AS a WHERE skill IN (760) AND guid IN (SELECT guid FROM characters b WHERE race IN (5) AND a.guid=b.guid);
spkansas/mangos-wotlk
sql/updates/characters/13991_01_characters_skills_cleanup_1829.sql
SQL
gpl-2.0
295
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TASK_SEQUENCE_MANAGER_SEQUENCE_MANAGER_IMPL_H_ #define BASE_TASK_SEQUENCE_MANAGER_SEQUENCE_MANAGER_IMPL_H_ #include <list> #include <map> #include <memory> #include <random> #include <set> #include <unordered_map> #include <utility> #include <vector> #include "base/atomic_sequence_num.h" #include "base/cancelable_callback.h" #include "base/containers/circular_deque.h" #include "base/debug/crash_logging.h" #include "base/macros.h" #include "base/memory/scoped_refptr.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop_current.h" #include "base/message_loop/message_pump_type.h" #include "base/pending_task.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" #include "base/task/common/task_annotator.h" #include "base/task/sequence_manager/associated_thread_id.h" #include "base/task/sequence_manager/enqueue_order.h" #include "base/task/sequence_manager/enqueue_order_generator.h" #include "base/task/sequence_manager/sequence_manager.h" #include "base/task/sequence_manager/task_queue_impl.h" #include "base/task/sequence_manager/task_queue_selector.h" #include "base/task/sequence_manager/thread_controller.h" #include "base/threading/thread_checker.h" #include "base/time/default_tick_clock.h" #include "build/build_config.h" namespace base { namespace trace_event { class ConvertableToTraceFormat; } // namespace trace_event namespace sequence_manager { class SequenceManagerForTest; class TaskQueue; class TaskTimeObserver; class TimeDomain; namespace internal { class RealTimeDomain; class TaskQueueImpl; class ThreadControllerImpl; // The task queue manager provides N task queues and a selector interface for // choosing which task queue to service next. Each task queue consists of two // sub queues: // // 1. Incoming task queue. Tasks that are posted get immediately appended here. // When a task is appended into an empty incoming queue, the task manager // work function (DoWork()) is scheduled to run on the main task runner. // // 2. Work queue. If a work queue is empty when DoWork() is entered, tasks from // the incoming task queue (if any) are moved here. The work queues are // registered with the selector as input to the scheduling decision. // class BASE_EXPORT SequenceManagerImpl : public SequenceManager, public internal::SequencedTaskSource, public internal::TaskQueueSelector::Observer, public RunLoop::NestingObserver { public: using Observer = SequenceManager::Observer; ~SequenceManagerImpl() override; // Assume direct control over current thread and create a SequenceManager. // This function should be called only once per thread. // This function assumes that a MessageLoop is initialized for // the current thread. static std::unique_ptr<SequenceManagerImpl> CreateOnCurrentThread( SequenceManager::Settings settings = SequenceManager::Settings()); // Create an unbound SequenceManager (typically for a future thread). The // SequenceManager can be initialized on the current thread and then needs to // be bound and initialized on the target thread by calling one of the Bind*() // methods. static std::unique_ptr<SequenceManagerImpl> CreateUnbound( SequenceManager::Settings settings); // SequenceManager implementation: void BindToCurrentThread() override; scoped_refptr<SequencedTaskRunner> GetTaskRunnerForCurrentTask() override; void BindToMessagePump(std::unique_ptr<MessagePump> message_pump) override; void SetObserver(Observer* observer) override; void AddTaskTimeObserver(TaskTimeObserver* task_time_observer) override; void RemoveTaskTimeObserver(TaskTimeObserver* task_time_observer) override; void RegisterTimeDomain(TimeDomain* time_domain) override; void UnregisterTimeDomain(TimeDomain* time_domain) override; TimeDomain* GetRealTimeDomain() const override; const TickClock* GetTickClock() const override; TimeTicks NowTicks() const override; void SetDefaultTaskRunner( scoped_refptr<SingleThreadTaskRunner> task_runner) override; void ReclaimMemory() override; bool GetAndClearSystemIsQuiescentBit() override; void SetWorkBatchSize(int work_batch_size) override; void SetTimerSlack(TimerSlack timer_slack) override; void EnableCrashKeys(const char* async_stack_crash_key) override; const MetricRecordingSettings& GetMetricRecordingSettings() const override; size_t GetPendingTaskCountForTesting() const override; scoped_refptr<TaskQueue> CreateTaskQueue( const TaskQueue::Spec& spec) override; std::string DescribeAllPendingTasks() const override; std::unique_ptr<NativeWorkHandle> OnNativeWorkPending( TaskQueue::QueuePriority priority) override; void AddTaskObserver(TaskObserver* task_observer) override; void RemoveTaskObserver(TaskObserver* task_observer) override; // SequencedTaskSource implementation: Task* SelectNextTask() override; void DidRunTask() override; TimeDelta DelayTillNextTask(LazyNow* lazy_now) const override; bool HasPendingHighResolutionTasks() override; bool OnSystemIdle() override; void AddDestructionObserver( MessageLoopCurrent::DestructionObserver* destruction_observer); void RemoveDestructionObserver( MessageLoopCurrent::DestructionObserver* destruction_observer); // TODO(alexclarke): Remove this as part of https://crbug.com/825327. void SetTaskRunner(scoped_refptr<SingleThreadTaskRunner> task_runner); // TODO(alexclarke): Remove this as part of https://crbug.com/825327. scoped_refptr<SingleThreadTaskRunner> GetTaskRunner(); bool IsBoundToCurrentThread() const; MessagePump* GetMessagePump() const; bool IsType(MessagePumpType type) const; void SetAddQueueTimeToTasks(bool enable); void SetTaskExecutionAllowed(bool allowed); bool IsTaskExecutionAllowed() const; #if defined(OS_IOS) void AttachToMessagePump(); #endif bool IsIdleForTesting() override; void BindToCurrentThread(std::unique_ptr<MessagePump> pump); void DeletePendingTasks(); bool HasTasks(); MessagePumpType GetType() const; // Requests that a task to process work is scheduled. void ScheduleWork(); // Requests that a delayed task to process work is posted on the main task // runner. These delayed tasks are de-duplicated. Must be called on the thread // this class was created on. // Schedules next wake-up at the given time, cancels any previous requests. // Use TimeTicks::Max() to cancel a wake-up. // Must be called from a TimeDomain only. void SetNextDelayedDoWork(LazyNow* lazy_now, TimeTicks run_time); // Returns the currently executing TaskQueue if any. Must be called on the // thread this class was created on. internal::TaskQueueImpl* currently_executing_task_queue() const; // Unregisters a TaskQueue previously created by |NewTaskQueue()|. // No tasks will run on this queue after this call. void UnregisterTaskQueueImpl( std::unique_ptr<internal::TaskQueueImpl> task_queue); // Schedule a call to UnregisterTaskQueueImpl as soon as it's safe to do so. void ShutdownTaskQueueGracefully( std::unique_ptr<internal::TaskQueueImpl> task_queue); const scoped_refptr<AssociatedThreadId>& associated_thread() const { return associated_thread_; } const Settings& settings() const { return settings_; } WeakPtr<SequenceManagerImpl> GetWeakPtr(); // How frequently to perform housekeeping tasks (sweeping canceled tasks etc). static constexpr TimeDelta kReclaimMemoryInterval = TimeDelta::FromSeconds(30); protected: static std::unique_ptr<ThreadControllerImpl> CreateThreadControllerImplForCurrentThread(const TickClock* clock); // Create a task queue manager where |controller| controls the thread // on which the tasks are eventually run. SequenceManagerImpl(std::unique_ptr<internal::ThreadController> controller, SequenceManager::Settings settings = Settings()); friend class internal::TaskQueueImpl; friend class ::base::sequence_manager::SequenceManagerForTest; private: class NativeWorkHandleImpl; // Returns the SequenceManager running the // current thread. It must only be used on the thread it was obtained. // Only to be used by MessageLoopCurrent for the moment static SequenceManagerImpl* GetCurrent(); friend class ::base::MessageLoopCurrent; enum class ProcessTaskResult { kDeferred, kExecuted, kSequenceManagerDeleted, }; // SequenceManager maintains a queue of non-nestable tasks since they're // uncommon and allocating an extra deque per TaskQueue will waste the memory. using NonNestableTaskDeque = circular_deque<internal::TaskQueueImpl::DeferredNonNestableTask>; // We have to track rentrancy because we support nested runloops but the // selector interface is unaware of those. This struct keeps track off all // task related state needed to make pairs of SelectNextTask() / DidRunTask() // work. struct ExecutingTask { ExecutingTask(Task&& task, internal::TaskQueueImpl* task_queue, TaskQueue::TaskTiming task_timing) : pending_task(std::move(task)), task_queue(task_queue), task_queue_name(task_queue->GetName()), task_timing(task_timing), priority(task_queue->GetQueuePriority()), task_type(pending_task.task_type) {} Task pending_task; internal::TaskQueueImpl* task_queue = nullptr; // Save task_queue_name as the task queue can be deleted within the task. const char* task_queue_name; TaskQueue::TaskTiming task_timing; // Save priority as it might change after running a task. TaskQueue::QueuePriority priority; // Save task metadata to use in after running a task as |pending_task| // won't be available then. int task_type; }; struct MainThreadOnly { explicit MainThreadOnly( const scoped_refptr<AssociatedThreadId>& associated_thread, const SequenceManager::Settings& settings); ~MainThreadOnly(); int nesting_depth = 0; NonNestableTaskDeque non_nestable_task_queue; // TODO(altimin): Switch to instruction pointer crash key when it's // available. debug::CrashKeyString* file_name_crash_key = nullptr; debug::CrashKeyString* function_name_crash_key = nullptr; debug::CrashKeyString* async_stack_crash_key = nullptr; std::array<char, static_cast<size_t>(debug::CrashKeySize::Size64)> async_stack_buffer = {}; std::mt19937_64 random_generator; std::uniform_real_distribution<double> uniform_distribution; internal::TaskQueueSelector selector; ObserverList<TaskObserver>::Unchecked task_observers; ObserverList<TaskTimeObserver>::Unchecked task_time_observers; std::set<TimeDomain*> time_domains; std::unique_ptr<internal::RealTimeDomain> real_time_domain; // If true MaybeReclaimMemory will attempt to reclaim memory. bool memory_reclaim_scheduled = false; // Used to ensure we don't perform expensive housekeeping too frequently. TimeTicks next_time_to_reclaim_memory; // List of task queues managed by this SequenceManager. // - active_queues contains queues that are still running tasks. // Most often they are owned by relevant TaskQueues, but // queues_to_gracefully_shutdown_ are included here too. // - queues_to_gracefully_shutdown contains queues which should be deleted // when they become empty. // - queues_to_delete contains soon-to-be-deleted queues, because some // internal scheduling code does not expect queues to be pulled // from underneath. std::set<internal::TaskQueueImpl*> active_queues; std::map<internal::TaskQueueImpl*, std::unique_ptr<internal::TaskQueueImpl>> queues_to_gracefully_shutdown; std::map<internal::TaskQueueImpl*, std::unique_ptr<internal::TaskQueueImpl>> queues_to_delete; bool task_was_run_on_quiescence_monitored_queue = false; bool nesting_observer_registered_ = false; // Due to nested runloops more than one task can be executing concurrently. std::vector<ExecutingTask> task_execution_stack; Observer* observer = nullptr; // NOT OWNED ObserverList<MessageLoopCurrent::DestructionObserver>::Unchecked destruction_observers; // By default native work is not prioritized at all. std::multiset<TaskQueue::QueuePriority> pending_native_work{ TaskQueue::kBestEffortPriority}; }; void CompleteInitializationOnBoundThread(); // TaskQueueSelector::Observer: void OnTaskQueueEnabled(internal::TaskQueueImpl* queue) override; // RunLoop::NestingObserver: void OnBeginNestedRunLoop() override; void OnExitNestedRunLoop() override; // Called by the task queue to inform this SequenceManager of a task that's // about to be queued. This SequenceManager may use this opportunity to add // metadata to |pending_task| before it is moved into the queue. void WillQueueTask(Task* pending_task, const char* task_queue_name); // Delayed Tasks with run_times <= Now() are enqueued onto the work queue and // reloads any empty work queues. void MoveReadyDelayedTasksToWorkQueues(LazyNow* lazy_now); void NotifyWillProcessTask(ExecutingTask* task, LazyNow* time_before_task); void NotifyDidProcessTask(ExecutingTask* task, LazyNow* time_after_task); EnqueueOrder GetNextSequenceNumber(); bool GetAddQueueTimeToTasks(); std::unique_ptr<trace_event::ConvertableToTraceFormat> AsValueWithSelectorResult(internal::WorkQueue* selected_work_queue, bool force_verbose) const; void AsValueWithSelectorResultInto(trace_event::TracedValue*, internal::WorkQueue* selected_work_queue, bool force_verbose) const; // Used in construction of TaskQueueImpl to obtain an AtomicFlag which it can // use to request reload by ReloadEmptyWorkQueues. The lifetime of // TaskQueueImpl is managed by this class and the handle will be released by // TaskQueueImpl::UnregisterTaskQueue which is always called before the // queue's destruction. AtomicFlagSet::AtomicFlag GetFlagToRequestReloadForEmptyQueue( TaskQueueImpl* task_queue); // Calls |TakeImmediateIncomingQueueTasks| on all queues with their reload // flag set in |empty_queues_to_reload_|. void ReloadEmptyWorkQueues() const; std::unique_ptr<internal::TaskQueueImpl> CreateTaskQueueImpl( const TaskQueue::Spec& spec) override; // Periodically reclaims memory by sweeping away canceled tasks and shrinking // buffers. void MaybeReclaimMemory(); // Deletes queues marked for deletion and empty queues marked for shutdown. void CleanUpQueues(); void RemoveAllCanceledTasksFromFrontOfWorkQueues(); TaskQueue::TaskTiming::TimeRecordingPolicy ShouldRecordTaskTiming( const internal::TaskQueueImpl* task_queue); bool ShouldRecordCPUTimeForTask(); void RecordCrashKeys(const PendingTask&); // Helper to terminate all scoped trace events to allow starting new ones // in SelectNextTask(). Task* SelectNextTaskImpl(); // Check if a task of priority |priority| should run given the pending set of // native work. bool ShouldRunTaskOfPriority(TaskQueue::QueuePriority priority) const; // Ignores any immediate work. TimeDelta GetDelayTillNextDelayedTask(LazyNow* lazy_now) const; #if DCHECK_IS_ON() void LogTaskDebugInfo(const internal::WorkQueue* work_queue) const; #endif // Determines if wall time or thread time should be recorded for the next // task. TaskQueue::TaskTiming InitializeTaskTiming( internal::TaskQueueImpl* task_queue); scoped_refptr<AssociatedThreadId> associated_thread_; EnqueueOrderGenerator enqueue_order_generator_; const std::unique_ptr<internal::ThreadController> controller_; const Settings settings_; const MetricRecordingSettings metric_recording_settings_; // Whether to add the queue time to tasks. base::subtle::Atomic32 add_queue_time_to_tasks_; AtomicFlagSet empty_queues_to_reload_; // A check to bail out early during memory corruption. // https://crbug.com/757940 bool Validate(); volatile int32_t memory_corruption_sentinel_; MainThreadOnly main_thread_only_; MainThreadOnly& main_thread_only() { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); return main_thread_only_; } const MainThreadOnly& main_thread_only() const { DCHECK_CALLED_ON_VALID_THREAD(associated_thread_->thread_checker); return main_thread_only_; } WeakPtrFactory<SequenceManagerImpl> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SequenceManagerImpl); }; } // namespace internal } // namespace sequence_manager } // namespace base #endif // BASE_TASK_SEQUENCE_MANAGER_SEQUENCE_MANAGER_IMPL_H_
Telegram-FOSS-Team/Telegram-FOSS
TMessagesProj/jni/voip/webrtc/base/task/sequence_manager/sequence_manager_impl.h
C
gpl-2.0
17,079
/* Copyright 2005-2013 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks 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. Threading Building Blocks is distributed in the hope that 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #include <stdlib.h> #include <stdio.h> #include <stdexcept> #if _WIN32 #include <io.h> #ifndef F_OK #define F_OK 0 #endif #define access _access #else #include <unistd.h> #endif const long INPUT_SIZE = 1000000; //! Generates sample input for square.cpp void gen_input( const char *fname ) { long num = INPUT_SIZE; FILE *fptr = fopen(fname, "w"); if(!fptr) { throw std::runtime_error("Could not open file for generating input"); } int a=0; int b=1; for( long j=0; j<num; ++j ) { fprintf(fptr, "%u\n",a); b+=a; a=(b-a)%10000; if (a<0) a=-a; } if(fptr) { fclose(fptr); } } void generate_if_needed( const char *fname ) { if ( access(fname, F_OK) != 0 ) gen_input(fname); }
rajkosto/deps-tbb
examples/pipeline/square/gen_input.cpp
C++
gpl-2.0
2,159
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.6"/> <title>CORE POS - Fannie: ObfWeekEntryPage Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); } }); </script> <link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - Fannie"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">CORE POS - Fannie </div> <div id="projectbrief">The CORE POS back end</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.6 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <div class="left"> <form id="FSearchBox" action="search.php" method="get"> <img id="MSearchSelect" src="search/mag.png" alt=""/> <input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)"/> </form> </div><div class="right"></div> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pub-attribs">Public Attributes</a> &#124; <a href="#pro-attribs">Protected Attributes</a> &#124; <a href="class_obf_week_entry_page-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">ObfWeekEntryPage Class Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for ObfWeekEntryPage:</div> <div class="dyncontent"> <div class="center"> <img src="class_obf_week_entry_page.png" usemap="#ObfWeekEntryPage_map" alt=""/> <map id="ObfWeekEntryPage_map" name="ObfWeekEntryPage_map"> <area href="class_fannie_r_e_s_tful_page.html" alt="FannieRESTfulPage" shape="rect" coords="0,112,125,136"/> <area href="class_fannie_page.html" alt="FanniePage" shape="rect" coords="0,56,125,80"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:af21e372e11e464fdaaa97666af50f332"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af21e372e11e464fdaaa97666af50f332"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>preprocess</b> ()</td></tr> <tr class="separator:af21e372e11e464fdaaa97666af50f332"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad5fe3805f9da7871226bbc29ac640c2e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad5fe3805f9da7871226bbc29ac640c2e"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>javascript_content</b> ()</td></tr> <tr class="separator:ad5fe3805f9da7871226bbc29ac640c2e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3144510e128f643a6e9c5e011695b931"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a3144510e128f643a6e9c5e011695b931"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>post_handler</b> ()</td></tr> <tr class="separator:a3144510e128f643a6e9c5e011695b931"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9f486731b592225a63fea15af3032e26"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9f486731b592225a63fea15af3032e26"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>post_id_handler</b> ()</td></tr> <tr class="separator:a9f486731b592225a63fea15af3032e26"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a58cece4446e27b1384e1376057d80ef4"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a58cece4446e27b1384e1376057d80ef4"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>get_id_view</b> ()</td></tr> <tr class="separator:a58cece4446e27b1384e1376057d80ef4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a0a5bfa5a7045ea03c60b8a84c6f90d0e"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0a5bfa5a7045ea03c60b8a84c6f90d0e"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>get_view</b> ()</td></tr> <tr class="separator:a0a5bfa5a7045ea03c60b8a84c6f90d0e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_class_fannie_r_e_s_tful_page"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_fannie_r_e_s_tful_page')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td></tr> <tr class="memitem:ab248b5009c98297c3346aa2915a38198 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_r_e_s_tful_page.html#ab248b5009c98297c3346aa2915a38198">readRoutes</a> ()</td></tr> <tr class="separator:ab248b5009c98297c3346aa2915a38198 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aaf9c0bc27476ba59b8aaf55ed572b341 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aaf9c0bc27476ba59b8aaf55ed572b341"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>addRoute</b> ()</td></tr> <tr class="separator:aaf9c0bc27476ba59b8aaf55ed572b341 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae329897c576b0f04691c4b5c5f4e7102 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae329897c576b0f04691c4b5c5f4e7102"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>preprocess</b> ()</td></tr> <tr class="separator:ae329897c576b0f04691c4b5c5f4e7102 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af0ea1761f325f8c2c3af16985c52b20d inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af0ea1761f325f8c2c3af16985c52b20d"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>bodyContent</b> ()</td></tr> <tr class="separator:af0ea1761f325f8c2c3af16985c52b20d inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a74dc769d2dd23662dfdd7919622e3ec0 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a74dc769d2dd23662dfdd7919622e3ec0"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>unitTest</b> ($phpunit)</td></tr> <tr class="separator:a74dc769d2dd23662dfdd7919622e3ec0 inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af23debecf050136de43947768ee7c0ed inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_r_e_s_tful_page.html#af23debecf050136de43947768ee7c0ed">setForm</a> (COREPOS\common\mvc\ValueContainer $f)</td></tr> <tr class="separator:af23debecf050136de43947768ee7c0ed inherit pub_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_class_fannie_page"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_class_fannie_page')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="class_fannie_page.html">FanniePage</a></td></tr> <tr class="memitem:a860186d52b9e42718ce40a24f3d1dbac inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a860186d52b9e42718ce40a24f3d1dbac">preprocess</a> ()</td></tr> <tr class="separator:a860186d52b9e42718ce40a24f3d1dbac inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae1b7a43a8afcdb9f63c6493ff999d128 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#ae1b7a43a8afcdb9f63c6493ff999d128">getHeader</a> ()</td></tr> <tr class="separator:ae1b7a43a8afcdb9f63c6493ff999d128 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae8bee0f380f38adf20ebec9f55c38f88 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#ae8bee0f380f38adf20ebec9f55c38f88">addBootstrap</a> ()</td></tr> <tr class="separator:ae8bee0f380f38adf20ebec9f55c38f88 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a656f23373048907a822434f03cd96933 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a656f23373048907a822434f03cd96933">addJQuery</a> ()</td></tr> <tr class="separator:a656f23373048907a822434f03cd96933 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9344efafb8c07915f5c83684af9e9cc9 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9344efafb8c07915f5c83684af9e9cc9"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>get_header</b> ()</td></tr> <tr class="separator:a9344efafb8c07915f5c83684af9e9cc9 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a266d42da8e98de9086ee14207dbb23e0 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a266d42da8e98de9086ee14207dbb23e0">getFooter</a> ()</td></tr> <tr class="separator:a266d42da8e98de9086ee14207dbb23e0 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af8c62a80e0dfe13b0785e8db12dddf8a inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af8c62a80e0dfe13b0785e8db12dddf8a"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>get_footer</b> ()</td></tr> <tr class="separator:af8c62a80e0dfe13b0785e8db12dddf8a inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a407701c8ca9b8bba67db6ed9bb7625ae inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a407701c8ca9b8bba67db6ed9bb7625ae">loginRedirect</a> ()</td></tr> <tr class="separator:a407701c8ca9b8bba67db6ed9bb7625ae inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a422037871e8271a00d40e6c4808c116c inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a422037871e8271a00d40e6c4808c116c"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>login_redirect</b> ()</td></tr> <tr class="separator:a422037871e8271a00d40e6c4808c116c inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac04c301f26ebef12f7b37a6314dbdc58 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#ac04c301f26ebef12f7b37a6314dbdc58">checkAuth</a> ()</td></tr> <tr class="separator:ac04c301f26ebef12f7b37a6314dbdc58 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9547de9b1c00308b72c06c8a4e815620 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9547de9b1c00308b72c06c8a4e815620"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>check_auth</b> ()</td></tr> <tr class="separator:a9547de9b1c00308b72c06c8a4e815620 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a108e78f7b6939c33cf9c586e03d63581 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a108e78f7b6939c33cf9c586e03d63581">helpContent</a> ()</td></tr> <tr class="separator:a108e78f7b6939c33cf9c586e03d63581 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a48aec6a908a3a97152906290d90ecdc7 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a48aec6a908a3a97152906290d90ecdc7"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>preFlight</b> ()</td></tr> <tr class="separator:a48aec6a908a3a97152906290d90ecdc7 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a0a6b76dac695aebde9fc3a3314e0768a inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0a6b76dac695aebde9fc3a3314e0768a"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>postFlight</b> ()</td></tr> <tr class="separator:a0a6b76dac695aebde9fc3a3314e0768a inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a0d4f91b4f87e871f09928923adc2f779 inherit pub_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0d4f91b4f87e871f09928923adc2f779"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>setPermissions</b> ($p)</td></tr> <tr class="separator:a0d4f91b4f87e871f09928923adc2f779 inherit pub_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:aacafe0993bda1ca5182c2b6390e4aae2"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aacafe0993bda1ca5182c2b6390e4aae2"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$page_set</b> = 'Plugin :: Open Book Financing'</td></tr> <tr class="separator:aacafe0993bda1ca5182c2b6390e4aae2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad4bf8b4faee1fc108ec845bfcc0e92a6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad4bf8b4faee1fc108ec845bfcc0e92a6"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$description</b> = '[Week Entry] sets labor amounts and sales goals by week.'</td></tr> <tr class="separator:ad4bf8b4faee1fc108ec845bfcc0e92a6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a702c8b1cde1f8b176bace30e69dde6dd"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a702c8b1cde1f8b176bace30e69dde6dd"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$themed</b> = true</td></tr> <tr class="separator:a702c8b1cde1f8b176bace30e69dde6dd"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_attribs_class_fannie_page"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_class_fannie_page')"><img src="closed.png" alt="-"/>&#160;Public Attributes inherited from <a class="el" href="class_fannie_page.html">FanniePage</a></td></tr> <tr class="memitem:ae18c3d10081ae143b9a26db50d56480f inherit pub_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#ae18c3d10081ae143b9a26db50d56480f">$themed</a> = true</td></tr> <tr class="separator:ae18c3d10081ae143b9a26db50d56480f inherit pub_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pro-attribs"></a> Protected Attributes</h2></td></tr> <tr class="memitem:afd619e26b7ab319382f4966f4a62daf4"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afd619e26b7ab319382f4966f4a62daf4"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$title</b> = 'OBF: Weeks'</td></tr> <tr class="separator:afd619e26b7ab319382f4966f4a62daf4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad57e987a4b0d3222973cb830ed2ef90a"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad57e987a4b0d3222973cb830ed2ef90a"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$header</b> = 'OBF: Weeks'</td></tr> <tr class="separator:ad57e987a4b0d3222973cb830ed2ef90a"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a200ab007855e27a546bce35e601533bd"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a200ab007855e27a546bce35e601533bd"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$lib_class</b> = '<a class="el" href="class_obf_lib.html">ObfLib</a>'</td></tr> <tr class="separator:a200ab007855e27a546bce35e601533bd"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pro_attribs_class_fannie_r_e_s_tful_page"><td colspan="2" onclick="javascript:toggleInherit('pro_attribs_class_fannie_r_e_s_tful_page')"><img src="closed.png" alt="-"/>&#160;Protected Attributes inherited from <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td></tr> <tr class="memitem:aff9f062ac5b7b0bd6ba89d15aa456bb5 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aff9f062ac5b7b0bd6ba89d15aa456bb5"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$__method</b> = ''</td></tr> <tr class="separator:aff9f062ac5b7b0bd6ba89d15aa456bb5 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aedc5c357438ee3d1d109fb44f894d902 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aedc5c357438ee3d1d109fb44f894d902"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$__models</b> = array()</td></tr> <tr class="separator:aedc5c357438ee3d1d109fb44f894d902 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a2ba99eea842d834507df28b700554d1a inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_r_e_s_tful_page.html#a2ba99eea842d834507df28b700554d1a">$__routes</a></td></tr> <tr class="separator:a2ba99eea842d834507df28b700554d1a inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a9f55b24e384acd32db2eabb0d6f1b2c5 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9f55b24e384acd32db2eabb0d6f1b2c5"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$__route_stem</b> = 'unknownRequest'</td></tr> <tr class="separator:a9f55b24e384acd32db2eabb0d6f1b2c5 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a14f51e549d83e151b69da9c87bfc6cc2 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a14f51e549d83e151b69da9c87bfc6cc2"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$form</b></td></tr> <tr class="separator:a14f51e549d83e151b69da9c87bfc6cc2 inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7ca6bddf98db9e03ff14112a8d934ddf inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a7ca6bddf98db9e03ff14112a8d934ddf"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$routing_trait</b></td></tr> <tr class="separator:a7ca6bddf98db9e03ff14112a8d934ddf inherit pro_attribs_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pro_attribs_class_fannie_page"><td colspan="2" onclick="javascript:toggleInherit('pro_attribs_class_fannie_page')"><img src="closed.png" alt="-"/>&#160;Protected Attributes inherited from <a class="el" href="class_fannie_page.html">FanniePage</a></td></tr> <tr class="memitem:ad0b3a863b24906fa287f180292247923 inherit pro_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#ad0b3a863b24906fa287f180292247923">$must_authenticate</a> = false</td></tr> <tr class="separator:ad0b3a863b24906fa287f180292247923 inherit pro_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a1779b368fff2522728265227ff8200d1 inherit pro_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a1779b368fff2522728265227ff8200d1">$current_user</a> = false</td></tr> <tr class="separator:a1779b368fff2522728265227ff8200d1 inherit pro_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af38ec8b4bcd38fdc3e1fd573e9a91a4c inherit pro_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#af38ec8b4bcd38fdc3e1fd573e9a91a4c">$auth_classes</a> = array()</td></tr> <tr class="separator:af38ec8b4bcd38fdc3e1fd573e9a91a4c inherit pro_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7d739d589389ac71869df52f4e40d7de inherit pro_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a7d739d589389ac71869df52f4e40d7de"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$title</b> = 'Page window title'</td></tr> <tr class="separator:a7d739d589389ac71869df52f4e40d7de inherit pro_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aba42cd4e7c68f0808f0e9eba8936dacf inherit pro_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aba42cd4e7c68f0808f0e9eba8936dacf"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>$header</b> = 'Page displayed header'</td></tr> <tr class="separator:aba42cd4e7c68f0808f0e9eba8936dacf inherit pro_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a88f874daa83234cd8ef3c3f79238af97 inherit pro_attribs_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a88f874daa83234cd8ef3c3f79238af97">$enable_linea</a> = false</td></tr> <tr class="separator:a88f874daa83234cd8ef3c3f79238af97 inherit pro_attribs_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a> Additional Inherited Members</h2></td></tr> <tr class="inherit_header pro_methods_class_fannie_r_e_s_tful_page"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_class_fannie_r_e_s_tful_page')"><img src="closed.png" alt="-"/>&#160;Protected Member Functions inherited from <a class="el" href="class_fannie_r_e_s_tful_page.html">FannieRESTfulPage</a></td></tr> <tr class="memitem:a8d146cbc9315648d0b589d104d196514 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8d146cbc9315648d0b589d104d196514"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>checkRoute</b> ($route, $try_routes)</td></tr> <tr class="separator:a8d146cbc9315648d0b589d104d196514 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae95987891edb747e52cbba2a8b26c1eb inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae95987891edb747e52cbba2a8b26c1eb"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>bestRoute</b> ($try_routes)</td></tr> <tr class="separator:ae95987891edb747e52cbba2a8b26c1eb inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:afdc093f79eff94c8c011947897931ae8 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_r_e_s_tful_page.html#afdc093f79eff94c8c011947897931ae8">unknownRequestHandler</a> ()</td></tr> <tr class="separator:afdc093f79eff94c8c011947897931ae8 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad9d19fea0f22d6b25d3d7b9c94fafe58 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_r_e_s_tful_page.html#ad9d19fea0f22d6b25d3d7b9c94fafe58">unknownRequestView</a> ()</td></tr> <tr class="separator:ad9d19fea0f22d6b25d3d7b9c94fafe58 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa89bdea912b8fc2e6c2e47503e95ee2d inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_r_e_s_tful_page.html#aa89bdea912b8fc2e6c2e47503e95ee2d">getModel</a> ($database_connection, $class, $params, $find=False)</td></tr> <tr class="separator:aa89bdea912b8fc2e6c2e47503e95ee2d inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:abe81e41b1c5290f9a8cab50957d68240 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abe81e41b1c5290f9a8cab50957d68240"></a> &#160;</td><td class="memItemRight" valign="bottom"><b>get_model</b> ($database_connection, $class, $params, $find=False)</td></tr> <tr class="separator:abe81e41b1c5290f9a8cab50957d68240 inherit pro_methods_class_fannie_r_e_s_tful_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pro_methods_class_fannie_page"><td colspan="2" onclick="javascript:toggleInherit('pro_methods_class_fannie_page')"><img src="closed.png" alt="-"/>&#160;Protected Member Functions inherited from <a class="el" href="class_fannie_page.html">FanniePage</a></td></tr> <tr class="memitem:a635432e0d3c003c4e6853ed9642a96ac inherit pro_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#a635432e0d3c003c4e6853ed9642a96ac">lineaJS</a> ()</td></tr> <tr class="separator:a635432e0d3c003c4e6853ed9642a96ac inherit pro_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ac6f041a222d197b196644578a09f5944 inherit pro_methods_class_fannie_page"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="class_fannie_page.html#ac6f041a222d197b196644578a09f5944">helpModal</a> ()</td></tr> <tr class="separator:ac6f041a222d197b196644578a09f5944 inherit pro_methods_class_fannie_page"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this class was generated from the following file:<ul> <li>fannie/modules/plugins2.0/OpenBookFinancing/ObfWeekEntryPage.php</li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Fri Sep 2 2016 11:31:09 for CORE POS - Fannie by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.6 </small></address> </body> </html>
CORE-POS/IS4C
documentation/doxy/output/fannie/html/class_obf_week_entry_page.html
HTML
gpl-2.0
30,842
/* =========================================================================== Copyright (C) 2006 Dmn_clown (aka: Bob Isaac ([email protected])) This file is part of Open Arena and is based upon Mr. Elusive's fuzzy logic system found in Quake 3 Arena. Open Arena 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. Open Arena is distributed in the hope that 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 Foobar; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =========================================================================== */ chat "Tony" { #include "teamplay.h" type "game_enter" { "Here we go again."; "Why don't you people just lay down and die, it'll save me the trouble."; } type "game_exit" { GOODBYE1; GOODBYE4; GOODBYE3; } type "level_start" { "Oh man, ", 4, " again?!?"; "Alright, ", 4, " has always been good to me."; } type "level_end" { "nice place ", 4, ", much less dangerous than d3dm2."; } type "level_end_victory" { "Yep."; } type "level_end_lose" { "Aww... crap!"; } type "hit_talking" { DEATH_TALKING; } type "hit_nodeath" { TAUNT0; TAUNT1; TAUNT2; } type "hit_nokill" { HIT_NOKILL0; HIT_NOKILL1; HIT_NOKILL1; } type "death_telefrag" { DEATH_TELEFRAGGED0; DEATH_TELEFRAGGED0; DEATH_TELEFRAGGED0; } type "death_cratered" { DEATH_FALLING0; DEATH_FALLING0; DEATH_FALLING0; } type "death_lava" { "Well it was getting a bit nippy..."; "mmm... toasty!"; } type "death_slime" { "D'oh!"; } type "death_drown" { "Who needs air?"; } type "death_suicide" { DEATH_SUICIDE0; DEATH_SUICIDE1; DEATH_SUICIDE1; } type "death_gauntlet" { DEATH_GAUNTLET0; DEATH_GAUNTLET1; DEATH_GAUNTLET1; } type "death_rail" { DEATH_RAIL1; DEATH_RAIL1; DEATH_RAIL0; } type "death_bfg" { DEATH_BFG1; DEATH_BFG0; } type "death_insult" { "What the... how cheap!"; "Back in my day, frags weren't so cheap."; } type "death_praise" { 0, " is death incarnate."; } type "kill_rail" { KILL_RAIL0; KILL_RAIL1; } type "kill_gauntlet" { KILL_GAUNTLET0; KILL_GAUNTLET1; } type "kill_telefrag" { TELEFRAGGED0; TELEFRAGGED1; } type "kill_suicide" { TAUNT0; TAUNT1; } type "kill_insult" { "Pathetic."; "tsk"; "My ", family_member, " could do better."; } type "kill_praise" { "Nice one, ", 0, "."; "Wow, ~you never saw that one coming, ", 0, "."; } type "random_insult" { 0, ", ~you suck!"; 0, " needs to stop calling my mom."; } type "random_misc" { 0, " gave my ~mom ", disease, "."; "Is it true that ", peeps, " is a bot?"; } }
deepmind/lab
assets_oa/botfiles/bots/tony_t.c
C
gpl-2.0
3,121
/* * Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Winterspring SD%Complete: Almost Completely Emptied SDComment: Vendor Rivern Frostwind. Quest Support 4901 SDCategory: Winterspring EndScriptData */ /* ContentData npc_rivern_frostwind npc_ranshalla go_elune_fire EndContentData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "Player.h" #include "WorldSession.h" /*###### ## npc_rivern_frostwind ######*/ class npc_rivern_frostwind : public CreatureScript { public: npc_rivern_frostwind() : CreatureScript("npc_rivern_frostwind") { } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) override { player->PlayerTalkClass->ClearMenus(); if (action == GOSSIP_ACTION_TRADE) player->GetSession()->SendListInventory(creature->GetGUID()); return true; } bool OnGossipHello(Player* player, Creature* creature) override { if (creature->IsQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); if (creature->IsVendor() && player->GetReputationRank(589) == REP_EXALTED) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_VENDOR, GOSSIP_TEXT_BROWSE_GOODS, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_TRADE); player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); return true; } }; enum Says { // Escort texts SAY_QUEST_START = 0, SAY_ENTER_OWL_THICKET = 1, SAY_REACH_TORCH = 2, SAY_AFTER_TORCH = 3, SAY_REACH_ALTAR_1 = 4, SAY_REACH_ALTAR_2 = 5, // After lighting the altar cinematic SAY_RANSHALLA_ALTAR_1 = 6, SAY_RANSHALLA_ALTAR_2 = 7, SAY_PRIESTESS_ALTAR_3 = 8, SAY_PRIESTESS_ALTAR_4 = 9, SAY_RANSHALLA_ALTAR_5 = 10, SAY_RANSHALLA_ALTAR_6 = 11, SAY_PRIESTESS_ALTAR_7 = 12, SAY_PRIESTESS_ALTAR_8 = 13, SAY_PRIESTESS_ALTAR_9 = 14, SAY_PRIESTESS_ALTAR_10 = 15, SAY_PRIESTESS_ALTAR_11 = 16, SAY_PRIESTESS_ALTAR_12 = 17, SAY_PRIESTESS_ALTAR_13 = 18, SAY_PRIESTESS_ALTAR_14 = 19, SAY_VOICE_ALTAR_15 = 20, SAY_PRIESTESS_ALTAR_16 = 21, SAY_PRIESTESS_ALTAR_17 = 22, SAY_PRIESTESS_ALTAR_18 = 23, SAY_PRIESTESS_ALTAR_19 = 24, SAY_PRIESTESS_ALTAR_20 = 25, SAY_PRIESTESS_ALTAR_21 = 26, SAY_RANSHALLA_END_1 = 27, SAY_RANSHALLA_END_2 = 28, EMOTE_CHANT_SPELL = 29, }; enum Spells { SPELL_LIGHT_TORCH = 18953, // channeled spell by Ranshalla while waiting for the torches / altar }; enum NPCs { NPC_RANSHALLA = 10300, NPC_PRIESTESS_ELUNE = 12116, NPC_VOICE_ELUNE = 12152, NPC_GUARDIAN_ELUNE = 12140, }; enum GOs { GO_ELUNE_ALTAR = 177404, GO_ELUNE_FIRE = 177417, GO_ELUNE_GEM = 177414, // is respawned in script GO_ELUNE_LIGHT = 177415, // are respawned in script }; enum Quests { QUEST_GUARDIANS_ALTAR = 4901, }; enum Dummies { NPC_PRIESTESS_DATA_1 = -1, // dummy member for the first priestess (right) NPC_PRIESTESS_DATA_2 = -2, // dummy member for the second priestess (left) DATA_MOVE_PRIESTESS = -3, // dummy member to check the priestess movement DATA_EVENT_END = -4, // dummy member to indicate the event end EVENT_RESUME = 1, // trigger rest of event }; // DialogueHelper (imported from SD) struct DialogueEntry { int32 TextEntry; ///< To be said text entry int32 SayerEntry; ///< Entry of the mob who should say uint32 SayTimer; ///< Time delay until next text of array is said (0 stops) }; class DialogueHelper { public: // The array MUST be terminated by {0, 0, 0} DialogueHelper(DialogueEntry const* dialogueArray) : _dialogueArray(dialogueArray), _currentEntry(NULL), _actionTimer(0) { } // The array MUST be terminated by {0, 0, 0, 0, 0} /// Function to initialize the dialogue helper for instances. If not used with instances, GetSpeakerByEntry MUST be overwritten to obtain the speakers /// Set if take first entries or second entries void StartNextDialogueText(int32 textEntry) { // Find textEntry bool found = false; for (DialogueEntry const* entry = _dialogueArray; entry->TextEntry; ++entry) { if (entry->TextEntry == textEntry) { _currentEntry = entry; found = true; break; } } if (!found) return; DoNextDialogueStep(); } void DialogueUpdate(uint32 diff) { if (_actionTimer) { if (_actionTimer <= diff) DoNextDialogueStep(); else _actionTimer -= diff; } } protected: /// Will be called when a dialogue step was done virtual void JustDidDialogueStep(int32 /*entry*/) { } /// Will be called to get a speaker, MUST be implemented if not used in instances virtual Creature* GetSpeakerByEntry(int32 /*entry*/) { return NULL; } private: void DoNextDialogueStep() { // Last Dialogue Entry done? if (!_currentEntry || !_currentEntry->TextEntry) { _actionTimer = 0; return; } // Get Text, SpeakerEntry and Timer int32 textEntry = _currentEntry->TextEntry; uint32 sayerEntry = _currentEntry->SayerEntry; _actionTimer = _currentEntry->SayTimer; // Simulate Case if (sayerEntry && textEntry >= 0) { // Use Speaker if directly provided if (Creature* speaker = GetSpeakerByEntry(sayerEntry)) speaker->AI()->Talk(textEntry); } JustDidDialogueStep(_currentEntry->TextEntry); // Increment position ++_currentEntry; } DialogueEntry const* _dialogueArray; DialogueEntry const* _currentEntry; uint32 _actionTimer; }; const DialogueEntry introDialogue[] = { {SAY_REACH_ALTAR_1, NPC_RANSHALLA, 2000}, {SAY_REACH_ALTAR_2, NPC_RANSHALLA, 3000}, {NPC_RANSHALLA, 0, 0}, // start the altar channeling {SAY_PRIESTESS_ALTAR_3, NPC_PRIESTESS_DATA_2, 1000}, {SAY_PRIESTESS_ALTAR_4, NPC_PRIESTESS_DATA_1, 4000}, {SAY_RANSHALLA_ALTAR_5, NPC_RANSHALLA, 4000}, {SAY_RANSHALLA_ALTAR_6, NPC_RANSHALLA, 4000}, // start the escort here {SAY_PRIESTESS_ALTAR_7, NPC_PRIESTESS_DATA_2, 4000}, {SAY_PRIESTESS_ALTAR_8, NPC_PRIESTESS_DATA_2, 5000}, // show the gem {GO_ELUNE_GEM, 0, 5000}, {SAY_PRIESTESS_ALTAR_9, NPC_PRIESTESS_DATA_1, 4000}, // move priestess 1 near me {NPC_PRIESTESS_DATA_1, 0, 3000}, {SAY_PRIESTESS_ALTAR_10, NPC_PRIESTESS_DATA_1, 5000}, {SAY_PRIESTESS_ALTAR_11, NPC_PRIESTESS_DATA_1, 4000}, {SAY_PRIESTESS_ALTAR_12, NPC_PRIESTESS_DATA_1, 5000}, {SAY_PRIESTESS_ALTAR_13, NPC_PRIESTESS_DATA_1, 8000}, // summon voice and guard of elune {NPC_VOICE_ELUNE, 0, 12000}, {SAY_VOICE_ALTAR_15, NPC_VOICE_ELUNE, 5000}, // move priestess 2 near me {NPC_PRIESTESS_DATA_2, 0, 3000}, {SAY_PRIESTESS_ALTAR_16, NPC_PRIESTESS_DATA_2, 4000}, {SAY_PRIESTESS_ALTAR_17, NPC_PRIESTESS_DATA_2, 6000}, {SAY_PRIESTESS_ALTAR_18, NPC_PRIESTESS_DATA_1, 5000}, {SAY_PRIESTESS_ALTAR_19, NPC_PRIESTESS_DATA_1, 3000}, // move the owlbeast {NPC_GUARDIAN_ELUNE, 0, 2000}, {SAY_PRIESTESS_ALTAR_20, NPC_PRIESTESS_DATA_1, 4000}, // move the first priestess up {SAY_PRIESTESS_ALTAR_21, NPC_PRIESTESS_DATA_2, 10000}, // move second priestess up {DATA_MOVE_PRIESTESS, 0, 6000}, // despawn the gem {DATA_EVENT_END, 0, 2000}, // turn towards the player {SAY_RANSHALLA_END_2, NPC_RANSHALLA, 0}, {0, 0, 0}, }; static Position wingThicketLocations[] = { {5515.98f, -4903.43f, 846.30f, 4.58f}, // 0 right priestess summon loc {5501.94f, -4920.20f, 848.69f, 6.15f}, // 1 left priestess summon loc {5497.35f, -4906.49f, 850.83f, 2.76f}, // 2 guard of elune summon loc {5518.38f, -4913.47f, 845.57f, 0.00f}, // 3 right priestess move loc {5510.36f, -4921.17f, 846.33f, 0.00f}, // 4 left priestess move loc {5511.31f, -4913.82f, 847.17f, 0.00f}, // 5 guard of elune move loc {5518.51f, -4917.56f, 845.23f, 0.00f}, // 6 right priestess second move loc {5514.40f, -4921.16f, 845.49f, 0.00f} // 7 left priestess second move loc }; /*##### # npc_ranshalla #####*/ class npc_ranshalla : public CreatureScript { public: npc_ranshalla() : CreatureScript("npc_ranshalla") { } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) override { if (quest->GetQuestId() == QUEST_GUARDIANS_ALTAR) { creature->AI()->Talk(SAY_QUEST_START); creature->setFaction(FACTION_ESCORT_A_NEUTRAL_PASSIVE); if (npc_ranshallaAI* escortAI = dynamic_cast<npc_ranshallaAI*>(creature->AI())) escortAI->Start(false, false, player->GetGUID(), quest); return true; } return false; } CreatureAI* GetAI(Creature* creature) const override { return new npc_ranshallaAI(creature); } struct npc_ranshallaAI : public npc_escortAI, private DialogueHelper { npc_ranshallaAI(Creature* creature) : npc_escortAI(creature), DialogueHelper(introDialogue) { Initialize(); } void Initialize() { _delayTimer = 0; } uint32 _delayTimer; ObjectGuid _firstPriestessGUID; ObjectGuid _secondPriestessGUID; ObjectGuid _guardEluneGUID; ObjectGuid _voiceEluneGUID; ObjectGuid _altarGUID; void Reset() override { Initialize(); } // Called when the player activates the torch / altar void DoContinueEscort(bool isAltarWaypoint = false) { me->InterruptNonMeleeSpells(false); if (isAltarWaypoint) Talk(SAY_RANSHALLA_ALTAR_1); else Talk(SAY_AFTER_TORCH); _delayTimer = 2000; } // Called when Ranshalla starts to channel on a torch / altar void DoChannelTorchSpell(bool isAltarWaypoint = false) { // Check if we are using the fire or the altar and remove the no_interact flag if (isAltarWaypoint) { if (GameObject* go = GetClosestGameObjectWithEntry(me, GO_ELUNE_ALTAR, 10.0f)) { go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); me->SetFacingToObject(go); _altarGUID = go->GetGUID(); } } else if (GameObject* go = GetClosestGameObjectWithEntry(me, GO_ELUNE_FIRE, 10.0f)) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); // Yell and set escort to pause Talk(SAY_REACH_TORCH); Talk(EMOTE_CHANT_SPELL); SetEscortPaused(true); DoCast(me, SPELL_LIGHT_TORCH); } void DoSummonPriestess() { // Summon 2 Elune priestess and make each of them move to a different spot if (Creature* priestess = me->SummonCreature(NPC_PRIESTESS_ELUNE, wingThicketLocations[0].m_positionX, wingThicketLocations[0].m_positionY, wingThicketLocations[0].m_positionZ, wingThicketLocations[0].m_orientation, TEMPSUMMON_CORPSE_DESPAWN, 0)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[3].m_positionX, wingThicketLocations[3].m_positionY, wingThicketLocations[3].m_positionZ); _firstPriestessGUID = priestess->GetGUID(); } if (Creature* priestess = me->SummonCreature(NPC_PRIESTESS_ELUNE, wingThicketLocations[1].m_positionX, wingThicketLocations[1].m_positionY, wingThicketLocations[1].m_positionZ, wingThicketLocations[1].m_orientation, TEMPSUMMON_CORPSE_DESPAWN, 0)) { // Left priestess should have a distinct move point because she is the one who starts the dialogue at point reach priestess->GetMotionMaster()->MovePoint(1, wingThicketLocations[4].m_positionX, wingThicketLocations[4].m_positionY, wingThicketLocations[4].m_positionZ); _secondPriestessGUID = priestess->GetGUID(); } } void SummonedMovementInform(Creature* summoned, uint32 type, uint32 pointId) { if (type != POINT_MOTION_TYPE || summoned->GetEntry() != NPC_PRIESTESS_ELUNE || pointId != 1) return; // Start the dialogue when the priestess reach the altar (they should both reach the point in the same time) StartNextDialogueText(SAY_PRIESTESS_ALTAR_3); } void WaypointReached(uint32 pointId) override { switch (pointId) { case 3: Talk(SAY_ENTER_OWL_THICKET); break; case 10: // Cavern 1 case 15: // Cavern 2 case 20: // Cavern 3 case 25: // Cavern 4 case 36: // Cavern 5 DoChannelTorchSpell(); break; case 39: StartNextDialogueText(SAY_REACH_ALTAR_1); SetEscortPaused(true); break; case 41: { // Search for all nearest lights and respawn them std::list<GameObject*> eluneLights; GetGameObjectListWithEntryInGrid(eluneLights, me, GO_ELUNE_LIGHT, 20.0f); for (std::list<GameObject*>::const_iterator itr = eluneLights.begin(); itr != eluneLights.end(); ++itr) { if ((*itr)->isSpawned()) continue; (*itr)->SetRespawnTime(115); (*itr)->Refresh(); } if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) me->SetFacingToObject(altar); break; } case 42: // Summon the 2 priestess SetEscortPaused(true); DoSummonPriestess(); Talk(SAY_RANSHALLA_ALTAR_2); events.ScheduleEvent(EVENT_RESUME, 2000); break; case 44: // Stop the escort and turn towards the altar SetEscortPaused(true); if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) me->SetFacingToObject(altar); break; } } void JustDidDialogueStep(int32 entry) { switch (entry) { case NPC_RANSHALLA: // Start the altar channeling DoChannelTorchSpell(true); break; case SAY_RANSHALLA_ALTAR_6: SetEscortPaused(false); break; case SAY_PRIESTESS_ALTAR_8: // make the gem respawn if (GameObject* gem = GetClosestGameObjectWithEntry(me, GO_ELUNE_GEM, 10.0f)) { if (gem->isSpawned()) break; gem->SetRespawnTime(90); gem->Refresh(); } break; case SAY_PRIESTESS_ALTAR_9: // move near the escort npc if (Creature* priestess = me->GetMap()->GetCreature(_firstPriestessGUID)) priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[6].m_positionX, wingThicketLocations[6].m_positionY, wingThicketLocations[6].m_positionZ); break; case SAY_PRIESTESS_ALTAR_13: // summon the Guardian of Elune if (Creature* guard = me->SummonCreature(NPC_GUARDIAN_ELUNE, wingThicketLocations[2].m_positionX, wingThicketLocations[2].m_positionY, wingThicketLocations[2].m_positionZ, wingThicketLocations[2].m_orientation, TEMPSUMMON_CORPSE_DESPAWN, 0)) { guard->GetMotionMaster()->MovePoint(0, wingThicketLocations[5].m_positionX, wingThicketLocations[5].m_positionY, wingThicketLocations[5].m_positionZ); _guardEluneGUID = guard->GetGUID(); } // summon the Voice of Elune if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) { if (Creature* voice = me->SummonCreature(NPC_VOICE_ELUNE, altar->GetPositionX(), altar->GetPositionY(), altar->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) _voiceEluneGUID = voice->GetGUID(); } break; case SAY_VOICE_ALTAR_15: // move near the escort npc and continue dialogue if (Creature* priestess = me->GetMap()->GetCreature(_secondPriestessGUID)) { priestess->AI()->Talk(SAY_PRIESTESS_ALTAR_14); priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[7].m_positionX, wingThicketLocations[7].m_positionY, wingThicketLocations[7].m_positionZ); } break; case SAY_PRIESTESS_ALTAR_19: // make the voice of elune leave if (Creature* guard = me->GetMap()->GetCreature(_guardEluneGUID)) { guard->GetMotionMaster()->MovePoint(0, wingThicketLocations[2].m_positionX, wingThicketLocations[2].m_positionY, wingThicketLocations[2].m_positionZ); guard->DespawnOrUnsummon(4000); } break; case SAY_PRIESTESS_ALTAR_20: // make the first priestess leave if (Creature* priestess = me->GetMap()->GetCreature(_firstPriestessGUID)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[0].m_positionX, wingThicketLocations[0].m_positionY, wingThicketLocations[0].m_positionZ); priestess->DespawnOrUnsummon(4000); } break; case SAY_PRIESTESS_ALTAR_21: // make the second priestess leave if (Creature* priestess = me->GetMap()->GetCreature(_secondPriestessGUID)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[1].m_positionX, wingThicketLocations[1].m_positionY, wingThicketLocations[1].m_positionZ); priestess->DespawnOrUnsummon(4000); } break; case DATA_EVENT_END: // Turn towards the player if (Player* player = GetPlayerForEscort()) { me->SetFacingToObject(player); Talk(SAY_RANSHALLA_END_1, player); } break; case SAY_RANSHALLA_END_2: // Turn towards the altar and kneel - quest complete if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) { me->SetFacingToObject(altar); altar->ResetDoorOrButton(); } me->SetStandState(UNIT_STAND_STATE_KNEEL); if (Player* player = GetPlayerForEscort()) { player->GroupEventHappens(QUEST_GUARDIANS_ALTAR, me); Talk(SAY_RANSHALLA_END_2, player); } me->DespawnOrUnsummon(4000); break; } } Creature* GetSpeakerByEntry(int32 entry) { switch (entry) { case NPC_RANSHALLA: return me; case NPC_VOICE_ELUNE: return me->GetMap()->GetCreature(_voiceEluneGUID); case NPC_PRIESTESS_DATA_1: return me->GetMap()->GetCreature(_firstPriestessGUID); case NPC_PRIESTESS_DATA_2: return me->GetMap()->GetCreature(_secondPriestessGUID); default: return NULL; } } void UpdateEscortAI(const uint32 diff) override { DialogueUpdate(diff); if (_delayTimer) { if (_delayTimer <= diff) { SetEscortPaused(false); _delayTimer = 0; } else _delayTimer -= diff; } events.Update(diff); if (events.ExecuteEvent() == EVENT_RESUME) StartNextDialogueText(SAY_PRIESTESS_ALTAR_3); npc_escortAI::UpdateEscortAI(diff); } private: EventMap events; }; }; /*##### # go_elune_fire #####*/ class go_elune_fire : public GameObjectScript { public: go_elune_fire() : GameObjectScript("go_elune_fire") { } bool OnGossipHello(Player* /*player*/, GameObject* go) override { // Check if we are using the torches or the altar bool isAltar = false; if (go->GetEntry() == GO_ELUNE_ALTAR) isAltar = true; if (Creature* ranshalla = GetClosestCreatureWithEntry(go, NPC_RANSHALLA, 10.0f)) { if (npc_ranshalla::npc_ranshallaAI* escortAI = dynamic_cast<npc_ranshalla::npc_ranshallaAI*>(ranshalla->AI())) escortAI->DoContinueEscort(isAltar); } go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); return false; } }; void AddSC_winterspring() { new npc_rivern_frostwind(); new npc_ranshalla(); new go_elune_fire(); }
Stenlibg/4.3.4
src/server/scripts/Kalimdor/zone_winterspring.cpp
C++
gpl-2.0
23,792
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) is distributed in the hope that 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.rtc.utils; import java.io.IOException; import java.io.PipedReader; import java.io.PipedWriter; import java.io.Reader; import java.lang.reflect.UndeclaredThrowableException; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.ValidationException; import org.opennms.core.utils.ThreadCategory; import org.opennms.netmgt.xml.rtc.EuiLevel; /** * The class that marshalls the object to be sent to a PipedReader * * @author <A HREF="mailto:[email protected]">Brian Weaver </A> * @author <A HREF="http://www.opennms.org">OpenNMS.org </A> * @author <A HREF="mailto:[email protected]">Brian Weaver </A> * @author <A HREF="http://www.opennms.org">OpenNMS.org </A> * @version $Id: $ */ public class PipedMarshaller { private EuiLevel m_objToMarshall; private class MarshalThread implements Runnable { private PipedWriter m_out; private PipedReader m_in; private EuiLevel m_obj; MarshalThread(EuiLevel inp) throws IOException { m_obj = inp; m_out = new PipedWriter(); m_in = new PipedReader(m_out); } public void run() { try { Marshaller.marshal(m_obj, m_out); m_out.flush(); m_out.close(); } catch (MarshalException e) { ThreadCategory.getInstance(this.getClass()).error("Failed to convert category to xml", e); throw new UndeclaredThrowableException(e); } catch (ValidationException e) { ThreadCategory.getInstance(this.getClass()).error("Failed to convert category to xml", e); throw new UndeclaredThrowableException(e); } catch (IOException e) { ThreadCategory.getInstance(this.getClass()).warn("Failed to convert category to xml", e); // don't rethrow, it just bubbles up into output.log and confuses people, the error still shows in rtc.log // throw new UndeclaredThrowableException(e); } } Reader getReader() { return m_in; } } /** * <p>Constructor for PipedMarshaller.</p> * * @param toMarshall a {@link org.opennms.netmgt.xml.rtc.EuiLevel} object. */ public PipedMarshaller(EuiLevel toMarshall) { m_objToMarshall = toMarshall; } /** * <p>getReader</p> * * @return a {@link java.io.Reader} object. * @throws java.io.IOException if any. */ public Reader getReader() throws IOException { try { MarshalThread m = new MarshalThread(m_objToMarshall); Thread t = new Thread(m, "PipedMarshaller"); t.start(); return m.getReader(); } catch (IOException e) { throw e; } } }
RangerRick/opennms
opennms-services/src/main/java/org/opennms/netmgt/rtc/utils/PipedMarshaller.java
Java
gpl-2.0
4,070
/* * Copyright (C) 2010 Maarten Lankhorst for CodeWeavers * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef __AMAUDIO__ #define __AMAUDIO__ #include <mmsystem.h> #include <dsound.h> #undef INTERFACE #define INTERFACE IAMDirectSound DECLARE_INTERFACE_(IAMDirectSound,IUnknown) { /*** IUnknown methods ***/ STDMETHOD_(HRESULT,QueryInterface)(THIS_ REFIID riid, void** ppvObject) PURE; STDMETHOD_(ULONG,AddRef)(THIS) PURE; STDMETHOD_(ULONG,Release)(THIS) PURE; /*** IAMDirectSound methods ***/ STDMETHOD(GetDirectSoundInterface)(THIS_ IDirectSound **ds) PURE; STDMETHOD(GetPrimaryBufferInterface)(THIS_ IDirectSoundBuffer **buf) PURE; STDMETHOD(GetSecondaryBufferInterface)(THIS_ IDirectSoundBuffer **buf) PURE; STDMETHOD(ReleaseDirectSoundInterface)(THIS_ IDirectSound *ds) PURE; STDMETHOD(ReleasePrimaryBufferInterface)(THIS_ IDirectSoundBuffer *buf) PURE; STDMETHOD(ReleaseSecondaryBufferInterface)(THIS_ IDirectSoundBuffer *buf) PURE; STDMETHOD(SetFocusWindow)(THIS_ HWND hwnd, BOOL bgsilent) PURE; STDMETHOD(GetFocusWindow)(THIS_ HWND hwnd) PURE; }; #endif
jfoote/verysleepy
src/dbghelpw/include/amaudio.h
C
gpl-2.0
1,819
/* complex/test.c * * Copyright (C) 1996, 1997, 1998, 1999, 2000 Brian Gough * * 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 <config.h> #include <stdlib.h> #include <stdio.h> #include <gsl/gsl_ieee_utils.h> #include <gsl/gsl_test.h> #include <gsl/gsl_math.h> #include <gsl/gsl_complex.h> #include <gsl/gsl_complex_math.h> struct f { char *name; double (*f) (gsl_complex z); double x; double y; double fx; double fy; }; struct fz { char *name; gsl_complex (*f) (gsl_complex z); double x; double y; double fx; double fy; }; #define FN(x) "gsl_complex_" #x, gsl_complex_ ## x #define ARG(x,y) x, y #define RES(x,y) x, y struct f list[] = { #include "results1.h" {"", 0, 0, 0, 0, 0} }; struct fz listz[] = { #include "results.h" {"", 0, 0, 0, 0, 0} }; int main (void) { size_t i = 0; gsl_ieee_env_setup(); for (i = 0 ; i < 10; i++) { double r = (i - 5.0) * 0.3 ; double t = 2.0 * M_PI * i / 5 ; double x = r * cos(t), y = r * sin(t) ; gsl_complex z = gsl_complex_polar (r, t) ; gsl_test_rel (GSL_REAL(z), x, 10 * GSL_DBL_EPSILON, "gsl_complex_polar real part at (r=%g,t=%g)", r, t); gsl_test_rel (GSL_IMAG(z), y, 10 * GSL_DBL_EPSILON, "gsl_complex_polar imag part at (r=%g,t=%g)", r, t); } i = 0; while (list[i].f) { struct f t = list[i]; gsl_complex z = gsl_complex_rect (t.x, t.y); double f = (t.f) (z); gsl_test_rel (f, t.fx, 10 * GSL_DBL_EPSILON, "%s at (%g,%g)", t.name, t.x, t.y); i++; } i = 0; while (listz[i].f) { struct fz t = listz[i]; gsl_complex z = gsl_complex_rect (t.x, t.y); gsl_complex fz = (t.f) (z); double fx = GSL_REAL (fz), fy = GSL_IMAG (fz); #ifdef DEBUG printf("x = "); gsl_ieee_fprintf_double (stdout, &t.x); printf("\n"); printf("y = "); gsl_ieee_fprintf_double (stdout, &t.y); printf("\n"); printf("fx = "); gsl_ieee_fprintf_double (stdout, &fx); printf("\n"); printf("ex = "); gsl_ieee_fprintf_double (stdout, &t.fx); printf("\n"); printf("fy = "); gsl_ieee_fprintf_double (stdout, &fy); printf("\n"); printf("ey = "); gsl_ieee_fprintf_double (stdout, &t.fy); printf("\n"); #endif gsl_test_rel (fx, t.fx, 10 * GSL_DBL_EPSILON, "%s real part at (%g,%g)", t.name, t.x, t.y); gsl_test_rel (fy, t.fy, 10 * GSL_DBL_EPSILON, "%s imag part at (%g,%g)", t.name, t.x, t.y); i++; } exit (gsl_test_summary ()); }
nchaimov/m3l-af
libs/gsl/complex/test.c
C
gpl-2.0
3,142
/* * Copyright (C) 2007-2010 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.zlibrary.text.view; import java.util.ArrayList; import org.geometerplus.zlibrary.core.dialogs.ZLComboOptionEntry; import org.geometerplus.zlibrary.core.options.ZLIntegerOption; import org.geometerplus.zlibrary.core.resources.ZLResource; public class ZLTextLineSpaceOptionEntry extends ZLComboOptionEntry { private static final String KEY_UNCHANGED = "unchanged"; private static final ArrayList<String> ourAllValues = new ArrayList<String>(); private static final ArrayList<String> ourAllValuesPlusBase = new ArrayList<String>(); private final ZLIntegerOption myOption; private final ZLResource myResource; private final boolean myAllowBase; public ZLTextLineSpaceOptionEntry(ZLIntegerOption option, final ZLResource resource, boolean allowBase) { myOption = option; myResource = resource; myAllowBase = allowBase; if (ourAllValuesPlusBase.size() == 0) { for (int i = 5; i <= 20; ++i) { ourAllValues.add("" + (char)(i / 10 + '0') + '.' + (char)(i % 10 + '0')); } ourAllValuesPlusBase.add(myResource.getResource(KEY_UNCHANGED).getValue()); ourAllValuesPlusBase.addAll(ourAllValues); } } //Override public ArrayList<String> getValues() { return myAllowBase ? ourAllValuesPlusBase : ourAllValues; } //Override public String initialValue() { final int value = myOption.getValue(); if (value == -1) { return ourAllValuesPlusBase.get(0); } final int index = Math.max(0, Math.min(15, (value + 5) / 10 - 5)); return ourAllValues.get(index); } //Override public void onAccept(String value) { if (ourAllValuesPlusBase.get(0).equals(value)) { myOption.setValue(-1); } else { for (int i = 5; i <= 20; ++i) { if (ourAllValues.get(i - 5).equals(value)) { myOption.setValue(10 * i); break; } } } } }
giannoug/android_device_jxd_s7300b
packages/PicturePlayer/src/org/geometerplus/zlibrary/text/view/ZLTextLineSpaceOptionEntry.java
Java
gpl-2.0
2,610
/* Copyright (C) 2001-2004 Kenichi Suto * * 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. */ #ifndef __MULTI_H__ #define __MULTI_H__ #include "defs.h" void show_multi(); void show_candidate(BOOK_INFO *binfo, gint code); void multi_select_row(GtkWidget *widget, gint row, gint column, GdkEventButton *bevent, gpointer user_data); GtkWidget *create_multi_tree(); void search_multi(); #endif /* __MULTI_H__ */
fujii/ebview
src/multi.h
C
gpl-2.0
1,091
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <link rel="up" title="FatFs" href="../00index_j.html"> <link rel="alternate" hreflang="en" title="English" href="../en/read.html"> <link rel="stylesheet" href="../css_j.css" type="text/css" media="screen" title="ELM Default"> <title>FatFs - f_read</title> </head> <body> <div class="para func"> <h2>f_read</h2> <p>ファイルからデータを読み出します。</p> <pre> FRESULT f_read ( FIL* <span class="arg">fp</span>, <span class="c">/* [IN] ファイル オブジェクト構造体 */</span> void* <span class="arg">buff</span>, <span class="c">/* [OUT] 読み出したデータを格納するバッファ */</span> UINT <span class="arg">btr</span>, <span class="c">/* [IN] 読み出すバイト数 */</span> UINT* <span class="arg">br</span> <span class="c">/* [OUT] 読み出されたバイト数 */</span> ); </pre> </div> <div class="para arg"> <h4>引数</h4> <dl class="par"> <dt>fp</dt> <dd>ファイル オブジェクト構造体へのポインタを指定します。</dd> <dt>buff</dt> <dd>読み出したデータを格納するバッファを指すポインタを指定します。</dd> <dt>btr</dt> <dd>読み出すバイト数(0~<tt>UINT</tt>型の最大値)を指定します。</dd> <dt>br</dt> <dd>実際に読み出されたバイト数を格納する変数を指すポインタを指定します。戻り値は関数の成否にかかわらず常に有効です。</dd> </dl> </div> <div class="para ret"> <h4>戻り値</h4> <p> <a href="rc.html#ok">FR_OK</a>, <a href="rc.html#de">FR_DISK_ERR</a>, <a href="rc.html#ie">FR_INT_ERR</a>, <a href="rc.html#nr">FR_NOT_READY</a>, <a href="rc.html#de">FR_DENIED</a>, <a href="rc.html#io">FR_INVALID_OBJECT</a>, <a href="rc.html#tm">FR_TIMEOUT</a> </p> </div> <div class="para desc"> <h4>解説</h4> <p>読み込み開始位置は、現在のリード/ライト ポインタからになります。リード/ライト ポインタは読み込まれたバイト数だけ進みます。関数が正常終了した後は、<tt class="arg">*br</tt>の値をチェックすべきです。<tt class="arg">*br</tt>が<tt class="arg">btr</tt>よりも小さいときは、読み込み中にファイルの終端に達したことを示しています。</p> </div> <div class="para comp"> <h4>対応情報</h4> <p>全ての構成で使用可能です。</p> </div> <div class="para ref"> <h4>参照</h4> <p><tt><a href="open.html">f_open</a>, <a href="gets.html">fgets</a>, <a href="write.html">f_write</a>, <a href="close.html">f_close</a>, <a href="sfile.html">FIL</a></tt></p> </div> <p class="foot"><a href="../00index_j.html">戻る</a></p> </body> </html>
JDogHerman/portapack-hackrf
firmware/chibios-portapack/ext/fatfs/doc/ja/read.html
HTML
gpl-2.0
2,978
<?php /** * Element: Languages * Displays a select box of languages * * @package NoNumber Framework * @version 15.1.2 * * @author Peter van Westen <[email protected]> * @link http://www.nonumber.nl * @copyright Copyright © 2015 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; class JFormFieldNN_Languages extends JFormField { public $type = 'Languages'; private $params = null; protected function getInput() { $this->params = $this->element->attributes(); $size = (int) $this->get('size'); $multiple = $this->get('multiple'); $client = $this->get('client', 'SITE'); jimport('joomla.language.helper'); $langs = JLanguageHelper::createLanguageList($this->value, constant('JPATH_' . strtoupper($client)), true); $options = array(); foreach ($langs as $lang) { if ($lang['value']) { $option = new stdClass; $option->value = $lang['value']; $option->text = $lang['text'] . ' [' . $lang['value'] . ']'; $options[] = $option; } } require_once JPATH_PLUGINS . '/system/nnframework/helpers/html.php'; return nnHtml::selectlistsimple($options, $this->name, $this->value, $this->id, $size, $multiple); } private function get($val, $default = '') { return (isset($this->params[$val]) && (string) $this->params[$val] != '') ? (string) $this->params[$val] : $default; } }
bundocba/chrisnetic
tmp/install_55014b0d3a2a1/framework/framework/j3/plugins/system/nnframework/fields/languages.php
PHP
gpl-2.0
1,457
/* { dg-do compile } */ /* { dg-options "-O2 -mbmi -fno-inline -dp --param max-default-completely-peeled-insns=0" } */ #include "bmi-andn-2.c" /* { dg-final { scan-assembler-times "bmi_andn_si" 1 } } */
crystax/android-toolchain-gcc-4-9
gcc/testsuite/gcc.target/i386/bmi-andn-2a.c
C
gpl-2.0
206
#region Copyright & License Information /* * Copyright 2007-2019 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you 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. For more * information, see COPYING. */ #endregion using System.Linq; using OpenRA.Traits; namespace OpenRA.Mods.Common.Traits { public class CreatesShroudInfo : AffectsShroudInfo { [Desc("Stance the watching player needs to see the generated shroud.")] public readonly Stance ValidStances = Stance.Neutral | Stance.Enemy; public override object Create(ActorInitializer init) { return new CreatesShroud(init.Self, this); } } public class CreatesShroud : AffectsShroud { readonly CreatesShroudInfo info; ICreatesShroudModifier[] rangeModifiers; public CreatesShroud(Actor self, CreatesShroudInfo info) : base(self, info) { this.info = info; } protected override void Created(Actor self) { base.Created(self); rangeModifiers = self.TraitsImplementing<ICreatesShroudModifier>().ToArray(); } protected override void AddCellsToPlayerShroud(Actor self, Player p, PPos[] uv) { if (!info.ValidStances.HasStance(p.Stances[self.Owner])) return; p.Shroud.AddSource(this, Shroud.SourceType.Shroud, uv); } protected override void RemoveCellsFromPlayerShroud(Actor self, Player p) { p.Shroud.RemoveSource(this); } public override WDist Range { get { if (CachedTraitDisabled) return WDist.Zero; var revealsShroudModifier = rangeModifiers.Select(x => x.GetCreatesShroudModifier()); var range = Util.ApplyPercentageModifiers(Info.Range.Length, revealsShroudModifier); return new WDist(range); } } } }
SoScared/OpenRA
OpenRA.Mods.Common/Traits/CreatesShroud.cs
C#
gpl-3.0
1,855
#ifndef NSBUNDLE_DYLD_H #define NSBUNDLE_DYLD_H #include <Foundation/NSBundle.h> @interface NSBundle (NSBundle_dyld) +(NSBundle*) gnu_mainBundle; +(NSBundle*) x_mainBundle; +(NSBundle*) gnu_bundleForClass: (Class) aClass; +(NSBundle*) x_bundleForClass: (Class) aClass; @end #endif
magicpriest/darling-FC-edition
src/libobjcdarwin/NSBundle_dyld.h
C
gpl-3.0
288
c--------------------------------------------------------------------- c--------------------------------------------------------------------- subroutine add c--------------------------------------------------------------------- c--------------------------------------------------------------------- c--------------------------------------------------------------------- c addition of update to the vector u c--------------------------------------------------------------------- include 'header.h' integer i,j,k,m if (timeron) call timer_start(t_add) do k = 1, nz2 do j = 1, ny2 do i = 1, nx2 do m = 1, 5 u(m,i,j,k) = u(m,i,j,k) + rhs(m,i,j,k) end do end do end do end do if (timeron) call timer_stop(t_add) return end
kfrye/SMM-MPI
test/NPB3.3.1/NPB3.3-SER/SP/add.f
FORTRAN
gpl-3.0
888
/* * Ref-Finder * Copyright (C) <2015> <PLSE_UCLA> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package lsd.rule; public class LSDBinding implements Comparable<LSDBinding> { private char type; private LSDVariable variable; private String groundConst = null; public boolean isBound() { return this.groundConst != null; } public String getGroundConst() { String temp = this.groundConst; if (temp != null) { temp = temp.substring(1, temp.length() - 1); } return temp; } public boolean equals(Object other) { if (!(other instanceof LSDBinding)) { return false; } LSDBinding otherBinding = (LSDBinding)other; if ((this.groundConst == null) || (otherBinding.groundConst == null)) { if (this.groundConst != otherBinding.groundConst) { return false; } } else if (!this.groundConst.equals(otherBinding.groundConst)) { return false; } if ((this.variable == null) || (otherBinding.variable == null)) { if (this.variable != otherBinding.variable) { return false; } } else if (!this.variable.equals(otherBinding.variable)) { return false; } return true; } public LSDBinding(LSDVariable var) { this.variable = var; this.type = var.getType(); } public LSDBinding(String cst) { this.variable = null; this.groundConst = cst; } public void ground(String cst) { this.type = this.variable.getType(); this.variable = null; this.groundConst = cst; } private LSDBinding(LSDBinding toCopyFrom) { this.variable = toCopyFrom.variable; this.type = toCopyFrom.type; this.groundConst = toCopyFrom.groundConst; } public boolean typeChecks(char type) { return (this.variable == null) || (this.variable.typeChecks(type)); } public LSDBinding substitute(LSDVariable toReplace, LSDBinding replacement) throws LSDInvalidTypeException { LSDBinding nb = new LSDBinding(this); if (this.variable == null) { return nb; } if (this.variable.equals(toReplace)) { if (!this.variable.typeChecks(toReplace)) { throw new LSDInvalidTypeException(); } if ((replacement.variable != null) && (!this.variable.typeChecks(replacement.variable))) { throw new LSDInvalidTypeException(); } nb.variable = replacement.variable; nb.type = this.variable.getType(); nb.groundConst = replacement.groundConst; } return nb; } public LSDVariable getVariable() { return this.variable; } public String toString() { if (this.variable != null) { return this.variable.toString(); } return this.groundConst.toString(); } public void replaceVar(LSDVariable newVar) { this.variable = newVar; this.type = newVar.getType(); } public char getType() { return this.type; } public int compareTo(LSDBinding o) { String os = o.getType() + ":" + o.groundConst; String ts = this.type + ":" + this.groundConst; return os.compareTo(ts); } public void setType(char c) { this.type = c; } }
SoftwareEngineeringToolDemos/FSE-2010-Ref-Finder
code/lsd/rule/LSDBinding.java
Java
gpl-3.0
3,817
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle is distributed in the hope that 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package local_onenote * @author Vinayak (Vin) Bhalerao ([email protected]) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @copyright Microsoft, Inc. */ /** * Upgrade the local_onenote plugin. * * @param int $oldversion the version we are upgrading from * @return bool result */ function xmldb_local_onenote_upgrade($oldversion) { global $CFG, $DB; $dbman = $DB->get_manager(); if ($oldversion < 2014110503) { // Define table to be created. $table = new xmldb_table('onenote_user_sections'); // Adding fields to table. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('user_id', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('course_id', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('section_id', XMLDB_TYPE_CHAR, '255', null, null, null, null); // Adding keys to table. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); // Create table. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); // Define table onenote_assign_pages to be created. $table = new xmldb_table('onenote_assign_pages'); // Adding fields to table. $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('user_id', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('assign_id', XMLDB_TYPE_INTEGER, '10', null, null, null, null); $table->add_field('submission_student_page_id', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('feedback_student_page_id', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('submission_teacher_page_id', XMLDB_TYPE_CHAR, '255', null, null, null, null); $table->add_field('feedback_teacher_page_id', XMLDB_TYPE_CHAR, '255', null, null, null, null); // Adding keys to table. $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); // Create table. if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); // Onenote savepoint reached. upgrade_plugin_savepoint(true, 2014110503, 'local', 'onenote'); } if ($oldversion < 2015111905) { // Define field submission_teacher_lastview to be added to onenote_assign_pages. $table = new xmldb_table('onenote_assign_pages'); $field = new xmldb_field('teacher_lastviewed', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'feedback_teacher_page_id'); // Conditionally launch add field submission_teacher_lastview. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } $field = new xmldb_field('student_lastmodified', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'teacher_lastviewed'); // Conditionally launch add field submission_student_checksum. if (!$dbman->field_exists($table, $field)) { $dbman->add_field($table, $field); } // Onenote savepoint reached. upgrade_plugin_savepoint(true, 2015111905, 'local', 'onenote'); } if ($oldversion < 2016062002) { // Define table to be renamed. $table = new xmldb_table('onenote_user_sections'); if ($dbman->table_exists($table)) { // Rename the table to use the correct Moodle naming convention. $dbman->rename_table($table, 'local_onenote_user_sections'); } // Define table to be renamed. $table = new xmldb_table('onenote_assign_pages'); if ($dbman->table_exists($table)) { // Rename the table to use the correct Moodle naming convention. $dbman->rename_table($table, 'local_onenote_assign_pages'); } // Onenote savepoint reached. upgrade_plugin_savepoint(true, 2016062002, 'local', 'onenote'); } return true; }
Microsoft/o365-moodle
local/onenote/db/upgrade.php
PHP
gpl-3.0
4,856
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-IEs" * found in "/home/einstein/openairinterface5g/openair-cn/S1AP/MESSAGES/ASN1/R10.5/S1AP-IEs.asn" * `asn1c -gen-PER` */ #include "S1ap-IE-Extensions.h" static asn_per_constraints_t asn_PER_type_S1ap_IE_Extensions_constr_1 GCC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 16, 16, 1, 65535 } /* (SIZE(1..65535)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_S1ap_IE_Extensions_1[] = { { ATF_POINTER, 0, 0, (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)), 0, &asn_DEF_S1ap_IE, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "" }, }; static ber_tlv_tag_t asn_DEF_S1ap_IE_Extensions_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_SET_OF_specifics_t asn_SPC_S1ap_IE_Extensions_specs_1 = { sizeof(struct S1ap_IE_Extensions), offsetof(struct S1ap_IE_Extensions, _asn_ctx), 0, /* XER encoding is XMLDelimitedItemList */ }; asn_TYPE_descriptor_t asn_DEF_S1ap_IE_Extensions = { "S1ap-IE-Extensions", "S1ap-IE-Extensions", SEQUENCE_OF_free, SEQUENCE_OF_print, SEQUENCE_OF_constraint, SEQUENCE_OF_decode_ber, SEQUENCE_OF_encode_der, SEQUENCE_OF_decode_xer, SEQUENCE_OF_encode_xer, SEQUENCE_OF_decode_uper, SEQUENCE_OF_encode_uper, SEQUENCE_OF_decode_aper, SEQUENCE_OF_encode_aper, 0, /* Use generic outmost tag fetcher */ asn_DEF_S1ap_IE_Extensions_tags_1, sizeof(asn_DEF_S1ap_IE_Extensions_tags_1) /sizeof(asn_DEF_S1ap_IE_Extensions_tags_1[0]), /* 1 */ asn_DEF_S1ap_IE_Extensions_tags_1, /* Same as above */ sizeof(asn_DEF_S1ap_IE_Extensions_tags_1) /sizeof(asn_DEF_S1ap_IE_Extensions_tags_1[0]), /* 1 */ &asn_PER_type_S1ap_IE_Extensions_constr_1, asn_MBR_S1ap_IE_Extensions_1, 1, /* Single element */ &asn_SPC_S1ap_IE_Extensions_specs_1 /* Additional specs */ };
massar5289/openairinterface5G
cmake_targets/oaisim_build_oai/build/CMakeFiles/R10.5/S1ap-IE-Extensions.c
C
gpl-3.0
1,905
// Copyright 2014 The Chromium 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 <stddef.h> #include "base/bind.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/threading/thread.h" #include "content/renderer/media/webrtc/media_stream_track_metrics.h" #include "content/renderer/media/webrtc/mock_peer_connection_dependency_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/webrtc/api/mediastreaminterface.h" using webrtc::AudioSourceInterface; using webrtc::AudioTrackInterface; using webrtc::AudioTrackSinkInterface; using webrtc::MediaStreamInterface; using webrtc::ObserverInterface; using webrtc::PeerConnectionInterface; using webrtc::VideoTrackSourceInterface; using webrtc::VideoTrackInterface; namespace content { // A very simple mock that implements only the id() method. class MockAudioTrackInterface : public AudioTrackInterface { public: explicit MockAudioTrackInterface(const std::string& id) : id_(id) {} virtual ~MockAudioTrackInterface() {} virtual std::string id() const override { return id_; } MOCK_METHOD1(RegisterObserver, void(ObserverInterface*)); MOCK_METHOD1(UnregisterObserver, void(ObserverInterface*)); MOCK_CONST_METHOD0(kind, std::string()); MOCK_CONST_METHOD0(enabled, bool()); MOCK_CONST_METHOD0(state, TrackState()); MOCK_METHOD1(set_enabled, bool(bool)); MOCK_METHOD1(set_state, bool(TrackState)); MOCK_CONST_METHOD0(GetSource, AudioSourceInterface*()); MOCK_METHOD1(AddSink, void(AudioTrackSinkInterface*)); MOCK_METHOD1(RemoveSink, void(AudioTrackSinkInterface*)); private: std::string id_; }; // A very simple mock that implements only the id() method. class MockVideoTrackInterface : public VideoTrackInterface { public: explicit MockVideoTrackInterface(const std::string& id) : id_(id) {} virtual ~MockVideoTrackInterface() {} virtual std::string id() const override { return id_; } MOCK_METHOD1(RegisterObserver, void(ObserverInterface*)); MOCK_METHOD1(UnregisterObserver, void(ObserverInterface*)); MOCK_CONST_METHOD0(kind, std::string()); MOCK_CONST_METHOD0(enabled, bool()); MOCK_CONST_METHOD0(state, TrackState()); MOCK_METHOD1(set_enabled, bool(bool)); MOCK_METHOD1(set_state, bool(TrackState)); MOCK_METHOD2(AddOrUpdateSink, void(rtc::VideoSinkInterface<webrtc::VideoFrame>*, const rtc::VideoSinkWants&)); MOCK_METHOD1(RemoveSink, void(rtc::VideoSinkInterface<webrtc::VideoFrame>*)); MOCK_CONST_METHOD0(GetSource, VideoTrackSourceInterface*()); private: std::string id_; }; class MockMediaStreamTrackMetrics : public MediaStreamTrackMetrics { public: virtual ~MockMediaStreamTrackMetrics() {} MOCK_METHOD4(SendLifetimeMessage, void(const std::string&, TrackType, LifetimeEvent, StreamType)); using MediaStreamTrackMetrics::MakeUniqueIdImpl; }; class MediaStreamTrackMetricsTest : public testing::Test { public: MediaStreamTrackMetricsTest() : signaling_thread_("signaling_thread") {} void SetUp() override { metrics_.reset(new MockMediaStreamTrackMetrics()); stream_ = new rtc::RefCountedObject<MockMediaStream>("stream"); signaling_thread_.Start(); } void TearDown() override { signaling_thread_.Stop(); metrics_.reset(); stream_ = NULL; } // Adds an audio track to |stream_| on the signaling thread to simulate how // notifications will be fired in Chrome. template <typename TrackType> void AddTrack(TrackType* track) { // Explicitly casting to this type is necessary since the // MediaStreamInterface has two methods with the same name. typedef bool (MediaStreamInterface::*AddTrack)(TrackType*); base::RunLoop run_loop; signaling_thread_.task_runner()->PostTaskAndReply(FROM_HERE, base::Bind( base::IgnoreResult<AddTrack>(&MediaStreamInterface::AddTrack), stream_, track), run_loop.QuitClosure()); run_loop.Run(); } template <typename TrackType> void RemoveTrack(TrackType* track) { // Explicitly casting to this type is necessary since the // MediaStreamInterface has two methods with the same name. typedef bool (MediaStreamInterface::*RemoveTrack)(TrackType*); base::RunLoop run_loop; signaling_thread_.task_runner()->PostTaskAndReply(FROM_HERE, base::Bind( base::IgnoreResult<RemoveTrack>(&MediaStreamInterface::RemoveTrack), stream_, track), run_loop.QuitClosure()); run_loop.Run(); } // Convenience methods to cast the mock track types into their webrtc // equivalents. void AddAudioTrack(AudioTrackInterface* track) { AddTrack(track); } void RemoveAudioTrack(AudioTrackInterface* track) { RemoveTrack(track); } void AddVideoTrack(VideoTrackInterface* track) { AddTrack(track); } void RemoveVideoTrack(VideoTrackInterface* track) { RemoveTrack(track); } scoped_refptr<MockAudioTrackInterface> MakeAudioTrack(const std::string& id) { return new rtc::RefCountedObject<MockAudioTrackInterface>(id); } scoped_refptr<MockVideoTrackInterface> MakeVideoTrack(const std::string& id) { return new rtc::RefCountedObject<MockVideoTrackInterface>(id); } std::unique_ptr<MockMediaStreamTrackMetrics> metrics_; scoped_refptr<MediaStreamInterface> stream_; base::MessageLoopForUI message_loop_; base::Thread signaling_thread_; }; TEST_F(MediaStreamTrackMetricsTest, MakeUniqueId) { // The important testable properties of the unique ID are that it // should differ when any of the three constituents differ // (PeerConnection pointer, track ID, remote or not. Also, testing // that the implementation does not discard the upper 32 bits of the // PeerConnection pointer is important. // // The important hard-to-test property is that the ID be generated // using a hash function with virtually zero chance of // collisions. We don't test this, we rely on MD5 having this // property. // Lower 32 bits the same, upper 32 differ. EXPECT_NE( metrics_->MakeUniqueIdImpl( 0x1000000000000001, "x", MediaStreamTrackMetrics::RECEIVED_STREAM), metrics_->MakeUniqueIdImpl( 0x2000000000000001, "x", MediaStreamTrackMetrics::RECEIVED_STREAM)); // Track ID differs. EXPECT_NE(metrics_->MakeUniqueIdImpl( 42, "x", MediaStreamTrackMetrics::RECEIVED_STREAM), metrics_->MakeUniqueIdImpl( 42, "y", MediaStreamTrackMetrics::RECEIVED_STREAM)); // Remove vs. local track differs. EXPECT_NE(metrics_->MakeUniqueIdImpl( 42, "x", MediaStreamTrackMetrics::RECEIVED_STREAM), metrics_->MakeUniqueIdImpl( 42, "x", MediaStreamTrackMetrics::SENT_STREAM)); } TEST_F(MediaStreamTrackMetricsTest, BasicRemoteStreams) { scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); scoped_refptr<MockVideoTrackInterface> video(MakeVideoTrack("video")); stream_->AddTrack(audio.get()); stream_->AddTrack(video.get()); metrics_->AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionDisconnected); } TEST_F(MediaStreamTrackMetricsTest, BasicLocalStreams) { scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); scoped_refptr<MockVideoTrackInterface> video(MakeVideoTrack("video")); stream_->AddTrack(audio.get()); stream_->AddTrack(video.get()); metrics_->AddStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange(PeerConnectionInterface::kIceConnectionFailed); } TEST_F(MediaStreamTrackMetricsTest, LocalStreamAddedAferIceConnect) { metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); scoped_refptr<MockVideoTrackInterface> video(MakeVideoTrack("video")); stream_->AddTrack(audio.get()); stream_->AddTrack(video.get()); metrics_->AddStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); } TEST_F(MediaStreamTrackMetricsTest, RemoteStreamAddedAferIceConnect) { metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); scoped_refptr<MockVideoTrackInterface> video(MakeVideoTrack("video")); stream_->AddTrack(audio.get()); stream_->AddTrack(video.get()); metrics_->AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, stream_.get()); } TEST_F(MediaStreamTrackMetricsTest, RemoteStreamTrackAdded) { scoped_refptr<MockAudioTrackInterface> initial(MakeAudioTrack("initial")); scoped_refptr<MockAudioTrackInterface> added(MakeAudioTrack("added")); stream_->AddTrack(initial.get()); metrics_->AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("initial", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("added", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); AddAudioTrack(added.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("initial", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("added", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange(PeerConnectionInterface::kIceConnectionFailed); } TEST_F(MediaStreamTrackMetricsTest, LocalStreamTrackRemoved) { scoped_refptr<MockAudioTrackInterface> first(MakeAudioTrack("first")); scoped_refptr<MockAudioTrackInterface> second(MakeAudioTrack("second")); stream_->AddTrack(first.get()); stream_->AddTrack(second.get()); metrics_->AddStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("first", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("second", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("first", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); stream_->RemoveTrack(first.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("second", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange(PeerConnectionInterface::kIceConnectionFailed); } TEST_F(MediaStreamTrackMetricsTest, LocalStreamModificationsBeforeAndAfter) { scoped_refptr<MockAudioTrackInterface> first(MakeAudioTrack("first")); scoped_refptr<MockAudioTrackInterface> second(MakeAudioTrack("second")); stream_->AddTrack(first.get()); metrics_->AddStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); // This gets added after we start observing, but no lifetime message // should be sent at this point since the call is not connected. It // should get sent only once it gets connected. AddAudioTrack(second.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("first", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("second", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("first", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("second", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange(PeerConnectionInterface::kIceConnectionFailed); // This happens after the call is disconnected so no lifetime // message should be sent. RemoveAudioTrack(first.get()); } TEST_F(MediaStreamTrackMetricsTest, RemoteStreamMultipleDisconnects) { scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); stream_->AddTrack(audio.get()); metrics_->AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionDisconnected); metrics_->IceConnectionChange(PeerConnectionInterface::kIceConnectionFailed); RemoveAudioTrack(audio.get()); } TEST_F(MediaStreamTrackMetricsTest, RemoteStreamConnectDisconnectTwice) { scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); stream_->AddTrack(audio.get()); metrics_->AddStream(MediaStreamTrackMetrics::RECEIVED_STREAM, stream_.get()); for (size_t i = 0; i < 2; ++i) { EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::RECEIVED_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionDisconnected); } RemoveAudioTrack(audio.get()); } TEST_F(MediaStreamTrackMetricsTest, LocalStreamRemovedNoDisconnect) { scoped_refptr<MockAudioTrackInterface> audio(MakeAudioTrack("audio")); scoped_refptr<MockVideoTrackInterface> video(MakeVideoTrack("video")); stream_->AddTrack(audio.get()); stream_->AddTrack(video.get()); metrics_->AddStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->RemoveStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); } TEST_F(MediaStreamTrackMetricsTest, LocalStreamLargerTest) { scoped_refptr<MockAudioTrackInterface> audio1(MakeAudioTrack("audio1")); scoped_refptr<MockAudioTrackInterface> audio2(MakeAudioTrack("audio2")); scoped_refptr<MockAudioTrackInterface> audio3(MakeAudioTrack("audio3")); scoped_refptr<MockVideoTrackInterface> video1(MakeVideoTrack("video1")); scoped_refptr<MockVideoTrackInterface> video2(MakeVideoTrack("video2")); scoped_refptr<MockVideoTrackInterface> video3(MakeVideoTrack("video3")); stream_->AddTrack(audio1.get()); stream_->AddTrack(video1.get()); metrics_->AddStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio1", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video1", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->IceConnectionChange( PeerConnectionInterface::kIceConnectionConnected); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio2", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); AddAudioTrack(audio2.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("video2", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); AddVideoTrack(video2.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio1", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); RemoveAudioTrack(audio1.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio3", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); AddAudioTrack(audio3.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("video3", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); AddVideoTrack(video3.get()); // Add back audio1 EXPECT_CALL(*metrics_, SendLifetimeMessage("audio1", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::CONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); AddAudioTrack(audio1.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio2", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); RemoveAudioTrack(audio2.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("video2", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); RemoveVideoTrack(video2.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio1", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); RemoveAudioTrack(audio1.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("video1", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); RemoveVideoTrack(video1.get()); EXPECT_CALL(*metrics_, SendLifetimeMessage("audio3", MediaStreamTrackMetrics::AUDIO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); EXPECT_CALL(*metrics_, SendLifetimeMessage("video3", MediaStreamTrackMetrics::VIDEO_TRACK, MediaStreamTrackMetrics::DISCONNECTED, MediaStreamTrackMetrics::SENT_STREAM)); metrics_->RemoveStream(MediaStreamTrackMetrics::SENT_STREAM, stream_.get()); } } // namespace content
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/content/renderer/media/webrtc/media_stream_track_metrics_unittest.cc
C++
gpl-3.0
26,893
# p-throttler [![Build Status](https://secure.travis-ci.org/IndigoUnited/node-p-throttler.png)](http://travis-ci.org/IndigoUnited/node-p-throttler.png) A promise based throttler responsible for limiting execution of parallel tasks. The number of parallel tasks may be limited and configured per type. ## Installation `$ npm install p-throttler` ## API ### #create(defaultConcurrency, types) Constructs a new throttler. The `defaultConcurrency` is the default maximum concurrent functions being run (-1 to specify no limits). The `types` allows you to specify different concurrencies for different types. Example: ```js var throttler = PThrottler.create(15, { // or new PThrottler() 'network_io': 10, 'disk_io': 50 }); ``` ### .enqueue(func, [type]): Promise Enqueues a function to be ran. The function is expected to return a promise or a value. The returned promise is resolved when the function finishes execution. The `type` argument is optional and can be a `string` or an array of `strings`. Use it to specify the type(s) associated with the function. The function will run as soon as a free slot is available for every `type`. If no `type` is passed or is unknown, the `defaultConcurrency` is used. The execution order is guaranteed for functions enqueued with the exact same `type` argument. Example: ```js var method = function () { return Q.resolve('foo'); }; var throttler = PThrottler.create(15, { 'foo': 1, 'bar': 2 }); // Single type, will only run when a free slot for // "foo" is available throttler.enqueue(function () { return method(); // method() returns some promise }, 'foo') .then(function (value) { console.log(value); }); // Multiple type, will only run when a free slot for // "foo" and "bar" are available throttler.enqueue(function () { return method(); // method() returns some promise }, ['foo', 'bar']) .then(function (value) { console.log(value); }); ``` ### .abort(): Promise Aborts all current work being done. Returns a promise that is resolved when the current running functions finish to execute. Any function that was in the queue waiting to be ran is removed immediately. ## License Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
kailash-cd/CustomAdCreator
node_modules/grunt-bower-installer/node_modules/bower/node_modules/p-throttler/README.md
Markdown
gpl-3.0
2,387
<?php /** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later * */ namespace Piwik\Plugins\Ecommerce\Categories; use Piwik\Category\Subcategory; class EcommerceLogSubcategory extends Subcategory { protected $categoryId = 'Goals_Ecommerce'; protected $id = 'Goals_EcommerceLog'; protected $order = 5; }
Morerice/piwik
plugins/Ecommerce/Categories/EcommerceLogSubcategory.php
PHP
gpl-3.0
406
/* -*- c++ -*- */ /* * Copyright 2010-2013 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio 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 Radio is distributed in the hope that 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 Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include "usrp_source_impl.h" #include "gr_uhd_common.h" #include <gnuradio/io_signature.h> #include <boost/format.hpp> #include <boost/thread/thread.hpp> #include <boost/make_shared.hpp> #include <stdexcept> #include <iostream> namespace gr { namespace uhd { usrp_source::sptr usrp_source::make(const ::uhd::device_addr_t &device_addr, const ::uhd::io_type_t &io_type, size_t num_channels) { //fill in the streamer args ::uhd::stream_args_t stream_args; switch(io_type.tid) { case ::uhd::io_type_t::COMPLEX_FLOAT32: stream_args.cpu_format = "fc32"; break; case ::uhd::io_type_t::COMPLEX_INT16: stream_args.cpu_format = "sc16"; break; default: throw std::runtime_error("only complex float and shorts known to work"); } stream_args.otw_format = "sc16"; //only sc16 known to work for(size_t chan = 0; chan < num_channels; chan++) stream_args.channels.push_back(chan); //linear mapping return usrp_source::make(device_addr, stream_args); } usrp_source::sptr usrp_source::make(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args) { check_abi(); return usrp_source::sptr (new usrp_source_impl(device_addr, stream_args)); } usrp_source_impl::usrp_source_impl(const ::uhd::device_addr_t &device_addr, const ::uhd::stream_args_t &stream_args): sync_block("gr uhd usrp source", io_signature::make(0, 0, 0), args_to_io_sig(stream_args)), _stream_args(stream_args), _nchan(std::max<size_t>(1, stream_args.channels.size())), _stream_now(_nchan == 1), _tag_now(false), _start_time_set(false) { if(stream_args.cpu_format == "fc32") _type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_FLOAT32); if(stream_args.cpu_format == "sc16") _type = boost::make_shared< ::uhd::io_type_t >(::uhd::io_type_t::COMPLEX_INT16); std::stringstream str; str << name() << unique_id(); _id = pmt::string_to_symbol(str.str()); _dev = ::uhd::usrp::multi_usrp::make(device_addr); } usrp_source_impl::~usrp_source_impl() { } ::uhd::dict<std::string, std::string> usrp_source_impl::get_usrp_info(size_t chan) { #ifdef UHD_USRP_MULTI_USRP_GET_USRP_INFO_API return _dev->get_usrp_rx_info(chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_subdev_spec(const std::string &spec, size_t mboard) { return _dev->set_rx_subdev_spec(spec, mboard); } std::string usrp_source_impl::get_subdev_spec(size_t mboard) { return _dev->get_rx_subdev_spec(mboard).to_string(); } void usrp_source_impl::set_samp_rate(double rate) { _dev->set_rx_rate(rate); _samp_rate = this->get_samp_rate(); _tag_now = true; } double usrp_source_impl::get_samp_rate(void) { return _dev->get_rx_rate(); } ::uhd::meta_range_t usrp_source_impl::get_samp_rates(void) { #ifdef UHD_USRP_MULTI_USRP_GET_RATES_API return _dev->get_rx_rates(); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::tune_result_t usrp_source_impl::set_center_freq(const ::uhd::tune_request_t tune_request, size_t chan) { const ::uhd::tune_result_t res = _dev->set_rx_freq(tune_request, chan); _center_freq = this->get_center_freq(chan); _tag_now = true; return res; } double usrp_source_impl::get_center_freq(size_t chan) { return _dev->get_rx_freq(chan); } ::uhd::freq_range_t usrp_source_impl::get_freq_range(size_t chan) { return _dev->get_rx_freq_range(chan); } void usrp_source_impl::set_gain(double gain, size_t chan) { return _dev->set_rx_gain(gain, chan); } void usrp_source_impl::set_gain(double gain, const std::string &name, size_t chan) { return _dev->set_rx_gain(gain, name, chan); } double usrp_source_impl::get_gain(size_t chan) { return _dev->get_rx_gain(chan); } double usrp_source_impl::get_gain(const std::string &name, size_t chan) { return _dev->get_rx_gain(name, chan); } std::vector<std::string> usrp_source_impl::get_gain_names(size_t chan) { return _dev->get_rx_gain_names(chan); } ::uhd::gain_range_t usrp_source_impl::get_gain_range(size_t chan) { return _dev->get_rx_gain_range(chan); } ::uhd::gain_range_t usrp_source_impl::get_gain_range(const std::string &name, size_t chan) { return _dev->get_rx_gain_range(name, chan); } void usrp_source_impl::set_antenna(const std::string &ant, size_t chan) { return _dev->set_rx_antenna(ant, chan); } std::string usrp_source_impl::get_antenna(size_t chan) { return _dev->get_rx_antenna(chan); } std::vector<std::string> usrp_source_impl::get_antennas(size_t chan) { return _dev->get_rx_antennas(chan); } void usrp_source_impl::set_bandwidth(double bandwidth, size_t chan) { return _dev->set_rx_bandwidth(bandwidth, chan); } double usrp_source_impl::get_bandwidth(size_t chan) { return _dev->get_rx_bandwidth(chan); } ::uhd::freq_range_t usrp_source_impl::get_bandwidth_range(size_t chan) { return _dev->get_rx_bandwidth_range(chan); } void usrp_source_impl::set_auto_dc_offset(const bool enable, size_t chan) { #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_rx_dc_offset(enable, chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_dc_offset(const std::complex<double> &offset, size_t chan) { #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_rx_dc_offset(offset, chan); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_iq_balance(const std::complex<double> &correction, size_t chan) { #ifdef UHD_USRP_MULTI_USRP_FRONTEND_CAL_API return _dev->set_rx_iq_balance(correction, chan); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::sensor_value_t usrp_source_impl::get_sensor(const std::string &name, size_t chan) { return _dev->get_rx_sensor(name, chan); } std::vector<std::string> usrp_source_impl::get_sensor_names(size_t chan) { return _dev->get_rx_sensor_names(chan); } ::uhd::sensor_value_t usrp_source_impl::get_mboard_sensor(const std::string &name, size_t mboard) { return _dev->get_mboard_sensor(name, mboard); } std::vector<std::string> usrp_source_impl::get_mboard_sensor_names(size_t mboard) { return _dev->get_mboard_sensor_names(mboard); } void usrp_source_impl::set_clock_config(const ::uhd::clock_config_t &clock_config, size_t mboard) { return _dev->set_clock_config(clock_config, mboard); } void usrp_source_impl::set_time_source(const std::string &source, const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->set_time_source(source, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::string usrp_source_impl::get_time_source(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_time_source(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::vector<std::string> usrp_source_impl::get_time_sources(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_time_sources(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_clock_source(const std::string &source, const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->set_clock_source(source, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::string usrp_source_impl::get_clock_source(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_clock_source(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } std::vector<std::string> usrp_source_impl::get_clock_sources(const size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_REF_SOURCES_API return _dev->get_clock_sources(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } double usrp_source_impl::get_clock_rate(size_t mboard) { return _dev->get_master_clock_rate(mboard); } void usrp_source_impl::set_clock_rate(double rate, size_t mboard) { return _dev->set_master_clock_rate(rate, mboard); } ::uhd::time_spec_t usrp_source_impl::get_time_now(size_t mboard) { return _dev->get_time_now(mboard); } ::uhd::time_spec_t usrp_source_impl::get_time_last_pps(size_t mboard) { return _dev->get_time_last_pps(mboard); } void usrp_source_impl::set_time_now(const ::uhd::time_spec_t &time_spec, size_t mboard) { return _dev->set_time_now(time_spec, mboard); } void usrp_source_impl::set_time_next_pps(const ::uhd::time_spec_t &time_spec) { return _dev->set_time_next_pps(time_spec); } void usrp_source_impl::set_time_unknown_pps(const ::uhd::time_spec_t &time_spec) { return _dev->set_time_unknown_pps(time_spec); } void usrp_source_impl::set_command_time(const ::uhd::time_spec_t &time_spec, size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_COMMAND_TIME_API return _dev->set_command_time(time_spec, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::clear_command_time(size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_COMMAND_TIME_API return _dev->clear_command_time(mboard); #else throw std::runtime_error("not implemented in this version"); #endif } ::uhd::usrp::dboard_iface::sptr usrp_source_impl::get_dboard_iface(size_t chan) { return _dev->get_rx_dboard_iface(chan); } ::uhd::usrp::multi_usrp::sptr usrp_source_impl::get_device(void) { return _dev; } void usrp_source_impl::set_user_register(const uint8_t addr, const uint32_t data, size_t mboard) { #ifdef UHD_USRP_MULTI_USRP_USER_REGS_API _dev->set_user_register(addr, data, mboard); #else throw std::runtime_error("not implemented in this version"); #endif } void usrp_source_impl::set_start_time(const ::uhd::time_spec_t &time) { _start_time = time; _start_time_set = true; _stream_now = false; } void usrp_source_impl::issue_stream_cmd(const ::uhd::stream_cmd_t &cmd) { _dev->issue_stream_cmd(cmd); } bool usrp_source_impl::start(void) { #ifdef GR_UHD_USE_STREAM_API _rx_stream = _dev->get_rx_stream(_stream_args); _samps_per_packet = _rx_stream->get_max_num_samps(); #endif //setup a stream command that starts streaming slightly in the future static const double reasonable_delay = 0.1; //order of magnitude over RTT ::uhd::stream_cmd_t stream_cmd(::uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS); stream_cmd.stream_now = _stream_now; if(_start_time_set) { _start_time_set = false; //cleared for next run stream_cmd.time_spec = _start_time; } else { stream_cmd.time_spec = get_time_now() + ::uhd::time_spec_t(reasonable_delay); } _dev->issue_stream_cmd(stream_cmd); _tag_now = true; return true; } void usrp_source_impl::flush(void) { const size_t nbytes = 4096; gr_vector_void_star outputs; std::vector<std::vector<char> > buffs(_nchan, std::vector<char>(nbytes)); for(size_t i = 0; i < _nchan; i++) { outputs.push_back(&buffs[i].front()); } while(true) { #ifdef GR_UHD_USE_STREAM_API const size_t bpi = ::uhd::convert::get_bytes_per_item(_stream_args.cpu_format); _rx_stream->recv(outputs, nbytes/bpi, _metadata, 0.0); #else _dev->get_device()->recv (outputs, nbytes/_type->size, _metadata, *_type, ::uhd::device::RECV_MODE_FULL_BUFF, 0.0); #endif if(_metadata.error_code == ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) break; } } bool usrp_source_impl::stop(void) { _dev->issue_stream_cmd(::uhd::stream_cmd_t::STREAM_MODE_STOP_CONTINUOUS); this->flush(); return true; } std::vector<std::complex<float> > usrp_source_impl::finite_acquisition(const size_t nsamps) { if(_nchan != 1) throw std::runtime_error("finite_acquisition: usrp source has multiple channels, call finite_acquisition_v"); return finite_acquisition_v(nsamps).front(); } std::vector<std::vector<std::complex<float> > > usrp_source_impl::finite_acquisition_v(const size_t nsamps) { #ifdef GR_UHD_USE_STREAM_API //kludgy way to ensure rx streamer exsists if(!_rx_stream) { this->start(); this->stop(); } //flush so there is no queued-up data this->flush(); //create a multi-dimensional container to hold an array of sample buffers std::vector<std::vector<std::complex<float> > > samps(_nchan, std::vector<std::complex<float> >(nsamps)); //load the void* vector of buffer pointers std::vector<void *> buffs(_nchan); for(size_t i = 0; i < _nchan; i++) { buffs[i] = &samps[i].front(); } //tell the device to stream a finite amount ::uhd::stream_cmd_t cmd(::uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE); cmd.num_samps = nsamps; cmd.stream_now = _stream_now; static const double reasonable_delay = 0.1; //order of magnitude over RTT cmd.time_spec = get_time_now() + ::uhd::time_spec_t(reasonable_delay); _dev->issue_stream_cmd(cmd); //receive samples until timeout const size_t actual_num_samps = _rx_stream->recv (buffs, nsamps, _metadata, 1.0); //resize the resulting sample buffers for(size_t i = 0; i < _nchan; i++) { samps[i].resize(actual_num_samps); } return samps; #else throw std::runtime_error("not implemented in this version"); #endif } int usrp_source_impl::work(int noutput_items, gr_vector_const_void_star &input_items, gr_vector_void_star &output_items) { #ifdef GR_UHD_USE_STREAM_API //In order to allow for low-latency: //We receive all available packets without timeout. //This call can timeout under regular operation... size_t num_samps = _rx_stream->recv (output_items, noutput_items, _metadata, 0.0); //If receive resulted in a timeout condition: //We now receive a single packet with a large timeout. if(_metadata.error_code == ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) { num_samps = _rx_stream->recv (output_items, noutput_items, _metadata, 0.1, true/*one pkt*/); } #else size_t num_samps = _dev->get_device()->recv (output_items, noutput_items, _metadata, *_type, ::uhd::device::RECV_MODE_FULL_BUFF, 0.0); if(_metadata.error_code == ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) { num_samps = _dev->get_device()->recv (output_items, noutput_items, _metadata, *_type, ::uhd::device::RECV_MODE_ONE_PACKET, 1.0); } #endif //handle possible errors conditions switch(_metadata.error_code) { case ::uhd::rx_metadata_t::ERROR_CODE_NONE: if(_tag_now) { _tag_now = false; //create a timestamp pmt for the first sample const pmt::pmt_t val = pmt::make_tuple (pmt::from_uint64(_metadata.time_spec.get_full_secs()), pmt::from_double(_metadata.time_spec.get_frac_secs())); //create a tag set for each channel for(size_t i = 0; i < _nchan; i++) { this->add_item_tag(i, nitems_written(0), TIME_KEY, val, _id); this->add_item_tag(i, nitems_written(0), RATE_KEY, pmt::from_double(_samp_rate), _id); this->add_item_tag(i, nitems_written(0), FREQ_KEY, pmt::from_double(_center_freq), _id); } } break; case ::uhd::rx_metadata_t::ERROR_CODE_TIMEOUT: //its ok to timeout, perhaps the user is doing finite streaming return 0; case ::uhd::rx_metadata_t::ERROR_CODE_OVERFLOW: _tag_now = true; //ignore overflows and try work again return work(noutput_items, input_items, output_items); default: std::cout << boost::format("UHD source block got error code 0x%x") % _metadata.error_code << std::endl; return num_samps; } return num_samps; } void usrp_source_impl::setup_rpc() { #ifdef GR_CTRLPORT add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_get<usrp_source, double>( alias(), "samp_rate", &usrp_source::get_samp_rate, pmt::mp(100000.0f), pmt::mp(25000000.0f), pmt::mp(1000000.0f), "sps", "RX Sample Rate", RPC_PRIVLVL_MIN, DISPTIME | DISPOPTSTRIP))); add_rpc_variable( rpcbasic_sptr(new rpcbasic_register_set<usrp_source, double>( alias(), "samp_rate", &usrp_source::set_samp_rate, pmt::mp(100000.0f), pmt::mp(25000000.0f), pmt::mp(1000000.0f), "sps", "RX Sample Rate", RPC_PRIVLVL_MIN, DISPNULL))); #endif /* GR_CTRLPORT */ } } /* namespace uhd */ } /* namespace gr */
Gabotero/GNURadioNext
gr-uhd/lib/usrp_source_impl.cc
C++
gpl-3.0
19,405
/* EQEMu: Everquest Server Emulator Copyright (C) 2001-2016 EQEMu Development Team (http://eqemulator.net) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY except by those people which sell it, which are required to give you total support for your newly bought product; 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 */ #ifndef COMMON_SOF_H #define COMMON_SOF_H #include "../struct_strategy.h" class EQStreamIdentifier; namespace SoF { //these are the only public member of this namespace. extern void Register(EQStreamIdentifier &into); extern void Reload(); //you should not directly access anything below.. //I just dont feel like making a seperate header for it. class Strategy : public StructStrategy { public: Strategy(); protected: virtual std::string Describe() const; virtual const EQ::versions::ClientVersion ClientVersion() const; //magic macro to declare our opcode processors #include "ss_declare.h" #include "sof_ops.h" }; }; /*SoF*/ #endif /*COMMON_SOF_H*/
af4t/Server
common/patches/sof.h
C
gpl-3.0
1,555
/*//////////////////////////GPL¿ªÔ´Ðí¿ÉÖ¤//////////////////////////////////////////////// Copyright (C) <2014> <Xianglong He> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ÎļþÃû£ºDS18B20.h ×÷ÕߣººÎÏàÁú ÓÊÏ䣺[email protected] [email protected] ¹¦ÄÜÃèÊö£ºDS18B20ζȴ«¸ÐÆ÷µÄ¼òµ¥²Ù×÷º¯ÊýÄ£¿éµÄÍ·Îļþ ±¸×¢£º¾¡Á¿Ê¹Ó÷â×°ºÃµÄº¯Êý½øÐвÙ×÷£¬¶ø²»ÒªÊ¹ÓÃÖ±½Ó¶ÔDS18B20¶ÁдµÄº¯Êý¡£ ʹÓøÃÄ£¿é£¬ÇëÔÚconfig.hÖж¨ÒåDS18B20_IO_SET³£Á¿ÎªDS18B20µÄÊý¾Ý½Ó¿Ú¡£ Èç #define DS18B20_IO_SET P0^0 ʹÓøÃÄ£¿é£¬ÇëÔÚconfig.hÖж¨ÒåXTAL³£Á¿Îª¾§ÕñƵÂÊ Èç #define XTAL 11.059200 *//////////////////////////////////////////////////////////////////////////////////////// #ifndef _HEAD_DS18B20_ #define _HEAD_DS18B20_ #include<intrins.h> #include<config.h> /*/////////////////////////////////////////////////////////////////////////////////// *º¯ÊýÃû£ºDS18B20_GetTemp *º¯Êý¹¦ÄÜ£º¶ÁÈ¡DS18B20£¬»ñµÃζȡ£ *²ÎÊýÁÐ±í£º * *addr * ²ÎÊýÀàÐÍ£ºunsigned charÐÍÖ¸Õ루Á¬Ðø8¸öunsigned charµÄÊý¾Ý£© * ²ÎÊýÃèÊö£º64×Ö½ÚµÄÆ÷¼þ±àºÅ¡£ÌرðµÄ£¬Skip ROMʱaddr[0]Çë´«Èë0x00 *·µ»ØÖµ£ºÒ»¸ödoubleÐͱäÁ¿£¬»ñÈ¡µ½µÄζÈÖµ¡££¨·¢Éú´íÎóʱ£¬·µ»Ø-999£© *//////////////////////////////////////////////////////////////////////////////////// double DS18B20_GetTemp(unsigned char *addr); /*/////////////////////////////////////////////////////////////////////////////////// *º¯ÊýÃû£ºDS18B20_Start *º¯Êý¹¦ÄÜ£ºÆô¶¯18B20ζÈת»»¡£ *²ÎÊýÁÐ±í£º * *addr * ²ÎÊýÀàÐÍ£ºunsigned charÐÍÖ¸Õ루Á¬Ðø8¸öunsigned charµÄÊý¾Ý£© * ²ÎÊýÃèÊö£º64×Ö½ÚµÄÆ÷¼þ±àºÅ¡£ÌرðµÄ£¬Skip ROMʱaddr[0]Çë´«Èë0x00 *·µ»ØÖµ£ºÒ»¸öbitÐͱäÁ¿£¬Æô¶¯ÊÇ·ñÕý³££¨1£»Õý³££¬0£ºÊ§°Ü£© *//////////////////////////////////////////////////////////////////////////////////// bit DS18B20_Start(unsigned char *addr); /*/////////////////////////////////////////////////////////////////////////////////// *º¯ÊýÃû£ºDS18B20_Init *º¯Êý¹¦ÄÜ£º³õʼ»¯18B20 *·µ»ØÖµ£ºÒ»¸öbitÐͱäÁ¿£¬³õʼ»¯ÊÇ·ñÕý³££¨1£»Õý³££¬0£ºÊ§°Ü£© *//////////////////////////////////////////////////////////////////////////////////// bit DS18B20_Init(); /*/////////////////////////////////////////////////////////////////////////////////// *º¯ÊýÃû£ºDS18B20_Write £¨¾¡Á¿²»ÒªÖ±½Óµ÷Óã© *º¯Êý¹¦ÄÜ£ºÏò18B20дһ¸öunsigned charÐ͵ÄÊý¾Ý»òÃüÁî *²ÎÊýÁÐ±í£º * dat * ²ÎÊýÀàÐÍ£ºunsigned charÐÍÕûÊý * ²ÎÊýÃèÊö£ºÒªÐ´ÈëµÄÊý¾Ý»òÃüÁî *//////////////////////////////////////////////////////////////////////////////////// void DS18B20_Write(unsigned char dat); /*/////////////////////////////////////////////////////////////////////////////////// *º¯ÊýÃû£ºDS18B20_Read ¾¡Á¿²»ÒªÖ±½Óµ÷Óã© *º¯Êý¹¦ÄÜ£º´ÓDS18B20ÖжÁȡһλÊý¾Ý *·µ»ØÖµ£ºÒ»¸öunsigned charÐͱäÁ¿£¬¶ÁÈ¡µ½µÄÊý¾Ý *//////////////////////////////////////////////////////////////////////////////////// unsigned char DS18B20_Read(); #endif // _HEAD_DS18B20_
hxl9654/E51
DS18B20/Sample/DS18B20.h
C
gpl-3.0
3,430
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM is distributed in the hope that 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "volFields.H" #include "surfaceFields.H" #include "fvcGrad.H" #include "coupledFvPatchFields.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class Type, class Limiter, template<class> class LimitFunc> Foam::tmp<Foam::surfaceScalarField> Foam::LimitedScheme<Type, Limiter, LimitFunc>::limiter ( const GeometricField<Type, fvPatchField, volMesh>& phi ) const { const fvMesh& mesh = this->mesh(); tmp<surfaceScalarField> tLimiter ( new surfaceScalarField ( IOobject ( type() + "Limiter(" + phi.name() + ')', mesh.time().timeName(), mesh ), mesh, dimless ) ); surfaceScalarField& lim = tLimiter(); tmp<GeometricField<typename Limiter::phiType, fvPatchField, volMesh> > tlPhi = LimitFunc<Type>()(phi); const GeometricField<typename Limiter::phiType, fvPatchField, volMesh>& lPhi = tlPhi(); tmp<GeometricField<typename Limiter::gradPhiType, fvPatchField, volMesh> > tgradc(fvc::grad(lPhi)); const GeometricField<typename Limiter::gradPhiType, fvPatchField, volMesh>& gradc = tgradc(); const surfaceScalarField& CDweights = mesh.surfaceInterpolation::weights(); const labelUList& owner = mesh.owner(); const labelUList& neighbour = mesh.neighbour(); const vectorField& C = mesh.C(); scalarField& pLim = lim.internalField(); forAll(pLim, face) { label own = owner[face]; label nei = neighbour[face]; pLim[face] = Limiter::limiter ( CDweights[face], this->faceFlux_[face], lPhi[own], lPhi[nei], gradc[own], gradc[nei], C[nei] - C[own] ); } surfaceScalarField::GeometricBoundaryField& bLim = lim.boundaryField(); forAll(bLim, patchi) { scalarField& pLim = bLim[patchi]; if (bLim[patchi].coupled()) { const scalarField& pCDweights = CDweights.boundaryField()[patchi]; const scalarField& pFaceFlux = this->faceFlux_.boundaryField()[patchi]; const Field<typename Limiter::phiType> plPhiP ( lPhi.boundaryField()[patchi].patchInternalField() ); const Field<typename Limiter::phiType> plPhiN ( lPhi.boundaryField()[patchi].patchNeighbourField() ); const Field<typename Limiter::gradPhiType> pGradcP ( gradc.boundaryField()[patchi].patchInternalField() ); const Field<typename Limiter::gradPhiType> pGradcN ( gradc.boundaryField()[patchi].patchNeighbourField() ); // Build the d-vectors vectorField pd(CDweights.boundaryField()[patchi].patch().delta()); forAll(pLim, face) { pLim[face] = Limiter::limiter ( pCDweights[face], pFaceFlux[face], plPhiP[face], plPhiN[face], pGradcP[face], pGradcN[face], pd[face] ); } } else { pLim = 1.0; } } return tLimiter; } // ************************************************************************* //
martinep/OpenFOAM-2.2.X
src/finiteVolume/interpolation/surfaceInterpolation/limitedSchemes/LimitedScheme/LimitedScheme.C
C++
gpl-3.0
4,697
package com.dotmarketing.portlets.htmlpages.struts; import java.text.ParseException; import java.text.SimpleDateFormat; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.ValidatorForm; import com.dotmarketing.beans.Host; import com.dotmarketing.business.APILocator; import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotRuntimeException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.folders.model.Folder; import com.dotmarketing.util.InodeUtils; import com.dotmarketing.util.Logger; import com.liferay.portal.model.User; import com.liferay.portal.util.Constants; /** @author Hibernate CodeGenerator */ public class HTMLPageForm extends ValidatorForm { private static final long serialVersionUID = 1L; /** identifier field */ private String parent; /** nullable persistent field */ private String selectedparent; /** nullable persistent field */ private String selectedparentPath; /** nullable persistent field */ private String metadata; /** nullable persistent field */ private java.util.Date startDate; /** nullable persistent field */ private java.util.Date endDate; /** nullable persistent field */ private String webStartDate; /** nullable persistent field */ private String webEndDate; /** nullable persistent field */ private String pageUrl; /** nullable persistent field */ private boolean httpsRequired; /** nullable persistent field */ private String redirect; /** nullable persistent field */ private String template; /** nullable persistent field */ private String selectedtemplate; /*** WEB ASSET FIELDS FOR THE FORM ***/ /** nullable persistent field */ private String title; /** nullable persistent field */ private String friendlyName; /** nullable persistent field */ private boolean showOnMenu; /** nullable persistent field */ private int sortOrder; /*** WEB ASSET FIELDS FOR THE FORM ***/ private long cacheTTL; private String seoKeywords; private String seoDescription; public long getCacheTTL() { return cacheTTL; } public void setCacheTTL(long cacheTTL) { this.cacheTTL = cacheTTL; } public String getSeoKeywords() { return seoKeywords; } public void setSeoKeywords(String seoKeywords) { this.seoKeywords = seoKeywords; } public String getSeoDescription() { return seoDescription; } public void setSeoDescription(String seoDescription) { this.seoDescription = seoDescription; } private String owner; // dotcms 472 public HTMLPageForm() { } public String toString() { return ToStringBuilder.reflectionToString(this); } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { try { ActionErrors ae = new ActionErrors(); if (request.getParameter("cmd") != null && request.getParameter("cmd").equals(Constants.ADD)) { String inode = request.getParameter("parent"); User user=com.liferay.portal.util.PortalUtil.getUser(request); Folder parentFolder = APILocator.getFolderAPI().find(inode, user, false); if (!InodeUtils.isSet(parentFolder.getInode())) { User systemUser; systemUser = APILocator.getUserAPI().getSystemUser(); Host host = APILocator.getHostAPI().find(inode, systemUser, false); if (host != null && InodeUtils.isSet(host.getInode())) { ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("message.folder.ishostfolder")); } } } return ae; } catch (Exception e) { Logger.error(HTMLPageForm.class, e.getMessage(), e); throw new DotRuntimeException(e.getMessage(), e); } } /** * Returns the endDate. * @return java.util.Date */ public java.util.Date getEndDate() { return endDate; } /** * Returns the httpsRequired. * @return boolean */ public boolean isHttpsRequired() { return httpsRequired; } /** * Returns the metadata. * @return String */ public String getMetadata() { return metadata; } /** * Returns the pageUrl. * @return String */ public String getPageUrl() { return pageUrl; } /** * Returns the parent. * @return String */ public String getParent() { return parent; } /** * Returns the redirect. * @return String */ public String getRedirect() { return redirect; } /** * Returns the startDate. * @return java.util.Date */ public java.util.Date getStartDate() { return startDate; } /** * Sets the endDate. * @param endDate The endDate to set */ public void setEndDate(java.util.Date endDate) { this.endDate = endDate; } /** * Sets the httpsRequired. * @param httpsRequired The httpsRequired to set */ public void setHttpsRequired(boolean httpsRequired) { this.httpsRequired = httpsRequired; } /** * Sets the metadata. * @param metadata The metadata to set */ public void setMetadata(String metadata) { this.metadata = metadata; } /** * Sets the pageUrl. * @param pageUrl The pageUrl to set */ public void setPageUrl(String pageUrl) { this.pageUrl = pageUrl; } /** * Sets the parent. * @param parent The parent to set */ public void setParent(String parent) { this.parent = parent; } /** * Sets the redirect. * @param redirect The redirect to set */ public void setRedirect(String redirect) { this.redirect = redirect; } /** * Sets the startDate. * @param startDate The startDate to set */ public void setStartDate(java.util.Date startDate) { this.startDate = startDate; } /** * Returns the webEndDate. * @return String */ public String getWebEndDate() { return webEndDate; } /** * Returns the webStartDate. * @return String */ public String getWebStartDate() { return webStartDate; } /** * Sets the webEndDate. * @param webEndDate The webEndDate to set */ public void setWebEndDate(String webEndDate) { this.webEndDate = webEndDate; if(webEndDate != null) try { this.endDate = new SimpleDateFormat("MM/dd/yyyy").parse(webEndDate); } catch (ParseException e) { Logger.warn(this, "Invalid date format", e); } } /** * Sets the webStartDate. * @param webStartDate The webStartDate to set */ public void setWebStartDate(String webStartDate) { this.webStartDate = webStartDate; try { this.startDate = new SimpleDateFormat("MM/dd/yyyy").parse(webStartDate); } catch(Exception ex) { } } /** * Returns the friendlyName. * @return String */ public String getFriendlyName() { return friendlyName; } /** * Returns the showOnMenu. * @return boolean */ public boolean isShowOnMenu() { return showOnMenu; } /** * Returns the sortOrder. * @return int */ public int getSortOrder() { return sortOrder; } /** * Returns the title. * @return String */ public String getTitle() { return title; } /** * Sets the friendlyName. * @param friendlyName The friendlyName to set */ public void setFriendlyName(String friendlyName) { this.friendlyName = friendlyName; } /** * Sets the showOnMenu. * @param showOnMenu The showOnMenu to set */ public void setShowOnMenu(boolean showOnMenu) { this.showOnMenu = showOnMenu; } /** * Sets the sortOrder. * @param sortOrder The sortOrder to set */ public void setSortOrder(int sortOrder) { this.sortOrder = sortOrder; } /** * Sets the title. * @param title The title to set */ public void setTitle(String title) { this.title = title; } /** * Returns the selectedtemplate. * @return String */ public String getSelectedtemplate() { return selectedtemplate; } /** * Returns the template. * @return String */ public String getTemplate() { return template; } /** * Sets the selectedtemplate. * @param selectedtemplate The selectedtemplate to set */ public void setSelectedtemplate(String selectedtemplate) { this.selectedtemplate = selectedtemplate; } /** * Sets the template. * @param template The template to set */ public void setTemplate(String template) { this.template = template; } /** * Returns the selectedparent. * @return String */ public String getSelectedparent() { return selectedparent; } /** * Sets the selectedparent. * @param selectedparent The selectedparent to set */ public void setSelectedparent(String selectedparent) { this.selectedparent = selectedparent; } /** * Returns the selectedparentPath. * @return String */ public String getSelectedparentPath() { return selectedparentPath; } /** * Sets the selectedparentPath. * @param selectedparentPath The selectedparentPath to set */ public void setSelectedparentPath(String selectedparentPath) { this.selectedparentPath = selectedparentPath; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } }
ggonzales/ksl
src/com/dotmarketing/portlets/htmlpages/struts/HTMLPageForm.java
Java
gpl-3.0
9,257
/* * Copyright (c) 2008, SQL Power Group Inc. * * This file is part of Power*Architect. * * Power*Architect 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. * * Power*Architect is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ca.sqlpower.sqlobject; import java.beans.PropertyChangeEvent; import ca.sqlpower.object.AbstractPoolingSPListener; import ca.sqlpower.object.SPChildEvent; public class TestingSQLObjectListener extends AbstractPoolingSPListener { private int insertedCount; private int removedCount; private int changedCount; private String lastEventName; public TestingSQLObjectListener() { insertedCount = 0; removedCount = 0; changedCount = 0; lastEventName = null; } @Override public void childAddedImpl(SPChildEvent e) { insertedCount++; } @Override public void childRemovedImpl(SPChildEvent e) { removedCount++; } @Override public void propertyChangeImpl(PropertyChangeEvent e) { changedCount++; lastEventName = e.getPropertyName(); } public int getInsertedCount() { return insertedCount; } public int getRemovedCount() { return removedCount; } public int getChangedCount() { return changedCount; } public String getLastEventName() { return lastEventName; } }
amitkr/sqlpower-library
src/test/java/ca/sqlpower/sqlobject/TestingSQLObjectListener.java
Java
gpl-3.0
1,916
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Make a hot-copy of the repos at repospath; copy it to destpath</title> </head> <body><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="function.svn-repos-fs.html">svn_repos_fs</a></div> <div class="next" style="text-align: right; float: right;"><a href="function.svn-repos-open.html">svn_repos_open</a></div> <div class="up"><a href="ref.svn.html">SVN Functions</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div><hr /><div id="function.svn-repos-hotcopy" class="refentry"> <div class="refnamediv"> <h1 class="refname">svn_repos_hotcopy</h1> <p class="verinfo">(PECL svn &gt;= 0.1.0)</p><p class="refpurpose"><span class="refname">svn_repos_hotcopy</span> &mdash; <span class="dc-title">Make a hot-copy of the repos at repospath; copy it to destpath</span></p> </div> <div class="refsect1 description" id="refsect1-function.svn-repos-hotcopy-description"> <h3 class="title">Description</h3> <div class="methodsynopsis dc-description"> <span class="type">bool</span> <span class="methodname"><strong>svn_repos_hotcopy</strong></span> ( <span class="methodparam"><span class="type">string</span> <code class="parameter">$repospath</code></span> , <span class="methodparam"><span class="type">string</span> <code class="parameter">$destpath</code></span> , <span class="methodparam"><span class="type">bool</span> <code class="parameter">$cleanlogs</code></span> )</div> <div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is currently not documented; only its argument list is available. </p></div> <p class="para"> Make a hot-copy of the repos at repospath; copy it to destpath </p> </div> <div class="refsect1 notes" id="refsect1-function.svn-repos-hotcopy-notes"> <h3 class="title">Notes</h3> <div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is <em class="emphasis">EXPERIMENTAL</em>. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. </p></div> </div> </div><hr /><div class="manualnavbar" style="text-align: center;"> <div class="prev" style="text-align: left; float: left;"><a href="function.svn-repos-fs.html">svn_repos_fs</a></div> <div class="next" style="text-align: right; float: right;"><a href="function.svn-repos-open.html">svn_repos_open</a></div> <div class="up"><a href="ref.svn.html">SVN Functions</a></div> <div class="home"><a href="index.html">PHP Manual</a></div> </div></body></html>
rafaelgou/the-phpjs-local-docs-collection
php/5.5/function.svn-repos-hotcopy.html
HTML
gpl-3.0
2,882
@echo off REM REM dex2jar - Tools to work with android .dex and java .class files REM Copyright (c) 2009-2013 Panxiaobo REM REM Licensed under the Apache License, Version 2.0 (the "License"); REM you may not use this file except in compliance with the License. REM You may obtain a copy of the License at REM REM http://www.apache.org/licenses/LICENSE-2.0 REM REM Unless required by applicable law or agreed to in writing, software REM distributed under the License is distributed on an "AS IS" BASIS, REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. REM See the License for the specific language governing permissions and REM limitations under the License. REM REM call d2j_invoke.bat to setup java environment @"%~dp0d2j_invoke.bat" com.googlecode.dex2jar.tools.ClassVersionSwitch %*
SUPERAndroidAnalyzer/super
vendor/dex2jar-2.1-SNAPSHOT/d2j-class-version-switch.bat
Batchfile
gpl-3.0
845
/*! \file log.h * \author Jay Ridgeway <[email protected]> * \copyright GNU General Public License v3 * \brief Buffered logging (headers) * \details Implementation of a simple buffered logger designed to remove * I/O wait from threads that may be sensitive to such delays. Buffers are * saved and reused to reduce allocation calls. The logger output can then * be printed to stdout and/or a log file. If external loggers are added * to the core, the logger output is passed to those as well. * * \ingroup core * \ref core */ #ifndef JANUS_LOG_H #define JANUS_LOG_H #include <stdio.h> #include <glib.h> /*! \brief Buffered vprintf * @param[in] format Format string as defined by glib, followed by the * optional parameters to insert into formatted string (printf style) * \note This output is buffered and may not appear immediately on stdout. */ void janus_vprintf(const char *format, ...) G_GNUC_PRINTF(1, 2); /*! \brief Log initialization * \note This should be called before attempting to use the logger. A buffer * pool and processing thread are created. * @param daemon Whether the Janus is running as a daemon or not * @param console Whether the output should be printed on stdout or not * @param logfile Log file to save the output to, if any * @returns 0 in case of success, a negative integer otherwise */ int janus_log_init(gboolean daemon, gboolean console, const char *logfile); /*! \brief Method to add a list of external loggers to the log management * @param loggers Hash table of external loggers registered in the core */ void janus_log_set_loggers(GHashTable *loggers); /*! \brief Log destruction */ void janus_log_destroy(void); /*! \brief Method to check whether stdout logging is enabled * @returns TRUE if stdout logging is enabled, FALSE otherwise */ gboolean janus_log_is_stdout_enabled(void); /*! \brief Method to check whether file-based logging is enabled * @returns TRUE if file-based logging is enabled, FALSE otherwise */ gboolean janus_log_is_logfile_enabled(void); /*! \brief Method to get the path to the log file * @returns The full path to the log file, or NULL otherwise */ char *janus_log_get_logfile_path(void); #endif
meetecho/janus-gateway
src/log.h
C
gpl-3.0
2,189
<?php class ControllerProductCategory extends Controller { public function index() { $this->load->language('product/category'); $this->load->model('catalog/category'); $this->load->model('catalog/product'); $this->load->model('tool/image'); if (isset($this->request->get['filter'])) { $filter = $this->request->get['filter']; } else { $filter = ''; } if (isset($this->request->get['sort'])) { $sort = $this->request->get['sort']; } else { $sort = 'p.sort_order'; } if (isset($this->request->get['order'])) { $order = $this->request->get['order']; } else { $order = 'ASC'; } if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } if (isset($this->request->get['limit'])) { $limit = (int)$this->request->get['limit']; } else { $limit = $this->config->get('theme_' . $this->config->get('config_theme') . '_product_limit'); } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'language=' . $this->config->get('config_language')) ); if (isset($this->request->get['path'])) { $url = ''; if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $path = ''; $parts = explode('_', (string)$this->request->get['path']); $category_id = (int)array_pop($parts); foreach ($parts as $path_id) { if (!$path) { $path = (int)$path_id; } else { $path .= '_' . (int)$path_id; } $category_info = $this->model_catalog_category->getCategory($path_id); if ($category_info) { $data['breadcrumbs'][] = array( 'text' => $category_info['name'], 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $path . $url) ); } } } else { $category_id = 0; } $category_info = $this->model_catalog_category->getCategory($category_id); if ($category_info) { $this->document->setTitle($category_info['meta_title']); $this->document->setDescription($category_info['meta_description']); $this->document->setKeywords($category_info['meta_keyword']); $data['heading_title'] = $category_info['name']; $data['text_compare'] = sprintf($this->language->get('text_compare'), (isset($this->session->data['compare']) ? count($this->session->data['compare']) : 0)); // Set the last category breadcrumb $data['breadcrumbs'][] = array( 'text' => $category_info['name'], 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path']) ); if ($category_info['image']) { $data['thumb'] = $this->model_tool_image->resize($category_info['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_category_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_category_height')); } else { $data['thumb'] = ''; } $data['description'] = html_entity_decode($category_info['description'], ENT_QUOTES, 'UTF-8'); $data['compare'] = $this->url->link('product/compare', 'language=' . $this->config->get('config_language')); $url = ''; if (isset($this->request->get['filter'])) { $url .= '&filter=' . $this->request->get['filter']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $data['categories'] = array(); $results = $this->model_catalog_category->getCategories($category_id); foreach ($results as $result) { $filter_data = array( 'filter_category_id' => $result['category_id'], 'filter_sub_category' => true ); $data['categories'][] = array( 'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''), 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url) ); } $data['products'] = array(); $filter_data = array( 'filter_category_id' => $category_id, 'filter_sub_category' => $this->config->get('config_product_category') ? true : false, 'filter_filter' => $filter, 'sort' => $sort, 'order' => $order, 'start' => ($page - 1) * $limit, 'limit' => $limit ); $product_total = $this->model_catalog_product->getTotalProducts($filter_data); $results = $this->model_catalog_product->getProducts($filter_data); foreach ($results as $result) { if ($result['image']) { $image = $this->model_tool_image->resize($result['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height')); } else { $image = $this->model_tool_image->resize('placeholder.png', $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_product_height')); } if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) { $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']); } else { $price = false; } if ((float)$result['special']) { $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']); } else { $special = false; } if ($this->config->get('config_tax')) { $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']); } else { $tax = false; } if ($this->config->get('config_review_status')) { $rating = (int)$result['rating']; } else { $rating = false; } $data['products'][] = array( 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'description' => utf8_substr(trim(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))), 0, $this->config->get('theme_' . $this->config->get('config_theme') . '_product_description_length')) . '..', 'price' => $price, 'special' => $special, 'tax' => $tax, 'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1, 'rating' => $result['rating'], 'href' => $this->url->link('product/product', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'] . $url) ); } $url = ''; if (isset($this->request->get['filter'])) { $url .= '&filter=' . $this->request->get['filter']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $data['sorts'] = array(); $data['sorts'][] = array( 'text' => $this->language->get('text_default'), 'value' => 'p.sort_order-ASC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=p.sort_order&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_name_asc'), 'value' => 'pd.name-ASC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=pd.name&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_name_desc'), 'value' => 'pd.name-DESC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=pd.name&order=DESC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_price_asc'), 'value' => 'p.price-ASC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=p.price&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_price_desc'), 'value' => 'p.price-DESC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=p.price&order=DESC' . $url) ); if ($this->config->get('config_review_status')) { $data['sorts'][] = array( 'text' => $this->language->get('text_rating_desc'), 'value' => 'rating-DESC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=rating&order=DESC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_rating_asc'), 'value' => 'rating-ASC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=rating&order=ASC' . $url) ); } $data['sorts'][] = array( 'text' => $this->language->get('text_model_asc'), 'value' => 'p.model-ASC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=p.model&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_model_desc'), 'value' => 'p.model-DESC', 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . '&sort=p.model&order=DESC' . $url) ); $url = ''; if (isset($this->request->get['filter'])) { $url .= '&filter=' . $this->request->get['filter']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } $data['limits'] = array(); $limits = array_unique(array($this->config->get('theme_' . $this->config->get('config_theme') . '_product_limit'), 25, 50, 75, 100)); sort($limits); foreach($limits as $value) { $data['limits'][] = array( 'text' => $value, 'value' => $value, 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . $url . '&limit=' . $value) ); } $url = ''; if (isset($this->request->get['filter'])) { $url .= '&filter=' . $this->request->get['filter']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $pagination = new Pagination(); $pagination->total = $product_total; $pagination->page = $page; $pagination->limit = $limit; $pagination->url = $this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $this->request->get['path'] . $url . '&page={page}'); $data['pagination'] = $pagination->render(); $data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($product_total - $limit)) ? $product_total : ((($page - 1) * $limit) + $limit), $product_total, ceil($product_total / $limit)); // http://googlewebmastercentral.blogspot.com/2011/09/pagination-with-relnext-and-relprev.html if ($page == 1) { $this->document->addLink($this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $category_info['category_id']), 'canonical'); } else { $this->document->addLink($this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $category_info['category_id'] . '&page='. $page), 'canonical'); } if ($page > 1) { $this->document->addLink($this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $category_info['category_id'] . (($page - 2) ? '&page='. ($page - 1) : '')), 'prev'); } if ($limit && ceil($product_total / $limit) > $page) { $this->document->addLink($this->url->link('product/category', 'language=' . $this->config->get('config_language') . '&path=' . $category_info['category_id'] . '&page='. ($page + 1)), 'next'); } $data['sort'] = $sort; $data['order'] = $order; $data['limit'] = $limit; $data['language'] = $this->config->get('config_language'); $data['continue'] = $this->url->link('common/home', 'language=' . $this->config->get('config_language')); $data['column_left'] = $this->load->controller('common/column_left'); $data['column_right'] = $this->load->controller('common/column_right'); $data['content_top'] = $this->load->controller('common/content_top'); $data['content_bottom'] = $this->load->controller('common/content_bottom'); $data['footer'] = $this->load->controller('common/footer'); $data['header'] = $this->load->controller('common/header'); $this->response->setOutput($this->load->view('product/category', $data)); } else { $url = ''; if (isset($this->request->get['path'])) { $url .= '&path=' . $this->request->get['path']; } if (isset($this->request->get['filter'])) { $url .= '&filter=' . $this->request->get['filter']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_error'), 'href' => $this->url->link('product/category', 'language=' . $this->config->get('config_language') . $url) ); $this->document->setTitle($this->language->get('text_error')); $data['continue'] = $this->url->link('common/home', 'language=' . $this->config->get('config_language')); $this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . ' 404 Not Found'); $data['column_left'] = $this->load->controller('common/column_left'); $data['column_right'] = $this->load->controller('common/column_right'); $data['content_top'] = $this->load->controller('common/content_top'); $data['content_bottom'] = $this->load->controller('common/content_bottom'); $data['footer'] = $this->load->controller('common/footer'); $data['header'] = $this->load->controller('common/header'); $this->response->setOutput($this->load->view('error/not_found', $data)); } } }
Felix-Ho/opencart
upload/catalog/controller/product/category.php
PHP
gpl-3.0
15,824
<?php session_start(); require_once('BDD.php'); if(isset($_POST['nom_mod']) && isset($_POST['code_mod']) && isset($_POST['cm_g']) && isset($_POST['td_g']) && isset($_POST['tp_g'])){ $req = $bdd->prepare("INSERT INTO module(nom_m,code_m,cm_g,td_g,tp_g) VALUES(:nom_mod,:code_mod,:cm_g,:td_g,:tp_g)"); $req->execute(array("nom_mod" => $_POST['nom_mod'] , "code_mod" => $_POST['code_mod'] , "cm_g" => $_POST['cm_g'] , "td_g" => $_POST['td_g'] , "tp_g" => $_POST['tp_g'])); $id_mod = $bdd->lastInsertId(); } echo("<option value='". $id_mod ."'>". $_POST["code_mod"]. " " . $_POST['nom_mod'] ."</option>"); ?>
seprote/Seprote
Seprote_Finale_DOYER/ajaxmodule.php
PHP
gpl-3.0
623
local S = farming.intllib -- Hoe registration function farming.register_hoe = function(name, def) -- Check for : prefix (register new hoes in your mod's namespace) if name:sub(1,1) ~= ":" then name = ":" .. name end -- Check def table if def.description == nil then def.description = "Hoe" end if def.inventory_image == nil then def.inventory_image = "unknown_item.png" end if def.recipe == nil then def.recipe = { {"air","air",""}, {"","group:stick",""}, {"","group:stick",""} } end if def.max_uses == nil then def.max_uses = 30 end -- Register the tool minetest.register_tool(name, { description = def.description, inventory_image = def.inventory_image, on_use = function(itemstack, user, pointed_thing) return farming.hoe_on_use(itemstack, user, pointed_thing, def.max_uses) end }) -- Register its recipe if def.material == nil then minetest.register_craft({ output = name:sub(2), recipe = def.recipe }) else minetest.register_craft({ output = name:sub(2), recipe = { {def.material, def.material, ""}, {"", "group:stick", ""}, {"", "group:stick", ""} } }) end end -- Turns dirt with group soil=1 into soil function farming.hoe_on_use(itemstack, user, pointed_thing, uses) local pt = pointed_thing -- check if pointing at a node if not pt or pt.type ~= "node" then return end local under = minetest.get_node(pt.under) local upos = pointed_thing.under if minetest.is_protected(upos, user:get_player_name()) then minetest.record_protection_violation(upos, user:get_player_name()) return end local p = {x = pt.under.x, y = pt.under.y + 1, z = pt.under.z} local above = minetest.get_node(p) -- return if any of the nodes is not registered if not minetest.registered_nodes[under.name] or not minetest.registered_nodes[above.name] then return end -- check if the node above the pointed thing is air if above.name ~= "air" then return end -- check if pointing at dirt if minetest.get_item_group(under.name, "soil") ~= 1 then return end -- turn the node into soil, wear out item and play sound minetest.set_node(pt.under, {name = "farming:soil"}) minetest.sound_play("default_dig_crumbly", {pos = pt.under, gain = 0.5}) if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/(uses-1)) end return itemstack end -- Define Hoes farming.register_hoe(":farming:hoe_wood", { description = S("Wooden Hoe"), inventory_image = "farming_tool_woodhoe.png", max_uses = 30, material = "group:wood" }) farming.register_hoe(":farming:hoe_stone", { description = S("Stone Hoe"), inventory_image = "farming_tool_stonehoe.png", max_uses = 90, material = "group:stone" }) farming.register_hoe(":farming:hoe_steel", { description = S("Steel Hoe"), inventory_image = "farming_tool_steelhoe.png", max_uses = 200, material = "default:steel_ingot" }) farming.register_hoe(":farming:hoe_bronze", { description = S("Bronze Hoe"), inventory_image = "farming_tool_bronzehoe.png", max_uses = 220, material = "default:bronze_ingot" }) farming.register_hoe(":farming:hoe_mese", { description = S("Mese Hoe"), inventory_image = "farming_tool_mesehoe.png", max_uses = 350, material = "default:mese_crystal" }) farming.register_hoe(":farming:hoe_diamond", { description = S("Diamond Hoe"), inventory_image = "farming_tool_diamondhoe.png", max_uses = 500, material = "default:diamond" })
linushsao/marsu_game-linus-v0.2
mods/plantlife/farming/hoes.lua
Lua
gpl-3.0
3,457
/** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ define([ 'mage/template', 'jquery' ], function (mageTemplate, $) { 'use strict'; describe('mage/template', function () { var templateString = 'Hello, <%= target %>', templateData = { target: 'Magento User' }, expectedString = 'Hello, Magento User', templateNode = $('<script id="hello" type="text/x-magento-template">' + templateString + '</script>'); beforeAll(function () { templateNode.appendTo(document.body); }); afterAll(function () { templateNode.remove(); }); it('compiles template function when only selector is passed', function () { var template = mageTemplate('#hello'); expect(typeof template).toBe('function'); expect(template(templateData)).toEqual(expectedString); }); it('renders template when both selector and data are passed', function () { expect(mageTemplate('#hello', templateData)).toEqual(expectedString); }); it('compiles template with string passed only', function () { var template = mageTemplate(templateString); expect(typeof template).toEqual('function'); expect(template(templateData)).toEqual(expectedString); }); it('renders template with string and data passed', function () { expect(mageTemplate(templateString, templateData)).toEqual(expectedString); }); }); });
rajmahesh/magento2-master
vendor/magento/magento2-base/dev/tests/js/jasmine/tests/lib/mage/template.test.js
JavaScript
gpl-3.0
1,624
# -*- coding: utf-8 -*- # # documentation build configuration file, created by # sphinx-quickstart on Sat Sep 27 13:23:22 2008-2009. # # This file is execfile()d with the current directory set to its # containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed # automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys import os # pip install sphinx_rtd_theme # import sphinx_rtd_theme # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. # sys.path.append(os.path.abspath('some/directory')) # sys.path.insert(0, os.path.join('ansible', 'lib')) sys.path.append(os.path.abspath(os.path.join('..', '_extensions'))) # We want sphinx to document the ansible modules contained in this repository, # not those that may happen to be installed in the version # of Python used to run sphinx. When sphinx loads in order to document, # the repository version needs to be the one that is loaded: sys.path.insert(0, os.path.abspath(os.path.join('..', '..', '..', 'lib'))) VERSION = 'devel' AUTHOR = 'Ansible, Inc' # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. # They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. # TEST: 'sphinxcontrib.fulltoc' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'pygments_lexer', 'notfound.extension'] # Later on, add 'sphinx.ext.viewcode' to the list if you want to have # colorized code generated too for references. # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'Ansible' copyright = "2019 Red Hat, Inc." # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = VERSION # The full version, including alpha/beta/rc tags. release = VERSION # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. # unused_docs = [] # List of directories, relative to source directories, that shouldn't be # searched for source files. # exclude_dirs = [] # A list of glob-style patterns that should be excluded when looking # for source files. # OBSOLETE - removing this - dharmabumstead 2018-02-06 # exclude_patterns = ['modules'] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' highlight_language = 'YAML+Jinja' # Substitutions, variables, entities, & shortcuts for text which do not need to link to anything. # For titles which should be a link, use the intersphinx anchors set at the index, chapter, and section levels, such as qi_start_: # |br| is useful for formatting fields inside of tables # |_| is a nonbreaking space; similarly useful inside of tables rst_epilog = """ .. |br| raw:: html <br> .. |_| unicode:: 0xA0 :trim: """ # Options for HTML output # ----------------------- html_theme_path = ['../_themes'] html_theme = 'sphinx_rtd_theme' html_short_title = 'Ansible Documentation' html_show_sphinx = False html_theme_options = { 'canonical_url': "https://docs.ansible.com/ansible/latest/", 'vcs_pageview_mode': 'edit' } html_context = { 'display_github': 'True', 'github_user': 'ansible', 'github_repo': 'ansible', 'github_version': 'devel/docs/docsite/rst/', 'github_module_version': 'devel/lib/ansible/modules/', 'github_root_dir': 'devel/lib/ansible', 'github_cli_version': 'devel/lib/ansible/cli/', 'current_version': version, 'latest_version': '2.9', # list specifically out of order to make latest work 'available_versions': ('latest', '2.8', '2.7', 'devel'), 'css_files': ('_static/ansible.css', # overrides to the standard theme ), } # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. # html_style = 'solar.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = 'Ansible Documentation' # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (within the static path) to place at the top of # the sidebar. # html_logo = # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = 'favicon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['../_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_use_modindex = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, the reST sources are included in the HTML build as _sources/<name>. html_copy_source = False # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = 'https://docs.ansible.com/ansible/latest' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Poseidodoc' # Configuration for sphinx-notfound-pages # with no 'notfound_template' and no 'notfound_context' set, # the extension builds 404.rst into a location-agnostic 404 page # # default is `en` - using this for the sub-site: notfound_default_language = "ansible" # default is `latest`: # setting explicitly - docsite serves up /ansible/latest/404.html # so keep this set to `latest` even on the `devel` branch # then no maintenance is needed when we branch a new stable_x.x notfound_default_version = "latest" # makes default setting explicit: notfound_no_urls_prefix = False # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). # latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). # latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class # [howto/manual]). latex_documents = [ ('index', 'ansible.tex', 'Ansible 2.2 Documentation', AUTHOR, 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # Additional stuff for the LaTeX preamble. # latex_preamble = '' # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_use_modindex = True autoclass_content = 'both' # Note: Our strategy for intersphinx mappings is to have the upstream build location as the # canonical source and then cached copies of the mapping stored locally in case someone is building # when disconnected from the internet. We then have a script to update the cached copies. # # Because of that, each entry in this mapping should have this format: # name: ('http://UPSTREAM_URL', (None, 'path/to/local/cache.inv')) # # The update script depends on this format so deviating from this (for instance, adding a third # location for the mappning to live) will confuse it. intersphinx_mapping = {'python': ('https://docs.python.org/2/', (None, '../python2.inv')), 'python3': ('https://docs.python.org/3/', (None, '../python3.inv')), 'jinja2': ('http://jinja.palletsprojects.com/', (None, '../jinja2.inv'))}
simonwydooghe/ansible
docs/docsite/rst/conf.py
Python
gpl-3.0
9,581
package com.arcusys.valamis.web.servlet.social.request import com.arcusys.valamis.web.servlet.request.{BaseRequest, Parameter} import org.scalatra.ScalatraBase object LRSToActivitySettingsRequest extends BaseRequest { val Title = "title" val MappedActivity = "mappedActivity" val MappedVerb = "mappedVerb" val Id = "id" def apply(scalatra: ScalatraBase) = new Model(scalatra) class Model(scalatra: ScalatraBase) { implicit val _scalatra = scalatra def courseId = Parameter(CourseId).intRequired def title = Parameter(Title).required def mappedActivity = Parameter(MappedActivity).option def mappedVerb = Parameter(MappedVerb).option def action = { Parameter(Action).option match { case Some(value) => LRSToActivitySettingActionType.withName(value.toUpperCase) case None => None } } def id = Parameter(Id).intRequired } }
igor-borisov/JSCORM
valamis-portlets/src/main/scala/com/arcusys/valamis/web/servlet/social/request/LRSToActivitySettingsRequest.scala
Scala
gpl-3.0
912
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "fixed_grammar.asn" * `asn1c -gen-PER` */ #include "CA-MIMO-ParametersDL-r10.h" static asn_TYPE_member_t asn_MBR_CA_MIMO_ParametersDL_r10_1[] = { { ATF_NOFLAGS, 0, offsetof(struct CA_MIMO_ParametersDL_r10, ca_BandwidthClassDL_r10), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_CA_BandwidthClass_r10, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "ca-BandwidthClassDL-r10" }, { ATF_POINTER, 1, offsetof(struct CA_MIMO_ParametersDL_r10, supportedMIMO_CapabilityDL_r10), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_MIMO_CapabilityDL_r10, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "supportedMIMO-CapabilityDL-r10" }, }; static int asn_MAP_CA_MIMO_ParametersDL_r10_oms_1[] = { 1 }; static ber_tlv_tag_t asn_DEF_CA_MIMO_ParametersDL_r10_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_TYPE_tag2member_t asn_MAP_CA_MIMO_ParametersDL_r10_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* ca-BandwidthClassDL-r10 at 3881 */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* supportedMIMO-CapabilityDL-r10 at 3882 */ }; static asn_SEQUENCE_specifics_t asn_SPC_CA_MIMO_ParametersDL_r10_specs_1 = { sizeof(struct CA_MIMO_ParametersDL_r10), offsetof(struct CA_MIMO_ParametersDL_r10, _asn_ctx), asn_MAP_CA_MIMO_ParametersDL_r10_tag2el_1, 2, /* Count of tags in the map */ asn_MAP_CA_MIMO_ParametersDL_r10_oms_1, /* Optional members */ 1, 0, /* Root/Additions */ -1, /* Start extensions */ -1 /* Stop extensions */ }; asn_TYPE_descriptor_t asn_DEF_CA_MIMO_ParametersDL_r10 = { "CA-MIMO-ParametersDL-r10", "CA-MIMO-ParametersDL-r10", SEQUENCE_free, SEQUENCE_print, SEQUENCE_constraint, SEQUENCE_decode_ber, SEQUENCE_encode_der, SEQUENCE_decode_xer, SEQUENCE_encode_xer, SEQUENCE_decode_uper, SEQUENCE_encode_uper, SEQUENCE_decode_aper, SEQUENCE_encode_aper, 0, /* Use generic outmost tag fetcher */ asn_DEF_CA_MIMO_ParametersDL_r10_tags_1, sizeof(asn_DEF_CA_MIMO_ParametersDL_r10_tags_1) /sizeof(asn_DEF_CA_MIMO_ParametersDL_r10_tags_1[0]), /* 1 */ asn_DEF_CA_MIMO_ParametersDL_r10_tags_1, /* Same as above */ sizeof(asn_DEF_CA_MIMO_ParametersDL_r10_tags_1) /sizeof(asn_DEF_CA_MIMO_ParametersDL_r10_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ asn_MBR_CA_MIMO_ParametersDL_r10_1, 2, /* Elements count */ &asn_SPC_CA_MIMO_ParametersDL_r10_specs_1 /* Additional specs */ };
massar5289/openairinterface5G
cmake_targets/oaisim_build_oai/build/CMakeFiles/Rel10/CA-MIMO-ParametersDL-r10.c
C
gpl-3.0
2,683
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle is distributed in the hope that 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Capability definitions for Moodle core. * * The capabilities are loaded into the database table when the module is * installed or updated. Whenever the capability definitions are updated, * the module version number should be bumped up. * * The system has four possible values for a capability: * CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set). * * * CAPABILITY NAMING CONVENTION * * It is important that capability names are unique. The naming convention * for capabilities that are specific to modules and blocks is as follows: * [mod/block]/<plugin_name>:<capabilityname> * * component_name should be the same as the directory name of the mod or block. * * Core moodle capabilities are defined thus: * moodle/<capabilityclass>:<capabilityname> * * Examples: mod/forum:viewpost * block/recent_activity:view * moodle/site:deleteuser * * The variable name for the capability definitions array is $capabilities * * For more information, take a look to the documentation available: * - Access API: {@link http://docs.moodle.org/dev/Access_API} * - Upgrade API: {@link http://docs.moodle.org/dev/Upgrade_API} * * @package core_access * @category access * @copyright 2006 onwards Martin Dougiamas http://dougiamas.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $capabilities = array( 'moodle/site:config' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG | RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( ) ), 'moodle/site:readallmessages' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW ) ), 'moodle/site:deleteanymessage' => array( 'riskbitmask' => RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/site:sendmessage' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, 'user' => CAP_ALLOW ) ), 'moodle/site:deleteownmessage' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW ) ), 'moodle/site:approvecourse' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/backup:backupcourse' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:backup' ), 'moodle/backup:backupsection' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/backup:backupcourse' ), 'moodle/backup:backupactivity' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/backup:backupcourse' ), 'moodle/backup:backuptargethub' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/backup:backupcourse' ), 'moodle/backup:backuptargetimport' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/backup:backupcourse' ), 'moodle/backup:downloadfile' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:backupdownload' ), 'moodle/backup:configure' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/backup:userinfo' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/backup:anonymise' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/restore:restorecourse' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:restore' ), 'moodle/restore:restoresection' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/restore:restorecourse' ), 'moodle/restore:restoreactivity' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/restore:restorecourse' ), 'moodle/restore:viewautomatedfilearea' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, ), 'moodle/restore:restoretargethub' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/restore:restorecourse' ), 'moodle/restore:restoretargetimport' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:import' ), 'moodle/restore:uploadfile' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/site:backupupload' ), 'moodle/restore:configure' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/restore:rolldates' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'coursecreator' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/restore:userinfo' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/restore:createuser' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/site:manageblocks' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/site:accessallgroups' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/site:viewfullnames' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), // In reports that give lists of users, extra information about each user's // identity (the fields configured in site option showuseridentity) will be // displayed to users who have this capability. 'moodle/site:viewuseridentity' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/site:viewreports' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/site:trustcontent' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/site:uploadusers' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), // Permission to manage filter setting overrides in subcontexts. 'moodle/filter:manage' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW, ) ), 'moodle/user:create' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/user:delete' => array( 'riskbitmask' => RISK_PERSONAL, RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/user:update' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/user:viewdetails' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'guest' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/user:viewalldetails' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/user:update' ), 'moodle/user:viewlastip' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/user:update' ), 'moodle/user:viewhiddendetails' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/user:loginas' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS | RISK_CONFIG, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), // can the user manage the system default profile page? 'moodle/user:managesyspages' => array( 'riskbitmap' => RISK_SPAM | RISK_PERSONAL | RISK_CONFIG, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), // can the user manage another user's profile page? 'moodle/user:manageblocks' => array( 'riskbitmap' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_USER ), // can the user manage their own profile page? 'moodle/user:manageownblocks' => array( 'riskbitmap' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW ) ), // can the user manage their own files? 'moodle/user:manageownfiles' => array( 'riskbitmap' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW ) ), // Can the user ignore the setting userquota? // The permissions are cloned from ignorefilesizelimits as it was partly used for that purpose. 'moodle/user:ignoreuserquota' => array( 'riskbitmap' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'clonepermissionsfrom' => 'moodle/course:ignorefilesizelimits' ), // can the user manage the system default dashboard page? 'moodle/my:configsyspages' => array( 'riskbitmap' => RISK_SPAM | RISK_PERSONAL | RISK_CONFIG, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/role:assign' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/role:review' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/role:override' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/role:safeoverride' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW ) ), 'moodle/role:manage' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/role:switchroles' => array( 'riskbitmask' => RISK_XSS | RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), // Create, update and delete course categories. (Deleting a course category // does not let you delete the courses it contains, unless you also have // moodle/course: delete.) Creating and deleting requires this permission in // the parent category. 'moodle/category:manage' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSECAT, 'archetypes' => array( 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/category:update' ), 'moodle/category:viewhiddencategories' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSECAT, 'archetypes' => array( 'coursecreator' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/category:visibility' ), // create, delete, move cohorts in system and course categories, // (cohorts with component !== null can be only moved) 'moodle/cohort:manage' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSECAT, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), // add and remove cohort members (only for cohorts where component !== null) 'moodle/cohort:assign' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSECAT, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), // View visible and hidden cohorts defined in the current context. 'moodle/cohort:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:create' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSECAT, 'archetypes' => array( 'coursecreator' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:request' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW, ) ), 'moodle/course:delete' => array( 'riskbitmask' => RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/course:update' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, ) ), /* review course enrolments - no group restrictions, it is really full access to all participants info*/ 'moodle/course:enrolreview' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW, ) ), /* add, remove, hide enrol instances in courses */ 'moodle/course:enrolconfig' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW, ) ), 'moodle/course:reviewotherusers' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW, ), 'clonepermissionsfrom' => 'moodle/role:assign' ), 'moodle/course:bulkmessaging' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:viewhiddenuserfields' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:viewhiddencourses' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'coursecreator' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:visibility' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:managefiles' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:ignorefilesizelimits' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( ) ), 'moodle/course:manageactivities' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:activityvisibility' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:viewhiddenactivities' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:viewparticipants' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:changefullname' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:update' ), 'moodle/course:changeshortname' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:update' ), 'moodle/course:changeidnumber' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:update' ), 'moodle/course:changecategory' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:update' ), 'moodle/course:changesummary' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:update' ), 'moodle/site:viewparticipants' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/course:isincompletionreports' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'student' => CAP_ALLOW, ), ), 'moodle/course:viewscales' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:managescales' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:managegroups' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:reset' => array( 'riskbitmask' => RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:viewsuspendedusers' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/blog:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'guest' => CAP_ALLOW, 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/blog:search' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'guest' => CAP_ALLOW, 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/blog:viewdrafts' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/blog:create' => array( // works in CONTEXT_SYSTEM only 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/blog:manageentries' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/blog:manageexternal' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'student' => CAP_ALLOW, 'user' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), // TODO: Remove 'moodle/blog:associatecourse' and 'moodle/blog:associatemodule' after a few releases. 'moodle/blog:associatecourse' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array() ), 'moodle/blog:associatemodule' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_MODULE, 'archetypes' => array() ), 'moodle/calendar:manageownentries' => array( // works in CONTEXT_SYSTEM only 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/calendar:managegroupentries' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/calendar:manageentries' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/user:editprofile' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/user:editownprofile' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'guest' => CAP_PROHIBIT, 'user' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/user:changeownpassword' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'guest' => CAP_PROHIBIT, 'user' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), // The next 3 might make no sense for some roles, e.g teacher, etc. // since the next level up is site. These are more for the parent role 'moodle/user:readuserposts' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/user:readuserblogs' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), // designed for parent role - not used in legacy roles 'moodle/user:viewuseractivitiesreport' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( ) ), //capabilities designed for the new message system configuration 'moodle/user:editmessageprofile' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/user:editownmessageprofile' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'guest' => CAP_PROHIBIT, 'user' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/question:managecategory' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), //new in moodle 1.9 'moodle/question:add' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:editmine' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:editall' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:viewmine' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:viewall' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:usemine' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:useall' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:movemine' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), 'moodle/question:moveall' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/question:manage' ), //END new in moodle 1.9 // Configure the installed question types. 'moodle/question:config' => array( 'riskbitmask' => RISK_CONFIG, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), // While attempting questions, the ability to flag particular questions for later reference. 'moodle/question:flag' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/site:doclinks' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:sectionvisibility' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:useremail' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:viewhiddensections' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:setcurrentsection' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:movesections' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:update' ), 'moodle/site:mnetlogintoremote' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( ) ), 'moodle/grade:viewall' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, // and CONTEXT_USER 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:viewcoursegrades' ), 'moodle/grade:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'student' => CAP_ALLOW ) ), 'moodle/grade:viewhidden' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:viewcoursegrades' ), 'moodle/grade:import' => array( 'riskbitmask' => RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), 'moodle/grade:export' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), 'moodle/grade:manage' => array( 'riskbitmask' => RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), 'moodle/grade:edit' => array( 'riskbitmask' => RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), // ability to define advanced grading forms in activities either from scratch // or from a shared template 'moodle/grade:managegradingforms' => array( 'riskbitmask' => RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), // ability to save a grading form as a new shared template and eventually edit // and remove own templates (templates originally shared by that user) 'moodle/grade:sharegradingforms' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ), ), // ability to edit and remove any shared template, even those originally shared // by other users 'moodle/grade:managesharedforms' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ), ), 'moodle/grade:manageoutcomes' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), 'moodle/grade:manageletters' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ), 'clonepermissionsfrom' => 'moodle/course:managegrades' ), 'moodle/grade:hide' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/grade:lock' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/grade:unlock' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/my:manageblocks' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW ) ), 'moodle/notes:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/notes:manage' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/tag:manage' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/tag:create' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, 'user' => CAP_ALLOW ) ), 'moodle/tag:edit' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/tag:flag' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, 'user' => CAP_ALLOW ) ), 'moodle/tag:editblocks' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/block:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'guest' => CAP_ALLOW, 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), 'moodle/block:edit' => array( 'riskbitmask' => RISK_SPAM | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_BLOCK, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/portfolio:export' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), 'moodle/comment:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'frontpage' => CAP_ALLOW, 'guest' => CAP_ALLOW, 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/comment:post' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/comment:delete' => array( 'riskbitmask' => RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/webservice:createtoken' => array( 'riskbitmask' => RISK_CONFIG | RISK_DATALOSS | RISK_SPAM | RISK_PERSONAL | RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/webservice:createmobiletoken' => array( 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'user' => CAP_ALLOW ) ), 'moodle/rating:view' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/rating:viewany' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/rating:viewall' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/rating:rate' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, 'student' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/course:publish' => array( 'captype' => 'write', 'riskbitmask' => RISK_SPAM | RISK_PERSONAL, 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW ) ), 'moodle/course:markcomplete' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, 'manager' => CAP_ALLOW ) ), 'moodle/community:add' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), 'moodle/community:download' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // Badges. 'moodle/badges:manageglobalsettings' => array( 'riskbitmask' => RISK_DATALOSS | RISK_CONFIG, 'captype' => 'write', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( 'manager' => CAP_ALLOW, ) ), // View available badges without earning them. 'moodle/badges:viewbadges' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, ) ), // Manage badges on own private badges page. 'moodle/badges:manageownbadges' => array( 'riskbitmap' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'user' => CAP_ALLOW ) ), // View public badges in other users' profiles. 'moodle/badges:viewotherbadges' => array( 'riskbitmap' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_USER, 'archetypes' => array( 'user' => CAP_ALLOW ) ), // Earn badge. 'moodle/badges:earnbadge' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'user' => CAP_ALLOW, ) ), // Create/duplicate badges. 'moodle/badges:createbadge' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // Delete badges. 'moodle/badges:deletebadge' => array( 'riskbitmask' => RISK_DATALOSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // Set up/edit badge details. 'moodle/badges:configuredetails' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // Set up/edit criteria of earning a badge. 'moodle/badges:configurecriteria' => array( 'riskbitmask' => RISK_XSS, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // Configure badge messages. 'moodle/badges:configuremessages' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // Award badge to a user. 'moodle/badges:awardbadge' => array( 'riskbitmask' => RISK_SPAM, 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), // View users who earned a specific badge without being able to award a badge. 'moodle/badges:viewawarded' => array( 'riskbitmask' => RISK_PERSONAL, 'captype' => 'read', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), 'moodle/site:forcelanguage' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_SYSTEM, 'archetypes' => array( ) ) );
jrtc27/moodle
lib/db/access.php
PHP
gpl-3.0
56,053
<?php namespace HL7\FHIR\STU3\FHIRResource\FHIRCompartmentDefinition; /*! * This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using * class definitions from HL7 FHIR (https://www.hl7.org/fhir/) * * Class creation date: February 10th, 2018 */ use HL7\FHIR\STU3\FHIRElement\FHIRBackboneElement; /** * A compartment definition that defines how resources are accessed on a server. */ class FHIRCompartmentDefinitionResource extends FHIRBackboneElement implements \JsonSerializable { /** * The name of a resource supported by the server. * @var \HL7\FHIR\STU3\FHIRElement\FHIRResourceType */ public $code = null; /** * The name of a search parameter that represents the link to the compartment. More than one may be listed because a resource may be linked to a compartment in more than one way,. * @var \HL7\FHIR\STU3\FHIRElement\FHIRString[] */ public $param = []; /** * Additional documentation about the resource and compartment. * @var \HL7\FHIR\STU3\FHIRElement\FHIRString */ public $documentation = null; /** * @var string */ private $_fhirElementName = 'CompartmentDefinition.Resource'; /** * The name of a resource supported by the server. * @return \HL7\FHIR\STU3\FHIRElement\FHIRResourceType */ public function getCode() { return $this->code; } /** * The name of a resource supported by the server. * @param \HL7\FHIR\STU3\FHIRElement\FHIRResourceType $code * @return $this */ public function setCode($code) { $this->code = $code; return $this; } /** * The name of a search parameter that represents the link to the compartment. More than one may be listed because a resource may be linked to a compartment in more than one way,. * @return \HL7\FHIR\STU3\FHIRElement\FHIRString[] */ public function getParam() { return $this->param; } /** * The name of a search parameter that represents the link to the compartment. More than one may be listed because a resource may be linked to a compartment in more than one way,. * @param \HL7\FHIR\STU3\FHIRElement\FHIRString $param * @return $this */ public function addParam($param) { $this->param[] = $param; return $this; } /** * Additional documentation about the resource and compartment. * @return \HL7\FHIR\STU3\FHIRElement\FHIRString */ public function getDocumentation() { return $this->documentation; } /** * Additional documentation about the resource and compartment. * @param \HL7\FHIR\STU3\FHIRElement\FHIRString $documentation * @return $this */ public function setDocumentation($documentation) { $this->documentation = $documentation; return $this; } /** * @return string */ public function get_fhirElementName() { return $this->_fhirElementName; } /** * @param mixed $data */ public function __construct($data = []) { if (is_array($data)) { if (isset($data['code'])) { $this->setCode($data['code']); } if (isset($data['param'])) { if (is_array($data['param'])) { foreach ($data['param'] as $d) { $this->addParam($d); } } else { throw new \InvalidArgumentException('"param" must be array of objects or null, '.gettype($data['param']).' seen.'); } } if (isset($data['documentation'])) { $this->setDocumentation($data['documentation']); } } else if (null !== $data) { throw new \InvalidArgumentException('$data expected to be array of values, saw "'.gettype($data).'"'); } parent::__construct($data); } /** * @return string */ public function __toString() { return $this->get_fhirElementName(); } /** * @return array */ public function jsonSerialize() { $json = parent::jsonSerialize(); if (isset($this->code)) { $json['code'] = $this->code; } if (0 < count($this->param)) { $json['param'] = []; foreach ($this->param as $param) { $json['param'][] = $param; } } if (isset($this->documentation)) { $json['documentation'] = $this->documentation; } return $json; } /** * @param boolean $returnSXE * @param \SimpleXMLElement $sxe * @return string|\SimpleXMLElement */ public function xmlSerialize($returnSXE = false, $sxe = null) { if (null === $sxe) { $sxe = new \SimpleXMLElement('<CompartmentDefinitionResource xmlns="http://hl7.org/fhir"></CompartmentDefinitionResource>'); } parent::xmlSerialize(true, $sxe); if (isset($this->code)) { $this->code->xmlSerialize(true, $sxe->addChild('code')); } if (0 < count($this->param)) { foreach ($this->param as $param) { $param->xmlSerialize(true, $sxe->addChild('param')); } } if (isset($this->documentation)) { $this->documentation->xmlSerialize(true, $sxe->addChild('documentation')); } if ($returnSXE) { return $sxe; } return $sxe->saveXML(); } }
vaibhavgupta3110/openemr
phpfhir/HL7/FHIR/STU3/src/FHIRResource/FHIRCompartmentDefinition/FHIRCompartmentDefinitionResource.php
PHP
gpl-3.0
5,634
/* written by vbabin-at-ncsu-dot-edu in 05/2008 */ #include <stdio.h> #include <assert.h> #include <stdlib.h> #include "ncsu-penalties.h" /******************************************************************************/ static void *xmalloc(size_t n) { void *ptr; ptr = malloc(n); if (ptr == NULL) { fputs("** Error ** : out of memory\n", stdout); exit(EXIT_FAILURE); } return ptr; } /******************************************************************************/ static size_t binomial_coefficient(size_t n, size_t k) { size_t i, t, b; assert(n > 0); assert(k > 0); assert(n >= k); for (i = k, t = 1; i != n; ++i) t *= i + 1; for (i = 0, b = 1; i + k != n; ++i) b *= i + 1; return (t/b); } /******************************************************************************/ /* * Iterates through all k-combinations of (0, ..., n - 1), i.e., * for n = 4 and k = 2 the output is (0, 1), (0, 2), (0, 3), * (1, 2), (1, 3), (2, 3) */ typedef struct { size_t n, k; /* elements go from 0 to n - 1 ; 1 <= k <= n */ size_t nc, *c; /* size == nc >= k */ } combination_t; static void combination_init(combination_t *self) { assert(self != NULL); self->n = 0; self->k = 0; self->nc = 0; self->c = NULL; } static void combination_fini(combination_t *self) { assert(self != NULL); if (self->c != NULL) { assert(self->nc > 0); free(self->c); } } static void combination_setup(combination_t *self, size_t n, size_t k) { assert(n != 0); assert(k != 0); assert(k <= n); assert(self != NULL); self->n = n; self->k = k; if (k > self->nc) { if (self->c != NULL) free(self->c); self->c = (size_t *) xmalloc(k*sizeof(size_t)); self->nc = k; } self->c[0] = self->n; /* impossible value */ } static size_t* combination_next(combination_t *self) { size_t r, n, i, mark; assert(self != NULL); assert(self->n > 0); assert(self->k > 0); assert(self->k <= self->n); assert(self->c != NULL); assert(self->nc >= self->k); if (self->c[0] == self->n) { for (i = 0; i < self->k; ++i) self->c[i] = i; return self->c; } r = self->k - 1; n = self->n - 1; for (mark = self->k;; --r, --n) { if (self->c[r] == n) { if (r != 0) { mark = --r; ++r; continue; } else { self->c[0] = self->n; return NULL; } } else { if (mark < self->k) { size_t nm = self->c[mark] + 1; for (i = mark; i != self->k; ++i, ++nm) self->c[i] = nm; return self->c; } for (i = 0; i < self->n; ++i) { if (self->c[r] == i) { self->c[r] = ++i; return self->c; } } } } return NULL; /* should not be reached */ } #define combination_is_null(self) ((self)->c[0] == (self)->n) #ifdef ENABLE_COMBINATION_MAIN int main(int argc, char** argv) { const size_t *c; combination_t cmb; combination_init(&cmb); combination_setup(&cmb, 7, 3); for (c = combination_next(&cmb); c != NULL; c = combination_next(&cmb)) { printf("%lu %lu %lu\n", (unsigned long) c[0], (unsigned long) c[1], (unsigned long) c[2]); } combination_fini(&cmb); exit(EXIT_SUCCESS); } #endif /* ENABLE_COMBINATION_MAIN */ /******************************************************************************/ /* * Iterates through non-negative integer solutions (c[0], ..., c[K - 1]) of * c[0]*1 + ... + c[K - 1]*K = N, (both K and N are positive integers). The * algorithm is from: * * Frank Stockmal * "Algorithm 95: Generation of partitions in part-count form", * Communications of the ACM, Volume 5, Issue 6 (June 1962), * Page 344, 1962 */ typedef struct { size_t K, N; size_t nc, *c; /* size == nc >= K */ } int_part_t; static void int_part_init(int_part_t *self) { assert(self != NULL); self->K = 0; self->N = 0; self->nc = 0; self->c = NULL; } static void int_part_fini(int_part_t *self) { assert(self != NULL); if (self->c != NULL) { assert(self->nc > 0); free(self->c); } } static void int_part_setup(int_part_t *self, size_t K, size_t N) { assert(K != 0); assert(N != 0); assert(self != NULL); self->N = N; self->K = K; if (K > self->nc) { if (self->c != NULL) free(self->c); self->c = (size_t *) xmalloc(K*sizeof(size_t)); self->nc = K; } self->c[0] = N + 1; /* impossible value */ } static const size_t* int_part_next(int_part_t *self) { size_t i, j, a; assert(self != NULL); assert(self->K != 0); assert(self->N != 0); assert(self->c != NULL); assert(self->nc >= self->K); /* K == 1 case first */ if (self->K == 1 && self->c[0] == self->N) { self->c[0] = self->N + 1; return NULL; } if (self->c[0] == self->N + 1) goto L3; j = 1; a = self->c[0]; L0: if (a <= j) goto L2; ++(self->c[j]); self->c[0] = a - j - 1; L1: for (i = 1; i < j; ++i) self->c[i] = 0; goto L4; L2: if (j + 1 == self->K) { self->c[0] = self->N + 1; /* impossible value */ return NULL; } a += (j + 1)*self->c[j]; ++j; goto L0; L3: /* the first partition : N*1 + 0*2 + ... + 0*K */ self->c[0] = self->N; j = self->K; goto L1; L4: return self->c; } /******************************************************************************/ #ifdef ENABLE_INT_PART_MAIN int main(int argc, char** argv) { size_t N = 0, K = 0; const size_t *t; int_part_t iter; int_part_init(&iter); /* constructor */ if (argc > 1) { char* endptr; N = (size_t) strtoul(argv[1], &endptr, 10); if (endptr == argv[1]) N = 0; } if (argc > 2) { char* endptr; K = (size_t) strtoul(argv[2], &endptr, 10); if (endptr == argv[2]) K = 0; } if (N == 0) N = 7; if (K == 0) K = 3; int_part_setup(&iter, K, N); for (t = int_part_next(&iter); t != NULL; t = int_part_next(&iter)) { printf("%lu = ", (unsigned long) iter.N); for (K = 0; K + 1 < iter.K; ++K) printf("%lu*%lu + ", (unsigned long) t[K], (unsigned long) K + 1); printf("%lu*%lu\n", (unsigned long) t[K], (unsigned long) K + 1); } int_part_fini(&iter); /* destructor */ exit(EXIT_SUCCESS); } #endif /* ENABLE_INT_PART_MAIN */ /******************************************************************************/ size_t ncsu_penalties_size(size_t N, const size_t *sizes, size_t g) { int_part_t prt; size_t i, result; const size_t *tpl; assert(g > 0); assert(g <= N); assert(sizes != NULL); result = 0; int_part_init(&prt); int_part_setup(&prt, N, g); /* go through partitions */ for (tpl = int_part_next(&prt); tpl != NULL; tpl = int_part_next(&prt)) { /* check if 'tpl' is applicable */ for (i = 0; i < g; ++i) { if (tpl[i] > sizes[i]) { i = g + 1; /* impossible value */ break; } } /* too few elements in some set, skip this partition */ if (i == g + 1) continue; /* count the size for this partition (keep it in 'N') */ for (N = 1, i = 0; i < g; ++i) { if (tpl[i] != 0) N *= binomial_coefficient(sizes[i], tpl[i]); } /* accumulate it */ result += N; } int_part_fini(&prt); return result; } /******************************************************************************/ void ncsu_penalties(size_t N, const size_t *sizes, size_t g, ncsu_penalty_func_t cb, void *cb_data) { size_t i; int_part_t prt; combination_t *cmb; ncsu_penalty_pair_t *pairs; const size_t *tpl; assert(g > 0); assert(g <= N); assert(sizes != NULL); assert(cb != NULL); pairs = (ncsu_penalty_pair_t *) xmalloc(N*sizeof(ncsu_penalty_pair_t)); cmb = (combination_t *) xmalloc(N*sizeof(combination_t)); for (i = 0; i < N; ++i) combination_init(cmb + i); int_part_init(&prt); int_part_setup(&prt, N, g); /* go through partitions */ for (tpl = int_part_next(&prt); tpl != NULL; tpl = int_part_next(&prt)) { size_t last = 0; /* check if 'tpl' is applicable */ for (i = 0; i < g; ++i) { if (tpl[i] > sizes[i]) { i = g + 1; /* impossible value */ break; } } /* too few elements in some set, skip this partition */ if (i == g + 1) continue; /* setup the combinations */ for (i = 0; i < g; ++i) { if (tpl[i] != 0) { assert(tpl[i] <= N); combination_setup(cmb + i, sizes[i], tpl[i]); (void) combination_next(cmb + i); last = i; } } /* go through Cartesian product of the applicable combinations */ while (1) { size_t npairs = 0; /* report current element */ for (i = 0; i < g; ++i) { if (tpl[i] != 0) { /* use these combination */ size_t l; for (l = 0; l < cmb[i].k; ++l) { assert(npairs < N); pairs[npairs].set_id = i; pairs[npairs].element_id = cmb[i].c[l]; ++npairs; } } /* tpl[i] != 0 */ } assert(npairs > 0); (*cb)(npairs, pairs, cb_data); /* advance to the next one */ for (i = 0; i < g; ++i) { if (tpl[i] != 0) { if (combination_next(cmb + i) != NULL) { break; } else { if (i == last) break; (void) combination_next(cmb + i); } } /* tpl[i] != 0 */ } /* advance to a next partition */ if (i == last && combination_is_null(cmb + i)) break; } /* while (1) */ } /* call destructors, free allocated memory */ int_part_fini(&prt); for (i = 0; i < N; ++i) combination_fini(cmb + i); free(cmb); free(pairs); } /******************************************************************************/
choderalab/ambermini
antechamber/ncsu-penalties.c
C
gpl-3.0
10,927
/* -*- buffer-read-only: t -*- vi: set ro: */ /* DO NOT EDIT! GENERATED AUTOMATICALLY! */ /* Test of <sys/stat.h> substitute. Copyright (C) 2007-2010 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* Written by Bruno Haible <[email protected]>, 2007. */ #include <config.h> #include <sys/stat.h> #include "verify.h" /* Check the existence of some macros. */ int a[] = { S_IFMT, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFREG, #ifdef S_IFLNK /* missing on mingw and djgpp */ S_IFLNK, #endif #ifdef S_IFSOCK /* missing on mingw and djgpp */ S_IFSOCK, #endif S_IRWXU, S_IRUSR, S_IWUSR, S_IXUSR, S_IRWXG, S_IRGRP, S_IWGRP, S_IXGRP, S_IRWXO, S_IROTH, S_IWOTH, S_IXOTH, S_ISUID, S_ISGID, S_ISVTX, S_ISBLK (S_IFREG), S_ISCHR (S_IFREG), S_ISDIR (S_IFREG), S_ISFIFO (S_IFREG), S_ISREG (S_IFREG), S_ISLNK (S_IFREG), S_ISSOCK (S_IFREG), S_ISDOOR (S_IFREG), S_ISMPB (S_IFREG), S_ISNAM (S_IFREG), S_ISNWK (S_IFREG), S_ISPORT (S_IFREG), S_ISCTG (S_IFREG), S_ISOFD (S_IFREG), S_ISOFL (S_IFREG), S_ISWHT (S_IFREG) }; /* Sanity checks. */ verify (S_IRWXU == (S_IRUSR | S_IWUSR | S_IXUSR)); verify (S_IRWXG == (S_IRGRP | S_IWGRP | S_IXGRP)); verify (S_IRWXO == (S_IROTH | S_IWOTH | S_IXOTH)); verify (S_ISBLK (S_IFBLK)); verify (!S_ISBLK (S_IFCHR)); verify (!S_ISBLK (S_IFDIR)); verify (!S_ISBLK (S_IFIFO)); verify (!S_ISBLK (S_IFREG)); #ifdef S_IFLNK verify (!S_ISBLK (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISBLK (S_IFSOCK)); #endif verify (!S_ISCHR (S_IFBLK)); verify (S_ISCHR (S_IFCHR)); verify (!S_ISCHR (S_IFDIR)); verify (!S_ISCHR (S_IFIFO)); verify (!S_ISCHR (S_IFREG)); #ifdef S_IFLNK verify (!S_ISCHR (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISCHR (S_IFSOCK)); #endif verify (!S_ISDIR (S_IFBLK)); verify (!S_ISDIR (S_IFCHR)); verify (S_ISDIR (S_IFDIR)); verify (!S_ISDIR (S_IFIFO)); verify (!S_ISDIR (S_IFREG)); #ifdef S_IFLNK verify (!S_ISDIR (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISDIR (S_IFSOCK)); #endif verify (!S_ISFIFO (S_IFBLK)); verify (!S_ISFIFO (S_IFCHR)); verify (!S_ISFIFO (S_IFDIR)); verify (S_ISFIFO (S_IFIFO)); verify (!S_ISFIFO (S_IFREG)); #ifdef S_IFLNK verify (!S_ISFIFO (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISFIFO (S_IFSOCK)); #endif verify (!S_ISREG (S_IFBLK)); verify (!S_ISREG (S_IFCHR)); verify (!S_ISREG (S_IFDIR)); verify (!S_ISREG (S_IFIFO)); verify (S_ISREG (S_IFREG)); #ifdef S_IFLNK verify (!S_ISREG (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISREG (S_IFSOCK)); #endif verify (!S_ISLNK (S_IFBLK)); verify (!S_ISLNK (S_IFCHR)); verify (!S_ISLNK (S_IFDIR)); verify (!S_ISLNK (S_IFIFO)); verify (!S_ISLNK (S_IFREG)); #ifdef S_IFLNK verify (S_ISLNK (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISLNK (S_IFSOCK)); #endif verify (!S_ISSOCK (S_IFBLK)); verify (!S_ISSOCK (S_IFCHR)); verify (!S_ISSOCK (S_IFDIR)); verify (!S_ISSOCK (S_IFIFO)); verify (!S_ISSOCK (S_IFREG)); #ifdef S_IFLNK verify (!S_ISSOCK (S_IFLNK)); #endif #ifdef S_IFSOCK verify (S_ISSOCK (S_IFSOCK)); #endif verify (!S_ISDOOR (S_IFBLK)); verify (!S_ISDOOR (S_IFCHR)); verify (!S_ISDOOR (S_IFDIR)); verify (!S_ISDOOR (S_IFIFO)); verify (!S_ISDOOR (S_IFREG)); #ifdef S_IFLNK verify (!S_ISDOOR (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISDOOR (S_IFSOCK)); #endif verify (!S_ISMPB (S_IFBLK)); verify (!S_ISMPB (S_IFCHR)); verify (!S_ISMPB (S_IFDIR)); verify (!S_ISMPB (S_IFIFO)); verify (!S_ISMPB (S_IFREG)); #ifdef S_IFLNK verify (!S_ISMPB (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISMPB (S_IFSOCK)); #endif verify (!S_ISNAM (S_IFBLK)); verify (!S_ISNAM (S_IFCHR)); verify (!S_ISNAM (S_IFDIR)); verify (!S_ISNAM (S_IFIFO)); verify (!S_ISNAM (S_IFREG)); #ifdef S_IFLNK verify (!S_ISNAM (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISNAM (S_IFSOCK)); #endif verify (!S_ISNWK (S_IFBLK)); verify (!S_ISNWK (S_IFCHR)); verify (!S_ISNWK (S_IFDIR)); verify (!S_ISNWK (S_IFIFO)); verify (!S_ISNWK (S_IFREG)); #ifdef S_IFLNK verify (!S_ISNWK (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISNWK (S_IFSOCK)); #endif verify (!S_ISPORT (S_IFBLK)); verify (!S_ISPORT (S_IFCHR)); verify (!S_ISPORT (S_IFDIR)); verify (!S_ISPORT (S_IFIFO)); verify (!S_ISPORT (S_IFREG)); #ifdef S_IFLNK verify (!S_ISPORT (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISPORT (S_IFSOCK)); #endif verify (!S_ISCTG (S_IFBLK)); verify (!S_ISCTG (S_IFCHR)); verify (!S_ISCTG (S_IFDIR)); verify (!S_ISCTG (S_IFIFO)); verify (!S_ISCTG (S_IFREG)); #ifdef S_IFLNK verify (!S_ISCTG (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISCTG (S_IFSOCK)); #endif verify (!S_ISOFD (S_IFBLK)); verify (!S_ISOFD (S_IFCHR)); verify (!S_ISOFD (S_IFDIR)); verify (!S_ISOFD (S_IFIFO)); verify (!S_ISOFD (S_IFREG)); #ifdef S_IFLNK verify (!S_ISOFD (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISOFD (S_IFSOCK)); #endif verify (!S_ISOFL (S_IFBLK)); verify (!S_ISOFL (S_IFCHR)); verify (!S_ISOFL (S_IFDIR)); verify (!S_ISOFL (S_IFIFO)); verify (!S_ISOFL (S_IFREG)); #ifdef S_IFLNK verify (!S_ISOFL (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISOFL (S_IFSOCK)); #endif verify (!S_ISWHT (S_IFBLK)); verify (!S_ISWHT (S_IFCHR)); verify (!S_ISWHT (S_IFDIR)); verify (!S_ISWHT (S_IFIFO)); verify (!S_ISWHT (S_IFREG)); #ifdef S_IFLNK verify (!S_ISWHT (S_IFLNK)); #endif #ifdef S_IFSOCK verify (!S_ISWHT (S_IFSOCK)); #endif /* POSIX 2008 requires traditional encoding of permission constants. */ verify (S_IRWXU == 00700); verify (S_IRUSR == 00400); verify (S_IWUSR == 00200); verify (S_IXUSR == 00100); verify (S_IRWXG == 00070); verify (S_IRGRP == 00040); verify (S_IWGRP == 00020); verify (S_IXGRP == 00010); verify (S_IRWXO == 00007); verify (S_IROTH == 00004); verify (S_IWOTH == 00002); verify (S_IXOTH == 00001); verify (S_ISUID == 04000); verify (S_ISGID == 02000); verify (S_ISVTX == 01000); #if ((0 <= UTIME_NOW && UTIME_NOW < 1000000000) \ || (0 <= UTIME_OMIT && UTIME_OMIT < 1000000000) \ || UTIME_NOW == UTIME_OMIT) invalid UTIME macros #endif /* Check the existence of some types. */ nlink_t t1; struct timespec t2; int main (void) { return 0; }
ystk/debian-coreutils
gnulib-tests/test-sys_stat.c
C
gpl-3.0
6,705
<?php include('header.php'); if (!empty($_GET['id_schedule'])) { $request = new Api(); $request -> add_request('removeSchedule', array($_GET['id_schedule'])); $result = $request -> send_request(); } ?>
taccons/Domoleaf
www/form/form_remove_schedule.php
PHP
gpl-3.0
209
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix */ #ifndef _Included_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix #define _Included_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix #ifdef __cplusplus extern "C" { #endif /* * Class: net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix * Method: multMatrices * Signature: ([DII[DII[DDDZZ)V */ JNIEXPORT void JNICALL Java_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix_multMatrices (JNIEnv *, jclass, jdoubleArray, jint, jint, jdoubleArray, jint, jint, jdoubleArray, jdouble, jdouble, jboolean, jboolean); /* * Class: net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix * Method: solveLSdgelsd * Signature: ([DII[DID[I)I */ JNIEXPORT jint JNICALL Java_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix_solveLSdgelsd (JNIEnv *, jclass, jdoubleArray, jint, jint, jdoubleArray, jint, jdouble, jintArray); /* * Class: net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix * Method: solveLSdgelsy * Signature: ([DII[DID[I)I */ JNIEXPORT jint JNICALL Java_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix_solveLSdgelsy (JNIEnv *, jclass, jdoubleArray, jint, jint, jdoubleArray, jint, jdouble, jintArray); /* * Class: net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix * Method: singularValueDecompositionDgesvd * Signature: (CCII[DI[D[DI[DI)I */ JNIEXPORT jint JNICALL Java_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix_singularValueDecompositionDgesvd (JNIEnv *, jclass, jchar, jchar, jint, jint, jdoubleArray, jint, jdoubleArray, jdoubleArray, jint, jdoubleArray, jint); /* * Class: net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix * Method: singularValueDecompositionDgesdd * Signature: (CII[DI[D[DI[DI)I */ JNIEXPORT jint JNICALL Java_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix_singularValueDecompositionDgesdd (JNIEnv *, jclass, jchar, jint, jint, jdoubleArray, jint, jdoubleArray, jdoubleArray, jint, jdoubleArray, jint); /* * Class: net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix * Method: eigenValueSymmetricDecomposition * Signature: (I[D[D[D)I */ JNIEXPORT jint JNICALL Java_net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix_eigenValueSymmetricDecomposition (JNIEnv *, jclass, jint, jdoubleArray, jdoubleArray, jdoubleArray); #ifdef __cplusplus } #endif #endif
guilherme-pereira/tassel4-poly
tassel4-poly/build/classes/net/maizegenetics/matrixalgebra/jni/net_maizegenetics_matrixalgebra_Matrix_BlasDoubleMatrix.h
C
gpl-3.0
2,496
/* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser 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 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 <http://www.gnu.org/licenses/>. * * Authored by: Thomas Voß <[email protected]> */ #include "backtrace.h" #include <cxxabi.h> #include <execinfo.h> namespace bt = core::posix::backtrace; namespace impl { std::tuple<std::string, bool> demangle(const std::string& symbol) { int status = 1; auto result = abi::__cxa_demangle(symbol.c_str(), nullptr, nullptr, &status); if (!result || status != 0) { return std::make_tuple(std::string(), false); } std::string s{result}; ::free(result); return std::make_tuple(s, true); } struct Frame : public bt::Frame { struct Symbol : public bt::Frame::Symbol { Symbol(const char* symbol) : raw_(symbol) { auto first = raw_.find_first_of("("); auto last = raw_.find_last_of(")"); if (first != std::string::npos && last != std::string::npos) { auto mangled_symbol = raw_.substr(first+1, (last-1) - (first+1)); auto plus = mangled_symbol.find_first_of("+"); if (plus != std::string::npos) mangled_symbol.erase(plus); std::tie(demangled_, is_cxx_) = demangle(mangled_symbol); if (!is_cxx_) demangled_ = raw_; } } bool is_cxx() const { return is_cxx_; } std::string demangled() const { return demangled_; } std::string raw() const { return raw_; } std::string raw_; std::string demangled_; bool is_cxx_ = false; }; std::size_t depth_; void* frame_pointer_; Symbol symbol_; Frame(std::size_t depth, void* frame_pointer, const char* symbol) : depth_(depth), frame_pointer_(frame_pointer), symbol_(symbol) { } std::size_t depth() const { return depth_; } virtual void* frame_pointer() const { return frame_pointer_; } const Symbol& symbol() const { return symbol_; } }; } std::shared_ptr<bt::Frame::Symbol> bt::Frame::Symbol::for_testing_from_raw_symbol(const char* symbol) { return std::shared_ptr<bt::Frame::Symbol>(new impl::Frame::Symbol(symbol)); } void bt::visit_with_handler(const bt::FrameHandler& handler) { static const unsigned int max_frames=64; void *frames[max_frames]; auto frame_count = ::backtrace(frames, max_frames); auto symbols = ::backtrace_symbols(frames, frame_count); struct Scope { Scope(char** symbols) : symbols(symbols) { } ~Scope() { ::free(symbols); } char** symbols = nullptr; } scope{symbols}; for (int i = 0; i < frame_count; i++) { impl::Frame frame(i, frames[i], symbols[i]); if (!handler(frame)) return; } }
AnboxU/anbox
external/process-cpp-minimal/src/core/posix/backtrace.cpp
C++
gpl-3.0
3,728
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, Benno Joy <[email protected]> # # This module 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 software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. import time try: from novaclient.v1_1 import client as nova_client try: from neutronclient.neutron import client except ImportError: from quantumclient.quantum import client from keystoneclient.v2_0 import client as ksclient HAVE_DEPS = True except ImportError: HAVE_DEPS = False ANSIBLE_METADATA = {'status': ['deprecated'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: quantum_floating_ip_associate version_added: "1.2" author: "Benno Joy (@bennojoy)" deprecated: Deprecated in 2.0. Use M(os_floating_ip) instead. short_description: Associate or disassociate a particular floating IP with an instance description: - Associates or disassociates a specific floating IP with a particular instance options: login_username: description: - login username to authenticate to keystone required: true default: admin login_password: description: - password of login user required: true default: 'yes' login_tenant_name: description: - the tenant name of the login user required: true default: true auth_url: description: - the keystone url for authentication required: false default: http://127.0.0.1:35357/v2.0/ region_name: description: - name of the region required: false default: None state: description: - indicates the desired state of the resource choices: ['present', 'absent'] default: present instance_name: description: - name of the instance to which the public IP should be assigned required: true default: None ip_address: description: - floating ip that should be assigned to the instance required: true default: None requirements: - "python >= 2.6" - "python-novaclient" - "python-neutronclient or python-quantumclient" - "python-keystoneclient" ''' EXAMPLES = ''' - name: Associate a specific floating IP with an Instance quantum_floating_ip_associate: state: present login_username: admin login_password: admin login_tenant_name: admin ip_address: 1.1.1.1 instance_name: vm1 ''' def _get_ksclient(module, kwargs): try: kclient = ksclient.Client(username=kwargs.get('login_username'), password=kwargs.get('login_password'), tenant_name=kwargs.get('login_tenant_name'), auth_url=kwargs.get('auth_url')) except Exception as e: module.fail_json(msg = "Error authenticating to the keystone: %s " % e.message) global _os_keystone _os_keystone = kclient return kclient def _get_endpoint(module, ksclient): try: endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') except Exception as e: module.fail_json(msg = "Error getting network endpoint: %s" % e.message) return endpoint def _get_neutron_client(module, kwargs): _ksclient = _get_ksclient(module, kwargs) token = _ksclient.auth_token endpoint = _get_endpoint(module, _ksclient) kwargs = { 'token': token, 'endpoint_url': endpoint } try: neutron = client.Client('2.0', **kwargs) except Exception as e: module.fail_json(msg = "Error in connecting to neutron: %s " % e.message) return neutron def _get_server_state(module, nova): server_info = None server = None try: for server in nova.servers.list(): if server: info = server._info if info['name'] == module.params['instance_name']: if info['status'] != 'ACTIVE' and module.params['state'] == 'present': module.fail_json(msg="The VM is available but not Active. state:" + info['status']) server_info = info break except Exception as e: module.fail_json(msg = "Error in getting the server list: %s" % e.message) return server_info, server def _get_port_id(neutron, module, instance_id): kwargs = dict(device_id = instance_id) try: ports = neutron.list_ports(**kwargs) except Exception as e: module.fail_json( msg = "Error in listing ports: %s" % e.message) if not ports['ports']: return None return ports['ports'][0]['id'] def _get_floating_ip_id(module, neutron): kwargs = { 'floating_ip_address': module.params['ip_address'] } try: ips = neutron.list_floatingips(**kwargs) except Exception as e: module.fail_json(msg = "error in fetching the floatingips's %s" % e.message) if not ips['floatingips']: module.fail_json(msg = "Could find the ip specified in parameter, Please check") ip = ips['floatingips'][0]['id'] if not ips['floatingips'][0]['port_id']: state = "detached" else: state = "attached" return state, ip def _update_floating_ip(neutron, module, port_id, floating_ip_id): kwargs = { 'port_id': port_id } try: result = neutron.update_floatingip(floating_ip_id, {'floatingip': kwargs}) except Exception as e: module.fail_json(msg = "There was an error in updating the floating ip address: %s" % e.message) module.exit_json(changed = True, result = result, public_ip=module.params['ip_address']) def main(): argument_spec = openstack_argument_spec() argument_spec.update(dict( ip_address = dict(required=True), instance_name = dict(required=True), state = dict(default='present', choices=['absent', 'present']) )) module = AnsibleModule(argument_spec=argument_spec) if not HAVE_DEPS: module.fail_json(msg='python-novaclient, python-keystoneclient, and either python-neutronclient or python-quantumclient are required') try: nova = nova_client.Client(module.params['login_username'], module.params['login_password'], module.params['login_tenant_name'], module.params['auth_url'], service_type='compute') except Exception as e: module.fail_json( msg = " Error in authenticating to nova: %s" % e.message) neutron = _get_neutron_client(module, module.params) state, floating_ip_id = _get_floating_ip_id(module, neutron) if module.params['state'] == 'present': if state == 'attached': module.exit_json(changed = False, result = 'attached', public_ip=module.params['ip_address']) server_info, server_obj = _get_server_state(module, nova) if not server_info: module.fail_json(msg = " The instance name provided cannot be found") port_id = _get_port_id(neutron, module, server_info['id']) if not port_id: module.fail_json(msg = "Cannot find a port for this instance, maybe fixed ip is not assigned") _update_floating_ip(neutron, module, port_id, floating_ip_id) if module.params['state'] == 'absent': if state == 'detached': module.exit_json(changed = False, result = 'detached') if state == 'attached': _update_floating_ip(neutron, module, None, floating_ip_id) module.exit_json(changed = True, result = "detached") # this is magic, see lib/ansible/module.params['common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
camradal/ansible
lib/ansible/modules/cloud/openstack/_quantum_floating_ip_associate.py
Python
gpl-3.0
8,337
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM is distributed in the hope that 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::searchableSurfaces Description Container for searchableSurfaces. SourceFiles searchableSurfaces.C \*---------------------------------------------------------------------------*/ #ifndef searchableSurfaces_H #define searchableSurfaces_H #include "searchableSurface.H" #include "labelPair.H" #include "writer.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // Forward declaration of classes class triSurface; /*---------------------------------------------------------------------------*\ Class searchableSurfaces Declaration \*---------------------------------------------------------------------------*/ class searchableSurfaces : public PtrList<searchableSurface> { // Private data //- Surface names wordList names_; //- Region names per surface List<wordList> regionNames_; ////- From global region name to surface and region on surface //HashTable<labelPair> regionNames_; //- Indices of all surfaces. Precalculated and stored. labelList allSurfaces_; // Private Member Functions //- Is edge on face static bool connected ( const triSurface& s, const label edgeI, const pointIndexHit& hit ); //- Disallow default bitwise copy construct searchableSurfaces(const searchableSurfaces&); //- Disallow default bitwise assignment void operator=(const searchableSurfaces&); public: ClassName("searchableSurfaces"); // Constructors //- Construct with length specified. Fill later. explicit searchableSurfaces(const label); ////- Construct from list of dictionaries //searchableSurfaces(const IOobject&, const PtrList<dictionary>&); //- Construct from dictionary searchableSurfaces(const IOobject&, const dictionary&); // Member Functions const wordList& names() const { return names_; } wordList& names() { return names_; } const List<wordList>& regionNames() const { return regionNames_; } List<wordList>& regionNames() { return regionNames_; } ////- If adding surfaces 'by hand' //HashTable<labelPair>& regionNames() //{ // return regionNames_; //} ////- Get surface and region for a name //const labelPair& surfaceRegion(const word& globalRegion) const //{ // return regionNames_[globalRegion]; //} //- Find index of surface. Return -1 if not found. label findSurfaceID(const word& name) const; // Multiple point queries. //- Find any intersection. Return hit point information and // surface number. If multiple surfaces hit the first surface // is returned, not necessarily the nearest (to start). void findAnyIntersection ( const pointField& start, const pointField& end, labelList& surfaces, List<pointIndexHit>& ) const; //- Find all intersections in order from start to end. Returns for // every hit the surface and the hit info. void findAllIntersections ( const pointField& start, const pointField& end, labelListList& surfaces, List<List<pointIndexHit> >& ) const; //Find intersections of edge nearest to both endpoints. void findNearestIntersection ( const pointField& start, const pointField& end, labelList& surface1, List<pointIndexHit>& hit1, labelList& surface2, List<pointIndexHit>& hit2 ) const; //- Find nearest. Return -1 (and a miss()) or surface and nearest // point. void findNearest ( const pointField&, const scalarField& nearestDistSqr, labelList& surfaces, List<pointIndexHit>& ) const; //- Calculate bounding box boundBox bounds() const; // Single point queries //- Calculate point which is on a set of surfaces. pointIndexHit facesIntersection ( const scalar initialDistSqr, const scalar convergenceDistSqr, const point& start ) const; // Checking //- Are all surfaces closed and manifold bool checkClosed(const bool report) const; //- Are all (triangulated) surfaces consistent normal orientation bool checkNormalOrientation(const bool report) const; //- Are all bounding boxes of similar size bool checkSizes(const scalar maxRatio, const bool report) const; //- Do surfaces self-intersect or intersect others bool checkIntersection ( const scalar tol, const autoPtr<writer<scalar> >&, const bool report ) const; //- Check triangle quality bool checkQuality ( const scalar minQuality, const bool report ) const; //- All topological checks. Return number of failed checks label checkTopology(const bool report) const; //- All geometric checks. Return number of failed checks label checkGeometry ( const scalar maxRatio, const scalar tolerance, const autoPtr<writer<scalar> >& setWriter, const scalar minQuality, const bool report ) const; //- Write some stats void writeStats(const List<wordList>&, Ostream&) const; // Member Operators //- Return const and non-const reference to searchableSurface by index. using PtrList<searchableSurface>::operator[]; //- Return const reference to searchableSurface by name. const searchableSurface& operator[](const word&) const; //- Return reference to searchableSurface by name. searchableSurface& operator[](const word&); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
firelab/OpenFOAM-2.2.x
src/meshTools/searchableSurface/searchableSurfaces.H
C++
gpl-3.0
7,943
### Use cases Different examples of use cases can be viewed below: ###Content: * [Landing](Landing.md)
one-love/one-love
use_cases/README.md
Markdown
gpl-3.0
105
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Windows.Input; namespace Rubberduck.UI.Command.MenuItems.ToolStripItems { public interface ICommandToolStripItem : IToolStripItem { ICommand Command { get; } } public interface IToolStripItem { ToolStripItem Item { get; } int DisplayOrder { get; } void Localize(); } public class CommandToolStripItem : ICommandToolStripItem { private readonly ICommand _command; private readonly ToolStripItem _item; private readonly int _displayOrder; private readonly Func<string> _caption; private readonly Func<string> _toolTip; public CommandToolStripItem(ICommand command, ToolStripItem item, int displayOrder, Func<string> caption = null, Func<string> toolTip = null) { _command = command; _item = item; _displayOrder = displayOrder; _caption = caption; _toolTip = toolTip; if (command != null) { item.Click += delegate { command.Execute(null); }; } } public void Localize() { if (_caption != null) { _item.Text = _caption.Invoke(); } if (_toolTip != null) { _item.ToolTipText = _toolTip.Invoke(); } } public ICommand Command { get { return _command; } } public ToolStripItem Item { get { return _item; } } public int DisplayOrder { get { return _displayOrder; } } } }
r14r/fork_vba_rubberduck
RetailCoder.VBE/UI/Command/MenuItems/ToolStripItems/CommandToolStripItem.cs
C#
gpl-3.0
1,655
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | \\ / A nd | For copyright notice see file Copyright \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend is distributed in the hope that 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. Class Foam::fv::gaussDivScheme Description Basic second-order div using face-gradients and Gauss' theorem. SourceFiles gaussDivScheme.C \*---------------------------------------------------------------------------*/ #ifndef gaussDivScheme_H #define gaussDivScheme_H #include "divScheme.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace fv { /*---------------------------------------------------------------------------*\ Class gaussDivScheme Declaration \*---------------------------------------------------------------------------*/ template<class Type> class gaussDivScheme : public fv::divScheme<Type> { // Private Member Functions //- Disallow default bitwise copy construct gaussDivScheme(const gaussDivScheme&); //- Disallow default bitwise assignment void operator=(const gaussDivScheme&); public: //- Runtime type information TypeName("Gauss"); // Constructors //- Construct null gaussDivScheme(const fvMesh& mesh) : divScheme<Type>(mesh) {} //- Construct from Istream gaussDivScheme(const fvMesh& mesh, Istream& is) : divScheme<Type>(mesh, is) {} // Member Functions tmp < GeometricField <typename innerProduct<vector, Type>::type, fvPatchField, volMesh> > fvcDiv ( const GeometricField<Type, fvPatchField, volMesh>& ); //- Return the blockLduMatrix<vector> corresponding to the implicit // div discretization. For block coupled system. tmp<blockVectorMatrix> fvmDiv ( const GeometricField<Type, fvPatchField, volMesh>& ) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace fv // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "gaussDivScheme.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
WensiWu/openfoam-extend-foam-extend-3.1
src/finiteVolume/finiteVolume/divSchemes/gaussDivScheme/gaussDivScheme.H
C++
gpl-3.0
3,509