patch
stringlengths 17
31.2k
| y
int64 1
1
| oldf
stringlengths 0
2.21M
| idx
int64 1
1
| id
int64 4.29k
68.4k
| msg
stringlengths 8
843
| proj
stringclasses 212
values | lang
stringclasses 9
values |
---|---|---|---|---|---|---|---|
@@ -125,6 +125,10 @@ type Task struct {
// ENI is the elastic network interface specified by this task
ENI *ENI
eniLock sync.RWMutex
+
+ // memoryCPULimitsEnabled to determine if task supports CPU, memory limits
+ memoryCPULimitsEnabled bool
+ memoryCPULimitsEnabledLock sync.RWMutex
}
// PostUnmarshalTask is run after a task has been unmarshalled, but before it has been | 1 | // Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 api
import (
"encoding/json"
"fmt"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/aws/amazon-ecs-agent/agent/acs/model/ecsacs"
"github.com/aws/amazon-ecs-agent/agent/config"
"github.com/aws/amazon-ecs-agent/agent/credentials"
"github.com/aws/amazon-ecs-agent/agent/ecscni"
"github.com/aws/amazon-ecs-agent/agent/engine/emptyvolume"
"github.com/aws/amazon-ecs-agent/agent/utils/ttime"
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/aws/aws-sdk-go/private/protocol/json/jsonutil"
"github.com/cihub/seelog"
"github.com/fsouza/go-dockerclient"
"github.com/pkg/errors"
)
const (
// PauseContainerName is the internal name for the pause container
PauseContainerName = "~internal~ecs~pause"
emptyHostVolumeName = "~internal~ecs-emptyvolume-source"
// awsSDKCredentialsRelativeURIPathEnvironmentVariableName defines the name of the environment
// variable containers' config, which will be used by the AWS SDK to fetch
// credentials.
awsSDKCredentialsRelativeURIPathEnvironmentVariableName = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"
arnResourceSections = 2
arnResourceDelimiter = "/"
// networkModeNone specifies the string used to define the `none` docker networking mode
networkModeNone = "none"
// networkModeContainerPrefix specifies the prefix string used for setting the
// container's network mode to be mapped to that of another existing container
networkModeContainerPrefix = "container:"
)
// TaskOverrides are the overrides applied to a task
type TaskOverrides struct{}
// Task is the internal representation of a task in the ECS agent
type Task struct {
// Arn is the unique identifer for the task
Arn string
// Overrides are the overrides applied to a task
Overrides TaskOverrides `json:"-"`
// Family is the name of the task definition family
Family string
// Version is the version of the task definition
Version string
// Containers are the containers for the task
Containers []*Container
// Volumes are the volumes for the task
Volumes []TaskVolume `json:"volumes"`
// VCPULimit is a task-level limit for compute resources. A value of 1 means that
// the task may access 100% of 1 vCPU on the instance
VCPULimit float64 `json:"CPULimit,omitempty"`
// MemoryLimit is a task-level limit for memory resources in bytes
MemoryLimit int64 `json:"Memory,omitempty"`
// DesiredStatusUnsafe represents the state where the task should go. Generally,
// the desired status is informed by the ECS backend as a result of either
// API calls made to ECS or decisions made by the ECS service scheduler.
// The DesiredStatusUnsafe is almost always either TaskRunning or TaskStopped.
// NOTE: Do not access DesiredStatusUnsafe directly. Instead, use `UpdateStatus`,
// `UpdateDesiredStatus`, `SetDesiredStatus`, and `SetDesiredStatus`.
// TODO DesiredStatusUnsafe should probably be private with appropriately written
// setter/getter. When this is done, we need to ensure that the UnmarshalJSON
// is handled properly so that the state storage continues to work.
DesiredStatusUnsafe TaskStatus `json:"DesiredStatus"`
desiredStatusLock sync.RWMutex
// KnownStatusUnsafe represents the state where the task is. This is generally
// the minimum of equivalent status types for the containers in the task;
// if one container is at ContainerRunning and another is at ContainerPulled,
// the task KnownStatusUnsafe would be TaskPulled.
// NOTE: Do not access KnownStatusUnsafe directly. Instead, use `UpdateStatus`,
// and `GetKnownStatus`.
// TODO KnownStatusUnsafe should probably be private with appropriately written
// setter/getter. When this is done, we need to ensure that the UnmarshalJSON
// is handled properly so that the state storage continues to work.
KnownStatusUnsafe TaskStatus `json:"KnownStatus"`
knownStatusLock sync.RWMutex
// KnownStatusTimeUnsafe captures the time when the KnownStatusUnsafe was last updated.
// NOTE: Do not access KnownStatusTime directly, instead use `GetKnownStatusTime`.
KnownStatusTimeUnsafe time.Time `json:"KnownTime"`
knownStatusTimeLock sync.RWMutex
// SentStatusUnsafe represents the last KnownStatusUnsafe that was sent to the ECS SubmitTaskStateChange API.
// TODO(samuelkarp) SentStatusUnsafe needs a lock and setters/getters.
// TODO SentStatusUnsafe should probably be private with appropriately written
// setter/getter. When this is done, we need to ensure that the UnmarshalJSON
// is handled properly so that the state storage continues to work.
SentStatusUnsafe TaskStatus `json:"SentStatus"`
sentStatusLock sync.RWMutex
StartSequenceNumber int64
StopSequenceNumber int64
// credentialsID is used to set the CredentialsId field for the
// IAMRoleCredentials object associated with the task. This id can be
// used to look up the credentials for task in the credentials manager
credentialsID string
credentialsIDLock sync.RWMutex
// ENI is the elastic network interface specified by this task
ENI *ENI
eniLock sync.RWMutex
}
// PostUnmarshalTask is run after a task has been unmarshalled, but before it has been
// run. It is possible it will be subsequently called after that and should be
// able to handle such an occurrence appropriately (e.g. behave idempotently).
func (task *Task) PostUnmarshalTask(cfg *config.Config, credentialsManager credentials.Manager) {
// TODO, add rudimentary plugin support and call any plugins that want to
// hook into this
task.adjustForPlatform()
task.initializeEmptyVolumes()
task.initializeCredentialsEndpoint(credentialsManager)
task.addNetworkResourceProvisioningDependency(cfg)
}
func (task *Task) initializeEmptyVolumes() {
requiredEmptyVolumes := []string{}
for _, container := range task.Containers {
for _, mountPoint := range container.MountPoints {
vol, ok := task.HostVolumeByName(mountPoint.SourceVolume)
if !ok {
continue
}
if _, ok := vol.(*EmptyHostVolume); ok {
if container.SteadyStateDependencies == nil {
container.SteadyStateDependencies = make([]string, 0)
}
container.SteadyStateDependencies = append(container.SteadyStateDependencies, emptyHostVolumeName)
requiredEmptyVolumes = append(requiredEmptyVolumes, mountPoint.SourceVolume)
}
}
}
if len(requiredEmptyVolumes) == 0 {
// No need to create the auxiliary 'empty-volumes' container
return
}
// If we have required empty volumes, add an 'internal' container that handles all
// of them
_, ok := task.ContainerByName(emptyHostVolumeName)
if !ok {
mountPoints := make([]MountPoint, len(requiredEmptyVolumes))
for i, volume := range requiredEmptyVolumes {
// BUG(samuelkarp) On Windows, volumes with names that differ only by case will collide
containerPath := getCanonicalPath(emptyvolume.ContainerPathPrefix + volume)
mountPoints[i] = MountPoint{SourceVolume: volume, ContainerPath: containerPath}
}
sourceContainer := &Container{
Name: emptyHostVolumeName,
Image: emptyvolume.Image + ":" + emptyvolume.Tag,
Command: []string{emptyvolume.Command}, // Command required, but this only gets created so N/A
MountPoints: mountPoints,
Essential: false,
Type: ContainerEmptyHostVolume,
DesiredStatusUnsafe: ContainerRunning,
}
task.Containers = append(task.Containers, sourceContainer)
}
}
// initializeCredentialsEndpoint sets the credentials endpoint for all containers in a task if needed.
func (task *Task) initializeCredentialsEndpoint(credentialsManager credentials.Manager) {
id := task.GetCredentialsID()
if id == "" {
// No credentials set for the task. Do not inject the endpoint environment variable.
return
}
taskCredentials, ok := credentialsManager.GetTaskCredentials(id)
if !ok {
// Task has credentials id set, but credentials manager is unaware of
// the id. This should never happen as the payload handler sets
// credentialsId for the task after adding credentials to the
// credentials manager
seelog.Errorf("Unable to get credentials for task: %s", task.Arn)
return
}
credentialsEndpointRelativeURI := taskCredentials.IAMRoleCredentials.GenerateCredentialsEndpointRelativeURI()
for _, container := range task.Containers {
// container.Environment map would not be initialized if there are
// no environment variables to be set or overridden in the container
// config. Check if that's the case and initilialize if needed
if container.Environment == nil {
container.Environment = make(map[string]string)
}
container.Environment[awsSDKCredentialsRelativeURIPathEnvironmentVariableName] = credentialsEndpointRelativeURI
}
}
// BuildCNIConfig constructs the cni configuration from eni
func (task *Task) BuildCNIConfig() (*ecscni.Config, error) {
if !task.isNetworkModeVPC() {
return nil, errors.New("task config: task has no ENIs associated with it, unable to generate cni config")
}
cfg := &ecscni.Config{}
eni := task.GetTaskENI()
cfg.ENIID = eni.ID
cfg.ID = eni.MacAddress
cfg.ENIMACAddress = eni.MacAddress
for _, ipv4 := range eni.IPV4Addresses {
if ipv4.Primary {
cfg.ENIIPV4Address = ipv4.Address
break
}
}
// If there is ipv6 assigned to eni then set it
if len(eni.IPV6Addresses) > 0 {
cfg.ENIIPV6Address = eni.IPV6Addresses[0].Address
}
return cfg, nil
}
// isNetworkModeVPC checks if the task is configured to use task-networking feature
func (task *Task) isNetworkModeVPC() bool {
if task.GetTaskENI() == nil {
return false
}
return true
}
func (task *Task) addNetworkResourceProvisioningDependency(cfg *config.Config) {
if !task.isNetworkModeVPC() {
return
}
for _, container := range task.Containers {
if container.IsInternal() {
continue
}
if container.SteadyStateDependencies == nil {
container.SteadyStateDependencies = make([]string, 0)
}
container.SteadyStateDependencies = append(container.SteadyStateDependencies, PauseContainerName)
}
pauseContainer := NewContainerWithSteadyState(ContainerResourcesProvisioned)
pauseContainer.Name = PauseContainerName
pauseContainer.Image = fmt.Sprintf("%s:%s", cfg.PauseContainerImageName, cfg.PauseContainerTag)
pauseContainer.Essential = true
pauseContainer.Type = ContainerCNIPause
task.Containers = append(task.Containers, pauseContainer)
}
// ContainerByName returns the *Container for the given name
func (task *Task) ContainerByName(name string) (*Container, bool) {
for _, container := range task.Containers {
if container.Name == name {
return container, true
}
}
return nil, false
}
// HostVolumeByName returns the task Volume for the given a volume name in that
// task. The second return value indicates the presense of that volume
func (task *Task) HostVolumeByName(name string) (HostVolume, bool) {
for _, v := range task.Volumes {
if v.Name == name {
return v.Volume, true
}
}
return nil, false
}
// UpdateMountPoints updates the mount points of volumes that were created
// without specifying a host path. This is used as part of the empty host
// volume feature.
func (task *Task) UpdateMountPoints(cont *Container, vols map[string]string) {
for _, mountPoint := range cont.MountPoints {
containerPath := getCanonicalPath(mountPoint.ContainerPath)
hostPath, ok := vols[containerPath]
if !ok {
// /path/ -> /path or \path\ -> \path
hostPath, ok = vols[strings.TrimRight(containerPath, string(filepath.Separator))]
}
if ok {
if hostVolume, exists := task.HostVolumeByName(mountPoint.SourceVolume); exists {
if empty, ok := hostVolume.(*EmptyHostVolume); ok {
empty.HostPath = hostPath
}
}
}
}
}
// updateTaskKnownStatus updates the given task's status based on its container's status.
// It updates to the minimum of all containers no matter what
// It returns a TaskStatus indicating what change occurred or TaskStatusNone if
// there was no change
// Invariant: task known status is the minimum of container known status
func (task *Task) updateTaskKnownStatus() (newStatus TaskStatus) {
seelog.Debugf("Updating task's known status, task: %s", task.String())
// Set to a large 'impossible' status that can't be the min
containerEarliestKnownStatus := ContainerZombie
var earliestKnownStatusContainer *Container
essentialContainerStopped := false
for _, container := range task.Containers {
containerKnownStatus := container.GetKnownStatus()
if containerKnownStatus == ContainerStopped && container.Essential {
essentialContainerStopped = true
}
if containerKnownStatus < containerEarliestKnownStatus {
containerEarliestKnownStatus = containerKnownStatus
earliestKnownStatusContainer = container
}
}
if earliestKnownStatusContainer == nil {
seelog.Criticalf(
"Impossible state found while updating tasks's known status, earliest state recorded as %s for task [%v]",
containerEarliestKnownStatus.String(), task)
return TaskStatusNone
}
seelog.Debugf("Container with earliest known container is [%s] for task: %s",
earliestKnownStatusContainer.String(), task.String())
// If the essential container is stopped while other containers may be running
// don't update the task status until the other containers are stopped.
if earliestKnownStatusContainer.IsKnownSteadyState() && essentialContainerStopped {
seelog.Debugf(
"Essential container is stopped while other containers are running, not updating task status for task: %s",
task.String())
return TaskStatusNone
}
// We can't rely on earliest container known status alone for determining if the
// task state needs to be updated as containers can have different steady states
// defined. Instead we should get the task status for all containers' known
// statuses and compute the min of this
earliestKnownTaskStatus := task.getEarliestKnownTaskStatusForContainers()
if task.GetKnownStatus() < earliestKnownTaskStatus {
seelog.Debugf("Updating task's known status to: %s, task: %s",
earliestKnownTaskStatus.String(), task.String())
task.SetKnownStatus(earliestKnownTaskStatus)
return task.GetKnownStatus()
}
return TaskStatusNone
}
// getEarliestKnownTaskStatusForContainers gets the lowest (earliest) task status
// based on the known statuses of all containers in the task
func (task *Task) getEarliestKnownTaskStatusForContainers() TaskStatus {
if len(task.Containers) == 0 {
seelog.Criticalf("No containers in the task: %s", task.String())
return TaskStatusNone
}
// Set earliest container status to an impossible to reach 'high' task status
earliest := TaskZombie
for _, container := range task.Containers {
containerKnownStatus := container.GetKnownStatus()
containerTaskStatus := containerKnownStatus.TaskStatus(container.GetSteadyStateStatus())
if containerTaskStatus < earliest {
earliest = containerTaskStatus
}
}
return earliest
}
// Overridden returns a copy of the task with all container's overridden and
// itself overridden as well
func (task *Task) Overridden() *Task {
result := *task
// Task has no overrides currently, just do the containers
// Shallow copy, take care of the deeper bits too
result.Containers = make([]*Container, len(result.Containers))
for i, cont := range task.Containers {
result.Containers[i] = cont.Overridden()
}
return &result
}
// DockerConfig converts the given container in this task to the format of
// GoDockerClient's 'Config' struct
func (task *Task) DockerConfig(container *Container) (*docker.Config, *DockerClientConfigError) {
return task.Overridden().dockerConfig(container.Overridden())
}
func (task *Task) dockerConfig(container *Container) (*docker.Config, *DockerClientConfigError) {
dockerVolumes, err := task.dockerConfigVolumes(container)
if err != nil {
return nil, &DockerClientConfigError{err.Error()}
}
dockerEnv := make([]string, 0, len(container.Environment))
for envKey, envVal := range container.Environment {
dockerEnv = append(dockerEnv, envKey+"="+envVal)
}
// Convert MB to B
dockerMem := int64(container.Memory * 1024 * 1024)
if dockerMem != 0 && dockerMem < DockerContainerMinimumMemoryInBytes {
dockerMem = DockerContainerMinimumMemoryInBytes
}
var entryPoint []string
if container.EntryPoint != nil {
entryPoint = *container.EntryPoint
}
config := &docker.Config{
Image: container.Image,
Cmd: container.Command,
Entrypoint: entryPoint,
ExposedPorts: task.dockerExposedPorts(container),
Volumes: dockerVolumes,
Env: dockerEnv,
Memory: dockerMem,
CPUShares: task.dockerCPUShares(container.CPU),
}
if container.DockerConfig.Config != nil {
err := json.Unmarshal([]byte(*container.DockerConfig.Config), &config)
if err != nil {
return nil, &DockerClientConfigError{"Unable decode given docker config: " + err.Error()}
}
}
if config.Labels == nil {
config.Labels = make(map[string]string)
}
return config, nil
}
// dockerCPUShares converts containerCPU shares if needed as per the logic stated below:
// Docker silently converts 0 to 1024 CPU shares, which is probably not what we
// want. Instead, we convert 0 to 2 to be closer to expected behavior. The
// reason for 2 over 1 is that 1 is an invalid value (Linux's choice, not Docker's).
func (task *Task) dockerCPUShares(containerCPU uint) int64 {
if containerCPU <= 1 {
seelog.Debugf(
"Converting CPU shares to allowed minimum of 2 for task arn: [%s] and cpu shares: %d",
task.Arn, containerCPU)
return 2
}
return int64(containerCPU)
}
func (task *Task) dockerExposedPorts(container *Container) map[docker.Port]struct{} {
dockerExposedPorts := make(map[docker.Port]struct{})
for _, portBinding := range container.Ports {
dockerPort := docker.Port(strconv.Itoa(int(portBinding.ContainerPort)) + "/" + portBinding.Protocol.String())
dockerExposedPorts[dockerPort] = struct{}{}
}
return dockerExposedPorts
}
func (task *Task) dockerConfigVolumes(container *Container) (map[string]struct{}, error) {
volumeMap := make(map[string]struct{})
for _, m := range container.MountPoints {
vol, exists := task.HostVolumeByName(m.SourceVolume)
if !exists {
return nil, &badVolumeError{"Container " + container.Name + " in task " + task.Arn + " references invalid volume " + m.SourceVolume}
}
// you can handle most volume mount types in the HostConfig at run-time;
// empty mounts are created by docker at create-time (Config) so set
// them here.
if container.Type == ContainerEmptyHostVolume {
// if container.Name == emptyHostVolumeName && container.Type {
_, ok := vol.(*EmptyHostVolume)
if !ok {
return nil, &badVolumeError{"Empty volume container in task " + task.Arn + " was the wrong type"}
}
volumeMap[m.ContainerPath] = struct{}{}
}
}
return volumeMap, nil
}
func (task *Task) DockerHostConfig(container *Container, dockerContainerMap map[string]*DockerContainer) (*docker.HostConfig, *HostConfigError) {
return task.Overridden().dockerHostConfig(container.Overridden(), dockerContainerMap)
}
func (task *Task) dockerHostConfig(container *Container, dockerContainerMap map[string]*DockerContainer) (*docker.HostConfig, *HostConfigError) {
dockerLinkArr, err := task.dockerLinks(container, dockerContainerMap)
if err != nil {
return nil, &HostConfigError{err.Error()}
}
dockerPortMap := task.dockerPortMap(container)
volumesFrom, err := task.dockerVolumesFrom(container, dockerContainerMap)
if err != nil {
return nil, &HostConfigError{err.Error()}
}
binds, err := task.dockerHostBinds(container)
if err != nil {
return nil, &HostConfigError{err.Error()}
}
// Populate hostConfig
hostConfig := &docker.HostConfig{
Links: dockerLinkArr,
Binds: binds,
PortBindings: dockerPortMap,
VolumesFrom: volumesFrom,
}
if container.DockerConfig.HostConfig != nil {
err := json.Unmarshal([]byte(*container.DockerConfig.HostConfig), hostConfig)
if err != nil {
return nil, &HostConfigError{"Unable to decode given host config: " + err.Error()}
}
}
task.platformHostConfigOverride(hostConfig)
// Determine if network mode should be overridden and override it if needed
ok, networkMode := task.shouldOverrideNetworkMode(container, dockerContainerMap)
if !ok {
return hostConfig, nil
}
hostConfig.NetworkMode = networkMode
return hostConfig, nil
}
// shouldOverrideNetworkMode returns true if the network mode of the container needs
// to be overridden. It also returns the override string in this case. It returns
// false otherwise
func (task *Task) shouldOverrideNetworkMode(container *Container, dockerContainerMap map[string]*DockerContainer) (bool, string) {
// TODO. We can do an early return here by determining which kind of task it is
// Example: Does this task have ENIs in its payload, what is its networking mode etc
if container.IsInternal() {
// If it's an internal container, set the network mode to none.
// Currently, internal containers are either for creating empty host
// volumes or for creating the 'pause' container. Both of these
// only need the network mode to be set to "none"
return true, networkModeNone
}
// For other types of containers, determine if the container map contains
// a pause container. Since a pause container is only added to the task
// when using non docker daemon supported network modes, its existence
// indicates the need to configure the network mode outside of supported
// network drivers
if task.GetTaskENI() == nil {
return false, ""
}
pauseContName := ""
for _, cont := range task.Containers {
if cont.Type == ContainerCNIPause {
pauseContName = cont.Name
break
}
}
if pauseContName == "" {
seelog.Critical("Pause container required, but not found in the task: %s", task.String())
return false, ""
}
pauseContainer, ok := dockerContainerMap[pauseContName]
if !ok || pauseContainer == nil {
// This should never be the case and implies a code-bug.
seelog.Criticalf("Pause container required, but not found in container map for container: [%s] in task: %s",
container.String(), task.String())
return false, ""
}
return true, networkModeContainerPrefix + pauseContainer.DockerID
}
func (task *Task) dockerLinks(container *Container, dockerContainerMap map[string]*DockerContainer) ([]string, error) {
dockerLinkArr := make([]string, len(container.Links))
for i, link := range container.Links {
linkParts := strings.Split(link, ":")
if len(linkParts) > 2 {
return []string{}, errors.New("Invalid link format")
}
linkName := linkParts[0]
var linkAlias string
if len(linkParts) == 2 {
linkAlias = linkParts[1]
} else {
seelog.Warnf("Link name [%s] found with no linkalias for container: [%s] in task: [%s]",
linkName, container.String(), task.String())
linkAlias = linkName
}
targetContainer, ok := dockerContainerMap[linkName]
if !ok {
return []string{}, errors.New("Link target not available: " + linkName)
}
dockerLinkArr[i] = targetContainer.DockerName + ":" + linkAlias
}
return dockerLinkArr, nil
}
func (task *Task) dockerPortMap(container *Container) map[docker.Port][]docker.PortBinding {
dockerPortMap := make(map[docker.Port][]docker.PortBinding)
for _, portBinding := range container.Ports {
dockerPort := docker.Port(strconv.Itoa(int(portBinding.ContainerPort)) + "/" + portBinding.Protocol.String())
currentMappings, existing := dockerPortMap[dockerPort]
if existing {
dockerPortMap[dockerPort] = append(currentMappings, docker.PortBinding{HostIP: portBindingHostIP, HostPort: strconv.Itoa(int(portBinding.HostPort))})
} else {
dockerPortMap[dockerPort] = []docker.PortBinding{{HostIP: portBindingHostIP, HostPort: strconv.Itoa(int(portBinding.HostPort))}}
}
}
return dockerPortMap
}
func (task *Task) dockerVolumesFrom(container *Container, dockerContainerMap map[string]*DockerContainer) ([]string, error) {
volumesFrom := make([]string, len(container.VolumesFrom))
for i, volume := range container.VolumesFrom {
targetContainer, ok := dockerContainerMap[volume.SourceContainer]
if !ok {
return []string{}, errors.New("Volume target not available: " + volume.SourceContainer)
}
if volume.ReadOnly {
volumesFrom[i] = targetContainer.DockerName + ":ro"
} else {
volumesFrom[i] = targetContainer.DockerName
}
}
return volumesFrom, nil
}
func (task *Task) dockerHostBinds(container *Container) ([]string, error) {
if container.Name == emptyHostVolumeName {
// emptyHostVolumes are handled as a special case in config, not
// hostConfig
return []string{}, nil
}
binds := make([]string, len(container.MountPoints))
for i, mountPoint := range container.MountPoints {
hv, ok := task.HostVolumeByName(mountPoint.SourceVolume)
if !ok {
return []string{}, errors.New("Invalid volume referenced: " + mountPoint.SourceVolume)
}
if hv.SourcePath() == "" || mountPoint.ContainerPath == "" {
seelog.Errorf(
"Unable to resolve volume mounts for container [%s]; invalid path: [%s]; [%s] -> [%s] in task: [%s]",
container.Name, mountPoint.SourceVolume, hv.SourcePath(), mountPoint.ContainerPath, task.String())
return []string{}, errors.New("Unable to resolve volume mounts; invalid path: " + container.Name + " " + mountPoint.SourceVolume + "; " + hv.SourcePath() + " -> " + mountPoint.ContainerPath)
}
bind := hv.SourcePath() + ":" + mountPoint.ContainerPath
if mountPoint.ReadOnly {
bind += ":ro"
}
binds[i] = bind
}
return binds, nil
}
// TaskFromACS translates ecsacs.Task to api.Task by first marshaling the recieved
// ecsacs.Task to json and unmrashaling it as api.Task
func TaskFromACS(acsTask *ecsacs.Task, envelope *ecsacs.PayloadMessage) (*Task, error) {
data, err := jsonutil.BuildJSON(acsTask)
if err != nil {
return nil, err
}
task := &Task{}
err = json.Unmarshal(data, task)
if err != nil {
return nil, err
}
if task.GetDesiredStatus() == TaskRunning && envelope.SeqNum != nil {
task.StartSequenceNumber = *envelope.SeqNum
} else if task.GetDesiredStatus() == TaskStopped && envelope.SeqNum != nil {
task.StopSequenceNumber = *envelope.SeqNum
}
// TODO: Inspect CgroupSpec upon model changes
return task, nil
}
// UpdateStatus updates a task's known and desired statuses to be compatible
// with all of its containers
// It will return a bool indicating if there was a change
func (task *Task) UpdateStatus() bool {
change := task.updateTaskKnownStatus()
// DesiredStatus can change based on a new known status
task.UpdateDesiredStatus()
return change != TaskStatusNone
}
// UpdateDesiredStatus sets the known status of the task
func (task *Task) UpdateDesiredStatus() {
task.updateTaskDesiredStatus()
task.updateContainerDesiredStatus()
}
// updateTaskDesiredStatus determines what status the task should properly be at based on the containers' statuses
// Invariant: task desired status must be stopped if any essential container is stopped
func (task *Task) updateTaskDesiredStatus() {
seelog.Debugf("Updating task: [%s]", task.String())
// A task's desired status is stopped if any essential container is stopped
// Otherwise, the task's desired status is unchanged (typically running, but no need to change)
for _, cont := range task.Containers {
if cont.Essential && (cont.KnownTerminal() || cont.DesiredTerminal()) {
seelog.Debugf("Updating task desired status to stopped because of container: [%s]; task: [%s]",
cont.Name, task.String())
task.SetDesiredStatus(TaskStopped)
}
}
}
// updateContainerDesiredStatus sets all container's desired status's to the
// task's desired status
// Invariant: container desired status is <= task desired status converted to container status
// Note: task desired status and container desired status is typically only RUNNING or STOPPED
func (task *Task) updateContainerDesiredStatus() {
for _, c := range task.Containers {
taskDesiredStatus := task.GetDesiredStatus()
taskDesiredStatusToContainerStatus := taskDesiredStatus.ContainerStatus(c.GetSteadyStateStatus())
if c.GetDesiredStatus() < taskDesiredStatusToContainerStatus {
c.SetDesiredStatus(taskDesiredStatusToContainerStatus)
}
}
}
// SetKnownStatus sets the known status of the task
func (task *Task) SetKnownStatus(status TaskStatus) {
task.setKnownStatus(status)
task.updateKnownStatusTime()
}
func (task *Task) setKnownStatus(status TaskStatus) {
task.knownStatusLock.Lock()
defer task.knownStatusLock.Unlock()
task.KnownStatusUnsafe = status
}
func (task *Task) updateKnownStatusTime() {
task.knownStatusTimeLock.Lock()
defer task.knownStatusTimeLock.Unlock()
task.KnownStatusTimeUnsafe = ttime.Now()
}
// GetKnownStatus gets the KnownStatus of the task
func (task *Task) GetKnownStatus() TaskStatus {
task.knownStatusLock.RLock()
defer task.knownStatusLock.RUnlock()
return task.KnownStatusUnsafe
}
// GetKnownStatusTime gets the KnownStatusTime of the task
func (task *Task) GetKnownStatusTime() time.Time {
task.knownStatusTimeLock.RLock()
defer task.knownStatusTimeLock.RUnlock()
return task.KnownStatusTimeUnsafe
}
// SetCredentialsID sets the credentials ID for the task
func (task *Task) SetCredentialsID(id string) {
task.credentialsIDLock.Lock()
defer task.credentialsIDLock.Unlock()
task.credentialsID = id
}
// GetCredentialsID gets the credentials ID for the task
func (task *Task) GetCredentialsID() string {
task.credentialsIDLock.RLock()
defer task.credentialsIDLock.RUnlock()
return task.credentialsID
}
// GetDesiredStatus gets the desired status of the task
func (task *Task) GetDesiredStatus() TaskStatus {
task.desiredStatusLock.RLock()
defer task.desiredStatusLock.RUnlock()
return task.DesiredStatusUnsafe
}
// SetDesiredStatus sets the desired status of the task
func (task *Task) SetDesiredStatus(status TaskStatus) {
task.desiredStatusLock.Lock()
defer task.desiredStatusLock.Unlock()
task.DesiredStatusUnsafe = status
}
// GetSentStatus safely returns the SentStatus of the task
func (task *Task) GetSentStatus() TaskStatus {
task.sentStatusLock.RLock()
defer task.sentStatusLock.RUnlock()
return task.SentStatusUnsafe
}
// SetSentStatus safely sets the SentStatus of the task
func (task *Task) SetSentStatus(status TaskStatus) {
task.sentStatusLock.Lock()
defer task.sentStatusLock.Unlock()
task.SentStatusUnsafe = status
}
// SetTaskENI sets the eni information of the task
func (task *Task) SetTaskENI(eni *ENI) {
task.eniLock.Lock()
defer task.eniLock.Unlock()
task.ENI = eni
}
// GetTaskENI returns the eni of task, for now task can only have one enis
func (task *Task) GetTaskENI() *ENI {
task.eniLock.RLock()
defer task.eniLock.RUnlock()
return task.ENI
}
// String returns a human readable string representation of this object
func (t *Task) String() string {
res := fmt.Sprintf("%s:%s %s, TaskStatus: (%s->%s)",
t.Family, t.Version, t.Arn,
t.GetKnownStatus().String(), t.GetDesiredStatus().String())
res += " Containers: ["
for _, c := range t.Containers {
res += fmt.Sprintf("%s (%s->%s),", c.Name, c.GetKnownStatus().String(), c.GetDesiredStatus().String())
}
return res + "]"
}
// GetID is used to retrieve the taskID from taskARN
// Reference: http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arn-syntax-ecs
func (task *Task) GetID() (string, error) {
// Parse taskARN
parsedARN, err := arn.Parse(task.Arn)
if err != nil {
return "", errors.Wrapf(err, "task get-id: malformed taskARN: %s", task.Arn)
}
// Get task resource section
resource := parsedARN.Resource
if !strings.Contains(resource, arnResourceDelimiter) {
return "", errors.New(fmt.Sprintf("task get-id: malformed task resource: %s", resource))
}
resourceSplit := strings.SplitN(resource, arnResourceDelimiter, arnResourceSections)
if len(resourceSplit) != arnResourceSections {
return "", errors.New(fmt.Sprintf("task get-id: invalid task resource split: %s, expected=%d, actual=%d", resource, arnResourceSections, len(resourceSplit)))
}
return resourceSplit[1], nil
}
| 1 | 17,442 | Does this need to be saved in the state file? Or are we recomputing when the task is read from the state file? | aws-amazon-ecs-agent | go |
@@ -503,11 +503,11 @@ func (s *Sublist) Stats() *SublistStats {
st := &SublistStats{}
st.NumSubs = s.count
st.NumCache = uint32(len(s.cache))
- st.NumInserts = s.inserts
- st.NumRemoves = s.removes
- st.NumMatches = s.matches
- if s.matches > 0 {
- st.CacheHitRate = float64(s.cacheHits) / float64(s.matches)
+ st.NumInserts = atomic.LoadUint64(&s.inserts)
+ st.NumRemoves = atomic.LoadUint64(&s.removes)
+ st.NumMatches = atomic.LoadUint64(&s.matches)
+ if st.NumMatches > 0 {
+ st.CacheHitRate = float64(atomic.LoadUint64(&s.cacheHits)) / float64(st.NumMatches)
}
// whip through cache for fanout stats
tot, max := 0, 0 | 1 | // Copyright 2016 Apcera Inc. All rights reserved.
// Package sublist is a routing mechanism to handle subject distribution
// and provides a facility to match subjects from published messages to
// interested subscribers. Subscribers can have wildcard subjects to match
// multiple published subjects.
package server
import (
"bytes"
"errors"
"strings"
"sync"
"sync/atomic"
)
// Common byte variables for wildcards and token separator.
const (
pwc = '*'
fwc = '>'
tsep = "."
btsep = '.'
)
// Sublist related errors
var (
ErrInvalidSubject = errors.New("sublist: Invalid Subject")
ErrNotFound = errors.New("sublist: No Matches Found")
)
// cacheMax is used to bound limit the frontend cache
const slCacheMax = 1024
// A result structure better optimized for queue subs.
type SublistResult struct {
psubs []*subscription
qsubs [][]*subscription // don't make this a map, too expensive to iterate
}
// A Sublist stores and efficiently retrieves subscriptions.
type Sublist struct {
sync.RWMutex
genid uint64
matches uint64
cacheHits uint64
inserts uint64
removes uint64
cache map[string]*SublistResult
root *level
count uint32
}
// A node contains subscriptions and a pointer to the next level.
type node struct {
next *level
psubs []*subscription
qsubs [][]*subscription
}
// A level represents a group of nodes and special pointers to
// wildcard nodes.
type level struct {
nodes map[string]*node
pwc, fwc *node
}
// Create a new default node.
func newNode() *node {
return &node{psubs: make([]*subscription, 0, 4)}
}
// Create a new default level. We use FNV1A as the hash
// algortihm for the tokens, which should be short.
func newLevel() *level {
return &level{nodes: make(map[string]*node)}
}
// New will create a default sublist
func NewSublist() *Sublist {
return &Sublist{root: newLevel(), cache: make(map[string]*SublistResult)}
}
// Insert adds a subscription into the sublist
func (s *Sublist) Insert(sub *subscription) error {
// copy the subject since we hold this and this might be part of a large byte slice.
subject := string(sub.subject)
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
s.Lock()
sfwc := false
l := s.root
var n *node
for _, t := range tokens {
if len(t) == 0 || sfwc {
s.Unlock()
return ErrInvalidSubject
}
switch t[0] {
case pwc:
n = l.pwc
case fwc:
n = l.fwc
sfwc = true
default:
n = l.nodes[t]
}
if n == nil {
n = newNode()
switch t[0] {
case pwc:
l.pwc = n
case fwc:
l.fwc = n
default:
l.nodes[t] = n
}
}
if n.next == nil {
n.next = newLevel()
}
l = n.next
}
if sub.queue == nil {
n.psubs = append(n.psubs, sub)
} else {
// This is a queue subscription
if i := findQSliceForSub(sub, n.qsubs); i >= 0 {
n.qsubs[i] = append(n.qsubs[i], sub)
} else {
n.qsubs = append(n.qsubs, []*subscription{sub})
}
}
s.count++
s.inserts++
s.addToCache(subject, sub)
atomic.AddUint64(&s.genid, 1)
s.Unlock()
return nil
}
// Deep copy
func copyResult(r *SublistResult) *SublistResult {
nr := &SublistResult{}
nr.psubs = append([]*subscription(nil), r.psubs...)
for _, qr := range r.qsubs {
nqr := append([]*subscription(nil), qr...)
nr.qsubs = append(nr.qsubs, nqr)
}
return nr
}
// addToCache will add the new entry to existing cache
// entries if needed. Assumes write lock is held.
func (s *Sublist) addToCache(subject string, sub *subscription) {
for k, r := range s.cache {
if matchLiteral(k, subject) {
// Copy since others may have a reference.
nr := copyResult(r)
if sub.queue == nil {
nr.psubs = append(nr.psubs, sub)
} else {
if i := findQSliceForSub(sub, nr.qsubs); i >= 0 {
nr.qsubs[i] = append(nr.qsubs[i], sub)
} else {
nr.qsubs = append(nr.qsubs, []*subscription{sub})
}
}
s.cache[k] = nr
}
}
}
// removeFromCache will remove the sub from any active cache entries.
// Assumes write lock is held.
func (s *Sublist) removeFromCache(subject string, sub *subscription) {
for k := range s.cache {
if !matchLiteral(k, subject) {
continue
}
// Since someone else may be referecing, can't modify the list
// safely, just let it re-populate.
delete(s.cache, k)
}
}
// Match will match all entries to the literal subject.
// It will return a set of results for both normal and queue subscribers.
func (s *Sublist) Match(subject string) *SublistResult {
s.RLock()
atomic.AddUint64(&s.matches, 1)
rc, ok := s.cache[subject]
s.RUnlock()
if ok {
atomic.AddUint64(&s.cacheHits, 1)
return rc
}
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
// FIXME(dlc) - Make shared pool between sublist and client readLoop?
result := &SublistResult{}
s.Lock()
matchLevel(s.root, tokens, result)
// Add to our cache
s.cache[subject] = result
// Bound the number of entries to sublistMaxCache
if len(s.cache) > slCacheMax {
for k := range s.cache {
delete(s.cache, k)
break
}
}
s.Unlock()
return result
}
// This will add in a node's results to the total results.
func addNodeToResults(n *node, results *SublistResult) {
results.psubs = append(results.psubs, n.psubs...)
for _, qr := range n.qsubs {
if len(qr) == 0 {
continue
}
// Need to find matching list in results
if i := findQSliceForSub(qr[0], results.qsubs); i >= 0 {
results.qsubs[i] = append(results.qsubs[i], qr...)
} else {
results.qsubs = append(results.qsubs, qr)
}
}
}
// We do not use a map here since we want iteration to be past when
// processing publishes in L1 on client. So we need to walk sequentially
// for now. Keep an eye on this in case we start getting large number of
// different queue subscribers for the same subject.
func findQSliceForSub(sub *subscription, qsl [][]*subscription) int {
if sub.queue == nil {
return -1
}
for i, qr := range qsl {
if len(qr) > 0 && bytes.Equal(sub.queue, qr[0].queue) {
return i
}
}
return -1
}
// matchLevel is used to recursively descend into the trie.
func matchLevel(l *level, toks []string, results *SublistResult) {
var pwc, n *node
for i, t := range toks {
if l == nil {
return
}
if l.fwc != nil {
addNodeToResults(l.fwc, results)
}
if pwc = l.pwc; pwc != nil {
matchLevel(pwc.next, toks[i+1:], results)
}
n = l.nodes[t]
if n != nil {
l = n.next
} else {
l = nil
}
}
if n != nil {
addNodeToResults(n, results)
}
if pwc != nil {
addNodeToResults(pwc, results)
}
}
// lnt is used to track descent into levels for a removal for pruning.
type lnt struct {
l *level
n *node
t string
}
// Remove will remove a subscription.
func (s *Sublist) Remove(sub *subscription) error {
subject := string(sub.subject)
tsa := [32]string{}
tokens := tsa[:0]
start := 0
for i := 0; i < len(subject); i++ {
if subject[i] == btsep {
tokens = append(tokens, subject[start:i])
start = i + 1
}
}
tokens = append(tokens, subject[start:])
s.Lock()
defer s.Unlock()
sfwc := false
l := s.root
var n *node
// Track levels for pruning
var lnts [32]lnt
levels := lnts[:0]
for _, t := range tokens {
if len(t) == 0 || sfwc {
return ErrInvalidSubject
}
if l == nil {
return ErrNotFound
}
switch t[0] {
case pwc:
n = l.pwc
case fwc:
n = l.fwc
sfwc = true
default:
n = l.nodes[t]
}
if n != nil {
levels = append(levels, lnt{l, n, t})
l = n.next
} else {
l = nil
}
}
if !s.removeFromNode(n, sub) {
return ErrNotFound
}
s.count--
s.removes++
for i := len(levels) - 1; i >= 0; i-- {
l, n, t := levels[i].l, levels[i].n, levels[i].t
if n.isEmpty() {
l.pruneNode(n, t)
}
}
s.removeFromCache(subject, sub)
atomic.AddUint64(&s.genid, 1)
return nil
}
// pruneNode is used to prune an empty node from the tree.
func (l *level) pruneNode(n *node, t string) {
if n == nil {
return
}
if n == l.fwc {
l.fwc = nil
} else if n == l.pwc {
l.pwc = nil
} else {
delete(l.nodes, t)
}
}
// isEmpty will test if the node has any entries. Used
// in pruning.
func (n *node) isEmpty() bool {
if len(n.psubs) == 0 && len(n.qsubs) == 0 {
if n.next == nil || n.next.numNodes() == 0 {
return true
}
}
return false
}
// Return the number of nodes for the given level.
func (l *level) numNodes() int {
num := len(l.nodes)
if l.pwc != nil {
num++
}
if l.fwc != nil {
num++
}
return num
}
// Removes a sub from a list.
func removeSubFromList(sub *subscription, sl []*subscription) ([]*subscription, bool) {
for i := 0; i < len(sl); i++ {
if sl[i] == sub {
last := len(sl) - 1
sl[i] = sl[last]
sl[last] = nil
sl = sl[:last]
return shrinkAsNeeded(sl), true
}
}
return sl, false
}
// Remove the sub for the given node.
func (s *Sublist) removeFromNode(n *node, sub *subscription) (found bool) {
if n == nil {
return false
}
if sub.queue == nil {
n.psubs, found = removeSubFromList(sub, n.psubs)
return found
}
// We have a queue group subscription here
if i := findQSliceForSub(sub, n.qsubs); i >= 0 {
n.qsubs[i], found = removeSubFromList(sub, n.qsubs[i])
if len(n.qsubs[i]) == 0 {
last := len(n.qsubs) - 1
n.qsubs[i] = n.qsubs[last]
n.qsubs[last] = nil
n.qsubs = n.qsubs[:last]
if len(n.qsubs) == 0 {
n.qsubs = nil
}
}
return found
}
return false
}
// Checks if we need to do a resize. This is for very large growth then
// subsequent return to a more normal size from unsubscribe.
func shrinkAsNeeded(sl []*subscription) []*subscription {
lsl := len(sl)
csl := cap(sl)
// Don't bother if list not too big
if csl <= 8 {
return sl
}
pFree := float32(csl-lsl) / float32(csl)
if pFree > 0.50 {
return append([]*subscription(nil), sl...)
}
return sl
}
// Count returns the number of subscriptions.
func (s *Sublist) Count() uint32 {
s.RLock()
defer s.RUnlock()
return s.count
}
// CacheCount returns the number of result sets in the cache.
func (s *Sublist) CacheCount() int {
s.RLock()
defer s.RUnlock()
return len(s.cache)
}
// Public stats for the sublist
type SublistStats struct {
NumSubs uint32 `json:"num_subscriptions"`
NumCache uint32 `json:"num_cache"`
NumInserts uint64 `json:"num_inserts"`
NumRemoves uint64 `json:"num_removes"`
NumMatches uint64 `json:"num_matches"`
CacheHitRate float64 `json:"cache_hit_rate"`
MaxFanout uint32 `json:"max_fanout"`
AvgFanout float64 `json:"avg_fanout"`
}
// Stats will return a stats structure for the current state.
func (s *Sublist) Stats() *SublistStats {
s.Lock()
defer s.Unlock()
st := &SublistStats{}
st.NumSubs = s.count
st.NumCache = uint32(len(s.cache))
st.NumInserts = s.inserts
st.NumRemoves = s.removes
st.NumMatches = s.matches
if s.matches > 0 {
st.CacheHitRate = float64(s.cacheHits) / float64(s.matches)
}
// whip through cache for fanout stats
tot, max := 0, 0
for _, r := range s.cache {
l := len(r.psubs) + len(r.qsubs)
tot += l
if l > max {
max = l
}
}
st.MaxFanout = uint32(max)
if tot > 0 {
st.AvgFanout = float64(tot) / float64(len(s.cache))
}
return st
}
// numLevels will return the maximum number of levels
// contained in the Sublist tree.
func (s *Sublist) numLevels() int {
return visitLevel(s.root, 0)
}
// visitLevel is used to descend the Sublist tree structure
// recursively.
func visitLevel(l *level, depth int) int {
if l == nil || l.numNodes() == 0 {
return depth
}
depth++
maxDepth := depth
for _, n := range l.nodes {
if n == nil {
continue
}
newDepth := visitLevel(n.next, depth)
if newDepth > maxDepth {
maxDepth = newDepth
}
}
if l.pwc != nil {
pwcDepth := visitLevel(l.pwc.next, depth)
if pwcDepth > maxDepth {
maxDepth = pwcDepth
}
}
if l.fwc != nil {
fwcDepth := visitLevel(l.fwc.next, depth)
if fwcDepth > maxDepth {
maxDepth = fwcDepth
}
}
return maxDepth
}
// IsValidSubject returns true if a subject is valid, false otherwise
func IsValidSubject(subject string) bool {
if subject == "" {
return false
}
sfwc := false
tokens := strings.Split(string(subject), tsep)
for _, t := range tokens {
if len(t) == 0 || sfwc {
return false
}
if len(t) > 1 {
continue
}
switch t[0] {
case fwc:
sfwc = true
}
}
return true
}
// IsValidLiteralSubject returns true if a subject is valid and literal (no wildcards), false otherwise
func IsValidLiteralSubject(subject string) bool {
tokens := strings.Split(string(subject), tsep)
for _, t := range tokens {
if len(t) == 0 {
return false
}
if len(t) > 1 {
continue
}
switch t[0] {
case pwc, fwc:
return false
}
}
return true
}
// matchLiteral is used to test literal subjects, those that do not have any
// wildcards, with a target subject. This is used in the cache layer.
func matchLiteral(literal, subject string) bool {
li := 0
ll := len(literal)
for i := 0; i < len(subject); i++ {
if li >= ll {
return false
}
b := subject[i]
switch b {
case pwc:
// Skip token in literal
ll := len(literal)
for {
if li >= ll || literal[li] == btsep {
li--
break
}
li++
}
case fwc:
return true
default:
if b != literal[li] {
return false
}
}
li++
}
// Make sure we have processed all of the literal's chars..
return li >= ll
}
| 1 | 6,863 | Looks like `s.inserts` and `s.removes` are updated under sublist's lock, so I don't think you need atomic for those 2. | nats-io-nats-server | go |
@@ -39,7 +39,10 @@ void setUseStaticIP(bool enabled) {
void markGotIP() {
lastGetIPmoment = millis();
+ // Create the 'got IP event' so mark the wifiStatus to not have the got IP flag set
+ // This also implies the services are not fully initialized.
wifiStatus &= ~ESPEASY_WIFI_GOT_IP;
+ wifiStatus &= ~ESPEASY_WIFI_SERVICES_INITIALIZED;
processedGotIP = false;
}
| 1 | #ifdef HAS_ETHERNET
#include "ETH.h"
#endif
#include "ESPEasyWiFiEvent.h"
#include "ESPEasyWifi_ProcessEvent.h"
#include "src/Globals/ESPEasyWiFiEvent.h"
#include "src/Globals/RTC.h"
#include "ESPEasyTimeTypes.h"
#include "ESPEasy_Log.h"
#include "ESPEasy_fdwdecl.h"
#include "src/DataStructs/RTCStruct.h"
#include "src/Helpers/ESPEasy_time_calc.h"
#ifdef HAS_ETHERNET
extern bool eth_connected;
#endif
#ifdef ESP32
void WiFi_Access_Static_IP::set_use_static_ip(bool enabled) {
_useStaticIp = enabled;
}
#endif // ifdef ESP32
#ifdef ESP8266
void WiFi_Access_Static_IP::set_use_static_ip(bool enabled) {
_useStaticIp = enabled;
}
#endif // ifdef ESP8266
void setUseStaticIP(bool enabled) {
WiFi_Access_Static_IP tmp_wifi;
tmp_wifi.set_use_static_ip(enabled);
}
void markGotIP() {
lastGetIPmoment = millis();
wifiStatus &= ~ESPEASY_WIFI_GOT_IP;
processedGotIP = false;
}
// ********************************************************************************
// Functions called on events.
// Make sure not to call anything in these functions that result in delay() or yield()
// ********************************************************************************
#ifdef ESP32
#include <WiFi.h>
static bool ignoreDisconnectEvent = false;
void WiFiEvent(system_event_id_t event, system_event_info_t info) {
switch (event) {
case SYSTEM_EVENT_STA_CONNECTED:
{
RTC.lastWiFiChannel = info.connected.channel;
for (byte i = 0; i < 6; ++i) {
if (RTC.lastBSSID[i] != info.connected.bssid[i]) {
bssid_changed = true;
RTC.lastBSSID[i] = info.connected.bssid[i];
}
}
char ssid_copy[33] = { 0 }; // Ensure space for maximum len SSID (32) plus trailing 0
memcpy(ssid_copy, info.connected.ssid, info.connected.ssid_len);
ssid_copy[32] = 0; // Potentially add 0-termination if none present earlier
last_ssid = (const char*) ssid_copy;
lastConnectMoment = millis();
processedConnect = false;
break;
}
case SYSTEM_EVENT_STA_DISCONNECTED:
if (!ignoreDisconnectEvent) {
ignoreDisconnectEvent = true;
lastDisconnectMoment = millis();
WiFi.persistent(false);
WiFi.disconnect(true);
if (timeDiff(lastConnectMoment, last_wifi_connect_attempt_moment) > 0) {
// There was an unsuccessful connection attempt
lastConnectedDuration = timeDiff(last_wifi_connect_attempt_moment, lastDisconnectMoment);
} else {
lastConnectedDuration = timeDiff(lastConnectMoment, lastDisconnectMoment);
}
processedDisconnect = false;
lastDisconnectReason = static_cast<WiFiDisconnectReason>(info.disconnected.reason);
}
break;
case SYSTEM_EVENT_STA_GOT_IP:
ignoreDisconnectEvent = false;
markGotIP();
break;
case SYSTEM_EVENT_AP_STACONNECTED:
for (byte i = 0; i < 6; ++i) {
lastMacConnectedAPmode[i] = info.sta_connected.mac[i];
}
processedConnectAPmode = false;
break;
case SYSTEM_EVENT_AP_STADISCONNECTED:
for (byte i = 0; i < 6; ++i) {
lastMacConnectedAPmode[i] = info.sta_disconnected.mac[i];
}
processedDisconnectAPmode = false;
break;
case SYSTEM_EVENT_SCAN_DONE:
processedScanDone = false;
break;
#ifdef HAS_ETHERNET
case SYSTEM_EVENT_ETH_START:
addLog(LOG_LEVEL_INFO, F("ETH Started"));
break;
case SYSTEM_EVENT_ETH_CONNECTED:
addLog(LOG_LEVEL_INFO, F("ETH Connected"));
eth_connected = true;
processEthernetConnected();
break;
case SYSTEM_EVENT_ETH_GOT_IP:
{
String log = F("ETH MAC: ");
log += NetworkMacAddress();
log += F(" IPv4: ");
log += NetworkLocalIP().toString();
log += " (";
log += NetworkGetHostname();
log += F(") GW: ");
log += NetworkGatewayIP().toString();
log += F(" SN: ");
log += NetworkSubnetMask().toString();
if (ETH.fullDuplex()) {
log += F(" FULL_DUPLEX");
}
log += F(" ");
log += ETH.linkSpeed();
log += F("Mbps");
addLog(LOG_LEVEL_INFO, log);
}
eth_connected = true;
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
addLog(LOG_LEVEL_ERROR, F("ETH Disconnected"));
eth_connected = false;
processEthernetDisconnected();
break;
case SYSTEM_EVENT_ETH_STOP:
addLog(LOG_LEVEL_INFO, F("ETH Stopped"));
eth_connected = false;
break;
case SYSTEM_EVENT_GOT_IP6:
addLog(LOG_LEVEL_INFO, F("ETH Got IP6"));
break;
#endif //HAS_ETHERNET
default:
break;
}
}
#endif // ifdef ESP32
#ifdef ESP8266
void onConnected(const WiFiEventStationModeConnected& event) {
lastConnectMoment = millis();
processedConnect = false;
channel_changed = RTC.lastWiFiChannel != event.channel;
RTC.lastWiFiChannel = event.channel;
last_ssid = event.ssid;
bssid_changed = false;
for (byte i = 0; i < 6; ++i) {
if (RTC.lastBSSID[i] != event.bssid[i]) {
bssid_changed = true;
RTC.lastBSSID[i] = event.bssid[i];
}
}
}
void onDisconnect(const WiFiEventStationModeDisconnected& event) {
lastDisconnectMoment = millis();
if (timeDiff(lastConnectMoment, last_wifi_connect_attempt_moment) > 0) {
// There was an unsuccessful connection attempt
lastConnectedDuration = timeDiff(last_wifi_connect_attempt_moment, lastDisconnectMoment);
} else {
lastConnectedDuration = timeDiff(lastConnectMoment, lastDisconnectMoment);
}
lastDisconnectReason = event.reason;
if (WiFi.status() == WL_CONNECTED) {
// See https://github.com/esp8266/Arduino/issues/5912
WiFi.persistent(false);
WiFi.disconnect(true);
}
processedDisconnect = false;
}
void onGotIP(const WiFiEventStationModeGotIP& event) {
markGotIP();
}
void ICACHE_RAM_ATTR onDHCPTimeout() {
processedDHCPTimeout = false;
}
void onConnectedAPmode(const WiFiEventSoftAPModeStationConnected& event) {
for (byte i = 0; i < 6; ++i) {
lastMacConnectedAPmode[i] = event.mac[i];
}
processedConnectAPmode = false;
}
void onDisonnectedAPmode(const WiFiEventSoftAPModeStationDisconnected& event) {
for (byte i = 0; i < 6; ++i) {
lastMacDisconnectedAPmode[i] = event.mac[i];
}
processedDisconnectAPmode = false;
}
#endif // ifdef ESP8266
| 1 | 19,986 | @TD-er use bitRead/bitWrite macros, do you use here inversed logic? | letscontrolit-ESPEasy | cpp |
@@ -19,11 +19,11 @@
/**
* External dependencies
*/
+import fetchMock from 'fetch-mock-jest';
/**
* WordPress dependencies
*/
-import apiFetch from '@wordpress/api-fetch';
import { createRegistry } from '@wordpress/data';
/** | 1 | /**
* Settings datastore functions tests.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
/**
* WordPress dependencies
*/
import apiFetch from '@wordpress/api-fetch';
import { createRegistry } from '@wordpress/data';
/**
* Internal dependencies
*/
import API from 'googlesitekit-api';
import {
muteConsole,
subscribeUntil,
unsubscribeFromAll,
} from '../../../../tests/js/utils';
import { createSettingsStore } from './create-settings-store';
const STORE_ARGS = [ 'core', 'site', 'settings' ];
describe( 'createSettingsStore store', () => {
let apiFetchSpy;
let dispatch;
let registry;
let select;
let storeDefinition;
let store;
beforeAll( () => {
API.setUsingCache( false );
} );
beforeEach( () => {
registry = createRegistry();
storeDefinition = createSettingsStore( ...STORE_ARGS, {
settingSlugs: [ 'isSkyBlue' ],
registry,
} );
registry.registerStore( storeDefinition.STORE_NAME, storeDefinition );
dispatch = registry.dispatch( storeDefinition.STORE_NAME );
store = registry.stores[ storeDefinition.STORE_NAME ].store;
select = registry.select( storeDefinition.STORE_NAME );
apiFetchSpy = jest.spyOn( { apiFetch }, 'apiFetch' );
} );
afterAll( () => {
API.setUsingCache( true );
} );
afterEach( () => {
unsubscribeFromAll( registry );
apiFetchSpy.mockRestore();
} );
describe( 'name', () => {
it( 'returns the correct default store name', () => {
expect( storeDefinition.STORE_NAME ).toEqual( `${ STORE_ARGS[ 0 ] }/${ STORE_ARGS[ 1 ] }` );
} );
} );
describe( 'actions', () => {
describe( 'setSettings', () => {
it( 'requires the values param', () => {
expect( () => {
dispatch.setSettings();
} ).toThrow( 'values is required.' );
} );
it( 'updates the respective settings', () => {
const values1 = { setting1: 'old', setting2: 'old' };
const values2 = { setting2: 'new' };
dispatch.setSettings( values1 );
expect( store.getState().settings ).toMatchObject( values1 );
dispatch.setSettings( values2 );
expect( store.getState().settings ).toMatchObject( { ...values1, ...values2 } );
} );
} );
describe( 'fetchSettings', () => {
it( 'does not require any params', () => {
expect( () => {
dispatch.fetchSettings();
} ).not.toThrow();
} );
} );
describe( 'receiveSettings', () => {
it( 'requires the values param', () => {
expect( () => {
dispatch.receiveSettings();
} ).toThrow( 'values is required.' );
} );
it( 'receives and sets values', () => {
const serverValues = { setting1: 'serverside', setting2: 'serverside' };
const clientValues = { setting1: 'clientside' };
dispatch.setSettings( clientValues );
dispatch.receiveSettings( serverValues );
// Client values take precedence if they were already modified before receiving from the server.
expect( store.getState().settings ).toMatchObject( { ...serverValues, ...clientValues } );
} );
} );
describe( 'saveSettings', () => {
it( 'does not require any params', () => {
expect( async () => {
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponseOnce(
JSON.stringify( { setting1: 'serverside' } ),
{ status: 200 }
);
await dispatch.saveSettings();
} ).not.toThrow();
} );
it( 'updates settings from server', async () => {
const response = { isSkyBlue: 'yes' };
fetch
.doMockIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponse(
JSON.stringify( response ),
{ status: 200 }
);
// The server is the authority. So because this won't be part of the response
// (see above), it will be disregarded.
dispatch.setSettings( { isSkyBlue: 'no' } );
dispatch.saveSettings();
await subscribeUntil( registry, () => select.isDoingSaveSettings() === false );
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( JSON.parse( fetch.mock.calls[ 0 ][ 1 ].body ).data ).toMatchObject( { isSkyBlue: 'no' } );
expect( store.getState().settings ).toMatchObject( response );
} );
} );
describe( 'fetchSaveSettings', () => {
it( 'requires the values param', () => {
const consoleErrorSpy = jest.spyOn( global.console, 'error' );
dispatch.fetchSaveSettings();
expect( consoleErrorSpy ).toHaveBeenCalledWith( 'values is required.' );
consoleErrorSpy.mockClear();
} );
it( 'sets isDoingSaveSettings', () => {
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponseOnce(
JSON.stringify( { setting1: true } ),
{ status: 200 }
);
dispatch.fetchSaveSettings( {} );
expect( select.isDoingSaveSettings() ).toEqual( true );
} );
} );
describe( 'receiveSaveSettings', () => {
it( 'requires the values param', () => {
expect( () => {
dispatch.receiveSaveSettings();
} ).toThrow( 'values is required.' );
} );
it( 'receives and sets values', () => {
const serverValues = { setting1: 'serverside', setting2: 'serverside' };
const clientValues = { setting1: 'clientside', setting3: 'clientside' };
dispatch.setSettings( clientValues );
dispatch.receiveSaveSettings( serverValues );
// Client values are ignored here, server values replace them.
expect( store.getState().settings ).toMatchObject( { ...serverValues } );
} );
} );
// Tests for "pseudo-action" setSetting, available via setting-specific "set{SettingSlug}".
describe( 'setSetting', () => {
it( 'has the correct action name', () => {
expect( Object.keys( storeDefinition.actions ) ).toEqual(
// "isSkyBlue" should turn into "setIsSkyBlue".
expect.arrayContaining( [ 'setIsSkyBlue' ] )
);
} );
it( 'returns the correct action type', () => {
const action = storeDefinition.actions.setIsSkyBlue( true );
// "isSkyBlue" should turn into "SET_IS_SKY_BLUE".
expect( action.type ).toEqual( 'SET_IS_SKY_BLUE' );
} );
it( 'requires the value param', () => {
expect( () => {
dispatch.setIsSkyBlue();
} ).toThrow( 'value is required.' );
} );
it( 'supports setting falsy values', () => {
expect( () => {
dispatch.setIsSkyBlue( false );
} ).not.toThrow( 'value is required.' );
} );
it( 'updates the respective setting', () => {
const value = 'new';
dispatch.setIsSkyBlue( value );
expect( store.getState().settings ).toMatchObject( { isSkyBlue: value } );
} );
} );
describe( 'rollbackSettings', () => {
it( 'returns settings back to their saved values', () => {
const savedSettings = { isSkyBlue: 'yes' };
dispatch.receiveSaveSettings( savedSettings );
expect( select.getIsSkyBlue() ).toBe( 'yes' );
dispatch.setIsSkyBlue( 'maybe' );
expect( select.getIsSkyBlue() ).toBe( 'maybe' );
dispatch.rollbackSettings();
expect( select.getIsSkyBlue() ).toBe( 'yes' );
} );
} );
} );
describe( 'selectors', () => {
describe( 'getSettings', () => {
it( 'uses a resolver to make a network request', async () => {
const response = { setting1: 'value' };
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponseOnce(
JSON.stringify( response ),
{ status: 200 }
);
const initialSettings = select.getSettings();
// Settings will be their initial value while being fetched.
expect( initialSettings ).toEqual( undefined );
await subscribeUntil( registry,
() => (
select.getSettings() !== undefined
),
);
const settings = select.getSettings();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( settings ).toEqual( response );
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( select.getSettings() ).toEqual( settings );
} );
it( 'does not make a network request if settings are already set', async () => {
const value = 'serverside';
dispatch.receiveSettings( { isSkyBlue: value } );
expect( select.getIsSkyBlue() ).toEqual( value );
await subscribeUntil( registry, () => select.hasFinishedResolution( 'getSettings' ) );
expect( fetch ).not.toHaveBeenCalled();
} );
it( 'returns client settings even if server settings have not loaded', () => {
const values = { setting1: 'value' };
dispatch.setSettings( values );
// If settings are set on the client, they must be available even
// if settings have not been loaded from the server yet.
muteConsole( 'error' ); // Ignore the API fetch failure here.
expect( select.getSettings() ).toEqual( values );
} );
it( 'dispatches an error if the request fails', async () => {
const response = {
code: 'internal_server_error',
message: 'Internal server error',
data: { status: 500 },
};
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponseOnce(
JSON.stringify( response ),
{ status: 500 }
);
muteConsole( 'error' );
select.getSettings();
await subscribeUntil( registry,
// TODO: We may want a selector for this, but for now this is fine
// because it's internal-only.
() => store.getState().isFetchingSettings === false,
);
const settings = select.getSettings();
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( settings ).toEqual( undefined );
} );
} );
describe( 'haveSettingsChanged', () => {
it( 'informs whether client-side settings differ from server-side ones', async () => {
// Initially false.
expect( select.haveSettingsChanged() ).toEqual( false );
const serverValues = { setting1: 'serverside' };
const clientValues = { setting1: 'clientside' };
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponseOnce(
JSON.stringify( serverValues ),
{ status: 200 }
);
select.getSettings();
await subscribeUntil( registry,
() => (
select.getSettings() !== undefined
),
);
// Still false after fetching settings from server.
expect( select.haveSettingsChanged() ).toEqual( false );
// True after updating settings on client.
dispatch.setSettings( clientValues );
expect( select.haveSettingsChanged() ).toEqual( true );
// False after updating settings back to original server value on client.
dispatch.setSettings( serverValues );
expect( select.haveSettingsChanged() ).toEqual( false );
} );
} );
// Tests for "pseudo-selector" getSetting, available via setting-specific "get{SettingSlug}".
describe( 'getSetting', () => {
it( 'has the correct selector name', () => {
expect( Object.keys( storeDefinition.selectors ) ).toEqual(
// "isSkyBlue" should turn into "getIsSkyBlue".
expect.arrayContaining( [ 'getIsSkyBlue' ] )
);
} );
it( 'uses a resolver to make a network request', async () => {
const value = 'serverside';
fetch
.doMockOnceIf(
/^\/google-site-kit\/v1\/core\/site\/data\/settings/
)
.mockResponseOnce(
JSON.stringify( {
otherSetting: 'other-value',
isSkyBlue: value,
} ),
{ status: 200 }
);
// Setting will have its initial value while being fetched.
expect( select.getIsSkyBlue() ).toEqual( undefined );
await subscribeUntil( registry,
() => (
select.getSettings() !== undefined
),
);
expect( fetch ).toHaveBeenCalledTimes( 1 );
expect( select.getIsSkyBlue() ).toEqual( value );
expect( fetch ).toHaveBeenCalledTimes( 1 );
} );
} );
} );
describe( 'per-setting selectors', () => {
it( 'get{SettingSlug}', () => {
dispatch.setSettings( { isSkyBlue: 'yes' } );
expect( select.getIsSkyBlue() ).toBe( 'yes' );
} );
it( 'set{SettingSlug}', () => {
dispatch.setSettings( { isSkyBlue: 'yes' } );
dispatch.setIsSkyBlue( 'not right now' );
expect( select.getIsSkyBlue() ).toBe( 'not right now' );
} );
} );
describe( 'controls', () => {
describe( 'FETCH_SETTINGS', () => {
it( 'requests from the correct API endpoint', async () => {
const [ type, identifier, datapoint ] = STORE_ARGS;
const response = { type, identifier, datapoint };
fetch
.mockResponseOnce( async ( req ) => {
if ( req.url.startsWith( `/google-site-kit/v1/${ type }/${ identifier }/data/${ datapoint }` ) ) {
return {
body: JSON.stringify( response ),
init: { status: 200 },
};
}
return {
body: JSON.stringify( {
code: 'incorrect_api_endpoint',
message: 'Incorrect API endpoint',
data: { status: 400 },
} ),
init: { status: 400 },
};
} );
const result = await storeDefinition.controls.FETCH_SETTINGS();
expect( result ).toEqual( response );
// Ensure `console.error()` wasn't called, which will happen if the API
// request fails.
expect( global.console.error ).not.toHaveBeenCalled();
} );
} );
describe( 'FETCH_SAVE_SETTINGS', () => {
it( 'requests from the correct API endpoint', async () => {
const [ type, identifier, datapoint ] = STORE_ARGS;
const response = { type, identifier, datapoint };
fetch
.mockResponseOnce( async ( req ) => {
if ( req.url.startsWith( `/google-site-kit/v1/${ type }/${ identifier }/data/${ datapoint }` ) ) {
return {
body: JSON.stringify( response ),
init: { status: 200 },
};
}
return {
body: JSON.stringify( {
code: 'incorrect_api_endpoint',
message: 'Incorrect API endpoint',
data: { status: 400 },
} ),
init: { status: 400 },
};
} );
const result = await storeDefinition.controls.FETCH_SAVE_SETTINGS( {
type: 'FETCH_SAVE_SETTINGS',
payload: { values: {} },
} );
expect( result ).toEqual( response );
// Ensure `console.error()` wasn't called, which will happen if the API
// request fails.
expect( global.console.error ).not.toHaveBeenCalled();
} );
} );
} );
} );
| 1 | 29,174 | The previous `fetch` mock was exposed globally before - can we do the same with `fetchMock` so we don't need to import it in every file? | google-site-kit-wp | js |
@@ -29,9 +29,9 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
HttpRequestHeaders headers,
Http2Stream context)
{
- if (!context.ExpectData)
+ if (context.EndStreamReceived)
{
- return MessageBody.ZeroContentLengthClose;
+ return ZeroContentLengthClose;
}
return new ForHttp2(context); | 1 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2
{
public abstract class Http2MessageBody : MessageBody
{
private readonly Http2Stream _context;
protected Http2MessageBody(Http2Stream context)
: base(context)
{
_context = context;
}
protected override Task OnConsumeAsync() => Task.CompletedTask;
public override Task StopAsync()
{
_context.RequestBodyPipe.Reader.Complete();
_context.RequestBodyPipe.Writer.Complete();
return Task.CompletedTask;
}
public static MessageBody For(
HttpRequestHeaders headers,
Http2Stream context)
{
if (!context.ExpectData)
{
return MessageBody.ZeroContentLengthClose;
}
return new ForHttp2(context);
}
private class ForHttp2 : Http2MessageBody
{
public ForHttp2(Http2Stream context)
: base(context)
{
}
}
}
}
| 1 | 14,119 | Is ExpectData still used anywhere? | aspnet-KestrelHttpServer | .cs |
@@ -230,7 +230,7 @@ class Docstring:
class SphinxDocstring(Docstring):
re_type = r"""
- [~!]? # Optional link style prefix
+ [~!.]? # Optional link style prefix
\w(?:\w|\.[^\.])* # Valid python name
"""
| 1 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-2018 Ashley Whetter <ashley@awhetter.co.uk>
# Copyright (c) 2016-2017 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2016 Yuri Bochkarev <baltazar.bz@gmail.com>
# Copyright (c) 2016 Glenn Matthews <glenn@e-dad.net>
# Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
# Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2017 Mitar <mitar.github@tnode.com>
# Copyright (c) 2018 ssolanki <sushobhitsolanki@gmail.com>
# Copyright (c) 2018 Anthony Sottile <asottile@umich.edu>
# Copyright (c) 2018 Mitchell T.H. Young <mitchelly@gmail.com>
# Copyright (c) 2018 Adrian Chirieac <chirieacam@gmail.com>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/COPYING
"""Utility methods for docstring checking."""
from __future__ import absolute_import, print_function
import re
import astroid
from pylint.checkers import utils
def space_indentation(s):
"""The number of leading spaces in a string
:param str s: input string
:rtype: int
:return: number of leading spaces
"""
return len(s) - len(s.lstrip(" "))
def get_setters_property_name(node):
"""Get the name of the property that the given node is a setter for.
:param node: The node to get the property name for.
:type node: str
:rtype: str or None
:returns: The name of the property that the node is a setter for,
or None if one could not be found.
"""
decorators = node.decorators.nodes if node.decorators else []
for decorator in decorators:
if (
isinstance(decorator, astroid.Attribute)
and decorator.attrname == "setter"
and isinstance(decorator.expr, astroid.Name)
):
return decorator.expr.name
return None
def get_setters_property(node):
"""Get the property node for the given setter node.
:param node: The node to get the property for.
:type node: astroid.FunctionDef
:rtype: astroid.FunctionDef or None
:returns: The node relating to the property of the given setter node,
or None if one could not be found.
"""
property_ = None
property_name = get_setters_property_name(node)
class_node = utils.node_frame_class(node)
if property_name and class_node:
class_attrs = class_node.getattr(node.name)
for attr in class_attrs:
if utils.decorated_with_property(attr):
property_ = attr
break
return property_
def returns_something(return_node):
"""Check if a return node returns a value other than None.
:param return_node: The return node to check.
:type return_node: astroid.Return
:rtype: bool
:return: True if the return node returns a value other than None,
False otherwise.
"""
returns = return_node.value
if returns is None:
return False
return not (isinstance(returns, astroid.Const) and returns.value is None)
def _get_raise_target(node):
if isinstance(node.exc, astroid.Call):
func = node.exc.func
if isinstance(func, (astroid.Name, astroid.Attribute)):
return utils.safe_infer(func)
return None
def possible_exc_types(node):
"""
Gets all of the possible raised exception types for the given raise node.
.. note::
Caught exception types are ignored.
:param node: The raise node to find exception types for.
:type node: astroid.node_classes.NodeNG
:returns: A list of exception types possibly raised by :param:`node`.
:rtype: set(str)
"""
excs = []
if isinstance(node.exc, astroid.Name):
inferred = utils.safe_infer(node.exc)
if inferred:
excs = [inferred.name]
elif node.exc is None:
handler = node.parent
while handler and not isinstance(handler, astroid.ExceptHandler):
handler = handler.parent
if handler and handler.type:
inferred_excs = astroid.unpack_infer(handler.type)
excs = (exc.name for exc in inferred_excs if exc is not astroid.Uninferable)
else:
target = _get_raise_target(node)
if isinstance(target, astroid.ClassDef):
excs = [target.name]
elif isinstance(target, astroid.FunctionDef):
for ret in target.nodes_of_class(astroid.Return):
if ret.frame() != target:
# return from inner function - ignore it
continue
val = utils.safe_infer(ret.value)
if (
val
and isinstance(val, (astroid.Instance, astroid.ClassDef))
and utils.inherit_from_std_ex(val)
):
excs.append(val.name)
try:
return {exc for exc in excs if not utils.node_ignores_exception(node, exc)}
except astroid.InferenceError:
return set()
def docstringify(docstring, default_type="default"):
for docstring_type in [
SphinxDocstring,
EpytextDocstring,
GoogleDocstring,
NumpyDocstring,
]:
instance = docstring_type(docstring)
if instance.is_valid():
return instance
docstring_type = DOCSTRING_TYPES.get(default_type, Docstring)
return docstring_type(docstring)
class Docstring:
re_for_parameters_see = re.compile(
r"""
For\s+the\s+(other)?\s*parameters\s*,\s+see
""",
re.X | re.S,
)
supports_yields = None
"""True if the docstring supports a "yield" section.
False if the docstring uses the returns section to document generators.
"""
# These methods are designed to be overridden
# pylint: disable=no-self-use
def __init__(self, doc):
doc = doc or ""
self.doc = doc.expandtabs()
def is_valid(self):
return False
def exceptions(self):
return set()
def has_params(self):
return False
def has_returns(self):
return False
def has_rtype(self):
return False
def has_property_returns(self):
return False
def has_property_type(self):
return False
def has_yields(self):
return False
def has_yields_type(self):
return False
def match_param_docs(self):
return set(), set()
def params_documented_elsewhere(self):
return self.re_for_parameters_see.search(self.doc) is not None
class SphinxDocstring(Docstring):
re_type = r"""
[~!]? # Optional link style prefix
\w(?:\w|\.[^\.])* # Valid python name
"""
re_simple_container_type = r"""
{type} # a container type
[\(\[] [^\n\s]+ [\)\]] # with the contents of the container
""".format(
type=re_type
)
re_xref = r"""
(?::\w+:)? # optional tag
`{}` # what to reference
""".format(
re_type
)
re_param_raw = r"""
: # initial colon
(?: # Sphinx keywords
param|parameter|
arg|argument|
key|keyword
)
\s+ # whitespace
(?: # optional type declaration
({type}|{container_type})
\s+
)?
(\w+) # Parameter name
\s* # whitespace
: # final colon
""".format(
type=re_type, container_type=re_simple_container_type
)
re_param_in_docstring = re.compile(re_param_raw, re.X | re.S)
re_type_raw = r"""
:type # Sphinx keyword
\s+ # whitespace
({type}) # Parameter name
\s* # whitespace
: # final colon
""".format(
type=re_type
)
re_type_in_docstring = re.compile(re_type_raw, re.X | re.S)
re_property_type_raw = r"""
:type: # Sphinx keyword
\s+ # whitespace
{type} # type declaration
""".format(
type=re_type
)
re_property_type_in_docstring = re.compile(re_property_type_raw, re.X | re.S)
re_raise_raw = r"""
: # initial colon
(?: # Sphinx keyword
raises?|
except|exception
)
\s+ # whitespace
({type}) # exception type
\s* # whitespace
: # final colon
""".format(
type=re_type
)
re_raise_in_docstring = re.compile(re_raise_raw, re.X | re.S)
re_rtype_in_docstring = re.compile(r":rtype:")
re_returns_in_docstring = re.compile(r":returns?:")
supports_yields = False
def is_valid(self):
return bool(
self.re_param_in_docstring.search(self.doc)
or self.re_raise_in_docstring.search(self.doc)
or self.re_rtype_in_docstring.search(self.doc)
or self.re_returns_in_docstring.search(self.doc)
or self.re_property_type_in_docstring.search(self.doc)
)
def exceptions(self):
types = set()
for match in re.finditer(self.re_raise_in_docstring, self.doc):
raise_type = match.group(1)
types.add(raise_type)
return types
def has_params(self):
if not self.doc:
return False
return self.re_param_in_docstring.search(self.doc) is not None
def has_returns(self):
if not self.doc:
return False
return bool(self.re_returns_in_docstring.search(self.doc))
def has_rtype(self):
if not self.doc:
return False
return bool(self.re_rtype_in_docstring.search(self.doc))
def has_property_returns(self):
if not self.doc:
return False
# The summary line is the return doc,
# so the first line must not be a known directive.
return not self.doc.lstrip().startswith(":")
def has_property_type(self):
if not self.doc:
return False
return bool(self.re_property_type_in_docstring.search(self.doc))
def match_param_docs(self):
params_with_doc = set()
params_with_type = set()
for match in re.finditer(self.re_param_in_docstring, self.doc):
name = match.group(2)
params_with_doc.add(name)
param_type = match.group(1)
if param_type is not None:
params_with_type.add(name)
params_with_type.update(re.findall(self.re_type_in_docstring, self.doc))
return params_with_doc, params_with_type
class EpytextDocstring(SphinxDocstring):
"""
Epytext is similar to Sphinx. See the docs:
http://epydoc.sourceforge.net/epytext.html
http://epydoc.sourceforge.net/fields.html#fields
It's used in PyCharm:
https://www.jetbrains.com/help/pycharm/2016.1/creating-documentation-comments.html#d848203e314
https://www.jetbrains.com/help/pycharm/2016.1/using-docstrings-to-specify-types.html
"""
re_param_in_docstring = re.compile(
SphinxDocstring.re_param_raw.replace(":", "@", 1), re.X | re.S
)
re_type_in_docstring = re.compile(
SphinxDocstring.re_type_raw.replace(":", "@", 1), re.X | re.S
)
re_property_type_in_docstring = re.compile(
SphinxDocstring.re_property_type_raw.replace(":", "@", 1), re.X | re.S
)
re_raise_in_docstring = re.compile(
SphinxDocstring.re_raise_raw.replace(":", "@", 1), re.X | re.S
)
re_rtype_in_docstring = re.compile(
r"""
@ # initial "at" symbol
(?: # Epytext keyword
rtype|returntype
)
: # final colon
""",
re.X | re.S,
)
re_returns_in_docstring = re.compile(r"@returns?:")
def has_property_returns(self):
if not self.doc:
return False
# If this is a property docstring, the summary is the return doc.
if self.has_property_type():
# The summary line is the return doc,
# so the first line must not be a known directive.
return not self.doc.lstrip().startswith("@")
return False
class GoogleDocstring(Docstring):
re_type = SphinxDocstring.re_type
re_xref = SphinxDocstring.re_xref
re_container_type = r"""
(?:{type}|{xref}) # a container type
[\(\[] [^\n]+ [\)\]] # with the contents of the container
""".format(
type=re_type, xref=re_xref
)
re_multiple_type = r"""
(?:{container_type}|{type}|{xref})
(?:\s+(?:of|or)\s+(?:{container_type}|{type}|{xref}))*
""".format(
type=re_type, xref=re_xref, container_type=re_container_type
)
_re_section_template = r"""
^([ ]*) {0} \s*: \s*$ # Google parameter header
( .* ) # section
"""
re_param_section = re.compile(
_re_section_template.format(r"(?:Args|Arguments|Parameters)"),
re.X | re.S | re.M,
)
re_keyword_param_section = re.compile(
_re_section_template.format(r"Keyword\s(?:Args|Arguments|Parameters)"),
re.X | re.S | re.M,
)
re_param_line = re.compile(
r"""
\s* \*{{0,2}}(\w+) # identifier potentially with asterisks
\s* ( [(]
{type}
(?:,\s+optional)?
[)] )? \s* : # optional type declaration
\s* (.*) # beginning of optional description
""".format(
type=re_multiple_type
),
re.X | re.S | re.M,
)
re_raise_section = re.compile(
_re_section_template.format(r"Raises"), re.X | re.S | re.M
)
re_raise_line = re.compile(
r"""
\s* ({type}) \s* : # identifier
\s* (.*) # beginning of optional description
""".format(
type=re_type
),
re.X | re.S | re.M,
)
re_returns_section = re.compile(
_re_section_template.format(r"Returns?"), re.X | re.S | re.M
)
re_returns_line = re.compile(
r"""
\s* ({type}:)? # identifier
\s* (.*) # beginning of description
""".format(
type=re_multiple_type
),
re.X | re.S | re.M,
)
re_property_returns_line = re.compile(
r"""
^{type}: # indentifier
\s* (.*) # Summary line / description
""".format(
type=re_multiple_type
),
re.X | re.S | re.M,
)
re_yields_section = re.compile(
_re_section_template.format(r"Yields?"), re.X | re.S | re.M
)
re_yields_line = re_returns_line
supports_yields = True
def is_valid(self):
return bool(
self.re_param_section.search(self.doc)
or self.re_raise_section.search(self.doc)
or self.re_returns_section.search(self.doc)
or self.re_yields_section.search(self.doc)
or self.re_property_returns_line.search(self._first_line())
)
def has_params(self):
if not self.doc:
return False
return self.re_param_section.search(self.doc) is not None
def has_returns(self):
if not self.doc:
return False
entries = self._parse_section(self.re_returns_section)
for entry in entries:
match = self.re_returns_line.match(entry)
if not match:
continue
return_desc = match.group(2)
if return_desc:
return True
return False
def has_rtype(self):
if not self.doc:
return False
entries = self._parse_section(self.re_returns_section)
for entry in entries:
match = self.re_returns_line.match(entry)
if not match:
continue
return_type = match.group(1)
if return_type:
return True
return False
def has_property_returns(self):
# The summary line is the return doc,
# so the first line must not be a known directive.
first_line = self._first_line()
return not bool(
self.re_param_section.search(first_line)
or self.re_raise_section.search(first_line)
or self.re_returns_section.search(first_line)
or self.re_yields_section.search(first_line)
)
def has_property_type(self):
if not self.doc:
return False
return bool(self.re_property_returns_line.match(self._first_line()))
def has_yields(self):
if not self.doc:
return False
entries = self._parse_section(self.re_yields_section)
for entry in entries:
match = self.re_yields_line.match(entry)
if not match:
continue
yield_desc = match.group(2)
if yield_desc:
return True
return False
def has_yields_type(self):
if not self.doc:
return False
entries = self._parse_section(self.re_yields_section)
for entry in entries:
match = self.re_yields_line.match(entry)
if not match:
continue
yield_type = match.group(1)
if yield_type:
return True
return False
def exceptions(self):
types = set()
entries = self._parse_section(self.re_raise_section)
for entry in entries:
match = self.re_raise_line.match(entry)
if not match:
continue
exc_type = match.group(1)
exc_desc = match.group(2)
if exc_desc:
types.add(exc_type)
return types
def match_param_docs(self):
params_with_doc = set()
params_with_type = set()
entries = self._parse_section(self.re_param_section)
entries.extend(self._parse_section(self.re_keyword_param_section))
for entry in entries:
match = self.re_param_line.match(entry)
if not match:
continue
param_name = match.group(1)
param_type = match.group(2)
param_desc = match.group(3)
if param_type:
params_with_type.add(param_name)
if param_desc:
params_with_doc.add(param_name)
return params_with_doc, params_with_type
def _first_line(self):
return self.doc.lstrip().split("\n", 1)[0]
@staticmethod
def min_section_indent(section_match):
return len(section_match.group(1)) + 1
@staticmethod
def _is_section_header(_):
# Google parsing does not need to detect section headers,
# because it works off of indentation level only
return False
def _parse_section(self, section_re):
section_match = section_re.search(self.doc)
if section_match is None:
return []
min_indentation = self.min_section_indent(section_match)
entries = []
entry = []
is_first = True
for line in section_match.group(2).splitlines():
if not line.strip():
continue
indentation = space_indentation(line)
if indentation < min_indentation:
break
# The first line after the header defines the minimum
# indentation.
if is_first:
min_indentation = indentation
is_first = False
if indentation == min_indentation:
if self._is_section_header(line):
break
# Lines with minimum indentation must contain the beginning
# of a new parameter documentation.
if entry:
entries.append("\n".join(entry))
entry = []
entry.append(line)
if entry:
entries.append("\n".join(entry))
return entries
class NumpyDocstring(GoogleDocstring):
_re_section_template = r"""
^([ ]*) {0} \s*?$ # Numpy parameters header
\s* [-=]+ \s*?$ # underline
( .* ) # section
"""
re_param_section = re.compile(
_re_section_template.format(r"(?:Args|Arguments|Parameters)"),
re.X | re.S | re.M,
)
re_param_line = re.compile(
r"""
\s* (\w+) # identifier
\s* :
\s* (?:({type})(?:,\s+optional)?)? # optional type declaration
\n # description starts on a new line
\s* (.*) # description
""".format(
type=GoogleDocstring.re_multiple_type
),
re.X | re.S,
)
re_raise_section = re.compile(
_re_section_template.format(r"Raises"), re.X | re.S | re.M
)
re_raise_line = re.compile(
r"""
\s* ({type})$ # type declaration
\s* (.*) # optional description
""".format(
type=GoogleDocstring.re_type
),
re.X | re.S | re.M,
)
re_returns_section = re.compile(
_re_section_template.format(r"Returns?"), re.X | re.S | re.M
)
re_returns_line = re.compile(
r"""
\s* (?:\w+\s+:\s+)? # optional name
({type})$ # type declaration
\s* (.*) # optional description
""".format(
type=GoogleDocstring.re_multiple_type
),
re.X | re.S | re.M,
)
re_yields_section = re.compile(
_re_section_template.format(r"Yields?"), re.X | re.S | re.M
)
re_yields_line = re_returns_line
supports_yields = True
@staticmethod
def min_section_indent(section_match):
return len(section_match.group(1))
@staticmethod
def _is_section_header(line):
return bool(re.match(r"\s*-+$", line))
DOCSTRING_TYPES = {
"sphinx": SphinxDocstring,
"epytext": EpytextDocstring,
"google": GoogleDocstring,
"numpy": NumpyDocstring,
"default": Docstring,
}
"""A map of the name of the docstring type to its class.
:type: dict(str, type)
"""
| 1 | 11,324 | Do you want to allow the character `.` or any character? Because inside a regex `.` means any character, if you want to authorize `.` then you need to add `\.` . | PyCQA-pylint | py |
@@ -711,4 +711,18 @@ describe('QueryCursor', function() {
assert.deepEqual(arr, ['KICKBOXER', 'IP MAN', 'ENTER THE DRAGON']);
});
});
+ it('returns array for schema hooks gh-9982', () => {
+ const testSchema = new mongoose.Schema({ name: String });
+ testSchema.post('find', (result) => {
+ assert.ok(Array.isArray(result));
+ });
+ const Movie = db.model('Movie', testSchema);
+ return co(function*() {
+ yield Movie.deleteMany({});
+ yield Movie.create({ name: 'Daniel' }, { name: 'Val' }, { name: 'Daniel' });
+ yield Movie.find({ name: 'Daniel' }).cursor().eachAsync(doc => {
+ assert.ok(Array.isArray(doc));
+ });
+ });
+ });
}); | 1 | /**
* Module dependencies.
*/
'use strict';
const start = require('./common');
const assert = require('assert');
const co = require('co');
const mongoose = start.mongoose;
const Schema = mongoose.Schema;
describe('QueryCursor', function() {
let db;
let Model;
before(function() {
db = start();
});
after(function(done) {
db.close(done);
});
beforeEach(() => db.deleteModel(/.*/));
afterEach(() => require('./util').clearTestData(db));
afterEach(() => require('./util').stopRemainingOps(db));
beforeEach(function() {
const schema = new Schema({ name: String });
schema.virtual('test').get(function() { return 'test'; });
Model = db.model('Test', schema);
return Model.create({ name: 'Axl' }, { name: 'Slash' });
});
describe('#next()', function() {
it('with callbacks', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor();
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc.name, 'Axl');
assert.equal(doc.test, 'test');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc.name, 'Slash');
assert.equal(doc.test, 'test');
done();
});
});
});
it('with promises', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor();
cursor.next().then(function(doc) {
assert.equal(doc.name, 'Axl');
assert.equal(doc.test, 'test');
cursor.next().then(function(doc) {
assert.equal(doc.name, 'Slash');
assert.equal(doc.test, 'test');
done();
});
});
});
it('with limit (gh-4266)', function(done) {
const cursor = Model.find().limit(1).sort({ name: 1 }).cursor();
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc.name, 'Axl');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.ok(!doc);
done();
});
});
});
it('with projection', function(done) {
const personSchema = new Schema({
name: String,
born: String
});
const Person = db.model('Person', personSchema);
const people = [
{ name: 'Axl Rose', born: 'William Bruce Rose' },
{ name: 'Slash', born: 'Saul Hudson' }
];
Person.create(people, function(error) {
assert.ifError(error);
const cursor = Person.find({}, { _id: 0, name: 1 }).sort({ name: 1 }).cursor();
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc._id, undefined);
assert.equal(doc.name, 'Axl Rose');
assert.equal(doc.born, undefined);
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc._id, undefined);
assert.equal(doc.name, 'Slash');
assert.equal(doc.born, undefined);
done();
});
});
});
});
describe('with populate', function() {
const bandSchema = new Schema({
name: String,
members: [{ type: mongoose.Schema.ObjectId, ref: 'Person' }]
});
const personSchema = new Schema({
name: String
});
let Band;
beforeEach(function(done) {
const Person = db.model('Person', personSchema);
Band = db.model('Band', bandSchema);
const people = [
{ name: 'Axl Rose' },
{ name: 'Slash' },
{ name: 'Nikki Sixx' },
{ name: 'Vince Neil' },
{ name: 'Trent Reznor' },
{ name: 'Thom Yorke' },
{ name: 'Billy Corgan' }
];
Person.create(people, function(error, docs) {
assert.ifError(error);
const bands = [
{ name: 'Guns N\' Roses', members: [docs[0], docs[1]] },
{ name: 'Motley Crue', members: [docs[2], docs[3]] },
{ name: 'Nine Inch Nails', members: [docs[4]] },
{ name: 'Radiohead', members: [docs[5]] },
{ name: 'The Smashing Pumpkins', members: [docs[6]] }
];
Band.create(bands, function(error) {
assert.ifError(error);
done();
});
});
});
it('with populate without specify batchSize', function(done) {
const cursor =
Band.find().sort({ name: 1 }).populate('members').cursor();
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 1);
assert.equal(doc.name, 'Guns N\' Roses');
assert.equal(doc.members.length, 2);
assert.equal(doc.members[0].name, 'Axl Rose');
assert.equal(doc.members[1].name, 'Slash');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 2);
assert.equal(doc.name, 'Motley Crue');
assert.equal(doc.members.length, 2);
assert.equal(doc.members[0].name, 'Nikki Sixx');
assert.equal(doc.members[1].name, 'Vince Neil');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 3);
assert.equal(doc.name, 'Nine Inch Nails');
assert.equal(doc.members.length, 1);
assert.equal(doc.members[0].name, 'Trent Reznor');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 4);
assert.equal(doc.name, 'Radiohead');
assert.equal(doc.members.length, 1);
assert.equal(doc.members[0].name, 'Thom Yorke');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 5);
assert.equal(doc.name, 'The Smashing Pumpkins');
assert.equal(doc.members.length, 1);
assert.equal(doc.members[0].name, 'Billy Corgan');
done();
});
});
});
});
});
});
it('with populate using custom batchSize', function(done) {
const cursor =
Band.find().sort({ name: 1 }).populate('members').batchSize(3).cursor();
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 3);
assert.equal(doc.name, 'Guns N\' Roses');
assert.equal(doc.members.length, 2);
assert.equal(doc.members[0].name, 'Axl Rose');
assert.equal(doc.members[1].name, 'Slash');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 3);
assert.equal(doc.name, 'Motley Crue');
assert.equal(doc.members.length, 2);
assert.equal(doc.members[0].name, 'Nikki Sixx');
assert.equal(doc.members[1].name, 'Vince Neil');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 3);
assert.equal(doc.name, 'Nine Inch Nails');
assert.equal(doc.members.length, 1);
assert.equal(doc.members[0].name, 'Trent Reznor');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 5);
assert.equal(doc.name, 'Radiohead');
assert.equal(doc.members.length, 1);
assert.equal(doc.members[0].name, 'Thom Yorke');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(cursor.cursor.cursorState.currentLimit, 5);
assert.equal(doc.name, 'The Smashing Pumpkins');
assert.equal(doc.members.length, 1);
assert.equal(doc.members[0].name, 'Billy Corgan');
done();
});
});
});
});
});
});
});
it('casting ObjectIds with where() (gh-4355)', function(done) {
Model.findOne(function(error, doc) {
assert.ifError(error);
assert.ok(doc);
const query = { _id: doc._id.toHexString() };
Model.find().where(query).cursor().next(function(error, doc) {
assert.ifError(error);
assert.ok(doc);
done();
});
});
});
it('cast errors (gh-4355)', function(done) {
Model.find().where({ _id: 'BadId' }).cursor().next(function(error) {
assert.ok(error);
assert.equal(error.name, 'CastError');
assert.equal(error.path, '_id');
done();
});
});
it('with pre-find hooks (gh-5096)', function() {
const schema = new Schema({ name: String });
let called = 0;
schema.pre('find', function(next) {
++called;
next();
});
db.deleteModel(/Test/);
const Model = db.model('Test', schema);
return co(function*() {
yield Model.deleteMany({});
yield Model.create({ name: 'Test' });
const doc = yield Model.find().cursor().next();
assert.equal(called, 1);
assert.equal(doc.name, 'Test');
});
});
});
it('as readable stream', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor();
const expectedNames = ['Axl', 'Slash'];
let cur = 0;
cursor.on('data', function(doc) {
assert.equal(doc.name, expectedNames[cur++]);
assert.equal(doc.test, 'test');
});
cursor.on('error', function(error) {
done(error);
});
cursor.on('end', function() {
assert.equal(cur, 2);
done();
});
});
describe('`transform` option', function() {
it('transforms document', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor({
transform: function(doc) {
doc.name += '_transform';
return doc;
}
});
const expectedNames = ['Axl_transform', 'Slash_transform'];
let cur = 0;
cursor.on('data', function(doc) {
assert.equal(doc.name, expectedNames[cur++]);
assert.equal(doc.test, 'test');
});
cursor.on('error', function(error) {
done(error);
});
cursor.on('end', function() {
assert.equal(cur, 2);
done();
});
});
});
describe('#map', function() {
it('maps documents', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor()
.map(function(obj) {
obj.name += '_mapped';
return obj;
})
.map(function(obj) {
obj.name += '_mappedagain';
return obj;
});
const expectedNames = ['Axl_mapped_mappedagain', 'Slash_mapped_mappedagain'];
let cur = 0;
cursor.on('data', function(doc) {
assert.equal(doc.name, expectedNames[cur++]);
assert.equal(doc.test, 'test');
});
cursor.on('error', function(error) {
done(error);
});
cursor.on('end', function() {
assert.equal(cur, 2);
done();
});
});
it('with #next', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor()
.map(function(obj) {
obj.name += '_next';
return obj;
});
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc.name, 'Axl_next');
assert.equal(doc.test, 'test');
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc.name, 'Slash_next');
assert.equal(doc.test, 'test');
done();
});
});
});
});
describe('#eachAsync()', function() {
it('iterates one-by-one, stopping for promises', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor();
const expectedNames = ['Axl', 'Slash'];
let cur = 0;
const checkDoc = function(doc) {
const _cur = cur;
assert.equal(doc.name, expectedNames[cur]);
return {
then: function(resolve) {
setTimeout(function() {
assert.equal(_cur, cur++);
resolve();
}, 50);
}
};
};
cursor.eachAsync(checkDoc).then(function() {
assert.equal(cur, 2);
done();
}).catch(done);
});
it('parallelization', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor();
const names = [];
const resolves = [];
const checkDoc = function(doc) {
names.push(doc.name);
const p = new Promise(resolve => {
resolves.push(resolve);
});
if (names.length === 2) {
setTimeout(() => resolves.forEach(r => r()), 0);
}
return p;
};
cursor.eachAsync(checkDoc, { parallel: 2 }).then(function() {
assert.equal(names.length, 2);
assert.deepEqual(names.sort(), ['Axl', 'Slash']);
done();
}).catch(done);
});
});
describe('#lean()', function() {
it('lean', function(done) {
const cursor = Model.find().sort({ name: 1 }).lean().cursor();
const expectedNames = ['Axl', 'Slash'];
let cur = 0;
cursor.on('data', function(doc) {
assert.equal(doc.name, expectedNames[cur++]);
assert.strictEqual(doc instanceof mongoose.Document, false);
});
cursor.on('error', function(error) {
done(error);
});
cursor.on('end', function() {
assert.equal(cur, 2);
done();
});
});
it('lean = false (gh-7197)', function() {
const cursor = Model.find().sort({ name: 1 }).lean(false).cursor();
return co(function*() {
const doc = yield cursor.next();
assert.ok(doc instanceof mongoose.Document);
});
});
});
describe('#close()', function() {
it('works (gh-4258)', function(done) {
const cursor = Model.find().sort({ name: 1 }).cursor();
cursor.next(function(error, doc) {
assert.ifError(error);
assert.equal(doc.name, 'Axl');
assert.equal(doc.test, 'test');
let closed = false;
cursor.on('close', function() {
closed = true;
});
cursor.close(function(error) {
assert.ifError(error);
assert.ok(closed);
cursor.next(function(error) {
assert.ok(error);
assert.equal(error.message, 'Cursor is closed');
done();
});
});
});
});
});
it('handles non-boolean lean option (gh-7137)', function() {
const schema = new Schema({ name: String });
db.deleteModel(/Test/);
const Model = db.model('Test', schema);
return co(function*() {
yield Model.deleteMany({});
yield Model.create({ name: 'test' });
let doc;
yield Model.find().lean({ virtuals: true }).cursor().eachAsync(_doc => {
assert.ok(!doc);
doc = _doc;
});
assert.ok(!doc.$__);
});
});
it('addCursorFlag (gh-4814)', function(done) {
const userSchema = new mongoose.Schema({
name: String
});
const User = db.model('User', userSchema);
const cursor = User.find().cursor().addCursorFlag('noCursorTimeout', true);
cursor.on('cursor', function() {
assert.equal(cursor.cursor.cursorState.cmd.noCursorTimeout, true);
done();
});
});
it('data before close (gh-4998)', function(done) {
const userSchema = new mongoose.Schema({
name: String
});
const User = db.model('User', userSchema);
const users = [];
for (let i = 0; i < 100; i++) {
users.push({
_id: mongoose.Types.ObjectId(),
name: 'Bob' + (i < 10 ? '0' : '') + i
});
}
User.insertMany(users, function(error) {
assert.ifError(error);
const stream = User.find({}).cursor();
const docs = [];
stream.on('data', function(doc) {
docs.push(doc);
});
stream.on('close', function() {
assert.equal(docs.length, 100);
done();
});
});
});
it('batchSize option (gh-8039)', function() {
const User = db.model('gh8039', Schema({ name: String }));
let cursor = User.find().cursor({ batchSize: 2000 });
return new Promise(resolve => cursor.once('cursor', () => resolve())).
then(() => assert.equal(cursor.cursor.cursorState.batchSize, 2000)).
then(() => {
cursor = User.find().batchSize(2001).cursor();
}).
then(() => new Promise(resolve => cursor.once('cursor', () => resolve()))).
then(() => {
assert.equal(cursor.cursor.cursorState.batchSize, 2001);
});
});
it('pulls schema-level readPreference (gh-8421)', function() {
const read = 'secondaryPreferred';
const User = db.model('User', Schema({ name: String }, { read }));
const cursor = User.find().cursor();
assert.equal(cursor.options.readPreference.mode, read);
});
it('eachAsync() with parallel > numDocs (gh-8422)', function() {
const schema = new mongoose.Schema({ name: String });
const Movie = db.model('Movie', schema);
return co(function*() {
yield Movie.deleteMany({});
yield Movie.create([
{ name: 'Kickboxer' },
{ name: 'Ip Man' },
{ name: 'Enter the Dragon' }
]);
let numDone = 0;
const test = co.wrap(function*() {
yield new Promise((resolve) => setTimeout(resolve, 100));
++numDone;
});
yield Movie.find().cursor().eachAsync(test, { parallel: 4 });
assert.equal(numDone, 3);
});
});
it('eachAsync() with sort, parallel, and sync function (gh-8557)', function() {
const User = db.model('User', Schema({ order: Number }));
return co(function*() {
yield User.create([{ order: 1 }, { order: 2 }, { order: 3 }]);
const cursor = User.aggregate([{ $sort: { order: 1 } }]).
cursor().
exec();
const docs = [];
yield cursor.eachAsync((doc) => docs.push(doc), { parallel: 3 });
assert.deepEqual(docs.map(d => d.order), [1, 2, 3]);
});
});
it('closing query cursor emits `close` event only once (gh-8835)', function(done) {
const User = db.model('User', new Schema({ name: String }));
const cursor = User.find().cursor();
cursor.on('data', () => {});
let closeEventTriggeredCount = 0;
cursor.on('close', () => closeEventTriggeredCount++);
setTimeout(() => {
assert.equal(closeEventTriggeredCount, 1);
done();
}, 20);
});
it('closing aggregation cursor emits `close` event only once (gh-8835)', function(done) {
const User = db.model('User', new Schema({ name: String }));
const cursor = User.aggregate([{ $match: {} }]).cursor().exec();
cursor.on('data', () => {});
let closeEventTriggeredCount = 0;
cursor.on('close', () => closeEventTriggeredCount++);
setTimeout(() => {
assert.equal(closeEventTriggeredCount, 1);
done();
}, 20);
});
it('passes document index as the second argument for query cursor (gh-8972)', function() {
return co(function *() {
const User = db.model('User', Schema({ order: Number }));
yield User.create([{ order: 1 }, { order: 2 }, { order: 3 }]);
const docsWithIndexes = [];
yield User.find().sort('order').cursor().eachAsync((doc, i) => {
docsWithIndexes.push({ order: doc.order, i: i });
});
const expected = [
{ order: 1, i: 0 },
{ order: 2, i: 1 },
{ order: 3, i: 2 }
];
assert.deepEqual(docsWithIndexes, expected);
});
});
it('passes document index as the second argument for aggregation cursor (gh-8972)', function() {
return co(function *() {
const User = db.model('User', Schema({ order: Number }));
yield User.create([{ order: 1 }, { order: 2 }, { order: 3 }]);
const docsWithIndexes = [];
yield User.aggregate([{ $sort: { order: 1 } }]).cursor().exec().eachAsync((doc, i) => {
docsWithIndexes.push({ order: doc.order, i: i });
});
const expected = [
{ order: 1, i: 0 },
{ order: 2, i: 1 },
{ order: 3, i: 2 }
];
assert.deepEqual(docsWithIndexes, expected);
});
});
it('post hooks (gh-9435)', function() {
const schema = new mongoose.Schema({ name: String });
schema.post('find', function(doc) {
doc.name = doc.name.toUpperCase();
});
const Movie = db.model('Movie', schema);
return co(function*() {
yield Movie.deleteMany({});
yield Movie.create([
{ name: 'Kickboxer' },
{ name: 'Ip Man' },
{ name: 'Enter the Dragon' }
]);
const arr = [];
yield Movie.find().sort({ name: -1 }).cursor().
eachAsync(doc => arr.push(doc.name));
assert.deepEqual(arr, ['KICKBOXER', 'IP MAN', 'ENTER THE DRAGON']);
});
});
});
| 1 | 14,553 | `eachAsync()` should pass a doc, not an array of docs, to the callback. This would be a massive breaking change. | Automattic-mongoose | js |
@@ -323,11 +323,11 @@ func (uc *UpstreamController) updatePodStatus(stop chan struct{}) {
}
default:
- klog.Infof("pod status operation: %s unsupported", msg.GetOperation())
+ klog.Warningf("pod status operation: %s unsupported", msg.GetOperation())
}
- klog.Infof("message: %s process successfully", msg.GetID())
+ klog.V(4).Infof("message: %s process successfully", msg.GetID())
case <-stop:
- klog.Info("stop updatePodStatus")
+ klog.Warning("stop updatePodStatus")
running = false
}
} | 1 | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@CHANGELOG
KubeEdge Authors: To manage node/pod status for edge deployment scenarios,
we grab some functions from `kubelet/status/status_manager.go and do some modifications, they are
1. updatePodStatus
2. updateNodeStatus
3. normalizePodStatus
4. isPodNotRunning
*/
package controller
import (
"encoding/json"
"sort"
"time"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/klog"
"github.com/kubeedge/beehive/pkg/core/model"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/config"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/constants"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/messagelayer"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/types"
"github.com/kubeedge/kubeedge/cloud/pkg/edgecontroller/utils"
common "github.com/kubeedge/kubeedge/common/constants"
edgeapi "github.com/kubeedge/kubeedge/common/types"
)
// SortedContainerStatuses define A type to help sort container statuses based on container names.
type SortedContainerStatuses []v1.ContainerStatus
func (s SortedContainerStatuses) Len() int { return len(s) }
func (s SortedContainerStatuses) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SortedContainerStatuses) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
// SortInitContainerStatuses ensures that statuses are in the order that their
// init container appears in the pod spec
func SortInitContainerStatuses(p *v1.Pod, statuses []v1.ContainerStatus) {
containers := p.Spec.InitContainers
current := 0
for _, container := range containers {
for j := current; j < len(statuses); j++ {
if container.Name == statuses[j].Name {
statuses[current], statuses[j] = statuses[j], statuses[current]
current++
break
}
}
}
}
// UpstreamController subscribe messages from edge and sync to k8s api server
type UpstreamController struct {
kubeClient *kubernetes.Clientset
messageLayer messagelayer.MessageLayer
//stop channel
stopDispatch chan struct{}
stopUpdateNodeStatus chan struct{}
stopUpdatePodStatus chan struct{}
stopQueryConfigMap chan struct{}
stopQuerySecret chan struct{}
stopQueryService chan struct{}
stopQueryEndpoints chan struct{}
stopQueryPersistentVolume chan struct{}
stopQueryPersistentVolumeClaim chan struct{}
stopQueryVolumeAttachment chan struct{}
stopQueryNode chan struct{}
stopUpdateNode chan struct{}
// message channel
nodeStatusChan chan model.Message
podStatusChan chan model.Message
secretChan chan model.Message
configMapChan chan model.Message
serviceChan chan model.Message
endpointsChan chan model.Message
persistentVolumeChan chan model.Message
persistentVolumeClaimChan chan model.Message
volumeAttachmentChan chan model.Message
queryNodeChan chan model.Message
updateNodeChan chan model.Message
}
// Start UpstreamController
func (uc *UpstreamController) Start() error {
klog.Info("start upstream controller")
uc.stopDispatch = make(chan struct{})
uc.stopUpdateNodeStatus = make(chan struct{})
uc.stopUpdatePodStatus = make(chan struct{})
uc.stopQueryConfigMap = make(chan struct{})
uc.stopQuerySecret = make(chan struct{})
uc.stopQueryService = make(chan struct{})
uc.stopQueryEndpoints = make(chan struct{})
uc.stopQueryPersistentVolume = make(chan struct{})
uc.stopQueryPersistentVolumeClaim = make(chan struct{})
uc.stopQueryVolumeAttachment = make(chan struct{})
uc.stopQueryNode = make(chan struct{})
uc.stopUpdateNode = make(chan struct{})
uc.nodeStatusChan = make(chan model.Message, config.UpdateNodeStatusBuffer)
uc.podStatusChan = make(chan model.Message, config.UpdatePodStatusBuffer)
uc.configMapChan = make(chan model.Message, config.QueryConfigMapBuffer)
uc.secretChan = make(chan model.Message, config.QuerySecretBuffer)
uc.serviceChan = make(chan model.Message, config.QueryServiceBuffer)
uc.endpointsChan = make(chan model.Message, config.QueryEndpointsBuffer)
uc.persistentVolumeChan = make(chan model.Message, config.QueryPersistentVolumeBuffer)
uc.persistentVolumeClaimChan = make(chan model.Message, config.QueryPersistentVolumeClaimBuffer)
uc.volumeAttachmentChan = make(chan model.Message, config.QueryVolumeAttachmentBuffer)
uc.queryNodeChan = make(chan model.Message, config.QueryNodeBuffer)
uc.updateNodeChan = make(chan model.Message, config.UpdateNodeBuffer)
go uc.dispatchMessage(uc.stopDispatch)
for i := 0; i < config.UpdateNodeStatusWorkers; i++ {
go uc.updateNodeStatus(uc.stopUpdateNodeStatus)
}
for i := 0; i < config.UpdatePodStatusWorkers; i++ {
go uc.updatePodStatus(uc.stopUpdatePodStatus)
}
for i := 0; i < config.QueryConfigMapWorkers; i++ {
go uc.queryConfigMap(uc.stopQueryConfigMap)
}
for i := 0; i < config.QuerySecretWorkers; i++ {
go uc.querySecret(uc.stopQuerySecret)
}
for i := 0; i < config.QueryServiceWorkers; i++ {
go uc.queryService(uc.stopQueryService)
}
for i := 0; i < config.QueryEndpointsWorkers; i++ {
go uc.queryEndpoints(uc.stopQueryEndpoints)
}
for i := 0; i < config.QueryPersistentVolumeWorkers; i++ {
go uc.queryPersistentVolume(uc.stopQueryPersistentVolume)
}
for i := 0; i < config.QueryPersistentVolumeClaimWorkers; i++ {
go uc.queryPersistentVolumeClaim(uc.stopQueryPersistentVolumeClaim)
}
for i := 0; i < config.QueryVolumeAttachmentWorkers; i++ {
go uc.queryVolumeAttachment(uc.stopQueryVolumeAttachment)
}
for i := 0; i < config.QueryNodeWorkers; i++ {
go uc.queryNode(uc.stopQueryNode)
}
for i := 0; i < config.UpdateNodeBuffer; i++ {
go uc.updateNode(uc.stopUpdateNode)
}
return nil
}
func (uc *UpstreamController) dispatchMessage(stop chan struct{}) {
running := true
go func() {
<-stop
klog.Info("stop dispatchMessage")
running = false
}()
for running {
msg, err := uc.messageLayer.Receive()
if err != nil {
klog.Warningf("receive message failed, %s", err)
continue
}
klog.Infof("dispatch message: %s", msg.GetID())
resourceType, err := messagelayer.GetResourceType(msg)
if err != nil {
klog.Warningf("parse message: %s resource type with error: %s", msg.GetID(), err)
continue
}
klog.Infof("message: %s, resource type is: %s", msg.GetID(), resourceType)
operationType := msg.GetOperation()
klog.Infof("message: %s, operation type is: %s", msg.GetID(), operationType)
switch resourceType {
case model.ResourceTypeNodeStatus:
uc.nodeStatusChan <- msg
case model.ResourceTypePodStatus:
uc.podStatusChan <- msg
case model.ResourceTypeConfigmap:
uc.configMapChan <- msg
case model.ResourceTypeSecret:
uc.secretChan <- msg
case common.ResourceTypeService:
uc.serviceChan <- msg
case common.ResourceTypeEndpoints:
uc.endpointsChan <- msg
case common.ResourceTypePersistentVolume:
uc.persistentVolumeChan <- msg
case common.ResourceTypePersistentVolumeClaim:
uc.persistentVolumeClaimChan <- msg
case common.ResourceTypeVolumeAttachment:
uc.volumeAttachmentChan <- msg
case model.ResourceTypeNode:
switch operationType {
case model.QueryOperation:
uc.queryNodeChan <- msg
case model.UpdateOperation:
uc.updateNodeChan <- msg
default:
klog.Errorf("message: %s, operation type: %s unsupported", msg.GetID(), operationType)
}
default:
klog.Errorf("message: %s, resource type: %s unsupported", msg.GetID(), resourceType)
}
}
}
func (uc *UpstreamController) updatePodStatus(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.podStatusChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, podStatuses := uc.unmarshalPodStatusMessage(msg)
switch msg.GetOperation() {
case model.UpdateOperation:
for _, podStatus := range podStatuses {
getPod, err := uc.kubeClient.CoreV1().Pods(namespace).Get(podStatus.Name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s, pod not found, namespace: %s, name: %s", msg.GetID(), namespace, podStatus.Name)
// Send request to delete this pod on edge side
delMsg := model.NewMessage("")
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("Get node ID failed with error: %s", err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypePod, podStatus.Name)
if err != nil {
klog.Warningf("Built message resource failed with error: %s", err)
continue
}
pod := &v1.Pod{}
pod.Namespace, pod.Name = namespace, podStatus.Name
delMsg.Content = pod
delMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.DeleteOperation)
if err := uc.messageLayer.Send(*delMsg); err != nil {
klog.Warningf("Send message failed with error: %s, operation: %s, resource: %s", err, delMsg.GetOperation(), delMsg.GetResource())
} else {
klog.Infof("Send message successfully, operation: %s, resource: %s", delMsg.GetOperation(), delMsg.GetResource())
}
continue
}
if err != nil {
klog.Warningf("message: %s, pod is nil, namespace: %s, name: %s, error: %s", msg.GetID(), namespace, podStatus.Name, err)
continue
}
status := podStatus.Status
oldStatus := getPod.Status
// Set ReadyCondition.LastTransitionTime
if _, readyCondition := uc.getPodCondition(&status, v1.PodReady); readyCondition != nil {
// Need to set LastTransitionTime.
lastTransitionTime := metaV1.Now()
_, oldReadyCondition := uc.getPodCondition(&oldStatus, v1.PodReady)
if oldReadyCondition != nil && readyCondition.Status == oldReadyCondition.Status {
lastTransitionTime = oldReadyCondition.LastTransitionTime
}
readyCondition.LastTransitionTime = lastTransitionTime
}
// Set InitializedCondition.LastTransitionTime.
if _, initCondition := uc.getPodCondition(&status, v1.PodInitialized); initCondition != nil {
// Need to set LastTransitionTime.
lastTransitionTime := metaV1.Now()
_, oldInitCondition := uc.getPodCondition(&oldStatus, v1.PodInitialized)
if oldInitCondition != nil && initCondition.Status == oldInitCondition.Status {
lastTransitionTime = oldInitCondition.LastTransitionTime
}
initCondition.LastTransitionTime = lastTransitionTime
}
// ensure that the start time does not change across updates.
if oldStatus.StartTime != nil && !oldStatus.StartTime.IsZero() {
status.StartTime = oldStatus.StartTime
} else if status.StartTime.IsZero() {
// if the status has no start time, we need to set an initial time
now := metaV1.Now()
status.StartTime = &now
}
uc.normalizePodStatus(getPod, &status)
getPod.Status = status
if updatedPod, err := uc.kubeClient.CoreV1().Pods(getPod.Namespace).UpdateStatus(getPod); err != nil {
klog.Warningf("message: %s, update pod status failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, getPod.Namespace, getPod.Name)
} else {
klog.Infof("message: %s, update pod status successfully, namespace: %s, name: %s", msg.GetID(), updatedPod.Namespace, updatedPod.Name)
if updatedPod.DeletionTimestamp != nil && (status.Phase == v1.PodSucceeded || status.Phase == v1.PodFailed) {
if uc.isPodNotRunning(status.ContainerStatuses) {
if err := uc.kubeClient.CoreV1().Pods(updatedPod.Namespace).Delete(updatedPod.Name, metaV1.NewDeleteOptions(0)); err != nil {
klog.Warningf("message: %s, graceful delete pod failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, updatedPod.Namespace, updatedPod.Name)
}
klog.Infof("message: %s, pod delete successfully, namespace: %s, name: %s", msg.GetID(), updatedPod.Namespace, updatedPod.Name)
}
}
}
}
default:
klog.Infof("pod status operation: %s unsupported", msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Info("stop updatePodStatus")
running = false
}
}
}
func (uc *UpstreamController) updateNodeStatus(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.nodeStatusChan:
klog.Infof("message: %s, operation is: %s, and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
nodeStatusRequest := &edgeapi.NodeStatusRequest{}
var data []byte
switch msg.Content.(type) {
case []byte:
data = msg.GetContent().([]byte)
default:
var err error
data, err = json.Marshal(msg.GetContent())
if err != nil {
klog.Warningf("message: %s process failure, marshal message content with error: %s", msg.GetID(), err)
continue
}
}
err := json.Unmarshal(data, nodeStatusRequest)
if err != nil {
klog.Warningf("message: %s process failure, unmarshal marshaled message content with error: %s", msg.GetID(), err)
continue
}
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.UpdateOperation:
getNode, err := uc.kubeClient.CoreV1().Nodes().Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, node %s not found", msg.GetID(), name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespaces: %s name: %s", msg.GetID(), err, namespace, name)
continue
}
// TODO: comment below for test failure. Needs to decide whether to keep post troubleshoot
// In case the status stored at metadata service is outdated, update the heartbeat automatically
if !config.EdgeSiteEnabled {
for i := range nodeStatusRequest.Status.Conditions {
if time.Now().Sub(nodeStatusRequest.Status.Conditions[i].LastHeartbeatTime.Time) > config.Kube.KubeUpdateNodeFrequency {
nodeStatusRequest.Status.Conditions[i].LastHeartbeatTime = metaV1.NewTime(time.Now())
}
if time.Now().Sub(nodeStatusRequest.Status.Conditions[i].LastTransitionTime.Time) > config.Kube.KubeUpdateNodeFrequency {
nodeStatusRequest.Status.Conditions[i].LastTransitionTime = metaV1.NewTime(time.Now())
}
}
}
if getNode.Annotations == nil {
klog.Warningf("node annotations is nil map, new a map for it. namespace: %s, name: %s", getNode.Namespace, getNode.Name)
getNode.Annotations = make(map[string]string)
}
for name, v := range nodeStatusRequest.ExtendResources {
if name == constants.NvidiaGPUScalarResourceName {
var gpuStatus []types.NvidiaGPUStatus
for _, er := range v {
gpuStatus = append(gpuStatus, types.NvidiaGPUStatus{ID: er.Name, Healthy: true})
}
if len(gpuStatus) > 0 {
data, _ := json.Marshal(gpuStatus)
getNode.Annotations[constants.NvidiaGPUStatusAnnotationKey] = string(data)
}
}
data, err := json.Marshal(v)
if err != nil {
klog.Warningf("message: %s process failure, extend resource list marshal with error: %s", msg.GetID(), err)
continue
}
getNode.Annotations[string(name)] = string(data)
}
// Keep the same "VolumesAttached" attribute with upstream,
// since this value is maintained by kube-controller-manager.
nodeStatusRequest.Status.VolumesAttached = getNode.Status.VolumesAttached
getNode.Status = nodeStatusRequest.Status
if _, err := uc.kubeClient.CoreV1().Nodes().UpdateStatus(getNode); err != nil {
klog.Warningf("message: %s process failure, update node failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, getNode.Namespace, getNode.Name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = "OK"
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("Message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypeNode, name)
if err != nil {
klog.Warningf("Message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
if err = uc.messageLayer.Response(*resMsg); err != nil {
klog.Warningf("Message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Infof("message: %s, update node status successfully, namespace: %s, name: %s", msg.GetID(), getNode.Namespace, getNode.Name)
default:
klog.Infof("message: %s process failure, node status operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Info("stop updateNodeStatus")
running = false
}
}
}
func (uc *UpstreamController) queryConfigMap(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.configMapChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
configMap, err := uc.kubeClient.CoreV1().ConfigMaps(namespace).Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, config map not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = configMap
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
}
resource, err := messagelayer.BuildResource(nodeID, configMap.Namespace, model.ResourceTypeConfigmap, configMap.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, config map operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Info("stop queryConfigMap")
running = false
}
}
}
func (uc *UpstreamController) querySecret(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.secretChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
secret, err := uc.kubeClient.CoreV1().Secrets(namespace).Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, secret not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = secret
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, secret.Namespace, model.ResourceTypeSecret, secret.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, secret operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Info("stop querySecret")
running = false
}
}
}
func (uc *UpstreamController) queryService(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.serviceChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
svc, err := uc.kubeClient.CoreV1().Services(namespace).Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, service not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = svc
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
}
resource, err := messagelayer.BuildResource(nodeID, svc.Namespace, common.ResourceTypeService, svc.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, service operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
case <-stop:
klog.Info("stop queryService")
running = false
}
}
}
func (uc *UpstreamController) queryEndpoints(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.endpointsChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
eps, err := uc.kubeClient.CoreV1().Endpoints(namespace).Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, endpoints not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = eps
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, eps.Namespace, common.ResourceTypeEndpoints, eps.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, endpoints operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Info("stop queryEndpoints")
running = false
}
}
}
func (uc *UpstreamController) queryPersistentVolume(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.persistentVolumeChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
pv, err := uc.kubeClient.CoreV1().PersistentVolumes().Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, persistentvolume not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = pv
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, "persistentvolume", pv.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, persistentvolume operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Infof("stop queryPersistentVolume")
running = false
}
}
}
func (uc *UpstreamController) queryPersistentVolumeClaim(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.persistentVolumeClaimChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
pvc, err := uc.kubeClient.CoreV1().PersistentVolumeClaims(namespace).Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, persistentvolumeclaim not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = pvc
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, pvc.Namespace, "persistentvolumeclaim", pvc.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, persistentvolumeclaim operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Infof("stop queryPersistentVolumeClaim")
running = false
}
}
}
func (uc *UpstreamController) queryVolumeAttachment(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.volumeAttachmentChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
va, err := uc.kubeClient.StorageV1().VolumeAttachments().Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, volumeattachment not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = va
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, "volumeattachment", va.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, volumeattachment operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Infof("stop queryVolumeAttachment")
running = false
}
}
}
func (uc *UpstreamController) updateNode(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.updateNodeChan:
klog.Infof("message: %s, operation is: %s, and resource is %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
noderequest := &v1.Node{}
var data []byte
switch msg.Content.(type) {
case []byte:
data = msg.GetContent().([]byte)
default:
var err error
data, err = json.Marshal(msg.GetContent())
if err != nil {
klog.Warningf("message: %s process failure, marshal message content with error: %s", msg.GetID(), err)
continue
}
}
err := json.Unmarshal(data, noderequest)
if err != nil {
klog.Warningf("message: %s process failure, unmarshal marshaled message content with error: %s", msg.GetID(), err)
continue
}
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.UpdateOperation:
getNode, err := uc.kubeClient.CoreV1().Nodes().Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, node %s not found", msg.GetID(), name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, name: %s", msg.GetID(), err, name)
continue
}
if getNode.Annotations == nil {
klog.Warningf("node annotations is nil map, new a map for it. namespace: %s, name: %s", getNode.Namespace, getNode.Name)
getNode.Annotations = make(map[string]string)
}
for k, v := range noderequest.Annotations {
getNode.Annotations[k] = v
}
if _, err := uc.kubeClient.CoreV1().Nodes().Update(getNode); err != nil {
klog.Warningf("message: %s process failure, update node failed with error: %s, namespace: %s, name: %s", msg.GetID(), err, getNode.Namespace, getNode.Name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = "OK"
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("Message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
continue
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypeNode, name)
if err != nil {
klog.Warningf("Message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
continue
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
if err = uc.messageLayer.Response(*resMsg); err != nil {
klog.Warningf("Message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Infof("message: %s, update node successfully, namespace: %s, name: %s", msg.GetID(), getNode.Namespace, getNode.Name)
default:
klog.Infof("message: %s process failure, node operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Infof("stop updateNode")
running = false
}
}
}
func (uc *UpstreamController) queryNode(stop chan struct{}) {
running := true
for running {
select {
case msg := <-uc.queryNodeChan:
klog.Infof("message: %s, operation is: %s, and resource is: %s", msg.GetID(), msg.GetOperation(), msg.GetResource())
namespace, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace failed with error: %s", msg.GetID(), err)
continue
}
name, err := messagelayer.GetResourceName(msg)
if err != nil {
klog.Warningf("message: %s process failure, get resource name failed with error: %s", msg.GetID(), err)
continue
}
switch msg.GetOperation() {
case model.QueryOperation:
node, err := uc.kubeClient.CoreV1().Nodes().Get(name, metaV1.GetOptions{})
if errors.IsNotFound(err) {
klog.Warningf("message: %s process failure, node not found, namespace: %s, name: %s", msg.GetID(), namespace, name)
continue
}
if err != nil {
klog.Warningf("message: %s process failure with error: %s, namespace: %s, name: %s", msg.GetID(), err, namespace, name)
continue
}
resMsg := model.NewMessage(msg.GetID())
resMsg.Content = node
nodeID, err := messagelayer.GetNodeID(msg)
if err != nil {
klog.Warningf("message: %s process failure, get node id failed with error: %s", msg.GetID(), err)
}
resource, err := messagelayer.BuildResource(nodeID, namespace, model.ResourceTypeNode, node.Name)
if err != nil {
klog.Warningf("message: %s process failure, build message resource failed with error: %s", msg.GetID(), err)
}
resMsg.BuildRouter(constants.EdgeControllerModuleName, constants.GroupResource, resource, model.ResponseOperation)
err = uc.messageLayer.Response(*resMsg)
if err != nil {
klog.Warningf("message: %s process failure, response failed with error: %s", msg.GetID(), err)
continue
}
klog.Warningf("message: %s process successfully", msg.GetID())
default:
klog.Infof("message: %s process failure, query node operation: %s unsupported", msg.GetID(), msg.GetOperation())
}
klog.Infof("message: %s process successfully", msg.GetID())
case <-stop:
klog.Infof("stop queryNode")
running = false
}
}
}
func (uc *UpstreamController) unmarshalPodStatusMessage(msg model.Message) (ns string, podStatuses []edgeapi.PodStatusRequest) {
ns, err := messagelayer.GetNamespace(msg)
if err != nil {
klog.Warningf("message: %s process failure, get namespace with error: %s", msg.GetID(), err)
return
}
name, _ := messagelayer.GetResourceName(msg)
var data []byte
switch msg.Content.(type) {
case []byte:
data = msg.GetContent().([]byte)
default:
var err error
data, err = json.Marshal(msg.GetContent())
if err != nil {
klog.Warningf("message: %s process failure, marshal content failed with error: %s", msg.GetID(), err)
return
}
}
if name == "" {
// multi pod status in one message
err = json.Unmarshal(data, &podStatuses)
if err != nil {
return
}
} else {
// one pod status per message
var status edgeapi.PodStatusRequest
if err := json.Unmarshal(data, &status); err != nil {
return
}
podStatuses = append(podStatuses, status)
}
return
}
// GetPodCondition extracts the provided condition from the given status and returns that.
// Returns nil and -1 if the condition is not present, and the index of the located condition.
func (uc *UpstreamController) getPodCondition(status *v1.PodStatus, conditionType v1.PodConditionType) (int, *v1.PodCondition) {
if status == nil {
return -1, nil
}
for i := range status.Conditions {
if status.Conditions[i].Type == conditionType {
return i, &status.Conditions[i]
}
}
return -1, nil
}
func (uc *UpstreamController) isPodNotRunning(statuses []v1.ContainerStatus) bool {
for _, status := range statuses {
if status.State.Terminated == nil && status.State.Waiting == nil {
return false
}
}
return true
}
// We add this function, because apiserver only supports *RFC3339* now, which means that the timestamp returned by
// apiserver has no nanosecond information. However, the timestamp returned by unversioned.Now() contains nanosecond,
// so when we do comparison between status from apiserver and cached status, isStatusEqual() will always return false.
// There is related issue #15262 and PR #15263 about this.
func (uc *UpstreamController) normalizePodStatus(pod *v1.Pod, status *v1.PodStatus) *v1.PodStatus {
normalizeTimeStamp := func(t *metaV1.Time) {
*t = t.Rfc3339Copy()
}
normalizeContainerState := func(c *v1.ContainerState) {
if c.Running != nil {
normalizeTimeStamp(&c.Running.StartedAt)
}
if c.Terminated != nil {
normalizeTimeStamp(&c.Terminated.StartedAt)
normalizeTimeStamp(&c.Terminated.FinishedAt)
}
}
if status.StartTime != nil {
normalizeTimeStamp(status.StartTime)
}
for i := range status.Conditions {
condition := &status.Conditions[i]
normalizeTimeStamp(&condition.LastProbeTime)
normalizeTimeStamp(&condition.LastTransitionTime)
}
// update container statuses
for i := range status.ContainerStatuses {
cstatus := &status.ContainerStatuses[i]
normalizeContainerState(&cstatus.State)
normalizeContainerState(&cstatus.LastTerminationState)
}
// Sort the container statuses, so that the order won't affect the result of comparison
sort.Sort(SortedContainerStatuses(status.ContainerStatuses))
// update init container statuses
for i := range status.InitContainerStatuses {
cstatus := &status.InitContainerStatuses[i]
normalizeContainerState(&cstatus.State)
normalizeContainerState(&cstatus.LastTerminationState)
}
// Sort the container statuses, so that the order won't affect the result of comparison
SortInitContainerStatuses(pod, status.InitContainerStatuses)
return status
}
// Stop UpstreamController
func (uc *UpstreamController) Stop() error {
klog.Info("Stopping upstream controller")
defer klog.Info("Upstream controller stopped")
uc.stopDispatch <- struct{}{}
for i := 0; i < config.UpdateNodeStatusWorkers; i++ {
uc.stopUpdateNodeStatus <- struct{}{}
}
for i := 0; i < config.UpdatePodStatusWorkers; i++ {
uc.stopUpdatePodStatus <- struct{}{}
}
for i := 0; i < config.QueryConfigMapWorkers; i++ {
uc.stopQueryConfigMap <- struct{}{}
}
for i := 0; i < config.QuerySecretWorkers; i++ {
uc.stopQuerySecret <- struct{}{}
}
for i := 0; i < config.QueryServiceWorkers; i++ {
uc.stopQueryService <- struct{}{}
}
for i := 0; i < config.QueryEndpointsWorkers; i++ {
uc.stopQueryEndpoints <- struct{}{}
}
return nil
}
// NewUpstreamController create UpstreamController from config
func NewUpstreamController() (*UpstreamController, error) {
cli, err := utils.KubeClient()
if err != nil {
klog.Warningf("create kube client failed with error: %s", err)
return nil, err
}
ml, err := messagelayer.NewMessageLayer()
if err != nil {
klog.Warningf("create message layer failed with error: %s", err)
}
uc := &UpstreamController{kubeClient: cli, messageLayer: ml}
return uc, nil
}
| 1 | 13,927 | please start log with caps letters | kubeedge-kubeedge | go |
@@ -10,4 +10,5 @@
<%= render 'layouts/typekit' %>
<%= csrf_meta_tag %>
<%= render 'layouts/ie_shiv' %>
+<%= render 'layouts/visual_website_optimizer' %>
<%= yield :head %> | 1 | <meta charset="utf-8" />
<title><%= page_title(app_name: t('layouts.app_name')) %></title>
<%= render 'layouts/stylesheets' %>
<link rel="icon" href="/favicon.ico" type="image/x-icon">
<meta http-equiv="Description" name="Description" content="<%= yield(:meta_description).presence || t('layouts.meta_description') %>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Keywords" name="Keywords" content="<%= keywords(yield :meta_keywords) %>" />
<meta name="google-site-verification" content="pFoYtgbd6tc74KGxv5yWxu2QTH0oKllYLrYbTt35iNM" />
<%= open_graph_tags %>
<%= render 'layouts/typekit' %>
<%= csrf_meta_tag %>
<%= render 'layouts/ie_shiv' %>
<%= yield :head %>
| 1 | 10,209 | Is this where we want it in relation to the other scripts? | thoughtbot-upcase | rb |
@@ -13,6 +13,7 @@
_,
T
*/
+ var FEATURE_NAME = "reports";
window.ReportingView = countlyView.extend({
featureName: 'reports', | 1 | /*global
Handlebars,
CountlyHelpers,
countlyGlobal,
countlyAuth,
countlyView,
countlyEvent,
ReportingView,
countlyReporting,
jQuery,
app,
$,
_,
T
*/
window.ReportingView = countlyView.extend({
featureName: 'reports',
statusChanged: {},
emailInput: {},
initialize: function() {
},
beforeRender: function() {
var allAjaxCalls = [];
var reportCallbacks = app.getReportsCallbacks();
Object.keys(reportCallbacks).forEach(function(report) {
if (reportCallbacks[report].ajax) {
allAjaxCalls.push(reportCallbacks[report].ajax());
}
});
allAjaxCalls.push(
countlyReporting.initialize()
);
if (this.template) {
return $.when.apply(null, allAjaxCalls).then(function() {});
}
else {
var self = this;
allAjaxCalls.push(
T.get('/reports/templates/drawer.html', function(src) {
src = (Handlebars.compile(src))({"email-placeholder": jQuery.i18n.map["reports.report-email"]});
Handlebars.registerPartial("reports-drawer-template", src);
}),
T.render('/reports/templates/reports.html', function(src) {
self.template = src;
})
);
return $.when.apply(null, allAjaxCalls).then(function() {});
}
},
getDayName: function(day) {
switch (day) {
case 1:
return jQuery.i18n.map["reports.monday"];
case 2:
return jQuery.i18n.map["reports.tuesday"];
case 3:
return jQuery.i18n.map["reports.wednesday"];
case 4:
return jQuery.i18n.map["reports.thursday"];
case 5:
return jQuery.i18n.map["reports.friday"];
case 6:
return jQuery.i18n.map["reports.saturday"];
case 7:
return jQuery.i18n.map["reports.sunday"];
default:
return "";
}
},
getDayNumber: function(day) {
switch (day) {
case jQuery.i18n.map["reports.monday"]:
return "1";
case jQuery.i18n.map["reports.tuesday"]:
return "2";
case jQuery.i18n.map["reports.wednesday"]:
return "3";
case jQuery.i18n.map["reports.thursday"]:
return "4";
case jQuery.i18n.map["reports.friday"]:
return "5";
case jQuery.i18n.map["reports.saturday"]:
return "6";
case jQuery.i18n.map["reports.sunday"]:
return "7";
default:
return "1";
}
},
renderCommon: function(isRefresh) {
var cnts = app.manageAppsView.getTimeZones();
ReportingView.zones = {};
var zNames = {};
var zoneNames = [];
for (var i in cnts) {
for (var j = 0; j < cnts[i].z.length; j++) {
for (var k in cnts[i].z[j]) {
zoneNames.push(k);
ReportingView.zones[k] = cnts[i].z[j][k];
zNames[cnts[i].z[j][k]] = k;
}
}
}
var data = countlyReporting.getData();
for (i = 0; i < data.length; i++) {
data[i].appNames = CountlyHelpers.appIdsToNames(data[i].apps || []).split(", ");
if (data[i].hour < 10) {
data[i].hour = "0" + data[i].hour;
}
if (data[i].minute < 10) {
data[i].minute = "0" + data[i].minute;
}
data[i].dayname = this.getDayName(data[i].day);
data[i].zoneName = zNames[data[i].timezone] || "(GMT+00:00) GMT (no daylight saving)";
}
zoneNames.sort(function(a, b) {
a = parseFloat(a.split(")")[0].replace(":", ".").substring(4));
b = parseFloat(b.split(")")[0].replace(":", ".").substring(4));
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
this.zoneNames = zoneNames;
this.zones = ReportingView.zones;
this.templateData = {
"page-title": jQuery.i18n.map["reports.title"],
"data": data,
"apps": countlyGlobal.apps,
"zoneNames": zoneNames,
"member": countlyGlobal.member,
"hasCrash": (typeof countlyCrashes !== "undefined"),
"hasPush": (typeof countlyPush !== "undefined"),
"hasRevenue": (typeof countlyRevenue !== "undefined"),
"hasViews": (typeof countlyViews !== "undefined")
};
var self = this;
if (!isRefresh) {
$(this.el).html(this.template(this.templateData));
self.dtable = $('#reports-table').dataTable($.extend({}, $.fn.dataTable.defaults, {
"aaData": data,
"fnRowCallback": function(nRow, aData) {
$(nRow).attr("id", aData._id);
},
"aoColumns": [
{"mData": 'title', "sType": "string", "sTitle": jQuery.i18n.map['report.report-title']},
{
"mData": function(row, type) {
if (type === "display") {
var disabled = (row.prepackaged) ? 'disabled' : '';
var input = '<div class="on-off-switch ' + disabled + '">';
if (row.enabled) {
input += '<input type="checkbox" class="on-off-switch-checkbox report-switcher" id="plugin-' + row._id + '" checked ' + disabled + '>';
}
else {
input += '<input type="checkbox" class="on-off-switch-checkbox report-switcher" id="plugin-' + row._id + '" ' + disabled + '>';
}
input += '<label class="on-off-switch-label" for="plugin-' + row._id + '"></label>';
input += '<span class="text">' + 'Enable' + '</span>';
return input;
}
else {
return row.enabled;
}
},
"sType": "string",
"sTitle": jQuery.i18n.map['report.status'],
"bSortable": false,
},
{
"mData": function(row) {
return row.emails.join("<br/>");
},
"sType": "string",
"sTitle": jQuery.i18n.map["reports.emails"]
},
{
"mData": function(row) {
var ret = "";
if (row.report_type === "core") {
for (var rowProp in row.metrics) {
ret += jQuery.i18n.map["reports." + rowProp] + ", ";
}
ret = ret.substring(0, ret.length - 2);
ret += " for " + row.appNames.join(", ");
}
else if (!row.pluginEnabled) {
ret = jQuery.i18n.prop("reports.enable-plugin", row.report_type);
}
else if (!row.isValid) {
ret = jQuery.i18n.prop("reports.not-valid");
}
else {
var report = app.getReportsCallbacks()[row.report_type];
if (report && report.tableData) {
ret = report.tableData(row);
}
}
return ret;
},
"sType": "string",
"sTitle": jQuery.i18n.map["reports.metrics"]
},
{
"mData": function(row) {
return jQuery.i18n.map["reports." + row.frequency];
},
"sType": "string",
"sTitle": jQuery.i18n.map["reports.frequency"]
},
{
"mData": function(row) {
var ret = jQuery.i18n.map["reports.at"] + " " + row.hour + ":" + row.minute + ", " + row.zoneName;
if (row.frequency === "weekly") {
ret += ", " + jQuery.i18n.map["reports.on"] + " " + row.dayname;
}
if (row.frequency === "monthly") {
ret += ", " + jQuery.i18n.map["reports.every-month"];
}
return ret;
},
"sType": "string",
"sTitle": jQuery.i18n.map["reports.time"]
},
{
"mData": function(row) {
var createdByMe = true;
if (countlyGlobal.member.global_admin === true || row.user === countlyGlobal.member._id) {
createdByMe = false;
}
return createdByMe;
},
"sTitle": jQuery.i18n.map['report.report-created-by-me'],
"bSortable": false,
},
{
"mData": function(row) {
var viewOnly = true;
if (countlyGlobal.member.global_admin === true || row.user === countlyGlobal.member._id) {
viewOnly = false;
}
var menu = "<div class='options-item'>" +
"<div class='edit'></div>" +
"<div class='edit-menu reports-menu'>";
if (row.pluginEnabled && row.isValid) {
menu += viewOnly ? "" : "<div class='edit-report item'" + " id='" + row._id + "'" + "><i class='fa fa-pencil'></i>Edit</div>";
menu += "<div class='send-report item'" + " id='" + row._id + "'" +
"><i class='fa fa-paper-plane'></i>Send Now</div>" +
"<div class='preview-report item'" + " id='" + row._id + "'" + ">" +
'<a href=\'/i/reports/preview?api_key=' + countlyGlobal.member.api_key + '&args=' + JSON.stringify({_id: row._id}) + '\' target="_blank" class=""><i class="fa fa-eye"></i><span data-localize="reports.preview">' + jQuery.i18n.map["reports.preview"] + '</span></a>' +
"</div>";
}
menu += viewOnly ? "" : "<div class='delete-report item'" + " id='" + row._id + "'" + " data-name = '" + row.title + "' ><i class='fa fa-trash'></i>Delete</div>" +
"</div>" +
"</div>";
return menu;
},
"bSortable": false,
},
]
}));
self.dtable.fnSort([ [0, 'desc'] ]);
self.dtable.stickyTableHeaders();
self.initTable();
self.initReportsWidget("core");
$("#add-report").on("click", function() {
self.widgetDrawer.init("core");
});
if (!countlyAuth.validateCreate(self.featureName)) {
$('#add-report').hide();
}
if (!countlyAuth.validateUpdate(self.featureName)) {
$('.edit-report').hide();
}
if (!countlyAuth.validateDelete(self.featureName)) {
$('.delete-report').hide();
}
}
},
initReportsWidget: function(reportType) {
var self = this;
var apps = [];
$("#add-report").on("click", function() {
$("#reports-widget-drawer").addClass("open");
$("#reports-widget-drawer").removeClass("editing");
var reportCallbacks = app.getReportsCallbacks();
Object.keys(reportCallbacks).forEach(function(report) {
if (reportCallbacks[report].reset) {
reportCallbacks[report].reset();
}
});
self.widgetDrawer.resetCore();
});
$("#frequency-dropdown").clySelectSetItems([
{name: jQuery.i18n.map["reports.daily"], value: "daily"},
{name: jQuery.i18n.map["reports.weekly"], value: "weekly"},
{name: jQuery.i18n.map["reports.monthly"], value: "monthly"}
]);
var timeList = [];
for (var i = 0; i < 24; i++) {
var v = (i > 9 ? i : "0" + i) + ":00";
timeList.push({ value: v, name: v});
}
$("#reports-time-dropdown").clySelectSetItems(timeList);
var cnts = app.manageAppsView.getTimeZones();
var zones = {};
var zNames = {};
var zoneNames = [];
var timeZoneList = [];
for (i in cnts) {
for (var j = 0; j < cnts[i].z.length; j++) {
for (var k in cnts[i].z[j]) {
zoneNames.push(k);
zones[k] = cnts[i].z[j][k];
zNames[cnts[i].z[j][k]] = k;
}
}
}
zoneNames.sort(function(a, b) {
a = parseFloat(a.split(")")[0].replace(":", ".").substring(4));
b = parseFloat(b.split(")")[0].replace(":", ".").substring(4));
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
zoneNames.forEach(function(zone) {
timeZoneList.push({value: zone, name: zone});
});
$("#reports-timezone-dropdown").clySelectSetItems(timeZoneList);
for (var appId in countlyGlobal.apps) {
apps.push({ value: appId, name: countlyGlobal.apps[appId].name });
}
$("#reports-multi-app-dropdown").clyMultiSelectSetItems(apps);
$("#reports-multi-metrics-dropdown").clyMultiSelectSetItems(countlyReporting.getMetrics());
$('#reports-widge-close').off("click").on("click", function() {
$("#reports-widget-drawer").removeClass("open");
});
$('#daily-option').on("click", function() {
$("#reports-dow-section").css("display", "none");
$('#weekly-option').removeClass("selected");
$('#monthly-option').removeClass("selected");
$(this).addClass("selected");
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$('#weekly-option').on("click", function() {
$("#reports-dow-section").css("display", "block");
$('#daily-option').removeClass("selected");
$('#monthly-option').removeClass("selected");
$("#reports-dow").clySelectSetSelection("", "");
$(this).addClass("selected");
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$('#monthly-option').on("click", function() {
$("#reports-dow-section").css("display", "none");
$('#weekly-option').removeClass("selected");
$('#daily-option').removeClass("selected");
$(this).addClass("selected");
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
var weekList = [
{name: jQuery.i18n.map["reports.monday"], value: 1},
{name: jQuery.i18n.map["reports.tuesday"], value: 2},
{name: jQuery.i18n.map["reports.wednesday"], value: 3},
{name: jQuery.i18n.map["reports.thursday"], value: 4},
{name: jQuery.i18n.map["reports.friday"], value: 5},
{name: jQuery.i18n.map["reports.saturday"], value: 6},
{name: jQuery.i18n.map["reports.sunday"], value: 7},
];
$("#reports-dow").clySelectSetItems(weekList);
$("#reports-create-widget").off().on("click", function() {
if ($(this).hasClass("disabled")) {
return;
}
var reportSetting = self.widgetDrawer.getReportSetting();
reportSetting.enabled = true;
for (var key in reportSetting) {
if (!reportSetting[key] || reportSetting[key] === '' ||
(reportSetting[key] && reportSetting[key].length === 0)) {
return CountlyHelpers.alert("Please complete all required fields",
"green",
function() { });
}
}
$.when(countlyReporting.create(reportSetting)).then(function(data) {
if (data.result === "Success") {
$("#reports-widget-drawer").removeClass("open");
app.activeView.render();
}
else {
CountlyHelpers.alert(data.result, "red");
}
}, function(err) {
var data = JSON.parse(err.responseText);
CountlyHelpers.alert(data.result, "red");
});
});
$("#reports-save-widget").off().on("click", function() {
if ($(this).hasClass("disabled")) {
return;
}
var reportSetting = self.widgetDrawer.getReportSetting();
reportSetting._id = $("#current_report_id").text();
for (var key in reportSetting) {
if (!reportSetting[key] || reportSetting[key] === '' ||
(reportSetting[key] && reportSetting[key].length === 0)) {
return CountlyHelpers.alert("Please complete all required fields",
"green",
function() { });
}
}
$.when(countlyReporting.update(reportSetting)).then(function(data) {
if (data.result === "Success") {
$("#reports-widget-drawer").removeClass("open");
app.activeView.render();
}
else {
CountlyHelpers.alert(data.result, "red");
}
}, function(err) {
var data = JSON.parse(err.responseText);
CountlyHelpers.alert(data.result, "red");
});
});
$(".cly-drawer").find(".close").off("click").on("click", function() {
$(".grid-stack-item").removeClass("marked-for-editing");
$(this).parents(".cly-drawer").removeClass("open");
});
$("#report-name-input").on("keyup", function() {
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$("#reports-multi-metrics-dropdown").on("cly-multi-select-change", function() {
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$("#report-types").on("click", ".opt:not(.disabled)", function() {
$("#report-types").find(".opt").removeClass("selected");
$(this).addClass("selected");
var selReportType = $("#report-types").find(".opt.selected").data("report-type");
var reportCallbacks = app.getReportsCallbacks();
Object.keys(reportCallbacks).forEach(function(report) {
if (reportCallbacks[report].reset) {
reportCallbacks[report].reset();
}
});
$("#reports-multi-app-dropdown").clyMultiSelectClearSelection();
$("#reports-multi-app-dropdown .select-items .item").removeClass("selected");
$("#reports-multi-metrics-dropdown").clyMultiSelectClearSelection();
$("#reports-multi-metrics-dropdown .select-items .item").removeClass("selected");
self.widgetDrawer.init(selReportType);
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$("#reports-dow, #reports-time-dropdown, #reports-timezone-dropdown").on("cly-select-change", function() {
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$("#reports-multi-app-dropdown").on("cly-multi-select-change", function() {
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
var selectedApps = $('#reports-multi-app-dropdown').clyMultiSelectGetSelection();
self.loadEventsForApps(selectedApps);
self.checkEventsSectionView();
$(".include-events").clyMultiSelectClearSelection();
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
self.loadEventsForApps = function(targetApps) {
countlyEvent.getEventsForApps(targetApps, function(eventData) {
$("#reports-multi-events-dropdown").clyMultiSelectSetItems(eventData);
$("#reports-widget-drawer").trigger("cly-report-widget-section-events-loaded");
});
};
self.checkEventsSectionView = function() {
var selectedMetrics = $('#reports-multi-metrics-dropdown').clyMultiSelectGetSelection();
var selectedApps = $('#reports-multi-app-dropdown').clyMultiSelectGetSelection();
var eventsSection = $("#reports-widget-drawer .details .include-events").closest(".section");
if (selectedMetrics.indexOf("events") > -1 && selectedApps.length > 0) {
eventsSection.show();
}
else {
eventsSection.hide();
}
};
$("#reports-widget-drawer .details .include-metrics").on("cly-multi-select-change", function() {
self.checkEventsSectionView();
});
$("#reports-multi-events-dropdown").on("cly-multi-select-change", function() {
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
var REGEX_EMAIL = '([a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)';
self.emailInput = $('#email-list-input').selectize({
plugins: ['remove_button'],
persist: false,
maxItems: null,
valueField: 'email',
labelField: 'name',
searchField: ['name', 'email'],
options: [
{email: countlyGlobal.member.email, name: ''},
],
render: {
item: function(item, escape) {
return '<div>' +
(item.name ? '<span class="name">' + escape(item.name) + '</span>' : '') +
(item.email ? '<span class="email">' + escape(item.email) + '</span>' : '') +
'</div>';
},
option: function(item, escape) {
var label = item.name || item.email;
var caption = item.name ? item.email : null;
return '<div>' +
'<span class="label">' + escape(label) + '</span>' +
(caption ? '<span class="caption">' + escape(caption) + '</span>' : '') +
'</div>';
}
},
createFilter: function(input) {
var match, regex;
// email@address.com
regex = new RegExp('^' + REGEX_EMAIL + '$', 'i');
match = input.match(regex);
if (match) {
return !Object.prototype.hasOwnProperty.call(this.options, match[0]);
}
// name <email@address.com>
/*eslint-disable */
regex = new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i');
/*eslint-enable */
match = input.match(regex);
if (match) {
return !Object.prototype.hasOwnProperty.call(this.options, match[2]);
}
return false;
},
create: function(input) {
if ((new RegExp('^' + REGEX_EMAIL + '$', 'i')).test(input)) {
return {email: input};
}
/*eslint-disable */
var match = input.match(new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i'));
/*eslint-enable */
if (match) {
return {
email: match[2],
name: $.trim(match[1])
};
}
CountlyHelpers.alert('Invalid email address.', "red");
return false;
}
});
self.emailInput.on("change", function() {
$("#reports-widget-drawer").trigger("cly-report-widget-section-complete");
});
$("#reports-widget-drawer").on("cly-report-widget-section-complete", function() {
var reportSetting = self.widgetDrawer.getReportSetting();
reportSetting.enabled = true;
var allGood = true;
for (var key in reportSetting) {
if (!reportSetting[key] || reportSetting[key] === '' ||
(reportSetting[key] && reportSetting[key].length === 0)) {
allGood = false;
}
}
if (allGood) {
$("#reports-create-widget").removeClass("disabled");
$("#reports-save-widget").removeClass("disabled");
}
else {
$("#reports-create-widget").addClass("disabled");
$("#reports-save-widget").addClass("disabled");
}
});
self.widgetDrawer.init(reportType);
},
widgetDrawer: {
init: function(reportType) {
var self = this;
self.report_type = reportType;
$("#reports-widget-drawer .details .section").hide();
$("#reports-widget-drawer .details #report-name-input").closest(".section").show();
$("#reports-widget-drawer .details #email-list-input").closest(".section").show();
$("#reports-widget-drawer .details #reports-frequency").closest(".section").show();
$("#reports-widget-drawer .details #reports-time-dropdown").closest(".section").show();
$("#reports-widget-drawer .details #reports-timezone-dropdown").closest(".section").show();
$("#reports-widget-drawer .details #report-types").closest(".section").show();
if ($("#weekly-option").hasClass("selected")) {
$("#reports-dow-section").show();
}
var $reportTypes = $("#report-types");
$reportTypes.find(".opt").removeClass("selected");
$reportTypes.find(".opt[data-report-type=" + reportType + "]").addClass("selected");
var report = app.getReportsCallbacks()[reportType];
if (report && report.init) {
report.init();
}
$("#reports-widget-drawer .report-multi-events-section").hide();
if (reportType === "core") {
$("#reports-widget-drawer .details #reports-multi-app-dropdown").closest(".section").show();
$("#reports-widget-drawer .details .include-metrics").closest(".section").show();
}
},
loadData: function(data) {
var reportType = data.report_type || "core";
this.init(reportType);
var emailInp = app.reportingView.emailInput;
if (emailInp && emailInp.length > 0) {
for (var i = 0; i < data.emails.length; i++) {
(emailInp[0]).selectize.addOption({ "name": '', "email": data.emails[i] });
}
(emailInp[0]).selectize.setValue(data.emails, false);
}
$("#report-types").find(".opt").removeClass("selected");
$("#report-types").find(".opt[data-report-type=" + reportType + "]").addClass("selected");
$("#reports-widget-drawer").addClass("open editing");
$("#current_report_id").text(data._id);
$("#report-name-input").val(data.title);
if (data.frequency === 'daily') {
$('#daily-option').addClass("selected");
$('#weekly-option').removeClass("selected");
$('#monthly-option').removeClass("selected");
$("#reports-dow-section").css("display", "none");
}
else if (data.frequency === 'monthly') {
$('#daily-option').removeClass("selected");
$('#weekly-option').removeClass("selected");
$('#monthly-option').addClass("selected");
$("#reports-dow-section").css("display", "none");
}
else {
$('#daily-option').removeClass("selected");
$('#monthly-option').removeClass("selected");
$('#weekly-option').addClass("selected");
$("#reports-dow-section").css("display", "block");
$("#reports-dow").clySelectSetSelection(data.day, app.reportingView.getDayName(data.day));
}
var timeString = data.hour + ":" + data.minute;
$("#reports-time-dropdown").clySelectSetSelection(timeString, timeString);
$("#reports-timezone-dropdown").clySelectSetSelection(data.zoneName, data.zoneName);
var report = app.getReportsCallbacks()[reportType];
if (report && report.set) {
report.set(data);
}
if (reportType === "core") {
var appSelected = [];
for (var index in data.apps) {
var appId = data.apps[index];
appSelected.push({name: countlyGlobal.apps[appId].name, value: appId});
}
$("#reports-multi-app-dropdown").clyMultiSelectSetSelection(appSelected);
var selectedMetrics = [];
var metricOptions = countlyReporting.getMetrics();
metricOptions.forEach(function(m) {
if (data.metrics[m.value] === true) {
selectedMetrics.push(m);
}
});
$("#reports-multi-metrics-dropdown").clyMultiSelectSetSelection(selectedMetrics);
$("#reports-widget-drawer").off("cly-report-widget-section-events-loaded").on("cly-report-widget-section-events-loaded", function() {
if (data.metrics.events > -1) {
var eventsSelected = data.selectedEvents || [];
var items = $("#reports-multi-events-dropdown").clyMultiSelectGetItems();
var map = {};
for (var item = 0; item < items.length; item++) {
map[items[item].value] = items[item].name;
}
var options = eventsSelected.map(function(e) {
var elements = e.split("***");
var targetAppId = elements[0];
var eventName = map[e] || elements[1];
var displayName = eventName + " (" + countlyGlobal.apps[targetAppId].name + ")";
return {value: e, name: displayName};
});
$("#reports-multi-events-dropdown").clyMultiSelectSetSelection(options);
}
});
}
$("#reports-save-widget").addClass("disabled");
},
resetCore: function() {
$("#current_report_id").text("");
$("#report-name-input").val("");
$("#report-name-input").attr("placeholder", jQuery.i18n.prop("reports.report-name"));
$("#reports-dow").clySelectSetSelection("", jQuery.i18n.prop("reports.select_dow"));
$("#reports-timezone-dropdown").clySelectSetSelection("", jQuery.i18n.prop("reports.select_timezone"));
$("#reports-time-dropdown").clySelectSetSelection("", jQuery.i18n.prop("reports.select_time"));
$("#reports-multi-app-dropdown").clyMultiSelectClearSelection();
$("#reports-multi-app-dropdown .select-items .item").removeClass("selected");
$("#reports-multi-app-dropdown .select-items .item").removeClass("disabled");
$("#reports-multi-metrics-dropdown").clyMultiSelectClearSelection();
$("#reports-multi-metrics-dropdown .select-items .item").removeClass("selected");
$("#reports-multi-metrics-dropdown").clyMultiSelectSetItems(countlyReporting.getMetrics());
$(".include-events").clyMultiSelectClearSelection();
$("#reports-dow-section").css("display", "none");
$("#reports-frequency").find(".check").removeClass("selected");
$('#daily-option').addClass("selected");
var emailInp = app.reportingView.emailInput;
if (emailInp && emailInp.length > 0) {
(emailInp[0]).selectize.addOption({});
(emailInp[0]).selectize.setValue([], false);
}
},
getReportSetting: function() {
var reportType = this.report_type;
var emails = [];
$("#email-list-input :selected").each(function() {
emails.push($(this).val());
});
var settings = {
report_type: reportType,
title: $("#report-name-input").val(),
emails: emails,
frequency: "daily",
day: 1,
hour: null,
minute: null
};
var selectDaily = $("#daily-option").hasClass("selected");
var selectMonthly = $("#monthly-option").hasClass("selected");
if (!selectDaily && !selectMonthly) {
settings.frequency = "weekly";
settings.day = parseInt($("#reports-dow").clySelectGetSelection());
}
if (selectMonthly) {
settings.frequency = "monthly";
}
var timeSelected = $("#reports-time-dropdown").clySelectGetSelection();
if (timeSelected) {
var time = timeSelected ? timeSelected.split(":") : null;
settings.hour = time[0];
settings.minute = time[1];
}
var zones = app.reportingView.zones;
if (!zones) {
var cnts = app.manageAppsView.getTimeZones();
zones = {};
for (var i in cnts) {
for (var j = 0; j < cnts[i].z.length; j++) {
for (var k in cnts[i].z[j]) {
zones[k] = cnts[i].z[j][k];
}
}
}
}
var timeZone = $("#reports-timezone-dropdown").clySelectGetSelection() || "Etc/GMT";
settings.timezone = zones[timeZone];
if (reportType === "core") {
settings.metrics = {};
var selectedMetrics = $('#reports-multi-metrics-dropdown').clyMultiSelectGetSelection();
selectedMetrics.forEach(function(m) {
settings.metrics[m] = true;
});
if (selectedMetrics.indexOf("events") > -1) {
settings.selectedEvents = $("#reports-multi-events-dropdown").clyMultiSelectGetSelection();
}
settings.apps = $('#reports-multi-app-dropdown').clyMultiSelectGetSelection();
}
var report = app.getReportsCallbacks()[reportType];
if (report && report.settings) {
var reportSettings = report.settings();
for (var key in reportSettings) {
settings[key] = reportSettings[key];
}
}
return settings;
}
},
initTable: function() {
var self = this;
$(".save-report").off("click").on("click", function(data) {
$.when(countlyReporting.update(data)).then(function(result) {
if (result.result === "Success") {
app.activeView.render();
}
else {
CountlyHelpers.alert(result.result, "red");
}
}, function(err) {
var errorData = JSON.parse(err.responseText);
CountlyHelpers.alert(errorData.result, "red");
});
});
$(".edit-report").off("click").on("click", function(e) {
var reportId = e.target.id;
var formData = countlyReporting.getReport(reportId);
self.widgetDrawer.loadData(formData);
});
$(".delete-report").off("click").on("click", function(e) {
var id = e.target.id;
var name = $(e.target).attr("data-name");
CountlyHelpers.confirm(jQuery.i18n.prop("reports.confirm", "<b>" + name + "</b>"), "popStyleGreen", function(result) {
if (!result) {
return false;
}
$.when(countlyReporting.del(id)).then(function(data) {
if (data.result === "Success") {
app.activeView.render();
}
else {
CountlyHelpers.alert(data.result, "red");
}
});
}, [jQuery.i18n.map["common.no-dont-delete"], jQuery.i18n.map["reports.yes-delete-report"]], {title: jQuery.i18n.map["reports.delete-report-title"], image: "delete-email-report"});
});
$(".send-report").off("click").on("click", function(e) {
var id = e.target.id;
var overlay = $("#overlay").clone();
overlay.show();
$.when(countlyReporting.send(id)).always(function(data) {
overlay.hide();
if (data && data.result === "Success") {
CountlyHelpers.alert(jQuery.i18n.map["reports.sent"], "green");
}
else {
if (data && data.result) {
CountlyHelpers.alert(data.result, "red");
}
else {
CountlyHelpers.alert(jQuery.i18n.map["reports.too-long"], "red");
}
}
});
});
$('input[name=frequency]').off("click").on("click", function() {
var currUserDetails = $(".user-details:visible");
switch ($(this).val()) {
case "daily":
currUserDetails.find(".reports-dow").hide();
break;
case "weekly":
currUserDetails.find(".reports-dow").show();
break;
case "monthly":
currUserDetails.find(".reports-dow").hide();
break;
}
});
CountlyHelpers.initializeSelect($(".user-details"));
// load menu
$("body").off("click", ".options-item .edit").on("click", ".options-item .edit", function() {
$(".edit-menu").fadeOut();
$(this).next(".edit-menu").fadeToggle();
event.stopPropagation();
});
$(window).click(function() {
$(".options-item").find(".edit").next(".edit-menu").fadeOut();
});
$(".report-switcher").off("click").on("click", function() {
var pluginId = this.id.toString().replace(/^plugin-/, '');
var newStatus = $(this).is(":checked");
var list = countlyReporting.getData();
var record = _.filter(list, function(item) {
return item._id === pluginId;
});
if (record) {
(record[0].enabled !== newStatus) ? (self.statusChanged[pluginId] = newStatus) : (delete self.statusChanged[pluginId]);
}
var keys = _.keys(self.statusChanged);
if (keys && keys.length > 0) {
$(".data-save-bar-remind").text(' You made ' + keys.length + (keys.length === 1 ? ' change.' : ' changes.'));
return $(".data-saver-bar").removeClass("data-saver-bar-hide");
}
$(".data-saver-bar").addClass("data-saver-bar-hide");
});
$(".data-saver-cancel-button").off("click").on("click", function() {
$.when(countlyReporting.initialize()).then(function() {
self.statusChanged = {};
self.renderCommon();
app.localize();
return $(".data-saver-bar").addClass("data-saver-bar-hide");
});
});
$(".data-saver-button").off("click").on("click", function() {
$.when(countlyReporting.updateStatus(self.statusChanged)).then(function() {
return $.when(countlyReporting.initialize()).then(function() {
self.statusChanged = {};
self.renderCommon();
app.localize();
return $(".data-saver-bar").addClass("data-saver-bar-hide");
});
});
});
$(".save-table-data").css("display", "none");
}
});
app.addReportsCallbacks = function(plugin, options) {
if (!this.reportCallbacks) {
this.reportCallbacks = {};
}
this.reportCallbacks[plugin] = options;
};
app.getReportsCallbacks = function() {
return this.reportCallbacks;
};
app.addReportsCallbacks("reports", {
initialize: function(el, reportType, cb) {
el = el || "body";
var self = this;
$.when(
T.get('/reports/templates/drawer.html', function(src) {
self.reportsDrawer = src;
}),
countlyReporting.initialize()
).then(function() {
$('#reports-widget-drawer').remove();
var drawerViewDom = Handlebars.compile(self.reportsDrawer)({"email-placeholder": jQuery.i18n.map["reports.report-email"]});
$(el).after(drawerViewDom);
app.localize();
app.reportingView.initReportsWidget(reportType);
$("#reports-widget-drawer .details #report-types").closest(".section").hide();
if (cb) {
return cb();
}
});
}
});
//register views
app.reportingView = new ReportingView();
if (countlyAuth.validateRead(app.reportingView.featureName)) {
app.route('/manage/reports', 'reports', function() {
this.renderWhenReady(this.reportingView);
});
}
$(document).ready(function() {
if (countlyAuth.validateRead(app.reportingView.featureName)) {
app.addMenu("management", {code: "reports", url: "#/manage/reports", text: "reports.title", priority: 30});
if (app.configurationsView) {
app.configurationsView.registerLabel("reports", "reports.title");
app.configurationsView.registerLabel(
"reports.secretKey",
"reports.secretKey"
);
}
}
});
| 1 | 14,303 | Please wrap this variable within a self invoking anonymous function. (function(){ FEATURE_NAME = "reports"; //and rest of the js goes here. })(); | Countly-countly-server | js |
@@ -393,6 +393,14 @@ func (c *linuxContainer) Signal(s os.Signal, all bool) error {
if err := c.initProcess.signal(s); err != nil {
return fmt.Errorf("unable to signal init: %w", err)
}
+ if status == Paused {
+ // For cgroup v1, killing a process in a frozen cgroup
+ // does nothing until it's thawed. Only thaw the cgroup
+ // for SIGKILL.
+ if s, ok := s.(unix.Signal); ok && s == unix.SIGKILL {
+ _ = c.cgroupManager.Freeze(configs.Thawed)
+ }
+ }
return nil
}
return ErrNotRunning | 1 | package libcontainer
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/checkpoint-restore/go-criu/v5"
criurpc "github.com/checkpoint-restore/go-criu/v5/rpc"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink/nl"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/proto"
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/libcontainer/intelrdt"
"github.com/opencontainers/runc/libcontainer/system"
"github.com/opencontainers/runc/libcontainer/utils"
)
const stdioFdCount = 3
type linuxContainer struct {
id string
root string
config *configs.Config
cgroupManager cgroups.Manager
intelRdtManager intelrdt.Manager
initPath string
initArgs []string
initProcess parentProcess
initProcessStartTime uint64
criuPath string
newuidmapPath string
newgidmapPath string
m sync.Mutex
criuVersion int
state containerState
created time.Time
fifo *os.File
}
// State represents a running container's state
type State struct {
BaseState
// Platform specific fields below here
// Specified if the container was started under the rootless mode.
// Set to true if BaseState.Config.RootlessEUID && BaseState.Config.RootlessCgroups
Rootless bool `json:"rootless"`
// Paths to all the container's cgroups, as returned by (*cgroups.Manager).GetPaths
//
// For cgroup v1, a key is cgroup subsystem name, and the value is the path
// to the cgroup for this subsystem.
//
// For cgroup v2 unified hierarchy, a key is "", and the value is the unified path.
CgroupPaths map[string]string `json:"cgroup_paths"`
// NamespacePaths are filepaths to the container's namespaces. Key is the namespace type
// with the value as the path.
NamespacePaths map[configs.NamespaceType]string `json:"namespace_paths"`
// Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore
ExternalDescriptors []string `json:"external_descriptors,omitempty"`
// Intel RDT "resource control" filesystem path
IntelRdtPath string `json:"intel_rdt_path"`
}
// Container is a libcontainer container object.
//
// Each container is thread-safe within the same process. Since a container can
// be destroyed by a separate process, any function may return that the container
// was not found.
type Container interface {
BaseContainer
// Methods below here are platform specific
// Checkpoint checkpoints the running container's state to disk using the criu(8) utility.
Checkpoint(criuOpts *CriuOpts) error
// Restore restores the checkpointed container to a running state using the criu(8) utility.
Restore(process *Process, criuOpts *CriuOpts) error
// If the Container state is RUNNING or CREATED, sets the Container state to PAUSING and pauses
// the execution of any user processes. Asynchronously, when the container finished being paused the
// state is changed to PAUSED.
// If the Container state is PAUSED, do nothing.
Pause() error
// If the Container state is PAUSED, resumes the execution of any user processes in the
// Container before setting the Container state to RUNNING.
// If the Container state is RUNNING, do nothing.
Resume() error
// NotifyOOM returns a read-only channel signaling when the container receives an OOM notification.
NotifyOOM() (<-chan struct{}, error)
// NotifyMemoryPressure returns a read-only channel signaling when the container reaches a given pressure level
NotifyMemoryPressure(level PressureLevel) (<-chan struct{}, error)
}
// ID returns the container's unique ID
func (c *linuxContainer) ID() string {
return c.id
}
// Config returns the container's configuration
func (c *linuxContainer) Config() configs.Config {
return *c.config
}
func (c *linuxContainer) Status() (Status, error) {
c.m.Lock()
defer c.m.Unlock()
return c.currentStatus()
}
func (c *linuxContainer) State() (*State, error) {
c.m.Lock()
defer c.m.Unlock()
return c.currentState()
}
func (c *linuxContainer) OCIState() (*specs.State, error) {
c.m.Lock()
defer c.m.Unlock()
return c.currentOCIState()
}
func (c *linuxContainer) Processes() ([]int, error) {
var pids []int
status, err := c.currentStatus()
if err != nil {
return pids, err
}
// for systemd cgroup, the unit's cgroup path will be auto removed if container's all processes exited
if status == Stopped && !c.cgroupManager.Exists() {
return pids, nil
}
pids, err = c.cgroupManager.GetAllPids()
if err != nil {
return nil, fmt.Errorf("unable to get all container pids: %w", err)
}
return pids, nil
}
func (c *linuxContainer) Stats() (*Stats, error) {
var (
err error
stats = &Stats{}
)
if stats.CgroupStats, err = c.cgroupManager.GetStats(); err != nil {
return stats, fmt.Errorf("unable to get container cgroup stats: %w", err)
}
if c.intelRdtManager != nil {
if stats.IntelRdtStats, err = c.intelRdtManager.GetStats(); err != nil {
return stats, fmt.Errorf("unable to get container Intel RDT stats: %w", err)
}
}
for _, iface := range c.config.Networks {
switch iface.Type {
case "veth":
istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
if err != nil {
return stats, fmt.Errorf("unable to get network stats for interface %q: %w", iface.HostInterfaceName, err)
}
stats.Interfaces = append(stats.Interfaces, istats)
}
}
return stats, nil
}
func (c *linuxContainer) Set(config configs.Config) error {
c.m.Lock()
defer c.m.Unlock()
status, err := c.currentStatus()
if err != nil {
return err
}
if status == Stopped {
return ErrNotRunning
}
if err := c.cgroupManager.Set(config.Cgroups.Resources); err != nil {
// Set configs back
if err2 := c.cgroupManager.Set(c.config.Cgroups.Resources); err2 != nil {
logrus.Warnf("Setting back cgroup configs failed due to error: %v, your state.json and actual configs might be inconsistent.", err2)
}
return err
}
if c.intelRdtManager != nil {
if err := c.intelRdtManager.Set(&config); err != nil {
// Set configs back
if err2 := c.cgroupManager.Set(c.config.Cgroups.Resources); err2 != nil {
logrus.Warnf("Setting back cgroup configs failed due to error: %v, your state.json and actual configs might be inconsistent.", err2)
}
if err2 := c.intelRdtManager.Set(c.config); err2 != nil {
logrus.Warnf("Setting back intelrdt configs failed due to error: %v, your state.json and actual configs might be inconsistent.", err2)
}
return err
}
}
// After config setting succeed, update config and states
c.config = &config
_, err = c.updateState(nil)
return err
}
func (c *linuxContainer) Start(process *Process) error {
c.m.Lock()
defer c.m.Unlock()
if c.config.Cgroups.Resources.SkipDevices {
return errors.New("can't start container with SkipDevices set")
}
if process.Init {
if err := c.createExecFifo(); err != nil {
return err
}
}
if err := c.start(process); err != nil {
if process.Init {
c.deleteExecFifo()
}
return err
}
return nil
}
func (c *linuxContainer) Run(process *Process) error {
if err := c.Start(process); err != nil {
return err
}
if process.Init {
return c.exec()
}
return nil
}
func (c *linuxContainer) Exec() error {
c.m.Lock()
defer c.m.Unlock()
return c.exec()
}
func (c *linuxContainer) exec() error {
path := filepath.Join(c.root, execFifoFilename)
pid := c.initProcess.pid()
blockingFifoOpenCh := awaitFifoOpen(path)
for {
select {
case result := <-blockingFifoOpenCh:
return handleFifoResult(result)
case <-time.After(time.Millisecond * 100):
stat, err := system.Stat(pid)
if err != nil || stat.State == system.Zombie {
// could be because process started, ran, and completed between our 100ms timeout and our system.Stat() check.
// see if the fifo exists and has data (with a non-blocking open, which will succeed if the writing process is complete).
if err := handleFifoResult(fifoOpen(path, false)); err != nil {
return errors.New("container process is already dead")
}
return nil
}
}
}
}
func readFromExecFifo(execFifo io.Reader) error {
data, err := ioutil.ReadAll(execFifo)
if err != nil {
return err
}
if len(data) <= 0 {
return errors.New("cannot start an already running container")
}
return nil
}
func awaitFifoOpen(path string) <-chan openResult {
fifoOpened := make(chan openResult)
go func() {
result := fifoOpen(path, true)
fifoOpened <- result
}()
return fifoOpened
}
func fifoOpen(path string, block bool) openResult {
flags := os.O_RDONLY
if !block {
flags |= unix.O_NONBLOCK
}
f, err := os.OpenFile(path, flags, 0)
if err != nil {
return openResult{err: fmt.Errorf("exec fifo: %w", err)}
}
return openResult{file: f}
}
func handleFifoResult(result openResult) error {
if result.err != nil {
return result.err
}
f := result.file
defer f.Close()
if err := readFromExecFifo(f); err != nil {
return err
}
return os.Remove(f.Name())
}
type openResult struct {
file *os.File
err error
}
func (c *linuxContainer) start(process *Process) (retErr error) {
parent, err := c.newParentProcess(process)
if err != nil {
return fmt.Errorf("unable to create new parent process: %w", err)
}
logsDone := parent.forwardChildLogs()
if logsDone != nil {
defer func() {
// Wait for log forwarder to finish. This depends on
// runc init closing the _LIBCONTAINER_LOGPIPE log fd.
err := <-logsDone
if err != nil && retErr == nil {
retErr = fmt.Errorf("unable to forward init logs: %w", err)
}
}()
}
if err := parent.start(); err != nil {
return fmt.Errorf("unable to start container process: %w", err)
}
if process.Init {
c.fifo.Close()
if c.config.Hooks != nil {
s, err := c.currentOCIState()
if err != nil {
return err
}
if err := c.config.Hooks[configs.Poststart].RunHooks(s); err != nil {
if err := ignoreTerminateErrors(parent.terminate()); err != nil {
logrus.Warn(fmt.Errorf("error running poststart hook: %w", err))
}
return err
}
}
}
return nil
}
func (c *linuxContainer) Signal(s os.Signal, all bool) error {
c.m.Lock()
defer c.m.Unlock()
status, err := c.currentStatus()
if err != nil {
return err
}
if all {
// for systemd cgroup, the unit's cgroup path will be auto removed if container's all processes exited
if status == Stopped && !c.cgroupManager.Exists() {
return nil
}
return signalAllProcesses(c.cgroupManager, s)
}
// to avoid a PID reuse attack
if status == Running || status == Created || status == Paused {
if err := c.initProcess.signal(s); err != nil {
return fmt.Errorf("unable to signal init: %w", err)
}
return nil
}
return ErrNotRunning
}
func (c *linuxContainer) createExecFifo() error {
rootuid, err := c.Config().HostRootUID()
if err != nil {
return err
}
rootgid, err := c.Config().HostRootGID()
if err != nil {
return err
}
fifoName := filepath.Join(c.root, execFifoFilename)
if _, err := os.Stat(fifoName); err == nil {
return fmt.Errorf("exec fifo %s already exists", fifoName)
}
oldMask := unix.Umask(0o000)
if err := unix.Mkfifo(fifoName, 0o622); err != nil {
unix.Umask(oldMask)
return err
}
unix.Umask(oldMask)
return os.Chown(fifoName, rootuid, rootgid)
}
func (c *linuxContainer) deleteExecFifo() {
fifoName := filepath.Join(c.root, execFifoFilename)
os.Remove(fifoName)
}
// includeExecFifo opens the container's execfifo as a pathfd, so that the
// container cannot access the statedir (and the FIFO itself remains
// un-opened). It then adds the FifoFd to the given exec.Cmd as an inherited
// fd, with _LIBCONTAINER_FIFOFD set to its fd number.
func (c *linuxContainer) includeExecFifo(cmd *exec.Cmd) error {
fifoName := filepath.Join(c.root, execFifoFilename)
fifo, err := os.OpenFile(fifoName, unix.O_PATH|unix.O_CLOEXEC, 0)
if err != nil {
return err
}
c.fifo = fifo
cmd.ExtraFiles = append(cmd.ExtraFiles, fifo)
cmd.Env = append(cmd.Env,
"_LIBCONTAINER_FIFOFD="+strconv.Itoa(stdioFdCount+len(cmd.ExtraFiles)-1))
return nil
}
func (c *linuxContainer) newParentProcess(p *Process) (parentProcess, error) {
parentInitPipe, childInitPipe, err := utils.NewSockPair("init")
if err != nil {
return nil, fmt.Errorf("unable to create init pipe: %w", err)
}
messageSockPair := filePair{parentInitPipe, childInitPipe}
parentLogPipe, childLogPipe, err := os.Pipe()
if err != nil {
return nil, fmt.Errorf("unable to create log pipe: %w", err)
}
logFilePair := filePair{parentLogPipe, childLogPipe}
cmd := c.commandTemplate(p, childInitPipe, childLogPipe)
if !p.Init {
return c.newSetnsProcess(p, cmd, messageSockPair, logFilePair)
}
// We only set up fifoFd if we're not doing a `runc exec`. The historic
// reason for this is that previously we would pass a dirfd that allowed
// for container rootfs escape (and not doing it in `runc exec` avoided
// that problem), but we no longer do that. However, there's no need to do
// this for `runc exec` so we just keep it this way to be safe.
if err := c.includeExecFifo(cmd); err != nil {
return nil, fmt.Errorf("unable to setup exec fifo: %w", err)
}
return c.newInitProcess(p, cmd, messageSockPair, logFilePair)
}
func (c *linuxContainer) commandTemplate(p *Process, childInitPipe *os.File, childLogPipe *os.File) *exec.Cmd {
cmd := exec.Command(c.initPath, c.initArgs[1:]...)
cmd.Args[0] = c.initArgs[0]
cmd.Stdin = p.Stdin
cmd.Stdout = p.Stdout
cmd.Stderr = p.Stderr
cmd.Dir = c.config.Rootfs
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &unix.SysProcAttr{}
}
cmd.Env = append(cmd.Env, "GOMAXPROCS="+os.Getenv("GOMAXPROCS"))
cmd.ExtraFiles = append(cmd.ExtraFiles, p.ExtraFiles...)
if p.ConsoleSocket != nil {
cmd.ExtraFiles = append(cmd.ExtraFiles, p.ConsoleSocket)
cmd.Env = append(cmd.Env,
"_LIBCONTAINER_CONSOLE="+strconv.Itoa(stdioFdCount+len(cmd.ExtraFiles)-1),
)
}
cmd.ExtraFiles = append(cmd.ExtraFiles, childInitPipe)
cmd.Env = append(cmd.Env,
"_LIBCONTAINER_INITPIPE="+strconv.Itoa(stdioFdCount+len(cmd.ExtraFiles)-1),
"_LIBCONTAINER_STATEDIR="+c.root,
)
cmd.ExtraFiles = append(cmd.ExtraFiles, childLogPipe)
cmd.Env = append(cmd.Env,
"_LIBCONTAINER_LOGPIPE="+strconv.Itoa(stdioFdCount+len(cmd.ExtraFiles)-1),
"_LIBCONTAINER_LOGLEVEL="+p.LogLevel,
)
// NOTE: when running a container with no PID namespace and the parent process spawning the container is
// PID1 the pdeathsig is being delivered to the container's init process by the kernel for some reason
// even with the parent still running.
if c.config.ParentDeathSignal > 0 {
cmd.SysProcAttr.Pdeathsig = unix.Signal(c.config.ParentDeathSignal)
}
return cmd
}
func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, messageSockPair, logFilePair filePair) (*initProcess, error) {
cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initStandard))
nsMaps := make(map[configs.NamespaceType]string)
for _, ns := range c.config.Namespaces {
if ns.Path != "" {
nsMaps[ns.Type] = ns.Path
}
}
_, sharePidns := nsMaps[configs.NEWPID]
data, err := c.bootstrapData(c.config.Namespaces.CloneFlags(), nsMaps)
if err != nil {
return nil, err
}
init := &initProcess{
cmd: cmd,
messageSockPair: messageSockPair,
logFilePair: logFilePair,
manager: c.cgroupManager,
intelRdtManager: c.intelRdtManager,
config: c.newInitConfig(p),
container: c,
process: p,
bootstrapData: data,
sharePidns: sharePidns,
}
c.initProcess = init
return init, nil
}
func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, messageSockPair, logFilePair filePair) (*setnsProcess, error) {
cmd.Env = append(cmd.Env, "_LIBCONTAINER_INITTYPE="+string(initSetns))
state, err := c.currentState()
if err != nil {
return nil, fmt.Errorf("unable to get container state: %w", err)
}
// for setns process, we don't have to set cloneflags as the process namespaces
// will only be set via setns syscall
data, err := c.bootstrapData(0, state.NamespacePaths)
if err != nil {
return nil, err
}
return &setnsProcess{
cmd: cmd,
cgroupPaths: state.CgroupPaths,
rootlessCgroups: c.config.RootlessCgroups,
intelRdtPath: state.IntelRdtPath,
messageSockPair: messageSockPair,
logFilePair: logFilePair,
manager: c.cgroupManager,
config: c.newInitConfig(p),
process: p,
bootstrapData: data,
initProcessPid: state.InitProcessPid,
}, nil
}
func (c *linuxContainer) newInitConfig(process *Process) *initConfig {
cfg := &initConfig{
Config: c.config,
Args: process.Args,
Env: process.Env,
User: process.User,
AdditionalGroups: process.AdditionalGroups,
Cwd: process.Cwd,
Capabilities: process.Capabilities,
PassedFilesCount: len(process.ExtraFiles),
ContainerId: c.ID(),
NoNewPrivileges: c.config.NoNewPrivileges,
RootlessEUID: c.config.RootlessEUID,
RootlessCgroups: c.config.RootlessCgroups,
AppArmorProfile: c.config.AppArmorProfile,
ProcessLabel: c.config.ProcessLabel,
Rlimits: c.config.Rlimits,
CreateConsole: process.ConsoleSocket != nil,
ConsoleWidth: process.ConsoleWidth,
ConsoleHeight: process.ConsoleHeight,
}
if process.NoNewPrivileges != nil {
cfg.NoNewPrivileges = *process.NoNewPrivileges
}
if process.AppArmorProfile != "" {
cfg.AppArmorProfile = process.AppArmorProfile
}
if process.Label != "" {
cfg.ProcessLabel = process.Label
}
if len(process.Rlimits) > 0 {
cfg.Rlimits = process.Rlimits
}
if cgroups.IsCgroup2UnifiedMode() {
cfg.Cgroup2Path = c.cgroupManager.Path("")
}
return cfg
}
func (c *linuxContainer) Destroy() error {
c.m.Lock()
defer c.m.Unlock()
return c.state.destroy()
}
func (c *linuxContainer) Pause() error {
c.m.Lock()
defer c.m.Unlock()
status, err := c.currentStatus()
if err != nil {
return err
}
switch status {
case Running, Created:
if err := c.cgroupManager.Freeze(configs.Frozen); err != nil {
return err
}
return c.state.transition(&pausedState{
c: c,
})
}
return ErrNotRunning
}
func (c *linuxContainer) Resume() error {
c.m.Lock()
defer c.m.Unlock()
status, err := c.currentStatus()
if err != nil {
return err
}
if status != Paused {
return ErrNotPaused
}
if err := c.cgroupManager.Freeze(configs.Thawed); err != nil {
return err
}
return c.state.transition(&runningState{
c: c,
})
}
func (c *linuxContainer) NotifyOOM() (<-chan struct{}, error) {
// XXX(cyphar): This requires cgroups.
if c.config.RootlessCgroups {
logrus.Warn("getting OOM notifications may fail if you don't have the full access to cgroups")
}
path := c.cgroupManager.Path("memory")
if cgroups.IsCgroup2UnifiedMode() {
return notifyOnOOMV2(path)
}
return notifyOnOOM(path)
}
func (c *linuxContainer) NotifyMemoryPressure(level PressureLevel) (<-chan struct{}, error) {
// XXX(cyphar): This requires cgroups.
if c.config.RootlessCgroups {
logrus.Warn("getting memory pressure notifications may fail if you don't have the full access to cgroups")
}
return notifyMemoryPressure(c.cgroupManager.Path("memory"), level)
}
var criuFeatures *criurpc.CriuFeatures
func (c *linuxContainer) checkCriuFeatures(criuOpts *CriuOpts, rpcOpts *criurpc.CriuOpts, criuFeat *criurpc.CriuFeatures) error {
t := criurpc.CriuReqType_FEATURE_CHECK
// make sure the features we are looking for are really not from
// some previous check
criuFeatures = nil
req := &criurpc.CriuReq{
Type: &t,
// Theoretically this should not be necessary but CRIU
// segfaults if Opts is empty.
// Fixed in CRIU 2.12
Opts: rpcOpts,
Features: criuFeat,
}
err := c.criuSwrk(nil, req, criuOpts, nil)
if err != nil {
logrus.Debugf("%s", err)
return errors.New("CRIU feature check failed")
}
missingFeatures := false
// The outer if checks if the fields actually exist
if (criuFeat.MemTrack != nil) &&
(criuFeatures.MemTrack != nil) {
// The inner if checks if they are set to true
if *criuFeat.MemTrack && !*criuFeatures.MemTrack {
missingFeatures = true
logrus.Debugf("CRIU does not support MemTrack")
}
}
// This needs to be repeated for every new feature check.
// Is there a way to put this in a function. Reflection?
if (criuFeat.LazyPages != nil) &&
(criuFeatures.LazyPages != nil) {
if *criuFeat.LazyPages && !*criuFeatures.LazyPages {
missingFeatures = true
logrus.Debugf("CRIU does not support LazyPages")
}
}
if missingFeatures {
return errors.New("CRIU is missing features")
}
return nil
}
func compareCriuVersion(criuVersion int, minVersion int) error {
// simple function to perform the actual version compare
if criuVersion < minVersion {
return fmt.Errorf("CRIU version %d must be %d or higher", criuVersion, minVersion)
}
return nil
}
// checkCriuVersion checks Criu version greater than or equal to minVersion
func (c *linuxContainer) checkCriuVersion(minVersion int) error {
// If the version of criu has already been determined there is no need
// to ask criu for the version again. Use the value from c.criuVersion.
if c.criuVersion != 0 {
return compareCriuVersion(c.criuVersion, minVersion)
}
criu := criu.MakeCriu()
criu.SetCriuPath(c.criuPath)
var err error
c.criuVersion, err = criu.GetCriuVersion()
if err != nil {
return fmt.Errorf("CRIU version check failed: %w", err)
}
return compareCriuVersion(c.criuVersion, minVersion)
}
const descriptorsFilename = "descriptors.json"
func (c *linuxContainer) addCriuDumpMount(req *criurpc.CriuReq, m *configs.Mount) {
mountDest := strings.TrimPrefix(m.Destination, c.config.Rootfs)
if dest, err := securejoin.SecureJoin(c.config.Rootfs, mountDest); err == nil {
mountDest = dest[len(c.config.Rootfs):]
}
extMnt := &criurpc.ExtMountMap{
Key: proto.String(mountDest),
Val: proto.String(mountDest),
}
req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
}
func (c *linuxContainer) addMaskPaths(req *criurpc.CriuReq) error {
for _, path := range c.config.MaskPaths {
fi, err := os.Stat(fmt.Sprintf("/proc/%d/root/%s", c.initProcess.pid(), path))
if err != nil {
if os.IsNotExist(err) {
continue
}
return err
}
if fi.IsDir() {
continue
}
extMnt := &criurpc.ExtMountMap{
Key: proto.String(path),
Val: proto.String("/dev/null"),
}
req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
}
return nil
}
func (c *linuxContainer) handleCriuConfigurationFile(rpcOpts *criurpc.CriuOpts) {
// CRIU will evaluate a configuration starting with release 3.11.
// Settings in the configuration file will overwrite RPC settings.
// Look for annotations. The annotation 'org.criu.config'
// specifies if CRIU should use a different, container specific
// configuration file.
_, annotations := utils.Annotations(c.config.Labels)
configFile, exists := annotations["org.criu.config"]
if exists {
// If the annotation 'org.criu.config' exists and is set
// to a non-empty string, tell CRIU to use that as a
// configuration file. If the file does not exist, CRIU
// will just ignore it.
if configFile != "" {
rpcOpts.ConfigFile = proto.String(configFile)
}
// If 'org.criu.config' exists and is set to an empty
// string, a runc specific CRIU configuration file will
// be not set at all.
} else {
// If the mentioned annotation has not been found, specify
// a default CRIU configuration file.
rpcOpts.ConfigFile = proto.String("/etc/criu/runc.conf")
}
}
func (c *linuxContainer) criuSupportsExtNS(t configs.NamespaceType) bool {
var minVersion int
switch t {
case configs.NEWNET:
// CRIU supports different external namespace with different released CRIU versions.
// For network namespaces to work we need at least criu 3.11.0 => 31100.
minVersion = 31100
case configs.NEWPID:
// For PID namespaces criu 31500 is needed.
minVersion = 31500
default:
return false
}
return c.checkCriuVersion(minVersion) == nil
}
func criuNsToKey(t configs.NamespaceType) string {
return "extRoot" + strings.Title(configs.NsName(t)) + "NS"
}
func (c *linuxContainer) handleCheckpointingExternalNamespaces(rpcOpts *criurpc.CriuOpts, t configs.NamespaceType) error {
if !c.criuSupportsExtNS(t) {
return nil
}
nsPath := c.config.Namespaces.PathOf(t)
if nsPath == "" {
return nil
}
// CRIU expects the information about an external namespace
// like this: --external <TYPE>[<inode>]:<key>
// This <key> is always 'extRoot<TYPE>NS'.
var ns unix.Stat_t
if err := unix.Stat(nsPath, &ns); err != nil {
return err
}
criuExternal := fmt.Sprintf("%s[%d]:%s", configs.NsName(t), ns.Ino, criuNsToKey(t))
rpcOpts.External = append(rpcOpts.External, criuExternal)
return nil
}
func (c *linuxContainer) handleRestoringNamespaces(rpcOpts *criurpc.CriuOpts, extraFiles *[]*os.File) error {
for _, ns := range c.config.Namespaces {
switch ns.Type {
case configs.NEWNET, configs.NEWPID:
// If the container is running in a network or PID namespace and has
// a path to the network or PID namespace configured, we will dump
// that network or PID namespace as an external namespace and we
// will expect that the namespace exists during restore.
// This basically means that CRIU will ignore the namespace
// and expect it to be setup correctly.
if err := c.handleRestoringExternalNamespaces(rpcOpts, extraFiles, ns.Type); err != nil {
return err
}
default:
// For all other namespaces except NET and PID CRIU has
// a simpler way of joining the existing namespace if set
nsPath := c.config.Namespaces.PathOf(ns.Type)
if nsPath == "" {
continue
}
if ns.Type == configs.NEWCGROUP {
// CRIU has no code to handle NEWCGROUP
return fmt.Errorf("Do not know how to handle namespace %v", ns.Type)
}
// CRIU has code to handle NEWTIME, but it does not seem to be defined in runc
// CRIU will issue a warning for NEWUSER:
// criu/namespaces.c: 'join-ns with user-namespace is not fully tested and dangerous'
rpcOpts.JoinNs = append(rpcOpts.JoinNs, &criurpc.JoinNamespace{
Ns: proto.String(configs.NsName(ns.Type)),
NsFile: proto.String(nsPath),
})
}
}
return nil
}
func (c *linuxContainer) handleRestoringExternalNamespaces(rpcOpts *criurpc.CriuOpts, extraFiles *[]*os.File, t configs.NamespaceType) error {
if !c.criuSupportsExtNS(t) {
return nil
}
nsPath := c.config.Namespaces.PathOf(t)
if nsPath == "" {
return nil
}
// CRIU wants the information about an existing namespace
// like this: --inherit-fd fd[<fd>]:<key>
// The <key> needs to be the same as during checkpointing.
// We are always using 'extRoot<TYPE>NS' as the key in this.
nsFd, err := os.Open(nsPath)
if err != nil {
logrus.Errorf("If a specific network namespace is defined it must exist: %s", err)
return fmt.Errorf("Requested network namespace %v does not exist", nsPath)
}
inheritFd := &criurpc.InheritFd{
Key: proto.String(criuNsToKey(t)),
// The offset of four is necessary because 0, 1, 2 and 3 are
// already used by stdin, stdout, stderr, 'criu swrk' socket.
Fd: proto.Int32(int32(4 + len(*extraFiles))),
}
rpcOpts.InheritFd = append(rpcOpts.InheritFd, inheritFd)
// All open FDs need to be transferred to CRIU via extraFiles
*extraFiles = append(*extraFiles, nsFd)
return nil
}
func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
c.m.Lock()
defer c.m.Unlock()
// Checkpoint is unlikely to work if os.Geteuid() != 0 || system.RunningInUserNS().
// (CLI prints a warning)
// TODO(avagin): Figure out how to make this work nicely. CRIU 2.0 has
// support for doing unprivileged dumps, but the setup of
// rootless containers might make this complicated.
// We are relying on the CRIU version RPC which was introduced with CRIU 3.0.0
if err := c.checkCriuVersion(30000); err != nil {
return err
}
if criuOpts.ImagesDirectory == "" {
return errors.New("invalid directory to save checkpoint")
}
// Since a container can be C/R'ed multiple times,
// the checkpoint directory may already exist.
if err := os.Mkdir(criuOpts.ImagesDirectory, 0o700); err != nil && !os.IsExist(err) {
return err
}
imageDir, err := os.Open(criuOpts.ImagesDirectory)
if err != nil {
return err
}
defer imageDir.Close()
rpcOpts := criurpc.CriuOpts{
ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
LogLevel: proto.Int32(4),
LogFile: proto.String("dump.log"),
Root: proto.String(c.config.Rootfs),
ManageCgroups: proto.Bool(true),
NotifyScripts: proto.Bool(true),
Pid: proto.Int32(int32(c.initProcess.pid())),
ShellJob: proto.Bool(criuOpts.ShellJob),
LeaveRunning: proto.Bool(criuOpts.LeaveRunning),
TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
FileLocks: proto.Bool(criuOpts.FileLocks),
EmptyNs: proto.Uint32(criuOpts.EmptyNs),
OrphanPtsMaster: proto.Bool(true),
AutoDedup: proto.Bool(criuOpts.AutoDedup),
LazyPages: proto.Bool(criuOpts.LazyPages),
}
// if criuOpts.WorkDirectory is not set, criu default is used.
if criuOpts.WorkDirectory != "" {
if err := os.Mkdir(criuOpts.WorkDirectory, 0o700); err != nil && !os.IsExist(err) {
return err
}
workDir, err := os.Open(criuOpts.WorkDirectory)
if err != nil {
return err
}
defer workDir.Close()
rpcOpts.WorkDirFd = proto.Int32(int32(workDir.Fd()))
}
c.handleCriuConfigurationFile(&rpcOpts)
// If the container is running in a network namespace and has
// a path to the network namespace configured, we will dump
// that network namespace as an external namespace and we
// will expect that the namespace exists during restore.
// This basically means that CRIU will ignore the namespace
// and expect to be setup correctly.
if err := c.handleCheckpointingExternalNamespaces(&rpcOpts, configs.NEWNET); err != nil {
return err
}
// Same for possible external PID namespaces
if err := c.handleCheckpointingExternalNamespaces(&rpcOpts, configs.NEWPID); err != nil {
return err
}
// CRIU can use cgroup freezer; when rpcOpts.FreezeCgroup
// is not set, CRIU uses ptrace() to pause the processes.
// Note cgroup v2 freezer is only supported since CRIU release 3.14.
if !cgroups.IsCgroup2UnifiedMode() || c.checkCriuVersion(31400) == nil {
if fcg := c.cgroupManager.Path("freezer"); fcg != "" {
rpcOpts.FreezeCgroup = proto.String(fcg)
}
}
// append optional criu opts, e.g., page-server and port
if criuOpts.PageServer.Address != "" && criuOpts.PageServer.Port != 0 {
rpcOpts.Ps = &criurpc.CriuPageServerInfo{
Address: proto.String(criuOpts.PageServer.Address),
Port: proto.Int32(criuOpts.PageServer.Port),
}
}
// pre-dump may need parentImage param to complete iterative migration
if criuOpts.ParentImage != "" {
rpcOpts.ParentImg = proto.String(criuOpts.ParentImage)
rpcOpts.TrackMem = proto.Bool(true)
}
// append optional manage cgroups mode
if criuOpts.ManageCgroupsMode != 0 {
mode := criuOpts.ManageCgroupsMode
rpcOpts.ManageCgroupsMode = &mode
}
var t criurpc.CriuReqType
if criuOpts.PreDump {
feat := criurpc.CriuFeatures{
MemTrack: proto.Bool(true),
}
if err := c.checkCriuFeatures(criuOpts, &rpcOpts, &feat); err != nil {
return err
}
t = criurpc.CriuReqType_PRE_DUMP
} else {
t = criurpc.CriuReqType_DUMP
}
if criuOpts.LazyPages {
// lazy migration requested; check if criu supports it
feat := criurpc.CriuFeatures{
LazyPages: proto.Bool(true),
}
if err := c.checkCriuFeatures(criuOpts, &rpcOpts, &feat); err != nil {
return err
}
if fd := criuOpts.StatusFd; fd != -1 {
// check that the FD is valid
flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0)
if err != nil {
return fmt.Errorf("invalid --status-fd argument %d: %w", fd, err)
}
// and writable
if flags&unix.O_WRONLY == 0 {
return fmt.Errorf("invalid --status-fd argument %d: not writable", fd)
}
if c.checkCriuVersion(31500) != nil {
// For criu 3.15+, use notifications (see case "status-ready"
// in criuNotifications). Otherwise, rely on criu status fd.
rpcOpts.StatusFd = proto.Int32(int32(fd))
}
}
}
req := &criurpc.CriuReq{
Type: &t,
Opts: &rpcOpts,
}
// no need to dump all this in pre-dump
if !criuOpts.PreDump {
hasCgroupns := c.config.Namespaces.Contains(configs.NEWCGROUP)
for _, m := range c.config.Mounts {
switch m.Device {
case "bind":
c.addCriuDumpMount(req, m)
case "cgroup":
if cgroups.IsCgroup2UnifiedMode() || hasCgroupns {
// real mount(s)
continue
}
// a set of "external" bind mounts
binds, err := getCgroupMounts(m)
if err != nil {
return err
}
for _, b := range binds {
c.addCriuDumpMount(req, b)
}
}
}
if err := c.addMaskPaths(req); err != nil {
return err
}
for _, node := range c.config.Devices {
m := &configs.Mount{Destination: node.Path, Source: node.Path}
c.addCriuDumpMount(req, m)
}
// Write the FD info to a file in the image directory
fdsJSON, err := json.Marshal(c.initProcess.externalDescriptors())
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0o600)
if err != nil {
return err
}
}
err = c.criuSwrk(nil, req, criuOpts, nil)
if err != nil {
return err
}
return nil
}
func (c *linuxContainer) addCriuRestoreMount(req *criurpc.CriuReq, m *configs.Mount) {
mountDest := strings.TrimPrefix(m.Destination, c.config.Rootfs)
if dest, err := securejoin.SecureJoin(c.config.Rootfs, mountDest); err == nil {
mountDest = dest[len(c.config.Rootfs):]
}
extMnt := &criurpc.ExtMountMap{
Key: proto.String(mountDest),
Val: proto.String(m.Source),
}
req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
}
func (c *linuxContainer) restoreNetwork(req *criurpc.CriuReq, criuOpts *CriuOpts) {
for _, iface := range c.config.Networks {
switch iface.Type {
case "veth":
veth := new(criurpc.CriuVethPair)
veth.IfOut = proto.String(iface.HostInterfaceName)
veth.IfIn = proto.String(iface.Name)
req.Opts.Veths = append(req.Opts.Veths, veth)
case "loopback":
// Do nothing
}
}
for _, i := range criuOpts.VethPairs {
veth := new(criurpc.CriuVethPair)
veth.IfOut = proto.String(i.HostInterfaceName)
veth.IfIn = proto.String(i.ContainerInterfaceName)
req.Opts.Veths = append(req.Opts.Veths, veth)
}
}
// makeCriuRestoreMountpoints makes the actual mountpoints for the
// restore using CRIU. This function is inspired from the code in
// rootfs_linux.go
func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {
switch m.Device {
case "cgroup":
// No mount point(s) need to be created:
//
// * for v1, mount points are saved by CRIU because
// /sys/fs/cgroup is a tmpfs mount
//
// * for v2, /sys/fs/cgroup is a real mount, but
// the mountpoint appears as soon as /sys is mounted
return nil
case "bind":
// The prepareBindMount() function checks if source
// exists. So it cannot be used for other filesystem types.
if err := prepareBindMount(m, c.config.Rootfs); err != nil {
return err
}
default:
// for all other filesystems just create the mountpoints
dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)
if err != nil {
return err
}
if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil {
return err
}
if err := os.MkdirAll(dest, 0o755); err != nil {
return err
}
}
return nil
}
// isPathInPrefixList is a small function for CRIU restore to make sure
// mountpoints, which are on a tmpfs, are not created in the roofs
func isPathInPrefixList(path string, prefix []string) bool {
for _, p := range prefix {
if strings.HasPrefix(path, p+"/") {
return true
}
}
return false
}
// prepareCriuRestoreMounts tries to set up the rootfs of the
// container to be restored in the same way runc does it for
// initial container creation. Even for a read-only rootfs container
// runc modifies the rootfs to add mountpoints which do not exist.
// This function also creates missing mountpoints as long as they
// are not on top of a tmpfs, as CRIU will restore tmpfs content anyway.
func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error {
// First get a list of a all tmpfs mounts
tmpfs := []string{}
for _, m := range mounts {
switch m.Device {
case "tmpfs":
tmpfs = append(tmpfs, m.Destination)
}
}
// Now go through all mounts and create the mountpoints
// if the mountpoints are not on a tmpfs, as CRIU will
// restore the complete tmpfs content from its checkpoint.
umounts := []string{}
defer func() {
for _, u := range umounts {
_ = utils.WithProcfd(c.config.Rootfs, u, func(procfd string) error {
if e := unix.Unmount(procfd, unix.MNT_DETACH); e != nil {
if e != unix.EINVAL { //nolint:errorlint // unix errors are bare
// Ignore EINVAL as it means 'target is not a mount point.'
// It probably has already been unmounted.
logrus.Warnf("Error during cleanup unmounting of %s (%s): %v", procfd, u, e)
}
}
return nil
})
}
}()
for _, m := range mounts {
if !isPathInPrefixList(m.Destination, tmpfs) {
if err := c.makeCriuRestoreMountpoints(m); err != nil {
return err
}
// If the mount point is a bind mount, we need to mount
// it now so that runc can create the necessary mount
// points for mounts in bind mounts.
// This also happens during initial container creation.
// Without this CRIU restore will fail
// See: https://github.com/opencontainers/runc/issues/2748
// It is also not necessary to order the mount points
// because during initial container creation mounts are
// set up in the order they are configured.
if m.Device == "bind" {
if err := utils.WithProcfd(c.config.Rootfs, m.Destination, func(procfd string) error {
if err := mount(m.Source, m.Destination, procfd, "", unix.MS_BIND|unix.MS_REC, ""); err != nil {
return err
}
return nil
}); err != nil {
return err
}
umounts = append(umounts, m.Destination)
}
}
}
return nil
}
func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error {
c.m.Lock()
defer c.m.Unlock()
var extraFiles []*os.File
// Restore is unlikely to work if os.Geteuid() != 0 || system.RunningInUserNS().
// (CLI prints a warning)
// TODO(avagin): Figure out how to make this work nicely. CRIU doesn't have
// support for unprivileged restore at the moment.
// We are relying on the CRIU version RPC which was introduced with CRIU 3.0.0
if err := c.checkCriuVersion(30000); err != nil {
return err
}
if criuOpts.ImagesDirectory == "" {
return errors.New("invalid directory to restore checkpoint")
}
imageDir, err := os.Open(criuOpts.ImagesDirectory)
if err != nil {
return err
}
defer imageDir.Close()
// CRIU has a few requirements for a root directory:
// * it must be a mount point
// * its parent must not be overmounted
// c.config.Rootfs is bind-mounted to a temporary directory
// to satisfy these requirements.
root := filepath.Join(c.root, "criu-root")
if err := os.Mkdir(root, 0o755); err != nil {
return err
}
defer os.Remove(root)
root, err = filepath.EvalSymlinks(root)
if err != nil {
return err
}
err = mount(c.config.Rootfs, root, "", "", unix.MS_BIND|unix.MS_REC, "")
if err != nil {
return err
}
defer unix.Unmount(root, unix.MNT_DETACH) //nolint: errcheck
t := criurpc.CriuReqType_RESTORE
req := &criurpc.CriuReq{
Type: &t,
Opts: &criurpc.CriuOpts{
ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
EvasiveDevices: proto.Bool(true),
LogLevel: proto.Int32(4),
LogFile: proto.String("restore.log"),
RstSibling: proto.Bool(true),
Root: proto.String(root),
ManageCgroups: proto.Bool(true),
NotifyScripts: proto.Bool(true),
ShellJob: proto.Bool(criuOpts.ShellJob),
ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
FileLocks: proto.Bool(criuOpts.FileLocks),
EmptyNs: proto.Uint32(criuOpts.EmptyNs),
OrphanPtsMaster: proto.Bool(true),
AutoDedup: proto.Bool(criuOpts.AutoDedup),
LazyPages: proto.Bool(criuOpts.LazyPages),
},
}
if criuOpts.LsmProfile != "" {
// CRIU older than 3.16 has a bug which breaks the possibility
// to set a different LSM profile.
if err := c.checkCriuVersion(31600); err != nil {
return errors.New("--lsm-profile requires at least CRIU 3.16")
}
req.Opts.LsmProfile = proto.String(criuOpts.LsmProfile)
}
if criuOpts.WorkDirectory != "" {
// Since a container can be C/R'ed multiple times,
// the work directory may already exist.
if err := os.Mkdir(criuOpts.WorkDirectory, 0o700); err != nil && !os.IsExist(err) {
return err
}
workDir, err := os.Open(criuOpts.WorkDirectory)
if err != nil {
return err
}
defer workDir.Close()
req.Opts.WorkDirFd = proto.Int32(int32(workDir.Fd()))
}
c.handleCriuConfigurationFile(req.Opts)
if err := c.handleRestoringNamespaces(req.Opts, &extraFiles); err != nil {
return err
}
// This will modify the rootfs of the container in the same way runc
// modifies the container during initial creation.
if err := c.prepareCriuRestoreMounts(c.config.Mounts); err != nil {
return err
}
hasCgroupns := c.config.Namespaces.Contains(configs.NEWCGROUP)
for _, m := range c.config.Mounts {
switch m.Device {
case "bind":
c.addCriuRestoreMount(req, m)
case "cgroup":
if cgroups.IsCgroup2UnifiedMode() || hasCgroupns {
continue
}
// cgroup v1 is a set of bind mounts, unless cgroupns is used
binds, err := getCgroupMounts(m)
if err != nil {
return err
}
for _, b := range binds {
c.addCriuRestoreMount(req, b)
}
}
}
if len(c.config.MaskPaths) > 0 {
m := &configs.Mount{Destination: "/dev/null", Source: "/dev/null"}
c.addCriuRestoreMount(req, m)
}
for _, node := range c.config.Devices {
m := &configs.Mount{Destination: node.Path, Source: node.Path}
c.addCriuRestoreMount(req, m)
}
if criuOpts.EmptyNs&unix.CLONE_NEWNET == 0 {
c.restoreNetwork(req, criuOpts)
}
// append optional manage cgroups mode
if criuOpts.ManageCgroupsMode != 0 {
mode := criuOpts.ManageCgroupsMode
req.Opts.ManageCgroupsMode = &mode
}
var (
fds []string
fdJSON []byte
)
if fdJSON, err = ioutil.ReadFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename)); err != nil {
return err
}
if err := json.Unmarshal(fdJSON, &fds); err != nil {
return err
}
for i := range fds {
if s := fds[i]; strings.Contains(s, "pipe:") {
inheritFd := new(criurpc.InheritFd)
inheritFd.Key = proto.String(s)
inheritFd.Fd = proto.Int32(int32(i))
req.Opts.InheritFd = append(req.Opts.InheritFd, inheritFd)
}
}
err = c.criuSwrk(process, req, criuOpts, extraFiles)
// Now that CRIU is done let's close all opened FDs CRIU needed.
for _, fd := range extraFiles {
fd.Close()
}
return err
}
func (c *linuxContainer) criuApplyCgroups(pid int, req *criurpc.CriuReq) error {
// need to apply cgroups only on restore
if req.GetType() != criurpc.CriuReqType_RESTORE {
return nil
}
// XXX: Do we need to deal with this case? AFAIK criu still requires root.
if err := c.cgroupManager.Apply(pid); err != nil {
return err
}
if err := c.cgroupManager.Set(c.config.Cgroups.Resources); err != nil {
return err
}
if cgroups.IsCgroup2UnifiedMode() {
return nil
}
// the stuff below is cgroupv1-specific
path := fmt.Sprintf("/proc/%d/cgroup", pid)
cgroupsPaths, err := cgroups.ParseCgroupFile(path)
if err != nil {
return err
}
for c, p := range cgroupsPaths {
cgroupRoot := &criurpc.CgroupRoot{
Ctrl: proto.String(c),
Path: proto.String(p),
}
req.Opts.CgRoot = append(req.Opts.CgRoot, cgroupRoot)
}
return nil
}
func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts *CriuOpts, extraFiles []*os.File) error {
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_SEQPACKET|unix.SOCK_CLOEXEC, 0)
if err != nil {
return err
}
var logPath string
if opts != nil {
logPath = filepath.Join(opts.WorkDirectory, req.GetOpts().GetLogFile())
} else {
// For the VERSION RPC 'opts' is set to 'nil' and therefore
// opts.WorkDirectory does not exist. Set logPath to "".
logPath = ""
}
criuClient := os.NewFile(uintptr(fds[0]), "criu-transport-client")
criuClientFileCon, err := net.FileConn(criuClient)
criuClient.Close()
if err != nil {
return err
}
criuClientCon := criuClientFileCon.(*net.UnixConn)
defer criuClientCon.Close()
criuServer := os.NewFile(uintptr(fds[1]), "criu-transport-server")
defer criuServer.Close()
args := []string{"swrk", "3"}
if c.criuVersion != 0 {
// If the CRIU Version is still '0' then this is probably
// the initial CRIU run to detect the version. Skip it.
logrus.Debugf("Using CRIU %d at: %s", c.criuVersion, c.criuPath)
}
cmd := exec.Command(c.criuPath, args...)
if process != nil {
cmd.Stdin = process.Stdin
cmd.Stdout = process.Stdout
cmd.Stderr = process.Stderr
}
cmd.ExtraFiles = append(cmd.ExtraFiles, criuServer)
if extraFiles != nil {
cmd.ExtraFiles = append(cmd.ExtraFiles, extraFiles...)
}
if err := cmd.Start(); err != nil {
return err
}
// we close criuServer so that even if CRIU crashes or unexpectedly exits, runc will not hang.
criuServer.Close()
// cmd.Process will be replaced by a restored init.
criuProcess := cmd.Process
var criuProcessState *os.ProcessState
defer func() {
if criuProcessState == nil {
criuClientCon.Close()
_, err := criuProcess.Wait()
if err != nil {
logrus.Warnf("wait on criuProcess returned %v", err)
}
}
}()
if err := c.criuApplyCgroups(criuProcess.Pid, req); err != nil {
return err
}
var extFds []string
if process != nil {
extFds, err = getPipeFds(criuProcess.Pid)
if err != nil {
return err
}
}
logrus.Debugf("Using CRIU in %s mode", req.GetType().String())
// In the case of criurpc.CriuReqType_FEATURE_CHECK req.GetOpts()
// should be empty. For older CRIU versions it still will be
// available but empty. criurpc.CriuReqType_VERSION actually
// has no req.GetOpts().
if logrus.GetLevel() >= logrus.DebugLevel &&
!(req.GetType() == criurpc.CriuReqType_FEATURE_CHECK ||
req.GetType() == criurpc.CriuReqType_VERSION) {
val := reflect.ValueOf(req.GetOpts())
v := reflect.Indirect(val)
for i := 0; i < v.NumField(); i++ {
st := v.Type()
name := st.Field(i).Name
if 'A' <= name[0] && name[0] <= 'Z' {
value := val.MethodByName("Get" + name).Call([]reflect.Value{})
logrus.Debugf("CRIU option %s with value %v", name, value[0])
}
}
}
data, err := proto.Marshal(req)
if err != nil {
return err
}
_, err = criuClientCon.Write(data)
if err != nil {
return err
}
buf := make([]byte, 10*4096)
oob := make([]byte, 4096)
for {
n, oobn, _, _, err := criuClientCon.ReadMsgUnix(buf, oob)
if req.Opts != nil && req.Opts.StatusFd != nil {
// Close status_fd as soon as we got something back from criu,
// assuming it has consumed (reopened) it by this time.
// Otherwise it will might be left open forever and whoever
// is waiting on it will wait forever.
fd := int(*req.Opts.StatusFd)
_ = unix.Close(fd)
req.Opts.StatusFd = nil
}
if err != nil {
return err
}
if n == 0 {
return errors.New("unexpected EOF")
}
if n == len(buf) {
return errors.New("buffer is too small")
}
resp := new(criurpc.CriuResp)
err = proto.Unmarshal(buf[:n], resp)
if err != nil {
return err
}
if !resp.GetSuccess() {
typeString := req.GetType().String()
return fmt.Errorf("criu failed: type %s errno %d\nlog file: %s", typeString, resp.GetCrErrno(), logPath)
}
t := resp.GetType()
switch {
case t == criurpc.CriuReqType_FEATURE_CHECK:
logrus.Debugf("Feature check says: %s", resp)
criuFeatures = resp.GetFeatures()
case t == criurpc.CriuReqType_NOTIFY:
if err := c.criuNotifications(resp, process, cmd, opts, extFds, oob[:oobn]); err != nil {
return err
}
t = criurpc.CriuReqType_NOTIFY
req = &criurpc.CriuReq{
Type: &t,
NotifySuccess: proto.Bool(true),
}
data, err = proto.Marshal(req)
if err != nil {
return err
}
_, err = criuClientCon.Write(data)
if err != nil {
return err
}
continue
case t == criurpc.CriuReqType_RESTORE:
case t == criurpc.CriuReqType_DUMP:
case t == criurpc.CriuReqType_PRE_DUMP:
default:
return fmt.Errorf("unable to parse the response %s", resp.String())
}
break
}
_ = criuClientCon.CloseWrite()
// cmd.Wait() waits cmd.goroutines which are used for proxying file descriptors.
// Here we want to wait only the CRIU process.
criuProcessState, err = criuProcess.Wait()
if err != nil {
return err
}
// In pre-dump mode CRIU is in a loop and waits for
// the final DUMP command.
// The current runc pre-dump approach, however, is
// start criu in PRE_DUMP once for a single pre-dump
// and not the whole series of pre-dump, pre-dump, ...m, dump
// If we got the message CriuReqType_PRE_DUMP it means
// CRIU was successful and we need to forcefully stop CRIU
if !criuProcessState.Success() && *req.Type != criurpc.CriuReqType_PRE_DUMP {
return fmt.Errorf("criu failed: %s\nlog file: %s", criuProcessState.String(), logPath)
}
return nil
}
// block any external network activity
func lockNetwork(config *configs.Config) error {
for _, config := range config.Networks {
strategy, err := getStrategy(config.Type)
if err != nil {
return err
}
if err := strategy.detach(config); err != nil {
return err
}
}
return nil
}
func unlockNetwork(config *configs.Config) error {
for _, config := range config.Networks {
strategy, err := getStrategy(config.Type)
if err != nil {
return err
}
if err = strategy.attach(config); err != nil {
return err
}
}
return nil
}
func (c *linuxContainer) criuNotifications(resp *criurpc.CriuResp, process *Process, cmd *exec.Cmd, opts *CriuOpts, fds []string, oob []byte) error {
notify := resp.GetNotify()
if notify == nil {
return fmt.Errorf("invalid response: %s", resp.String())
}
script := notify.GetScript()
logrus.Debugf("notify: %s\n", script)
switch script {
case "post-dump":
f, err := os.Create(filepath.Join(c.root, "checkpoint"))
if err != nil {
return err
}
f.Close()
case "network-unlock":
if err := unlockNetwork(c.config); err != nil {
return err
}
case "network-lock":
if err := lockNetwork(c.config); err != nil {
return err
}
case "setup-namespaces":
if c.config.Hooks != nil {
s, err := c.currentOCIState()
if err != nil {
return nil
}
s.Pid = int(notify.GetPid())
if err := c.config.Hooks[configs.Prestart].RunHooks(s); err != nil {
return err
}
if err := c.config.Hooks[configs.CreateRuntime].RunHooks(s); err != nil {
return err
}
}
case "post-restore":
pid := notify.GetPid()
p, err := os.FindProcess(int(pid))
if err != nil {
return err
}
cmd.Process = p
r, err := newRestoredProcess(cmd, fds)
if err != nil {
return err
}
process.ops = r
if err := c.state.transition(&restoredState{
imageDir: opts.ImagesDirectory,
c: c,
}); err != nil {
return err
}
// create a timestamp indicating when the restored checkpoint was started
c.created = time.Now().UTC()
if _, err := c.updateState(r); err != nil {
return err
}
if err := os.Remove(filepath.Join(c.root, "checkpoint")); err != nil {
if !os.IsNotExist(err) {
logrus.Error(err)
}
}
case "orphan-pts-master":
scm, err := unix.ParseSocketControlMessage(oob)
if err != nil {
return err
}
fds, err := unix.ParseUnixRights(&scm[0])
if err != nil {
return err
}
master := os.NewFile(uintptr(fds[0]), "orphan-pts-master")
defer master.Close()
// While we can access console.master, using the API is a good idea.
if err := utils.SendFd(process.ConsoleSocket, master.Name(), master.Fd()); err != nil {
return err
}
case "status-ready":
if opts.StatusFd != -1 {
// write \0 to status fd to notify that lazy page server is ready
_, err := unix.Write(opts.StatusFd, []byte{0})
if err != nil {
logrus.Warnf("can't write \\0 to status fd: %v", err)
}
_ = unix.Close(opts.StatusFd)
opts.StatusFd = -1
}
}
return nil
}
func (c *linuxContainer) updateState(process parentProcess) (*State, error) {
if process != nil {
c.initProcess = process
}
state, err := c.currentState()
if err != nil {
return nil, err
}
err = c.saveState(state)
if err != nil {
return nil, err
}
return state, nil
}
func (c *linuxContainer) saveState(s *State) (retErr error) {
tmpFile, err := ioutil.TempFile(c.root, "state-")
if err != nil {
return err
}
defer func() {
if retErr != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
}
}()
err = utils.WriteJSON(tmpFile, s)
if err != nil {
return err
}
err = tmpFile.Close()
if err != nil {
return err
}
stateFilePath := filepath.Join(c.root, stateFilename)
return os.Rename(tmpFile.Name(), stateFilePath)
}
func (c *linuxContainer) currentStatus() (Status, error) {
if err := c.refreshState(); err != nil {
return -1, err
}
return c.state.status(), nil
}
// refreshState needs to be called to verify that the current state on the
// container is what is true. Because consumers of libcontainer can use it
// out of process we need to verify the container's status based on runtime
// information and not rely on our in process info.
func (c *linuxContainer) refreshState() error {
paused, err := c.isPaused()
if err != nil {
return err
}
if paused {
return c.state.transition(&pausedState{c: c})
}
t := c.runType()
switch t {
case Created:
return c.state.transition(&createdState{c: c})
case Running:
return c.state.transition(&runningState{c: c})
}
return c.state.transition(&stoppedState{c: c})
}
func (c *linuxContainer) runType() Status {
if c.initProcess == nil {
return Stopped
}
pid := c.initProcess.pid()
stat, err := system.Stat(pid)
if err != nil {
return Stopped
}
if stat.StartTime != c.initProcessStartTime || stat.State == system.Zombie || stat.State == system.Dead {
return Stopped
}
// We'll create exec fifo and blocking on it after container is created,
// and delete it after start container.
if _, err := os.Stat(filepath.Join(c.root, execFifoFilename)); err == nil {
return Created
}
return Running
}
func (c *linuxContainer) isPaused() (bool, error) {
state, err := c.cgroupManager.GetFreezerState()
if err != nil {
return false, err
}
return state == configs.Frozen, nil
}
func (c *linuxContainer) currentState() (*State, error) {
var (
startTime uint64
externalDescriptors []string
pid = -1
)
if c.initProcess != nil {
pid = c.initProcess.pid()
startTime, _ = c.initProcess.startTime()
externalDescriptors = c.initProcess.externalDescriptors()
}
intelRdtPath := ""
if c.intelRdtManager != nil {
intelRdtPath = c.intelRdtManager.GetPath()
}
state := &State{
BaseState: BaseState{
ID: c.ID(),
Config: *c.config,
InitProcessPid: pid,
InitProcessStartTime: startTime,
Created: c.created,
},
Rootless: c.config.RootlessEUID && c.config.RootlessCgroups,
CgroupPaths: c.cgroupManager.GetPaths(),
IntelRdtPath: intelRdtPath,
NamespacePaths: make(map[configs.NamespaceType]string),
ExternalDescriptors: externalDescriptors,
}
if pid > 0 {
for _, ns := range c.config.Namespaces {
state.NamespacePaths[ns.Type] = ns.GetPath(pid)
}
for _, nsType := range configs.NamespaceTypes() {
if !configs.IsNamespaceSupported(nsType) {
continue
}
if _, ok := state.NamespacePaths[nsType]; !ok {
ns := configs.Namespace{Type: nsType}
state.NamespacePaths[ns.Type] = ns.GetPath(pid)
}
}
}
return state, nil
}
func (c *linuxContainer) currentOCIState() (*specs.State, error) {
bundle, annotations := utils.Annotations(c.config.Labels)
state := &specs.State{
Version: specs.Version,
ID: c.ID(),
Bundle: bundle,
Annotations: annotations,
}
status, err := c.currentStatus()
if err != nil {
return nil, err
}
state.Status = specs.ContainerState(status.String())
if status != Stopped {
if c.initProcess != nil {
state.Pid = c.initProcess.pid()
}
}
return state, nil
}
// orderNamespacePaths sorts namespace paths into a list of paths that we
// can setns in order.
func (c *linuxContainer) orderNamespacePaths(namespaces map[configs.NamespaceType]string) ([]string, error) {
paths := []string{}
for _, ns := range configs.NamespaceTypes() {
// Remove namespaces that we don't need to join.
if !c.config.Namespaces.Contains(ns) {
continue
}
if p, ok := namespaces[ns]; ok && p != "" {
// check if the requested namespace is supported
if !configs.IsNamespaceSupported(ns) {
return nil, fmt.Errorf("namespace %s is not supported", ns)
}
// only set to join this namespace if it exists
if _, err := os.Lstat(p); err != nil {
return nil, fmt.Errorf("namespace path: %w", err)
}
// do not allow namespace path with comma as we use it to separate
// the namespace paths
if strings.ContainsRune(p, ',') {
return nil, fmt.Errorf("invalid namespace path %s", p)
}
paths = append(paths, fmt.Sprintf("%s:%s", configs.NsName(ns), p))
}
}
return paths, nil
}
func encodeIDMapping(idMap []configs.IDMap) ([]byte, error) {
data := bytes.NewBuffer(nil)
for _, im := range idMap {
line := fmt.Sprintf("%d %d %d\n", im.ContainerID, im.HostID, im.Size)
if _, err := data.WriteString(line); err != nil {
return nil, err
}
}
return data.Bytes(), nil
}
// bootstrapData encodes the necessary data in netlink binary format
// as a io.Reader.
// Consumer can write the data to a bootstrap program
// such as one that uses nsenter package to bootstrap the container's
// init process correctly, i.e. with correct namespaces, uid/gid
// mapping etc.
func (c *linuxContainer) bootstrapData(cloneFlags uintptr, nsMaps map[configs.NamespaceType]string) (io.Reader, error) {
// create the netlink message
r := nl.NewNetlinkRequest(int(InitMsg), 0)
// write cloneFlags
r.AddData(&Int32msg{
Type: CloneFlagsAttr,
Value: uint32(cloneFlags),
})
// write custom namespace paths
if len(nsMaps) > 0 {
nsPaths, err := c.orderNamespacePaths(nsMaps)
if err != nil {
return nil, err
}
r.AddData(&Bytemsg{
Type: NsPathsAttr,
Value: []byte(strings.Join(nsPaths, ",")),
})
}
// write namespace paths only when we are not joining an existing user ns
_, joinExistingUser := nsMaps[configs.NEWUSER]
if !joinExistingUser {
// write uid mappings
if len(c.config.UidMappings) > 0 {
if c.config.RootlessEUID && c.newuidmapPath != "" {
r.AddData(&Bytemsg{
Type: UidmapPathAttr,
Value: []byte(c.newuidmapPath),
})
}
b, err := encodeIDMapping(c.config.UidMappings)
if err != nil {
return nil, err
}
r.AddData(&Bytemsg{
Type: UidmapAttr,
Value: b,
})
}
// write gid mappings
if len(c.config.GidMappings) > 0 {
b, err := encodeIDMapping(c.config.GidMappings)
if err != nil {
return nil, err
}
r.AddData(&Bytemsg{
Type: GidmapAttr,
Value: b,
})
if c.config.RootlessEUID && c.newgidmapPath != "" {
r.AddData(&Bytemsg{
Type: GidmapPathAttr,
Value: []byte(c.newgidmapPath),
})
}
if requiresRootOrMappingTool(c.config) {
r.AddData(&Boolmsg{
Type: SetgroupAttr,
Value: true,
})
}
}
}
if c.config.OomScoreAdj != nil {
// write oom_score_adj
r.AddData(&Bytemsg{
Type: OomScoreAdjAttr,
Value: []byte(strconv.Itoa(*c.config.OomScoreAdj)),
})
}
// write rootless
r.AddData(&Boolmsg{
Type: RootlessEUIDAttr,
Value: c.config.RootlessEUID,
})
return bytes.NewReader(r.Serialize()), nil
}
// ignoreTerminateErrors returns nil if the given err matches an error known
// to indicate that the terminate occurred successfully or err was nil, otherwise
// err is returned unaltered.
func ignoreTerminateErrors(err error) error {
if err == nil {
return nil
}
// terminate() might return an error from either Kill or Wait.
// The (*Cmd).Wait documentation says: "If the command fails to run
// or doesn't complete successfully, the error is of type *ExitError".
// Filter out such errors (like "exit status 1" or "signal: killed").
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return nil
}
// TODO: use errors.Is(err, os.ErrProcessDone) here and
// remove "process already finished" string comparison below
// once go 1.16 is minimally supported version.
s := err.Error()
if strings.Contains(s, "process already finished") ||
strings.Contains(s, "Wait was already called") {
return nil
}
return err
}
func requiresRootOrMappingTool(c *configs.Config) bool {
gidMap := []configs.IDMap{
{ContainerID: 0, HostID: os.Getegid(), Size: 1},
}
return !reflect.DeepEqual(c.GidMappings, gidMap)
}
| 1 | 24,887 | Haven't tried, but what happens currently if `-f` is used and it's not running? (thinking: `-f` should ignore the case and just proceed?) I see we have a special case for `all` | opencontainers-runc | go |
@@ -1,10 +1,11 @@
'use strict';
const { MongoClient } = require('../../src');
const { expect } = require('chai');
+const { MongoURIError } = require('../../src/error');
describe('LDAP', function () {
if (process.env.MONGODB_URI == null) {
- throw new Error(`skipping SSL tests, MONGODB_URI environment variable is not defined`);
+ throw new MongoURIError(`skipping SSL tests, MONGODB_URI environment variable is not defined`);
}
it('Should correctly authenticate against ldap', function (done) { | 1 | 'use strict';
const { MongoClient } = require('../../src');
const { expect } = require('chai');
describe('LDAP', function () {
if (process.env.MONGODB_URI == null) {
throw new Error(`skipping SSL tests, MONGODB_URI environment variable is not defined`);
}
it('Should correctly authenticate against ldap', function (done) {
const client = new MongoClient(process.env.MONGODB_URI);
client.connect(function (err, client) {
expect(err).to.not.exist;
client
.db('ldap')
.collection('test')
.findOne(function (err, doc) {
expect(err).to.not.exist;
expect(doc).property('ldap').to.equal(true);
client.close(done);
});
});
});
});
| 1 | 20,718 | no need for custom errors in tests unless the tests are intended to mock a specific sort of error | mongodb-node-mongodb-native | js |
@@ -21,4 +21,6 @@ const (
NvidiaGPUStatusAnnotationKey = "huawei.com/gpu-status"
// NvidiaGPUScalarResourceName is the device plugin resource name used for special handling
NvidiaGPUScalarResourceName = "nvidia.com/gpu"
+
+ EdgeNodeRoleLabelKey = "node-role.kubernetes.io/edge"
) | 1 | package constants
// Service level constants
const (
ResourceNodeIDIndex = 1
ResourceNamespaceIndex = 2
ResourceResourceTypeIndex = 3
ResourceResourceNameIndex = 4
EdgeSiteResourceNamespaceIndex = 0
EdgeSiteResourceResourceTypeIndex = 1
EdgeSiteResourceResourceNameIndex = 2
ResourceNode = "node"
// Group
GroupResource = "resource"
// Nvidia Constants
// NvidiaGPUStatusAnnotationKey is the key of the node annotation for GPU status
NvidiaGPUStatusAnnotationKey = "huawei.com/gpu-status"
// NvidiaGPUScalarResourceName is the device plugin resource name used for special handling
NvidiaGPUScalarResourceName = "nvidia.com/gpu"
)
| 1 | 20,079 | This const has already existed in the code, no need to define a new one | kubeedge-kubeedge | go |
@@ -362,7 +362,7 @@ func captureErrorLogs(algohConfig algoh.HostConfig, errorOutput stdCollector, ou
func reportErrorf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
- logging.Base().Fatalf(format, args...)
+ logging.Base().Warnf(format, args...)
}
func sendLogs() { | 1 | // Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/daemon/algod/api/client"
"github.com/algorand/go-algorand/data/bookkeeping"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/nodecontrol"
"github.com/algorand/go-algorand/shared/algoh"
"github.com/algorand/go-algorand/tools/network"
"github.com/algorand/go-algorand/util"
)
var dataDirectory = flag.String("d", "", "Root Algorand daemon data path")
var versionCheck = flag.Bool("v", false, "Display and write current build version and exit")
var telemetryOverride = flag.String("t", "", `Override telemetry setting if supported (Use "true", "false", "0" or "1")`)
// the following flags aren't being used by the algoh, but are needed so that the flag package won't complain that
// these flags were provided but were not defined. We grab all the input flags and pass these downstream to the algod executable
// as an input arguments.
var peerOverride = flag.String("p", "", "Override phonebook with peer ip:port (or semicolon separated list: ip:port;ip:port;ip:port...)")
var listenIP = flag.String("l", "", "Override config.EndpointAddress (REST listening address) with ip:port")
var seed = flag.String("seed", "", "input to math/rand.Seed()")
var genesisFile = flag.String("g", "", "Genesis configuration file")
const algodFileName = "algod"
const goalFileName = "goal"
var exeDir string
func init() {
}
type stdCollector struct {
output string
}
func (c *stdCollector) Write(p []byte) (n int, err error) {
s := string(p)
c.output += s
return len(p), nil
}
func main() {
blockWatcherInitialized := false
flag.Parse()
nc := getNodeController()
genesis, err := nc.GetGenesis()
if err != nil {
fmt.Fprintln(os.Stdout, "error loading telemetry config", err)
return
}
dataDir := ensureDataDir()
absolutePath, absPathErr := filepath.Abs(dataDir)
config.UpdateVersionDataDir(absolutePath)
if *versionCheck {
fmt.Println(config.FormatVersionAndLicense())
return
}
// If data directory doesn't exist, we can't run. Don't bother trying.
if len(dataDir) == 0 {
fmt.Fprintln(os.Stderr, "Data directory not specified. Please use -d or set $ALGORAND_DATA in your environment.")
os.Exit(1)
}
if absPathErr != nil {
reportErrorf("Can't convert data directory's path to absolute, %v\n", dataDir)
}
algodConfig, err := config.LoadConfigFromDisk(absolutePath)
if err != nil && !os.IsNotExist(err) {
log.Fatalf("Cannot load config: %v", err)
}
if _, err := os.Stat(absolutePath); err != nil {
reportErrorf("Data directory %s does not appear to be valid\n", dataDir)
}
algohConfig, err := algoh.LoadConfigFromFile(filepath.Join(dataDir, algoh.ConfigFilename))
if err != nil && !os.IsNotExist(err) {
reportErrorf("Error loading configuration, %v\n", err)
}
validateConfig(algohConfig)
done := make(chan struct{})
log := logging.Base()
configureLogging(genesis, log, absolutePath, done, algodConfig)
defer log.CloseTelemetry()
exeDir, err = util.ExeDir()
if err != nil {
reportErrorf("Error getting ExeDir: %v\n", err)
}
var errorOutput stdCollector
var output stdCollector
go func() {
args := make([]string, len(os.Args)-1)
copy(args, os.Args[1:]) // Copy our arguments (skip the executable)
if log.GetTelemetryEnabled() {
args = append(args, "-s", log.GetTelemetrySession())
}
algodPath := filepath.Join(exeDir, algodFileName)
cmd := exec.Command(algodPath, args...)
cmd.Stderr = &errorOutput
cmd.Stdout = &output
err = cmd.Start()
if err != nil {
reportErrorf("error starting algod: %v", err)
}
err = cmd.Wait()
if err != nil {
reportErrorf("error waiting for algod: %v", err)
}
close(done)
// capture logs if algod terminated prior to blockWatcher starting
if !blockWatcherInitialized {
captureErrorLogs(algohConfig, errorOutput, output, absolutePath, true)
}
log.Infoln("++++++++++++++++++++++++++++++++++++++++")
log.Infoln("algod exited. Exiting...")
log.Infoln("++++++++++++++++++++++++++++++++++++++++")
}()
// Set up error capturing
defer func() {
captureErrorLogs(algohConfig, errorOutput, output, absolutePath, false)
}()
// Handle signals cleanly
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
signal.Ignore(syscall.SIGHUP)
go func() {
sig := <-c
fmt.Printf("Exiting algoh on %v\n", sig)
os.Exit(0)
}()
algodClient, err := waitForClient(nc, done)
if err != nil {
reportErrorf("error creating Rest Client: %v\n", err)
}
var wg sync.WaitGroup
deadMan := makeDeadManWatcher(algohConfig.DeadManTimeSec, algodClient, algohConfig.UploadOnError, done, &wg, algodConfig)
wg.Add(1)
listeners := []blockListener{deadMan}
if algohConfig.SendBlockStats {
// Note: Resume can be implemented here. Store blockListener state and set curBlock based on latestBlock/lastBlock.
listeners = append(listeners, &blockstats{log: logging.Base()})
}
delayBetweenStatusChecks := time.Duration(algohConfig.StatusDelayMS) * time.Millisecond
stallDetectionDelay := time.Duration(algohConfig.StallDelayMS) * time.Millisecond
runBlockWatcher(listeners, algodClient, done, &wg, delayBetweenStatusChecks, stallDetectionDelay)
wg.Add(1)
blockWatcherInitialized = true
wg.Wait()
fmt.Println("Exiting algoh normally...")
}
func waitForClient(nc nodecontrol.NodeController, abort chan struct{}) (client client.RestClient, err error) {
for {
client, err = getRestClient(nc)
if err == nil {
return client, nil
}
select {
case <-abort:
err = fmt.Errorf("aborted waiting for client")
return
case <-time.After(100 * time.Millisecond):
}
}
}
func getRestClient(nc nodecontrol.NodeController) (rc client.RestClient, err error) {
// Fetch the algod client
algodClient, err := nc.AlgodClient()
if err != nil {
return
}
// Make sure the node is running
_, err = algodClient.Status()
if err != nil {
return
}
return algodClient, nil
}
func resolveDataDir() string {
// Figure out what data directory to tell algod to use.
// If not specified on cmdline with '-d', look for default in environment.
var dir string
if dataDirectory == nil || *dataDirectory == "" {
dir = os.Getenv("ALGORAND_DATA")
} else {
dir = *dataDirectory
}
return dir
}
func ensureDataDir() string {
// Get the target data directory to work against,
// then handle the scenario where no data directory is provided.
dir := resolveDataDir()
if dir == "" {
reportErrorf("Data directory not specified. Please use -d or set $ALGORAND_DATA in your environment. Exiting.\n")
}
return dir
}
func getNodeController() nodecontrol.NodeController {
binDir, err := util.ExeDir()
if err != nil {
panic(err)
}
nc := nodecontrol.MakeNodeController(binDir, ensureDataDir())
return nc
}
func configureLogging(genesis bookkeeping.Genesis, log logging.Logger, rootPath string, abort chan struct{}, algodConfig config.Local) {
log = logging.Base()
liveLog := fmt.Sprintf("%s/host.log", rootPath)
fmt.Println("Logging to: ", liveLog)
writer, err := os.OpenFile(liveLog, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
panic(fmt.Sprintf("configureLogging: cannot open log file %v", err))
}
log.SetOutput(writer)
log.SetJSONFormatter()
log.SetLevel(logging.Debug)
initTelemetry(genesis, log, rootPath, abort, algodConfig)
// if we have the telemetry enabled, we want to use it's sessionid as part of the
// collected metrics decorations.
fmt.Fprintln(writer, "++++++++++++++++++++++++++++++++++++++++")
fmt.Fprintln(writer, "Logging Starting")
fmt.Fprintln(writer, "++++++++++++++++++++++++++++++++++++++++")
}
func initTelemetry(genesis bookkeeping.Genesis, log logging.Logger, dataDirectory string, abort chan struct{}, algodConfig config.Local) {
// Enable telemetry hook in daemon to send logs to cloud
// If ALGOTEST env variable is set, telemetry is disabled - allows disabling telemetry for tests
isTest := os.Getenv("ALGOTEST") != ""
if !isTest {
telemetryConfig, err := logging.EnsureTelemetryConfig(&dataDirectory, genesis.ID())
if err != nil {
fmt.Fprintln(os.Stdout, "error loading telemetry config", err)
return
}
fmt.Fprintf(os.Stdout, "algoh telemetry configured from '%s'\n", telemetryConfig.FilePath)
// Apply telemetry override.
telemetryConfig.Enable = logging.TelemetryOverride(*telemetryOverride, &telemetryConfig)
if telemetryConfig.Enable {
err = log.EnableTelemetry(telemetryConfig)
if err != nil {
fmt.Fprintln(os.Stdout, "error creating telemetry hook", err)
return
}
if log.GetTelemetryEnabled() {
// If the telemetry URI is not set, periodically check SRV records for new telemetry URI
if log.GetTelemetryURI() == "" {
network.StartTelemetryURIUpdateService(time.Minute, algodConfig, genesis.Network, log, abort)
}
// For privacy concerns, we don't want to provide the full data directory to telemetry.
// But to be useful where multiple nodes are installed for convenience, we should be
// able to discriminate between instances with the last letter of the path.
if dataDirectory != "" {
dataDirectory = dataDirectory[len(dataDirectory)-1:]
}
currentVersion := config.GetCurrentVersion()
startupDetails := telemetryspec.StartupEventDetails{
Version: currentVersion.String(),
CommitHash: currentVersion.CommitHash,
Branch: currentVersion.Branch,
Channel: currentVersion.Channel,
InstanceHash: crypto.Hash([]byte(dataDirectory)).String(),
}
log.EventWithDetails(telemetryspec.HostApplicationState, telemetryspec.StartupEvent, startupDetails)
}
}
}
}
// capture algod error output and optionally upload logs
func captureErrorLogs(algohConfig algoh.HostConfig, errorOutput stdCollector, output stdCollector, absolutePath string, errorCondition bool) {
if errorOutput.output != "" {
fmt.Fprintf(os.Stdout, "errorOutput.output: `%s`\n", errorOutput.output)
errorCondition = true
fmt.Fprintf(os.Stderr, errorOutput.output)
details := telemetryspec.ErrorOutputEventDetails{
Error: errorOutput.output,
Output: output.output,
}
log.EventWithDetails(telemetryspec.HostApplicationState, telemetryspec.ErrorOutputEvent, details)
// Write stdout & stderr streams to disk
_ = ioutil.WriteFile(filepath.Join(absolutePath, nodecontrol.StdOutFilename), []byte(output.output), os.ModePerm)
_ = ioutil.WriteFile(filepath.Join(absolutePath, nodecontrol.StdErrFilename), []byte(errorOutput.output), os.ModePerm)
}
if errorCondition && algohConfig.UploadOnError {
fmt.Fprintf(os.Stdout, "Uploading logs...\n")
sendLogs()
}
}
func reportErrorf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
logging.Base().Fatalf(format, args...)
}
func sendLogs() {
var args []string
args = append(args, "-d", ensureDataDir())
args = append(args, "logging", "send")
goalPath := filepath.Join(exeDir, goalFileName)
cmd := exec.Command(goalPath, args...)
err := cmd.Run()
if err != nil {
reportErrorf("Error sending logs: %v\n", err)
}
}
func validateConfig(config algoh.HostConfig) {
// Enforce a reasonable deadman timeout
if config.DeadManTimeSec > 0 && config.DeadManTimeSec < 30 {
reportErrorf("Config.DeadManTimeSec should be >= 30 seconds (set to %v)\n", config.DeadManTimeSec)
}
}
| 1 | 42,137 | Would Errorf be better than Warnf? | algorand-go-algorand | go |
@@ -93,15 +93,16 @@ public class JSExport {
}
public static String getCordovaPluginJS(Context context) {
- return getFilesContent(context, "public/plugins", "");
+ return getFilesContent(context, "public/plugins");
}
- public static String getFilesContent(Context context, String path, String currentContent) {
+ public static String getFilesContent(Context context, String path) {
+ String currentContent = "";
try {
String[] content = context.getAssets().list(path);
if (content.length > 0) {
for (String file: content) {
- currentContent += getFilesContent(context, path+"/"+file, currentContent);
+ currentContent += getFilesContent(context, path+"/"+file);
}
} else {
return getJS(context, path); | 1 | package com.getcapacitor;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class JSExport {
private static String CATCHALL_OPTIONS_PARAM = "_options";
private static String CALLBACK_PARAM = "_callback";
public static String getCoreJS(Context context) throws JSExportException {
try {
return getJS(context, "public/native-bridge.js");
} catch(IOException ex) {
throw new JSExportException("Unable to load native-bridge.js. Capacitor will not function!", ex);
}
}
private static String getJS(Context context, String fileName) throws IOException {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName)));
StringBuffer b = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
b.append(line + "\n");
}
return b.toString();
} catch(IOException ex) {
throw ex;
}
}
public static String getCordovaJS(Context context) {
String fileContent = "";
try {
fileContent = getJS(context, "public/cordova.js");
} catch(IOException ex) {
Log.e(Bridge.TAG, "Unable to read public/cordova.js file, Cordova plugins will not work");
}
return fileContent;
}
public static String getCordovaPluginsFileJS(Context context) {
String fileContent = "";
try {
fileContent = getJS(context, "public/cordova_plugins.js");
} catch(IOException ex) {
Log.e(Bridge.TAG, "Unable to read public/cordova_plugins.js file, Cordova plugins will not work");
}
return fileContent;
}
public static String getPluginJS(Collection<PluginHandle> plugins) {
List<String> lines = new ArrayList<String>();
lines.add("// Begin: Capacitor Plugin JS");
for(PluginHandle plugin : plugins) {
lines.add("(function(w) {\n" +
"var a = w.Capacitor; var p = a.Plugins;\n" +
"var t = p['" + plugin.getId() + "'] = {};\n" +
"t.addListener = function(eventName, callback) {\n" +
" return w.Capacitor.addListener('" + plugin.getId() + "', eventName, callback);\n" +
"}\n" +
"t.removeListener = function(eventName, callback) {\n" +
" return w.Capacitor.removeListener('" + plugin.getId() + "', eventName, callback);\n" +
"}");
Collection<PluginMethodHandle> methods = plugin.getMethods();
for(PluginMethodHandle method : methods) {
if (method.getName().equals("addListener") || method.getName().equals("removeListener")) {
// Don't export add/remove listener, we do that automatically above as they are "special snowflakes"
continue;
}
lines.add(generateMethodJS(plugin, method));
}
lines.add("})(window);\n");
}
return TextUtils.join("\n", lines);
}
public static String getCordovaPluginJS(Context context) {
return getFilesContent(context, "public/plugins", "");
}
public static String getFilesContent(Context context, String path, String currentContent) {
try {
String[] content = context.getAssets().list(path);
if (content.length > 0) {
for (String file: content) {
currentContent += getFilesContent(context, path+"/"+file, currentContent);
}
} else {
return getJS(context, path);
}
} catch(IOException ex) {
Log.e(Bridge.TAG, "Unable to read file at path "+path);
}
return currentContent;
}
private static String generateMethodJS(PluginHandle plugin, PluginMethodHandle method) {
List<String> lines = new ArrayList<String>();
List<String> args = new ArrayList<String>();
// Add the catch all param that will take a full javascript object to pass to the plugin
args.add(CATCHALL_OPTIONS_PARAM);
String returnType = method.getReturnType();
if (returnType == PluginMethod.RETURN_CALLBACK) {
args.add(CALLBACK_PARAM);
}
// Create the method function declaration
lines.add("t['" + method.getName() + "'] = function(" + TextUtils.join(", ", args) + ") {");
switch(returnType) {
case PluginMethod.RETURN_NONE:
lines.add("return w.Capacitor.nativeCallback('" + plugin.getId() + "', '" + method.getName() + "', " + CATCHALL_OPTIONS_PARAM + ")");
break;
case PluginMethod.RETURN_PROMISE:
lines.add("return w.Capacitor.nativePromise('" + plugin.getId() + "', '" + method.getName() + "', " + CATCHALL_OPTIONS_PARAM + ")");
break;
case PluginMethod.RETURN_CALLBACK:
lines.add("return w.Capacitor.nativeCallback('" + plugin.getId() + "', '" +
method.getName() + "', " + CATCHALL_OPTIONS_PARAM + ", " + CALLBACK_PARAM + ")");
break;
default:
// TODO: Do something here?
}
lines.add("}");
return TextUtils.join("\n", lines);
}
}
| 1 | 7,152 | A good candidate for StringBuilder? Also make sure to add white space around the operators (`path + "/" + file`) | ionic-team-capacitor | js |
@@ -200,4 +200,17 @@ public interface ProjectLoader {
throws ProjectManagerException;
void updateProjectSettings(Project project) throws ProjectManagerException;
+
+ /**
+ * Uploads flow file.
+ */
+ void uploadFlowFile(int projectId, int projectVersion, int flowVersion,
+ File flowFile) throws ProjectManagerException;
+
+ /**
+ * Gets flow file that's uploaded.
+ */
+ File getUploadedFlowFile(int projectId, int projectVersion, String flowName, int
+ flowVersion) throws ProjectManagerException;
+
} | 1 | /*
* Copyright 2012 LinkedIn Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package azkaban.project;
import azkaban.flow.Flow;
import azkaban.project.ProjectLogEvent.EventType;
import azkaban.user.Permission;
import azkaban.user.User;
import azkaban.utils.Props;
import azkaban.utils.Triple;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public interface ProjectLoader {
/**
* Returns all projects which are active
*/
List<Project> fetchAllActiveProjects() throws ProjectManagerException;
/**
* Loads whole project, including permissions, by the project id.
*/
Project fetchProjectById(int id) throws ProjectManagerException;
/**
* Loads whole project, including permissions, by the project name.
*/
Project fetchProjectByName(String name) throws ProjectManagerException;
/**
* Should create an empty project with the given name and user and adds it to the data store. It
* will auto assign a unique id for this project if successful.
*
* If an active project of the same name exists, it will throw an exception. If the name and
* description of the project exceeds the store's constraints, it will throw an exception.
*
* @throws ProjectManagerException if an active project of the same name exists.
*/
Project createNewProject(String name, String description, User creator)
throws ProjectManagerException;
/**
* Removes the project by marking it inactive.
*/
void removeProject(Project project, String user)
throws ProjectManagerException;
/**
* Adds and updates the user permissions. Does not check if the user is valid. If the permission
* doesn't exist, it adds. If the permission exists, it updates.
*/
void updatePermission(Project project, String name, Permission perm,
boolean isGroup) throws ProjectManagerException;
void removePermission(Project project, String name, boolean isGroup)
throws ProjectManagerException;
/**
* Modifies and commits the project description.
*/
void updateDescription(Project project, String description, String user)
throws ProjectManagerException;
/**
* Stores logs for a particular project. Will soft fail rather than throw exception.
*
* @param message return true if the posting was success.
*/
boolean postEvent(Project project, EventType type, String user,
String message);
/**
* Returns all the events for a project sorted
*/
List<ProjectLogEvent> getProjectEvents(Project project, int num,
int skip) throws ProjectManagerException;
/**
* Will upload the files and return the version number of the file uploaded.
*/
void uploadProjectFile(int projectId, int version, File localFile, String user)
throws ProjectManagerException;
/**
* Add project and version info to the project_versions table. This current maintains the metadata
* for each uploaded version of the project
*/
void addProjectVersion(int projectId, int version, File localFile, String uploader, byte[] md5,
String resourceId)
throws ProjectManagerException;
/**
* Fetch project metadata from project_versions table
*
* @param projectId project ID
* @param version version
* @return ProjectFileHandler object containing the metadata
*/
ProjectFileHandler fetchProjectMetaData(int projectId, int version);
/**
* Get file that's uploaded.
*/
ProjectFileHandler getUploadedFile(int projectId, int version)
throws ProjectManagerException;
/**
* Changes and commits different project version.
*/
void changeProjectVersion(Project project, int version, String user)
throws ProjectManagerException;
void updateFlow(Project project, int version, Flow flow)
throws ProjectManagerException;
/**
* Uploads all computed flows
*/
void uploadFlows(Project project, int version, Collection<Flow> flows)
throws ProjectManagerException;
/**
* Upload just one flow.
*/
void uploadFlow(Project project, int version, Flow flow)
throws ProjectManagerException;
/**
* Fetches one particular flow.
*/
Flow fetchFlow(Project project, String flowId)
throws ProjectManagerException;
/**
* Fetches all flows.
*/
List<Flow> fetchAllProjectFlows(Project project)
throws ProjectManagerException;
/**
* Gets the latest upload version.
*/
int getLatestProjectVersion(Project project)
throws ProjectManagerException;
/**
* Upload Project properties
*/
void uploadProjectProperty(Project project, Props props)
throws ProjectManagerException;
/**
* Upload Project properties. Map contains key value of path and properties
*/
void uploadProjectProperties(Project project, List<Props> properties)
throws ProjectManagerException;
/**
* Fetch project properties
*/
Props fetchProjectProperty(Project project, String propsName)
throws ProjectManagerException;
/**
* Fetch all project properties
*/
Map<String, Props> fetchProjectProperties(int projectId, int version)
throws ProjectManagerException;
/**
* Cleans all project versions less tha
*/
void cleanOlderProjectVersion(int projectId, int version)
throws ProjectManagerException;
void updateProjectProperty(Project project, Props props)
throws ProjectManagerException;
Props fetchProjectProperty(int projectId, int projectVer, String propsName)
throws ProjectManagerException;
List<Triple<String, Boolean, Permission>> getProjectPermissions(Project project)
throws ProjectManagerException;
void updateProjectSettings(Project project) throws ProjectManagerException;
}
| 1 | 15,205 | Can we have the same argument order as `getUploadedFlowFile`? | azkaban-azkaban | java |
@@ -46,7 +46,7 @@ type (
RangeSize int64
GetTasksBatchSize dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
UpdateAckInterval dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
- IdleTaskqueueCheckInterval dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
+ IdleTaskqueueCheckInterval dynamicconfig.DurationPropertyFn
MaxTaskqueueIdleTime dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
NumTaskqueueWritePartitions dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
NumTaskqueueReadPartitions dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters | 1 | // The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package matching
import (
"time"
"go.temporal.io/server/common"
"go.temporal.io/server/common/cache"
"go.temporal.io/server/common/dynamicconfig"
)
type (
// Config represents configuration for matching service
Config struct {
PersistenceMaxQPS dynamicconfig.IntPropertyFn
PersistenceGlobalMaxQPS dynamicconfig.IntPropertyFn
SyncMatchWaitDuration dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
RPS dynamicconfig.IntPropertyFn
ShutdownDrainDuration dynamicconfig.DurationPropertyFn
// taskQueueManager configuration
RangeSize int64
GetTasksBatchSize dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
UpdateAckInterval dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
IdleTaskqueueCheckInterval dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
MaxTaskqueueIdleTime dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
NumTaskqueueWritePartitions dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
NumTaskqueueReadPartitions dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
ForwarderMaxOutstandingPolls dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
ForwarderMaxOutstandingTasks dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
ForwarderMaxRatePerSecond dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
ForwarderMaxChildrenPerNode dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
ResilientSyncMatch dynamicconfig.BoolPropertyFn
// Time to hold a poll request before returning an empty response if there are no tasks
LongPollExpirationInterval dynamicconfig.DurationPropertyFnWithTaskQueueInfoFilters
MinTaskThrottlingBurstSize dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
MaxTaskDeleteBatchSize dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
// taskWriter configuration
OutstandingTaskAppendsThreshold dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
MaxTaskBatchSize dynamicconfig.IntPropertyFnWithTaskQueueInfoFilters
ThrottledLogRPS dynamicconfig.IntPropertyFn
AdminNamespaceToPartitionDispatchRate dynamicconfig.FloatPropertyFnWithNamespaceFilter
AdminNamespaceTaskqueueToPartitionDispatchRate dynamicconfig.FloatPropertyFnWithTaskQueueInfoFilters
}
forwarderConfig struct {
ForwarderMaxOutstandingPolls func() int
ForwarderMaxOutstandingTasks func() int
ForwarderMaxRatePerSecond func() int
ForwarderMaxChildrenPerNode func() int
}
taskQueueConfig struct {
forwarderConfig
SyncMatchWaitDuration func() time.Duration
// Time to hold a poll request before returning an empty response if there are no tasks
LongPollExpirationInterval func() time.Duration
RangeSize int64
GetTasksBatchSize func() int
UpdateAckInterval func() time.Duration
IdleTaskqueueCheckInterval func() time.Duration
MaxTaskqueueIdleTime func() time.Duration
MinTaskThrottlingBurstSize func() int
MaxTaskDeleteBatchSize func() int
// taskWriter configuration
OutstandingTaskAppendsThreshold func() int
MaxTaskBatchSize func() int
NumWritePartitions func() int
NumReadPartitions func() int
// partition qps = AdminNamespaceToPartitionDispatchRate(namespace)
AdminNamespaceToPartitionDispatchRate func() float64
// partition qps = AdminNamespaceTaskQueueToPartitionDispatchRate(namespace, task_queue)
AdminNamespaceTaskQueueToPartitionDispatchRate func() float64
// ResilientSyncMatch enables or disables sync-matching while
// persistence is unavailable
ResilientSyncMatch func() bool
}
)
// NewConfig returns new service config with default values
func NewConfig(dc *dynamicconfig.Collection) *Config {
return &Config{
PersistenceMaxQPS: dc.GetIntProperty(dynamicconfig.MatchingPersistenceMaxQPS, 3000),
PersistenceGlobalMaxQPS: dc.GetIntProperty(dynamicconfig.MatchingPersistenceGlobalMaxQPS, 0),
SyncMatchWaitDuration: dc.GetDurationPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingSyncMatchWaitDuration, 200*time.Millisecond),
RPS: dc.GetIntProperty(dynamicconfig.MatchingRPS, 1200),
RangeSize: 100000,
GetTasksBatchSize: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingGetTasksBatchSize, 1000),
UpdateAckInterval: dc.GetDurationPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingUpdateAckInterval, 1*time.Minute),
IdleTaskqueueCheckInterval: dc.GetDurationPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingIdleTaskqueueCheckInterval, 5*time.Minute),
MaxTaskqueueIdleTime: dc.GetDurationPropertyFilteredByTaskQueueInfo(dynamicconfig.MaxTaskqueueIdleTime, 5*time.Minute),
LongPollExpirationInterval: dc.GetDurationPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingLongPollExpirationInterval, time.Minute),
MinTaskThrottlingBurstSize: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingMinTaskThrottlingBurstSize, 1),
MaxTaskDeleteBatchSize: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingMaxTaskDeleteBatchSize, 100),
OutstandingTaskAppendsThreshold: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingOutstandingTaskAppendsThreshold, 250),
MaxTaskBatchSize: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingMaxTaskBatchSize, 100),
ThrottledLogRPS: dc.GetIntProperty(dynamicconfig.MatchingThrottledLogRPS, 20),
NumTaskqueueWritePartitions: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingNumTaskqueueWritePartitions, dynamicconfig.DefaultNumTaskQueuePartitions),
NumTaskqueueReadPartitions: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingNumTaskqueueReadPartitions, dynamicconfig.DefaultNumTaskQueuePartitions),
ForwarderMaxOutstandingPolls: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingForwarderMaxOutstandingPolls, 1),
ForwarderMaxOutstandingTasks: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingForwarderMaxOutstandingTasks, 1),
ForwarderMaxRatePerSecond: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingForwarderMaxRatePerSecond, 10),
ForwarderMaxChildrenPerNode: dc.GetIntPropertyFilteredByTaskQueueInfo(dynamicconfig.MatchingForwarderMaxChildrenPerNode, 20),
ResilientSyncMatch: dc.GetBoolProperty(dynamicconfig.ResilientSyncMatch, false),
ShutdownDrainDuration: dc.GetDurationProperty(dynamicconfig.MatchingShutdownDrainDuration, 0),
AdminNamespaceToPartitionDispatchRate: dc.GetFloatPropertyFilteredByNamespace(dynamicconfig.AdminMatchingNamespaceToPartitionDispatchRate, 10000),
AdminNamespaceTaskqueueToPartitionDispatchRate: dc.GetFloatPropertyFilteredByTaskQueueInfo(dynamicconfig.AdminMatchingNamespaceTaskqueueToPartitionDispatchRate, 1000),
}
}
func newTaskQueueConfig(id *taskQueueID, config *Config, namespaceCache cache.NamespaceCache) (*taskQueueConfig, error) {
namespaceEntry, err := namespaceCache.GetNamespaceByID(id.namespaceID)
if err != nil {
return nil, err
}
namespace := namespaceEntry.GetInfo().Name
taskQueueName := id.name
taskType := id.taskType
writePartition := func() int {
return common.MaxInt(1, config.NumTaskqueueWritePartitions(namespace, taskQueueName, taskType))
}
readPartition := func() int {
return common.MaxInt(1, config.NumTaskqueueReadPartitions(namespace, taskQueueName, taskType))
}
return &taskQueueConfig{
RangeSize: config.RangeSize,
GetTasksBatchSize: func() int {
return config.GetTasksBatchSize(namespace, taskQueueName, taskType)
},
UpdateAckInterval: func() time.Duration {
return config.UpdateAckInterval(namespace, taskQueueName, taskType)
},
IdleTaskqueueCheckInterval: func() time.Duration {
return config.IdleTaskqueueCheckInterval(namespace, taskQueueName, taskType)
},
MaxTaskqueueIdleTime: func() time.Duration {
return config.MaxTaskqueueIdleTime(namespace, taskQueueName, taskType)
},
MinTaskThrottlingBurstSize: func() int {
return config.MinTaskThrottlingBurstSize(namespace, taskQueueName, taskType)
},
SyncMatchWaitDuration: func() time.Duration {
return config.SyncMatchWaitDuration(namespace, taskQueueName, taskType)
},
LongPollExpirationInterval: func() time.Duration {
return config.LongPollExpirationInterval(namespace, taskQueueName, taskType)
},
MaxTaskDeleteBatchSize: func() int {
return config.MaxTaskDeleteBatchSize(namespace, taskQueueName, taskType)
},
OutstandingTaskAppendsThreshold: func() int {
return config.OutstandingTaskAppendsThreshold(namespace, taskQueueName, taskType)
},
MaxTaskBatchSize: func() int {
return config.MaxTaskBatchSize(namespace, taskQueueName, taskType)
},
NumWritePartitions: writePartition,
NumReadPartitions: readPartition,
AdminNamespaceToPartitionDispatchRate: func() float64 {
return config.AdminNamespaceToPartitionDispatchRate(namespace)
},
AdminNamespaceTaskQueueToPartitionDispatchRate: func() float64 {
return config.AdminNamespaceTaskqueueToPartitionDispatchRate(namespace, taskQueueName, taskType)
},
forwarderConfig: forwarderConfig{
ForwarderMaxOutstandingPolls: func() int {
return config.ForwarderMaxOutstandingPolls(namespace, taskQueueName, taskType)
},
ForwarderMaxOutstandingTasks: func() int {
return config.ForwarderMaxOutstandingTasks(namespace, taskQueueName, taskType)
},
ForwarderMaxRatePerSecond: func() int {
return config.ForwarderMaxRatePerSecond(namespace, taskQueueName, taskType)
},
ForwarderMaxChildrenPerNode: func() int {
return common.MaxInt(1, config.ForwarderMaxChildrenPerNode(namespace, taskQueueName, taskType))
},
},
ResilientSyncMatch: func() bool {
return config.ResilientSyncMatch()
},
}, nil
}
| 1 | 12,281 | this dynamic config should still be valid, i.e. operator should have the ability to control each individual task queue just in case | temporalio-temporal | go |
@@ -394,6 +394,17 @@ class VirtualBufferTextInfo(browseMode.BrowseModeDocumentTextInfo,textInfos.offs
obj = self.obj.getNVDAObjectFromIdentifier(docHandle, nodeId)
return obj.mathMl
+ def scrollIntoView(self):
+ # Scroll the deepest object at this point into view.
+ obj = self.NVDAObjectAtStart
+ if not obj:
+ return
+ if obj == self.obj.rootNVDAObject:
+ # However never scroll to the document itself
+ return
+ obj.scrollIntoView()
+
+
class VirtualBuffer(browseMode.BrowseModeDocumentTreeInterceptor):
TextInfo=VirtualBufferTextInfo | 1 | # -*- coding: UTF-8 -*-
#virtualBuffers/__init__.py
#A part of NonVisual Desktop Access (NVDA)
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
#Copyright (C) 2007-2017 NV Access Limited, Peter Vágner
import time
import threading
import ctypes
import collections
import itertools
import typing
import weakref
import wx
import review
import NVDAHelper
import XMLFormatting
import scriptHandler
from scriptHandler import script
import speech
import NVDAObjects
import api
import controlTypes
import textInfos.offsets
import config
import cursorManager
import browseMode
import gui
import eventHandler
import braille
import queueHandler
from logHandler import log
import ui
import aria
import treeInterceptorHandler
import watchdog
from abc import abstractmethod
VBufStorage_findDirection_forward=0
VBufStorage_findDirection_back=1
VBufStorage_findDirection_up=2
VBufRemote_nodeHandle_t=ctypes.c_ulonglong
class VBufStorage_findMatch_word(str):
pass
VBufStorage_findMatch_notEmpty = object()
FINDBYATTRIBS_ESCAPE_TABLE = {
# Symbols that are escaped in the attributes string.
ord(u":"): r"\\:",
ord(u";"): r"\\;",
ord(u"\\"): u"\\\\\\\\",
}
# Symbols that must be escaped for a regular expression.
FINDBYATTRIBS_ESCAPE_TABLE.update({(ord(s), u"\\" + s) for s in u"^$.*+?()[]{}|"})
def _prepareForFindByAttributes(attribs):
# A lambda that coerces a value to a string and escapes characters suitable for a regular expression.
escape = lambda val: str(val).translate(FINDBYATTRIBS_ESCAPE_TABLE)
reqAttrs = []
regexp = []
if isinstance(attribs, dict):
# Single option.
attribs = (attribs,)
# All options will match against all requested attributes,
# so first build the list of requested attributes.
for option in attribs:
for name in option:
reqAttrs.append(name)
# Now build the regular expression.
for option in attribs:
optRegexp = []
for name in reqAttrs:
optRegexp.append("%s:" % escape(name))
values = option.get(name)
if not values:
# The value isn't tested for this attribute, so match any (or no) value.
optRegexp.append(r"(?:\\;|[^;])*;")
elif values[0] is VBufStorage_findMatch_notEmpty:
# There must be a value for this attribute.
optRegexp.append(r"(?:\\;|[^;])+;")
elif isinstance(values[0], VBufStorage_findMatch_word):
# Assume all are word matches.
optRegexp.append(r"(?:\\;|[^;])*\b(?:")
optRegexp.append("|".join(escape(val) for val in values))
optRegexp.append(r")\b(?:\\;|[^;])*;")
else:
# Assume all are exact matches or None (must not exist).
optRegexp.append("(?:" )
optRegexp.append("|".join((escape(val)+u';') if val is not None else u';' for val in values))
optRegexp.append(")")
regexp.append("".join(optRegexp))
return u" ".join(reqAttrs), u"|".join(regexp)
class VirtualBufferQuickNavItem(browseMode.TextInfoQuickNavItem):
def __init__(self,itemType,document,vbufNode,startOffset,endOffset):
textInfo=document.makeTextInfo(textInfos.offsets.Offsets(startOffset,endOffset))
super(VirtualBufferQuickNavItem,self).__init__(itemType,document,textInfo)
docHandle=ctypes.c_int()
ID=ctypes.c_int()
NVDAHelper.localLib.VBuf_getIdentifierFromControlFieldNode(document.VBufHandle, vbufNode, ctypes.byref(docHandle), ctypes.byref(ID))
self.vbufFieldIdentifier=(docHandle.value,ID.value)
self.vbufNode=vbufNode
@property
def obj(self):
return self.document.getNVDAObjectFromIdentifier(*self.vbufFieldIdentifier)
@property
def label(self):
attrs = {}
def propertyGetter(prop):
if not attrs:
# Lazily fetch the attributes the first time they're needed.
# We do this because we don't want to do this if they're not needed at all.
attrs.update(self.textInfo._getControlFieldAttribs(self.vbufFieldIdentifier[0], self.vbufFieldIdentifier[1]))
return attrs.get(prop)
return self._getLabelForProperties(propertyGetter)
def isChild(self,parent):
if self.itemType == "heading":
try:
if (int(self.textInfo._getControlFieldAttribs(self.vbufFieldIdentifier[0], self.vbufFieldIdentifier[1])["level"])
> int(parent.textInfo._getControlFieldAttribs(parent.vbufFieldIdentifier[0], parent.vbufFieldIdentifier[1])["level"])):
return True
except (KeyError, ValueError, TypeError):
return False
return super(VirtualBufferQuickNavItem,self).isChild(parent)
class VirtualBufferTextInfo(browseMode.BrowseModeDocumentTextInfo,textInfos.offsets.OffsetsTextInfo):
allowMoveToOffsetPastEnd=False #: no need for end insertion point as vbuf is not editable.
def _getControlFieldAttribs(self, docHandle, id):
info = self.copy()
info.expand(textInfos.UNIT_CHARACTER)
for field in reversed(info.getTextWithFields()):
if not (isinstance(field, textInfos.FieldCommand) and field.command == "controlStart"):
# Not a control field.
continue
attrs = field.field
if int(attrs["controlIdentifier_docHandle"]) == docHandle and int(attrs["controlIdentifier_ID"]) == id:
return attrs
raise LookupError
def _getFieldIdentifierFromOffset(self, offset):
startOffset = ctypes.c_int()
endOffset = ctypes.c_int()
docHandle = ctypes.c_int()
ID = ctypes.c_int()
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_locateControlFieldNodeAtOffset(self.obj.VBufHandle, offset, ctypes.byref(startOffset), ctypes.byref(endOffset), ctypes.byref(docHandle), ctypes.byref(ID),ctypes.byref(node))
if not any((docHandle.value, ID.value)):
raise LookupError("Neither docHandle nor ID found for offset %d" % offset)
return docHandle.value, ID.value
def _getOffsetsFromFieldIdentifier(self, docHandle, ID):
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_getControlFieldNodeWithIdentifier(self.obj.VBufHandle, docHandle, ID,ctypes.byref(node))
if not node:
raise LookupError
start = ctypes.c_int()
end = ctypes.c_int()
NVDAHelper.localLib.VBuf_getFieldNodeOffsets(self.obj.VBufHandle, node, ctypes.byref(start), ctypes.byref(end))
return start.value, end.value
def _getBoundingRectFromOffset(self,offset):
o = self._getNVDAObjectFromOffset(offset)
if not o:
raise LookupError("no NVDAObject at offset %d" % offset)
if o.hasIrrelevantLocation:
raise LookupError("Object is off screen, invisible or has no location")
return o.location
def _getNVDAObjectFromOffset(self,offset):
try:
docHandle,ID=self._getFieldIdentifierFromOffset(offset)
except LookupError:
log.debugWarning("Couldn't get NVDAObject from offset %d" % offset)
return None
return self.obj.getNVDAObjectFromIdentifier(docHandle,ID)
def _getOffsetsFromNVDAObjectInBuffer(self,obj):
docHandle,ID=self.obj.getIdentifierFromNVDAObject(obj)
return self._getOffsetsFromFieldIdentifier(docHandle,ID)
def _getOffsetsFromNVDAObject(self, obj):
while True:
try:
return self._getOffsetsFromNVDAObjectInBuffer(obj)
except LookupError:
pass
# Interactive list/combo box/tree view descendants aren't rendered into the buffer, even though they are still considered part of it.
# Use the container in this case.
obj = obj.parent
if not obj or obj.role not in (controlTypes.Role.LIST, controlTypes.Role.COMBOBOX, controlTypes.Role.GROUPING, controlTypes.Role.TREEVIEW, controlTypes.Role.TREEVIEWITEM):
break
raise LookupError
def __init__(self,obj,position):
self.obj=obj
super(VirtualBufferTextInfo,self).__init__(obj,position)
def _getSelectionOffsets(self):
start=ctypes.c_int()
end=ctypes.c_int()
NVDAHelper.localLib.VBuf_getSelectionOffsets(self.obj.VBufHandle,ctypes.byref(start),ctypes.byref(end))
return start.value,end.value
def _setSelectionOffsets(self,start,end):
NVDAHelper.localLib.VBuf_setSelectionOffsets(self.obj.VBufHandle,start,end)
def _getCaretOffset(self):
return self._getSelectionOffsets()[0]
def _setCaretOffset(self,offset):
return self._setSelectionOffsets(offset,offset)
def _getStoryLength(self):
return NVDAHelper.localLib.VBuf_getTextLength(self.obj.VBufHandle)
def _getTextRange(self,start,end):
if start==end:
return u""
return NVDAHelper.VBuf_getTextInRange(self.obj.VBufHandle,start,end,False) or u""
def _getPlaceholderAttribute(self, attrs, placeholderAttrsKey):
"""Gets the placeholder attribute to be used.
@return: The placeholder attribute when there is no content within the ControlField.
None when the ControlField has content.
@note: The content is considered empty if it holds a single space.
"""
placeholder = attrs.get(placeholderAttrsKey)
# For efficiency, only check if it is valid to return placeholder when we have a placeholder value to return.
if not placeholder:
return None
# Get the start and end offsets for the field. This can be used to check if the field has any content.
try:
start, end = self._getOffsetsFromFieldIdentifier(
int(attrs.get('controlIdentifier_docHandle')),
int(attrs.get('controlIdentifier_ID')))
except (LookupError, ValueError):
log.debugWarning("unable to get offsets used to fetch content")
return placeholder
else:
valueLen = end - start
if not valueLen: # value is empty, use placeholder
return placeholder
# Because fetching the content of the field could result in a large amount of text
# we only do it in order to check for space.
# We first compare the length by comparing the offsets, if the length is less than 2 (ie
# could hold space)
if valueLen < 2:
controlFieldText = self.obj.makeTextInfo(textInfos.offsets.Offsets(start, end)).text
if not controlFieldText or controlFieldText == ' ':
return placeholder
return None
def _getFieldsInRange(self,start,end):
text=NVDAHelper.VBuf_getTextInRange(self.obj.VBufHandle,start,end,True)
if not text:
return ""
commandList: typing.List[textInfos.FieldCommand] = XMLFormatting.XMLTextParser().parse(text)
for command in commandList:
if not isinstance(command, textInfos.FieldCommand):
continue # no need to normalize str or None
field = command.field
if isinstance(field, textInfos.ControlField):
command.field = self._normalizeControlField(field)
elif isinstance(field, textInfos.FormatField):
command.field = self._normalizeFormatField(field)
return commandList
def getTextWithFields(self,formatConfig=None):
start=self._startOffset
end=self._endOffset
if start==end:
return ""
return self._getFieldsInRange(start,end)
def _getWordOffsets(self,offset):
#Use VBuf_getBufferLineOffsets with out screen layout to find out the range of the current field
lineStart=ctypes.c_int()
lineEnd=ctypes.c_int()
NVDAHelper.localLib.VBuf_getLineOffsets(self.obj.VBufHandle,offset,0,False,ctypes.byref(lineStart),ctypes.byref(lineEnd))
word_startOffset,word_endOffset=super(VirtualBufferTextInfo,self)._getWordOffsets(offset)
return (max(lineStart.value,word_startOffset),min(lineEnd.value,word_endOffset))
def _getLineOffsets(self,offset):
lineStart=ctypes.c_int()
lineEnd=ctypes.c_int()
NVDAHelper.localLib.VBuf_getLineOffsets(self.obj.VBufHandle,offset,config.conf["virtualBuffers"]["maxLineLength"],config.conf["virtualBuffers"]["useScreenLayout"],ctypes.byref(lineStart),ctypes.byref(lineEnd))
return lineStart.value,lineEnd.value
def _getParagraphOffsets(self,offset):
lineStart=ctypes.c_int()
lineEnd=ctypes.c_int()
NVDAHelper.localLib.VBuf_getLineOffsets(self.obj.VBufHandle,offset,0,True,ctypes.byref(lineStart),ctypes.byref(lineEnd))
return lineStart.value,lineEnd.value
def _normalizeControlField(self, attrs: textInfos.ControlField):
tableLayout=attrs.get('table-layout')
if tableLayout:
attrs['table-layout']=tableLayout=="1"
# convert some table attributes to ints
for attr in ("table-id","table-rownumber","table-columnnumber","table-rowsspanned","table-columnsspanned"):
attrVal=attrs.get(attr)
if attrVal is not None:
attrs[attr]=int(attrVal)
isHidden=attrs.get('isHidden')
if isHidden:
attrs['isHidden']=isHidden=="1"
# Handle table row and column headers.
for axis in "row", "column":
attr = attrs.pop("table-%sheadercells" % axis, None)
if not attr:
continue
cellIdentifiers = [identifier.split(",") for identifier in attr.split(";") if identifier]
# Get the text for the header cells.
textList = []
for docHandle, ID in cellIdentifiers:
if attrs.get("controlIdentifier_docHandle") == docHandle and attrs.get("controlIdentifier_ID") == ID:
# This is a self-reference to a column or row header
# Do not double up the cell header name. This is happening in Chrome.
continue
try:
start, end = self._getOffsetsFromFieldIdentifier(int(docHandle), int(ID))
except (LookupError, ValueError):
continue
textList.append(self.obj.makeTextInfo(textInfos.offsets.Offsets(start, end)).text)
attrs["table-%sheadertext" % axis] = "\n".join(textList)
if attrs.get("role") in (controlTypes.Role.LANDMARK, controlTypes.Role.REGION):
attrs['alwaysReportName'] = True
# Expose a unique ID on the controlField for quick and safe comparison using the virtualBuffer field's docHandle and ID
docHandle=attrs.get('controlIdentifier_docHandle')
ID=attrs.get('controlIdentifier_ID')
if docHandle is not None and ID is not None:
attrs['uniqueID']=(docHandle,ID)
return attrs
def _normalizeFormatField(self, attrs: textInfos.FormatField):
strippedCharsFromStart = attrs.get("strippedCharsFromStart")
if strippedCharsFromStart is not None:
assert strippedCharsFromStart.isdigit(), "strippedCharsFromStart isn't a digit, %r" % strippedCharsFromStart
attrs["strippedCharsFromStart"] = int(strippedCharsFromStart)
return attrs
def _getLineNumFromOffset(self, offset):
return None
def _get_fieldIdentifierAtStart(self):
return self._getFieldIdentifierFromOffset( self._startOffset)
def _getUnitOffsets(self, unit, offset):
if unit == textInfos.UNIT_CONTROLFIELD:
startOffset=ctypes.c_int()
endOffset=ctypes.c_int()
docHandle=ctypes.c_int()
ID=ctypes.c_int()
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_locateControlFieldNodeAtOffset(self.obj.VBufHandle,offset,ctypes.byref(startOffset),ctypes.byref(endOffset),ctypes.byref(docHandle),ctypes.byref(ID),ctypes.byref(node))
return startOffset.value,endOffset.value
elif unit == textInfos.UNIT_FORMATFIELD:
startOffset=ctypes.c_int()
endOffset=ctypes.c_int()
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_locateTextFieldNodeAtOffset(self.obj.VBufHandle,offset,ctypes.byref(startOffset),ctypes.byref(endOffset),ctypes.byref(node))
return startOffset.value,endOffset.value
return super(VirtualBufferTextInfo, self)._getUnitOffsets(unit, offset)
def _get_clipboardText(self):
# Blocks should start on a new line, but they don't necessarily have an end of line indicator.
# Therefore, get the text in block (paragraph) chunks and join the chunks with \r\n.
blocks = (block.strip("\r\n") for block in self.getTextInChunks(textInfos.UNIT_PARAGRAPH))
return "\r\n".join(blocks)
def activate(self):
self.obj._activatePosition(info=self)
def getMathMl(self, field):
docHandle = int(field["controlIdentifier_docHandle"])
nodeId = int(field["controlIdentifier_ID"])
obj = self.obj.getNVDAObjectFromIdentifier(docHandle, nodeId)
return obj.mathMl
class VirtualBuffer(browseMode.BrowseModeDocumentTreeInterceptor):
TextInfo=VirtualBufferTextInfo
#: Maps root identifiers (docHandle and ID) to buffers.
rootIdentifiers = weakref.WeakValueDictionary()
def __init__(self,rootNVDAObject,backendName=None):
super(VirtualBuffer,self).__init__(rootNVDAObject)
self.backendName=backendName
self.VBufHandle=None
self.isLoading=False
self.rootDocHandle,self.rootID=self.getIdentifierFromNVDAObject(self.rootNVDAObject)
self.rootIdentifiers[self.rootDocHandle, self.rootID] = self
def prepare(self):
if not self.rootNVDAObject.appModule.helperLocalBindingHandle:
# #5758: If NVDA starts with a document already in focus, there will have been no focus event to inject nvdaHelper yet.
# So at very least don't try to prepare a virtualBuffer as it will fail.
# The user will most likely need to manually move focus away and back again to allow this virtualBuffer to work.
log.debugWarning("appModule has no binding handle to injected code, can't prepare virtualBuffer yet.")
return
self.shouldPrepare=False
self.loadBuffer()
def _get_shouldPrepare(self):
return not self.isLoading and not self.VBufHandle
def terminate(self):
super(VirtualBuffer,self).terminate()
if not self.VBufHandle:
return
self.unloadBuffer()
def _get_isReady(self):
return bool(self.VBufHandle and not self.isLoading)
def loadBuffer(self):
self.isLoading = True
self._loadProgressCallLater = wx.CallLater(1000, self._loadProgress)
threading.Thread(
name=f"{self.__class__.__module__}.{self.loadBuffer.__qualname__}",
target=self._loadBuffer).start(
)
def _loadBuffer(self):
try:
if log.isEnabledFor(log.DEBUG):
startTime = time.time()
self.VBufHandle=NVDAHelper.localLib.VBuf_createBuffer(
self.rootNVDAObject.appModule.helperLocalBindingHandle,
self.rootDocHandle,self.rootID,
self.backendName
)
if not self.VBufHandle:
raise RuntimeError("Could not remotely create virtualBuffer")
except:
log.error("", exc_info=True)
queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone, success=False)
return
if log.isEnabledFor(log.DEBUG):
log.debug("Buffer load took %.3f sec, %d chars" % (
time.time() - startTime,
NVDAHelper.localLib.VBuf_getTextLength(self.VBufHandle)))
queueHandler.queueFunction(queueHandler.eventQueue, self._loadBufferDone)
def _loadBufferDone(self, success=True):
self._loadProgressCallLater.Stop()
del self._loadProgressCallLater
self.isLoading = False
if not success:
self.passThrough=True
return
if self._hadFirstGainFocus:
# If this buffer has already had focus once while loaded, this is a refresh.
# Translators: Reported when a page reloads (example: after refreshing a webpage).
ui.message(_("Refreshed"))
if api.getFocusObject().treeInterceptor == self:
self.event_treeInterceptor_gainFocus()
def _loadProgress(self):
# Translators: Reported while loading a document.
ui.message(_("Loading document..."))
def unloadBuffer(self):
if self.VBufHandle is not None:
try:
watchdog.cancellableExecute(NVDAHelper.localLib.VBuf_destroyBuffer, ctypes.byref(ctypes.c_int(self.VBufHandle)))
except WindowsError:
pass
self.VBufHandle=None
def isNVDAObjectPartOfLayoutTable(self,obj):
docHandle,ID=self.getIdentifierFromNVDAObject(obj)
ID=str(ID)
info=self.makeTextInfo(obj)
info.collapse()
info.expand(textInfos.UNIT_CHARACTER)
fieldCommands=[x for x in info.getTextWithFields() if isinstance(x,textInfos.FieldCommand)]
tableLayout=None
tableID=None
for fieldCommand in fieldCommands:
fieldID=fieldCommand.field.get("controlIdentifier_ID") if fieldCommand.field else None
if fieldID==ID:
tableLayout=fieldCommand.field.get('table-layout')
if tableLayout is not None:
return tableLayout
tableID=fieldCommand.field.get('table-id')
break
if tableID is None:
return False
for fieldCommand in fieldCommands:
fieldID=fieldCommand.field.get("controlIdentifier_ID") if fieldCommand.field else None
if fieldID==tableID:
tableLayout=fieldCommand.field.get('table-layout',False)
break
return tableLayout
@abstractmethod
def getNVDAObjectFromIdentifier(self, docHandle, ID):
"""Retrieve an NVDAObject for a given node identifier.
Subclasses must override this method.
@param docHandle: The document handle.
@type docHandle: int
@param ID: The ID of the node.
@type ID: int
@return: The NVDAObject.
@rtype: L{NVDAObjects.NVDAObject}
"""
raise NotImplementedError
@abstractmethod
def getIdentifierFromNVDAObject(self,obj):
"""Retreaves the virtualBuffer field identifier from an NVDAObject.
@param obj: the NVDAObject to retreave the field identifier from.
@type obj: L{NVDAObject}
@returns: a the field identifier as a doc handle and ID paire.
@rtype: 2-tuple.
"""
raise NotImplementedError
def script_refreshBuffer(self,gesture):
if scriptHandler.isScriptWaiting():
# This script may cause subsequently queued scripts to fail, so don't execute.
return
self.unloadBuffer()
self.loadBuffer()
# Translators: the description for the refreshBuffer script on virtualBuffers.
script_refreshBuffer.__doc__ = _("Refreshes the document content")
@script(
description=_(
# Translators: the description for the toggleScreenLayout script on virtualBuffers.
"Toggles on and off if the screen layout is preserved while rendering the document content"
),
gesture="kb:NVDA+v",
)
def script_toggleScreenLayout(self,gesture):
config.conf["virtualBuffers"]["useScreenLayout"]=not config.conf["virtualBuffers"]["useScreenLayout"]
if config.conf["virtualBuffers"]["useScreenLayout"]:
# Translators: Presented when use screen layout option is toggled.
ui.message(_("Use screen layout on"))
else:
# Translators: Presented when use screen layout option is toggled.
ui.message(_("Use screen layout off"))
def _searchableAttributesForNodeType(self,nodeType):
pass
def _iterNodesByType(self,nodeType,direction="next",pos=None):
attribs=self._searchableAttribsForNodeType(nodeType)
if not attribs:
raise NotImplementedError
return self._iterNodesByAttribs(attribs, direction, pos,nodeType)
def _iterNodesByAttribs(self, attribs, direction="next", pos=None,nodeType=None):
offset=pos._startOffset if pos else -1
reqAttrs, regexp = _prepareForFindByAttributes(attribs)
startOffset=ctypes.c_int()
endOffset=ctypes.c_int()
if direction=="next":
direction=VBufStorage_findDirection_forward
elif direction=="previous":
direction=VBufStorage_findDirection_back
elif direction=="up":
direction=VBufStorage_findDirection_up
else:
raise ValueError("unknown direction: %s"%direction)
while True:
try:
node=VBufRemote_nodeHandle_t()
NVDAHelper.localLib.VBuf_findNodeByAttributes(self.VBufHandle,offset,direction,reqAttrs,regexp,ctypes.byref(startOffset),ctypes.byref(endOffset),ctypes.byref(node))
except:
return
if not node:
return
yield VirtualBufferQuickNavItem(nodeType,self,node,startOffset.value,endOffset.value)
offset=startOffset
def _getTableCellAt(self,tableID,startPos,row,column):
try:
return next(self._iterTableCells(tableID,row=row,column=column))
except StopIteration:
raise LookupError
def _iterTableCells(self, tableID, startPos=None, direction="next", row=None, column=None):
attrs = {"table-id": [str(tableID)]}
# row could be 0.
if row is not None:
attrs["table-rownumber"] = [str(row)]
if column is not None:
attrs["table-columnnumber"] = [str(column)]
results = self._iterNodesByAttribs(attrs, pos=startPos, direction=direction)
if not startPos and not row and not column and direction == "next":
# The first match will be the table itself, so skip it.
next(results)
for item in results:
yield item.textInfo
def _getNearestTableCell(self, tableID, startPos, origRow, origCol, origRowSpan, origColSpan, movement, axis):
# Determine destination row and column.
destRow = origRow
destCol = origCol
if axis == "row":
destRow += origRowSpan if movement == "next" else -1
elif axis == "column":
destCol += origColSpan if movement == "next" else -1
if destCol < 1:
# Optimisation: We're definitely at the edge of the column.
raise LookupError
# Optimisation: Try searching for exact destination coordinates.
# This won't work if they are covered by a cell spanning multiple rows/cols, but this won't be true in the majority of cases.
try:
return self._getTableCellAt(tableID,startPos,destRow,destCol)
except LookupError:
pass
# Cells are grouped by row, so in most cases, we simply need to search in the right direction.
for info in self._iterTableCells(tableID, direction=movement, startPos=startPos):
_ignore, row, col, rowSpan, colSpan = self._getTableCellCoords(info)
if row <= destRow < row + rowSpan and col <= destCol < col + colSpan:
return info
elif row > destRow and movement == "next":
# Optimisation: We've gone forward past destRow, so we know we won't find the cell.
# We can't reverse this logic when moving backwards because there might be a prior cell on an earlier row which spans multiple rows.
break
if axis == "row" or (axis == "column" and movement == "previous"):
# In most cases, there's nothing more to try.
raise LookupError
else:
# We're moving forward by column.
# In this case, there might be a cell on an earlier row which spans multiple rows.
# Therefore, try searching backwards.
for info in self._iterTableCells(tableID, direction="previous", startPos=startPos):
_ignore, row, col, rowSpan, colSpan = self._getTableCellCoords(info)
if row <= destRow < row + rowSpan and col <= destCol < col + colSpan:
return info
else:
raise LookupError
def _isSuitableNotLinkBlock(self, textRange):
return (textRange._endOffset - textRange._startOffset) >= self.NOT_LINK_BLOCK_MIN_LEN
def getEnclosingContainerRange(self, textRange):
formatConfig=config.conf['documentFormatting'].copy()
formatConfig.update({"reportBlockQuotes":True,"reportTables":True,"reportLists":True,"reportFrames":True})
controlFields=[]
for cmd in textRange.getTextWithFields():
if not isinstance(cmd,textInfos.FieldCommand) or cmd.command!="controlStart":
break
controlFields.append(cmd.field)
containerField=None
while controlFields:
field=controlFields.pop()
if field.getPresentationCategory(controlFields,formatConfig)==field.PRESCAT_CONTAINER or field.get("landmark"):
containerField=field
break
if not containerField: return None
docHandle=int(containerField['controlIdentifier_docHandle'])
ID=int(containerField['controlIdentifier_ID'])
offsets = textRange._getOffsetsFromFieldIdentifier(docHandle,ID)
return self.makeTextInfo(textInfos.offsets.Offsets(*offsets))
@classmethod
def changeNotify(cls, rootDocHandle, rootID):
try:
queueHandler.queueFunction(queueHandler.eventQueue, cls.rootIdentifiers[rootDocHandle, rootID]._handleUpdate)
except KeyError:
pass
def _handleUpdate(self):
"""Handle an update to this buffer.
"""
if not self.VBufHandle:
# #4859: The buffer was unloaded after this method was queued.
return
braille.handler.handleUpdate(self)
def getControlFieldForNVDAObject(self, obj):
docHandle, objId = self.getIdentifierFromNVDAObject(obj)
objId = str(objId)
info = self.makeTextInfo(obj)
info.collapse()
info.expand(textInfos.UNIT_CHARACTER)
for item in info.getTextWithFields():
if not isinstance(item, textInfos.FieldCommand) or not item.field:
continue
fieldId = item.field.get("controlIdentifier_ID")
if fieldId == objId:
return item.field
raise LookupError
def _isNVDAObjectInApplication_noWalk(self, obj):
inApp = super(VirtualBuffer, self)._isNVDAObjectInApplication_noWalk(obj)
if inApp is not None:
return inApp
# If the object is in the buffer, it's definitely not in an application.
try:
docHandle, objId = self.getIdentifierFromNVDAObject(obj)
except:
log.debugWarning("getIdentifierFromNVDAObject failed. "
"Object probably died while walking ancestors.", exc_info=True)
return None
node = VBufRemote_nodeHandle_t()
if not self.VBufHandle:
return None
try:
NVDAHelper.localLib.VBuf_getControlFieldNodeWithIdentifier(self.VBufHandle, docHandle, objId,ctypes.byref(node))
except WindowsError:
return None
if node:
return False
return None
__gestures = {
"kb:NVDA+f5": "refreshBuffer",
}
| 1 | 33,837 | Should these cases be logged? `if not obj` used to be | nvaccess-nvda | py |
@@ -0,0 +1,19 @@
+require 'travis/build/appliances/base'
+
+module Travis
+ module Build
+ module Appliances
+ class UpdateAptKeys < Base
+ def apply
+ command = <<-EOF
+ if command -v apt-get &>/dev/null && [[ -d /var/lib/apt/lists ]]; then
+ LANG=C apt-key list | awk -F'[ /]+' '/expired:/{printf "apt-key adv --recv-keys --keyserver keys.gnupg.net %s\\n", $3}' | sudo sh &>/dev/null
+ fi
+ EOF
+ sh.cmd command, echo: false
+ end
+ end
+ end
+ end
+end
+ | 1 | 1 | 15,802 | Is it OK to assume that keys.gnupg.net has the new key? | travis-ci-travis-build | rb |
|
@@ -128,11 +128,6 @@ class FileSystem(object):
exist, raise luigi.target.MissingParentDirectory
:param bool raise_if_exists: raise luigi.target.FileAlreadyExists if
the folder already exists.
-
- *Note*: This method is optional, not all FileSystem subclasses implements it.
-
- *Note*: parents and raise_if_exists were added in August 2014. Some
- implementations might not support these flags yet.
"""
raise NotImplementedError("mkdir() not implemented on {0}".format(self.__class__.__name__))
| 1 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
The abstract :py:class:`Target` class.
It is a central concept of Luigi and represents the state of the workflow.
"""
import abc
import io
import os
import random
import tempfile
import logging
import warnings
from luigi import six
logger = logging.getLogger('luigi-interface')
@six.add_metaclass(abc.ABCMeta)
class Target(object):
"""
A Target is a resource generated by a :py:class:`~luigi.task.Task`.
For example, a Target might correspond to a file in HDFS or data in a database. The Target
interface defines one method that must be overridden: :py:meth:`exists`, which signifies if the
Target has been created or not.
Typically, a :py:class:`~luigi.task.Task` will define one or more Targets as output, and the Task
is considered complete if and only if each of its output Targets exist.
"""
@abc.abstractmethod
def exists(self):
"""
Returns ``True`` if the :py:class:`Target` exists and ``False`` otherwise.
"""
pass
class FileSystemException(Exception):
"""
Base class for generic file system exceptions.
"""
pass
class FileAlreadyExists(FileSystemException):
"""
Raised when a file system operation can't be performed because
a directory exists but is required to not exist.
"""
pass
class MissingParentDirectory(FileSystemException):
"""
Raised when a parent directory doesn't exist.
(Imagine mkdir without -p)
"""
pass
class NotADirectory(FileSystemException):
"""
Raised when a file system operation can't be performed because
an expected directory is actually a file.
"""
pass
@six.add_metaclass(abc.ABCMeta)
class FileSystem(object):
"""
FileSystem abstraction used in conjunction with :py:class:`FileSystemTarget`.
Typically, a FileSystem is associated with instances of a :py:class:`FileSystemTarget`. The
instances of the py:class:`FileSystemTarget` will delegate methods such as
:py:meth:`FileSystemTarget.exists` and :py:meth:`FileSystemTarget.remove` to the FileSystem.
Methods of FileSystem raise :py:class:`FileSystemException` if there is a problem completing the
operation.
"""
@abc.abstractmethod
def exists(self, path):
"""
Return ``True`` if file or directory at ``path`` exist, ``False`` otherwise
:param str path: a path within the FileSystem to check for existence.
"""
pass
@abc.abstractmethod
def remove(self, path, recursive=True, skip_trash=True):
""" Remove file or directory at location ``path``
:param str path: a path within the FileSystem to remove.
:param bool recursive: if the path is a directory, recursively remove the directory and all
of its descendants. Defaults to ``True``.
"""
pass
def mkdir(self, path, parents=True, raise_if_exists=False):
"""
Create directory at location ``path``
Creates the directory at ``path`` and implicitly create parent
directories if they do not already exist.
:param str path: a path within the FileSystem to create as a directory.
:param bool parents: Create parent directories when necessary. When
parents=False and the parent directory doesn't
exist, raise luigi.target.MissingParentDirectory
:param bool raise_if_exists: raise luigi.target.FileAlreadyExists if
the folder already exists.
*Note*: This method is optional, not all FileSystem subclasses implements it.
*Note*: parents and raise_if_exists were added in August 2014. Some
implementations might not support these flags yet.
"""
raise NotImplementedError("mkdir() not implemented on {0}".format(self.__class__.__name__))
def isdir(self, path):
"""
Return ``True`` if the location at ``path`` is a directory. If not, return ``False``.
:param str path: a path within the FileSystem to check as a directory.
*Note*: This method is optional, not all FileSystem subclasses implements it.
"""
raise NotImplementedError("isdir() not implemented on {0}".format(self.__class__.__name__))
def listdir(self, path):
"""Return a list of files rooted in path.
This returns an iterable of the files rooted at ``path``. This is intended to be a
recursive listing.
:param str path: a path within the FileSystem to list.
*Note*: This method is optional, not all FileSystem subclasses implements it.
"""
raise NotImplementedError("listdir() not implemented on {0}".format(self.__class__.__name__))
def move(self, path, dest):
"""
Move a file, as one would expect.
"""
raise NotImplementedError("move() not implemented on {0}".format(self.__class__.__name__))
def rename_dont_move(self, path, dest):
"""
Potentially rename ``path`` to ``dest``, but don't move it into the
``dest`` folder (if it is a folder). This relates to :ref:`AtomicWrites`.
This method has a reasonable but not bullet proof default
implementation. It will just do ``move()`` if the file doesn't
``exists()`` already.
"""
warnings.warn("File system {} client doesn't support atomic mv.".format(self.__class__.__name__))
if self.exists(dest):
raise FileAlreadyExists()
self.move(path, dest)
def rename(self, *args, **kwargs):
"""
Alias for ``move()``
"""
self.move(*args, **kwargs)
def copy(self, path, dest):
"""
Copy a file or a directory with contents.
Currently, LocalFileSystem and MockFileSystem support only single file
copying but S3Client copies either a file or a directory as required.
"""
raise NotImplementedError("copy() not implemented on {0}".
format(self.__class__.__name__))
class FileSystemTarget(Target):
"""
Base class for FileSystem Targets like :class:`~luigi.file.LocalTarget` and :class:`~luigi.contrib.hdfs.HdfsTarget`.
A FileSystemTarget has an associated :py:class:`FileSystem` to which certain operations can be
delegated. By default, :py:meth:`exists` and :py:meth:`remove` are delegated to the
:py:class:`FileSystem`, which is determined by the :py:attr:`fs` property.
Methods of FileSystemTarget raise :py:class:`FileSystemException` if there is a problem
completing the operation.
"""
def __init__(self, path):
"""
Initializes a FileSystemTarget instance.
:param str path: the path associated with this FileSystemTarget.
"""
self.path = path
@abc.abstractproperty
def fs(self):
"""
The :py:class:`FileSystem` associated with this FileSystemTarget.
"""
raise NotImplementedError()
@abc.abstractmethod
def open(self, mode):
"""
Open the FileSystem target.
This method returns a file-like object which can either be read from or written to depending
on the specified mode.
:param str mode: the mode `r` opens the FileSystemTarget in read-only mode, whereas `w` will
open the FileSystemTarget in write mode. Subclasses can implement
additional options.
"""
pass
def exists(self):
"""
Returns ``True`` if the path for this FileSystemTarget exists; ``False`` otherwise.
This method is implemented by using :py:attr:`fs`.
"""
path = self.path
if '*' in path or '?' in path or '[' in path or '{' in path:
logger.warning("Using wildcards in path %s might lead to processing of an incomplete dataset; "
"override exists() to suppress the warning.", path)
return self.fs.exists(path)
def remove(self):
"""
Remove the resource at the path specified by this FileSystemTarget.
This method is implemented by using :py:attr:`fs`.
"""
self.fs.remove(self.path)
def temporary_path(self):
"""
A context manager that enables a reasonably short, general and
magic-less way to solve the :ref:`AtomicWrites`. When the context
manager enters it will not do anything, but when it exits it will move
the file if there was no exception thrown.
The final move operation will be carried out by calling
:py:meth:`FileSystem.rename_dont_move` on :py:attr:`fs`.
The typical use case looks like this:
.. code:: python
class MyTask(luigi.Task):
def output(self):
return MyFileSystemTarget(...)
def run(self):
with self.output().temporary_path() as self.temp_output_path:
run_some_external_command(output_dir=self.temp_output_path)
"""
class _Manager(object):
target = self
def __init__(self):
num = random.randrange(0, 1e10)
self._temp_path = '{}-luigi-tmp-{:010}{}'.format(
self.target.path.rstrip('/').rstrip("\\"),
num,
self.target._trailing_slash())
def __enter__(self):
return self._temp_path
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is None:
# There were no exceptions
self.target.fs.rename_dont_move(self._temp_path, self.target.path)
return False # False means we don't suppress the exception
return _Manager()
def _touchz(self):
with self.open('w'):
pass
def _trailing_slash(self):
# I suppose one day schema-like paths, like
# file:///path/blah.txt?params=etc can be parsed too
return self.path[-1] if self.path[-1] in r'\/' else ''
class AtomicLocalFile(io.BufferedWriter):
"""Abstract class to create a Target that creates
a temporary file in the local filesystem before
moving it to its final destination.
This class is just for the writing part of the Target. See
:class:`luigi.file.LocalTarget` for example
"""
def __init__(self, path):
self.__tmp_path = self.generate_tmp_path(path)
self.path = path
super(AtomicLocalFile, self).__init__(io.FileIO(self.__tmp_path, 'w'))
def close(self):
super(AtomicLocalFile, self).close()
self.move_to_final_destination()
def generate_tmp_path(self, path):
return os.path.join(tempfile.gettempdir(), 'luigi-s3-tmp-%09d' % random.randrange(0, 1e10))
def move_to_final_destination(self):
raise NotImplementedError()
def __del__(self):
if os.path.exists(self.tmp_path):
os.remove(self.tmp_path)
@property
def tmp_path(self):
return self.__tmp_path
def __exit__(self, exc_type, exc, traceback):
" Close/commit the file if there are no exception "
if exc_type:
return
return super(AtomicLocalFile, self).__exit__(exc_type, exc, traceback)
| 1 | 16,214 | A note for however is curious. I think these two notes add negative value only. In general we want people to implement this method (in particular after this patch). If we leave these old (and currently mis-rendered) notes, file system implementors might not implement this method referring to this. | spotify-luigi | py |
@@ -216,15 +216,12 @@ public class PriorityQueueTest extends AbstractTraversableTest {
empty().dequeue();
}
- // -- toSortedQueue
+ // -- toPriorityQueue
@Test
- public void shouldKeepInstanceOfSortedQueue() {
- final SerializableComparator<Integer> comparator = naturalComparator();
- final PriorityQueue<Integer> queue = PriorityQueue.of(comparator, 1, 3, 2);
- if (!queue.isSingleValued()) {
- assertThat(queue.toSortedQueue(comparator)).isSameAs(queue);
- }
+ public void shouldKeepInstanceOfPriorityQueue() {
+ final PriorityQueue<Integer> queue = PriorityQueue.of(1, 3, 2);
+ assertThat(queue.toPriorityQueue()).isSameAs(queue);
}
// -- property based tests | 1 | /* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.Tuple;
import javaslang.Value;
import javaslang.collection.Comparators.SerializableComparator;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
import java.util.stream.Stream;
import static java.lang.Integer.bitCount;
import static java.util.stream.Collectors.toList;
import static javaslang.collection.Comparators.naturalComparator;
public class PriorityQueueTest extends AbstractTraversableTest {
private final List<Integer> values = List.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8, 4, 1, 9, 7, 1, 6, 9, 3, 9, 9, 3, 7, 5, 1, 0);
@Override
protected <T> Collector<T, ArrayList<T>, PriorityQueue<T>> collector() {
return PriorityQueue.collector();
}
@Override
protected <T> PriorityQueue<T> empty() {
return PriorityQueue.empty(toStringComparator());
}
@Override
protected <T> PriorityQueue<T> of(T element) {
return PriorityQueue.ofAll(toStringComparator(), List.of(element));
}
@Override
@SuppressWarnings("unchecked")
protected final <T> PriorityQueue<T> of(T... elements) {
return PriorityQueue.ofAll(toStringComparator(), List.of(elements));
}
@Override
protected <T> PriorityQueue<T> ofAll(Iterable<? extends T> elements) {
return PriorityQueue.ofAll(toStringComparator(), elements);
}
@Override
protected <T> Traversable<T> ofJavaStream(Stream<? extends T> javaStream) {
return PriorityQueue.ofAll(toStringComparator(), javaStream);
}
@Override
protected PriorityQueue<Boolean> ofAll(boolean[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Byte> ofAll(byte[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Character> ofAll(char[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Double> ofAll(double[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Float> ofAll(float[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Integer> ofAll(int[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Long> ofAll(long[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected PriorityQueue<Short> ofAll(short[] array) {
return PriorityQueue.ofAll(List.ofAll(array));
}
@Override
protected <T> PriorityQueue<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
return PriorityQueue.tabulate(n, f);
}
@Override
protected <T> PriorityQueue<T> fill(int n, Supplier<? extends T> s) {
return PriorityQueue.fill(n, s);
}
@Override
protected boolean useIsEqualToInsteadOfIsSameAs() {
return true;
}
@Override
protected int getPeekNonNilPerformingAnAction() {
return 1;
}
@Override
protected boolean emptyShouldBeSingleton() {
return false;
}
private static SerializableComparator<Object> toStringComparator() {
return (o1, o2) -> String.valueOf(o1).compareTo(String.valueOf(o2));
}
private static Comparator<Integer> composedComparator() {
final Comparator<Integer> bitCountComparator = (o1, o2) -> Integer.compare(bitCount(o1), bitCount(o2));
return bitCountComparator.thenComparing(naturalComparator());
}
@Test
@Override
public void shouldScanLeftWithNonComparable() {
// The resulting type would need a comparator
}
@Test
@Override
public void shouldScanRightWithNonComparable() {
// The resulting type would need a comparator
}
@Override
public void shouldPreserveSingletonInstanceOnDeserialization() {
// The empty PriorityQueue encapsulates a comparator and therefore cannot be a singleton
}
// -- static narrow
@Test
public void shouldNarrowQueue() {
final PriorityQueue<Double> doubles = of(1.0d);
final PriorityQueue<Number> numbers = PriorityQueue.narrow(doubles);
final int actual = numbers.enqueue(new BigDecimal("2.0")).sum().intValue();
assertThat(actual).isEqualTo(3);
}
// -- toList
@Test
public void toListIsSortedAccordingToComparator() {
final Comparator<Integer> comparator = composedComparator();
final PriorityQueue<Integer> queue = PriorityQueue.ofAll(comparator, values);
assertThat(queue.toList()).isEqualTo(values.sorted(comparator));
}
// -- merge
@Test
public void shouldMergeTwoPriorityQueues() {
final PriorityQueue<Integer> source = of(3, 1, 4, 1, 5);
final PriorityQueue<Integer> target = of(9, 2, 6, 5, 3);
assertThat(source.merge(target)).isEqualTo(of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3));
assertThat(PriorityQueue.of(3).merge(PriorityQueue.of(toStringComparator(), 1))).isEqualTo(of(3, 1));
}
// -- distinct
@Test
public void shouldComputeDistinctOfNonEmptyTraversableUsingKeyExtractor() {
final Comparator<String> comparator = (o1, o2) -> Integer.compare(o1.charAt(1), o2.charAt(1));
assertThat(PriorityQueue.of(comparator, "5c", "1a", "3a", "1a", "2a", "4b", "3b").distinct().map(s -> s.substring(1))).isEqualTo(of("a", "b", "c"));
}
// -- removeAll
@Test
public void shouldRemoveAllElements() {
assertThat(of(3, 1, 4, 1, 5, 9, 2, 6).removeAll(of(1, 9, 1, 2))).isEqualTo(of(3, 4, 5, 6));
}
// -- enqueueAll
@Test
public void shouldEnqueueAllElements() {
assertThat(of(3, 1, 4).enqueueAll(of(1, 5, 9, 2))).isEqualTo(of(3, 1, 4, 1, 5, 9, 2));
}
// -- peek
@Test(expected = NoSuchElementException.class)
public void shouldFailPeekOfEmpty() {
empty().peek();
}
// -- dequeue
@Test
public void shouldDeque() {
assertThat(of(3, 1, 4, 1, 5).dequeue()).isEqualTo(Tuple.of(1, of(3, 4, 1, 5)));
}
@Test(expected = NoSuchElementException.class)
public void shouldFailDequeueOfEmpty() {
empty().dequeue();
}
// -- toSortedQueue
@Test
public void shouldKeepInstanceOfSortedQueue() {
final SerializableComparator<Integer> comparator = naturalComparator();
final PriorityQueue<Integer> queue = PriorityQueue.of(comparator, 1, 3, 2);
if (!queue.isSingleValued()) {
assertThat(queue.toSortedQueue(comparator)).isSameAs(queue);
}
}
// -- property based tests
@Test
public void shouldBehaveExactlyLikeAnotherPriorityQueue() {
for (int i = 0; i < 10; i++) {
final Random random = getRandom(-1);
final java.util.PriorityQueue<Integer> mutablePriorityQueue = new java.util.PriorityQueue<>();
javaslang.collection.PriorityQueue<Integer> functionalPriorityQueue = javaslang.collection.PriorityQueue.empty();
final int size = 100_000;
for (int j = 0; j < size; j++) {
/* Insert */
if (random.nextInt() % 3 == 0) {
assertMinimumsAreEqual(mutablePriorityQueue, functionalPriorityQueue);
final int value = random.nextInt(size) - (size / 2);
mutablePriorityQueue.add(value);
functionalPriorityQueue = functionalPriorityQueue.enqueue(value);
}
assertMinimumsAreEqual(mutablePriorityQueue, functionalPriorityQueue);
/* Delete */
if (random.nextInt() % 5 == 0) {
if (!mutablePriorityQueue.isEmpty()) { mutablePriorityQueue.poll(); }
if (!functionalPriorityQueue.isEmpty()) { functionalPriorityQueue = functionalPriorityQueue.tail(); }
assertMinimumsAreEqual(mutablePriorityQueue, functionalPriorityQueue);
}
}
final Collection<Integer> oldValues = mutablePriorityQueue.stream().sorted().collect(toList());
final Collection<Integer> newValues = functionalPriorityQueue.toJavaList();
assertThat(oldValues).isEqualTo(newValues);
}
}
private void assertMinimumsAreEqual(java.util.PriorityQueue<Integer> oldQueue, PriorityQueue<Integer> newQueue) {
assertThat(oldQueue.isEmpty()).isEqualTo(newQueue.isEmpty());
if (!newQueue.isEmpty()) {
assertThat(oldQueue.peek()).isEqualTo(newQueue.head());
}
}
// -- toSortedQueue
@Test
public void shouldReturnSelfOnConvertToSortedQueue() {
Value<Integer> value = of(1, 2, 3);
assertThat(value.toSortedQueue(Integer::compareTo)).isSameAs(value);
}
} | 1 | 9,316 | Comparators (or functions in general) cannot be compared for equality. Therefore `PriorityQueue.of(comparator, ...)` always has to return a new instance. | vavr-io-vavr | java |
@@ -27,7 +27,7 @@ module Bolt
@noop = noop
@run_as = nil
- @pool = Concurrent::CachedThreadPool.new(max_threads: @config[:concurrency])
+ @pool = Concurrent::ThreadPoolExecutor.new(max_threads: @config[:concurrency])
@logger.debug { "Started with #{@config[:concurrency]} max thread(s)" }
@notifier = Bolt::Notifier.new
end | 1 | # frozen_string_literal: true
# Used for $ERROR_INFO. This *must* be capitalized!
require 'English'
require 'json'
require 'concurrent'
require 'logging'
require 'bolt/result'
require 'bolt/config'
require 'bolt/notifier'
require 'bolt/result_set'
require 'bolt/puppetdb'
module Bolt
class Executor
attr_reader :noop, :transports
attr_accessor :run_as, :plan_logging
def initialize(config = Bolt::Config.new, noop = nil)
@config = config
@logger = Logging.logger[self]
@plan_logging = false
@transports = Bolt::TRANSPORTS.each_with_object({}) do |(key, val), coll|
coll[key.to_s] = Concurrent::Delay.new { val.new }
end
@noop = noop
@run_as = nil
@pool = Concurrent::CachedThreadPool.new(max_threads: @config[:concurrency])
@logger.debug { "Started with #{@config[:concurrency]} max thread(s)" }
@notifier = Bolt::Notifier.new
end
def transport(transport)
impl = @transports[transport || 'ssh']
raise(Bolt::UnknownTransportError, transport) unless impl
# If there was an error creating the transport, ensure it gets thrown
impl.no_error!
impl.value
end
# Execute the given block on a list of nodes in parallel, one thread per "batch".
#
# This is the main driver of execution on a list of targets. It first
# groups targets by transport, then divides each group into batches as
# defined by the transport. Each batch, along with the corresponding
# transport, is yielded to the block in turn and the results all collected
# into a single ResultSet.
def batch_execute(targets)
promises = targets.group_by(&:protocol).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_object({}) do |target, h|
h[target] = Concurrent::Promise.new(executor: :immediate)
end
# Pass this argument through to avoid retaining a reference to a
# local variable that will change on the next iteration of the loop.
@pool.post(batch_promises) do |result_promises|
begin
results = yield transport, batch
Array(results).each do |result|
result_promises[result.target].set(result)
end
# NotImplementedError can be thrown if the transport is implemented improperly
rescue StandardError, NotImplementedError => e
result_promises.each do |target, promise|
promise.set(Bolt::Result.from_exception(target, e))
end
ensure
# Make absolutely sure every promise gets a result to avoid a
# deadlock. Use whatever exception is causing this block to
# execute, or generate one if we somehow got here without an
# exception and some promise is still missing a result.
result_promises.each do |target, promise|
next if promise.fulfilled?
error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}",
"puppetlabs.bolt/missing-result-error")
promise.set(Bolt::Result.from_exception(target, error))
end
end
end
batch_promises.values
end
end
ResultSet.new(promises.map(&:value))
end
def log_action(description, targets)
# When running a plan, info messages like starting a task are promoted to notice.
log_method = @plan_logging ? :notice : :info
target_str = if targets.length > 5
"#{targets.count} targets"
else
targets.map(&:uri).join(', ')
end
@logger.send(log_method, "Starting: #{description} on #{target_str}")
start_time = Time.now
results = yield
duration = Time.now - start_time
failures = results.error_set.length
plural = failures == 1 ? '' : 's'
@logger.send(log_method, "Finished: #{description} with #{failures} failure#{plural} in #{duration.round(2)} sec")
results
end
private :log_action
def with_node_logging(description, batch)
@logger.info("#{description} on #{batch.map(&:uri)}")
result = yield
@logger.info(result.to_json)
result
end
private :with_node_logging
def run_command(targets, command, options = {}, &callback)
description = options.fetch('_description', "command '#{command}'")
log_action(description, targets) do
notify = proc { |event| @notifier.notify(callback, event) if callback }
options = { '_run_as' => run_as }.merge(options) if run_as
results = batch_execute(targets) do |transport, batch|
with_node_logging("Running command '#{command}'", batch) do
transport.batch_command(batch, command, options, ¬ify)
end
end
@notifier.shutdown
results
end
end
def run_script(targets, script, arguments, options = {}, &callback)
description = options.fetch('_description', "script #{script}")
log_action(description, targets) do
notify = proc { |event| @notifier.notify(callback, event) if callback }
options = { '_run_as' => run_as }.merge(options) if run_as
results = batch_execute(targets) do |transport, batch|
with_node_logging("Running script #{script} with '#{arguments}'", batch) do
transport.batch_script(batch, script, arguments, options, ¬ify)
end
end
@notifier.shutdown
results
end
end
def run_task(targets, task, arguments, options = {}, &callback)
description = options.fetch('_description', "task #{task.name}")
log_action(description, targets) do
notify = proc { |event| @notifier.notify(callback, event) if callback }
options = { '_run_as' => run_as }.merge(options) if run_as
results = batch_execute(targets) do |transport, batch|
with_node_logging("Running task #{task.name} with '#{arguments}' via #{task.input_method}", batch) do
transport.batch_task(batch, task, arguments, options, ¬ify)
end
end
@notifier.shutdown
results
end
end
def file_upload(targets, source, destination, options = {}, &callback)
description = options.fetch('_description', "file upload from #{source} to #{destination}")
log_action(description, targets) do
notify = proc { |event| @notifier.notify(callback, event) if callback }
options = { '_run_as' => run_as }.merge(options) if run_as
results = batch_execute(targets) do |transport, batch|
with_node_logging("Uploading file #{source} to #{destination}", batch) do
transport.batch_upload(batch, source, destination, options, ¬ify)
end
end
@notifier.shutdown
results
end
end
# Plan context doesn't make sense for most transports but it is tightly
# coupled with the orchestrator transport since the transport behaves
# differently when a plan is running. In order to limit how much this
# pollutes the transport API we only handle the orchestrator transport here.
# Since we callt this function without resolving targets this will result
# in the orchestrator transport always being initialized during plan runs.
# For now that's ok.
#
# In the future if other transports need this or if we want a plan stack
# we'll need to refactor.
def start_plan(plan_context)
transport('pcp').plan_context = plan_context
@plan_logging = true
end
def finish_plan(plan_result)
transport('pcp').finish_plan(plan_result)
end
end
end
| 1 | 8,626 | It's a little surprising that CachedThreadPool overrides the max_threads argument. This makes sense as a solution though. | puppetlabs-bolt | rb |
@@ -42,12 +42,14 @@ def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
# if avg_factor is not specified, just reduce the loss
if avg_factor is None:
loss = reduce_loss(loss, reduction)
- # otherwise average the loss by avg_factor
- else:
- if reduction != 'mean':
- raise ValueError(
- 'avg_factor can only be used with reduction="mean"')
+ # if avg_factor are specified
+ # if reduction is mean, reduce the loss sum by avg factor
+ elif reduction == 'mean':
loss = loss.sum() / avg_factor
+ elif reduction == 'none':
+ loss = loss
+ else:
+ raise ValueError('avg_factor can not be used with reduction="sum"')
return loss
| 1 | import functools
import torch.nn.functional as F
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = F._Reduction.get_enum(reduction)
# none: 0, elementwise_mean:1, sum: 2
if reduction_enum == 0:
return loss
elif reduction_enum == 1:
return loss.mean()
elif reduction_enum == 2:
return loss.sum()
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
"""Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Avarage factor when computing the mean of losses.
Returns:
Tensor: Processed loss values.
"""
# if weight is specified, apply element-wise weight
if weight is not None:
loss = loss * weight
# if avg_factor is not specified, just reduce the loss
if avg_factor is None:
loss = reduce_loss(loss, reduction)
# otherwise average the loss by avg_factor
else:
if reduction != 'mean':
raise ValueError(
'avg_factor can only be used with reduction="mean"')
loss = loss.sum() / avg_factor
return loss
def weighted_loss(loss_func):
"""Create a weighted version of a given loss function.
To use this decorator, the loss function must have the signature like
`loss_func(pred, target, **kwargs)`. The function only needs to compute
element-wise loss without any reduction. This decorator will add weight
and reduction arguments to the function. The decorated function will have
the signature like `loss_func(pred, target, weight=None, reduction='mean',
avg_factor=None, **kwargs)`.
:Example:
>>> @weighted_loss
>>> def l1_loss(pred, target):
>>> return (pred - target).abs()
>>> pred = torch.Tensor([0, 2, 3])
>>> target = torch.Tensor([1, 1, 1])
>>> weight = torch.Tensor([1, 0, 1])
>>> l1_loss(pred, target)
tensor(1.3333)
>>> l1_loss(pred, target, weight)
tensor(1.)
>>> l1_loss(pred, target, reduction='none')
tensor([1., 1., 2.])
>>> l1_loss(pred, target, weight, avg_factor=2)
tensor(1.5000)
"""
@functools.wraps(loss_func)
def wrapper(pred,
target,
weight=None,
reduction='mean',
avg_factor=None,
**kwargs):
# get element-wise loss
loss = loss_func(pred, target, **kwargs)
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
return wrapper
| 1 | 17,617 | ```python # if avg_factor is not specified, just reduce the loss if avg_factor is None: loss = reduce_loss(loss, reduction) else: # if reduction is mean, then average the loss by avg_factor if reduction == 'mean': loss = loss.sum() / avg_factor # if reduction is 'none', then do nothing, otherwise raise an error elif reduction != 'none': raise ValueError('avg_factor can not be used with reduction="sum"') | open-mmlab-mmdetection | py |
@@ -46,9 +46,9 @@ class BasicBlock(nn.Module):
planes,
planes,
3,
- stride=stride,
- padding=dilation,
- dilation=dilation,
+ stride=1,
+ padding=1,
+ dilation=1,
bias=False)
self.add_module(self.norm2_name, norm2)
| 1 | import logging
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import constant_init, kaiming_init
from mmcv.runner import load_checkpoint
from mmdet.ops import DeformConv, ModulatedDeformConv
from ..registry import BACKBONES
from ..utils import build_conv_layer, build_norm_layer
class BasicBlock(nn.Module):
expansion = 1
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
normalize=dict(type='BN'),
dcn=None):
super(BasicBlock, self).__init__()
assert dcn is None, "Not implemented yet."
self.norm1_name, norm1 = build_norm_layer(normalize, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(normalize, planes, postfix=2)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
3,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm1_name, norm1)
self.conv2 = build_conv_layer(
conv_cfg,
planes,
planes,
3,
stride=stride,
padding=dilation,
dilation=dilation,
bias=False)
self.add_module(self.norm2_name, norm2)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
assert not with_cp
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.norm2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self,
inplanes,
planes,
stride=1,
dilation=1,
downsample=None,
style='pytorch',
with_cp=False,
conv_cfg=None,
normalize=dict(type='BN'),
dcn=None):
"""Bottleneck block for ResNet.
If style is "pytorch", the stride-two layer is the 3x3 conv layer,
if it is "caffe", the stride-two layer is the first 1x1 conv layer.
"""
super(Bottleneck, self).__init__()
assert style in ['pytorch', 'caffe']
assert dcn is None or isinstance(dcn, dict)
self.inplanes = inplanes
self.planes = planes
self.conv_cfg = conv_cfg
self.normalize = normalize
self.dcn = dcn
self.with_dcn = dcn is not None
if style == 'pytorch':
self.conv1_stride = 1
self.conv2_stride = stride
else:
self.conv1_stride = stride
self.conv2_stride = 1
self.norm1_name, norm1 = build_norm_layer(normalize, planes, postfix=1)
self.norm2_name, norm2 = build_norm_layer(normalize, planes, postfix=2)
self.norm3_name, norm3 = build_norm_layer(
normalize, planes * self.expansion, postfix=3)
self.conv1 = build_conv_layer(
conv_cfg,
inplanes,
planes,
kernel_size=1,
stride=self.conv1_stride,
bias=False)
self.add_module(self.norm1_name, norm1)
fallback_on_stride = False
self.with_modulated_dcn = False
if self.with_dcn:
fallback_on_stride = dcn.get('fallback_on_stride', False)
self.with_modulated_dcn = dcn.get('modulated', False)
if not self.with_dcn or fallback_on_stride:
self.conv2 = build_conv_layer(
conv_cfg,
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
bias=False)
else:
assert conv_cfg is None, 'conv_cfg must be None for DCN'
deformable_groups = dcn.get('deformable_groups', 1)
if not self.with_modulated_dcn:
conv_op = DeformConv
offset_channels = 18
else:
conv_op = ModulatedDeformConv
offset_channels = 27
self.conv2_offset = nn.Conv2d(
planes,
deformable_groups * offset_channels,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation)
self.conv2 = conv_op(
planes,
planes,
kernel_size=3,
stride=self.conv2_stride,
padding=dilation,
dilation=dilation,
deformable_groups=deformable_groups,
bias=False)
self.add_module(self.norm2_name, norm2)
self.conv3 = build_conv_layer(
conv_cfg,
planes,
planes * self.expansion,
kernel_size=1,
bias=False)
self.add_module(self.norm3_name, norm3)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.dilation = dilation
self.with_cp = with_cp
self.normalize = normalize
@property
def norm1(self):
return getattr(self, self.norm1_name)
@property
def norm2(self):
return getattr(self, self.norm2_name)
@property
def norm3(self):
return getattr(self, self.norm3_name)
def forward(self, x):
def _inner_forward(x):
identity = x
out = self.conv1(x)
out = self.norm1(out)
out = self.relu(out)
if not self.with_dcn:
out = self.conv2(out)
elif self.with_modulated_dcn:
offset_mask = self.conv2_offset(out)
offset = offset_mask[:, :18, :, :]
mask = offset_mask[:, -9:, :, :].sigmoid()
out = self.conv2(out, offset, mask)
else:
offset = self.conv2_offset(out)
out = self.conv2(out, offset)
out = self.norm2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.norm3(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
return out
if self.with_cp and x.requires_grad:
out = cp.checkpoint(_inner_forward, x)
else:
out = _inner_forward(x)
out = self.relu(out)
return out
def make_res_layer(block,
inplanes,
planes,
blocks,
stride=1,
dilation=1,
style='pytorch',
with_cp=False,
conv_cfg=None,
normalize=dict(type='BN'),
dcn=None):
downsample = None
if stride != 1 or inplanes != planes * block.expansion:
downsample = nn.Sequential(
build_conv_layer(
conv_cfg,
inplanes,
planes * block.expansion,
kernel_size=1,
stride=stride,
bias=False),
build_norm_layer(normalize, planes * block.expansion)[1],
)
layers = []
layers.append(
block(
inplanes,
planes,
stride,
dilation,
downsample,
style=style,
with_cp=with_cp,
conv_cfg=conv_cfg,
normalize=normalize,
dcn=dcn))
inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(
block(
inplanes,
planes,
1,
dilation,
style=style,
with_cp=with_cp,
conv_cfg=conv_cfg,
normalize=normalize,
dcn=dcn))
return nn.Sequential(*layers)
@BACKBONES.register_module
class ResNet(nn.Module):
"""ResNet backbone.
Args:
depth (int): Depth of resnet, from {18, 34, 50, 101, 152}.
num_stages (int): Resnet stages, normally 4.
strides (Sequence[int]): Strides of the first block of each stage.
dilations (Sequence[int]): Dilation of each stage.
out_indices (Sequence[int]): Output from which stages.
style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
layer is the 3x3 conv layer, otherwise the stride-two layer is
the first 1x1 conv layer.
frozen_stages (int): Stages to be frozen (all param fixed). -1 means
not freezing any parameters.
normalize (dict): dictionary to construct and config norm layer.
norm_eval (bool): Whether to set norm layers to eval mode, namely,
freeze running stats (mean and var). Note: Effect on Batch Norm
and its variants only.
with_cp (bool): Use checkpoint or not. Using checkpoint will save some
memory while slowing down the training speed.
zero_init_residual (bool): whether to use zero init for last norm layer
in resblocks to let them behave as identity.
"""
arch_settings = {
18: (BasicBlock, (2, 2, 2, 2)),
34: (BasicBlock, (3, 4, 6, 3)),
50: (Bottleneck, (3, 4, 6, 3)),
101: (Bottleneck, (3, 4, 23, 3)),
152: (Bottleneck, (3, 8, 36, 3))
}
def __init__(self,
depth,
num_stages=4,
strides=(1, 2, 2, 2),
dilations=(1, 1, 1, 1),
out_indices=(0, 1, 2, 3),
style='pytorch',
frozen_stages=-1,
conv_cfg=None,
normalize=dict(type='BN', frozen=False),
norm_eval=True,
dcn=None,
stage_with_dcn=(False, False, False, False),
with_cp=False,
zero_init_residual=True):
super(ResNet, self).__init__()
if depth not in self.arch_settings:
raise KeyError('invalid depth {} for resnet'.format(depth))
self.depth = depth
self.num_stages = num_stages
assert num_stages >= 1 and num_stages <= 4
self.strides = strides
self.dilations = dilations
assert len(strides) == len(dilations) == num_stages
self.out_indices = out_indices
assert max(out_indices) < num_stages
self.style = style
self.frozen_stages = frozen_stages
self.conv_cfg = conv_cfg
self.normalize = normalize
self.with_cp = with_cp
self.norm_eval = norm_eval
self.dcn = dcn
self.stage_with_dcn = stage_with_dcn
if dcn is not None:
assert len(stage_with_dcn) == num_stages
self.zero_init_residual = zero_init_residual
self.block, stage_blocks = self.arch_settings[depth]
self.stage_blocks = stage_blocks[:num_stages]
self.inplanes = 64
self._make_stem_layer()
self.res_layers = []
for i, num_blocks in enumerate(self.stage_blocks):
stride = strides[i]
dilation = dilations[i]
dcn = self.dcn if self.stage_with_dcn[i] else None
planes = 64 * 2**i
res_layer = make_res_layer(
self.block,
self.inplanes,
planes,
num_blocks,
stride=stride,
dilation=dilation,
style=self.style,
with_cp=with_cp,
conv_cfg=conv_cfg,
normalize=normalize,
dcn=dcn)
self.inplanes = planes * self.block.expansion
layer_name = 'layer{}'.format(i + 1)
self.add_module(layer_name, res_layer)
self.res_layers.append(layer_name)
self._freeze_stages()
self.feat_dim = self.block.expansion * 64 * 2**(
len(self.stage_blocks) - 1)
@property
def norm1(self):
return getattr(self, self.norm1_name)
def _make_stem_layer(self):
self.conv1 = build_conv_layer(
self.conv_cfg,
3,
64,
kernel_size=7,
stride=2,
padding=3,
bias=False)
self.norm1_name, norm1 = build_norm_layer(
self.normalize, 64, postfix=1)
self.add_module(self.norm1_name, norm1)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
def _freeze_stages(self):
if self.frozen_stages >= 0:
self.norm1.eval()
for m in [self.conv1, self.norm1]:
for param in m.parameters():
param.requires_grad = False
for i in range(1, self.frozen_stages + 1):
m = getattr(self, 'layer{}'.format(i))
m.eval()
for param in m.parameters():
param.requires_grad = False
def init_weights(self, pretrained=None):
if isinstance(pretrained, str):
logger = logging.getLogger()
load_checkpoint(self, pretrained, strict=False, logger=logger)
elif pretrained is None:
for m in self.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m)
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
constant_init(m, 1)
if self.dcn is not None:
for m in self.modules():
if isinstance(m, Bottleneck) and hasattr(
m, 'conv2_offset'):
constant_init(m.conv2_offset, 0)
if self.zero_init_residual:
for m in self.modules():
if isinstance(m, Bottleneck):
constant_init(m.norm3, 0)
elif isinstance(m, BasicBlock):
constant_init(m.norm2, 0)
else:
raise TypeError('pretrained must be a str or None')
def forward(self, x):
x = self.conv1(x)
x = self.norm1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = []
for i, layer_name in enumerate(self.res_layers):
res_layer = getattr(self, layer_name)
x = res_layer(x)
if i in self.out_indices:
outs.append(x)
return tuple(outs)
def train(self, mode=True):
super(ResNet, self).train(mode)
if mode and self.norm_eval:
for m in self.modules():
# trick: eval have effect on BatchNorm only
if isinstance(m, nn.BatchNorm2d):
m.eval()
| 1 | 17,245 | `padding` should be 0 instead. Actually you can just remove padding and dilation to use default values. | open-mmlab-mmdetection | py |
@@ -1447,7 +1447,7 @@ class Aleph extends AbstractBase implements \Laminas\Log\LoggerAwareInterface,
$checkout = $finesListSort[$key]["checkout"];
$transactiondate = $finesListSort[$key]["transactiondate"];
$transactiontype = $finesListSort[$key]["transactiontype"];
- $balance += $finesListSort[$key]["amount"];
+ $balance = $finesListSort[$key]["amount"];
$id = $finesListSort[$key]["id"];
$fine = $finesListSort[$key]["fine"];
$finesList[] = [ | 1 | <?php
/**
* Aleph ILS driver
*
* PHP version 7
*
* Copyright (C) UB/FU Berlin
*
* last update: 7.11.2007
* tested with X-Server Aleph 18.1.
*
* TODO: login, course information, getNewItems, duedate in holdings,
* https connection to x-server, ...
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package ILS_Drivers
* @author Christoph Krempe <vufind-tech@lists.sourceforge.net>
* @author Alan Rykhus <vufind-tech@lists.sourceforge.net>
* @author Jason L. Cooper <vufind-tech@lists.sourceforge.net>
* @author Kun Lin <vufind-tech@lists.sourceforge.net>
* @author Vaclav Rosecky <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
namespace VuFind\ILS\Driver;
use Laminas\I18n\Translator\TranslatorInterface;
use VuFind\Date\DateException;
use VuFind\Exception\ILS as ILSException;
/**
* Aleph Translator Class
*
* @category VuFind
* @package ILS_Drivers
* @author Vaclav Rosecky <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
class AlephTranslator
{
/**
* Character set
*
* @var string
*/
protected $charset;
/**
* Table 15 configuration
*
* @var array
*/
protected $table15;
/**
* Table 40 configuration
*
* @var array
*/
protected $table40;
/**
* Sub library configuration table
*
* @var array
*/
protected $table_sub_library;
/**
* Constructor
*
* @param array $configArray Aleph configuration
*/
public function __construct($configArray)
{
$this->charset = $configArray['util']['charset'];
$this->table15 = $this->parsetable(
$configArray['util']['tab15'],
get_class($this) . "::tab15Callback"
);
$this->table40 = $this->parsetable(
$configArray['util']['tab40'],
get_class($this) . "::tab40Callback"
);
$this->table_sub_library = $this->parsetable(
$configArray['util']['tab_sub_library'],
get_class($this) . "::tabSubLibraryCallback"
);
}
/**
* Parse a table
*
* @param string $file Input file
* @param string $callback Callback routine for parsing
*
* @return array
*/
public function parsetable($file, $callback)
{
$result = [];
$file_handle = fopen($file, "r, ccs=UTF-8");
$rgxp = "";
while (!feof($file_handle)) {
$line = fgets($file_handle);
$line = chop($line);
if (preg_match("/!!/", $line)) {
$line = chop($line);
$rgxp = AlephTranslator::regexp($line);
}
if (preg_match("/!.*/", $line) || $rgxp == "" || $line == "") {
} else {
$line = str_pad($line, 80);
$matches = "";
if (preg_match($rgxp, $line, $matches)) {
call_user_func_array(
$callback,
[$matches, &$result, $this->charset]
);
}
}
}
fclose($file_handle);
return $result;
}
/**
* Get a tab40 collection description
*
* @param string $collection Collection
* @param string $sublib Sub-library
*
* @return string
*/
public function tab40Translate($collection, $sublib)
{
$findme = $collection . "|" . $sublib;
$desc = $this->table40[$findme];
if ($desc == null) {
$findme = $collection . "|";
$desc = $this->table40[$findme];
}
return $desc;
}
/**
* Support method for tab15Translate -- translate a sub-library name
*
* @param string $sl Text to translate
*
* @return string
*/
public function tabSubLibraryTranslate($sl)
{
return $this->table_sub_library[$sl];
}
/**
* Get a tab15 item status
*
* @param string $slc Sub-library
* @param string $isc Item status code
* @param string $ipsc Item process status code
*
* @return string
*/
public function tab15Translate($slc, $isc, $ipsc)
{
$tab15 = $this->tabSubLibraryTranslate($slc);
if ($tab15 == null) {
echo "tab15 is null!<br>";
}
$findme = $tab15["tab15"] . "|" . $isc . "|" . $ipsc;
$result = $this->table15[$findme] ?? null;
if ($result == null) {
$findme = $tab15["tab15"] . "||" . $ipsc;
$result = $this->table15[$findme];
}
$result["sub_lib_desc"] = $tab15["desc"];
return $result;
}
/**
* Callback for tab15 (modify $tab15 by reference)
*
* @param array $matches preg_match() return array
* @param array $tab15 result array to generate
* @param string $charset character set
*
* @return void
*/
public static function tab15Callback($matches, &$tab15, $charset)
{
$lib = $matches[1];
$no1 = $matches[2];
if ($no1 == "##") {
$no1 = "";
}
$no2 = $matches[3];
if ($no2 == "##") {
$no2 = "";
}
$desc = iconv($charset, 'UTF-8', $matches[5]);
$key = trim($lib) . "|" . trim($no1) . "|" . trim($no2);
$tab15[trim($key)] = [
"desc" => trim($desc), "loan" => $matches[6], "request" => $matches[8],
"opac" => $matches[10]
];
}
/**
* Callback for tab40 (modify $tab40 by reference)
*
* @param array $matches preg_match() return array
* @param array $tab40 result array to generate
* @param string $charset character set
*
* @return void
*/
public static function tab40Callback($matches, &$tab40, $charset)
{
$code = trim($matches[1]);
$sub = trim($matches[2]);
$sub = trim(preg_replace("/#/", "", $sub));
$desc = trim(iconv($charset, 'UTF-8', $matches[4]));
$key = $code . "|" . $sub;
$tab40[trim($key)] = [ "desc" => $desc ];
}
/**
* Sub-library callback (modify $tab_sub_library by reference)
*
* @param array $matches preg_match() return array
* @param array $tab_sub_library result array to generate
* @param string $charset character set
*
* @return void
*/
public static function tabSubLibraryCallback(
$matches,
&$tab_sub_library,
$charset
) {
$sublib = trim($matches[1]);
$desc = trim(iconv($charset, 'UTF-8', $matches[5]));
$tab = trim($matches[6]);
$tab_sub_library[$sublib] = [ "desc" => $desc, "tab15" => $tab ];
}
/**
* Apply standard regular expression cleanup to a string.
*
* @param string $string String to clean up.
*
* @return string
*/
public static function regexp($string)
{
$string = preg_replace("/\\-/", ")\\s(", $string);
$string = preg_replace("/!/", ".", $string);
$string = preg_replace("/[<>]/", "", $string);
$string = "/(" . $string . ")/";
return $string;
}
}
/**
* ILS Exception
*
* @category VuFind
* @package Exceptions
* @author Vaclav Rosecky <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development Wiki
*/
class AlephRestfulException extends ILSException
{
/**
* XML response (false for none)
*
* @var string|bool
*/
protected $xmlResponse = false;
/**
* Attach an XML response to the exception
*
* @param string $body XML
*
* @return void
*/
public function setXmlResponse($body)
{
$this->xmlResponse = $body;
}
/**
* Return XML response (false if none)
*
* @return string|bool
*/
public function getXmlResponse()
{
return $this->xmlResponse;
}
}
/**
* Aleph ILS driver
*
* @category VuFind
* @package ILS_Drivers
* @author Christoph Krempe <vufind-tech@lists.sourceforge.net>
* @author Alan Rykhus <vufind-tech@lists.sourceforge.net>
* @author Jason L. Cooper <vufind-tech@lists.sourceforge.net>
* @author Kun Lin <vufind-tech@lists.sourceforge.net>
* @author Vaclav Rosecky <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki
*/
class Aleph extends AbstractBase implements \Laminas\Log\LoggerAwareInterface,
\VuFindHttp\HttpServiceAwareInterface
{
use \VuFind\Log\LoggerAwareTrait;
use \VuFindHttp\HttpServiceAwareTrait;
public const RECORD_ID_BASE_SEPARATOR = '-';
/**
* Translator object
*
* @var AlephTranslator
*/
protected $alephTranslator = false;
/**
* Cache manager
*
* @var \VuFind\Cache\Manager
*/
protected $cacheManager;
/**
* Translator
*
* @var TranslatorInterface
*/
protected $translator;
/**
* Date converter object
*
* @var \VuFind\Date\Converter
*/
protected $dateConverter = null;
/**
* The base URL, where the REST DLF API is running
*
* @var string
*/
protected $dlfbaseurl = null;
/**
* Aleph server
*
* @var string
*/
protected $host;
/**
* Bibliographic bases
*
* @var array
*/
protected $bib;
/**
* User library
*
* @var string
*/
protected $useradm;
/**
* Item library
*
* @var string
*/
protected $admlib;
/**
* X server user name
*
* @var string
*/
protected $wwwuser;
/**
* X server user password
*
* @var string
*/
protected $wwwpasswd;
/**
* Is X server enabled?
*
* @var bool
*/
protected $xserver_enabled;
/**
* X server port (defaults to 80)
*
* @var int
*/
protected $xport;
/**
* DLF REST API port
*
* @var int
*/
protected $dlfport;
/**
* Statuse considered as available
*
* @var array
*/
protected $available_statuses;
/**
* List of patron hoe libraries
*
* @var array
*/
protected $sublibadm;
/**
* If enabled and Xserver is disabled, slower RESTful API is used for
* availability check.
*
* @var bool
*/
protected $quick_availability;
/**
* Is debug mode enabled?
*
* @var bool
*/
protected $debug_enabled;
/**
* Preferred pickup locations
*
* @var array
*/
protected $preferredPickUpLocations;
/**
* Patron id used when no specific patron defined
*
* @var string
*/
protected $defaultPatronId;
/**
* Mapping of z304 address elements in Aleph to getMyProfile attributes
*
* @var array
*/
protected $addressMappings = null;
/**
* ISO 3166-1 alpha-2 to ISO 3166-1 alpha-3 mapping for
* translation in REST DLF API.
*
* @var array
*/
protected $languages = [];
/**
* Regex for extracting position in queue from status in holdings.
*
* @var string
*/
protected $queuePositionRegex = "/Waiting in position "
. "(?<position>[0-9]+) in queue;/";
/**
* Constructor
*
* @param \VuFind\Date\Converter $dateConverter Date converter
* @param \VuFind\Cache\Manager $cacheManager Cache manager (optional)
* @param TranslatorInterface $translator Translator (optional)
*/
public function __construct(
\VuFind\Date\Converter $dateConverter,
\VuFind\Cache\Manager $cacheManager = null,
TranslatorInterface $translator = null
) {
$this->dateConverter = $dateConverter;
$this->cacheManager = $cacheManager;
$this->translator = $translator;
}
/**
* Initialize the driver.
*
* Validate configuration and perform all resource-intensive tasks needed to
* make the driver active.
*
* @throws ILSException
* @return void
*/
public function init()
{
// Validate config
$required = [
'host', 'bib', 'useradm', 'admlib', 'dlfport', 'available_statuses'
];
foreach ($required as $current) {
if (!isset($this->config['Catalog'][$current])) {
throw new ILSException("Missing Catalog/{$current} config setting.");
}
}
if (!isset($this->config['sublibadm'])) {
throw new ILSException('Missing sublibadm config setting.');
}
// Process config
$this->host = $this->config['Catalog']['host'];
$this->bib = explode(',', $this->config['Catalog']['bib']);
$this->useradm = $this->config['Catalog']['useradm'];
$this->admlib = $this->config['Catalog']['admlib'];
if (isset($this->config['Catalog']['wwwuser'])
&& isset($this->config['Catalog']['wwwpasswd'])
) {
$this->wwwuser = $this->config['Catalog']['wwwuser'];
$this->wwwpasswd = $this->config['Catalog']['wwwpasswd'];
$this->xserver_enabled = true;
$this->xport = $this->config['Catalog']['xport'] ?? 80;
} else {
$this->xserver_enabled = false;
}
$this->dlfport = $this->config['Catalog']['dlfport'];
if (isset($this->config['Catalog']['dlfbaseurl'])) {
$this->dlfbaseurl = $this->config['Catalog']['dlfbaseurl'];
}
$this->sublibadm = $this->config['sublibadm'];
$this->available_statuses
= explode(',', $this->config['Catalog']['available_statuses']);
$this->quick_availability
= $this->config['Catalog']['quick_availability'] ?? false;
$this->debug_enabled = $this->config['Catalog']['debug'] ?? false;
if (isset($this->config['util']['tab40'])
&& isset($this->config['util']['tab15'])
&& isset($this->config['util']['tab_sub_library'])
) {
$cache = null;
if (isset($this->config['Cache']['type'])
&& null !== $this->cacheManager
) {
$cache = $this->cacheManager
->getCache($this->config['Cache']['type']);
$this->alephTranslator = $cache->getItem('alephTranslator');
}
if ($this->alephTranslator == false) {
$this->alephTranslator = new AlephTranslator($this->config);
if (isset($cache)) {
$cache->setItem('alephTranslator', $this->alephTranslator);
}
}
}
if (isset($this->config['Catalog']['preferred_pick_up_locations'])) {
$this->preferredPickUpLocations = explode(
',',
$this->config['Catalog']['preferred_pick_up_locations']
);
}
if (isset($this->config['Catalog']['default_patron_id'])) {
$this->defaultPatronId = $this->config['Catalog']['default_patron_id'];
}
$this->addressMappings = $this->getDefaultAddressMappings();
if (isset($this->config['AddressMappings'])) {
foreach ($this->config['AddressMappings'] as $key => $val) {
$this->addressMappings[$key] = $val;
}
}
if (isset($this->config['Catalog']['queue_position_regex'])) {
$this->queuePositionRegex
= $this->config['Catalog']['queue_position_regex'];
}
if (isset($this->config['Languages'])) {
foreach ($this->config['Languages'] as $locale => $lang) {
$this->languages[$locale] = $lang;
}
}
}
/**
* Return default mapping of z304 address elements in Aleph
* to getMyProfile attributes.
*
* @return array
*/
protected function getDefaultAddressMappings()
{
return [
'fullname' => 'z304-address-1',
'address1' => 'z304-address-2',
'address2' => 'z304-address-3',
'city' => 'z304-address-4',
'zip' => 'z304-zip',
'email' => 'z304-email-address',
'phone' => 'z304-telephone-1',
];
}
/**
* Perform an XServer request.
*
* @param string $op Operation
* @param array $params Parameters
* @param bool $auth Include authentication?
*
* @return SimpleXMLElement
*/
protected function doXRequest($op, $params, $auth = false)
{
if (!$this->xserver_enabled) {
throw new \Exception(
'Call to doXRequest without X-Server configuration in Aleph.ini'
);
}
$url = "http://$this->host:$this->xport/X?op=$op";
$url = $this->appendQueryString($url, $params);
if ($auth) {
$url = $this->appendQueryString(
$url,
[
'user_name' => $this->wwwuser,
'user_password' => $this->wwwpasswd
]
);
}
$result = $this->doHTTPRequest($url);
if ($result->error) {
if ($this->debug_enabled) {
$this->debug(
"XServer error, URL is $url, error message: $result->error."
);
}
throw new ILSException("XServer error: $result->error.");
}
return $result;
}
/**
* Perform a RESTful DLF request.
*
* @param array $path_elements URL path elements
* @param array $params GET parameters (null for none)
* @param string $method HTTP method
* @param string $body HTTP body
*
* @return SimpleXMLElement
*/
protected function doRestDLFRequest(
$path_elements,
$params = null,
$method = 'GET',
$body = null
) {
$path = implode('/', $path_elements);
if ($this->dlfbaseurl === null) {
$url = "http://$this->host:$this->dlfport/rest-dlf/" . $path;
} else {
$url = $this->dlfbaseurl . $path;
}
if ($params == null) {
$params = [];
}
if (!empty($this->languages) && $this->translator != null) {
$locale = $this->translator->getLocale();
if (isset($this->languages[$locale])) {
$params['lang'] = $this->languages[$locale];
}
}
$url = $this->appendQueryString($url, $params);
$result = $this->doHTTPRequest($url, $method, $body);
$replyCode = (string)$result->{'reply-code'};
if ($replyCode != "0000") {
$replyText = (string)$result->{'reply-text'};
$this->logError(
"DLF request failed",
[
'url' => $url, 'reply-code' => $replyCode,
'reply-message' => $replyText
]
);
$ex = new AlephRestfulException($replyText, $replyCode);
$ex->setXmlResponse($result);
throw $ex;
}
return $result;
}
/**
* Add values to an HTTP query string.
*
* @param string $url URL so far
* @param array $params Parameters to add
*
* @return string
*/
protected function appendQueryString($url, $params)
{
$sep = (strpos($url, "?") === false) ? '?' : '&';
if ($params != null) {
foreach ($params as $key => $value) {
$url .= $sep . $key . "=" . urlencode($value);
$sep = "&";
}
}
return $url;
}
/**
* Perform an HTTP request.
*
* @param string $url URL of request
* @param string $method HTTP method
* @param string $body HTTP body (null for none)
*
* @return SimpleXMLElement
*/
protected function doHTTPRequest($url, $method = 'GET', $body = null)
{
if ($this->debug_enabled) {
$this->debug("URL: '$url'");
}
$result = null;
try {
$client = $this->httpService->createClient($url);
$client->setMethod($method);
if ($body != null) {
$client->setRawBody($body);
}
$result = $client->send();
} catch (\Exception $e) {
$this->throwAsIlsException($e);
}
if (!$result->isSuccess()) {
throw new ILSException('HTTP error');
}
$answer = $result->getBody();
if ($this->debug_enabled) {
$this->debug("url: $url response: $answer");
}
$answer = str_replace('xmlns=', 'ns=', $answer);
$result = @simplexml_load_string($answer);
if (!$result) {
if ($this->debug_enabled) {
$this->debug("XML is not valid, URL: $url");
}
throw new ILSException(
"XML is not valid, URL: $url method: $method answer: $answer."
);
}
return $result;
}
/**
* Convert an ID string into an array of bibliographic base and ID within
* the base.
*
* @param string $id ID to parse.
*
* @return array
*/
protected function parseId($id)
{
$result = null;
if (strpos($id, self::RECORD_ID_BASE_SEPARATOR) !== false) {
$result = explode(self::RECORD_ID_BASE_SEPARATOR, $id);
$base = $result[0];
if (!in_array($base, $this->bib)) {
throw new \Exception("Unknown library base '$base'");
}
} elseif (count($this->bib) == 1) {
$result = [$this->bib[0], $id];
} else {
throw new \Exception(
"Invalid record identifier '$id' "
. "without library base"
);
}
return $result;
}
/**
* Get Status
*
* This is responsible for retrieving the status information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
*
* @throws ILSException
* @return mixed On success, an associative array with the following keys:
* id, availability (boolean), status, location, reserve, callnumber.
*/
public function getStatus($id)
{
$statuses = $this->getHolding($id);
foreach ($statuses as &$status) {
$status['status']
= ($status['availability'] == 1) ? 'available' : 'unavailable';
}
return $statuses;
}
/**
* Support method for getStatuses -- load ID information from a particular
* bibliographic library.
*
* @param string $bib Library to search
* @param array $ids IDs to search within library
*
* @return array
*
* Description of AVA tag:
* http://igelu.org/wp-content/uploads/2011/09/Staff-vs-Public-Data-views.pdf
* (page 28)
*
* a ADM code - Institution Code
* b Sublibrary code - Library Code
* c Collection (first found) - Collection Code
* d Call number (first found)
* e Availability status - If it is on loan (it has a Z36), if it is on hold
* shelf (it has Z37=S) or if it has a processing status.
* f Number of items (for entire sublibrary)
* g Number of unavailable loans
* h Multi-volume flag (Y/N) If first Z30-ENUMERATION-A is not blank or 0, then
* the flag=Y, otherwise the flag=N.
* i Number of loans (for ranking/sorting)
* j Collection code
*/
public function getStatusesX($bib, $ids)
{
$doc_nums = "";
$sep = "";
foreach ($ids as $id) {
$doc_nums .= $sep . $id;
$sep = ",";
}
$xml = $this->doXRequest(
"publish_avail",
['library' => $bib, 'doc_num' => $doc_nums],
false
);
$holding = [];
foreach ($xml->xpath('/publish-avail/OAI-PMH') as $rec) {
$identifier = $rec->xpath(".//identifier/text()");
$id = ((count($this->bib) > 1) ? $bib . "-" : "")
. substr($identifier[0], strrpos($identifier[0], ':') + 1);
$temp = [];
foreach ($rec->xpath(".//datafield[@tag='AVA']") as $datafield) {
$status = $datafield->xpath('./subfield[@code="e"]/text()');
$location = $datafield->xpath('./subfield[@code="a"]/text()');
$signature = $datafield->xpath('./subfield[@code="d"]/text()');
$availability
= ($status[0] == 'available' || $status[0] == 'check_holdings');
$reserve = true;
$temp[] = [
'id' => $id,
'availability' => $availability,
'status' => (string)$status[0],
'location' => (string)$location[0],
'signature' => (string)$signature[0],
'reserve' => $reserve,
'callnumber' => (string)$signature[0]
];
}
$holding[] = $temp;
}
return $holding;
}
/**
* Get Statuses
*
* This is responsible for retrieving the status information for a
* collection of records.
*
* @param array $idList The array of record ids to retrieve the status for
*
* @throws ILSException
* @return array An array of getStatus() return values on success.
*/
public function getStatuses($idList)
{
if (!$this->xserver_enabled) {
if (!$this->quick_availability) {
return [];
}
$result = [];
foreach ($idList as $id) {
$items = $this->getStatus($id);
$result[] = $items;
}
return $result;
}
$ids = [];
$holdings = [];
foreach ($idList as $id) {
[$bib, $sys_no] = $this->parseId($id);
$ids[$bib][] = $sys_no;
}
foreach ($ids as $key => $values) {
$holds = $this->getStatusesX($key, $values);
foreach ($holds as $hold) {
$holdings[] = $hold;
}
}
return $holdings;
}
/**
* Get Holding
*
* This is responsible for retrieving the holding information of a certain
* record.
*
* @param string $id The record id to retrieve the holdings for
* @param array $patron Patron data
* @param array $options Extra options (not currently used)
*
* @throws DateException
* @throws ILSException
* @return array On success, an associative array with the following
* keys: id, availability (boolean), status, location, reserve, callnumber,
* duedate, number, barcode.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getHolding($id, array $patron = null, array $options = [])
{
$holding = [];
[$bib, $sys_no] = $this->parseId($id);
$resource = $bib . $sys_no;
$params = ['view' => 'full'];
if (!empty($patron['id'])) {
$params['patron'] = $patron['id'];
} elseif (isset($this->defaultPatronId)) {
$params['patron'] = $this->defaultPatronId;
}
$xml = $this->doRestDLFRequest(['record', $resource, 'items'], $params);
if (!empty($xml->{'items'})) {
$items = $xml->{'items'}->{'item'};
} else {
$items = [];
}
foreach ($items as $item) {
$item_status = (string)$item->{'z30-item-status-code'}; // $isc
// $ipsc:
$item_process_status = (string)$item->{'z30-item-process-status-code'};
$sub_library_code = (string)$item->{'z30-sub-library-code'}; // $slc
$z30 = $item->z30;
if ($this->alephTranslator) {
$item_status = $this->alephTranslator->tab15Translate(
$sub_library_code,
$item_status,
$item_process_status
);
} else {
$item_status = [
'opac' => 'Y',
'request' => 'C',
'desc' => (string)$z30->{'z30-item-status'},
'sub_lib_desc' => (string)$z30->{'z30-sub-library'}
];
}
if ($item_status['opac'] != 'Y') {
continue;
}
$availability = false;
//$reserve = ($item_status['request'] == 'C')?'N':'Y';
$collection = (string)$z30->{'z30-collection'};
$collection_desc = ['desc' => $collection];
if ($this->alephTranslator) {
$collection_code = (string)$item->{'z30-collection-code'};
$collection_desc = $this->alephTranslator->tab40Translate(
$collection_code,
$sub_library_code
);
}
$requested = false;
$duedate = '';
$addLink = false;
$status = (string)$item->{'status'};
if (in_array($status, $this->available_statuses)) {
$availability = true;
}
if ($item_status['request'] == 'Y' && $availability == false) {
$addLink = true;
}
if (!empty($patron)) {
$hold_request = $item->xpath('info[@type="HoldRequest"]/@allowed');
$addLink = ($hold_request[0] == 'Y');
}
$matches = [];
$dueDateWithStatusRegEx
= "/([0-9]*\\/[a-zA-Z0-9]*\\/[0-9]*);([a-zA-Z ]*)/";
$dueDateRegEx = "/([0-9]*\\/[a-zA-Z0-9]*\\/[0-9]*)/";
if (preg_match($dueDateWithStatusRegEx, $status, $matches)) {
$duedate = $this->parseDate($matches[1]);
$requested = (trim($matches[2]) == "Requested");
} elseif (preg_match($dueDateRegEx, $status, $matches)) {
$duedate = $this->parseDate($matches[1]);
} else {
$duedate = null;
}
$item_id = $item->attributes()->href;
$item_id = substr($item_id, strrpos($item_id, '/') + 1);
$note = (string)$z30->{'z30-note-opac'};
$holding[] = [
'id' => $id,
'item_id' => $item_id,
'availability' => $availability,
'status' => (string)$item_status['desc'],
'location' => $sub_library_code,
'reserve' => 'N',
'callnumber' => (string)$z30->{'z30-call-no'},
'duedate' => (string)$duedate,
'number' => (string)$z30->{'z30-inventory-number'},
'barcode' => (string)$z30->{'z30-barcode'},
'description' => (string)$z30->{'z30-description'},
'notes' => ($note == null) ? null : [$note],
'is_holdable' => true,
'addLink' => $addLink,
'holdtype' => 'hold',
/* below are optional attributes*/
'collection' => (string)$collection,
'collection_desc' => (string)$collection_desc['desc'],
'callnumber_second' => (string)$z30->{'z30-call-no-2'},
'sub_lib_desc' => (string)$item_status['sub_lib_desc'],
'no_of_loans' => (string)$z30->{'$no_of_loans'},
'requested' => (string)$requested
];
}
return $holding;
}
/**
* Get Patron Loan History
*
* @param array $user The patron array from patronLogin
* @param array $params Parameters
*
* @throws DateException
* @throws ILSException
* @return array Array of the patron's historic loans on success.
*/
public function getMyTransactionHistory($user, $params = null)
{
return $this->getMyTransactions($user, $params, true);
}
/**
* Get Patron Transactions
*
* This is responsible for retrieving all transactions (i.e. checked out items)
* by a specific patron.
*
* @param array $user The patron array from patronLogin
* @param array $params Parameters
* @param boolean $history History
*
* @throws DateException
* @throws ILSException
* @return array Array of the patron's transactions on success.
*/
public function getMyTransactions($user, $params = [], $history = false)
{
$userId = $user['id'];
$alephParams = [];
if ($history) {
$alephParams['type'] = 'history';
}
// total count without details is fast
$totalCount = count(
$this->doRestDLFRequest(
['patron', $userId, 'circulationActions', 'loans'],
$alephParams
)->xpath('//loan')
);
// with full details and paging
$pageSize = $params['limit'] ?? 50;
$itemsNoKey = $history ? 'no_loans' : 'noItems';
$alephParams += [
'view' => 'full',
'startPos' => isset($params['page'])
? ($params['page'] - 1) * $pageSize : 0,
$itemsNoKey => $pageSize,
];
$xml = $this->doRestDLFRequest(
['patron', $userId, 'circulationActions', 'loans'],
$alephParams
);
$transList = [];
foreach ($xml->xpath('//loan') as $item) {
$z36 = ($history) ? $item->z36h : $item->z36;
$prefix = ($history) ? 'z36h-' : 'z36-';
$z13 = $item->z13;
$z30 = $item->z30;
$group = $item->xpath('@href');
$group = substr(strrchr($group[0], "/"), 1);
$renew = $item->xpath('@renew');
$location = (string)$z36->{$prefix . 'pickup_location'};
$reqnum = (string)$z36->{$prefix . 'doc-number'}
. (string)$z36->{$prefix . 'item-sequence'}
. (string)$z36->{$prefix . 'sequence'};
$due = (string)$z36->{$prefix . 'due-date'};
$title = (string)$z13->{'z13-title'};
$author = (string)$z13->{'z13-author'};
$isbn = (string)$z13->{'z13-isbn-issn'};
$barcode = (string)$z30->{'z30-barcode'};
// Secondary, Aleph-specific identifier that may be useful for
// local customizations
$adm_id = (string)$z30->{'z30-doc-number'};
$transaction = [
'id' => $this->barcodeToID($barcode),
'adm_id' => $adm_id,
'item_id' => $group,
'location' => $location,
'title' => $title,
'author' => $author,
'isbn' => $isbn,
'reqnum' => $reqnum,
'barcode' => $barcode,
'duedate' => $this->parseDate($due),
'renewable' => $renew[0] == "Y",
];
if ($history) {
$issued = (string)$z36->{$prefix . 'loan-date'};
$returned = (string)$z36->{$prefix . 'returned-date'};
$transaction['checkoutDate'] = $this->parseDate($issued);
$transaction['returnDate'] = $this->parseDate($returned);
}
$transList[] = $transaction;
}
$key = ($history) ? 'transactions' : 'records';
return [
'count' => $totalCount,
$key => $transList
];
}
/**
* Get Renew Details
*
* In order to renew an item, Voyager requires the patron details and an item
* id. This function returns the item id as a string which is then used
* as submitted form data in checkedOut.php. This value is then extracted by
* the RenewMyItems function.
*
* @param array $details An array of item data
*
* @return string Data for use in a form field
*/
public function getRenewDetails($details)
{
return $details['item_id'];
}
/**
* Renew My Items
*
* Function for attempting to renew a patron's items. The data in
* $details['details'] is determined by getRenewDetails().
*
* @param array $details An array of data required for renewing items
* including the Patron ID and an array of renewal IDS
*
* @return array An array of renewal information keyed by item ID
*/
public function renewMyItems($details)
{
$patron = $details['patron'];
$result = [];
foreach ($details['details'] as $id) {
try {
$xml = $this->doRestDLFRequest(
[
'patron', $patron['id'], 'circulationActions', 'loans', $id
],
null,
'POST',
null
);
$due = (string)current($xml->xpath('//new-due-date'));
$result[$id] = [
'success' => true, 'new_date' => $this->parseDate($due)
];
} catch (AlephRestfulException $ex) {
$result[$id] = [
'success' => false, 'sysMessage' => $ex->getMessage()
];
}
}
return ['blocks' => false, 'details' => $result];
}
/**
* Get Patron Holds
*
* This is responsible for retrieving all holds by a specific patron.
*
* @param array $user The patron array from patronLogin
*
* @throws DateException
* @throws ILSException
* @return array Array of the patron's holds on success.
*/
public function getMyHolds($user)
{
$userId = $user['id'];
$holdList = [];
$xml = $this->doRestDLFRequest(
['patron', $userId, 'circulationActions', 'requests', 'holds'],
['view' => 'full']
);
foreach ($xml->xpath('//hold-request') as $item) {
$z37 = $item->z37;
$z13 = $item->z13;
$z30 = $item->z30;
$delete = $item->xpath('@delete');
$href = $item->xpath('@href');
$item_id = substr($href[0], strrpos($href[0], '/') + 1);
$type = "hold";
$location = (string)$z37->{'z37-pickup-location'};
$reqnum = (string)$z37->{'z37-doc-number'}
. (string)$z37->{'z37-item-sequence'}
. (string)$z37->{'z37-sequence'};
$expire = (string)$z37->{'z37-end-request-date'};
$create = (string)$z37->{'z37-open-date'};
$holddate = (string)$z37->{'z37-hold-date'};
$title = (string)$z13->{'z13-title'};
$author = (string)$z13->{'z13-author'};
$isbn = (string)$z13->{'z13-isbn-issn'};
$barcode = (string)$z30->{'z30-barcode'};
// remove superfluous spaces in status
$status = preg_replace("/\s[\s]+/", " ", $item->status);
$position = null;
// Extract position in the hold queue from item status
if (preg_match($this->queuePositionRegex, $status, $matches)) {
$position = $matches['position'];
}
if ($holddate == "00000000") {
$holddate = null;
} else {
$holddate = $this->parseDate($holddate);
}
$delete = ($delete[0] == "Y");
// Secondary, Aleph-specific identifier that may be useful for
// local customizations
$adm_id = (string)$z30->{'z30-doc-number'};
$holdList[] = [
'type' => $type,
'item_id' => $item_id,
'adm_id' => $adm_id,
'location' => $location,
'title' => $title,
'author' => $author,
'isbn' => $isbn,
'reqnum' => $reqnum,
'barcode' => $barcode,
'id' => $this->barcodeToID($barcode),
'expire' => $this->parseDate($expire),
'holddate' => $holddate,
'delete' => $delete,
'create' => $this->parseDate($create),
'status' => $status,
'position' => $position,
];
}
return $holdList;
}
/**
* Get Cancel Hold Details
*
* @param array $holdDetails A single hold array from getMyHolds
* @param array $patron Patron information from patronLogin
*
* @return string Data for use in a form field
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getCancelHoldDetails($holdDetails, $patron = [])
{
if ($holdDetails['delete']) {
return $holdDetails['item_id'];
} else {
return null;
}
}
/**
* Cancel Holds
*
* Attempts to Cancel a hold or recall on a particular item. The
* data in $cancelDetails['details'] is determined by getCancelHoldDetails().
*
* @param array $details An array of item and patron data
*
* @return array An array of data on each request including
* whether or not it was successful and a system message (if available)
*/
public function cancelHolds($details)
{
$patron = $details['patron'];
$patronId = $patron['id'];
$count = 0;
$statuses = [];
foreach ($details['details'] as $id) {
try {
$result = $this->doRestDLFRequest(
[
'patron', $patronId, 'circulationActions', 'requests',
'holds', $id
],
null,
"DELETE"
);
} catch (AlephRestfulException $e) {
$statuses[$id] = [
'success' => false, 'status' => 'cancel_hold_failed',
'sysMessage' => $e->getMessage(),
];
}
if (isset($result)) {
$count++;
$statuses[$id]
= ['success' => true, 'status' => 'cancel_hold_ok'];
}
}
$statuses['count'] = $count;
return $statuses;
}
/**
* Get Patron Fines
*
* This is responsible for retrieving all fines by a specific patron.
*
* @param array $user The patron array from patronLogin
*
* @throws DateException
* @throws ILSException
* @return mixed Array of the patron's fines on success.
*/
public function getMyFines($user)
{
$finesList = [];
$finesListSort = [];
$xml = $this->doRestDLFRequest(
['patron', $user['id'], 'circulationActions', 'cash'],
["view" => "full"]
);
foreach ($xml->xpath('//cash') as $item) {
$z31 = $item->z31;
$z13 = $item->z13;
$z30 = $item->z30;
//$delete = $item->xpath('@delete');
$title = (string)$z13->{'z13-title'};
$description = (string)$z31->{'z31-description'};
$transactiondate = date('d-m-Y', strtotime((string)$z31->{'z31-date'}));
$transactiontype = (string)$z31->{'z31-credit-debit'};
$id = (string)$z13->{'z13-doc-number'};
$barcode = (string)$z30->{'z30-barcode'};
$checkout = (string)$z31->{'z31-date'};
$id = $this->barcodeToID($barcode);
$mult = ($transactiontype == "Credit") ? 100 : -100;
$amount
= (float)(preg_replace("/[\(\)]/", "", (string)$z31->{'z31-sum'}))
* $mult;
$cashref = (string)$z31->{'z31-sequence'};
//$cashdate = date('d-m-Y', strtotime((string) $z31->{'z31-date'}));
$balance = 0;
$finesListSort["$cashref"] = [
"title" => $title,
"barcode" => $barcode,
"amount" => $amount,
"transactiondate" => $transactiondate,
"transactiontype" => $transactiontype,
"checkout" => $this->parseDate($checkout),
"balance" => $balance,
"id" => $id,
"fine" => $description,
];
}
ksort($finesListSort);
foreach (array_keys($finesListSort) as $key) {
$title = $finesListSort[$key]["title"];
$barcode = $finesListSort[$key]["barcode"];
$amount = $finesListSort[$key]["amount"];
$checkout = $finesListSort[$key]["checkout"];
$transactiondate = $finesListSort[$key]["transactiondate"];
$transactiontype = $finesListSort[$key]["transactiontype"];
$balance += $finesListSort[$key]["amount"];
$id = $finesListSort[$key]["id"];
$fine = $finesListSort[$key]["fine"];
$finesList[] = [
"title" => $title,
"barcode" => $barcode,
"amount" => $amount,
"transactiondate" => $transactiondate,
"transactiontype" => $transactiontype,
"balance" => $balance,
"checkout" => $checkout,
"id" => $id,
"printLink" => "test",
"fine" => $fine,
];
}
return $finesList;
}
/**
* Get Patron Profile
*
* This is responsible for retrieving the profile for a specific patron.
*
* @param array $user The patron array
*
* @throws ILSException
* @return array Array of the patron's profile data on success.
*/
public function getMyProfile($user)
{
if ($this->xserver_enabled) {
$profile = $this->getMyProfileX($user);
} else {
$profile = $this->getMyProfileDLF($user);
}
$profile['cat_username'] = $profile['cat_username'] ?? $user['id'];
return $profile;
}
/**
* Get profile information using X-server.
*
* @param array $user The patron array
*
* @throws ILSException
* @return array Array of the patron's profile data on success.
*/
public function getMyProfileX($user)
{
if (!isset($user['college'])) {
$user['college'] = $this->useradm;
}
$xml = $this->doXRequest(
"bor-info",
[
'loans' => 'N', 'cash' => 'N', 'hold' => 'N',
'library' => $user['college'], 'bor_id' => $user['id']
],
true
);
$id = (string)$xml->z303->{'z303-id'};
$address1 = (string)$xml->z304->{'z304-address-2'};
$address2 = (string)$xml->z304->{'z304-address-3'};
$zip = (string)$xml->z304->{'z304-zip'};
$phone = (string)$xml->z304->{'z304-telephone'};
$barcode = (string)$xml->z304->{'z304-address-0'};
$group = (string)$xml->z305->{'z305-bor-status'};
$expiry = (string)$xml->z305->{'z305-expiry-date'};
$credit_sum = (string)$xml->z305->{'z305-sum'};
$credit_sign = (string)$xml->z305->{'z305-credit-debit'};
$name = (string)$xml->z303->{'z303-name'};
if (strstr($name, ",")) {
[$lastname, $firstname] = explode(",", $name);
} else {
$lastname = $name;
$firstname = "";
}
if ($credit_sign == null) {
$credit_sign = "C";
}
$recordList = compact('firstname', 'lastname');
if (isset($user['email'])) {
$recordList['email'] = $user['email'];
}
$recordList['address1'] = $address1;
$recordList['address2'] = $address2;
$recordList['zip'] = $zip;
$recordList['phone'] = $phone;
$recordList['group'] = $group;
$recordList['barcode'] = $barcode;
$recordList['expire'] = $this->parseDate($expiry);
$recordList['credit'] = $expiry;
$recordList['credit_sum'] = $credit_sum;
$recordList['credit_sign'] = $credit_sign;
$recordList['id'] = $id;
return $recordList;
}
/**
* Get profile information using DLF service.
*
* @param array $user The patron array
*
* @throws ILSException
* @return array Array of the patron's profile data on success.
*/
public function getMyProfileDLF($user)
{
$recordList = [];
$xml = $this->doRestDLFRequest(
['patron', $user['id'], 'patronInformation', 'address']
);
$profile = [];
$profile['id'] = $user['id'];
$profile['cat_username'] = $user['id'];
$address = $xml->xpath('//address-information')[0];
foreach ($this->addressMappings as $key => $value) {
if (!empty($value)) {
$profile[$key] = (string)$address->{$value};
}
}
$fullName = $profile['fullname'];
if (strpos($fullName, ",") === false) {
$profile['lastname'] = $fullName;
$profile['firstname'] = "";
} else {
[$profile['lastname'], $profile['firstname']]
= explode(",", $fullName);
}
$xml = $this->doRestDLFRequest(
['patron', $user['id'], 'patronStatus', 'registration']
);
$status = $xml->xpath("//institution/z305-bor-status");
$expiry = $xml->xpath("//institution/z305-expiry-date");
$profile['expiration_date'] = $this->parseDate($expiry[0]);
$profile['group'] = $status[0];
return $profile;
}
/**
* Patron Login
*
* This is responsible for authenticating a patron against the catalog.
*
* @param string $user The patron username
* @param string $password The patron's password
*
* @throws ILSException
* @return mixed Associative array of patron info on successful login,
* null on unsuccessful login.
*/
public function patronLogin($user, $password)
{
if ($password == null) {
$temp = ["id" => $user];
$temp['college'] = $this->useradm;
return $this->getMyProfile($temp);
}
try {
$xml = $this->doXRequest(
'bor-auth',
[
'library' => $this->useradm, 'bor_id' => $user,
'verification' => $password
],
true
);
} catch (\Exception $ex) {
if (strpos($ex->getMessage(), 'Error in Verification') !== false) {
return null;
}
$this->throwAsIlsException($ex);
}
$patron = [];
$name = $xml->z303->{'z303-name'};
if (strstr($name, ",")) {
[$lastName, $firstName] = explode(",", $name);
} else {
$lastName = $name;
$firstName = "";
}
$email_addr = $xml->z304->{'z304-email-address'};
$id = $xml->z303->{'z303-id'};
$home_lib = $xml->z303->z303_home_library;
// Default the college to the useradm library and overwrite it if the
// home_lib exists
$patron['college'] = $this->useradm;
if (($home_lib != '') && (array_key_exists("$home_lib", $this->sublibadm))) {
if ($this->sublibadm["$home_lib"] != '') {
$patron['college'] = $this->sublibadm["$home_lib"];
}
}
$patron['id'] = (string)$id;
$patron['barcode'] = (string)$user;
$patron['firstname'] = (string)$firstName;
$patron['lastname'] = (string)$lastName;
$patron['cat_username'] = (string)$user;
$patron['cat_password'] = $password;
$patron['email'] = (string)$email_addr;
$patron['major'] = null;
return $patron;
}
/**
* Support method for placeHold -- get holding info for an item.
*
* @param string $patronId Patron ID
* @param string $id Bib ID
* @param string $group Item ID
*
* @return array
*/
public function getHoldingInfoForItem($patronId, $id, $group)
{
[$bib, $sys_no] = $this->parseId($id);
$resource = $bib . $sys_no;
$xml = $this->doRestDLFRequest(
['patron', $patronId, 'record', $resource, 'items', $group]
);
$locations = [];
$part = $xml->xpath('//pickup-locations');
if ($part) {
foreach ($part[0]->children() as $node) {
$arr = $node->attributes();
$code = (string)$arr['code'];
$loc_name = (string)$node;
$locations[$code] = $loc_name;
}
} else {
throw new ILSException('No pickup locations');
}
$requests = 0;
$str = $xml->xpath('//item/queue/text()');
if ($str != null) {
[$requests] = explode(' ', trim($str[0]));
}
$date = $xml->xpath('//last-interest-date/text()');
$date = $date[0];
$date = "" . substr($date, 6, 2) . "." . substr($date, 4, 2) . "."
. substr($date, 0, 4);
return [
'pickup-locations' => $locations, 'last-interest-date' => $date,
'order' => $requests + 1
];
}
/**
* Get Default "Hold Required By" Date (as Unix timestamp) or null if unsupported
*
* @param array $patron Patron information returned by the patronLogin method.
* @param array $holdInfo Contains most of the same values passed to
* placeHold, minus the patron data.
*
* @return int
*/
public function getHoldDefaultRequiredDate($patron, $holdInfo)
{
$details = [];
if ($holdInfo != null) {
$details = $this->getHoldingInfoForItem(
$patron['id'],
$holdInfo['id'],
$holdInfo['item_id']
);
}
if (isset($details['last-interest-date'])) {
try {
return $this->dateConverter
->convert('d.m.Y', 'U', $details['last-interest-date']);
} catch (DateException $e) {
// If we couldn't convert the date, fail gracefully.
$this->debug(
'Could not convert date: ' . $details['last-interest-date']
);
}
}
return null;
}
/**
* Place Hold
*
* Attempts to place a hold or recall on a particular item and returns
* an array with result details or throws an exception on failure of support
* classes
*
* @param array $details An array of item and patron data
*
* @throws ILSException
* @return mixed An array of data on the request including
* whether or not it was successful and a system message (if available)
*/
public function placeHold($details)
{
[$bib, $sys_no] = $this->parseId($details['id']);
$recordId = $bib . $sys_no;
$itemId = $details['item_id'];
$patron = $details['patron'];
$pickupLocation = $details['pickUpLocation'];
if (!$pickupLocation) {
$pickupLocation = $this->getDefaultPickUpLocation($patron, $details);
}
$comment = $details['comment'];
if (strlen($comment) <= 50) {
$comment1 = $comment;
$comment2 = null;
} else {
$comment1 = substr($comment, 0, 50);
$comment2 = substr($comment, 50, 50);
}
try {
$requiredBy = $this->dateConverter
->convertFromDisplayDate('Ymd', $details['requiredBy']);
} catch (DateException $de) {
return [
'success' => false,
'sysMessage' => 'hold_date_invalid'
];
}
$patronId = $patron['id'];
$body = new \SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>'
. '<hold-request-parameters></hold-request-parameters>'
);
$body->addChild('pickup-location', $pickupLocation);
$body->addChild('last-interest-date', $requiredBy);
$body->addChild('note-1', $comment1);
if (isset($comment2)) {
$body->addChild('note-2', $comment2);
}
$body = 'post_xml=' . $body->asXML();
try {
$this->doRestDLFRequest(
[
'patron', $patronId, 'record', $recordId, 'items', $itemId,
'hold'
],
null,
"PUT",
$body
);
} catch (AlephRestfulException $exception) {
$message = $exception->getMessage();
$note = $exception->getXmlResponse()
->xpath('/put-item-hold/create-hold/note[@type="error"]');
$note = $note[0];
return [
'success' => false,
'sysMessage' => "$message ($note)"
];
}
return ['success' => true];
}
/**
* Convert a barcode to an item ID.
*
* @param string $bar Barcode
*
* @return string
*/
public function barcodeToID($bar)
{
if (!$this->xserver_enabled) {
return null;
}
foreach ($this->bib as $base) {
try {
$xml = $this->doXRequest(
"find",
["base" => $base, "request" => "BAR=$bar"],
false
);
$docs = (int)$xml->{"no_records"};
if ($docs == 1) {
$set = (string)$xml->{"set_number"};
$result = $this->doXRequest(
"present",
["set_number" => $set, "set_entry" => "1"],
false
);
$id = $result->xpath('//doc_number/text()');
if (count($this->bib) == 1) {
return $id[0];
} else {
return $base . "-" . $id[0];
}
}
} catch (\Exception $ex) {
}
}
throw new ILSException('barcode not found');
}
/**
* Parse a date.
*
* @param string $date Date to parse
*
* @return string
*/
public function parseDate($date)
{
if ($date == null || $date == "") {
return "";
} elseif (preg_match("/^[0-9]{8}$/", $date) === 1) { // 20120725
return $this->dateConverter->convertToDisplayDate('Ynd', $date);
} elseif (preg_match("/^[0-9]+\/[A-Za-z]{3}\/[0-9]{4}$/", $date) === 1) {
// 13/jan/2012
return $this->dateConverter->convertToDisplayDate('d/M/Y', $date);
} elseif (preg_match("/^[0-9]+\/[0-9]+\/[0-9]{4}$/", $date) === 1) {
// 13/7/2012
return $this->dateConverter->convertToDisplayDate('d/m/Y', $date);
} else {
throw new \Exception("Invalid date: $date");
}
}
/**
* Helper method to determine whether or not a certain method can be
* called on this driver. Required method for any smart drivers.
*
* @param string $method The name of the called method.
* @param array $params Array of passed parameters
*
* @return bool True if the method can be called with the given parameters,
* false otherwise.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function supportsMethod($method, $params)
{
// Loan history is only available if properly configured
if ($method == 'getMyTransactionHistory') {
return !empty($this->config['TransactionHistory']['enabled']);
}
return is_callable([$this, $method]);
}
/**
* Public Function which retrieves historic loan, renew, hold and cancel
* settings from the driver ini file.
*
* @param string $func The name of the feature to be checked
* @param array $params Optional feature-specific parameters (array)
*
* @return array An array with key-value pairs.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getConfig($func, $params = null)
{
if ($func == "Holds") {
if (isset($this->config['Holds'])) {
return $this->config['Holds'];
}
return [
"HMACKeys" => "id:item_id",
"extraHoldFields" => "comments:requiredByDate:pickUpLocation",
"defaultRequiredDate" => "0:1:0"
];
} elseif ('getMyTransactionHistory' === $func) {
if (empty($this->config['TransactionHistory']['enabled'])) {
return false;
}
return [
'max_results' => 10000,
];
} else {
return [];
}
}
/**
* Get Pick Up Locations
*
* This is responsible for gettting a list of valid library locations for
* holds / recall retrieval
*
* @param array $patron Patron information returned by the patronLogin method.
* @param array $holdInfo Optional array, only passed in when getting a list
* in the context of placing or editing a hold. When placing a hold, it contains
* most of the same values passed to placeHold, minus the patron data. When
* editing a hold it contains all the hold information returned by getMyHolds.
* May be used to limit the pickup options or may be ignored. The driver must
* not add new options to the return array based on this data or other areas of
* VuFind may behave incorrectly.
*
* @throws ILSException
* @return array An array of associative arrays with locationID and
* locationDisplay keys
*/
public function getPickUpLocations($patron, $holdInfo = null)
{
$pickupLocations = [];
if ($holdInfo != null) {
$details = $this->getHoldingInfoForItem(
$patron['id'],
$holdInfo['id'],
$holdInfo['item_id']
);
foreach ($details['pickup-locations'] as $key => $value) {
$pickupLocations[] = [
"locationID" => $key,
"locationDisplay" => $value,
];
}
} else {
$default = $this->getDefaultPickUpLocation($patron);
if (!empty($default)) {
$pickupLocations[] = [
"locationID" => $default,
"locationDisplay" => $default,
];
}
}
return $pickupLocations;
}
/**
* Get Default Pick Up Location
*
* Returns the default pick up location set in VoyagerRestful.ini
*
* @param array $patron Patron information returned by the patronLogin method.
* @param array $holdInfo Optional array, only passed in when getting a list
* in the context of placing a hold; contains most of the same values passed to
* placeHold, minus the patron data. May be used to limit the pickup options
* or may be ignored.
*
* @return string The default pickup location for the patron.
*/
public function getDefaultPickUpLocation($patron, $holdInfo = null)
{
if ($holdInfo != null) {
$details = $this->getHoldingInfoForItem(
$patron['id'],
$holdInfo['id'],
$holdInfo['item_id']
);
$pickupLocations = $details['pickup-locations'];
if (isset($this->preferredPickUpLocations)) {
foreach (array_keys($details['pickup-locations']) as $locationID) {
if (in_array($locationID, $this->preferredPickUpLocations)) {
return $locationID;
}
}
}
// nothing found or preferredPickUpLocations is empty? Return the first
// locationId in pickupLocations array
return array_key_first($pickupLocations);
} elseif (isset($this->preferredPickUpLocations)) {
return $this->preferredPickUpLocations[0];
} else {
throw new ILSException(
'Missing Catalog/preferredPickUpLocations config setting.'
);
}
}
/**
* Get Purchase History
*
* This is responsible for retrieving the acquisitions history data for the
* specific record (usually recently received issues of a serial).
*
* @param string $id The record id to retrieve the info for
*
* @throws ILSException
* @return array An array with the acquisitions data on success.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getPurchaseHistory($id)
{
// TODO
return [];
}
/**
* Get New Items
*
* Retrieve the IDs of items recently added to the catalog.
*
* @param int $page Page number of results to retrieve (counting starts at 1)
* @param int $limit The size of each page of results to retrieve
* @param int $daysOld The maximum age of records to retrieve in days (max. 30)
* @param int $fundId optional fund ID to use for limiting results (use a value
* returned by getFunds, or exclude for no limit); note that "fund" may be a
* misnomer - if funds are not an appropriate way to limit your new item
* results, you can return a different set of values from getFunds. The
* important thing is that this parameter supports an ID returned by getFunds,
* whatever that may mean.
*
* @throws ILSException
* @return array Associative array with 'count' and 'results' keys
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function getNewItems($page, $limit, $daysOld, $fundId = null)
{
// TODO
$items = [];
return $items;
}
/**
* Get Departments
*
* Obtain a list of departments for use in limiting the reserves list.
*
* @throws ILSException
* @return array An associative array with key = dept. ID, value = dept. name.
*/
public function getDepartments()
{
// TODO
return [];
}
/**
* Get Instructors
*
* Obtain a list of instructors for use in limiting the reserves list.
*
* @throws ILSException
* @return array An associative array with key = ID, value = name.
*/
public function getInstructors()
{
// TODO
return [];
}
/**
* Get Courses
*
* Obtain a list of courses for use in limiting the reserves list.
*
* @throws ILSException
* @return array An associative array with key = ID, value = name.
*/
public function getCourses()
{
// TODO
return [];
}
/**
* Find Reserves
*
* Obtain information on course reserves.
*
* @param string $course ID from getCourses (empty string to match all)
* @param string $inst ID from getInstructors (empty string to match all)
* @param string $dept ID from getDepartments (empty string to match all)
*
* @throws ILSException
* @return array An array of associative arrays representing reserve items.
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function findReserves($course, $inst, $dept)
{
// TODO
return [];
}
}
| 1 | 33,135 | $balance is initialized to 0 above in line 1428 and then assigned in line 1437. If we're no longer manipulating that value, is there a reason to use a variable at all? It might make the overall code less confusing to make some changes there. | vufind-org-vufind | php |
@@ -73,9 +73,9 @@ class SeriesPlotTest(ReusedSQLTestCase, TestUtils):
pdf = self.pdf1
kdf = self.kdf1
- ax1 = pdf['a'].plot("bar", colormap='Paired')
+ ax1 = pdf['a'].plot(kind="bar", colormap='Paired')
bin1 = self.plot_to_base64(ax1)
- ax2 = kdf['a'].plot("bar", colormap='Paired')
+ ax2 = kdf['a'].plot(kind="bar", colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
| 1 | #
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import base64
from io import BytesIO
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from databricks import koalas as ks
from databricks.koalas.config import set_option, reset_option
from databricks.koalas.testing.utils import ReusedSQLTestCase, TestUtils
from databricks.koalas.plot import KoalasBoxPlot, KoalasHistPlot
matplotlib.use('agg')
class SeriesPlotTest(ReusedSQLTestCase, TestUtils):
@classmethod
def setUpClass(cls):
super(SeriesPlotTest, cls).setUpClass()
set_option('plotting.max_rows', 1000)
@classmethod
def tearDownClass(cls):
reset_option('plotting.max_rows')
super(SeriesPlotTest, cls).tearDownClass()
@property
def pdf1(self):
return pd.DataFrame({
'a': [1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 50],
}, index=[0, 1, 3, 5, 6, 8, 9, 9, 9, 10, 10])
@property
def kdf1(self):
return ks.from_pandas(self.pdf1)
@property
def kdf2(self):
return ks.range(1002)
@property
def pdf2(self):
return self.kdf2.to_pandas()
@staticmethod
def plot_to_base64(ax):
bytes_data = BytesIO()
ax.figure.savefig(bytes_data, format='png')
bytes_data.seek(0)
b64_data = base64.b64encode(bytes_data.read())
plt.close(ax.figure)
return b64_data
def test_bar_plot(self):
pdf = self.pdf1
kdf = self.kdf1
ax1 = pdf['a'].plot("bar", colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot("bar", colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['a'].plot(kind='bar', colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot(kind='bar', colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_bar_plot_limited(self):
pdf = self.pdf2
kdf = self.kdf2
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['id'][:1000].plot.bar(colormap='Paired')
ax1.text(1, 1, 'showing top 1000 elements only', size=6, ha='right', va='bottom',
transform=ax1.transAxes)
bin1 = self.plot_to_base64(ax1)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['id'].plot.bar(colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_pie_plot(self):
pdf = self.pdf1
kdf = self.kdf1
ax1 = pdf['a'].plot.pie(colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot.pie(colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['a'].plot(kind='pie', colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot(kind='pie', colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_pie_plot_limited(self):
pdf = self.pdf2
kdf = self.kdf2
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['id'][:1000].plot.pie(colormap='Paired')
ax1.text(1, 1, 'showing top 1000 elements only', size=6, ha='right', va='bottom',
transform=ax1.transAxes)
bin1 = self.plot_to_base64(ax1)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['id'].plot.pie(colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_line_plot(self):
pdf = self.pdf1
kdf = self.kdf1
ax1 = pdf['a'].plot("line", colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot("line", colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['a'].plot.line(colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot.line(colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_barh_plot(self):
pdf = self.pdf1
kdf = self.kdf1
ax1 = pdf['a'].plot("barh", colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot("barh", colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_barh_plot_limited(self):
pdf = self.pdf2
kdf = self.kdf2
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['id'][:1000].plot.barh(colormap='Paired')
ax1.text(1, 1, 'showing top 1000 elements only', size=6, ha='right', va='bottom',
transform=ax1.transAxes)
bin1 = self.plot_to_base64(ax1)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['id'].plot.barh(colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_hist_plot(self):
pdf = self.pdf1
kdf = self.kdf1
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['a'].plot.hist()
bin1 = self.plot_to_base64(ax1)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['a'].plot.hist()
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['a'].plot.hist(bins=15)
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot.hist(bins=15)
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['a'].plot(kind='hist', bins=15)
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot(kind='hist', bins=15)
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['a'].plot.hist(bins=3, bottom=[2, 1, 3])
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['a'].plot.hist(bins=3, bottom=[2, 1, 3])
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_compute_hist(self):
kdf = self.kdf1
expected_bins = np.linspace(1, 50, 11)
bins = KoalasHistPlot._get_bins(kdf[['a']].to_spark(), 10)
expected_histogram = np.array([5, 4, 1, 0, 0, 0, 0, 0, 0, 1])
histogram = KoalasHistPlot._compute_hist(kdf[['a']].to_spark(), bins)
self.assert_eq(pd.Series(expected_bins), pd.Series(bins))
self.assert_eq(pd.Series(expected_histogram), histogram)
def test_area_plot(self):
pdf = pd.DataFrame({
'sales': [3, 2, 3, 9, 10, 6],
'signups': [5, 5, 6, 12, 14, 13],
'visits': [20, 42, 28, 62, 81, 50],
}, index=pd.date_range(start='2018/01/01', end='2018/07/01', freq='M'))
kdf = ks.from_pandas(pdf)
ax1 = pdf['sales'].plot("area", colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['sales'].plot("area", colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
ax1 = pdf['sales'].plot.area(colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf['sales'].plot.area(colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
# just a sanity check for df.col type
ax1 = pdf.sales.plot("area", colormap='Paired')
bin1 = self.plot_to_base64(ax1)
ax2 = kdf.sales.plot("area", colormap='Paired')
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
def test_box_plot(self):
def check_box_plot(pdf, kdf, *args, **kwargs):
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['a'].plot.box(*args, **kwargs)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['a'].plot.box(*args, **kwargs)
diffs = [np.array([0, .5, 0, .5, 0, -.5, 0, -.5, 0, .5]),
np.array([0, .5, 0, 0]),
np.array([0, -.5, 0, 0])]
try:
for i, (line1, line2) in enumerate(zip(ax1.get_lines(), ax2.get_lines())):
expected = line1.get_xydata().ravel()
actual = line2.get_xydata().ravel()
if i < 3:
actual += diffs[i]
self.assert_eq(pd.Series(expected), pd.Series(actual))
finally:
ax1.cla()
ax2.cla()
check_box_plot(self.pdf1, self.kdf1)
check_box_plot(self.pdf1, self.kdf1, showfliers=True)
check_box_plot(self.pdf1, self.kdf1, sym='')
check_box_plot(self.pdf1, self.kdf1, sym='.', color='r')
check_box_plot(self.pdf1, self.kdf1, use_index=False, labels=['Test'])
check_box_plot(self.pdf1, self.kdf1, usermedians=[2.0])
check_box_plot(self.pdf1, self.kdf1, conf_intervals=[(1.0, 3.0)])
val = (1, 3)
self.assertRaises(
ValueError,
lambda: check_box_plot(self.pdf1, self.kdf1, usermedians=[2.0, 3.0]))
self.assertRaises(
ValueError,
lambda: check_box_plot(self.pdf1, self.kdf1, conf_intervals=[val, val]))
self.assertRaises(
ValueError,
lambda: check_box_plot(self.pdf1, self.kdf1, conf_intervals=[(1,)]))
def test_box_summary(self):
kdf = self.kdf1
pdf = self.pdf1
k = 1.5
stats, fences = KoalasBoxPlot._compute_stats(kdf['a'], 'a', whis=k, precision=0.01)
outliers = KoalasBoxPlot._outliers(kdf['a'], 'a', *fences)
whiskers = KoalasBoxPlot._calc_whiskers('a', outliers)
fliers = KoalasBoxPlot._get_fliers('a', outliers)
expected_mean = pdf['a'].mean()
expected_median = pdf['a'].median()
expected_q1 = np.percentile(pdf['a'], 25)
expected_q3 = np.percentile(pdf['a'], 75)
iqr = (expected_q3 - expected_q1)
expected_fences = (expected_q1 - k * iqr, expected_q3 + k * iqr)
pdf['outlier'] = ~pdf['a'].between(fences[0], fences[1])
expected_whiskers = pdf.query('not outlier')['a'].min(), pdf.query('not outlier')['a'].max()
expected_fliers = pdf.query('outlier')['a'].values
self.assertEqual(expected_mean, stats['mean'])
self.assertEqual(expected_median, stats['med'])
self.assertEqual(expected_q1, stats['q1'] + .5)
self.assertEqual(expected_q3, stats['q3'] - .5)
self.assertEqual(expected_fences[0], fences[0] + 2.0)
self.assertEqual(expected_fences[1], fences[1] - 2.0)
self.assertEqual(expected_whiskers[0], whiskers[0])
self.assertEqual(expected_whiskers[1], whiskers[1])
self.assertEqual(expected_fliers, fliers)
def test_kde_plot(self):
def moving_average(a, n=10):
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def check_kde_plot(pdf, kdf, *args, **kwargs):
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['a'].plot.kde(*args, **kwargs)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['a'].plot.kde(*args, **kwargs)
try:
for i, (line1, line2) in enumerate(zip(ax1.get_lines(), ax2.get_lines())):
expected = line1.get_xydata().ravel()
actual = line2.get_xydata().ravel()
# TODO: Due to implementation difference, the output is different comparing
# to pandas'. We should identify the root cause of difference, and reduce
# the diff.
# Note: Data is from 1 to 50. So, it smooths them by moving average and compares
# both.
self.assertTrue(
np.allclose(moving_average(actual),
moving_average(expected), rtol=3))
finally:
ax1.cla()
ax2.cla()
check_kde_plot(self.pdf1, self.kdf1, bw_method=0.3)
check_kde_plot(self.pdf1, self.kdf1, ind=[1, 2, 3, 4, 5], bw_method=3.0)
def test_empty_hist(self):
pdf = self.pdf1.assign(categorical='A')
kdf = ks.from_pandas(pdf)
kser = kdf['categorical']
with self.assertRaisesRegex(TypeError,
"Empty 'DataFrame': no numeric data to plot"):
kser.plot.hist()
def test_single_value_hist(self):
pdf = self.pdf1.assign(single=2)
kdf = ks.from_pandas(pdf)
_, ax1 = plt.subplots(1, 1)
ax1 = pdf['single'].plot.hist()
bin1 = self.plot_to_base64(ax1)
_, ax2 = plt.subplots(1, 1)
ax2 = kdf['single'].plot.hist()
bin2 = self.plot_to_base64(ax2)
self.assertEqual(bin1, bin2)
| 1 | 13,903 | Why do we need to explicitly use keyword arguments? | databricks-koalas | py |
@@ -708,7 +708,8 @@ func (c *Client) updateProgress(tid int, target *core.BuildTarget, metadata *pb.
case pb.ExecutionStage_EXECUTING:
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Building...")
case pb.ExecutionStage_COMPLETED:
- c.state.LogBuildResult(tid, target.Label, core.TargetBuilt, "Built")
+ // The build result will be logged in build/build_step.go
+ return
}
} else {
switch metadata.Stage { | 1 | // Package remote provides our interface to the Google remote execution APIs
// (https://github.com/bazelbuild/remote-apis) which Please can use to distribute
// work to remote servers.
package remote
import (
"context"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
sdkdigest "github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
"github.com/bazelbuild/remote-apis-sdks/go/pkg/retry"
fpb "github.com/bazelbuild/remote-apis/build/bazel/remote/asset/v1"
pb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
"github.com/bazelbuild/remote-apis/build/bazel/semver"
"github.com/golang/protobuf/ptypes"
"github.com/grpc-ecosystem/go-grpc-middleware/retry"
"golang.org/x/sync/errgroup"
"google.golang.org/genproto/googleapis/longrunning"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
_ "google.golang.org/grpc/encoding/gzip" // Registers the gzip compressor at init
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
"gopkg.in/op/go-logging.v1"
"github.com/thought-machine/please/src/core"
"github.com/thought-machine/please/src/fs"
)
var log = logging.MustGetLogger("remote")
// The API version we support.
var apiVersion = semver.SemVer{Major: 2}
// A Client is the interface to the remote API.
//
// It provides a higher-level interface over the specific RPCs available.
type Client struct {
client *client.Client
fetchClient fpb.FetchClient
initOnce sync.Once
state *core.BuildState
origState *core.BuildState
err error // for initialisation
instance string
// Stored output directories from previously executed targets.
// This isn't just a cache - it is needed for cases where we don't actually
// have the files physically on disk.
outputs map[core.BuildLabel]*pb.Directory
outputMutex sync.RWMutex
// The unstamped build action digests. Stamped and test digests are not stored.
// This isn't just a cache - it is needed because building a target can modify the target and things like plz hash
// --detailed and --shell will fail to get the right action digest.
unstampedBuildActionDigests actionDigestMap
// Used to control downloading targets (we must make sure we don't re-fetch them
// while another target is trying to use them).
//
// This map is of effective type `map[*core.BuildTarget]*pendingDownload`
downloads sync.Map
// Server-sent cache properties
maxBlobBatchSize int64
// Platform properties that we will request from the remote.
// TODO(peterebden): this will need some modification for cross-compiling support.
platform *pb.Platform
// Cache this for later
bashPath string
// Stats used to report RPC data rates
byteRateIn, byteRateOut, totalBytesIn, totalBytesOut int
stats *statsHandler
}
type actionDigestMap struct {
m sync.Map
}
func (m *actionDigestMap) Get(label core.BuildLabel) *pb.Digest {
d, ok := m.m.Load(label)
if !ok {
panic(fmt.Sprintf("could not find action digest for label: %s", label.String()))
}
return d.(*pb.Digest)
}
func (m *actionDigestMap) Put(label core.BuildLabel, actionDigest *pb.Digest) {
m.m.Store(label, actionDigest)
}
// A pendingDownload represents a pending download of a build target. It is used to
// ensure we only download each target exactly once.
type pendingDownload struct {
once sync.Once
err error // Any error if the download failed.
}
// New returns a new Client instance.
// It begins the process of contacting the remote server but does not wait for it.
func New(state *core.BuildState) *Client {
c := &Client{
state: state,
origState: state,
instance: state.Config.Remote.Instance,
outputs: map[core.BuildLabel]*pb.Directory{},
}
c.stats = newStatsHandler(c)
go c.CheckInitialised() // Kick off init now, but we don't have to wait for it.
return c
}
// CheckInitialised checks that the client has connected to the server correctly.
func (c *Client) CheckInitialised() error {
c.initOnce.Do(c.init)
return c.err
}
// init is passed to the sync.Once to do the actual initialisation.
func (c *Client) init() {
// Change grpc to log using our implementation
grpclog.SetLoggerV2(&grpcLogMabob{})
var g errgroup.Group
g.Go(c.initExec)
if c.state.Config.Remote.AssetURL != "" {
g.Go(c.initFetch)
}
c.err = g.Wait()
if c.err != nil {
log.Error("Error setting up remote execution client: %s", c.err)
}
}
// initExec initialiases the remote execution client.
func (c *Client) initExec() error {
// Create a copy of the state where we can modify the config
c.state = c.state.ForConfig()
c.state.Config.HomeDir = c.state.Config.Remote.HomeDir
dialOpts, err := c.dialOpts()
if err != nil {
return err
}
client, err := client.NewClient(context.Background(), c.instance, client.DialParams{
Service: c.state.Config.Remote.URL,
CASService: c.state.Config.Remote.CASURL,
NoSecurity: !c.state.Config.Remote.Secure,
TransportCredsOnly: c.state.Config.Remote.Secure,
DialOpts: dialOpts,
}, client.UseBatchOps(true), client.RetryTransient(), client.RPCTimeout(c.state.Config.Remote.Timeout))
if err != nil {
return err
}
c.client = client
// Extend timeouts a bit, RetryTransient only gives about 1.5 seconds total which isn't
// necessarily very much if the other end needs to sort its life out.
c.client.Retrier.Backoff = retry.ExponentialBackoff(500*time.Millisecond, 5*time.Second, retry.Attempts(8))
// Query the server for its capabilities. This tells us whether it is capable of
// execution, caching or both.
resp, err := c.client.GetCapabilities(context.Background())
if err != nil {
return err
}
if lessThan(&apiVersion, resp.LowApiVersion) || lessThan(resp.HighApiVersion, &apiVersion) {
return fmt.Errorf("Unsupported API version; we require %s but server only supports %s - %s", printVer(&apiVersion), printVer(resp.LowApiVersion), printVer(resp.HighApiVersion))
}
caps := resp.CacheCapabilities
if caps == nil {
return fmt.Errorf("Cache capabilities not supported by server (we do not support execution-only servers)")
}
if err := c.chooseDigest(caps.DigestFunction); err != nil {
return err
}
c.maxBlobBatchSize = caps.MaxBatchTotalSizeBytes
if c.maxBlobBatchSize == 0 {
// No limit was set by the server, assume we are implicitly limited to 4MB (that's
// gRPC's limit which most implementations do not seem to override). Round it down a
// bit to allow a bit of serialisation overhead etc.
c.maxBlobBatchSize = 4000000
}
// Look this up just once now.
bash, err := core.LookBuildPath("bash", c.state.Config)
c.bashPath = bash
log.Debug("Remote execution client initialised for storage")
// Now check if it can do remote execution
if resp.ExecutionCapabilities == nil {
return fmt.Errorf("Remote execution is configured but the build server doesn't support it")
}
if err := c.chooseDigest([]pb.DigestFunction_Value{resp.ExecutionCapabilities.DigestFunction}); err != nil {
return err
} else if !resp.ExecutionCapabilities.ExecEnabled {
return fmt.Errorf("Remote execution not enabled for this server")
}
c.platform = convertPlatform(c.state.Config)
log.Debug("Remote execution client initialised for execution")
if c.state.Config.Remote.AssetURL == "" {
c.fetchClient = fpb.NewFetchClient(client.Connection)
}
return nil
}
// initFetch initialises the remote fetch server.
func (c *Client) initFetch() error {
dialOpts, err := c.dialOpts()
if err != nil {
return err
}
if c.state.Config.Remote.Secure {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))
} else {
dialOpts = append(dialOpts, grpc.WithInsecure())
}
conn, err := grpc.Dial(c.state.Config.Remote.AssetURL, append(dialOpts, grpc.WithUnaryInterceptor(grpc_retry.UnaryClientInterceptor()))...)
if err != nil {
return fmt.Errorf("Failed to connect to the remote fetch server: %s", err)
}
c.fetchClient = fpb.NewFetchClient(conn)
return nil
}
// chooseDigest selects a digest function that we will use.w
func (c *Client) chooseDigest(fns []pb.DigestFunction_Value) error {
systemFn := c.digestEnum(c.state.Config.Build.HashFunction)
for _, fn := range fns {
if fn == systemFn {
return nil
}
}
return fmt.Errorf("No acceptable hash function available; server supports %s but we require %s. Hint: you may need to set the hash function appropriately in the [build] section of your config", fns, systemFn)
}
// digestEnum returns a proto enum for the digest function of given name (as we name them in config)
func (c *Client) digestEnum(name string) pb.DigestFunction_Value {
switch c.state.Config.Build.HashFunction {
case "sha256":
return pb.DigestFunction_SHA256
case "sha1":
return pb.DigestFunction_SHA1
default:
return pb.DigestFunction_UNKNOWN // Shouldn't get here
}
}
// Build executes a remote build of the given target.
func (c *Client) Build(tid int, target *core.BuildTarget) (*core.BuildMetadata, error) {
if err := c.CheckInitialised(); err != nil {
return nil, err
}
metadata, ar, digest, err := c.build(tid, target)
if err != nil {
return metadata, err
}
if c.state.TargetHasher != nil {
hash, _ := hex.DecodeString(c.outputHash(ar))
c.state.TargetHasher.SetHash(target, hash)
}
if err := c.setOutputs(target, ar); err != nil {
return metadata, c.wrapActionErr(err, digest)
}
if c.origState.ShouldDownload(target) {
if !c.outputsExist(target, digest) {
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Downloading")
if err := c.download(target, func() error {
return c.reallyDownload(target, digest, ar)
}); err != nil {
return metadata, err
}
} else {
log.Debug("Not downloading outputs for %s, they are already up-to-date", target)
// Ensure this is marked as already downloaded.
v, _ := c.downloads.LoadOrStore(target, &pendingDownload{})
v.(*pendingDownload).once.Do(func() {})
}
if err := c.downloadData(target); err != nil {
return metadata, err
}
}
return metadata, nil
}
// downloadData downloads all the runtime data for a target, recursively.
func (c *Client) downloadData(target *core.BuildTarget) error {
var g errgroup.Group
for _, datum := range target.AllData() {
if l := datum.Label(); l != nil {
t := c.state.Graph.TargetOrDie(*l)
g.Go(func() error {
if err := c.Download(t); err != nil {
return err
}
return c.downloadData(t)
})
}
}
return g.Wait()
}
// Run runs a target on the remote executors.
func (c *Client) Run(target *core.BuildTarget) error {
if err := c.CheckInitialised(); err != nil {
return err
}
cmd, digest, err := c.uploadAction(target, false, true)
if err != nil {
return err
}
// 24 hours is kind of an arbitrarily long timeout. Basically we just don't want to limit it here.
_, _, err = c.execute(0, target, cmd, digest, 24*time.Hour, false, false)
return err
}
// build implements the actual build of a target.
func (c *Client) build(tid int, target *core.BuildTarget) (*core.BuildMetadata, *pb.ActionResult, *pb.Digest, error) {
needStdout := target.PostBuildFunction != nil
// If we're gonna stamp the target, first check the unstamped equivalent that we store results under.
// This implements the rules of stamp whereby we don't force rebuilds every time e.g. the SCM revision changes.
command, stampedDigest, unstampedDigest, err := c.buildStampedAndUnstampedAction(target)
if err != nil {
return nil, nil, nil, err
}
if target.Stamp {
if metadata, ar := c.maybeRetrieveResults(tid, target, command, unstampedDigest, needStdout); metadata != nil {
return metadata, ar, stampedDigest, nil
}
}
metadata, ar, err := c.execute(tid, target, command, stampedDigest, target.BuildTimeout, false, needStdout)
if target.Stamp && err == nil {
// Store results under unstamped digest too.
c.locallyCacheResults(target, unstampedDigest, metadata, ar)
c.client.UpdateActionResult(context.Background(), &pb.UpdateActionResultRequest{
InstanceName: c.instance,
ActionDigest: unstampedDigest,
ActionResult: ar,
})
}
return metadata, ar, stampedDigest, err
}
// Download downloads outputs for the given target.
func (c *Client) Download(target *core.BuildTarget) error {
if target.Local {
return nil // No download needed since this target was built locally
}
return c.download(target, func() error {
buildAction := c.unstampedBuildActionDigests.Get(target.Label)
if c.outputsExist(target, buildAction) {
return nil
}
_, ar := c.retrieveResults(target, nil, buildAction, false)
if ar == nil {
return fmt.Errorf("Failed to retrieve action result for %s", target)
}
return c.reallyDownload(target, buildAction, ar)
})
}
func (c *Client) download(target *core.BuildTarget, f func() error) error {
v, _ := c.downloads.LoadOrStore(target, &pendingDownload{})
d := v.(*pendingDownload)
d.once.Do(func() {
d.err = f()
})
return d.err
}
func (c *Client) reallyDownload(target *core.BuildTarget, digest *pb.Digest, ar *pb.ActionResult) error {
log.Debug("Downloading outputs for %s", target)
if err := removeOutputs(target); err != nil {
return err
}
if err := c.downloadActionOutputs(context.Background(), ar, target); err != nil {
return c.wrapActionErr(err, digest)
}
c.recordAttrs(target, digest)
log.Debug("Downloaded outputs for %s", target)
return nil
}
func (c *Client) downloadActionOutputs(ctx context.Context, ar *pb.ActionResult, target *core.BuildTarget) error {
// We can download straight into the out dir if there are no outdirs to worry about
if len(target.OutputDirectories) == 0 {
return c.client.DownloadActionOutputs(ctx, ar, target.OutDir())
}
defer os.RemoveAll(target.TmpDir())
if err := c.client.DownloadActionOutputs(ctx, ar, target.TmpDir()); err != nil {
return err
}
if err := moveOutDirsToTmpRoot(target); err != nil {
return fmt.Errorf("failed to move out directories to correct place in tmp folder: %w", err)
}
if err := moveTmpFilesToOutDir(target); err != nil {
return fmt.Errorf("failed to move downloaded action output from target tmp dir to out dir: %w", err)
}
return nil
}
// moveTmpFilesToOutDir moves files from the target tmp dir to the out dir
func moveTmpFilesToOutDir(target *core.BuildTarget) error {
files, err := ioutil.ReadDir(target.TmpDir())
if err != nil {
return err
}
for _, f := range files {
oldPath := filepath.Join(target.TmpDir(), f.Name())
newPath := filepath.Join(target.OutDir(), f.Name())
if err := fs.RecursiveCopy(oldPath, newPath, target.OutMode()); err != nil {
return err
}
}
return nil
}
// moveOutDirsToTmpRoot moves all the files from the output dirs into the root of the build temp dir and deletes the
// now empty directory
func moveOutDirsToTmpRoot(target *core.BuildTarget) error {
for _, dir := range target.OutputDirectories {
if err := moveOutDirFilesToTmpRoot(target, dir.Dir()); err != nil {
return fmt.Errorf("failed to move output dir (%s) contents to rule root: %w", dir, err)
}
if err := os.Remove(filepath.Join(target.TmpDir(), dir.Dir())); err != nil {
return err
}
}
return nil
}
func moveOutDirFilesToTmpRoot(target *core.BuildTarget, dir string) error {
fullDir := filepath.Join(target.TmpDir(), dir)
files, err := ioutil.ReadDir(fullDir)
if err != nil {
return err
}
for _, f := range files {
from := filepath.Join(fullDir, f.Name())
to := filepath.Join(target.TmpDir(), f.Name())
if err := os.Rename(from, to); err != nil {
return err
}
}
return nil
}
// Test executes a remote test of the given target.
// It returns the results (and coverage if appropriate) as bytes to be parsed elsewhere.
func (c *Client) Test(tid int, target *core.BuildTarget) (metadata *core.BuildMetadata, results [][]byte, coverage []byte, err error) {
if err := c.CheckInitialised(); err != nil {
return nil, nil, nil, err
}
command, digest, err := c.buildAction(target, true, false)
if err != nil {
return nil, nil, nil, err
}
metadata, ar, execErr := c.execute(tid, target, command, digest, target.TestTimeout, true, false)
// Error handling here is a bit fiddly due to prioritisation; the execution error
// is more relevant, but we want to still try to get results if we can, and it's an
// error if we can't get those results on success.
if !target.NoTestOutput && ar != nil {
results, err = c.downloadAllPrefixedFiles(ar, core.TestResultsFile)
if execErr == nil && err != nil {
return metadata, nil, nil, err
}
}
if target.NeedCoverage(c.state) && ar != nil {
if digest := c.digestForFilename(ar, core.CoverageFile); digest != nil {
coverage, err = c.client.ReadBlob(context.Background(), sdkdigest.NewFromProtoUnvalidated(digest))
if execErr == nil && err != nil {
return metadata, results, nil, err
}
}
}
return metadata, results, coverage, execErr
}
// retrieveResults retrieves target results from where it can (either from the local cache or from remote).
// It returns nil if it cannot be retrieved.
func (c *Client) retrieveResults(target *core.BuildTarget, command *pb.Command, digest *pb.Digest, needStdout bool) (*core.BuildMetadata, *pb.ActionResult) {
// First see if this execution is cached locally
if metadata, ar := c.retrieveLocalResults(target, digest); metadata != nil {
log.Debug("Got locally cached results for %s %s", target.Label, c.actionURL(digest, true))
metadata.Cached = true
return metadata, ar
}
// Now see if it is cached on the remote server
if ar, err := c.client.GetActionResult(context.Background(), &pb.GetActionResultRequest{
InstanceName: c.instance,
ActionDigest: digest,
InlineStdout: needStdout,
}); err == nil {
// This action already exists and has been cached.
if metadata, err := c.buildMetadata(ar, needStdout, false); err == nil {
log.Debug("Got remotely cached results for %s %s", target.Label, c.actionURL(digest, true))
if command != nil {
err = c.verifyActionResult(target, command, digest, ar, c.state.Config.Remote.VerifyOutputs)
}
if err == nil {
c.locallyCacheResults(target, digest, metadata, ar)
metadata.Cached = true
return metadata, ar
}
log.Debug("Remotely cached results for %s were missing some outputs, forcing a rebuild: %s", target.Label, err)
}
}
return nil, nil
}
// maybeRetrieveResults is like retrieveResults but only retrieves if we aren't forcing a rebuild of the target
// (i.e. not if we're doing plz build --rebuild).
func (c *Client) maybeRetrieveResults(tid int, target *core.BuildTarget, command *pb.Command, digest *pb.Digest, needStdout bool) (*core.BuildMetadata, *pb.ActionResult) {
if !c.state.ShouldRebuild(target) {
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Checking remote...")
if metadata, ar := c.retrieveResults(target, command, digest, needStdout); metadata != nil {
return metadata, ar
}
}
return nil, nil
}
// execute submits an action to the remote executor and monitors its progress.
// The returned ActionResult may be nil on failure.
func (c *Client) execute(tid int, target *core.BuildTarget, command *pb.Command, digest *pb.Digest, timeout time.Duration, isTest, needStdout bool) (*core.BuildMetadata, *pb.ActionResult, error) {
if !isTest || c.state.NumTestRuns == 1 {
if metadata, ar := c.maybeRetrieveResults(tid, target, command, digest, needStdout); metadata != nil {
return metadata, ar, nil
}
}
// We didn't actually upload the inputs before, so we must do so now.
command, digest, err := c.uploadAction(target, isTest, false)
if err != nil {
return nil, nil, fmt.Errorf("Failed to upload build action: %s", err)
}
// Remote actions & filegroups get special treatment at this point.
if target.IsFilegroup {
// Filegroups get special-cased since they are just a movement of files.
return c.buildFilegroup(target, command, digest)
} else if target.IsRemoteFile {
return c.fetchRemoteFile(tid, target, digest)
}
return c.reallyExecute(tid, target, command, digest, needStdout)
}
// reallyExecute is like execute but after the initial cache check etc.
// The action & sources must have already been uploaded.
func (c *Client) reallyExecute(tid int, target *core.BuildTarget, command *pb.Command, digest *pb.Digest, needStdout bool) (*core.BuildMetadata, *pb.ActionResult, error) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for i := 1; i < 1000000; i++ {
select {
case <-ctx.Done():
return
case <-time.After(1 * time.Minute):
if i == 1 {
log.Notice("%s still executing after 1 minute", target)
} else {
log.Notice("%s still executing after %d minutes", target, i)
}
}
}
}()
resp, err := c.client.ExecuteAndWaitProgress(context.Background(), &pb.ExecuteRequest{
InstanceName: c.instance,
ActionDigest: digest,
SkipCacheLookup: true, // We've already done it above.
}, func(metadata *pb.ExecuteOperationMetadata) {
c.updateProgress(tid, target, metadata)
})
if err != nil {
// Handle timing issues if we try to resume an execution as it fails. If we get a
// "not found" we might find that it's already been completed and we can't resume.
if status.Code(err) == codes.NotFound {
if metadata, ar := c.retrieveResults(target, command, digest, needStdout); metadata != nil {
return metadata, ar, nil
}
}
return nil, nil, c.wrapActionErr(fmt.Errorf("Failed to execute %s: %s", target, err), digest)
}
switch result := resp.Result.(type) {
case *longrunning.Operation_Error:
// We shouldn't really get here - the rex API requires servers to always
// use the response field instead of error.
return nil, nil, convertError(result.Error)
case *longrunning.Operation_Response:
response := &pb.ExecuteResponse{}
if err := ptypes.UnmarshalAny(result.Response, response); err != nil {
log.Error("Failed to deserialise execution response: %s", err)
return nil, nil, err
}
if response.CachedResult {
c.state.LogBuildResult(tid, target.Label, core.TargetCached, "Cached")
}
for k, v := range response.ServerLogs {
log.Debug("Server log available: %s: hash key %s", k, v.Digest.Hash)
}
var respErr error
if response.Status != nil {
respErr = convertError(response.Status)
if respErr != nil {
if !strings.Contains(respErr.Error(), c.state.Config.Remote.DisplayURL) {
if url := c.actionURL(digest, false); url != "" {
respErr = fmt.Errorf("%s\nAction URL: %s", respErr, url)
}
}
}
}
if resp.Result == nil { // This is optional on failure.
return nil, nil, respErr
}
if response.Result == nil { // This seems to happen when things go wrong on the build server end.
if response.Status != nil {
return nil, nil, fmt.Errorf("Build server returned invalid result: %s", convertError(response.Status))
}
log.Debug("Bad result from build server: %+v", response)
return nil, nil, fmt.Errorf("Build server did not return valid result")
}
if response.Message != "" {
// Informational messages can be emitted on successful actions.
log.Debug("Message from build server:\n %s", response.Message)
}
failed := respErr != nil || response.Result.ExitCode != 0
metadata, err := c.buildMetadata(response.Result, needStdout || failed, failed)
logResponseTimings(target, response.Result)
// The original error is higher priority than us trying to retrieve the
// output of the thing that failed.
if respErr != nil {
return metadata, response.Result, respErr
} else if response.Result.ExitCode != 0 {
err := fmt.Errorf("Remotely executed command exited with %d", response.Result.ExitCode)
if response.Message != "" {
err = fmt.Errorf("%s\n %s", err, response.Message)
}
if len(metadata.Stdout) != 0 {
err = fmt.Errorf("%s\nStdout:\n%s", err, metadata.Stdout)
}
if len(metadata.Stderr) != 0 {
err = fmt.Errorf("%s\nStderr:\n%s", err, metadata.Stderr)
}
// Add a link to the action URL, but only if the server didn't do it (they
// might add one to the failed action if they're using the Buildbarn extension
// for it, which we can't replicate here).
if !strings.Contains(response.Message, c.state.Config.Remote.DisplayURL) {
if url := c.actionURL(digest, true); url != "" {
err = fmt.Errorf("%s\n%s", err, url)
}
}
return metadata, response.Result, err
} else if err != nil {
return nil, nil, err
}
log.Debug("Completed remote build action for %s", target)
if err := c.verifyActionResult(target, command, digest, response.Result, false); err != nil {
return metadata, response.Result, err
}
c.locallyCacheResults(target, digest, metadata, response.Result)
return metadata, response.Result, nil
default:
if !resp.Done {
return nil, nil, fmt.Errorf("Received an incomplete response for %s", target)
}
return nil, nil, fmt.Errorf("Unknown response type (was a %T): %#v", resp.Result, resp) // Shouldn't get here
}
}
func logResponseTimings(target *core.BuildTarget, ar *pb.ActionResult) {
if ar != nil && ar.ExecutionMetadata != nil {
startTime := toTime(ar.ExecutionMetadata.ExecutionStartTimestamp)
endTime := toTime(ar.ExecutionMetadata.ExecutionCompletedTimestamp)
inputFetchStartTime := toTime(ar.ExecutionMetadata.InputFetchStartTimestamp)
inputFetchEndTime := toTime(ar.ExecutionMetadata.InputFetchCompletedTimestamp)
log.Debug("Completed remote build action for %s; input fetch %s, build time %s", target, inputFetchEndTime.Sub(inputFetchStartTime), endTime.Sub(startTime))
}
}
// updateProgress updates the progress of a target based on its metadata.
func (c *Client) updateProgress(tid int, target *core.BuildTarget, metadata *pb.ExecuteOperationMetadata) {
if c.state.Config.Remote.DisplayURL != "" {
log.Debug("Remote progress for %s: %s%s", target.Label, metadata.Stage, c.actionURL(metadata.ActionDigest, true))
}
if target.State() <= core.Built {
switch metadata.Stage {
case pb.ExecutionStage_CACHE_CHECK:
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Checking cache...")
case pb.ExecutionStage_QUEUED:
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Queued")
case pb.ExecutionStage_EXECUTING:
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Building...")
case pb.ExecutionStage_COMPLETED:
c.state.LogBuildResult(tid, target.Label, core.TargetBuilt, "Built")
}
} else {
switch metadata.Stage {
case pb.ExecutionStage_CACHE_CHECK:
c.state.LogBuildResult(tid, target.Label, core.TargetTesting, "Checking cache...")
case pb.ExecutionStage_QUEUED:
c.state.LogBuildResult(tid, target.Label, core.TargetTesting, "Queued")
case pb.ExecutionStage_EXECUTING:
c.state.LogBuildResult(tid, target.Label, core.TargetTesting, "Testing...")
case pb.ExecutionStage_COMPLETED:
c.state.LogBuildResult(tid, target.Label, core.TargetTested, "Tested")
}
}
}
// PrintHashes prints the action hashes for a target.
func (c *Client) PrintHashes(target *core.BuildTarget, isTest bool) {
actionDigest := c.unstampedBuildActionDigests.Get(target.Label)
fmt.Printf(" Action: %7d bytes: %s\n", actionDigest.SizeBytes, actionDigest.Hash)
if c.state.Config.Remote.DisplayURL != "" {
fmt.Printf(" URL: %s\n", c.actionURL(actionDigest, false))
}
}
// DataRate returns an estimate of the current in/out RPC data rates in bytes per second.
func (c *Client) DataRate() (int, int, int, int) {
return c.byteRateIn, c.byteRateOut, c.totalBytesIn, c.totalBytesOut
}
// fetchRemoteFile sends a request to fetch a file using the remote asset API.
func (c *Client) fetchRemoteFile(tid int, target *core.BuildTarget, actionDigest *pb.Digest) (*core.BuildMetadata, *pb.ActionResult, error) {
c.state.LogBuildResult(tid, target.Label, core.TargetBuilding, "Downloading...")
urls := target.AllURLs(c.state.Config)
req := &fpb.FetchBlobRequest{
InstanceName: c.instance,
Timeout: ptypes.DurationProto(target.BuildTimeout),
Uris: urls,
}
if !c.state.NeedHashesOnly || !c.state.IsOriginalTargetOrParent(target) {
if sri := subresourceIntegrity(target); sri != "" {
req.Qualifiers = []*fpb.Qualifier{{
Name: "checksum.sri",
Value: sri,
}}
}
}
ctx, cancel := context.WithTimeout(context.Background(), target.BuildTimeout)
defer cancel()
resp, err := c.fetchClient.FetchBlob(ctx, req)
if err != nil {
return nil, nil, fmt.Errorf("Failed to download file: %s", err)
}
c.state.LogBuildResult(tid, target.Label, core.TargetBuilt, "Downloaded.")
// If we get here, the blob exists in the CAS. Create an ActionResult corresponding to it.
outs := target.Outputs()
ar := &pb.ActionResult{
OutputFiles: []*pb.OutputFile{{
Path: outs[0],
Digest: resp.BlobDigest,
IsExecutable: target.IsBinary,
}},
}
if _, err := c.client.UpdateActionResult(context.Background(), &pb.UpdateActionResultRequest{
InstanceName: c.instance,
ActionDigest: actionDigest,
ActionResult: ar,
}); err != nil {
return nil, nil, fmt.Errorf("Error updating action result: %s", err)
}
return &core.BuildMetadata{}, ar, nil
}
// buildFilegroup "builds" a single filegroup target.
func (c *Client) buildFilegroup(target *core.BuildTarget, command *pb.Command, actionDigest *pb.Digest) (*core.BuildMetadata, *pb.ActionResult, error) {
b, err := c.uploadInputDir(nil, target, false) // We don't need to actually upload the inputs here, that is already done.
if err != nil {
return nil, nil, err
}
ar := &pb.ActionResult{}
if err := c.uploadBlobs(func(ch chan<- *chunker.Chunker) error {
defer close(ch)
b.Root(ch)
for _, out := range command.OutputPaths {
if d, f := b.Node(path.Join(target.Label.PackageName, out)); d != nil {
chomk, _ := chunker.NewFromProto(b.Tree(path.Join(target.Label.PackageName, out)), int(c.client.ChunkMaxSize))
ch <- chomk
ar.OutputDirectories = append(ar.OutputDirectories, &pb.OutputDirectory{
Path: out,
TreeDigest: chomk.Digest().ToProto(),
})
} else if f != nil {
ar.OutputFiles = append(ar.OutputFiles, &pb.OutputFile{
Path: out,
Digest: f.Digest,
IsExecutable: f.IsExecutable,
})
} else {
// Of course, we should not get here (classic developer things...)
return fmt.Errorf("Missing output from filegroup: %s", out)
}
}
return nil
}); err != nil {
return nil, nil, err
}
if _, err := c.client.UpdateActionResult(context.Background(), &pb.UpdateActionResultRequest{
InstanceName: c.instance,
ActionDigest: actionDigest,
ActionResult: ar,
}); err != nil {
return nil, nil, fmt.Errorf("Error updating action result: %s", err)
}
return &core.BuildMetadata{}, ar, nil
}
// A grpcLogMabob is an implementation of grpc's logging interface using our backend.
type grpcLogMabob struct{}
func (g *grpcLogMabob) Info(args ...interface{}) { log.Info("%s", args) }
func (g *grpcLogMabob) Infof(format string, args ...interface{}) { log.Info(format, args...) }
func (g *grpcLogMabob) Infoln(args ...interface{}) { log.Info("%s", args) }
func (g *grpcLogMabob) Warning(args ...interface{}) { log.Warning("%s", args) }
func (g *grpcLogMabob) Warningf(format string, args ...interface{}) { log.Warning(format, args...) }
func (g *grpcLogMabob) Warningln(args ...interface{}) { log.Warning("%s", args) }
func (g *grpcLogMabob) Error(args ...interface{}) { log.Error("", args...) }
func (g *grpcLogMabob) Errorf(format string, args ...interface{}) { log.Errorf(format, args...) }
func (g *grpcLogMabob) Errorln(args ...interface{}) { log.Error("", args...) }
func (g *grpcLogMabob) Fatal(args ...interface{}) { log.Fatal(args...) }
func (g *grpcLogMabob) Fatalf(format string, args ...interface{}) { log.Fatalf(format, args...) }
func (g *grpcLogMabob) Fatalln(args ...interface{}) { log.Fatal(args...) }
func (g *grpcLogMabob) V(l int) bool { return log.IsEnabledFor(logging.Level(l)) }
| 1 | 9,141 | Might still want to log this as `TargetBuilding` but with a slightly different message? | thought-machine-please | go |
@@ -6,6 +6,17 @@
C015_queue_element::C015_queue_element() {}
+C015_queue_element::C015_queue_element(C015_queue_element&& other)
+ : idx(other.idx), _timestamp(other._timestamp), TaskIndex(other.TaskIndex)
+ , controller_idx(other.controller_idx), valuesSent(other.valuesSent)
+ , valueCount(other.valueCount)
+{
+ for (byte i = 0; i < VARS_PER_TASK; ++i) {
+ txt[i] = std::move(other.txt[i]);
+ vPin[i] = other.vPin[i];
+ }
+}
+
C015_queue_element::C015_queue_element(const struct EventStruct *event, byte value_count) :
idx(event->idx),
TaskIndex(event->TaskIndex), | 1 | #include "../ControllerQueue/C015_queue_element.h"
#include "../DataStructs/ESPEasy_EventStruct.h"
#ifdef USES_C015
C015_queue_element::C015_queue_element() {}
C015_queue_element::C015_queue_element(const struct EventStruct *event, byte value_count) :
idx(event->idx),
TaskIndex(event->TaskIndex),
controller_idx(event->ControllerIndex),
valuesSent(0),
valueCount(value_count) {}
bool C015_queue_element::checkDone(bool succesfull) const {
if (succesfull) { ++valuesSent; }
return valuesSent >= valueCount || valuesSent >= VARS_PER_TASK;
}
size_t C015_queue_element::getSize() const {
size_t total = sizeof(*this);
for (int i = 0; i < VARS_PER_TASK; ++i) {
total += txt[i].length();
}
return total;
}
bool C015_queue_element::isDuplicate(const C015_queue_element& other) const {
if (other.controller_idx != controller_idx ||
other.TaskIndex != TaskIndex ||
other.sensorType != sensorType ||
other.valueCount != valueCount ||
other.idx != idx) {
return false;
}
for (byte i = 0; i < VARS_PER_TASK; ++i) {
if (other.txt[i] != txt[i]) {
return false;
}
if (other.vPin[i] != vPin[i]) {
return false;
}
}
return true;
}
#endif
| 1 | 21,945 | ref. above, this also can be omitted in case `txt = std::move(other.txt);` could work (or copy), consider `std::array<String, VARS_PER_TASK>;`? or a custom object implementing `Object& operator=(Object&&) noexcept;' | letscontrolit-ESPEasy | cpp |
@@ -10,7 +10,7 @@
"""Looks for try/except statements with too much code in the try clause."""
-from astroid.node_classes import For, If, While, With
+from astroid import nodes
from pylint import checkers, interfaces
| 1 | # Copyright (c) 2019-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2019-2020 Tyler Thieding <tyler@thieding.com>
# Copyright (c) 2020 hippo91 <guillaume.peillex@gmail.com>
# Copyright (c) 2020 Anthony Sottile <asottile@umich.edu>
# Copyright (c) 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
"""Looks for try/except statements with too much code in the try clause."""
from astroid.node_classes import For, If, While, With
from pylint import checkers, interfaces
class BroadTryClauseChecker(checkers.BaseChecker):
"""Checks for try clauses with too many lines.
According to PEP 8, ``try`` clauses shall contain the absolute minimum
amount of code. This checker enforces a maximum number of statements within
``try`` clauses.
"""
__implements__ = interfaces.IAstroidChecker
# configuration section name
name = "broad_try_clause"
msgs = {
"W0717": (
"%s",
"too-many-try-statements",
"Try clause contains too many statements.",
)
}
priority = -2
options = (
(
"max-try-statements",
{
"default": 1,
"type": "int",
"metavar": "<int>",
"help": "Maximum number of statements allowed in a try clause",
},
),
)
def _count_statements(self, try_node):
statement_count = len(try_node.body)
for body_node in try_node.body:
if isinstance(body_node, (For, If, While, With)):
statement_count += self._count_statements(body_node)
return statement_count
def visit_tryexcept(self, node):
try_clause_statements = self._count_statements(node)
if try_clause_statements > self.config.max_try_statements:
msg = f"try clause contains {try_clause_statements} statements, expected at most {self.config.max_try_statements}"
self.add_message(
"too-many-try-statements", node.lineno, node=node, args=msg
)
def visit_tryfinally(self, node):
self.visit_tryexcept(node)
def register(linter):
"""Required method to auto register this checker."""
linter.register_checker(BroadTryClauseChecker(linter))
| 1 | 15,396 | Well done, we forget that one apparentely. | PyCQA-pylint | py |
@@ -25,17 +25,6 @@ except:
xr = None
-def toarray(v, index_value=False):
- """
- Interface helper function to turn dask Arrays into numpy arrays as
- necessary. If index_value is True, a value is returned instead of
- an array holding a single value.
- """
- if dask and isinstance(v, dask.array.Array):
- arr = v.compute()
- return arr[()] if index_value else arr
- else:
- return v
def compute_edges(edges):
""" | 1 | import itertools
import param
import numpy as np
from ..core import Dataset, OrderedDict
from ..core.operation import ElementOperation
from ..core.util import (is_nan, sort_topologically, one_to_one,
cartesian_product, is_cyclic)
try:
import pandas as pd
from ..core.data import PandasInterface
except:
pd = None
try:
import dask
except:
dask = None
try:
import xarray as xr
except:
xr = None
def toarray(v, index_value=False):
"""
Interface helper function to turn dask Arrays into numpy arrays as
necessary. If index_value is True, a value is returned instead of
an array holding a single value.
"""
if dask and isinstance(v, dask.array.Array):
arr = v.compute()
return arr[()] if index_value else arr
else:
return v
def compute_edges(edges):
"""
Computes edges from a number of bin centers,
throwing an exception if the edges are not
evenly spaced.
"""
widths = np.diff(edges)
if np.allclose(widths, widths[0]):
width = widths[0]
else:
raise ValueError('Centered bins have to be of equal width.')
edges -= width/2.
return np.concatenate([edges, [edges[-1]+width]])
def reduce_fn(x):
"""
Aggregation function to get the first non-zero value.
"""
values = x.values if pd and isinstance(x, pd.Series) else x
for v in values:
if not is_nan(v):
return v
return np.NaN
class categorical_aggregate2d(ElementOperation):
"""
Generates a gridded Dataset of 2D aggregate arrays indexed by the
first two dimensions of the passed Element, turning all remaining
dimensions into value dimensions. The key dimensions of the
gridded array are treated as categorical indices. Useful for data
indexed by two independent categorical variables such as a table
of population values indexed by country and year. Data that is
indexed by continuous dimensions should be binned before
aggregation. The aggregation will retain the global sorting order
of both dimensions.
>> table = Table([('USA', 2000, 282.2), ('UK', 2005, 58.89)],
kdims=['Country', 'Year'], vdims=['Population'])
>> categorical_aggregate2d(table)
Dataset({'Country': ['USA', 'UK'], 'Year': [2000, 2005],
'Population': [[ 282.2 , np.NaN], [np.NaN, 58.89]]},
kdims=['Country', 'Year'], vdims=['Population'])
"""
datatype = param.List(['xarray', 'grid'] if xr else ['grid'], doc="""
The grid interface types to use when constructing the gridded Dataset.""")
def _get_coords(self, obj):
"""
Get the coordinates of the 2D aggregate, maintaining the correct
sorting order.
"""
xdim, ydim = obj.dimensions(label=True)[:2]
xcoords = obj.dimension_values(xdim, False)
ycoords = obj.dimension_values(ydim, False)
# Determine global orderings of y-values using topological sort
grouped = obj.groupby(xdim, container_type=OrderedDict,
group_type=Dataset).values()
orderings = OrderedDict()
sort = True
for group in grouped:
vals = group.dimension_values(ydim, False)
if len(vals) == 1:
orderings[vals[0]] = [vals[0]]
else:
for i in range(len(vals)-1):
p1, p2 = vals[i:i+2]
orderings[p1] = [p2]
if sort:
if vals.dtype.kind in ('i', 'f'):
sort = (np.diff(vals)>=0).all()
else:
sort = np.array_equal(np.sort(vals), vals)
if sort or one_to_one(orderings, ycoords):
ycoords = np.sort(ycoords)
elif not is_cyclic(orderings):
ycoords = list(itertools.chain(*sort_topologically(orderings)))
return xcoords, ycoords
def _aggregate_dataset(self, obj, xcoords, ycoords):
"""
Generates a gridded Dataset from a column-based dataset and
lists of xcoords and ycoords
"""
dim_labels = obj.dimensions(label=True)
vdims = obj.dimensions()[2:]
xdim, ydim = dim_labels[:2]
shape = (len(ycoords), len(xcoords))
nsamples = np.product(shape)
ys, xs = cartesian_product([ycoords, xcoords], copy=True)
data = {xdim: xs, ydim: ys}
for vdim in vdims:
values = np.empty(nsamples)
values[:] = np.NaN
data[vdim.name] = values
dtype = 'dataframe' if pd else 'dictionary'
dense_data = Dataset(data, kdims=obj.kdims, vdims=obj.vdims, datatype=[dtype])
concat_data = obj.interface.concatenate([dense_data, obj], datatype=[dtype])
reindexed = concat_data.reindex([xdim, ydim], vdims)
if pd:
df = PandasInterface.as_dframe(reindexed)
df = df.groupby([xdim, ydim], sort=False).first().reset_index()
agg = reindexed.clone(df)
else:
agg = reindexed.aggregate([xdim, ydim], reduce_fn)
# Convert data to a gridded dataset
grid_data = {xdim: xcoords, ydim: ycoords}
for vdim in vdims:
grid_data[vdim.name] = agg.dimension_values(vdim).reshape(shape)
return agg.clone(grid_data, kdims=[xdim, ydim], vdims=vdims,
datatype=self.p.datatype)
def _process(self, obj, key=None):
"""
Generates a categorical 2D aggregate by inserting NaNs at all
cross-product locations that do not already have a value assigned.
Returns a 2D gridded Dataset object.
"""
if isinstance(obj, Dataset) and obj.interface.gridded:
return obj
elif obj.ndims > 2:
raise ValueError("Cannot aggregate more than two dimensions")
elif len(obj.dimensions()) < 3:
raise ValueError("Must have at two dimensions to aggregate over"
"and one value dimension to aggregate on.")
dtype = 'dataframe' if pd else 'dictionary'
obj = Dataset(obj, datatype=[dtype])
xcoords, ycoords = self._get_coords(obj)
return self._aggregate_dataset(obj, xcoords, ycoords)
| 1 | 15,956 | Guess it isn't used. The dask thing was just a prototype so removing it is probably the right thing to do. | holoviz-holoviews | py |
@@ -12,7 +12,17 @@ from elasticsearch.helpers import bulk
from t4_lambda_shared.preview import ELASTIC_LIMIT_BYTES
-CONTENT_INDEX_EXTS = [
+def _get_extension_overrides():
+ """check the environment for index extension overrides; this is a standalone
+ function so that it can be unit tested"""
+ return {
+ t.strip().lower()
+ for t in os.getenv("CONTENT_INDEX_EXTS", "").split(",")
+ if t.strip().startswith(".")
+ }
+
+
+CONTENT_INDEX_EXTS = _get_extension_overrides() or {
".csv",
".ipynb",
".md", | 1 | """ core logic for fetching documents from S3 and queueing them locally before
sending to elastic search in memory-limited batches"""
from datetime import datetime
from math import floor
import os
from aws_requests_auth.aws_auth import AWSRequestsAuth
import boto3
from elasticsearch import Elasticsearch, RequestsHttpConnection
from elasticsearch.helpers import bulk
from t4_lambda_shared.preview import ELASTIC_LIMIT_BYTES
CONTENT_INDEX_EXTS = [
".csv",
".ipynb",
".md",
".parquet",
".rmd",
".tsv",
".txt"
]
EVENT_PREFIX = {
"Created": "ObjectCreated:",
"Removed": "ObjectRemoved:"
}
# See https://amzn.to/2xJpngN for chunk size as a function of container size
CHUNK_LIMIT_BYTES = int(os.getenv('CHUNK_LIMIT_BYTES') or 9_500_000)
ELASTIC_TIMEOUT = 30
MAX_BACKOFF = 360 # seconds
MAX_RETRY = 4 # prevent long-running lambdas due to malformed calls
# signifies that the object is truly deleted, not to be confused with
# s3:ObjectRemoved:DeleteMarkerCreated, which we may see in versioned buckets
# see https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html
QUEUE_LIMIT_BYTES = 100_000_000 # 100MB
RETRY_429 = 5
# pylint: disable=super-init-not-called
class RetryError(Exception):
"""Fatal and final error if docs fail after multiple retries"""
def __init__(self, message):
pass
class DocumentQueue:
"""transient in-memory queue for documents to be indexed"""
def __init__(self, context):
"""constructor"""
self.queue = []
self.size = 0
self.context = context
def append(
self,
event_type,
size=0,
*,
last_modified,
bucket,
ext,
key,
text,
etag,
version_id
):
"""format event as a document and then queue the document"""
if not isinstance(version_id, (str, type(None))):
# should never raise given how index.py, the only caller of .append(),
# works
raise ValueError(
f".append() must set version_id even if missing from event; "
f"got {version_id}"
)
if event_type.startswith(EVENT_PREFIX["Created"]):
_op_type = "index"
elif event_type.startswith(EVENT_PREFIX["Removed"]):
_op_type = "delete"
else:
print("Skipping unrecognized event type {event_type}")
return
# On types and fields, see
# https://www.elastic.co/guide/en/elasticsearch/reference/master/mapping.html
body = {
# Elastic native keys
"_id": f"{key}:{version_id}",
"_index": bucket,
"_type": "_doc",
# index will upsert (and clobber existing equivalent _ids)
"_op_type": "delete" if event_type.startswith(EVENT_PREFIX["Removed"]) else "index",
# Quilt keys
# Be VERY CAREFUL changing these values, as a type change can cause a
# mapper_parsing_exception that below code won't handle
# TODO: remove this field from ES in /enterprise (now deprecated and unused)
"comment": "",
"content": text, # field for full-text search
"etag": etag,
"event": event_type,
"ext": ext,
"key": key,
# "key_text": created by mappings copy_to
"last_modified": last_modified.isoformat(),
# TODO: remove this field from ES in /enterprise (now deprecated and unused)
"meta_text": "",
"size": size,
"target": "",
"updated": datetime.utcnow().isoformat(),
"version_id": version_id
}
self.append_document(body)
if self.size >= QUEUE_LIMIT_BYTES:
self.send_all()
def append_document(self, doc):
"""append well-formed documents (used for retry or by append())"""
if doc["content"]:
# document text dominates memory footprint; OK to neglect the
# small fixed size for the JSON metadata
self.size += min(doc["size"], ELASTIC_LIMIT_BYTES)
self.queue.append(doc)
def send_all(self):
"""flush self.queue in 1-2 bulk calls"""
if not self.queue:
return
elastic_host = os.environ["ES_HOST"]
session = boto3.session.Session()
credentials = session.get_credentials().get_frozen_credentials()
awsauth = AWSRequestsAuth(
# These environment variables are automatically set by Lambda
aws_access_key=credentials.access_key,
aws_secret_access_key=credentials.secret_key,
aws_token=credentials.token,
aws_host=elastic_host,
aws_region=session.region_name,
aws_service="es"
)
elastic = Elasticsearch(
hosts=[{"host": elastic_host, "port": 443}],
http_auth=awsauth,
max_backoff=get_time_remaining(self.context) if self.context else MAX_BACKOFF,
# Give ES time to respond when under load
timeout=ELASTIC_TIMEOUT,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection
)
# For response format see
# https://www.elastic.co/guide/en/elasticsearch/reference/6.7/docs-bulk.html
# (We currently use Elastic 6.7 per quiltdata/deployment search.py)
# note that `elasticsearch` post-processes this response
_, errors = bulk_send(elastic, self.queue)
if errors:
id_to_doc = {d["_id"]: d for d in self.queue}
send_again = []
for error in errors:
# retry index and delete errors
if "index" in error or "delete" in error:
if "index" in error:
inner = error["index"]
if "delete" in error:
inner = error["delete"]
if "_id" in inner:
doc = id_to_doc[inner["_id"]]
# Always retry the source document if we can identify it.
# This catches temporary 403 on index write blocks & other
# transient issues.
send_again.append(doc)
# retry the entire batch
else:
# Unclear what would cause an error that's neither index nor delete
# but if there's an unknown error we need to assume it applies to
# the batch.
send_again = self.queue
# Last retry (though elasticsearch might retry 429s tho)
if send_again:
_, errors = bulk_send(elastic, send_again)
if errors:
raise RetryError(
"Failed to load messages into Elastic on second retry.\n"
f"{_}\nErrors: {errors}\nTo resend:{send_again}"
)
# empty the queue
self.size = 0
self.queue = []
def get_time_remaining(context):
"""returns time remaining in seconds before lambda context is shut down"""
time_remaining = floor(context.get_remaining_time_in_millis()/1000)
if time_remaining < 30:
print(
f"Warning: Lambda function has less than {time_remaining} seconds."
" Consider reducing bulk batch size."
)
return time_remaining
def bulk_send(elastic, list_):
"""make a bulk() call to elastic"""
return bulk(
elastic,
list_,
# Some magic numbers to reduce memory pressure
# e.g. see https://github.com/wagtail/wagtail/issues/4554
chunk_size=100, # max number of documents sent in one chunk
# The stated default is max_chunk_bytes=10485760, but with default
# ES will still return an exception stating that the very
# same request size limit has been exceeded
max_chunk_bytes=CHUNK_LIMIT_BYTES,
# number of retries for 429 (too many requests only)
# all other errors handled by our code
max_retries=RETRY_429,
# we'll process errors on our own
raise_on_error=False,
raise_on_exception=False
)
| 1 | 18,635 | This code is correct, but it's a bit confusing to see how (e.g., without the if startswith(".') the or below would break.) I think it will be clearer for the long run if you refactor this just a bit. CONTENT_INDEX_EXTS (all caps) looks like a constant, but is now being set by the environment. Instead, replace the reference to CONTENT_INDEX_EXTS in index.py with a simple call to a method "get_content_index_exts" (or similar). Then you can write all the logic into one clean function. | quiltdata-quilt | py |
@@ -298,4 +298,9 @@ public final class ZMSConsts {
public static final int ZMS_DISABLED_AUTHORITY_FILTER = 0x01;
public static final String ZMS_PROP_STATUS_CHECKER_FACTORY_CLASS = "athenz.zms.status_checker_factory_class";
+
+ public static final String ZMS_PROP_ENABLE_PRINCIPAL_STATE_UPDATER = "athenz.zms.enable_principal_state_updater";
+ public static final String ZMS_PROP_PRINCIPAL_STATE_UPDATER_FREQUENCY = "athenz.zms.principal_state_updater_frequency";
+ public static final String ZMS_PROP_PRINCIPAL_STATE_UPDATER_FREQUENCY_DEFAULT = "30"; // in minutes
+ public static final String ZMS_PROP_PRINCIPAL_STATE_UPDATER_DISABLE_TIMER = "athenz.zms.disable_principal_state_updater_timer_task";
} | 1 | /*
* Copyright 2016 Yahoo Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.zms;
/**
* Contains constants shared by classes throughout the service.
**/
public final class ZMSConsts {
// System property names with defaults(where applicable)
public static final String ZMS_PROP_USER_DOMAIN = "athenz.user_domain";
public static final String ZMS_PROP_HOME_DOMAIN = "athenz.home_domain";
public static final String ZMS_PROP_USER_DOMAIN_ALIAS = "athenz.user_domain_alias";
public static final String ZMS_PROP_HTTP_PORT = "athenz.port";
public static final String ZMS_PROP_HTTPS_PORT = "athenz.tls_port";
public static final String ZMS_PROP_STATUS_PORT = "athenz.status_port";
public static final String ZMS_PROP_ADDL_USER_CHECK_DOMAINS = "athenz.zms.addl_user_check_domains";
public static final String ZMS_PROP_ROOT_DIR = "athenz.zms.root_dir";
public static final String ZMS_PROP_HOSTNAME = "athenz.zms.hostname";
public static final String ZMS_PROP_DOMAIN_ADMIN = "athenz.zms.domain_admin";
public static final String ZMS_PROP_FILE_NAME = "athenz.zms.prop_file";
public static final String ZMS_PROP_VIRTUAL_DOMAIN = "athenz.zms.virtual_domain_support";
public static final String ZMS_PROP_VIRTUAL_DOMAIN_LIMIT = "athenz.zms.virtual_domain_limit";
public static final String ZMS_PROP_READ_ONLY_MODE = "athenz.zms.read_only_mode";
public static final String ZMS_PROP_DOMAIN_NAME_MAX_SIZE = "athenz.zms.domain_name_max_len";
public static final String ZMS_PROP_HEALTH_CHECK_PATH = "athenz.zms.health_check_path";
public static final String ZMS_PROP_SERVER_REGION = "athenz.zms.server_region";
public static final String ZMS_PROP_CONFLICT_RETRY_COUNT = "athenz.zms.request_conflict_retry_count";
public static final String ZMS_PROP_CONFLICT_RETRY_SLEEP_TIME = "athenz.zms.request_conflict_retry_sleep_time";
public static final String ZMS_PROP_JDBC_RW_STORE = "athenz.zms.jdbc_store";
public static final String ZMS_PROP_JDBC_RW_USER = "athenz.zms.jdbc_user";
public static final String ZMS_PROP_JDBC_RW_PASSWORD = "athenz.zms.jdbc_password";
public static final String ZMS_PROP_JDBC_RO_STORE = "athenz.zms.jdbc_ro_store";
public static final String ZMS_PROP_JDBC_RO_USER = "athenz.zms.jdbc_ro_user";
public static final String ZMS_PROP_JDBC_RO_PASSWORD = "athenz.zms.jdbc_ro_password";
public static final String ZMS_PROP_JDBC_APP_NAME = "athenz.zms.jdbc_app_name";
public static final String ZMS_PROP_JDBC_VERIFY_SERVER_CERT = "athenz.zms.jdbc_verify_server_certificate";
public static final String ZMS_PROP_JDBC_USE_SSL = "athenz.zms.jdbc_use_ssl";
public static final String ZMS_PROP_JDBC_TLS_VERSIONS = "athenz.zms.jdbc_tls_versions";
public static final String ZMS_PROP_FILE_STORE_NAME = "athenz.zms.file_store_name";
public static final String ZMS_PROP_FILE_STORE_QUOTA = "athenz.zms.file_store_quota";
public static final String ZMS_PROP_FILE_STORE_PATH = "athenz.zms.file_store_path";
public static final String ZMS_PROP_AUTHORITY_CLASSES = "athenz.zms.authority_classes";
public static final String ZMS_PROP_STORE_OP_TIMEOUT = "athenz.zms.store_operation_timeout";
public static final String ZMS_PROP_NOAUTH_URI_LIST = "athenz.zms.no_auth_uri_list";
public static final String ZMS_PROP_CORS_ORIGIN_LIST = "athenz.zms.cors_origin_list";
public static final String ZMS_PROP_AWS_RDS_USER = "athenz.zms.aws_rds_user";
public static final String ZMS_PROP_AWS_RDS_IAM_ROLE = "athenz.zms.aws_rds_iam_role";
public static final String ZMS_PROP_AWS_RDS_ENGINE = "athenz.zms.aws_rds_engine";
public static final String ZMS_PROP_AWS_RDS_DATABASE = "athenz.zms.aws_rds_database";
public static final String ZMS_PROP_AWS_RDS_MASTER_INSTANCE = "athenz.zms.aws_rds_master_instance";
public static final String ZMS_PROP_AWS_RDS_MASTER_PORT = "athenz.zms.aws_rds_master_port";
public static final String ZMS_PROP_AWS_RDS_REPLICA_INSTANCE = "athenz.zms.aws_rds_replica_instance";
public static final String ZMS_PROP_AWS_RDS_CREDS_REFRESH_TIME = "athenz.zms.aws_rds_creds_refresh_time";
public static final String ZMS_AUTO_UPDATE_TEMPLATE_FEATURE_FLAG = "athenz.zms.auto_update_template_feature_flag";
public static final String DB_PROP_USER = "user";
public static final String DB_PROP_PASSWORD = "password";
public static final String DB_PROP_USE_SSL = "useSSL";
public static final String DB_PROP_VERIFY_SERVER_CERT = "verifyServerCertificate";
public static final String DB_PROP_TLS_PROTOCOLS = "enabledTLSProtocols";
public static final String ZMS_PROP_USER_AUTHORITY_CLASS = "athenz.zms.user_authority_class";
public static final String ZMS_PROP_PRINCIPAL_AUTHORITY_CLASS = "athenz.zms.principal_authority_class";
public static final String ZMS_PROP_TIMEOUT = "athenz.zms.user_token_timeout";
public static final String ZMS_PROP_SIGNED_POLICY_TIMEOUT = "athenz.zms.signed_policy_timeout";
public static final String ZMS_PROP_AUTHZ_SERVICE_FNAME = "athenz.zms.authz_service_fname";
public static final String ZMS_PROP_SOLUTION_TEMPLATE_FNAME = "athenz.zms.solution_templates_fname";
public static final String ZMS_PROP_PROVIDER_ENDPOINTS = "athenz.zms.provider_endpoints";
public static final String ZMS_PROP_PRODUCT_ID_SUPPORT = "athenz.zms.product_id_support";
public static final String ZMS_PROP_SECURE_REQUESTS_ONLY = "athenz.zms.secure_requests_only";
public static final String ZMS_PROP_RESERVED_SERVICE_NAMES = "athenz.zms.reserved_service_names";
public static final String ZMS_PROP_SERVICE_NAME_MIN_LENGTH = "athenz.zms.service_name_min_length";
public static final String ZMS_PROP_VALIDATE_USER_MEMBERS = "athenz.zms.validate_user_members";
public static final String ZMS_PROP_VALIDATE_SERVICE_MEMBERS = "athenz.zms.validate_service_members";
public static final String ZMS_PROP_VALIDATE_SERVICE_MEMBERS_SKIP_DOMAINS = "athenz.zms.validate_service_members_skip_domains";
public static final String ZMS_PROP_MASTER_COPY_FOR_SIGNED_DOMAINS = "athenz.zms.master_copy_for_signed_domains";
// properties used to over-ride default Audit logger
public static final String ZMS_PROP_METRIC_FACTORY_CLASS = "athenz.zms.metric_factory_class";
public static final String ZMS_PROP_AUDIT_LOGGER_FACTORY_CLASS = "athenz.zms.audit_logger_factory_class";
public static final String ZMS_AUDIT_LOGGER_FACTORY_CLASS = "com.yahoo.athenz.common.server.log.impl.DefaultAuditLoggerFactory";
public static final String ZMS_PROP_AUDIT_REF_VALIDATOR_FACTORY_CLASS = "athenz.zms.audit_ref_validator_factory_class";
public static final String ZMS_PROP_AUDIT_REF_CHECK_OBJECTS = "athenz.zms.audit_ref_check_objects";
public static final String ZMS_AUDIT_TYPE_ROLE = "role";
public static final String ZMS_AUDIT_TYPE_GROUP = "group";
public static final String ZMS_AUDIT_TYPE_POLICY = "policy";
public static final String ZMS_AUDIT_TYPE_SERVICE = "service";
public static final String ZMS_AUDIT_TYPE_DOMAIN = "domain";
public static final String ZMS_AUDIT_TYPE_ENTITY = "entity";
public static final String ZMS_AUDIT_TYPE_TENANCY = "tenancy";
public static final String ZMS_AUDIT_TYPE_TEMPLATE = "template";
public static final String ZMS_PROP_PRIVATE_KEY_STORE_FACTORY_CLASS = "athenz.zms.private_key_store_factory_class";
public static final String ZMS_PRIVATE_KEY_STORE_FACTORY_CLASS = "com.yahoo.athenz.auth.impl.FilePrivateKeyStoreFactory";
public static final String ZMS_PROP_OBJECT_STORE_FACTORY_CLASS = "athenz.zms.object_store_factory_class";
public static final String ZMS_OBJECT_STORE_FACTORY_CLASS = "com.yahoo.athenz.zms.store.impl.FileObjectStoreFactory";
// properties for our default quota limits
public static final String ZMS_PROP_QUOTA_CHECK = "athenz.zms.quota_check";
public static final String ZMS_PROP_QUOTA_ROLE = "athenz.zms.quota_role";
public static final String ZMS_PROP_QUOTA_ROLE_MEMBER = "athenz.zms.quota_role_member";
public static final String ZMS_PROP_QUOTA_POLICY = "athenz.zms.quota_policy";
public static final String ZMS_PROP_QUOTA_ASSERTION = "athenz.zms.quota_assertion";
public static final String ZMS_PROP_QUOTA_SERVICE = "athenz.zms.quota_service";
public static final String ZMS_PROP_QUOTA_SERVICE_HOST = "athenz.zms.quota_service_host";
public static final String ZMS_PROP_QUOTA_PUBLIC_KEY = "athenz.zms.quota_public_key";
public static final String ZMS_PROP_QUOTA_ENTITY = "athenz.zms.quota_entity";
public static final String ZMS_PROP_QUOTA_SUBDOMAIN = "athenz.zms.quota_subdomain";
public static final String ZMS_PROP_QUOTA_GROUP = "athenz.zms.quota_group";
public static final String ZMS_PROP_QUOTA_GROUP_MEMBER = "athenz.zms.quota_group_member";
public static final String ZMS_PROP_MYSQL_SERVER_TIMEZONE = "athenz.zms.mysql_server_timezone";
public static final String ZMS_PRINCIPAL_AUTHORITY_CLASS = "com.yahoo.athenz.auth.impl.PrincipalAuthority";
public static final String ZMS_UNKNOWN_DOMAIN = "unknown_domain";
public static final String ZMS_INVALID_DOMAIN = "invalid_domain";
public static final String ZMS_SERVICE = "zms";
public static final String ZMS_DOMAIN_NAME_MAX_SIZE_DEFAULT = "128";
public static final String USER_DOMAIN = "user";
public static final String RSA = "RSA";
public static final String EC = "EC";
public static final String HTTP_ORIGIN = "Origin";
public static final String HTTP_RFC1123_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss zzz";
public static final String HTTP_DATE_GMT_ZONE = "GMT";
public static final String HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public static final String HTTP_ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
public static final String HTTP_ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
public static final String HTTP_ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
public static final String HTTP_ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
public static final String HTTP_ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
public static final String ZMS_RESERVED_SERVICE_NAMES_DEFAULT = "com,net,org,edu,biz,gov,mil,info,name,mobi,cloud";
public static final String LOCALHOST = "localhost";
public static final String SCHEME_HTTP = "http";
public static final String SCHEME_HTTPS = "https";
public static final String SCHEME_CLASS = "class";
public static final int ZMS_HTTPS_PORT_DEFAULT = 4443;
public static final int ZMS_HTTP_PORT_DEFAULT = 4080;
public static final String DB_COLUMN_DESCRIPTION = "description";
public static final String DB_COLUMN_ORG = "org";
public static final String DB_COLUMN_UUID = "uuid";
public static final String DB_COLUMN_ENABLED = "enabled";
public static final String DB_COLUMN_AUDIT_ENABLED = "audit_enabled";
public static final String DB_COLUMN_MODIFIED = "modified";
public static final String DB_COLUMN_NAME = "name";
public static final String DB_COLUMN_TRUST = "trust";
public static final String DB_COLUMN_MEMBER = "member";
public static final String DB_COLUMN_ENTITY = "entity";
public static final String DB_COLUMN_SUBDOMAIN = "subdomain";
public static final String DB_COLUMN_ROLE = "role";
public static final String DB_COLUMN_ROLE_MEMBER = "role_member";
public static final String DB_COLUMN_POLICY = "policy";
public static final String DB_COLUMN_SERVICE = "service";
public static final String DB_COLUMN_SERVICE_HOST = "service_host";
public static final String DB_COLUMN_PUBLIC_KEY = "public_key";
public static final String DB_COLUMN_ASSERTION = "assertion";
public static final String DB_COLUMN_RESOURCE = "resource";
public static final String DB_COLUMN_ACTION = "action";
public static final String DB_COLUMN_EFFECT = "effect";
public static final String DB_COLUMN_KEY_VALUE = "key_value";
public static final String DB_COLUMN_KEY_ID = "key_id";
public static final String DB_COLUMN_SVC_USER = "svc_user";
public static final String DB_COLUMN_SVC_GROUP = "svc_group";
public static final String DB_COLUMN_EXECUTABLE = "executable";
public static final String DB_COLUMN_PROVIDER_ENDPOINT = "provider_endpoint";
public static final String DB_COLUMN_VALUE = "value";
public static final String DB_COLUMN_DOMAIN_ID = "domain_id";
public static final String DB_COLUMN_ACCOUNT = "account";
public static final String DB_COLUMN_PRODUCT_ID = "ypm_id";
public static final String DB_COLUMN_ADMIN = "admin";
public static final String DB_COLUMN_CREATED = "created";
public static final String DB_COLUMN_AUDIT_REF = "audit_ref";
public static final String DB_COLUMN_ROLE_NAME = "role_name";
public static final String DB_COLUMN_ASSERT_DOMAIN_ID = "assert_domain_id";
public static final String DB_COLUMN_ASSERT_ID = "assertion_id";
public static final String DB_COLUMN_CERT_DNS_DOMAIN = "cert_dns_domain";
public static final String DB_COLUMN_SELF_SERVE = "self_serve";
public static final String DB_COLUMN_EXPIRATION = "expiration";
public static final String DB_COLUMN_REVIEW_REMINDER = "review_reminder";
public static final String DB_COLUMN_MEMBER_EXPIRY_DAYS = "member_expiry_days";
public static final String DB_COLUMN_TOKEN_EXPIRY_MINS = "token_expiry_mins";
public static final String DB_COLUMN_CERT_EXPIRY_MINS = "cert_expiry_mins";
public static final String DB_COLUMN_DOMAIN_NAME = "domain_name";
public static final String DB_COLUMN_PRINCIPAL_NAME = "principal_name";
public static final String DB_COLUMN_APPLICATION_ID = "application_id";
public static final String DB_COLUMN_SIGN_ALGORITHM = "sign_algorithm";
public static final String DB_COLUMN_REVIEW_ENABLED = "review_enabled";
public static final String DB_COLUMN_NOTIFY_ROLES = "notify_roles";
public static final String DB_COLUMN_LAST_REVIEWED_TIME = "last_reviewed_time";
public static final String DB_COLUMN_REQ_PRINCIPAL = "req_principal";
public static final String DB_COLUMN_MEMBER_REVIEW_DAYS = "member_review_days";
public static final String DB_COLUMN_TEMPLATE_NAME = "template";
public static final String DB_COLUMN_TEMPLATE_VERSION = "current_version";
public static final String DB_COLUMN_AS_DOMAIN_NAME = "domain_name";
public static final String DB_COLUMN_AS_ROLE_NAME = "role_name";
public static final String DB_COLUMN_AS_GROUP_NAME = "group_name";
public static final String DB_COLUMN_SYSTEM_DISABLED = "system_disabled";
public static final String DB_COLUMN_SERVICE_REVIEW_DAYS = "service_review_days";
public static final String DB_COLUMN_SERVICE_EXPIRY_DAYS = "service_expiry_days";
public static final String DB_COLUMN_GROUP_EXPIRY_DAYS = "group_expiry_days";
public static final String DB_COLUMN_ROLE_CERT_EXPIRY_MINS = "role_cert_expiry_mins";
public static final String DB_COLUMN_SERVICE_CERT_EXPIRY_MINS = "service_cert_expiry_mins";
public static final String DB_COLUMN_PRINCIPAL_GROUP = "principal_group";
public static final String DB_COLUMN_PRINCIPAL_GROUP_MEMBER = "principal_group_member";
public static final String DB_COLUMN_USER_AUTHORITY_FILTER = "user_authority_filter";
public static final String DB_COLUMN_USER_AUTHORITY_EXPIRATION = "user_authority_expiration";
public static final String DB_COLUMN_AS_DOMAIN_USER_AUTHORITY_FILTER = "domain_user_authority_filter";
public static final String ADMIN_POLICY_NAME = "admin";
public static final String ADMIN_ROLE_NAME = "admin";
public static final String ASSERTION_EFFECT_ALLOW = "ALLOW";
public static final String ACTION_ASSUME_ROLE = "assume_role";
public static final String ACTION_ASSUME_AWS_ROLE = "assume_aws_role";
public static final String ACTION_UPDATE = "update";
public static final String OBJECT_DOMAIN = "domain";
public static final String OBJECT_ROLE = "role";
public static final String OBJECT_POLICY = "policy";
public static final String OBJECT_SERVICE = "service";
public static final String OBJECT_PRINCIPAL = "principal";
public static final String OBJECT_HOST = "host";
public static final String OBJECT_GROUP = "group";
public static final String SYSTEM_META_PRODUCT_ID = "productid";
public static final String SYSTEM_META_ACCOUNT = "account";
public static final String SYSTEM_META_CERT_DNS_DOMAIN = "certdnsdomain";
public static final String SYSTEM_META_AUDIT_ENABLED = "auditenabled";
public static final String SYSTEM_META_USER_AUTH_FILTER = "userauthorityfilter";
public static final String SYSTEM_META_ENABLED = "enabled";
public static final String SYSTEM_META_ORG = "org";
public static final String SYSTEM_META_LAST_MOD_TIME = "modified";
public static final String SYSTEM_META_PROVIDER_ENDPOINT = "providerendpoint";
// HTTP operation types used in metrics
public static final String HTTP_GET = "GET";
public static final String HTTP_PUT = "PUT";
public static final String HTTP_POST = "POST";
public static final String HTTP_DELETE = "DELETE";
public static final String HTTP_OPTIONS = "OPTIONS";
public static final String HTTP_REQUEST = "REQUEST";
public static final String STR_DEF_ROOT = "/home/athenz";
public static final int STRING_BLDR_SIZE_DEFAULT = 512;
public static final String ZMS_JSON_PARSER_ERROR_RESPONSE = "{\"code\":400,\"message\":\"Invalid Object: checkout https://github.com/yahoo/athenz/tree/master/core/zms/src/main/rdl for object definitions\"}";
public static final String SYS_AUTH_AUDIT_BY_ORG = "sys.auth.audit.org";
public static final String SYS_AUTH_AUDIT_BY_DOMAIN = "sys.auth.audit.domain";
public static final String ZMS_PROP_PENDING_ROLE_MEMBER_LIFESPAN = "athenz.zms.pending_role_member_lifespan";
public static final String ZMS_PENDING_ROLE_MEMBER_LIFESPAN_DEFAULT = "30";
public static final String SYS_AUTH_MONITOR = "sys.auth.monitor";
public static final String ZMS_PROP_MONITOR_IDENTITY = "athenz.zms.monitor_identity";
public static final int ZMS_DISABLED_AUTHORITY_FILTER = 0x01;
public static final String ZMS_PROP_STATUS_CHECKER_FACTORY_CLASS = "athenz.zms.status_checker_factory_class";
}
| 1 | 5,446 | please update the zms conf file to have a small description of these options since by default feature is off and must be enabled | AthenZ-athenz | java |
@@ -31,7 +31,12 @@ module.exports = class ThumbnailGenerator extends Plugin {
const defaultOptions = {
thumbnailWidth: null,
thumbnailHeight: null,
- waitForThumbnailsBeforeUpload: false
+ waitForThumbnailsBeforeUpload: false,
+ lazy: false
+ }
+
+ if (defaultOptions.lazy && defaultOptions.waitForThumbnailsBeforeUpload) {
+ throw new Error('ThumbnailGenerator: The `lazy` and `waitForThumbnailsBeforeUpload` options are mutually exclusive. Please ensure at most one of them is set to `true`.')
}
this.opts = { ...defaultOptions, ...opts } | 1 | const { Plugin } = require('@uppy/core')
const Translator = require('@uppy/utils/lib/Translator')
const dataURItoBlob = require('@uppy/utils/lib/dataURItoBlob')
const isObjectURL = require('@uppy/utils/lib/isObjectURL')
const isPreviewSupported = require('@uppy/utils/lib/isPreviewSupported')
const MathLog2 = require('math-log2') // Polyfill for IE.
const exifr = require('exifr/dist/mini.legacy.umd.js')
/**
* The Thumbnail Generator plugin
*/
module.exports = class ThumbnailGenerator extends Plugin {
static VERSION = require('../package.json').version
constructor (uppy, opts) {
super(uppy, opts)
this.type = 'modifier'
this.id = this.opts.id || 'ThumbnailGenerator'
this.title = 'Thumbnail Generator'
this.queue = []
this.queueProcessing = false
this.defaultThumbnailDimension = 200
this.defaultLocale = {
strings: {
generatingThumbnails: 'Generating thumbnails...'
}
}
const defaultOptions = {
thumbnailWidth: null,
thumbnailHeight: null,
waitForThumbnailsBeforeUpload: false
}
this.opts = { ...defaultOptions, ...opts }
this.i18nInit()
}
setOptions (newOpts) {
super.setOptions(newOpts)
this.i18nInit()
}
i18nInit () {
this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale])
this.i18n = this.translator.translate.bind(this.translator)
this.setPluginState() // so that UI re-renders and we see the updated locale
}
/**
* Create a thumbnail for the given Uppy file object.
*
* @param {{data: Blob}} file
* @param {number} targetWidth
* @param {number} targetHeight
* @returns {Promise}
*/
createThumbnail (file, targetWidth, targetHeight) {
const originalUrl = URL.createObjectURL(file.data)
const onload = new Promise((resolve, reject) => {
const image = new Image()
image.src = originalUrl
image.addEventListener('load', () => {
URL.revokeObjectURL(originalUrl)
resolve(image)
})
image.addEventListener('error', (event) => {
URL.revokeObjectURL(originalUrl)
reject(event.error || new Error('Could not create thumbnail'))
})
})
const orientationPromise = exifr.rotation(file.data).catch(_err => 1)
return Promise.all([onload, orientationPromise])
.then(([image, orientation]) => {
const dimensions = this.getProportionalDimensions(image, targetWidth, targetHeight, orientation.deg)
const rotatedImage = this.rotateImage(image, orientation)
const resizedImage = this.resizeImage(rotatedImage, dimensions.width, dimensions.height)
return this.canvasToBlob(resizedImage, 'image/png')
})
.then(blob => {
return URL.createObjectURL(blob)
})
}
/**
* Get the new calculated dimensions for the given image and a target width
* or height. If both width and height are given, only width is taken into
* account. If neither width nor height are given, the default dimension
* is used.
*/
getProportionalDimensions (img, width, height, rotation) {
var aspect = img.width / img.height
if (rotation === 90 || rotation === 270) {
aspect = img.height / img.width
}
if (width != null) {
return {
width: width,
height: Math.round(width / aspect)
}
}
if (height != null) {
return {
width: Math.round(height * aspect),
height: height
}
}
return {
width: this.defaultThumbnailDimension,
height: Math.round(this.defaultThumbnailDimension / aspect)
}
}
/**
* Make sure the image doesn’t exceed browser/device canvas limits.
* For ios with 256 RAM and ie
*/
protect (image) {
// https://stackoverflow.com/questions/6081483/maximum-size-of-a-canvas-element
var ratio = image.width / image.height
var maxSquare = 5000000 // ios max canvas square
var maxSize = 4096 // ie max canvas dimensions
var maxW = Math.floor(Math.sqrt(maxSquare * ratio))
var maxH = Math.floor(maxSquare / Math.sqrt(maxSquare * ratio))
if (maxW > maxSize) {
maxW = maxSize
maxH = Math.round(maxW / ratio)
}
if (maxH > maxSize) {
maxH = maxSize
maxW = Math.round(ratio * maxH)
}
if (image.width > maxW) {
var canvas = document.createElement('canvas')
canvas.width = maxW
canvas.height = maxH
canvas.getContext('2d').drawImage(image, 0, 0, maxW, maxH)
image = canvas
}
return image
}
/**
* Resize an image to the target `width` and `height`.
*
* Returns a Canvas with the resized image on it.
*/
resizeImage (image, targetWidth, targetHeight) {
// Resizing in steps refactored to use a solution from
// https://blog.uploadcare.com/image-resize-in-browsers-is-broken-e38eed08df01
image = this.protect(image)
var steps = Math.ceil(MathLog2(image.width / targetWidth))
if (steps < 1) {
steps = 1
}
var sW = targetWidth * Math.pow(2, steps - 1)
var sH = targetHeight * Math.pow(2, steps - 1)
var x = 2
while (steps--) {
var canvas = document.createElement('canvas')
canvas.width = sW
canvas.height = sH
canvas.getContext('2d').drawImage(image, 0, 0, sW, sH)
image = canvas
sW = Math.round(sW / x)
sH = Math.round(sH / x)
}
return image
}
rotateImage (image, translate) {
var w = image.width
var h = image.height
if (translate.deg === 90 || translate.deg === 270) {
w = image.height
h = image.width
}
var canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
var context = canvas.getContext('2d')
context.translate(w / 2, h / 2)
if (translate.canvas) {
context.rotate(translate.rad)
context.scale(translate.scaleX, translate.scaleY)
}
context.drawImage(image, -image.width / 2, -image.height / 2, image.width, image.height)
return canvas
}
/**
* Save a <canvas> element's content to a Blob object.
*
* @param {HTMLCanvasElement} canvas
* @returns {Promise}
*/
canvasToBlob (canvas, type, quality) {
try {
canvas.getContext('2d').getImageData(0, 0, 1, 1)
} catch (err) {
if (err.code === 18) {
return Promise.reject(new Error('cannot read image, probably an svg with external resources'))
}
}
if (canvas.toBlob) {
return new Promise(resolve => {
canvas.toBlob(resolve, type, quality)
}).then((blob) => {
if (blob === null) {
throw new Error('cannot read image, probably an svg with external resources')
}
return blob
})
}
return Promise.resolve().then(() => {
return dataURItoBlob(canvas.toDataURL(type, quality), {})
}).then((blob) => {
if (blob === null) {
throw new Error('could not extract blob, probably an old browser')
}
return blob
})
}
/**
* Set the preview URL for a file.
*/
setPreviewURL (fileID, preview) {
this.uppy.setFileState(fileID, { preview })
}
addToQueue (item) {
this.queue.push(item)
if (this.queueProcessing === false) {
this.processQueue()
}
}
processQueue () {
this.queueProcessing = true
if (this.queue.length > 0) {
const current = this.queue.shift()
return this.requestThumbnail(current)
.catch(err => {}) // eslint-disable-line handle-callback-err
.then(() => this.processQueue())
} else {
this.queueProcessing = false
this.uppy.log('[ThumbnailGenerator] Emptied thumbnail queue')
this.uppy.emit('thumbnail:all-generated')
}
}
requestThumbnail (file) {
if (isPreviewSupported(file.type) && !file.isRemote) {
return this.createThumbnail(file, this.opts.thumbnailWidth, this.opts.thumbnailHeight)
.then(preview => {
this.setPreviewURL(file.id, preview)
this.uppy.log(`[ThumbnailGenerator] Generated thumbnail for ${file.id}`)
this.uppy.emit('thumbnail:generated', this.uppy.getFile(file.id), preview)
})
.catch(err => {
this.uppy.log(`[ThumbnailGenerator] Failed thumbnail for ${file.id}:`, 'warning')
this.uppy.log(err, 'warning')
this.uppy.emit('thumbnail:error', this.uppy.getFile(file.id), err)
})
}
return Promise.resolve()
}
onFileAdded = (file) => {
if (!file.preview && isPreviewSupported(file.type) && !file.isRemote) {
this.addToQueue(file)
}
}
onFileRemoved = (file) => {
const index = this.queue.indexOf(file)
if (index !== -1) {
this.queue.splice(index, 1)
}
// Clean up object URLs.
if (file.preview && isObjectURL(file.preview)) {
URL.revokeObjectURL(file.preview)
}
}
onRestored = () => {
const { files } = this.uppy.getState()
const fileIDs = Object.keys(files)
fileIDs.forEach((fileID) => {
const file = this.uppy.getFile(fileID)
if (!file.isRestored) return
// Only add blob URLs; they are likely invalid after being restored.
if (!file.preview || isObjectURL(file.preview)) {
this.addToQueue(file)
}
})
}
waitUntilAllProcessed = (fileIDs) => {
fileIDs.forEach((fileID) => {
const file = this.uppy.getFile(fileID)
this.uppy.emit('preprocess-progress', file, {
mode: 'indeterminate',
message: this.i18n('generatingThumbnails')
})
})
const emitPreprocessCompleteForAll = () => {
fileIDs.forEach((fileID) => {
const file = this.uppy.getFile(fileID)
this.uppy.emit('preprocess-complete', file)
})
}
return new Promise((resolve, reject) => {
if (this.queueProcessing) {
this.uppy.once('thumbnail:all-generated', () => {
emitPreprocessCompleteForAll()
resolve()
})
} else {
emitPreprocessCompleteForAll()
resolve()
}
})
}
install () {
this.uppy.on('file-removed', this.onFileRemoved)
this.uppy.on('file-added', this.onFileAdded)
this.uppy.on('restored', this.onRestored)
if (this.opts.waitForThumbnailsBeforeUpload) {
this.uppy.addPreProcessor(this.waitUntilAllProcessed)
}
}
uninstall () {
this.uppy.off('file-removed', this.onFileRemoved)
this.uppy.off('file-added', this.onFileAdded)
this.uppy.off('restored', this.onRestored)
if (this.opts.waitForThumbnailsBeforeUpload) {
this.uppy.removePreProcessor(this.waitUntilAllProcessed)
}
}
}
| 1 | 12,952 | Should be `this.opts` instead of `defaultOptions` | transloadit-uppy | js |
@@ -27,6 +27,7 @@ const pkgVersion = module.exports.version;
const pkgName = module.exports.name;
export const DIST_TAGS = 'dist-tags';
+export const USERS = 'users';
export function getUserAgent(): string {
assert(_.isString(pkgName)); | 1 | // @flow
import _ from 'lodash';
import fs from 'fs';
import assert from 'assert';
import semver from 'semver';
import YAML from 'js-yaml';
import URL from 'url';
import createError from 'http-errors';
import marked from 'marked';
import {
HTTP_STATUS,
API_ERROR,
DEFAULT_PORT,
DEFAULT_DOMAIN,
} from './constants';
import {generateGravatarUrl, GRAVATAR_DEFAULT} from '../utils/user';
import type {Package} from '@verdaccio/types';
import type {$Request} from 'express';
import type {StringValue} from '../../types';
import {normalizeContributors} from './storage-utils';
const Logger = require('./logger');
const pkginfo = require('pkginfo')(module); // eslint-disable-line no-unused-vars
const pkgVersion = module.exports.version;
const pkgName = module.exports.name;
export const DIST_TAGS = 'dist-tags';
export function getUserAgent(): string {
assert(_.isString(pkgName));
assert(_.isString(pkgVersion));
return `${pkgName}/${pkgVersion}`;
}
export function buildBase64Buffer(payload: string): Buffer {
return new Buffer(payload, 'base64');
}
/**
* Validate a package.
* @return {Boolean} whether the package is valid or not
*/
function validate_package(name: any): boolean {
name = name.split('/', 2);
if (name.length === 1) {
// normal package
return validateName(name[0]);
} else {
// scoped package
return (
name[0][0] === '@' &&
validateName(name[0].slice(1)) &&
validateName(name[1])
);
}
}
/**
* From normalize-package-data/lib/fixer.js
* @param {*} name the package name
* @return {Boolean} whether is valid or not
*/
function validateName(name: string): boolean {
if (_.isString(name) === false) {
return false;
}
name = name.toLowerCase();
// all URL-safe characters and "@" for issue #75
return !(
!name.match(/^[-a-zA-Z0-9_.!~*'()@]+$/) ||
name.charAt(0) === '.' || // ".bin", etc.
name.charAt(0) === '-' || // "-" is reserved by couchdb
name === 'node_modules' ||
name === '__proto__' ||
name === 'favicon.ico'
);
}
/**
* Check whether an element is an Object
* @param {*} obj the element
* @return {Boolean}
*/
function isObject(obj: any): boolean {
return _.isObject(obj) && _.isNull(obj) === false && _.isArray(obj) === false;
}
/**
* Validate the package metadata, add additional properties whether are missing within
* the metadata properties.
* @param {*} object
* @param {*} name
* @return {Object} the object with additional properties as dist-tags ad versions
*/
function validate_metadata(object: Package, name: string) {
assert(isObject(object), 'not a json object');
assert.equal(object.name, name);
if (!isObject(object[DIST_TAGS])) {
object[DIST_TAGS] = {};
}
if (!isObject(object['versions'])) {
object['versions'] = {};
}
if (!isObject(object['time'])) {
object['time'] = {};
}
return object;
}
/**
* Create base url for registry.
* @return {String} base registry url
*/
function combineBaseUrl(
protocol: string,
host: string,
prefix?: string
): string {
let result = `${protocol}://${host}`;
if (prefix) {
prefix = prefix.replace(/\/$/, '');
result = prefix.indexOf('/') === 0 ? `${result}${prefix}` : prefix;
}
return result;
}
export function extractTarballFromUrl(url: string) {
// $FlowFixMe
return URL.parse(url).pathname.replace(/^.*\//, '');
}
/**
* Iterate a packages's versions and filter each original tarball url.
* @param {*} pkg
* @param {*} req
* @param {*} config
* @return {String} a filtered package
*/
export function convertDistRemoteToLocalTarballUrls(
pkg: Package,
req: $Request,
urlPrefix: string | void
) {
for (let ver in pkg.versions) {
if (Object.prototype.hasOwnProperty.call(pkg.versions, ver)) {
const distName = pkg.versions[ver].dist;
if (
_.isNull(distName) === false &&
_.isNull(distName.tarball) === false
) {
distName.tarball = getLocalRegistryTarballUri(
distName.tarball,
pkg.name,
req,
urlPrefix
);
}
}
}
return pkg;
}
/**
* Filter a tarball url.
* @param {*} uri
* @return {String} a parsed url
*/
export function getLocalRegistryTarballUri(
uri: string,
pkgName: string,
req: $Request,
urlPrefix: string | void
) {
const currentHost = req.headers.host;
if (!currentHost) {
return uri;
}
const tarballName = extractTarballFromUrl(uri);
const domainRegistry = combineBaseUrl(
getWebProtocol(req),
req.headers.host,
urlPrefix
);
return `${domainRegistry}/${pkgName.replace(/\//g, '%2f')}/-/${tarballName}`;
}
/**
* Create a tag for a package
* @param {*} data
* @param {*} version
* @param {*} tag
* @return {Boolean} whether a package has been tagged
*/
function tagVersion(data: Package, version: string, tag: StringValue) {
if (tag) {
if (data[DIST_TAGS][tag] !== version) {
if (semver.parse(version, true)) {
// valid version - store
data[DIST_TAGS][tag] = version;
return true;
}
}
}
return false;
}
/**
* Gets version from a package object taking into account semver weirdness.
* @return {String} return the semantic version of a package
*/
function getVersion(pkg: Package, version: any) {
// this condition must allow cast
if (pkg.versions[version] != null) {
return pkg.versions[version];
}
try {
version = semver.parse(version, true);
for (let versionItem in pkg.versions) {
// $FlowFixMe
if (version.compare(semver.parse(versionItem, true)) === 0) {
return pkg.versions[versionItem];
}
}
} catch (err) {
return undefined;
}
}
/**
* Parse an internet address
* Allow:
- https:localhost:1234 - protocol + host + port
- localhost:1234 - host + port
- 1234 - port
- http::1234 - protocol + port
- https://localhost:443/ - full url + https
- http://[::1]:443/ - ipv6
- unix:/tmp/http.sock - unix sockets
- https://unix:/tmp/http.sock - unix sockets (https)
* @param {*} urlAddress the internet address definition
* @return {Object|Null} literal object that represent the address parsed
*/
function parse_address(urlAddress: any) {
//
// TODO: refactor it to something more reasonable?
//
// protocol : // ( host )|( ipv6 ): port /
let urlPattern = /^((https?):(\/\/)?)?((([^\/:]*)|\[([^\[\]]+)\]):)?(\d+)\/?$/.exec(
urlAddress
);
if (urlPattern) {
return {
proto: urlPattern[2] || 'http',
host: urlPattern[6] || urlPattern[7] || DEFAULT_DOMAIN,
port: urlPattern[8] || DEFAULT_PORT,
};
}
urlPattern = /^((https?):(\/\/)?)?unix:(.*)$/.exec(urlAddress);
if (urlPattern) {
return {
proto: urlPattern[2] || 'http',
path: urlPattern[4],
};
}
return null;
}
/**
* Function filters out bad semver versions and sorts the array.
* @return {Array} sorted Array
*/
function semverSort(listVersions: Array<string>): string[] {
return listVersions
.filter(function(x) {
if (!semver.parse(x, true)) {
Logger.logger.warn({ver: x}, 'ignoring bad version @{ver}');
return false;
}
return true;
})
.sort(semver.compareLoose)
.map(String);
}
/**
* Flatten arrays of tags.
* @param {*} data
*/
export function normalizeDistTags(pkg: Package) {
let sorted;
if (!pkg[DIST_TAGS].latest) {
// overwrite latest with highest known version based on semver sort
sorted = semverSort(Object.keys(pkg.versions));
if (sorted && sorted.length) {
pkg[DIST_TAGS].latest = sorted.pop();
}
}
for (let tag in pkg[DIST_TAGS]) {
if (_.isArray(pkg[DIST_TAGS][tag])) {
if (pkg[DIST_TAGS][tag].length) {
// sort array
// $FlowFixMe
sorted = semverSort(pkg[DIST_TAGS][tag]);
if (sorted.length) {
// use highest version based on semver sort
pkg[DIST_TAGS][tag] = sorted.pop();
}
} else {
delete pkg[DIST_TAGS][tag];
}
} else if (_.isString(pkg[DIST_TAGS][tag])) {
if (!semver.parse(pkg[DIST_TAGS][tag], true)) {
// if the version is invalid, delete the dist-tag entry
delete pkg[DIST_TAGS][tag];
}
}
}
}
const parseIntervalTable = {
'': 1000,
ms: 1,
s: 1000,
m: 60 * 1000,
h: 60 * 60 * 1000,
d: 86400000,
w: 7 * 86400000,
M: 30 * 86400000,
y: 365 * 86400000,
};
/**
* Parse an internal string to number
* @param {*} interval
* @return {Number}
*/
function parseInterval(interval: any) {
if (typeof interval === 'number') {
return interval * 1000;
}
let result = 0;
let last_suffix = Infinity;
interval.split(/\s+/).forEach(function(x) {
if (!x) return;
let m = x.match(/^((0|[1-9][0-9]*)(\.[0-9]+)?)(ms|s|m|h|d|w|M|y|)$/);
if (
!m ||
parseIntervalTable[m[4]] >= last_suffix ||
(m[4] === '' && last_suffix !== Infinity)
) {
throw Error('invalid interval: ' + interval);
}
last_suffix = parseIntervalTable[m[4]];
result += Number(m[1]) * parseIntervalTable[m[4]];
});
return result;
}
/**
* Detect running protocol (http or https)
* @param {*} req
* @return {String}
*/
function getWebProtocol(req: $Request) {
return req.get('X-Forwarded-Proto') || req.protocol;
}
const getLatestVersion = function(pkgInfo: Package) {
return pkgInfo[DIST_TAGS].latest;
};
const ErrorCode = {
getConflict: (message: string = 'this package is already present') => {
return createError(HTTP_STATUS.CONFLICT, message);
},
getBadData: (customMessage?: string) => {
return createError(HTTP_STATUS.BAD_DATA, customMessage || 'bad data');
},
getBadRequest: (customMessage?: string) => {
return createError(HTTP_STATUS.BAD_REQUEST, customMessage);
},
getInternalError: (customMessage?: string) => {
return customMessage
? createError(HTTP_STATUS.INTERNAL_ERROR, customMessage)
: createError(HTTP_STATUS.INTERNAL_ERROR);
},
getUnauthorized: (message: string = 'no credentials provided') => {
return createError(HTTP_STATUS.UNAUTHORIZED, message);
},
getForbidden: (message: string = 'can\'t use this filename') => {
return createError(HTTP_STATUS.FORBIDDEN, message);
},
getServiceUnavailable: (
message: string = API_ERROR.RESOURCE_UNAVAILABLE
) => {
return createError(HTTP_STATUS.SERVICE_UNAVAILABLE, message);
},
getNotFound: (customMessage?: string) => {
return createError(
HTTP_STATUS.NOT_FOUND,
customMessage || API_ERROR.NO_PACKAGE
);
},
getCode: (statusCode: number, customMessage: string) => {
return createError(statusCode, customMessage);
},
};
const parseConfigFile = (configPath: string) =>
YAML.safeLoad(fs.readFileSync(configPath, 'utf8'));
/**
* Check whether the path already exist.
* @param {String} path
* @return {Boolean}
*/
function folderExists(path: string) {
try {
const stat = fs.statSync(path);
return stat.isDirectory();
} catch (_) {
return false;
}
}
/**
* Check whether the file already exist.
* @param {String} path
* @return {Boolean}
*/
function fileExists(path: string) {
try {
const stat = fs.statSync(path);
return stat.isFile();
} catch (_) {
return false;
}
}
function sortByName(packages: Array<any>): string[] {
return packages.sort(function(a, b) {
if (a.name < b.name) {
return -1;
} else {
return 1;
}
});
}
function addScope(scope: string, packageName: string) {
return `@${scope}/${packageName}`;
}
function deleteProperties(propertiesToDelete: Array<string>, objectItem: any) {
_.forEach(propertiesToDelete, (property) => {
delete objectItem[property];
});
return objectItem;
}
function addGravatarSupport(pkgInfo: Object): Object {
const pkgInfoCopy = {...pkgInfo};
const author = _.get(pkgInfo, 'latest.author', null);
const contributors = normalizeContributors(_.get(pkgInfo, 'latest.contributors', []));
const maintainers = _.get(pkgInfo, 'latest.maintainers', []);
// for author.
if (author && _.isObject(author)) {
pkgInfoCopy.latest.author.avatar = generateGravatarUrl(author.email);
}
if (author && _.isString(author)) {
pkgInfoCopy.latest.author = {
avatar: generateGravatarUrl(),
email: '',
author,
};
}
// for contributors
if (_.isEmpty(contributors) === false) {
pkgInfoCopy.latest.contributors = contributors.map((contributor) => {
if (isObject(contributor)) {
// $FlowFixMe
contributor.avatar = generateGravatarUrl(contributor.email);
} else if (_.isString(contributor)) {
contributor = {
avatar: GRAVATAR_DEFAULT,
email: contributor,
name: contributor,
};
}
return contributor;
});
}
// for maintainers
if (_.isEmpty(maintainers) === false) {
pkgInfoCopy.latest.maintainers = maintainers.map((maintainer) => {
maintainer.avatar = generateGravatarUrl(maintainer.email);
return maintainer;
});
}
return pkgInfoCopy;
}
/**
* parse package readme - markdown/ascii
* @param {String} packageName name of package
* @param {String} readme package readme
* @return {String} converted html template
*/
function parseReadme(packageName: string, readme: string): string {
if (readme) {
return marked(readme);
}
// logs readme not found error
Logger.logger.error({packageName}, '@{packageName}: No readme found');
return marked('ERROR: No README data found!');
}
export function buildToken(type: string, token: string) {
return `${_.capitalize(type)} ${token}`;
}
export {
addGravatarSupport,
deleteProperties,
addScope,
sortByName,
folderExists,
fileExists,
parseInterval,
semverSort,
parse_address,
getVersion,
tagVersion,
combineBaseUrl,
validate_metadata,
isObject,
validateName,
validate_package,
getWebProtocol,
getLatestVersion,
ErrorCode,
parseConfigFile,
parseReadme,
};
| 1 | 19,849 | You can reuse `USERS` above as well. | verdaccio-verdaccio | js |
@@ -460,11 +460,6 @@ public final class Util {
continue;
}
- if (results.size() == topN-1 && maxQueueDepth == topN) {
- // Last path -- don't bother w/ queue anymore:
- queue = null;
- }
-
// We take path and find its "0 output completion",
// ie, just keep traversing the first arc with
// NO_OUTPUT that we can find, since this must lead | 1 | /*
* 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.lucene.util.fst;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.FST.Arc;
import org.apache.lucene.util.fst.FST.BytesReader;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
/** Static helper methods.
*
* @lucene.experimental */
public final class Util {
private Util() {
}
/** Looks up the output for this input, or null if the
* input is not accepted. */
public static<T> T get(FST<T> fst, IntsRef input) throws IOException {
// TODO: would be nice not to alloc this on every lookup
final FST.Arc<T> arc = fst.getFirstArc(new FST.Arc<T>());
final BytesReader fstReader = fst.getBytesReader();
// Accumulate output as we go
T output = fst.outputs.getNoOutput();
for(int i=0;i<input.length;i++) {
if (fst.findTargetArc(input.ints[input.offset + i], arc, arc, fstReader) == null) {
return null;
}
output = fst.outputs.add(output, arc.output());
}
if (arc.isFinal()) {
return fst.outputs.add(output, arc.nextFinalOutput());
} else {
return null;
}
}
// TODO: maybe a CharsRef version for BYTE2
/** Looks up the output for this input, or null if the
* input is not accepted */
public static<T> T get(FST<T> fst, BytesRef input) throws IOException {
assert fst.inputType == FST.INPUT_TYPE.BYTE1;
final BytesReader fstReader = fst.getBytesReader();
// TODO: would be nice not to alloc this on every lookup
final FST.Arc<T> arc = fst.getFirstArc(new FST.Arc<>());
// Accumulate output as we go
T output = fst.outputs.getNoOutput();
for(int i=0;i<input.length;i++) {
if (fst.findTargetArc(input.bytes[i+input.offset] & 0xFF, arc, arc, fstReader) == null) {
return null;
}
output = fst.outputs.add(output, arc.output());
}
if (arc.isFinal()) {
return fst.outputs.add(output, arc.nextFinalOutput());
} else {
return null;
}
}
/** Reverse lookup (lookup by output instead of by input),
* in the special case when your FSTs outputs are
* strictly ascending. This locates the input/output
* pair where the output is equal to the target, and will
* return null if that output does not exist.
*
* <p>NOTE: this only works with {@code FST<Long>}, only
* works when the outputs are ascending in order with
* the inputs.
* For example, simple ordinals (0, 1,
* 2, ...), or file offsets (when appending to a file)
* fit this. */
@Deprecated
public static IntsRef getByOutput(FST<Long> fst, long targetOutput) throws IOException {
final BytesReader in = fst.getBytesReader();
// TODO: would be nice not to alloc this on every lookup
FST.Arc<Long> arc = fst.getFirstArc(new FST.Arc<Long>());
FST.Arc<Long> scratchArc = new FST.Arc<>();
final IntsRefBuilder result = new IntsRefBuilder();
return getByOutput(fst, targetOutput, in, arc, scratchArc, result);
}
/**
* Expert: like {@link Util#getByOutput(FST, long)} except reusing
* BytesReader, initial and scratch Arc, and result.
*/
@Deprecated
public static IntsRef getByOutput(FST<Long> fst, long targetOutput, BytesReader in, Arc<Long> arc, Arc<Long> scratchArc, IntsRefBuilder result) throws IOException {
long output = arc.output();
int upto = 0;
//System.out.println("reverseLookup output=" + targetOutput);
while(true) {
//System.out.println("loop: output=" + output + " upto=" + upto + " arc=" + arc);
if (arc.isFinal()) {
final long finalOutput = output + arc.nextFinalOutput();
//System.out.println(" isFinal finalOutput=" + finalOutput);
if (finalOutput == targetOutput) {
result.setLength(upto);
//System.out.println(" found!");
return result.get();
} else if (finalOutput > targetOutput) {
//System.out.println(" not found!");
return null;
}
}
if (FST.targetHasArcs(arc)) {
//System.out.println(" targetHasArcs");
result.grow(1+upto);
fst.readFirstRealTargetArc(arc.target(), arc, in);
if (arc.bytesPerArc() != 0 && arc.arcIdx() > Integer.MIN_VALUE) {
int low = 0;
int high = arc.numArcs() -1;
int mid = 0;
//System.out.println("bsearch: numArcs=" + arc.numArcs + " target=" + targetOutput + " output=" + output);
boolean exact = false;
while (low <= high) {
mid = (low + high) >>> 1;
in.setPosition(arc.posArcsStart());
in.skipBytes(arc.bytesPerArc() *mid);
final byte flags = in.readByte();
fst.readLabel(in);
final long minArcOutput;
if ((flags & FST.BIT_ARC_HAS_OUTPUT) != 0) {
final long arcOutput = fst.outputs.read(in);
minArcOutput = output + arcOutput;
} else {
minArcOutput = output;
}
//System.out.println(" cycle mid=" + mid + " output=" + minArcOutput);
if (minArcOutput == targetOutput) {
exact = true;
break;
} else if (minArcOutput < targetOutput) {
low = mid + 1;
} else {
high = mid - 1;
}
}
int idx;
if (high == -1) {
return null;
} else if (exact) {
idx = mid;
} else {
idx = low - 1;
}
fst.readArcByIndex(arc, in, idx);
result.setIntAt(upto++, arc.label());
output += arc.output();
} else {
FST.Arc<Long> prevArc = null;
while(true) {
//System.out.println(" cycle label=" + arc.label + " output=" + arc.output);
// This is the min output we'd hit if we follow
// this arc:
final long minArcOutput = output + arc.output();
if (minArcOutput == targetOutput) {
// Recurse on this arc:
//System.out.println(" match! break");
output = minArcOutput;
result.setIntAt(upto++, arc.label());
break;
} else if (minArcOutput > targetOutput) {
if (prevArc == null) {
// Output doesn't exist
return null;
} else {
// Recurse on previous arc:
arc.copyFrom(prevArc);
result.setIntAt(upto++, arc.label());
output += arc.output();
//System.out.println(" recurse prev label=" + (char) arc.label + " output=" + output);
break;
}
} else if (arc.isLast()) {
// Recurse on this arc:
output = minArcOutput;
//System.out.println(" recurse last label=" + (char) arc.label + " output=" + output);
result.setIntAt(upto++, arc.label());
break;
} else {
// Read next arc in this node:
prevArc = scratchArc;
prevArc.copyFrom(arc);
//System.out.println(" after copy label=" + (char) prevArc.label + " vs " + (char) arc.label);
fst.readNextRealArc(arc, in);
}
}
}
} else {
//System.out.println(" no target arcs; not found!");
return null;
}
}
}
/** Represents a path in TopNSearcher.
*
* @lucene.experimental
*/
public static class FSTPath<T> {
/** Holds the last arc appended to this path */
public FST.Arc<T> arc;
/** Holds cost plus any usage-specific output: */
public T output;
public final IntsRefBuilder input;
public final float boost;
public final CharSequence context;
// Custom int payload for consumers; the NRT suggester uses this to record if this path has already enumerated a surface form
public int payload;
FSTPath(T output, FST.Arc<T> arc, IntsRefBuilder input, float boost, CharSequence context, int payload) {
this.arc = new FST.Arc<T>().copyFrom(arc);
this.output = output;
this.input = input;
this.boost = boost;
this.context = context;
this.payload = payload;
}
FSTPath<T> newPath(T output, IntsRefBuilder input) {
return new FSTPath<>(output, this.arc, input, this.boost, this.context, this.payload);
}
@Override
public String toString() {
return "input=" + input.get() + " output=" + output + " context=" + context + " boost=" + boost + " payload=" + payload;
}
}
/** Compares first by the provided comparator, and then
* tie breaks by path.input. */
private static class TieBreakByInputComparator<T> implements Comparator<FSTPath<T>> {
private final Comparator<T> comparator;
TieBreakByInputComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
@Override
public int compare(FSTPath<T> a, FSTPath<T> b) {
int cmp = comparator.compare(a.output, b.output);
if (cmp == 0) {
return a.input.get().compareTo(b.input.get());
} else {
return cmp;
}
}
}
/** Utility class to find top N shortest paths from start
* point(s). */
public static class TopNSearcher<T> {
private final FST<T> fst;
private final BytesReader bytesReader;
private final int topN;
private final int maxQueueDepth;
private final FST.Arc<T> scratchArc = new FST.Arc<>();
private final Comparator<T> comparator;
private final Comparator<FSTPath<T>> pathComparator;
TreeSet<FSTPath<T>> queue;
/**
* Creates an unbounded TopNSearcher
* @param fst the {@link org.apache.lucene.util.fst.FST} to search on
* @param topN the number of top scoring entries to retrieve
* @param maxQueueDepth the maximum size of the queue of possible top entries
* @param comparator the comparator to select the top N
*/
public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, Comparator<T> comparator) {
this(fst, topN, maxQueueDepth, comparator, new TieBreakByInputComparator<>(comparator));
}
public TopNSearcher(FST<T> fst, int topN, int maxQueueDepth, Comparator<T> comparator,
Comparator<FSTPath<T>> pathComparator) {
this.fst = fst;
this.bytesReader = fst.getBytesReader();
this.topN = topN;
this.maxQueueDepth = maxQueueDepth;
this.comparator = comparator;
this.pathComparator = pathComparator;
queue = new TreeSet<>(pathComparator);
}
// If back plus this arc is competitive then add to queue:
protected void addIfCompetitive(FSTPath<T> path) {
assert queue != null;
T output = fst.outputs.add(path.output, path.arc.output());
if (queue.size() == maxQueueDepth) {
FSTPath<T> bottom = queue.last();
int comp = pathComparator.compare(path, bottom);
if (comp > 0) {
// Doesn't compete
return;
} else if (comp == 0) {
// Tie break by alpha sort on the input:
path.input.append(path.arc.label());
final int cmp = bottom.input.get().compareTo(path.input.get());
path.input.setLength(path.input.length() - 1);
// We should never see dups:
assert cmp != 0;
if (cmp < 0) {
// Doesn't compete
return;
}
}
// Competes
}
// else ... Queue isn't full yet, so any path we hit competes:
// copy over the current input to the new input
// and add the arc.label to the end
IntsRefBuilder newInput = new IntsRefBuilder();
newInput.copyInts(path.input.get());
newInput.append(path.arc.label());
FSTPath<T> newPath = path.newPath(output, newInput);
if (acceptPartialPath(newPath)) {
queue.add(newPath);
if (queue.size() == maxQueueDepth+1) {
queue.pollLast();
}
}
}
public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRefBuilder input) throws IOException {
addStartPaths(node, startOutput, allowEmptyString, input, 0, null, -1);
}
/** Adds all leaving arcs, including 'finished' arc, if
* the node is final, from this node into the queue. */
public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRefBuilder input,
float boost, CharSequence context, int payload) throws IOException {
// De-dup NO_OUTPUT since it must be a singleton:
if (startOutput.equals(fst.outputs.getNoOutput())) {
startOutput = fst.outputs.getNoOutput();
}
FSTPath<T> path = new FSTPath<>(startOutput, node, input, boost, context, payload);
fst.readFirstTargetArc(node, path.arc, bytesReader);
// Bootstrap: find the min starting arc
while (true) {
if (allowEmptyString || path.arc.label() != FST.END_LABEL) {
addIfCompetitive(path);
}
if (path.arc.isLast()) {
break;
}
fst.readNextArc(path.arc, bytesReader);
}
}
public TopResults<T> search() throws IOException {
final List<Result<T>> results = new ArrayList<>();
final BytesReader fstReader = fst.getBytesReader();
final T NO_OUTPUT = fst.outputs.getNoOutput();
// TODO: we could enable FST to sorting arcs by weight
// as it freezes... can easily do this on first pass
// (w/o requiring rewrite)
// TODO: maybe we should make an FST.INPUT_TYPE.BYTE0.5!?
// (nibbles)
int rejectCount = 0;
// For each top N path:
while (results.size() < topN) {
FSTPath<T> path;
if (queue == null) {
// Ran out of paths
break;
}
// Remove top path since we are now going to
// pursue it:
path = queue.pollFirst();
if (path == null) {
// There were less than topN paths available:
break;
}
//System.out.println("pop path=" + path + " arc=" + path.arc.output);
if (acceptPartialPath(path) == false) {
continue;
}
if (path.arc.label() == FST.END_LABEL) {
// Empty string!
path.input.setLength(path.input.length() - 1);
results.add(new Result<>(path.input.get(), path.output));
continue;
}
if (results.size() == topN-1 && maxQueueDepth == topN) {
// Last path -- don't bother w/ queue anymore:
queue = null;
}
// We take path and find its "0 output completion",
// ie, just keep traversing the first arc with
// NO_OUTPUT that we can find, since this must lead
// to the minimum path that completes from
// path.arc.
// For each input letter:
while (true) {
fst.readFirstTargetArc(path.arc, path.arc, fstReader);
// For each arc leaving this node:
boolean foundZero = false;
while(true) {
// tricky: instead of comparing output == 0, we must
// express it via the comparator compare(output, 0) == 0
if (comparator.compare(NO_OUTPUT, path.arc.output()) == 0) {
if (queue == null) {
foundZero = true;
break;
} else if (!foundZero) {
scratchArc.copyFrom(path.arc);
foundZero = true;
} else {
addIfCompetitive(path);
}
} else if (queue != null) {
addIfCompetitive(path);
}
if (path.arc.isLast()) {
break;
}
fst.readNextArc(path.arc, fstReader);
}
assert foundZero;
if (queue != null) {
// TODO: maybe we can save this copyFrom if we
// are more clever above... eg on finding the
// first NO_OUTPUT arc we'd switch to using
// scratchArc
path.arc.copyFrom(scratchArc);
}
if (path.arc.label() == FST.END_LABEL) {
// Add final output:
path.output = fst.outputs.add(path.output, path.arc.output());
if (acceptResult(path)) {
results.add(new Result<>(path.input.get(), path.output));
} else {
rejectCount++;
}
break;
} else {
path.input.append(path.arc.label());
path.output = fst.outputs.add(path.output, path.arc.output());
if (acceptPartialPath(path) == false) {
break;
}
}
}
}
return new TopResults<>(rejectCount + topN <= maxQueueDepth, results);
}
protected boolean acceptResult(FSTPath<T> path) {
return acceptResult(path.input.get(), path.output);
}
/** Override this to prevent considering a path before it's complete */
protected boolean acceptPartialPath(FSTPath<T> path) {
return true;
}
protected boolean acceptResult(IntsRef input, T output) {
return true;
}
}
/** Holds a single input (IntsRef) + output, returned by
* {@link #shortestPaths shortestPaths()}. */
public final static class Result<T> {
public final IntsRef input;
public final T output;
public Result(IntsRef input, T output) {
this.input = input;
this.output = output;
}
}
/**
* Holds the results for a top N search using {@link TopNSearcher}
*/
public static final class TopResults<T> implements Iterable<Result<T>> {
/**
* <code>true</code> iff this is a complete result ie. if
* the specified queue size was large enough to find the complete list of results. This might
* be <code>false</code> if the {@link TopNSearcher} rejected too many results.
*/
public final boolean isComplete;
/**
* The top results
*/
public final List<Result<T>> topN;
TopResults(boolean isComplete, List<Result<T>> topN) {
this.topN = topN;
this.isComplete = isComplete;
}
@Override
public Iterator<Result<T>> iterator() {
return topN.iterator();
}
}
/** Starting from node, find the top N min cost
* completions to a final node. */
public static <T> TopResults<T> shortestPaths(FST<T> fst, FST.Arc<T> fromNode, T startOutput, Comparator<T> comparator, int topN,
boolean allowEmptyString) throws IOException {
// All paths are kept, so we can pass topN for
// maxQueueDepth and the pruning is admissible:
TopNSearcher<T> searcher = new TopNSearcher<>(fst, topN, topN, comparator);
// since this search is initialized with a single start node
// it is okay to start with an empty input path here
searcher.addStartPaths(fromNode, startOutput, allowEmptyString, new IntsRefBuilder());
return searcher.search();
}
/**
* Dumps an {@link FST} to a GraphViz's <code>dot</code> language description
* for visualization. Example of use:
*
* <pre class="prettyprint">
* PrintWriter pw = new PrintWriter("out.dot");
* Util.toDot(fst, pw, true, true);
* pw.close();
* </pre>
*
* and then, from command line:
*
* <pre>
* dot -Tpng -o out.png out.dot
* </pre>
*
* <p>
* Note: larger FSTs (a few thousand nodes) won't even
* render, don't bother.
*
* @param sameRank
* If <code>true</code>, the resulting <code>dot</code> file will try
* to order states in layers of breadth-first traversal. This may
* mess up arcs, but makes the output FST's structure a bit clearer.
*
* @param labelStates
* If <code>true</code> states will have labels equal to their offsets in their
* binary format. Expands the graph considerably.
*
* @see <a href="http://www.graphviz.org/">graphviz project</a>
*/
public static <T> void toDot(FST<T> fst, Writer out, boolean sameRank, boolean labelStates)
throws IOException {
final String expandedNodeColor = "blue";
// This is the start arc in the automaton (from the epsilon state to the first state
// with outgoing transitions.
final FST.Arc<T> startArc = fst.getFirstArc(new FST.Arc<>());
// A queue of transitions to consider for the next level.
final List<FST.Arc<T>> thisLevelQueue = new ArrayList<>();
// A queue of transitions to consider when processing the next level.
final List<FST.Arc<T>> nextLevelQueue = new ArrayList<>();
nextLevelQueue.add(startArc);
//System.out.println("toDot: startArc: " + startArc);
// A list of states on the same level (for ranking).
final List<Integer> sameLevelStates = new ArrayList<>();
// A bitset of already seen states (target offset).
final BitSet seen = new BitSet();
seen.set((int) startArc.target());
// Shape for states.
final String stateShape = "circle";
final String finalStateShape = "doublecircle";
// Emit DOT prologue.
out.write("digraph FST {\n");
out.write(" rankdir = LR; splines=true; concentrate=true; ordering=out; ranksep=2.5; \n");
if (!labelStates) {
out.write(" node [shape=circle, width=.2, height=.2, style=filled]\n");
}
emitDotState(out, "initial", "point", "white", "");
final T NO_OUTPUT = fst.outputs.getNoOutput();
final BytesReader r = fst.getBytesReader();
// final FST.Arc<T> scratchArc = new FST.Arc<>();
{
final String stateColor;
if (fst.isExpandedTarget(startArc, r)) {
stateColor = expandedNodeColor;
} else {
stateColor = null;
}
final boolean isFinal;
final T finalOutput;
if (startArc.isFinal()) {
isFinal = true;
finalOutput = startArc.nextFinalOutput() == NO_OUTPUT ? null : startArc.nextFinalOutput();
} else {
isFinal = false;
finalOutput = null;
}
emitDotState(out, Long.toString(startArc.target()), isFinal ? finalStateShape : stateShape, stateColor, finalOutput == null ? "" : fst.outputs.outputToString(finalOutput));
}
out.write(" initial -> " + startArc.target() + "\n");
int level = 0;
while (!nextLevelQueue.isEmpty()) {
// we could double buffer here, but it doesn't matter probably.
//System.out.println("next level=" + level);
thisLevelQueue.addAll(nextLevelQueue);
nextLevelQueue.clear();
level++;
out.write("\n // Transitions and states at level: " + level + "\n");
while (!thisLevelQueue.isEmpty()) {
final FST.Arc<T> arc = thisLevelQueue.remove(thisLevelQueue.size() - 1);
//System.out.println(" pop: " + arc);
if (FST.targetHasArcs(arc)) {
// scan all target arcs
//System.out.println(" readFirstTarget...");
final long node = arc.target();
fst.readFirstRealTargetArc(arc.target(), arc, r);
//System.out.println(" firstTarget: " + arc);
while (true) {
//System.out.println(" cycle arc=" + arc);
// Emit the unseen state and add it to the queue for the next level.
if (arc.target() >= 0 && !seen.get((int) arc.target())) {
/*
boolean isFinal = false;
T finalOutput = null;
fst.readFirstTargetArc(arc, scratchArc);
if (scratchArc.isFinal() && fst.targetHasArcs(scratchArc)) {
// target is final
isFinal = true;
finalOutput = scratchArc.output == NO_OUTPUT ? null : scratchArc.output;
System.out.println("dot hit final label=" + (char) scratchArc.label);
}
*/
final String stateColor;
if (fst.isExpandedTarget(arc, r)) {
stateColor = expandedNodeColor;
} else {
stateColor = null;
}
final String finalOutput;
if (arc.nextFinalOutput() != null && arc.nextFinalOutput() != NO_OUTPUT) {
finalOutput = fst.outputs.outputToString(arc.nextFinalOutput());
} else {
finalOutput = "";
}
emitDotState(out, Long.toString(arc.target()), stateShape, stateColor, finalOutput);
// To see the node address, use this instead:
//emitDotState(out, Integer.toString(arc.target), stateShape, stateColor, String.valueOf(arc.target));
seen.set((int) arc.target());
nextLevelQueue.add(new FST.Arc<T>().copyFrom(arc));
sameLevelStates.add((int) arc.target());
}
String outs;
if (arc.output() != NO_OUTPUT) {
outs = "/" + fst.outputs.outputToString(arc.output());
} else {
outs = "";
}
if (!FST.targetHasArcs(arc) && arc.isFinal() && arc.nextFinalOutput() != NO_OUTPUT) {
// Tricky special case: sometimes, due to
// pruning, the builder can [sillily] produce
// an FST with an arc into the final end state
// (-1) but also with a next final output; in
// this case we pull that output up onto this
// arc
outs = outs + "/[" + fst.outputs.outputToString(arc.nextFinalOutput()) + "]";
}
final String arcColor;
if (arc.flag(FST.BIT_TARGET_NEXT)) {
arcColor = "red";
} else {
arcColor = "black";
}
assert arc.label() != FST.END_LABEL;
out.write(" " + node + " -> " + arc.target() + " [label=\"" + printableLabel(arc.label()) + outs + "\"" + (arc.isFinal() ? " style=\"bold\"" : "" ) + " color=\"" + arcColor + "\"]\n");
// Break the loop if we're on the last arc of this state.
if (arc.isLast()) {
//System.out.println(" break");
break;
}
fst.readNextRealArc(arc, r);
}
}
}
// Emit state ranking information.
if (sameRank && sameLevelStates.size() > 1) {
out.write(" {rank=same; ");
for (int state : sameLevelStates) {
out.write(state + "; ");
}
out.write(" }\n");
}
sameLevelStates.clear();
}
// Emit terminating state (always there anyway).
out.write(" -1 [style=filled, color=black, shape=doublecircle, label=\"\"]\n\n");
out.write(" {rank=sink; -1 }\n");
out.write("}\n");
out.flush();
}
/**
* Emit a single state in the <code>dot</code> language.
*/
private static void emitDotState(Writer out, String name, String shape,
String color, String label) throws IOException {
out.write(" " + name
+ " ["
+ (shape != null ? "shape=" + shape : "") + " "
+ (color != null ? "color=" + color : "") + " "
+ (label != null ? "label=\"" + label + "\"" : "label=\"\"") + " "
+ "]\n");
}
/**
* Ensures an arc's label is indeed printable (dot uses US-ASCII).
*/
private static String printableLabel(int label) {
// Any ordinary ascii character, except for " or \, are
// printed as the character; else, as a hex string:
if (label >= 0x20 && label <= 0x7d && label != 0x22 && label != 0x5c) { // " OR \
return Character.toString((char) label);
}
return "0x" + Integer.toHexString(label);
}
/** Just maps each UTF16 unit (char) to the ints in an
* IntsRef. */
public static IntsRef toUTF16(CharSequence s, IntsRefBuilder scratch) {
final int charLimit = s.length();
scratch.setLength(charLimit);
scratch.grow(charLimit);
for (int idx = 0; idx < charLimit; idx++) {
scratch.setIntAt(idx, (int) s.charAt(idx));
}
return scratch.get();
}
/** Decodes the Unicode codepoints from the provided
* CharSequence and places them in the provided scratch
* IntsRef, which must not be null, returning it. */
public static IntsRef toUTF32(CharSequence s, IntsRefBuilder scratch) {
int charIdx = 0;
int intIdx = 0;
final int charLimit = s.length();
while(charIdx < charLimit) {
scratch.grow(intIdx+1);
final int utf32 = Character.codePointAt(s, charIdx);
scratch.setIntAt(intIdx, utf32);
charIdx += Character.charCount(utf32);
intIdx++;
}
scratch.setLength(intIdx);
return scratch.get();
}
/** Decodes the Unicode codepoints from the provided
* char[] and places them in the provided scratch
* IntsRef, which must not be null, returning it. */
public static IntsRef toUTF32(char[] s, int offset, int length, IntsRefBuilder scratch) {
int charIdx = offset;
int intIdx = 0;
final int charLimit = offset + length;
while(charIdx < charLimit) {
scratch.grow(intIdx+1);
final int utf32 = Character.codePointAt(s, charIdx, charLimit);
scratch.setIntAt(intIdx, utf32);
charIdx += Character.charCount(utf32);
intIdx++;
}
scratch.setLength(intIdx);
return scratch.get();
}
/** Just takes unsigned byte values from the BytesRef and
* converts into an IntsRef. */
public static IntsRef toIntsRef(BytesRef input, IntsRefBuilder scratch) {
scratch.clear();
for(int i=0;i<input.length;i++) {
scratch.append(input.bytes[i+input.offset] & 0xFF);
}
return scratch.get();
}
/** Just converts IntsRef to BytesRef; you must ensure the
* int values fit into a byte. */
public static BytesRef toBytesRef(IntsRef input, BytesRefBuilder scratch) {
scratch.grow(input.length);
for(int i=0;i<input.length;i++) {
int value = input.ints[i+input.offset];
// NOTE: we allow -128 to 255
assert value >= Byte.MIN_VALUE && value <= 255: "value " + value + " doesn't fit into byte";
scratch.setByteAt(i, (byte) value);
}
scratch.setLength(input.length);
return scratch.get();
}
// Uncomment for debugging:
/*
public static <T> void dotToFile(FST<T> fst, String filePath) throws IOException {
Writer w = new OutputStreamWriter(new FileOutputStream(filePath));
toDot(fst, w, true, true);
w.close();
}
*/
/**
* Reads the first arc greater or equal than the given label into the provided
* arc in place and returns it iff found, otherwise return <code>null</code>.
*
* @param label the label to ceil on
* @param fst the fst to operate on
* @param follow the arc to follow reading the label from
* @param arc the arc to read into in place
* @param in the fst's {@link BytesReader}
*/
public static <T> Arc<T> readCeilArc(int label, FST<T> fst, Arc<T> follow, Arc<T> arc, BytesReader in) throws IOException {
if (label == FST.END_LABEL) {
return FST.readEndArc(follow, arc);
}
if (!FST.targetHasArcs(follow)) {
return null;
}
fst.readFirstTargetArc(follow, arc, in);
if (arc.bytesPerArc() != 0 && arc.label() != FST.END_LABEL) {
if (arc.arcIdx() == Integer.MIN_VALUE) {
// Arcs are in an array-with-gaps
int offset = label - arc.label();
if (offset >= arc.numArcs()) {
return null;
} else if (offset < 0) {
return arc;
} else {
return fst.readArcAtPosition(arc, in, arc.posArcsStart() - offset * arc.bytesPerArc());
}
}
// Arcs are packed array -- use binary search to find the target.
int idx = binarySearch(fst, arc, label);
if (idx >= 0) {
return fst.readArcByIndex(arc, in, idx);
}
idx = -1 - idx;
if (idx == arc.numArcs()) {
// DEAD END!
return null;
}
return fst.readArcByIndex(arc, in , idx);
}
// Linear scan
fst.readFirstRealTargetArc(follow.target(), arc, in);
while (true) {
// System.out.println(" non-bs cycle");
// TODO: we should fix this code to not have to create
// object for the output of every arc we scan... only
// for the matching arc, if found
if (arc.label() >= label) {
// System.out.println(" found!");
return arc;
} else if (arc.isLast()) {
return null;
} else {
fst.readNextRealArc(arc, in);
}
}
}
/**
* Perform a binary search of Arcs encoded as a packed array
* @param fst the FST from which to read
* @param arc the starting arc; sibling arcs greater than this will be searched. Usually the first arc in the array.
* @param targetLabel the label to search for
* @param <T> the output type of the FST
* @return the index of the Arc having the target label, or if no Arc has the matching label, {@code -1 - idx)},
* where {@code idx} is the index of the Arc with the next highest label, or the total number of arcs
* if the target label exceeds the maximum.
* @throws IOException when the FST reader does
*/
static <T> int binarySearch(FST<T> fst, FST.Arc<T> arc, int targetLabel) throws IOException {
BytesReader in = fst.getBytesReader();
int low = arc.arcIdx();
int mid = 0;
int high = arc.numArcs() -1;
while (low <= high) {
mid = (low + high) >>> 1;
in.setPosition(arc.posArcsStart());
in.skipBytes(arc.bytesPerArc() * mid + 1);
final int midLabel = fst.readLabel(in);
final int cmp = midLabel - targetLabel;
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return mid;
}
}
return -1 - low;
}
}
| 1 | 30,652 | Whoa, was this opto breaking something? I guess if this final path is filtered out, we still need the queue? Have you run the suggest benchmarks to see if removing this opto hurt performance? | apache-lucene-solr | java |
@@ -191,7 +191,7 @@ final class Collections {
if (iterable instanceof Seq) {
return (Seq<T>) iterable;
} else {
- return List.ofAll(iterable);
+ return Stream.ofAll(iterable);
}
}
} | 1 | /* / \____ _ _ ____ ______ / \ ____ __ _______
* / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG
* _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io
* /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0
*/
package javaslang.collection;
import javaslang.control.Option;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
* Internal class, containing helpers.
*
* @author Daniel Dietrich
* @since 2.0.0
*/
final class Collections {
@SuppressWarnings("unchecked")
static <C extends Traversable<T>, T> C removeAll(C collection, T element) {
Objects.requireNonNull(element, "element is null");
return removeAll(collection, List.of(element));
}
@SuppressWarnings("unchecked")
static <C extends Traversable<T>, T> C removeAll(C collection, Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
final Set<T> removed = HashSet.ofAll(elements);
return (C) collection.filter(e -> !removed.contains(e));
}
@SuppressWarnings("unchecked")
static <C extends Traversable<T>, T> C removeAll(C collection, Predicate<? super T> predicate) {
Objects.requireNonNull(predicate, "predicate is null");
return (C) collection.filter(predicate.negate());
}
@SuppressWarnings("unchecked")
static <C extends Traversable<T>, T> C retainAll(C collection, Iterable<? extends T> elements) {
Objects.requireNonNull(elements, "elements is null");
final Set<T> removed = HashSet.ofAll(elements);
return (C) collection.filter(removed::contains);
}
public static <T, C, R extends Iterable<T>> Map<C, R> groupBy(Traversable<T> collection, Function<? super T, ? extends C> classifier, Function<? super Iterable<T>, R> mapper) {
Objects.requireNonNull(collection, "collection is null");
Objects.requireNonNull(classifier, "classifier is null");
Objects.requireNonNull(mapper, "mapper is null");
final java.util.Map<C, Collection<T>> mutableResults = new java.util.LinkedHashMap<>();
for (T value : collection) {
final C key = classifier.apply(value);
mutableResults.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}
Map<C, R> results = LinkedHashMap.empty();
for (java.util.Map.Entry<C, Collection<T>> entry : mutableResults.entrySet()) {
results = results.put(entry.getKey(), mapper.apply(entry.getValue()));
}
return results;
}
@SuppressWarnings("unchecked")
public static <K, V, K2, U extends Map<K2, V>> U mapKeys(Map<K, V> source, U zero, Function<? super K, ? extends K2> keyMapper, BiFunction<? super V, ? super V, ? extends V> valueMerge) {
Objects.requireNonNull(source, "source is null");
Objects.requireNonNull(zero, "zero is null");
Objects.requireNonNull(keyMapper, "keyMapper is null");
Objects.requireNonNull(valueMerge, "valueMerge is null");
return source.foldLeft(zero, (acc, entry) -> {
final K2 k2 = keyMapper.apply(entry._1);
final V v2 = entry._2;
final Option<V> v1 = acc.get(k2);
final V v = v1.isDefined() ? valueMerge.apply(v1.get(), v2) : v2;
return (U) acc.put(k2, v);
});
}
static Option<Integer> indexOption(int index) {
return Option.when(index >= 0, index);
}
// checks, if the *elements* of the given iterables are equal
static boolean areEqual(Iterable<?> iterable1, Iterable<?> iterable2) {
final java.util.Iterator<?> iter1 = iterable1.iterator();
final java.util.Iterator<?> iter2 = iterable2.iterator();
while (iter1.hasNext() && iter2.hasNext()) {
if (!Objects.equals(iter1.next(), iter2.next())) {
return false;
}
}
return iter1.hasNext() == iter2.hasNext();
}
// hashes the elements of an iterable
static int hash(Iterable<?> iterable) {
int hashCode = 1;
for (Object o : iterable) {
hashCode = 31 * hashCode + Objects.hashCode(o);
}
return hashCode;
}
static <T, U, C extends Iterable<U>, R extends Traversable<U>> R scanLeft(Iterable<? extends T> elements,
U zero, BiFunction<? super U, ? super T, ? extends U> operation,
C cumulativeResult, BiFunction<C, U, C> combiner,
Function<C, R> finisher) {
U acc = zero;
cumulativeResult = combiner.apply(cumulativeResult, acc);
for (T a : elements) {
acc = operation.apply(acc, a);
cumulativeResult = combiner.apply(cumulativeResult, acc);
}
return finisher.apply(cumulativeResult);
}
static <T, U, C extends Iterable<U>, R extends Traversable<U>> R scanRight(Iterable<? extends T> elements,
U zero, BiFunction<? super T, ? super U, ? extends U> operation,
C cumulativeResult, BiFunction<C, U, C> combiner,
Function<C, R> finisher) {
final Iterator<? extends T> reversedElements = seq(elements).reverseIterator(); // TODO a List will be reversed too many times this way
return scanLeft(reversedElements, zero, (u, t) -> operation.apply(t, u), cumulativeResult, combiner, finisher);
}
@SuppressWarnings("unchecked")
static <T, S extends Seq<T>> Iterator<S> crossProduct(S empty, S seq, int power) {
if (power < 0) {
return Iterator.empty();
}
return Iterator.range(0, power)
.foldLeft(Iterator.of(empty), (product, ignored) -> product.flatMap(el -> seq.map(t -> (S) el.append(t))));
}
static <C extends Traversable<T>, T> C tabulate(int n, Function<? super Integer, ? extends T> f, C empty, Function<T[], C> of) {
Objects.requireNonNull(f, "f is null");
Objects.requireNonNull(empty, "empty is null");
Objects.requireNonNull(of, "of is null");
if (n <= 0) {
return empty;
} else {
@SuppressWarnings("unchecked")
final T[] elements = (T[]) new Object[n];
for (int i = 0; i < n; i++) {
elements[i] = f.apply(i);
}
return of.apply(elements);
}
}
static <C extends Traversable<T>, T> C fill(int n, Supplier<? extends T> s, C empty, Function<T[], C> of) {
Objects.requireNonNull(s, "s is null");
Objects.requireNonNull(empty, "empty is null");
Objects.requireNonNull(of, "of is null");
return tabulate(n, anything -> s.get(), empty, of);
}
static <T> Iterator<T> tabulate(int n, Function<? super Integer, ? extends T> f) {
Objects.requireNonNull(f, "f is null");
if (n <= 0) {
return Iterator.empty();
} else {
return new AbstractIterator<T>() {
int i = 0;
@Override
public boolean hasNext() {
return i < n;
}
@Override
protected T getNext() {
return f.apply(i++);
}
};
}
}
static <T> Iterator<T> fill(int n, Supplier<? extends T> supplier) {
Objects.requireNonNull(supplier, "supplier is null");
return tabulate(n, ignored -> supplier.get());
}
@SuppressWarnings("unchecked")
static <T> Seq<T> seq(Iterable<? extends T> iterable) {
if (iterable instanceof Seq) {
return (Seq<T>) iterable;
} else {
return List.ofAll(iterable);
}
}
}
| 1 | 10,360 | I'm not sure about this, please check the usages. It's only used currently to reverse it, maybe we should eliminate this method completely instead. | vavr-io-vavr | java |
@@ -638,6 +638,18 @@ class AbstractBase extends AbstractActionController
return $check->getTagSetting() !== 'disabled';
}
+ /**
+ * Are list tags enabled?
+ *
+ * @return bool
+ */
+ protected function listTagsEnabled()
+ {
+ $check = $this->serviceLocator
+ ->get(\VuFind\Config\AccountCapabilities::class);
+ return $check->getListTagSetting() === 'enabled';
+ }
+
/**
* Store a referer (if appropriate) to keep post-login redirect pointing
* to an appropriate location. This is used when the user clicks the | 1 | <?php
/**
* VuFind controller base class (defines some methods that can be shared by other
* controllers).
*
* PHP version 7
*
* Copyright (C) Villanova University 2010.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Controller
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:controllers Wiki
*/
namespace VuFind\Controller;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\MvcEvent;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Laminas\View\Model\ViewModel;
use VuFind\Exception\Auth as AuthException;
use VuFind\Exception\ILS as ILSException;
use VuFind\Http\PhpEnvironment\Request as HttpRequest;
use ZfcRbac\Service\AuthorizationServiceAwareInterface;
/**
* VuFind controller base class (defines some methods that can be shared by other
* controllers).
*
* @category VuFind
* @package Controller
* @author Chris Hallberg <challber@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:controllers Wiki
*
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/
class AbstractBase extends AbstractActionController
{
/**
* Permission that must be granted to access this module (false for no
* restriction, null to use configured default (which is usually the same
* as false)).
*
* @var string|bool
*/
protected $accessPermission = null;
/**
* Behavior when access is denied (used unless overridden through
* permissionBehavior.ini). Valid values are 'promptLogin' and 'exception'.
* Leave at null to use the defaultDeniedControllerBehavior set in
* permissionBehavior.ini (normally 'promptLogin' unless changed).
*
* @var string
*/
protected $accessDeniedBehavior = null;
/**
* Service manager
*
* @var ServiceLocatorInterface
*/
protected $serviceLocator;
/**
* Constructor
*
* @param ServiceLocatorInterface $sm Service locator
*/
public function __construct(ServiceLocatorInterface $sm)
{
$this->serviceLocator = $sm;
}
/**
* Use preDispatch event to block access when appropriate.
*
* @param MvcEvent $e Event object
*
* @return void
*/
public function validateAccessPermission(MvcEvent $e)
{
// If there is an access permission set for this controller, pass it
// through the permission helper, and if the helper returns a custom
// response, use that instead of the normal behavior.
if ($this->accessPermission) {
$response = $this->permission()
->check($this->accessPermission, $this->accessDeniedBehavior);
if (is_object($response)) {
$e->setResponse($response);
}
}
}
/**
* Getter for access permission.
*
* @return string|bool
*/
public function getAccessPermission()
{
return $this->accessPermission;
}
/**
* Getter for access permission.
*
* @param string $ap Permission to require for access to the controller (false
* for no requirement)
*
* @return void
*/
public function setAccessPermission($ap)
{
$this->accessPermission = empty($ap) ? false : $ap;
}
/**
* Get request object
*
* @return HttpRequest
*/
public function getRequest()
{
if (!$this->request) {
$this->request = new HttpRequest();
}
return $this->request;
}
/**
* Register the default events for this controller
*
* @return void
*/
protected function attachDefaultListeners()
{
parent::attachDefaultListeners();
// Attach preDispatch event if we need to check permissions.
if ($this->accessPermission) {
$events = $this->getEventManager();
$events->attach(
MvcEvent::EVENT_DISPATCH, [$this, 'validateAccessPermission'], 1000
);
}
}
/**
* Create a new ViewModel.
*
* @param array $params Parameters to pass to ViewModel constructor.
*
* @return ViewModel
*/
protected function createViewModel($params = null)
{
if ($this->inLightbox()) {
$this->layout()->setTemplate('layout/lightbox');
$params['inLightbox'] = true;
}
return new ViewModel($params);
}
/**
* Create a new ViewModel to use as an email form.
*
* @param array $params Parameters to pass to ViewModel constructor.
* @param string $defaultSubject Default subject line to use.
*
* @return ViewModel
*/
protected function createEmailViewModel($params = null, $defaultSubject = null)
{
// Build view:
$view = $this->createViewModel($params);
// Load configuration and current user for convenience:
$config = $this->getConfig();
$view->disableFrom
= (isset($config->Mail->disable_from) && $config->Mail->disable_from);
$view->editableSubject = isset($config->Mail->user_editable_subjects)
&& $config->Mail->user_editable_subjects;
$view->maxRecipients = isset($config->Mail->maximum_recipients)
? intval($config->Mail->maximum_recipients) : 1;
$user = $this->getUser();
// Send parameters back to view so form can be re-populated:
if ($this->getRequest()->isPost()) {
$view->to = $this->params()->fromPost('to');
if (!$view->disableFrom) {
$view->from = $this->params()->fromPost('from');
}
if ($view->editableSubject) {
$view->subject = $this->params()->fromPost('subject');
}
$view->message = $this->params()->fromPost('message');
}
// Set default values if applicable:
if ((!isset($view->to) || empty($view->to)) && $user
&& isset($config->Mail->user_email_in_to)
&& $config->Mail->user_email_in_to
) {
$view->to = $user->email;
}
if (!isset($view->from) || empty($view->from)) {
if ($user && isset($config->Mail->user_email_in_from)
&& $config->Mail->user_email_in_from
) {
$view->userEmailInFrom = true;
$view->from = $user->email;
} elseif (isset($config->Mail->default_from)
&& $config->Mail->default_from
) {
$view->from = $config->Mail->default_from;
}
}
if (!isset($view->subject) || empty($view->subject)) {
$view->subject = $defaultSubject;
}
// Fail if we're missing a from and the form element is disabled:
if ($view->disableFrom) {
if (empty($view->from)) {
$view->from = $config->Site->email;
}
if (empty($view->from)) {
throw new \Exception('Unable to determine email from address');
}
}
return $view;
}
/**
* Get the account manager object.
*
* @return \VuFind\Auth\Manager
*/
protected function getAuthManager()
{
return $this->serviceLocator->get(\VuFind\Auth\Manager::class);
}
/**
* Get the authorization service (note that we're doing this on-demand
* rather than through injection with the AuthorizationServiceAwareInterface
* to minimize expensive initialization when authorization is not needed.
*
* @return \ZfcRbac\Service\AuthorizationService
*/
protected function getAuthorizationService()
{
return $this->serviceLocator
->get(\ZfcRbac\Service\AuthorizationService::class);
}
/**
* Get the ILS authenticator.
*
* @return \VuFind\Auth\ILSAuthenticator
*/
protected function getILSAuthenticator()
{
return $this->serviceLocator->get(\VuFind\Auth\ILSAuthenticator::class);
}
/**
* Get the user object if logged in, false otherwise.
*
* @return object|bool
*/
protected function getUser()
{
return $this->getAuthManager()->isLoggedIn();
}
/**
* Get the view renderer
*
* @return \Laminas\View\Renderer\RendererInterface
*/
protected function getViewRenderer()
{
return $this->serviceLocator->get('ViewRenderer');
}
/**
* Redirect the user to the login screen.
*
* @param string $msg Flash message to display on login screen
* @param array $extras Associative array of extra fields to store
* @param bool $forward True to forward, false to redirect
*
* @return mixed
*/
public function forceLogin($msg = null, $extras = [], $forward = true)
{
// Set default message if necessary.
if (null === $msg) {
$msg = 'You must be logged in first';
}
// We don't want to return to the lightbox
$serverUrl = $this->getServerUrl();
$serverUrl = str_replace(
['?layout=lightbox', '&layout=lightbox'],
['?', '&'],
$serverUrl
);
// Store the current URL as a login followup action
$this->followup()->store($extras, $serverUrl);
if (!empty($msg)) {
$this->flashMessenger()->addMessage($msg, 'error');
}
// Set a flag indicating that we are forcing login:
$this->getRequest()->getPost()->set('forcingLogin', true);
if ($forward) {
return $this->forwardTo('MyResearch', 'Login');
}
return $this->redirect()->toRoute('myresearch-home');
}
/**
* Does the user have catalog credentials available? Returns associative array
* of patron data if so, otherwise forwards to appropriate login prompt and
* returns false. If there is an ILS exception, a flash message is added and
* a newly created ViewModel is returned.
*
* @return bool|array|ViewModel
*/
protected function catalogLogin()
{
// First make sure user is logged in to VuFind:
$account = $this->getAuthManager();
if ($account->isLoggedIn() == false) {
return $this->forceLogin();
}
// Now check if the user has provided credentials with which to log in:
$ilsAuth = $this->getILSAuthenticator();
$patron = null;
if (($username = $this->params()->fromPost('cat_username', false))
&& ($password = $this->params()->fromPost('cat_password', false))
) {
// Check for multiple ILS target selection
$target = $this->params()->fromPost('target', false);
if ($target) {
$username = "$target.$username";
}
try {
if ('email' === $this->getILSLoginMethod($target)) {
$routeMatch = $this->getEvent()->getRouteMatch();
$routeName = $routeMatch ? $routeMatch->getMatchedRouteName()
: 'myresearch-profile';
$ilsAuth->sendEmailLoginLink($username, $routeName);
$this->flashMessenger()
->addSuccessMessage('email_login_link_sent');
} else {
$patron = $ilsAuth->newCatalogLogin($username, $password);
// If login failed, store a warning message:
if (!$patron) {
$this->flashMessenger()
->addErrorMessage('Invalid Patron Login');
}
}
} catch (ILSException $e) {
$this->flashMessenger()->addErrorMessage('ils_connection_failed');
}
} elseif ('ILS' === $this->params()->fromQuery('auth_method', false)
&& ($hash = $this->params()->fromQuery('hash', false))
) {
try {
$patron = $ilsAuth->processEmailLoginHash($hash);
} catch (AuthException $e) {
$this->flashMessenger()->addErrorMessage($e->getMessage());
}
} else {
try {
// If no credentials were provided, try the stored values:
$patron = $ilsAuth->storedCatalogLogin();
} catch (ILSException $e) {
$this->flashMessenger()->addErrorMessage('ils_connection_failed');
return $this->createViewModel();
}
}
// If catalog login failed, send the user to the right page:
if (!$patron) {
return $this->forwardTo('MyResearch', 'CatalogLogin');
}
// Send value (either false or patron array) back to caller:
return $patron;
}
/**
* Get a VuFind configuration.
*
* @param string $id Configuration identifier (default = main VuFind config)
*
* @return \Laminas\Config\Config
*/
public function getConfig($id = 'config')
{
return $this->serviceLocator->get(\VuFind\Config\PluginManager::class)
->get($id);
}
/**
* Get the ILS connection.
*
* @return \VuFind\ILS\Connection
*/
public function getILS()
{
return $this->serviceLocator->get(\VuFind\ILS\Connection::class);
}
/**
* Get the record loader
*
* @return \VuFind\Record\Loader
*/
public function getRecordLoader()
{
return $this->serviceLocator->get(\VuFind\Record\Loader::class);
}
/**
* Get the record cache
*
* @return \VuFind\Record\Cache
*/
public function getRecordCache()
{
return $this->serviceLocator->get(\VuFind\Record\Cache::class);
}
/**
* Get the record router.
*
* @return \VuFind\Record\Router
*/
public function getRecordRouter()
{
return $this->serviceLocator->get(\VuFind\Record\Router::class);
}
/**
* Get a database table object.
*
* @param string $table Name of table to retrieve
*
* @return \VuFind\Db\Table\Gateway
*/
public function getTable($table)
{
return $this->serviceLocator->get(\VuFind\Db\Table\PluginManager::class)
->get($table);
}
/**
* Get the full URL to one of VuFind's routes.
*
* @param bool|string $route Boolean true for current URL, otherwise name of
* route to render as URL
*
* @return string
*/
public function getServerUrl($route = true)
{
$serverHelper = $this->getViewRenderer()->plugin('serverurl');
return $serverHelper(
$route === true ? true : $this->url()->fromRoute($route)
);
}
/**
* Translate a string if a translator is available.
*
* @param string $msg Message to translate
* @param array $tokens Tokens to inject into the translated string
* @param string $default Default value to use if no translation is found (null
* for no default).
*
* @return string
*/
public function translate($msg, $tokens = [], $default = null)
{
return $this->getViewRenderer()->plugin('translate')
->__invoke($msg, $tokens, $default);
}
/**
* Convenience method to make invocation of forward() helper less verbose.
*
* @param string $controller Controller to invoke
* @param string $action Action to invoke
* @param array $params Extra parameters for the RouteMatch object (no
* need to provide action here, since $action takes care of that)
*
* @return mixed
*/
public function forwardTo($controller, $action, $params = [])
{
// Inject action into the RouteMatch parameters
$params['action'] = $action;
// Dispatch the requested controller/action:
return $this->forward()->dispatch($controller, $params);
}
/**
* Check to see if a form was submitted from its post value
* Also validate the Captcha, if it's activated
*
* @param string $submitElement Name of the post field of the submit button
* @param bool $useRecaptcha Are we using captcha in this situation?
*
* @return bool
*/
protected function formWasSubmitted($submitElement = 'submit',
$useRecaptcha = false
) {
// Fail if the expected submission element was missing from the POST:
// Form was submitted; if CAPTCHA is expected, validate it now.
return $this->params()->fromPost($submitElement, false)
&& (!$useRecaptcha || $this->recaptcha()->validate());
}
/**
* Confirm an action.
*
* @param string $title Title of confirm dialog
* @param string $yesTarget Form target for "confirm" action
* @param string $noTarget Form target for "cancel" action
* @param string|array $messages Info messages for confirm dialog
* @param array $extras Extra details to include in form
*
* @return mixed
*/
public function confirm($title, $yesTarget, $noTarget, $messages = [],
$extras = []
) {
return $this->forwardTo(
'Confirm', 'Confirm',
[
'data' => [
'title' => $title,
'confirm' => $yesTarget,
'cancel' => $noTarget,
'messages' => (array)$messages,
'extras' => $extras
]
]
);
}
/**
* Prevent session writes -- this is designed to be called prior to time-
* consuming AJAX operations to help reduce the odds of a timing-related bug
* that causes the wrong version of session data to be written to disk (see
* VUFIND-716 for more details).
*
* @return void
*/
protected function disableSessionWrites()
{
$this->serviceLocator->get(\VuFind\Session\Settings::class)->disableWrite();
}
/**
* Get the search memory
*
* @return \VuFind\Search\Memory
*/
public function getSearchMemory()
{
return $this->serviceLocator->get(\VuFind\Search\Memory::class);
}
/**
* Are comments enabled?
*
* @return bool
*/
protected function commentsEnabled()
{
$check = $this->serviceLocator
->get(\VuFind\Config\AccountCapabilities::class);
return $check->getCommentSetting() !== 'disabled';
}
/**
* Are lists enabled?
*
* @return bool
*/
protected function listsEnabled()
{
$check = $this->serviceLocator
->get(\VuFind\Config\AccountCapabilities::class);
return $check->getListSetting() !== 'disabled';
}
/**
* Are tags enabled?
*
* @return bool
*/
protected function tagsEnabled()
{
$check = $this->serviceLocator
->get(\VuFind\Config\AccountCapabilities::class);
return $check->getTagSetting() !== 'disabled';
}
/**
* Store a referer (if appropriate) to keep post-login redirect pointing
* to an appropriate location. This is used when the user clicks the
* log in link from an arbitrary page or when a password is mistyped;
* separate logic is used for storing followup information when VuFind
* forces the user to log in from another context.
*
* @return void
*/
protected function setFollowupUrlToReferer()
{
// lbreferer is the stored current url of the lightbox
// which overrides the url from the server request when present
$referer = $this->getRequest()->getQuery()->get(
'lbreferer',
$this->getRequest()->getServer()->get('HTTP_REFERER', null)
);
// Get the referer -- if it's empty, there's nothing to store!
if (empty($referer)) {
return;
}
$refererNorm = $this->normalizeUrlForComparison($referer);
// If the referer lives outside of VuFind, don't store it! We only
// want internal post-login redirects.
$baseUrl = $this->getServerUrl('home');
$baseUrlNorm = $this->normalizeUrlForComparison($baseUrl);
if (0 !== strpos($refererNorm, $baseUrlNorm)) {
return;
}
// If the referer is the MyResearch/Home action, it probably means
// that the user is repeatedly mistyping their password. We should
// ignore this and instead rely on any previously stored referer.
$myResearchHomeUrl = $this->getServerUrl('myresearch-home');
$mrhuNorm = $this->normalizeUrlForComparison($myResearchHomeUrl);
if ($mrhuNorm === $refererNorm) {
return;
}
// If the referer is the MyResearch/UserLogin action, it probably means
// that the user is repeatedly mistyping their password. We should
// ignore this and instead rely on any previously stored referer.
$myUserLogin = $this->getServerUrl('myresearch-userlogin');
$mulNorm = $this->normalizeUrlForComparison($myUserLogin);
if (0 === strpos($refererNorm, $mulNorm)) {
return;
}
// If we got this far, we want to store the referer:
$this->followup()->store([], $referer);
}
/**
* Normalize the referer URL so that inconsistencies in protocol and trailing
* slashes do not break comparisons.
*
* @param string $url URL to normalize
*
* @return string
*/
protected function normalizeUrlForComparison($url)
{
$parts = explode('://', $url, 2);
return trim(end($parts), '/');
}
/**
* Retrieve a referer to keep post-login redirect pointing
* to an appropriate location.
* Unset the followup before returning.
*
* @return string
*/
protected function getFollowupUrl()
{
return $this->followup()->retrieve('url', '');
}
/**
* Sometimes we need to unset the followup to trigger default behaviors
*
* @return void
*/
protected function clearFollowupUrl()
{
$this->followup()->clear('url');
}
/**
* Get the tab configuration for this controller.
*
* @return \VuFind\RecordTab\TabManager
*/
protected function getRecordTabManager()
{
return $this->serviceLocator->get(\VuFind\RecordTab\TabManager::class);
}
/**
* Are we currently in a lightbox context?
*
* @return bool
*/
protected function inLightbox()
{
return
$this->params()->fromPost(
'layout', $this->params()->fromQuery('layout', false)
) === 'lightbox'
|| 'layout/lightbox' == $this->layout()->getTemplate();
}
/**
* What login method does the ILS use (password, email, vufind)
*
* @param string $target Login target (MultiILS only)
*
* @return string
*/
protected function getILSLoginMethod($target = '')
{
$config = $this->getILS()->checkFunction(
'patronLogin', ['patron' => ['cat_username' => "$target.login"]]
);
return $config['loginMethod'] ?? 'password';
}
/**
* Get settings required for displaying the catalog login form
*
* @return array
*/
protected function getILSLoginSettings()
{
$targets = null;
$defaultTarget = null;
$loginMethod = null;
$loginMethods = [];
// Connect to the ILS and check if multiple target support is available:
$catalog = $this->getILS();
if ($catalog->checkCapability('getLoginDrivers')) {
$targets = $catalog->getLoginDrivers();
$defaultTarget = $catalog->getDefaultLoginDriver();
foreach ($targets as $t) {
$loginMethods[$t] = $this->getILSLoginMethod($t);
}
} else {
$loginMethod = $this->getILSLoginMethod();
}
return compact('targets', 'defaultTarget', 'loginMethod', 'loginMethods');
}
}
| 1 | 29,668 | Since this is only used in the MyResearchController, does it need to be placed at the AbstractBase level? | vufind-org-vufind | php |
@@ -55,7 +55,7 @@ type SelectorSpec struct {
// +optional
AnnotationSelectors map[string]string `json:"annotationSelectors,omitempty"`
- // PodPhaseSelector is a set of condition of a pod at the current time.
+ // PhaseSelector is a set of condition of a pod at the current time.
// supported value: Pending / Running / Succeeded / Failed / Unknown
PodPhaseSelectors []string `json:"phaseSelector,omitempty"`
} | 1 | // Copyright 2019 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// SelectorSpec defines the some selectors to select objects.
// If the all selectors are empty, all objects will be used in chaos experiment.
type SelectorSpec struct {
// Namespaces is a set of namespace to which objects belong.
// +optional
Namespaces []string `json:"namespaces,omitempty"`
// Nodes is a set of node name and objects must belong to these nodes.
// +optional
Nodes []string `json:"nodes,omitempty"`
// Pods is a map of string keys and a set values that used to select pods.
// The key defines the namespace which pods belong,
// and the each values is a set of pod names.
// +optional
Pods map[string][]string `json:"pods,omitempty"`
// Map of string keys and values that can be used to select nodes.
// Selector which must match a node's labels,
// and objects must belong to these selected nodes.
// +optional
NodeSelectors map[string]string `json:"nodeSelectors,omitempty"`
// Map of string keys and values that can be used to select objects.
// A selector based on fields.
// +optional
FieldSelectors map[string]string `json:"fieldSelectors,omitempty"`
// Map of string keys and values that can be used to select objects.
// A selector based on labels.
// +optional
LabelSelectors map[string]string `json:"labelSelectors,omitempty"`
// Map of string keys and values that can be used to select objects.
// A selector based on annotations.
// +optional
AnnotationSelectors map[string]string `json:"annotationSelectors,omitempty"`
// PodPhaseSelector is a set of condition of a pod at the current time.
// supported value: Pending / Running / Succeeded / Failed / Unknown
PodPhaseSelectors []string `json:"phaseSelector,omitempty"`
}
// SchedulerSpec defines information about schedule of the chaos experiment.
type SchedulerSpec struct {
// Cron defines a cron job rule.
//
// Some rule examples:
// "0 30 * * * *" means to "Every hour on the half hour"
// "@hourly" means to "Every hour"
// "@every 1h30m" means to "Every hour thirty"
//
// More rule info: https://godoc.org/github.com/robfig/cron
Cron string `json:"cron"`
}
// PodMode represents the mode to run pod chaos action.
type PodMode string
const (
// OnePodMode represents that the system will do the chaos action on one pod selected randomly.
OnePodMode PodMode = "one"
// AllPodMode represents that the system will do the chaos action on all pods
// regardless of status (not ready or not running pods includes).
// Use this label carefully.
AllPodMode PodMode = "all"
// FixedPodMode represents that the system will do the chaos action on a specific number of running pods.
FixedPodMode PodMode = "fixed"
// FixedPercentPodMode to specify a fixed % that can be inject chaos action.
FixedPercentPodMode PodMode = "fixed-percent"
// RandomMaxPercentPodMode to specify a maximum % that can be inject chaos action.
RandomMaxPercentPodMode PodMode = "random-max-percent"
)
// ChaosPhase is the current status of chaos task.
type ChaosPhase string
const (
ChaosPhaseNone ChaosPhase = ""
ChaosPhaseNormal ChaosPhase = "Normal"
ChaosPhaseAbnormal ChaosPhase = "Abnormal"
)
type ChaosStatus struct {
// Phase is the chaos status.
Phase ChaosPhase `json:"phase"`
Reason string `json:"reason,omitempty"`
// Experiment records the last experiment state.
Experiment ExperimentStatus `json:"experiment"`
}
// ExperimentPhase is the current status of chaos experiment.
type ExperimentPhase string
const (
ExperimentPhaseRunning ExperimentPhase = "Running"
ExperimentPhaseFailed ExperimentPhase = "Failed"
ExperimentPhaseFinished ExperimentPhase = "Finished"
)
type ExperimentStatus struct {
// +optional
Phase ExperimentPhase `json:"phase,omitempty"`
// +optional
Reason string `json:"reason,omitempty"`
// +optional
StartTime *metav1.Time `json:"startTime,omitempty"`
// +optional
EndTime *metav1.Time `json:"endTime,omitempty"`
// +optional
Pods []PodStatus `json:"podChaos,omitempty"`
}
| 1 | 12,900 | why `PhaseSelector` ? | chaos-mesh-chaos-mesh | go |
@@ -32,6 +32,8 @@ type rawConfig struct {
RestrictedLicenses []string `json:"restricted_licenses"`
// modules that get completely ignored during analysis
+ AllowlistedModules []string `json:"allowlisted_modules"`
+ // Deprecated. TODO(tbarrella): Clean up
WhitelistedModules []string `json:"whitelisted_modules"`
}
| 1 | // Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"io/ioutil"
"github.com/ghodss/yaml"
)
type rawConfig struct {
// definitely ok to use and modify.
UnrestrictedLicenses []string `json:"unrestricted_licenses"`
// can be used but not modified
ReciprocalLicenses []string `json:"reciprocal_licenses"`
// cannot be used
RestrictedLicenses []string `json:"restricted_licenses"`
// modules that get completely ignored during analysis
WhitelistedModules []string `json:"whitelisted_modules"`
}
type config struct {
// definitely ok to use and modify.
unrestrictedLicenses map[string]bool
// can be used but not modified
reciprocalLicenses map[string]bool
// cannot be used
restrictedLicenses map[string]bool
// modules that get completely ignored during analysis
whitelistedModules map[string]bool
}
func newConfig() config {
return config{
unrestrictedLicenses: make(map[string]bool),
reciprocalLicenses: make(map[string]bool),
restrictedLicenses: make(map[string]bool),
whitelistedModules: make(map[string]bool),
}
}
func readConfig(path string) (config, error) {
var b []byte
var err error
if b, err = ioutil.ReadFile(path); err != nil {
return config{}, fmt.Errorf("unable to read configuration file %s: %v", path, err)
}
var rc rawConfig
if err = yaml.Unmarshal(b, &rc); err != nil {
return config{}, fmt.Errorf("unable to parse configuration file %s: %v", path, err)
}
c := newConfig()
for _, s := range rc.UnrestrictedLicenses {
c.unrestrictedLicenses[s] = true
}
for _, s := range rc.ReciprocalLicenses {
c.reciprocalLicenses[s] = true
}
for _, s := range rc.RestrictedLicenses {
c.restrictedLicenses[s] = true
}
for _, s := range rc.WhitelistedModules {
c.whitelistedModules[s] = true
}
return c, nil
}
| 1 | 8,953 | Does` AllowlistedModules` have the same meaning of `WhitelistedModules`? | istio-tools | go |
@@ -357,7 +357,7 @@ return [
'ArithmeticError::getTrace' => ['array<int,array<string,mixed>>'],
'ArithmeticError::getTraceAsString' => ['string'],
'array_change_key_case' => ['array|false', 'input'=>'array', 'case='=>'int'],
-'array_chunk' => ['array[]', 'input'=>'array', 'size'=>'int', 'preserve_keys='=>'bool'],
+'array_chunk' => ['list<array>', 'input'=>'array', 'size'=>'int', 'preserve_keys='=>'bool'],
'array_column' => ['array', 'array'=>'array', 'column_key'=>'mixed', 'index_key='=>'mixed'],
'array_combine' => ['array|false', 'keys'=>'string[]|int[]', 'values'=>'array'],
'array_count_values' => ['int[]', 'input'=>'array'], | 1 | <?php // phpcs:ignoreFile
namespace Phan\Language\Internal;
/**
* Format
*
* '<function_name>' => ['<return_type>, '<arg_name>'=>'<arg_type>']
* alternative signature for the same function
* '<function_name\'1>' => ['<return_type>, '<arg_name>'=>'<arg_type>']
*
* A '&' in front of the <arg_name> means the arg is always passed by reference.
* (i.e. ReflectionParameter->isPassedByReference())
* This was previously only used in cases where the function actually created the
* variable in the local scope.
* Some reference arguments will have prefixes in <arg_name> to indicate the way the argument is used.
* Currently, the only prefixes with meaning are 'rw_' (read-write) and 'w_' (write).
* Those prefixes don't mean anything for non-references.
* Code using these signatures should remove those prefixes from messages rendered to the user.
* 1. '&rw_<arg_name>' indicates that a parameter with a value is expected to be passed in, and may be modified.
* Phan will warn if the variable has an incompatible type, or is undefined.
* 2. '&w_<arg_name>' indicates that a parameter is expected to be passed in, and the value will be ignored, and may be overwritten.
* 3. The absence of a prefix is treated by Phan the same way as having the prefix 'w_' (Some may be changed to 'rw_name'). These will have prefixes added later.
*
* So, for functions like sort() where technically the arg is by-ref,
* indicate the reference param's signature by-ref and read-write,
* as `'&rw_array'=>'array'`
* so that Phan won't create it in the local scope
*
* However, for a function like preg_match() where the 3rd arg is an array of sub-pattern matches (and optional),
* this arg needs to be marked as by-ref and write-only, as `'&w_matches='=>'array'`.
*
* A '=' following the <arg_name> indicates this arg is optional.
*
* The <arg_name> can begin with '...' to indicate the arg is variadic.
* '...args=' indicates it is both variadic and optional.
*
* Some reference arguments will have prefixes in <arg_name> to indicate the way the argument is used.
* Currently, the only prefixes with meaning are 'rw_' and 'w_'.
* Code using these signatures should remove those prefixes from messages rendered to the user.
* 1. '&rw_name' indicates that a parameter with a value is expected to be passed in, and may be modified.
* 2. '&w_name' indicates that a parameter is expected to be passed in, and the value will be ignored, and may be overwritten.
*
* This file contains the signatures for the most recent minor release of PHP supported by phan (php 7.2)
*
* Changes:
*
* In Phan 0.12.3,
*
* - This started using array shapes for union types (array{...}).
*
* \Phan\Language\UnionType->withFlattenedArrayShapeOrLiteralTypeInstances() may be of help to programmatically convert these to array<string,T1>|array<string,T2>
*
* - This started using array shapes with optional fields for union types (array{key?:int}).
* A `?` after the array shape field's key indicates that the field is optional.
*
* - This started adding param signatures and return signatures to `callable` types.
* E.g. 'usort' => ['bool', '&rw_array_arg'=>'array', 'cmp_function'=>'callable(mixed,mixed):int'].
* See NEWS.md for 0.12.3 for possible syntax. A suffix of `=` within `callable(...)` means that a parameter is optional.
*
* (Phan assumes that callbacks with optional arguments can be cast to callbacks with/without those args (Similar to inheritance checks)
* (e.g. callable(T1,T2=) can be cast to callable(T1) or callable(T1,T2), in the same way that a subclass would check).
* For some signatures, e.g. set_error_handler, this results in repetition, because callable(T1=) can't cast to callable(T1).
*
* Sources of stub info:
*
* 1. Reflection
* 2. docs.php.net's SVN repo or website, and examples (See internal/internalsignatures.php)
*
* See https://secure.php.net/manual/en/copyright.php
*
* The PHP manual text and comments are covered by the [Creative Commons Attribution 3.0 License](http://creativecommons.org/licenses/by/3.0/legalcode),
* copyright (c) the PHP Documentation Group
* 3. Various websites documenting individual extensions
* 4. PHPStorm stubs (For anything missing from the above sources)
* See internal/internalsignatures.php
*
* Available from https://github.com/JetBrains/phpstorm-stubs under the [Apache 2 license](https://www.apache.org/licenses/LICENSE-2.0)
*
* @phan-file-suppress PhanPluginMixedKeyNoKey (read by Phan when analyzing this file)
*
* Note: Some of Phan's inferences about return types are written as plugins for functions/methods where the return type depends on the parameter types.
* E.g. src/Phan/Plugin/Internal/DependentReturnTypeOverridePlugin.php is one plugin
*/
return [
'_' => ['string', 'message'=>'string'],
'__halt_compiler' => ['void'],
'abs' => ['int', 'number'=>'int'],
'abs\'1' => ['float', 'number'=>'float'],
'abs\'2' => ['numeric', 'number'=>'numeric'],
'accelerator_get_configuration' => ['array'],
'accelerator_get_scripts' => ['array'],
'accelerator_get_status' => ['array', 'fetch_scripts'=>'bool'],
'accelerator_reset' => [''],
'accelerator_set_status' => ['void', 'status'=>'bool'],
'acos' => ['float', 'number'=>'float'],
'acosh' => ['float', 'number'=>'float'],
'addcslashes' => ['string', 'str'=>'string', 'charlist'=>'string'],
'addslashes' => ['string', 'str'=>'string'],
'AMQPBasicProperties::__construct' => ['void', 'content_type='=>'string', 'content_encoding='=>'string', 'headers='=>'array', 'delivery_mode='=>'int', 'priority='=>'int', 'correlation_id='=>'string', 'reply_to='=>'string', 'expiration='=>'string', 'message_id='=>'string', 'timestamp='=>'int', 'type='=>'string', 'user_id='=>'string', 'app_id='=>'string', 'cluster_id='=>'string'],
'AMQPBasicProperties::getAppId' => ['string'],
'AMQPBasicProperties::getClusterId' => ['string'],
'AMQPBasicProperties::getContentEncoding' => ['string'],
'AMQPBasicProperties::getContentType' => ['string'],
'AMQPBasicProperties::getCorrelationId' => ['string'],
'AMQPBasicProperties::getDeliveryMode' => ['int'],
'AMQPBasicProperties::getExpiration' => ['string'],
'AMQPBasicProperties::getHeaders' => ['array'],
'AMQPBasicProperties::getMessageId' => ['string'],
'AMQPBasicProperties::getPriority' => ['int'],
'AMQPBasicProperties::getReplyTo' => ['string'],
'AMQPBasicProperties::getTimestamp' => ['string'],
'AMQPBasicProperties::getType' => ['string'],
'AMQPBasicProperties::getUserId' => ['string'],
'AMQPChannel::__construct' => ['void', 'amqp_connection'=>'AMQPConnection'],
'AMQPChannel::basicRecover' => ['', 'requeue='=>'bool'],
'AMQPChannel::close' => [''],
'AMQPChannel::commitTransaction' => ['bool'],
'AMQPChannel::confirmSelect' => [''],
'AMQPChannel::getChannelId' => ['int'],
'AMQPChannel::getConnection' => ['AMQPConnection'],
'AMQPChannel::getConsumers' => ['AMQPQueue[]'],
'AMQPChannel::getPrefetchCount' => ['int'],
'AMQPChannel::getPrefetchSize' => ['int'],
'AMQPChannel::isConnected' => ['bool'],
'AMQPChannel::qos' => ['bool', 'size'=>'int', 'count'=>'int'],
'AMQPChannel::rollbackTransaction' => ['bool'],
'AMQPChannel::setConfirmCallback' => ['', 'ack_callback='=>'?callable', 'nack_callback='=>'?callable'],
'AMQPChannel::setPrefetchCount' => ['bool', 'count'=>'int'],
'AMQPChannel::setPrefetchSize' => ['bool', 'size'=>'int'],
'AMQPChannel::setReturnCallback' => ['', 'return_callback='=>'?callable'],
'AMQPChannel::startTransaction' => ['bool'],
'AMQPChannel::waitForBasicReturn' => ['', 'timeout='=>'float'],
'AMQPChannel::waitForConfirm' => ['', 'timeout='=>'float'],
'AMQPConnection::__construct' => ['void', 'credentials='=>'array'],
'AMQPConnection::connect' => ['bool'],
'AMQPConnection::disconnect' => ['bool'],
'AMQPConnection::getCACert' => ['string'],
'AMQPConnection::getCert' => ['string'],
'AMQPConnection::getHeartbeatInterval' => ['int'],
'AMQPConnection::getHost' => ['string'],
'AMQPConnection::getKey' => ['string'],
'AMQPConnection::getLogin' => ['string'],
'AMQPConnection::getMaxChannels' => ['?int'],
'AMQPConnection::getMaxFrameSize' => ['int'],
'AMQPConnection::getPassword' => ['string'],
'AMQPConnection::getPort' => ['int'],
'AMQPConnection::getReadTimeout' => ['float'],
'AMQPConnection::getTimeout' => ['float'],
'AMQPConnection::getUsedChannels' => ['int'],
'AMQPConnection::getVerify' => ['bool'],
'AMQPConnection::getVhost' => ['string'],
'AMQPConnection::getWriteTimeout' => ['float'],
'AMQPConnection::isConnected' => ['bool'],
'AMQPConnection::isPersistent' => ['?bool'],
'AMQPConnection::pconnect' => ['bool'],
'AMQPConnection::pdisconnect' => ['bool'],
'AMQPConnection::preconnect' => ['bool'],
'AMQPConnection::reconnect' => ['bool'],
'AMQPConnection::setCACert' => ['', 'cacert'=>'string'],
'AMQPConnection::setCert' => ['', 'cert'=>'string'],
'AMQPConnection::setHost' => ['bool', 'host'=>'string'],
'AMQPConnection::setKey' => ['', 'key'=>'string'],
'AMQPConnection::setLogin' => ['bool', 'login'=>'string'],
'AMQPConnection::setPassword' => ['bool', 'password'=>'string'],
'AMQPConnection::setPort' => ['bool', 'port'=>'int'],
'AMQPConnection::setReadTimeout' => ['bool', 'timeout'=>'int'],
'AMQPConnection::setTimeout' => ['bool', 'timeout'=>'int'],
'AMQPConnection::setVerify' => ['', 'verify'=>'bool'],
'AMQPConnection::setVhost' => ['bool', 'vhost'=>'string'],
'AMQPConnection::setWriteTimeout' => ['bool', 'timeout'=>'int'],
'AMQPDecimal::__construct' => ['void', 'exponent'=>'', 'significand'=>''],
'AMQPDecimal::getExponent' => ['int'],
'AMQPDecimal::getSignificand' => ['int'],
'AMQPEnvelope::__construct' => ['void'],
'AMQPEnvelope::getAppId' => ['string'],
'AMQPEnvelope::getBody' => ['string'],
'AMQPEnvelope::getClusterId' => ['string'],
'AMQPEnvelope::getConsumerTag' => ['string'],
'AMQPEnvelope::getContentEncoding' => ['string'],
'AMQPEnvelope::getContentType' => ['string'],
'AMQPEnvelope::getCorrelationId' => ['string'],
'AMQPEnvelope::getDeliveryMode' => ['int'],
'AMQPEnvelope::getDeliveryTag' => ['string'],
'AMQPEnvelope::getExchangeName' => ['string'],
'AMQPEnvelope::getExpiration' => ['string'],
'AMQPEnvelope::getHeader' => ['string|false', 'header_key'=>'string'],
'AMQPEnvelope::getHeaders' => ['array'],
'AMQPEnvelope::getMessageId' => ['string'],
'AMQPEnvelope::getPriority' => ['int'],
'AMQPEnvelope::getReplyTo' => ['string'],
'AMQPEnvelope::getRoutingKey' => ['string'],
'AMQPEnvelope::getTimeStamp' => ['string'],
'AMQPEnvelope::getType' => ['string'],
'AMQPEnvelope::getUserId' => ['string'],
'AMQPEnvelope::hasHeader' => ['bool', 'header_key'=>'string'],
'AMQPEnvelope::isRedelivery' => ['bool'],
'AMQPExchange::__construct' => ['void', 'amqp_channel'=>'AMQPChannel'],
'AMQPExchange::bind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPExchange::declareExchange' => ['bool'],
'AMQPExchange::delete' => ['bool', 'exchangeName='=>'string', 'flags='=>'int'],
'AMQPExchange::getArgument' => ['int|string|false', 'key'=>'string'],
'AMQPExchange::getArguments' => ['array'],
'AMQPExchange::getChannel' => ['AMQPChannel'],
'AMQPExchange::getConnection' => ['AMQPConnection'],
'AMQPExchange::getFlags' => ['int'],
'AMQPExchange::getName' => ['string'],
'AMQPExchange::getType' => ['string'],
'AMQPExchange::hasArgument' => ['bool', 'key'=>'string'],
'AMQPExchange::publish' => ['bool', 'message'=>'string', 'routing_key='=>'string', 'flags='=>'int', 'attributes='=>'array'],
'AMQPExchange::setArgument' => ['bool', 'key'=>'string', 'value'=>'int|string'],
'AMQPExchange::setArguments' => ['bool', 'arguments'=>'array'],
'AMQPExchange::setFlags' => ['bool', 'flags'=>'int'],
'AMQPExchange::setName' => ['bool', 'exchange_name'=>'string'],
'AMQPExchange::setType' => ['bool', 'exchange_type'=>'string'],
'AMQPExchange::unbind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPQueue::__construct' => ['void', 'amqp_channel'=>'AMQPChannel'],
'AMQPQueue::ack' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::bind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPQueue::cancel' => ['bool', 'consumer_tag='=>'string'],
'AMQPQueue::consume' => ['void', 'callback='=>'?callable', 'flags='=>'int', 'consumerTag='=>'string'],
'AMQPQueue::declareQueue' => ['int'],
'AMQPQueue::delete' => ['int', 'flags='=>'int'],
'AMQPQueue::get' => ['AMQPEnvelope|false', 'flags='=>'int'],
'AMQPQueue::getArgument' => ['int|string|false', 'key'=>'string'],
'AMQPQueue::getArguments' => ['array'],
'AMQPQueue::getChannel' => ['AMQPChannel'],
'AMQPQueue::getConnection' => ['AMQPConnection'],
'AMQPQueue::getConsumerTag' => ['?string'],
'AMQPQueue::getFlags' => ['int'],
'AMQPQueue::getName' => ['string'],
'AMQPQueue::hasArgument' => ['bool', 'key'=>'string'],
'AMQPQueue::nack' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::purge' => ['bool'],
'AMQPQueue::reject' => ['bool', 'delivery_tag'=>'string', 'flags='=>'int'],
'AMQPQueue::setArgument' => ['bool', 'key'=>'string', 'value'=>'mixed'],
'AMQPQueue::setArguments' => ['bool', 'arguments'=>'array'],
'AMQPQueue::setFlags' => ['bool', 'flags'=>'int'],
'AMQPQueue::setName' => ['bool', 'queue_name'=>'string'],
'AMQPQueue::unbind' => ['bool', 'exchange_name'=>'string', 'routing_key='=>'string', 'arguments='=>'array'],
'AMQPTimestamp::__construct' => ['void', 'timestamp'=>'string'],
'AMQPTimestamp::__toString' => ['string'],
'AMQPTimestamp::getTimestamp' => ['string'],
'apache_child_terminate' => ['bool'],
'apache_get_modules' => ['array'],
'apache_get_version' => ['string|false'],
'apache_getenv' => ['string|false', 'variable'=>'string', 'walk_to_top='=>'bool'],
'apache_lookup_uri' => ['object', 'filename'=>'string'],
'apache_note' => ['string|false', 'note_name'=>'string', 'note_value='=>'string'],
'apache_request_headers' => ['array|false'],
'apache_reset_timeout' => ['bool'],
'apache_response_headers' => ['array|false'],
'apache_setenv' => ['bool', 'variable'=>'string', 'value'=>'string', 'walk_to_top='=>'bool'],
'apc_add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'ttl='=>'int'],
'apc_add\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'apc_bin_dump' => ['string|false|null', 'files='=>'array', 'user_vars='=>'array'],
'apc_bin_dumpfile' => ['int|false', 'files'=>'array', 'user_vars'=>'array', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'apc_bin_load' => ['bool', 'data'=>'string', 'flags='=>'int'],
'apc_bin_loadfile' => ['bool', 'filename'=>'string', 'context='=>'resource', 'flags='=>'int'],
'apc_cache_info' => ['array|false', 'cache_type='=>'string', 'limited='=>'bool'],
'apc_cas' => ['bool', 'key'=>'string', 'old'=>'int', 'new'=>'int'],
'apc_clear_cache' => ['bool', 'cache_type='=>'string'],
'apc_compile_file' => ['bool', 'filename'=>'string', 'atomic='=>'bool'],
'apc_dec' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool'],
'apc_define_constants' => ['bool', 'key'=>'string', 'constants'=>'array', 'case_sensitive='=>'bool'],
'apc_delete' => ['bool', 'key'=>'string|string[]|APCIterator'],
'apc_delete_file' => ['bool|string[]', 'keys'=>'mixed'],
'apc_exists' => ['bool', 'keys'=>'string'],
'apc_exists\'1' => ['array', 'keys'=>'string[]'],
'apc_fetch' => ['mixed|false', 'key'=>'string', '&w_success='=>'bool'],
'apc_fetch\'1' => ['array|false', 'key'=>'string[]', '&w_success='=>'bool'],
'apc_inc' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool'],
'apc_load_constants' => ['bool', 'key'=>'string', 'case_sensitive='=>'bool'],
'apc_sma_info' => ['array|false', 'limited='=>'bool'],
'apc_store' => ['bool', 'key'=>'string', 'var'=>'', 'ttl='=>'int'],
'apc_store\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'APCIterator::__construct' => ['void', 'cache'=>'string', 'search='=>'null|string|string[]', 'format='=>'int', 'chunk_size='=>'int', 'list='=>'int'],
'APCIterator::current' => ['mixed|false'],
'APCIterator::getTotalCount' => ['int|false'],
'APCIterator::getTotalHits' => ['int|false'],
'APCIterator::getTotalSize' => ['int|false'],
'APCIterator::key' => ['string'],
'APCIterator::next' => ['void'],
'APCIterator::rewind' => ['void'],
'APCIterator::valid' => ['bool'],
'apcu_add' => ['bool', 'key'=>'string', 'var'=>'', 'ttl='=>'int'],
'apcu_add\'1' => ['array<string,int>', 'values'=>'array<string,mixed>', 'unused='=>'', 'ttl='=>'int'],
'apcu_cache_info' => ['array<string,mixed>|false', 'limited='=>'bool'],
'apcu_cas' => ['bool', 'key'=>'string', 'old'=>'int', 'new'=>'int'],
'apcu_clear_cache' => ['bool'],
'apcu_dec' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool', 'ttl='=>'int'],
'apcu_delete' => ['bool', 'key'=>'string|APCUIterator'],
'apcu_delete\'1' => ['array<int,string>', 'key'=>'string[]'],
'apcu_enabled' => ['bool'],
'apcu_entry' => ['mixed', 'key'=>'string', 'generator'=>'callable', 'ttl='=>'int'],
'apcu_exists' => ['bool', 'keys'=>'string'],
'apcu_exists\'1' => ['array', 'keys'=>'string[]'],
'apcu_fetch' => ['mixed|false', 'key'=>'string', '&w_success='=>'bool'],
'apcu_fetch\'1' => ['array|false', 'key'=>'string[]', '&w_success='=>'bool'],
'apcu_inc' => ['int|false', 'key'=>'string', 'step='=>'int', '&w_success='=>'bool', 'ttl='=>'int'],
'apcu_key_info' => ['?array', 'key'=>'string'],
'apcu_sma_info' => ['array|false', 'limited='=>'bool'],
'apcu_store' => ['bool', 'key'=>'string', 'var='=>'', 'ttl='=>'int'],
'apcu_store\'1' => ['array', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'APCUIterator::__construct' => ['void', 'search='=>'string|string[]|null', 'format='=>'int', 'chunk_size='=>'int', 'list='=>'int'],
'APCUIterator::current' => ['mixed|false'],
'APCUIterator::getTotalCount' => ['int|false'],
'APCUIterator::getTotalHits' => ['int|false'],
'APCUIterator::getTotalSize' => ['int|false'],
'APCUIterator::key' => ['string|int|false'],
'APCUIterator::next' => ['bool'],
'APCUIterator::rewind' => ['void'],
'APCUIterator::valid' => ['bool'],
'apd_breakpoint' => ['bool', 'debug_level'=>'int'],
'apd_callstack' => ['array'],
'apd_clunk' => ['void', 'warning'=>'string', 'delimiter='=>'string'],
'apd_continue' => ['bool', 'debug_level'=>'int'],
'apd_croak' => ['void', 'warning'=>'string', 'delimiter='=>'string'],
'apd_dump_function_table' => ['void'],
'apd_dump_persistent_resources' => ['array'],
'apd_dump_regular_resources' => ['array'],
'apd_echo' => ['bool', 'output'=>'string'],
'apd_get_active_symbols' => ['array'],
'apd_set_pprof_trace' => ['string', 'dump_directory='=>'string', 'fragment='=>'string'],
'apd_set_session' => ['void', 'debug_level'=>'int'],
'apd_set_session_trace' => ['void', 'debug_level'=>'int', 'dump_directory='=>'string'],
'apd_set_session_trace_socket' => ['bool', 'tcp_server'=>'string', 'socket_type'=>'int', 'port'=>'int', 'debug_level'=>'int'],
'AppendIterator::__construct' => ['void'],
'AppendIterator::append' => ['void', 'iterator'=>'Iterator'],
'AppendIterator::current' => ['mixed'],
'AppendIterator::getArrayIterator' => ['ArrayIterator'],
'AppendIterator::getInnerIterator' => ['Iterator'],
'AppendIterator::getIteratorIndex' => ['int'],
'AppendIterator::key' => ['int|string|float|bool'],
'AppendIterator::next' => ['void'],
'AppendIterator::rewind' => ['void'],
'AppendIterator::valid' => ['bool'],
'ArgumentCountError::__clone' => ['void'],
'ArgumentCountError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'ArgumentCountError::__toString' => ['string'],
'ArgumentCountError::__wakeup' => ['void'],
'ArgumentCountError::getCode' => ['int'],
'ArgumentCountError::getFile' => ['string'],
'ArgumentCountError::getLine' => ['int'],
'ArgumentCountError::getMessage' => ['string'],
'ArgumentCountError::getPrevious' => ['?Throwable'],
'ArgumentCountError::getTrace' => ['array<int,array<string,mixed>>'],
'ArgumentCountError::getTraceAsString' => ['string'],
'ArithmeticError::__clone' => ['void'],
'ArithmeticError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'ArithmeticError::__toString' => ['string'],
'ArithmeticError::__wakeup' => ['void'],
'ArithmeticError::getCode' => ['int'],
'ArithmeticError::getFile' => ['string'],
'ArithmeticError::getLine' => ['int'],
'ArithmeticError::getMessage' => ['string'],
'ArithmeticError::getPrevious' => ['?Throwable'],
'ArithmeticError::getTrace' => ['array<int,array<string,mixed>>'],
'ArithmeticError::getTraceAsString' => ['string'],
'array_change_key_case' => ['array|false', 'input'=>'array', 'case='=>'int'],
'array_chunk' => ['array[]', 'input'=>'array', 'size'=>'int', 'preserve_keys='=>'bool'],
'array_column' => ['array', 'array'=>'array', 'column_key'=>'mixed', 'index_key='=>'mixed'],
'array_combine' => ['array|false', 'keys'=>'string[]|int[]', 'values'=>'array'],
'array_count_values' => ['int[]', 'input'=>'array'],
'array_diff' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_diff_assoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_diff_key' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_diff_uassoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_uassoc\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_diff_ukey' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_diff_ukey\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_fill' => ['array', 'start_key'=>'int', 'num'=>'int', 'val'=>'mixed'],
'array_fill_keys' => ['array', 'keys'=>'array', 'val'=>'mixed'],
'array_filter' => ['array', 'input'=>'array', 'callback='=>'callable(mixed,mixed=):scalar', 'flag='=>'int'],
'array_flip' => ['?array', 'input'=>'array'],
'array_intersect' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_intersect_assoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_intersect_key' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_intersect_uassoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_uassoc\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_intersect_ukey' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_intersect_ukey\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest'=>'array|callable(mixed,mixed):int'],
'array_key_exists' => ['bool', 'key'=>'string|int', 'search'=>'array|ArrayObject'],
'array_key_first' => ['int|string|null', 'array'=>'array'],
'array_key_last' => ['int|string|null', 'array'=>'array'],
'array_keys' => ['array<int,string>|array<int,int>', 'input'=>'array', 'search_value='=>'mixed', 'strict='=>'bool'],
'array_map' => ['array', 'callback'=>'?callable', 'input1'=>'array', '...args='=>'array'],
'array_merge' => ['array', 'arr1'=>'array', '...args='=>'array'],
'array_merge_recursive' => ['array', 'arr1'=>'array', '...args='=>'array'],
'array_multisort' => ['bool', '&rw_array1'=>'array', 'array1_sort_order='=>'array|int', 'array1_sort_flags='=>'array|int', '...args='=>'array|int'],
'array_pad' => ['array', 'input'=>'array', 'pad_size'=>'int', 'pad_value'=>'mixed'],
'array_pop' => ['mixed', '&rw_stack'=>'array'],
'array_product' => ['int|float', 'input'=>'array'],
'array_push' => ['int', '&rw_stack'=>'array', 'var'=>'mixed', '...vars='=>'mixed'],
'array_rand' => ['int|string|array<int,int>|array<int,string>', 'input'=>'array', 'num_req'=>'int'],
'array_rand\'1' => ['int|string', 'input'=>'array'],
'array_reduce' => ['mixed', 'input'=>'array', 'callback'=>'callable(mixed,mixed):mixed', 'initial='=>'mixed'],
'array_replace' => ['array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_replace_recursive' => ['?array', 'arr1'=>'array', 'arr2'=>'array', '...args='=>'array'],
'array_reverse' => ['array', 'input'=>'array', 'preserve='=>'bool'],
'array_search' => ['int|string|false', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'array_shift' => ['mixed|null', '&rw_stack'=>'array'],
'array_slice' => ['array', 'input'=>'array', 'offset'=>'int', 'length='=>'?int', 'preserve_keys='=>'bool'],
'array_splice' => ['array', '&rw_input'=>'array', 'offset'=>'int', 'length='=>'int', 'replacement='=>'array|string'],
'array_sum' => ['int|float', 'input'=>'array'],
'array_udiff' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_assoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_assoc\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_udiff_uassoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'data_comp_func'=>'callable(mixed,mixed):int', 'key_comp_func'=>'callable(mixed,mixed):int'],
'array_udiff_uassoc\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_assoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_assoc\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable', '...rest='=>'array|callable(mixed,mixed):int'],
'array_uintersect_uassoc' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'data_compare_func'=>'callable(mixed,mixed):int', 'key_compare_func'=>'callable(mixed,mixed):int'],
'array_uintersect_uassoc\'1' => ['array', 'arr1'=>'array', 'arr2'=>'array', 'arr3'=>'array', 'arg4'=>'array|callable(mixed,mixed):int', 'arg5'=>'array|callable(mixed,mixed):int', '...rest='=>'array|callable(mixed,mixed):int'],
'array_unique' => ['array', 'input'=>'array', 'sort_flags='=>'int'],
'array_unshift' => ['int', '&rw_stack'=>'array', 'var'=>'mixed', '...vars='=>'mixed'],
'array_values' => ['array', 'input'=>'array'],
'array_walk' => ['bool', '&rw_input'=>'array', 'callback'=>'callable', 'userdata='=>'mixed'],
'array_walk_recursive' => ['bool', '&rw_input'=>'array', 'callback'=>'callable', 'userdata='=>'mixed'],
'ArrayAccess::offsetExists' => ['bool', 'offset'=>'mixed'],
'ArrayAccess::offsetGet' => ['mixed', 'offset'=>'mixed'],
'ArrayAccess::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'ArrayAccess::offsetUnset' => ['void', 'offset'=>'mixed'],
'ArrayIterator::__construct' => ['void', 'array='=>'array|object', 'flags='=>'int'],
'ArrayIterator::append' => ['void', 'value'=>'mixed'],
'ArrayIterator::asort' => ['void'],
'ArrayIterator::count' => ['int'],
'ArrayIterator::current' => ['mixed'],
'ArrayIterator::getArrayCopy' => ['array'],
'ArrayIterator::getFlags' => ['int'],
'ArrayIterator::key' => ['int|string|false'],
'ArrayIterator::ksort' => ['void'],
'ArrayIterator::natcasesort' => ['void'],
'ArrayIterator::natsort' => ['void'],
'ArrayIterator::next' => ['void'],
'ArrayIterator::offsetExists' => ['bool', 'index'=>'string|int'],
'ArrayIterator::offsetGet' => ['mixed', 'index'=>'string|int'],
'ArrayIterator::offsetSet' => ['void', 'index'=>'string|int', 'newval'=>'mixed'],
'ArrayIterator::offsetUnset' => ['void', 'index'=>'string|int'],
'ArrayIterator::rewind' => ['void'],
'ArrayIterator::seek' => ['void', 'position'=>'int'],
'ArrayIterator::serialize' => ['string'],
'ArrayIterator::setFlags' => ['void', 'flags'=>'string'],
'ArrayIterator::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayIterator::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayIterator::unserialize' => ['void', 'serialized'=>'string'],
'ArrayIterator::valid' => ['bool'],
'ArrayObject::__construct' => ['void', 'input='=>'array|object', 'flags='=>'int', 'iterator_class='=>'string'],
'ArrayObject::append' => ['void', 'value'=>'mixed'],
'ArrayObject::asort' => ['void'],
'ArrayObject::count' => ['int'],
'ArrayObject::exchangeArray' => ['array', 'ar'=>'mixed'],
'ArrayObject::getArrayCopy' => ['array'],
'ArrayObject::getFlags' => ['int'],
'ArrayObject::getIterator' => ['ArrayIterator'],
'ArrayObject::getIteratorClass' => ['string'],
'ArrayObject::ksort' => ['void'],
'ArrayObject::natcasesort' => ['void'],
'ArrayObject::natsort' => ['void'],
'ArrayObject::offsetExists' => ['bool', 'index'=>'int|string'],
'ArrayObject::offsetGet' => ['mixed|null', 'index'=>'int|string'],
'ArrayObject::offsetSet' => ['void', 'index'=>'int|string', 'newval'=>'mixed'],
'ArrayObject::offsetUnset' => ['void', 'index'=>'int|string'],
'ArrayObject::serialize' => ['string'],
'ArrayObject::setFlags' => ['void', 'flags'=>'int'],
'ArrayObject::setIteratorClass' => ['void', 'iterator_class'=>'string'],
'ArrayObject::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayObject::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'ArrayObject::unserialize' => ['void', 'serialized'=>'string'],
'arsort' => ['bool', '&rw_array_arg'=>'array', 'sort_flags='=>'int'],
'asin' => ['float', 'number'=>'float'],
'asinh' => ['float', 'number'=>'float'],
'asort' => ['bool', '&rw_array_arg'=>'array', 'sort_flags='=>'int'],
'assert' => ['bool', 'assertion'=>'string|bool', 'description='=>'string|Throwable|null'],
'assert_options' => ['mixed|false', 'what'=>'int', 'value='=>'mixed'],
'ast\get_kind_name' => ['string', 'kind'=>'int'],
'ast\get_metadata' => ['array<int,ast\Metadata>'],
'ast\get_supported_versions' => ['array<int,int>', 'exclude_deprecated='=>'bool'],
'ast\kind_uses_flags' => ['bool', 'kind'=>'int'],
'ast\Node::__construct' => ['void', 'kind='=>'int', 'flags='=>'int', 'children='=>'ast\Node\Decl[]|ast\Node[]|int[]|string[]|float[]|bool[]|null[]', 'start_line='=>'int'],
'ast\parse_code' => ['ast\Node', 'code'=>'string', 'version'=>'int', 'filename='=>'string'],
'ast\parse_file' => ['ast\Node', 'filename'=>'string', 'version'=>'int'],
'atan' => ['float', 'number'=>'float'],
'atan2' => ['float', 'y'=>'float', 'x'=>'float'],
'atanh' => ['float', 'number'=>'float'],
'BadFunctionCallException::__clone' => ['void'],
'BadFunctionCallException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?BadFunctionCallException'],
'BadFunctionCallException::__toString' => ['string'],
'BadFunctionCallException::getCode' => ['int'],
'BadFunctionCallException::getFile' => ['string'],
'BadFunctionCallException::getLine' => ['int'],
'BadFunctionCallException::getMessage' => ['string'],
'BadFunctionCallException::getPrevious' => ['?Throwable|?BadFunctionCallException'],
'BadFunctionCallException::getTrace' => ['array'],
'BadFunctionCallException::getTraceAsString' => ['string'],
'BadMethodCallException::__clone' => ['void'],
'BadMethodCallException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?BadMethodCallException'],
'BadMethodCallException::__toString' => ['string'],
'BadMethodCallException::getCode' => ['int'],
'BadMethodCallException::getFile' => ['string'],
'BadMethodCallException::getLine' => ['int'],
'BadMethodCallException::getMessage' => ['string'],
'BadMethodCallException::getPrevious' => ['?Throwable|?BadMethodCallException'],
'BadMethodCallException::getTrace' => ['array'],
'BadMethodCallException::getTraceAsString' => ['string'],
'base64_decode' => ['string|false', 'str'=>'string', 'strict='=>'bool'],
'base64_encode' => ['string', 'str'=>'string'],
'base_convert' => ['string', 'number'=>'string', 'frombase'=>'int', 'tobase'=>'int'],
'basename' => ['string', 'path'=>'string', 'suffix='=>'string'],
'bbcode_add_element' => ['bool', 'bbcode_container'=>'resource', 'tag_name'=>'string', 'tag_rules'=>'array'],
'bbcode_add_smiley' => ['bool', 'bbcode_container'=>'resource', 'smiley'=>'string', 'replace_by'=>'string'],
'bbcode_create' => ['resource', 'bbcode_initial_tags='=>'array'],
'bbcode_destroy' => ['bool', 'bbcode_container'=>'resource'],
'bbcode_parse' => ['string', 'bbcode_container'=>'resource', 'to_parse'=>'string'],
'bbcode_set_arg_parser' => ['bool', 'bbcode_container'=>'resource', 'bbcode_arg_parser'=>'resource'],
'bbcode_set_flags' => ['bool', 'bbcode_container'=>'resource', 'flags'=>'int', 'mode='=>'int'],
'bcadd' => ['string', 'left_operand'=>'string', 'right_operand'=>'string', 'scale='=>'int'],
'bccomp' => ['int', 'left_operand'=>'string', 'right_operand'=>'string', 'scale='=>'int'],
'bcdiv' => ['?string', 'left_operand'=>'string', 'right_operand'=>'string', 'scale='=>'int'],
'bcmod' => ['?string', 'left_operand'=>'string', 'right_operand'=>'string', 'scale='=>'int'],
'bcmul' => ['string', 'left_operand'=>'string', 'right_operand'=>'string', 'scale='=>'int'],
'bcompiler_load' => ['bool', 'filename'=>'string'],
'bcompiler_load_exe' => ['bool', 'filename'=>'string'],
'bcompiler_parse_class' => ['bool', 'class'=>'string', 'callback'=>'string'],
'bcompiler_read' => ['bool', 'filehandle'=>'resource'],
'bcompiler_write_class' => ['bool', 'filehandle'=>'resource', 'classname'=>'string', 'extends='=>'string'],
'bcompiler_write_constant' => ['bool', 'filehandle'=>'resource', 'constantname'=>'string'],
'bcompiler_write_exe_footer' => ['bool', 'filehandle'=>'resource', 'startpos'=>'int'],
'bcompiler_write_file' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcompiler_write_footer' => ['bool', 'filehandle'=>'resource'],
'bcompiler_write_function' => ['bool', 'filehandle'=>'resource', 'functionname'=>'string'],
'bcompiler_write_functions_from_file' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcompiler_write_header' => ['bool', 'filehandle'=>'resource', 'write_ver='=>'string'],
'bcompiler_write_included_filename' => ['bool', 'filehandle'=>'resource', 'filename'=>'string'],
'bcpow' => ['string', 'base'=>'string', 'exponent'=>'string', 'scale='=>'int'],
'bcpowmod' => ['?string', 'base'=>'string', 'exponent'=>'string', 'modulus'=>'string', 'scale='=>'int'],
'bcscale' => ['int', 'scale='=>'int'],
'bcsqrt' => ['string', 'operand'=>'string', 'scale='=>'int'],
'bcsub' => ['string', 'left_operand'=>'string', 'right_operand'=>'string', 'scale='=>'int'],
'bin2hex' => ['string', 'data'=>'string'],
'bind_textdomain_codeset' => ['string', 'domain'=>'string', 'codeset'=>'string'],
'bindec' => ['int|float', 'binary_number'=>'string'],
'bindtextdomain' => ['string', 'domain_name'=>'string', 'dir'=>'string'],
'birdstep_autocommit' => ['bool', 'index'=>'int'],
'birdstep_close' => ['bool', 'id'=>'int'],
'birdstep_commit' => ['bool', 'index'=>'int'],
'birdstep_connect' => ['int', 'server'=>'string', 'user'=>'string', 'pass'=>'string'],
'birdstep_exec' => ['int', 'index'=>'int', 'exec_str'=>'string'],
'birdstep_fetch' => ['bool', 'index'=>'int'],
'birdstep_fieldname' => ['string', 'index'=>'int', 'col'=>'int'],
'birdstep_fieldnum' => ['int', 'index'=>'int'],
'birdstep_freeresult' => ['bool', 'index'=>'int'],
'birdstep_off_autocommit' => ['bool', 'index'=>'int'],
'birdstep_result' => ['', 'index'=>'int', 'col'=>''],
'birdstep_rollback' => ['bool', 'index'=>'int'],
'blenc_encrypt' => ['string', 'plaintext'=>'string', 'encodedfile'=>'string', 'encryption_key='=>'string'],
'boolval' => ['bool', 'var'=>'mixed'],
'bson_decode' => ['array', 'bson'=>'string'],
'bson_encode' => ['string', 'anything'=>'mixed'],
'bzclose' => ['bool', 'bz'=>'resource'],
'bzcompress' => ['string|int', 'source'=>'string', 'blocksize100k='=>'int', 'workfactor='=>'int'],
'bzdecompress' => ['string|int', 'source'=>'string', 'small='=>'int'],
'bzerrno' => ['int', 'bz'=>'resource'],
'bzerror' => ['array', 'bz'=>'resource'],
'bzerrstr' => ['string', 'bz'=>'resource'],
'bzflush' => ['bool', 'bz'=>'resource'],
'bzopen' => ['resource|false', 'file'=>'string|resource', 'mode'=>'string'],
'bzread' => ['string|false', 'bz'=>'resource', 'length='=>'int'],
'bzwrite' => ['int|false', 'bz'=>'resource', 'data'=>'string', 'length='=>'int'],
'CachingIterator::__construct' => ['void', 'iterator'=>'Iterator', 'flags='=>''],
'CachingIterator::__toString' => ['string'],
'CachingIterator::count' => ['int'],
'CachingIterator::current' => ['mixed'],
'CachingIterator::getCache' => ['array'],
'CachingIterator::getFlags' => ['int'],
'CachingIterator::getInnerIterator' => ['Iterator'],
'CachingIterator::hasNext' => ['bool'],
'CachingIterator::key' => ['int|string|float|bool'],
'CachingIterator::next' => ['void'],
'CachingIterator::offsetExists' => ['bool', 'index'=>'string'],
'CachingIterator::offsetGet' => ['mixed', 'index'=>'string'],
'CachingIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'mixed'],
'CachingIterator::offsetUnset' => ['void', 'index'=>'string'],
'CachingIterator::rewind' => ['void'],
'CachingIterator::setFlags' => ['void', 'flags'=>'int'],
'CachingIterator::valid' => ['bool'],
'Cairo::availableFonts' => ['array'],
'Cairo::availableSurfaces' => ['array'],
'Cairo::statusToString' => ['string', 'status'=>'int'],
'Cairo::version' => ['int'],
'Cairo::versionString' => ['string'],
'cairo_append_path' => ['', 'path'=>'cairopath', 'context'=>'cairocontext'],
'cairo_arc' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'cairo_arc_negative' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'cairo_available_fonts' => ['array'],
'cairo_available_surfaces' => ['array'],
'cairo_clip' => ['', 'context'=>'cairocontext'],
'cairo_clip_extents' => ['array', 'context'=>'cairocontext'],
'cairo_clip_preserve' => ['', 'context'=>'cairocontext'],
'cairo_clip_rectangle_list' => ['array', 'context'=>'cairocontext'],
'cairo_close_path' => ['', 'context'=>'cairocontext'],
'cairo_copy_page' => ['', 'context'=>'cairocontext'],
'cairo_copy_path' => ['CairoPath', 'context'=>'cairocontext'],
'cairo_copy_path_flat' => ['CairoPath', 'context'=>'cairocontext'],
'cairo_create' => ['CairoContext', 'surface'=>'cairosurface'],
'cairo_curve_to' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float', 'context'=>'cairocontext'],
'cairo_device_to_user' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'cairo_device_to_user_distance' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'cairo_fill' => ['', 'context'=>'cairocontext'],
'cairo_fill_extents' => ['array', 'context'=>'cairocontext'],
'cairo_fill_preserve' => ['', 'context'=>'cairocontext'],
'cairo_font_extents' => ['array', 'context'=>'cairocontext'],
'cairo_font_face_get_type' => ['int', 'fontface'=>'cairofontface'],
'cairo_font_face_status' => ['int', 'fontface'=>'cairofontface'],
'cairo_font_options_create' => ['CairoFontOptions'],
'cairo_font_options_equal' => ['bool', 'options'=>'cairofontoptions', 'other'=>'cairofontoptions'],
'cairo_font_options_get_antialias' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_hint_metrics' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_hint_style' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_get_subpixel_order' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_hash' => ['int', 'options'=>'cairofontoptions'],
'cairo_font_options_merge' => ['void', 'options'=>'cairofontoptions', 'other'=>'cairofontoptions'],
'cairo_font_options_set_antialias' => ['void', 'options'=>'cairofontoptions', 'antialias'=>'int'],
'cairo_font_options_set_hint_metrics' => ['void', 'options'=>'cairofontoptions', 'hint_metrics'=>'int'],
'cairo_font_options_set_hint_style' => ['void', 'options'=>'cairofontoptions', 'hint_style'=>'int'],
'cairo_font_options_set_subpixel_order' => ['void', 'options'=>'cairofontoptions', 'subpixel_order'=>'int'],
'cairo_font_options_status' => ['int', 'options'=>'cairofontoptions'],
'cairo_format_stride_for_width' => ['int', 'format'=>'int', 'width'=>'int'],
'cairo_get_antialias' => ['int', 'context'=>'cairocontext'],
'cairo_get_current_point' => ['array', 'context'=>'cairocontext'],
'cairo_get_dash' => ['array', 'context'=>'cairocontext'],
'cairo_get_dash_count' => ['int', 'context'=>'cairocontext'],
'cairo_get_fill_rule' => ['int', 'context'=>'cairocontext'],
'cairo_get_font_face' => ['', 'context'=>'cairocontext'],
'cairo_get_font_matrix' => ['', 'context'=>'cairocontext'],
'cairo_get_font_options' => ['', 'context'=>'cairocontext'],
'cairo_get_group_target' => ['', 'context'=>'cairocontext'],
'cairo_get_line_cap' => ['int', 'context'=>'cairocontext'],
'cairo_get_line_join' => ['int', 'context'=>'cairocontext'],
'cairo_get_line_width' => ['float', 'context'=>'cairocontext'],
'cairo_get_matrix' => ['', 'context'=>'cairocontext'],
'cairo_get_miter_limit' => ['float', 'context'=>'cairocontext'],
'cairo_get_operator' => ['int', 'context'=>'cairocontext'],
'cairo_get_scaled_font' => ['', 'context'=>'cairocontext'],
'cairo_get_source' => ['', 'context'=>'cairocontext'],
'cairo_get_target' => ['', 'context'=>'cairocontext'],
'cairo_get_tolerance' => ['float', 'context'=>'cairocontext'],
'cairo_glyph_path' => ['', 'glyphs'=>'array', 'context'=>'cairocontext'],
'cairo_has_current_point' => ['bool', 'context'=>'cairocontext'],
'cairo_identity_matrix' => ['', 'context'=>'cairocontext'],
'cairo_image_surface_create' => ['CairoImageSurface', 'format'=>'int', 'width'=>'int', 'height'=>'int'],
'cairo_image_surface_create_for_data' => ['CairoImageSurface', 'data'=>'string', 'format'=>'int', 'width'=>'int', 'height'=>'int', 'stride='=>'int'],
'cairo_image_surface_create_from_png' => ['CairoImageSurface', 'file'=>'string'],
'cairo_image_surface_get_data' => ['string', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_format' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_height' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_stride' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_image_surface_get_width' => ['int', 'surface'=>'cairoimagesurface'],
'cairo_in_fill' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_in_stroke' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_line_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_mask' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'cairo_mask_surface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'cairo_matrix_create_scale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'cairo_matrix_init' => ['object', 'xx='=>'float', 'yx='=>'float', 'xy='=>'float', 'yy='=>'float', 'x0='=>'float', 'y0='=>'float'],
'cairo_matrix_init_identity' => ['object'],
'cairo_matrix_init_rotate' => ['object', 'radians'=>'float'],
'cairo_matrix_init_scale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'cairo_matrix_init_translate' => ['object', 'tx'=>'float', 'ty'=>'float'],
'cairo_matrix_invert' => ['void', 'matrix'=>'cairomatrix'],
'cairo_matrix_multiply' => ['CairoMatrix', 'matrix1'=>'cairomatrix', 'matrix2'=>'cairomatrix'],
'cairo_matrix_rotate' => ['', 'matrix'=>'cairomatrix', 'radians'=>'float'],
'cairo_matrix_scale' => ['', 'sx'=>'float', 'sy'=>'float', 'context'=>'cairocontext'],
'cairo_matrix_transform_distance' => ['array', 'matrix'=>'cairomatrix', 'dx'=>'float', 'dy'=>'float'],
'cairo_matrix_transform_point' => ['array', 'matrix'=>'cairomatrix', 'dx'=>'float', 'dy'=>'float'],
'cairo_matrix_translate' => ['void', 'matrix'=>'cairomatrix', 'tx'=>'float', 'ty'=>'float'],
'cairo_move_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_new_path' => ['', 'context'=>'cairocontext'],
'cairo_new_sub_path' => ['', 'context'=>'cairocontext'],
'cairo_paint' => ['', 'context'=>'cairocontext'],
'cairo_paint_with_alpha' => ['', 'alpha'=>'string', 'context'=>'cairocontext'],
'cairo_path_extents' => ['array', 'context'=>'cairocontext'],
'cairo_pattern_add_color_stop_rgb' => ['void', 'pattern'=>'cairogradientpattern', 'offset'=>'float', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'cairo_pattern_add_color_stop_rgba' => ['void', 'pattern'=>'cairogradientpattern', 'offset'=>'float', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha'=>'float'],
'cairo_pattern_create_for_surface' => ['CairoPattern', 'surface'=>'cairosurface'],
'cairo_pattern_create_linear' => ['CairoPattern', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float'],
'cairo_pattern_create_radial' => ['CairoPattern', 'x0'=>'float', 'y0'=>'float', 'r0'=>'float', 'x1'=>'float', 'y1'=>'float', 'r1'=>'float'],
'cairo_pattern_create_rgb' => ['CairoPattern', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'cairo_pattern_create_rgba' => ['CairoPattern', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha'=>'float'],
'cairo_pattern_get_color_stop_count' => ['int', 'pattern'=>'cairogradientpattern'],
'cairo_pattern_get_color_stop_rgba' => ['array', 'pattern'=>'cairogradientpattern', 'index'=>'int'],
'cairo_pattern_get_extend' => ['int', 'pattern'=>'string'],
'cairo_pattern_get_filter' => ['int', 'pattern'=>'cairosurfacepattern'],
'cairo_pattern_get_linear_points' => ['array', 'pattern'=>'cairolineargradient'],
'cairo_pattern_get_matrix' => ['CairoMatrix', 'pattern'=>'cairopattern'],
'cairo_pattern_get_radial_circles' => ['array', 'pattern'=>'cairoradialgradient'],
'cairo_pattern_get_rgba' => ['array', 'pattern'=>'cairosolidpattern'],
'cairo_pattern_get_surface' => ['CairoSurface', 'pattern'=>'cairosurfacepattern'],
'cairo_pattern_get_type' => ['int', 'pattern'=>'cairopattern'],
'cairo_pattern_set_extend' => ['void', 'pattern'=>'string', 'extend'=>'string'],
'cairo_pattern_set_filter' => ['void', 'pattern'=>'cairosurfacepattern', 'filter'=>'int'],
'cairo_pattern_set_matrix' => ['void', 'pattern'=>'cairopattern', 'matrix'=>'cairomatrix'],
'cairo_pattern_status' => ['int', 'pattern'=>'cairopattern'],
'cairo_pdf_surface_create' => ['CairoPdfSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_pdf_surface_set_size' => ['void', 'surface'=>'cairopdfsurface', 'width'=>'float', 'height'=>'float'],
'cairo_pop_group' => ['', 'context'=>'cairocontext'],
'cairo_pop_group_to_source' => ['', 'context'=>'cairocontext'],
'cairo_ps_get_levels' => ['array'],
'cairo_ps_level_to_string' => ['string', 'level'=>'int'],
'cairo_ps_surface_create' => ['CairoPsSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_ps_surface_dsc_begin_page_setup' => ['void', 'surface'=>'cairopssurface'],
'cairo_ps_surface_dsc_begin_setup' => ['void', 'surface'=>'cairopssurface'],
'cairo_ps_surface_dsc_comment' => ['void', 'surface'=>'cairopssurface', 'comment'=>'string'],
'cairo_ps_surface_get_eps' => ['bool', 'surface'=>'cairopssurface'],
'cairo_ps_surface_restrict_to_level' => ['void', 'surface'=>'cairopssurface', 'level'=>'int'],
'cairo_ps_surface_set_eps' => ['void', 'surface'=>'cairopssurface', 'level'=>'bool'],
'cairo_ps_surface_set_size' => ['void', 'surface'=>'cairopssurface', 'width'=>'float', 'height'=>'float'],
'cairo_push_group' => ['', 'context'=>'cairocontext'],
'cairo_push_group_with_content' => ['', 'content'=>'string', 'context'=>'cairocontext'],
'cairo_rectangle' => ['', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string', 'context'=>'cairocontext'],
'cairo_rel_curve_to' => ['', 'x1'=>'string', 'y1'=>'string', 'x2'=>'string', 'y2'=>'string', 'x3'=>'string', 'y3'=>'string', 'context'=>'cairocontext'],
'cairo_rel_line_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_rel_move_to' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_reset_clip' => ['', 'context'=>'cairocontext'],
'cairo_restore' => ['', 'context'=>'cairocontext'],
'cairo_rotate' => ['', 'sx'=>'string', 'sy'=>'string', 'context'=>'cairocontext', 'angle'=>'string'],
'cairo_save' => ['', 'context'=>'cairocontext'],
'cairo_scale' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_scaled_font_create' => ['CairoScaledFont', 'fontface'=>'cairofontface', 'matrix'=>'cairomatrix', 'ctm'=>'cairomatrix', 'fontoptions'=>'cairofontoptions'],
'cairo_scaled_font_extents' => ['array', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_ctm' => ['CairoMatrix', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_face' => ['CairoFontFace', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_matrix' => ['CairoFontOptions', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_font_options' => ['CairoFontOptions', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_scale_matrix' => ['CairoMatrix', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_get_type' => ['int', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_glyph_extents' => ['array', 'scaledfont'=>'cairoscaledfont', 'glyphs'=>'array'],
'cairo_scaled_font_status' => ['int', 'scaledfont'=>'cairoscaledfont'],
'cairo_scaled_font_text_extents' => ['array', 'scaledfont'=>'cairoscaledfont', 'text'=>'string'],
'cairo_select_font_face' => ['', 'family'=>'string', 'slant='=>'string', 'weight='=>'string', 'context='=>'cairocontext'],
'cairo_set_antialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'cairo_set_dash' => ['', 'dashes'=>'array', 'offset='=>'string', 'context='=>'cairocontext'],
'cairo_set_fill_rule' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_font_face' => ['', 'fontface'=>'cairofontface', 'context'=>'cairocontext'],
'cairo_set_font_matrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_set_font_options' => ['', 'fontoptions'=>'cairofontoptions', 'context'=>'cairocontext'],
'cairo_set_font_size' => ['', 'size'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_cap' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_join' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_line_width' => ['', 'width'=>'string', 'context'=>'cairocontext'],
'cairo_set_matrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_set_miter_limit' => ['', 'limit'=>'string', 'context'=>'cairocontext'],
'cairo_set_operator' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'cairo_set_scaled_font' => ['', 'scaledfont'=>'cairoscaledfont', 'context'=>'cairocontext'],
'cairo_set_source' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'cairo_set_source_surface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'cairo_set_tolerance' => ['', 'tolerance'=>'string', 'context'=>'cairocontext'],
'cairo_show_page' => ['', 'context'=>'cairocontext'],
'cairo_show_text' => ['', 'text'=>'string', 'context'=>'cairocontext'],
'cairo_status' => ['int', 'context'=>'cairocontext'],
'cairo_status_to_string' => ['string', 'status'=>'int'],
'cairo_stroke' => ['', 'context'=>'cairocontext'],
'cairo_stroke_extents' => ['array', 'context'=>'cairocontext'],
'cairo_stroke_preserve' => ['', 'context'=>'cairocontext'],
'cairo_surface_copy_page' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_create_similar' => ['CairoSurface', 'surface'=>'cairosurface', 'content'=>'int', 'width'=>'float', 'height'=>'float'],
'cairo_surface_finish' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_flush' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_get_content' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_get_device_offset' => ['array', 'surface'=>'cairosurface'],
'cairo_surface_get_font_options' => ['CairoFontOptions', 'surface'=>'cairosurface'],
'cairo_surface_get_type' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_mark_dirty' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_mark_dirty_rectangle' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'cairo_surface_set_device_offset' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float'],
'cairo_surface_set_fallback_resolution' => ['void', 'surface'=>'cairosurface', 'x'=>'float', 'y'=>'float'],
'cairo_surface_show_page' => ['void', 'surface'=>'cairosurface'],
'cairo_surface_status' => ['int', 'surface'=>'cairosurface'],
'cairo_surface_write_to_png' => ['void', 'surface'=>'cairosurface', 'stream'=>'resource'],
'cairo_svg_get_versions' => ['array'],
'cairo_svg_surface_create' => ['CairoSvgSurface', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'cairo_svg_surface_get_versions' => ['array'],
'cairo_svg_surface_restrict_to_version' => ['void', 'surface'=>'cairosvgsurface', 'version'=>'int'],
'cairo_svg_version_to_string' => ['string', 'version'=>'int'],
'cairo_text_extents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'cairo_text_path' => ['', 'string'=>'string', 'context'=>'cairocontext', 'text'=>'string'],
'cairo_transform' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'cairo_translate' => ['', 'tx'=>'string', 'ty'=>'string', 'context'=>'cairocontext', 'x'=>'string', 'y'=>'string'],
'cairo_user_to_device' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_user_to_device_distance' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'cairo_version' => ['int'],
'cairo_version_string' => ['string'],
'CairoContext::__construct' => ['void', 'surface'=>'CairoSurface'],
'CairoContext::appendPath' => ['', 'path'=>'cairopath', 'context'=>'cairocontext'],
'CairoContext::arc' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'CairoContext::arcNegative' => ['', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'angle1'=>'float', 'angle2'=>'float', 'context'=>'cairocontext'],
'CairoContext::clip' => ['', 'context'=>'cairocontext'],
'CairoContext::clipExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::clipPreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::clipRectangleList' => ['array', 'context'=>'cairocontext'],
'CairoContext::closePath' => ['', 'context'=>'cairocontext'],
'CairoContext::copyPage' => ['', 'context'=>'cairocontext'],
'CairoContext::copyPath' => ['CairoPath', 'context'=>'cairocontext'],
'CairoContext::copyPathFlat' => ['CairoPath', 'context'=>'cairocontext'],
'CairoContext::curveTo' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float', 'context'=>'cairocontext'],
'CairoContext::deviceToUser' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'CairoContext::deviceToUserDistance' => ['array', 'x'=>'float', 'y'=>'float', 'context'=>'cairocontext'],
'CairoContext::fill' => ['', 'context'=>'cairocontext'],
'CairoContext::fillExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::fillPreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::fontExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::getAntialias' => ['int', 'context'=>'cairocontext'],
'CairoContext::getCurrentPoint' => ['array', 'context'=>'cairocontext'],
'CairoContext::getDash' => ['array', 'context'=>'cairocontext'],
'CairoContext::getDashCount' => ['int', 'context'=>'cairocontext'],
'CairoContext::getFillRule' => ['int', 'context'=>'cairocontext'],
'CairoContext::getFontFace' => ['', 'context'=>'cairocontext'],
'CairoContext::getFontMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoContext::getGroupTarget' => ['', 'context'=>'cairocontext'],
'CairoContext::getLineCap' => ['int', 'context'=>'cairocontext'],
'CairoContext::getLineJoin' => ['int', 'context'=>'cairocontext'],
'CairoContext::getLineWidth' => ['float', 'context'=>'cairocontext'],
'CairoContext::getMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::getMiterLimit' => ['float', 'context'=>'cairocontext'],
'CairoContext::getOperator' => ['int', 'context'=>'cairocontext'],
'CairoContext::getScaledFont' => ['', 'context'=>'cairocontext'],
'CairoContext::getSource' => ['', 'context'=>'cairocontext'],
'CairoContext::getTarget' => ['', 'context'=>'cairocontext'],
'CairoContext::getTolerance' => ['float', 'context'=>'cairocontext'],
'CairoContext::glyphPath' => ['', 'glyphs'=>'array', 'context'=>'cairocontext'],
'CairoContext::hasCurrentPoint' => ['bool', 'context'=>'cairocontext'],
'CairoContext::identityMatrix' => ['', 'context'=>'cairocontext'],
'CairoContext::inFill' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::inStroke' => ['bool', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::lineTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::mask' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'CairoContext::maskSurface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'CairoContext::moveTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::newPath' => ['', 'context'=>'cairocontext'],
'CairoContext::newSubPath' => ['', 'context'=>'cairocontext'],
'CairoContext::paint' => ['', 'context'=>'cairocontext'],
'CairoContext::paintWithAlpha' => ['', 'alpha'=>'string', 'context'=>'cairocontext'],
'CairoContext::pathExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::popGroup' => ['', 'context'=>'cairocontext'],
'CairoContext::popGroupToSource' => ['', 'context'=>'cairocontext'],
'CairoContext::pushGroup' => ['', 'context'=>'cairocontext'],
'CairoContext::pushGroupWithContent' => ['', 'content'=>'string', 'context'=>'cairocontext'],
'CairoContext::rectangle' => ['', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string', 'context'=>'cairocontext'],
'CairoContext::relCurveTo' => ['', 'x1'=>'string', 'y1'=>'string', 'x2'=>'string', 'y2'=>'string', 'x3'=>'string', 'y3'=>'string', 'context'=>'cairocontext'],
'CairoContext::relLineTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::relMoveTo' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::resetClip' => ['', 'context'=>'cairocontext'],
'CairoContext::restore' => ['', 'context'=>'cairocontext'],
'CairoContext::rotate' => ['', 'angle'=>'string', 'context'=>'cairocontext'],
'CairoContext::save' => ['', 'context'=>'cairocontext'],
'CairoContext::scale' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::selectFontFace' => ['', 'family'=>'string', 'slant='=>'string', 'weight='=>'string', 'context='=>'cairocontext'],
'CairoContext::setAntialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'CairoContext::setDash' => ['', 'dashes'=>'array', 'offset='=>'string', 'context='=>'cairocontext'],
'CairoContext::setFillRule' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setFontFace' => ['', 'fontface'=>'cairofontface', 'context'=>'cairocontext'],
'CairoContext::setFontMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::setFontOptions' => ['', 'fontoptions'=>'cairofontoptions', 'context'=>'cairocontext'],
'CairoContext::setFontSize' => ['', 'size'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineCap' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineJoin' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setLineWidth' => ['', 'width'=>'string', 'context'=>'cairocontext'],
'CairoContext::setMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::setMiterLimit' => ['', 'limit'=>'string', 'context'=>'cairocontext'],
'CairoContext::setOperator' => ['', 'setting'=>'string', 'context'=>'cairocontext'],
'CairoContext::setScaledFont' => ['', 'scaledfont'=>'cairoscaledfont', 'context'=>'cairocontext'],
'CairoContext::setSource' => ['', 'pattern'=>'cairopattern', 'context'=>'cairocontext'],
'CairoContext::setSourceRGB' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'CairoContext::setSourceRGBA' => ['', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string', 'context'=>'cairocontext', 'pattern'=>'cairopattern'],
'CairoContext::setSourceSurface' => ['', 'surface'=>'cairosurface', 'x='=>'string', 'y='=>'string', 'context='=>'cairocontext'],
'CairoContext::setTolerance' => ['', 'tolerance'=>'string', 'context'=>'cairocontext'],
'CairoContext::showPage' => ['', 'context'=>'cairocontext'],
'CairoContext::showText' => ['', 'text'=>'string', 'context'=>'cairocontext'],
'CairoContext::status' => ['int', 'context'=>'cairocontext'],
'CairoContext::stroke' => ['', 'context'=>'cairocontext'],
'CairoContext::strokeExtents' => ['array', 'context'=>'cairocontext'],
'CairoContext::strokePreserve' => ['', 'context'=>'cairocontext'],
'CairoContext::textExtents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'CairoContext::textPath' => ['', 'string'=>'string', 'context'=>'cairocontext', 'text'=>'string'],
'CairoContext::transform' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoContext::translate' => ['', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::userToDevice' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoContext::userToDeviceDistance' => ['array', 'x'=>'string', 'y'=>'string', 'context'=>'cairocontext'],
'CairoFontFace::__construct' => ['void'],
'CairoFontFace::getType' => ['int'],
'CairoFontFace::status' => ['int', 'fontface'=>'cairofontface'],
'CairoFontOptions::__construct' => ['void'],
'CairoFontOptions::equal' => ['bool', 'other'=>'string'],
'CairoFontOptions::getAntialias' => ['int', 'context'=>'cairocontext'],
'CairoFontOptions::getHintMetrics' => ['int'],
'CairoFontOptions::getHintStyle' => ['int'],
'CairoFontOptions::getSubpixelOrder' => ['int'],
'CairoFontOptions::hash' => ['int'],
'CairoFontOptions::merge' => ['void', 'other'=>'string'],
'CairoFontOptions::setAntialias' => ['', 'antialias='=>'string', 'context='=>'cairocontext'],
'CairoFontOptions::setHintMetrics' => ['void', 'hint_metrics'=>'string'],
'CairoFontOptions::setHintStyle' => ['void', 'hint_style'=>'string'],
'CairoFontOptions::setSubpixelOrder' => ['void', 'subpixel_order'=>'string'],
'CairoFontOptions::status' => ['int', 'context'=>'cairocontext'],
'CairoFormat::strideForWidth' => ['int', 'format'=>'int', 'width'=>'int'],
'CairoGradientPattern::addColorStopRgb' => ['void', 'offset'=>'string', 'red'=>'string', 'green'=>'string', 'blue'=>'string'],
'CairoGradientPattern::addColorStopRgba' => ['void', 'offset'=>'string', 'red'=>'string', 'green'=>'string', 'blue'=>'string', 'alpha'=>'string'],
'CairoGradientPattern::getColorStopCount' => ['int'],
'CairoGradientPattern::getColorStopRgba' => ['array', 'index'=>'string'],
'CairoGradientPattern::getExtend' => ['int'],
'CairoGradientPattern::setExtend' => ['void', 'extend'=>'int'],
'CairoImageSurface::__construct' => ['void', 'format'=>'int', 'width'=>'int', 'height'=>'int'],
'CairoImageSurface::createForData' => ['void', 'data'=>'string', 'format'=>'int', 'width'=>'int', 'height'=>'int', 'stride='=>'int'],
'CairoImageSurface::createFromPng' => ['CairoImageSurface', 'file'=>'string'],
'CairoImageSurface::getData' => ['string'],
'CairoImageSurface::getFormat' => ['int'],
'CairoImageSurface::getHeight' => ['int'],
'CairoImageSurface::getStride' => ['int'],
'CairoImageSurface::getWidth' => ['int'],
'CairoLinearGradient::__construct' => ['void', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float'],
'CairoLinearGradient::getPoints' => ['array'],
'CairoMatrix::__construct' => ['void', 'xx='=>'float', 'yx='=>'float', 'xy='=>'float', 'yy='=>'float', 'x0='=>'float', 'y0='=>'float'],
'CairoMatrix::initIdentity' => ['object'],
'CairoMatrix::initRotate' => ['object', 'radians'=>'float'],
'CairoMatrix::initScale' => ['object', 'sx'=>'float', 'sy'=>'float'],
'CairoMatrix::initTranslate' => ['object', 'tx'=>'float', 'ty'=>'float'],
'CairoMatrix::invert' => ['void'],
'CairoMatrix::multiply' => ['CairoMatrix', 'matrix1'=>'cairomatrix', 'matrix2'=>'cairomatrix'],
'CairoMatrix::rotate' => ['', 'sx'=>'string', 'sy'=>'string', 'context'=>'cairocontext', 'angle'=>'string'],
'CairoMatrix::scale' => ['', 'sx'=>'float', 'sy'=>'float', 'context'=>'cairocontext'],
'CairoMatrix::transformDistance' => ['array', 'dx'=>'string', 'dy'=>'string'],
'CairoMatrix::transformPoint' => ['array', 'dx'=>'string', 'dy'=>'string'],
'CairoMatrix::translate' => ['', 'tx'=>'string', 'ty'=>'string', 'context'=>'cairocontext', 'x'=>'string', 'y'=>'string'],
'CairoPattern::__construct' => ['void'],
'CairoPattern::getMatrix' => ['', 'context'=>'cairocontext'],
'CairoPattern::getType' => ['int'],
'CairoPattern::setMatrix' => ['', 'matrix'=>'cairomatrix', 'context'=>'cairocontext'],
'CairoPattern::status' => ['int', 'context'=>'cairocontext'],
'CairoPdfSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoPdfSurface::setSize' => ['void', 'width'=>'string', 'height'=>'string'],
'CairoPsSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoPsSurface::dscBeginPageSetup' => ['void'],
'CairoPsSurface::dscBeginSetup' => ['void'],
'CairoPsSurface::dscComment' => ['void', 'comment'=>'string'],
'CairoPsSurface::getEps' => ['bool'],
'CairoPsSurface::getLevels' => ['array'],
'CairoPsSurface::levelToString' => ['string', 'level'=>'int'],
'CairoPsSurface::restrictToLevel' => ['void', 'level'=>'string'],
'CairoPsSurface::setEps' => ['void', 'level'=>'string'],
'CairoPsSurface::setSize' => ['void', 'width'=>'string', 'height'=>'string'],
'CairoRadialGradient::__construct' => ['void', 'x0'=>'float', 'y0'=>'float', 'r0'=>'float', 'x1'=>'float', 'y1'=>'float', 'r1'=>'float'],
'CairoRadialGradient::getCircles' => ['array'],
'CairoScaledFont::__construct' => ['void', 'font_face'=>'CairoFontFace', 'matrix'=>'CairoMatrix', 'ctm'=>'CairoMatrix', 'options'=>'CairoFontOptions'],
'CairoScaledFont::extents' => ['array'],
'CairoScaledFont::getCtm' => ['CairoMatrix'],
'CairoScaledFont::getFontFace' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getFontMatrix' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoScaledFont::getScaleMatrix' => ['void'],
'CairoScaledFont::getType' => ['int'],
'CairoScaledFont::glyphExtents' => ['array', 'glyphs'=>'string'],
'CairoScaledFont::status' => ['int', 'context'=>'cairocontext'],
'CairoScaledFont::textExtents' => ['array', 'text'=>'string', 'context'=>'cairocontext'],
'CairoSolidPattern::__construct' => ['void', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'alpha='=>'float'],
'CairoSolidPattern::getRgba' => ['array'],
'CairoSurface::__construct' => ['void'],
'CairoSurface::copyPage' => ['', 'context'=>'cairocontext'],
'CairoSurface::createSimilar' => ['void', 'other'=>'cairosurface', 'content'=>'int', 'width'=>'string', 'height'=>'string'],
'CairoSurface::finish' => ['void'],
'CairoSurface::flush' => ['void'],
'CairoSurface::getContent' => ['int'],
'CairoSurface::getDeviceOffset' => ['array'],
'CairoSurface::getFontOptions' => ['', 'context'=>'cairocontext'],
'CairoSurface::getType' => ['int'],
'CairoSurface::markDirty' => ['void'],
'CairoSurface::markDirtyRectangle' => ['void', 'x'=>'string', 'y'=>'string', 'width'=>'string', 'height'=>'string'],
'CairoSurface::setDeviceOffset' => ['void', 'x'=>'string', 'y'=>'string'],
'CairoSurface::setFallbackResolution' => ['void', 'x'=>'string', 'y'=>'string'],
'CairoSurface::showPage' => ['', 'context'=>'cairocontext'],
'CairoSurface::status' => ['int', 'context'=>'cairocontext'],
'CairoSurface::writeToPng' => ['void', 'file'=>'string'],
'CairoSurfacePattern::__construct' => ['void', 'surface'=>'CairoSurface'],
'CairoSurfacePattern::getExtend' => ['int'],
'CairoSurfacePattern::getFilter' => ['int'],
'CairoSurfacePattern::getSurface' => ['void'],
'CairoSurfacePattern::setExtend' => ['void', 'extend'=>'int'],
'CairoSurfacePattern::setFilter' => ['void', 'filter'=>'string'],
'CairoSvgSurface::__construct' => ['void', 'file'=>'string', 'width'=>'float', 'height'=>'float'],
'CairoSvgSurface::getVersions' => ['array'],
'CairoSvgSurface::restrictToVersion' => ['void', 'version'=>'string'],
'CairoSvgSurface::versionToString' => ['string', 'version'=>'int'],
'cal_days_in_month' => ['int', 'calendar'=>'int', 'month'=>'int', 'year'=>'int'],
'cal_from_jd' => ['false|array{date:string,month:int,day:int,year:int,dow:int,abbrevdayname:string,dayname:string,abbrevmonth:string,monthname:string}', 'jd'=>'int', 'calendar'=>'int'],
'cal_info' => ['array', 'calendar='=>'int'],
'cal_to_jd' => ['int', 'calendar'=>'int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'calcul_hmac' => ['string', 'clent'=>'string', 'siretcode'=>'string', 'price'=>'string', 'reference'=>'string', 'validity'=>'string', 'taxation'=>'string', 'devise'=>'string', 'language'=>'string'],
'calculhmac' => ['string', 'clent'=>'string', 'data'=>'string'],
'call_user_func' => ['mixed|false', 'function'=>'callable', '...parameters='=>'mixed'],
'call_user_func_array' => ['mixed|false', 'function'=>'callable', 'parameters'=>'array<int,mixed>'],
'call_user_method' => ['mixed', 'method_name'=>'string', 'obj'=>'object', 'parameter='=>'mixed', '...args='=>'mixed'],
'call_user_method_array' => ['mixed', 'method_name'=>'string', 'obj'=>'object', 'params'=>'array<int,mixed>'],
'CallbackFilterIterator::__construct' => ['void', 'iterator'=>'Iterator', 'func'=>'callable(mixed):bool|callable(mixed,mixed):bool|callable(mixed,mixed,mixed):bool'],
'CallbackFilterIterator::accept' => ['bool'],
'CallbackFilterIterator::current' => ['mixed'],
'CallbackFilterIterator::getInnerIterator' => ['Iterator'],
'CallbackFilterIterator::key' => ['mixed'],
'CallbackFilterIterator::next' => ['void'],
'CallbackFilterIterator::rewind' => ['void'],
'CallbackFilterIterator::valid' => ['bool'],
'ceil' => ['float|int', 'number'=>'float'],
'chdb::__construct' => ['void', 'pathname'=>'string'],
'chdb::get' => ['string', 'key'=>'string'],
'chdb_create' => ['bool', 'pathname'=>'string', 'data'=>'array'],
'chdir' => ['bool', 'directory'=>'string'],
'checkdate' => ['bool', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'checkdnsrr' => ['bool', 'host'=>'string', 'type='=>'string'],
'chgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'chmod' => ['bool', 'filename'=>'string', 'mode'=>'int'],
'chop' => ['string', 'str'=>'string', 'character_mask='=>'string'],
'chown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'chr' => ['string', 'ascii'=>'int'],
'chroot' => ['bool', 'directory'=>'string'],
'chunk_split' => ['string', 'str'=>'string', 'chunklen='=>'int', 'ending='=>'string'],
'class_alias' => ['bool', 'user_class_name'=>'string', 'alias_name'=>'string', 'autoload='=>'bool'],
'class_exists' => ['bool', 'classname'=>'string', 'autoload='=>'bool'],
'class_implements' => ['array<string,string>|false', 'what'=>'object|string', 'autoload='=>'bool'],
'class_parents' => ['array<string, class-string>|false', 'instance'=>'object|string', 'autoload='=>'bool'],
'class_uses' => ['array<string,string>|false', 'what'=>'object|string', 'autoload='=>'bool'],
'classkit_import' => ['array', 'filename'=>'string'],
'classkit_method_add' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int'],
'classkit_method_copy' => ['bool', 'dclass'=>'string', 'dmethod'=>'string', 'sclass'=>'string', 'smethod='=>'string'],
'classkit_method_redefine' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int'],
'classkit_method_remove' => ['bool', 'classname'=>'string', 'methodname'=>'string'],
'classkit_method_rename' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'newname'=>'string'],
'classObj::__construct' => ['void', 'layer'=>'layerObj', 'class'=>'classObj'],
'classObj::addLabel' => ['int', 'label'=>'labelObj'],
'classObj::convertToString' => ['string'],
'classObj::createLegendIcon' => ['imageObj', 'width'=>'int', 'height'=>'int'],
'classObj::deletestyle' => ['int', 'index'=>'int'],
'classObj::drawLegendIcon' => ['int', 'width'=>'int', 'height'=>'int', 'im'=>'imageObj', 'dstX'=>'int', 'dstY'=>'int'],
'classObj::free' => ['void'],
'classObj::getExpressionString' => ['string'],
'classObj::getLabel' => ['labelObj', 'index'=>'int'],
'classObj::getMetaData' => ['int', 'name'=>'string'],
'classObj::getStyle' => ['styleObj', 'index'=>'int'],
'classObj::getTextString' => ['string'],
'classObj::movestyledown' => ['int', 'index'=>'int'],
'classObj::movestyleup' => ['int', 'index'=>'int'],
'classObj::ms_newClassObj' => ['classObj', 'layer'=>'layerObj', 'class'=>'classObj'],
'classObj::removeLabel' => ['labelObj', 'index'=>'int'],
'classObj::removeMetaData' => ['int', 'name'=>'string'],
'classObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'classObj::setExpression' => ['int', 'expression'=>'string'],
'classObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'classObj::settext' => ['int', 'text'=>'string'],
'classObj::updateFromString' => ['int', 'snippet'=>'string'],
'clearstatcache' => ['void', 'clear_realpath_cache='=>'bool', 'filename='=>'string'],
'cli_get_process_title' => ['string'],
'cli_set_process_title' => ['bool', 'arg'=>'string'],
'ClosedGeneratorException::__clone' => ['void'],
'ClosedGeneratorException::__toString' => ['string'],
'ClosedGeneratorException::getCode' => ['int'],
'ClosedGeneratorException::getFile' => ['string'],
'ClosedGeneratorException::getLine' => ['int'],
'ClosedGeneratorException::getMessage' => ['string'],
'ClosedGeneratorException::getPrevious' => ['Throwable|ClosedGeneratorException|null'],
'ClosedGeneratorException::getTrace' => ['array'],
'ClosedGeneratorException::getTraceAsString' => ['string'],
'closedir' => ['void', 'dir_handle='=>'resource'],
'closelog' => ['bool'],
'Closure::__construct' => ['void'],
'Closure::__invoke' => ['', '...args='=>''],
'Closure::bind' => ['Closure|false', 'old'=>'Closure', 'to'=>'?object', 'scope='=>'object|string'],
'Closure::bindTo' => ['Closure|false', 'new'=>'?object', 'newscope='=>'object|string'],
'Closure::call' => ['', 'to'=>'object', '...parameters='=>''],
'Closure::fromCallable' => ['Closure', 'callable'=>'callable'],
'clusterObj::convertToString' => ['string'],
'clusterObj::getFilterString' => ['string'],
'clusterObj::getGroupString' => ['string'],
'clusterObj::setFilter' => ['int', 'expression'=>'string'],
'clusterObj::setGroup' => ['int', 'expression'=>'string'],
'Collator::__construct' => ['void', 'locale'=>'string'],
'Collator::asort' => ['bool', '&rw_arr'=>'array', 'sort_flag='=>'int'],
'Collator::compare' => ['int|false', 'str1'=>'string', 'str2'=>'string'],
'Collator::create' => ['?Collator', 'locale'=>'string'],
'Collator::getAttribute' => ['int|false', 'attr'=>'int'],
'Collator::getErrorCode' => ['int'],
'Collator::getErrorMessage' => ['string'],
'Collator::getLocale' => ['string', 'type'=>'int'],
'Collator::getSortKey' => ['string|false', 'str'=>'string'],
'Collator::getStrength' => ['int|false'],
'Collator::setAttribute' => ['bool', 'attr'=>'int', 'val'=>'int'],
'Collator::setStrength' => ['bool', 'strength'=>'int'],
'Collator::sort' => ['bool', '&rw_arr'=>'array', 'sort_flags='=>'int'],
'Collator::sortWithSortKeys' => ['bool', '&rw_arr'=>'array'],
'collator_asort' => ['bool', 'coll'=>'collator', '&rw_arr'=>'array', 'sort_flag='=>'int'],
'collator_compare' => ['int', 'coll'=>'collator', 'str1'=>'string', 'str2'=>'string'],
'collator_create' => ['Collator', 'locale'=>'string'],
'collator_get_attribute' => ['int|false', 'coll'=>'collator', 'attr'=>'int'],
'collator_get_error_code' => ['int', 'coll'=>'collator'],
'collator_get_error_message' => ['string', 'coll'=>'collator'],
'collator_get_locale' => ['string', 'coll'=>'collator', 'type'=>'int'],
'collator_get_sort_key' => ['string', 'coll'=>'collator', 'str'=>'string'],
'collator_get_strength' => ['int|false', 'coll'=>'collator'],
'collator_set_attribute' => ['bool', 'coll'=>'collator', 'attr'=>'int', 'val'=>'int'],
'collator_set_strength' => ['bool', 'coll'=>'collator', 'strength'=>'int'],
'collator_sort' => ['bool', 'coll'=>'collator', '&rw_arr'=>'array', 'sort_flag='=>'int'],
'collator_sort_with_sort_keys' => ['bool', 'coll'=>'collator', '&rw_arr'=>'array'],
'Collectable::isGarbage' => ['bool'],
'Collectable::setGarbage' => ['void'],
'colorObj::setHex' => ['int', 'hex'=>'string'],
'colorObj::toHex' => ['string'],
'COM::__call' => ['', 'name'=>'', 'args'=>''],
'COM::__construct' => ['void', 'module_name'=>'string', 'server_name='=>'mixed', 'codepage='=>'int', 'typelib='=>'string'],
'COM::__get' => ['', 'name'=>''],
'COM::__set' => ['void', 'name'=>'', 'value'=>''],
'com_addref' => [''],
'com_create_guid' => ['string'],
'com_event_sink' => ['bool', 'comobject'=>'VARIANT', 'sinkobject'=>'object', 'sinkinterface='=>'mixed'],
'com_get_active_object' => ['VARIANT', 'progid'=>'string', 'code_page='=>'int'],
'com_isenum' => ['bool', 'com_module'=>'variant'],
'com_load_typelib' => ['bool', 'typelib_name'=>'string', 'case_insensitive='=>'int'],
'com_message_pump' => ['bool', 'timeoutms='=>'int'],
'com_print_typeinfo' => ['bool', 'comobject_or_typelib'=>'object', 'dispinterface='=>'string', 'wantsink='=>'bool'],
'commonmark\cql::__invoke' => ['', 'root'=>'CommonMark\Node', 'handler'=>'callable'],
'commonmark\interfaces\ivisitable::accept' => ['void', 'visitor'=>'CommonMark\Interfaces\IVisitor'],
'commonmark\interfaces\ivisitor::enter' => ['?int|IVisitable', 'visitable'=>'IVisitable'],
'commonmark\interfaces\ivisitor::leave' => ['?int|IVisitable', 'visitable'=>'IVisitable'],
'commonmark\node::accept' => ['void', 'visitor'=>'CommonMark\Interfaces\IVisitor'],
'commonmark\node::appendChild' => ['CommonMark\Node', 'child'=>'CommonMark\Node'],
'commonmark\node::insertAfter' => ['CommonMark\Node', 'sibling'=>'CommonMark\Node'],
'commonmark\node::insertBefore' => ['CommonMark\Node', 'sibling'=>'CommonMark\Node'],
'commonmark\node::prependChild' => ['CommonMark\Node', 'child'=>'CommonMark\Node'],
'commonmark\node::replace' => ['CommonMark\Node', 'target'=>'CommonMark\Node'],
'commonmark\node::unlink' => ['void'],
'commonmark\parse' => ['CommonMark\Node', 'content'=>'string', 'options='=>'int'],
'commonmark\parser::finish' => ['CommonMark\Node'],
'commonmark\parser::parse' => ['void', 'buffer'=>'string'],
'commonmark\render' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\html' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int'],
'commonmark\render\latex' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\man' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int', 'width='=>'int'],
'commonmark\render\xml' => ['string', 'node'=>'CommonMark\Node', 'options='=>'int'],
'compact' => ['array', 'var_name'=>'string|array', '...var_names='=>'string|array'],
'COMPersistHelper::__construct' => ['void', 'com_object'=>'object'],
'COMPersistHelper::GetCurFile' => ['string'],
'COMPersistHelper::GetMaxStreamSize' => ['int'],
'COMPersistHelper::InitNew' => ['int'],
'COMPersistHelper::LoadFromFile' => ['bool', 'filename'=>'string', 'flags'=>'int'],
'COMPersistHelper::LoadFromStream' => ['', 'stream'=>''],
'COMPersistHelper::SaveToFile' => ['bool', 'filename'=>'string', 'remember'=>'bool'],
'COMPersistHelper::SaveToStream' => ['int', 'stream'=>''],
'componere\abstract\definition::addInterface' => ['Componere\Abstract\Definition', 'interface'=>'string'],
'componere\abstract\definition::addMethod' => ['Componere\Abstract\Definition', 'name'=>'string', 'method'=>'Componere\Method'],
'componere\abstract\definition::addTrait' => ['Componere\Abstract\Definition', 'trait'=>'string'],
'componere\abstract\definition::getReflector' => ['ReflectionClass'],
'componere\cast' => ['object', 'arg1'=>'string', 'object'=>'object'],
'componere\cast_by_ref' => ['object', 'arg1'=>'string', 'object'=>'object'],
'componere\definition::addConstant' => ['Componere\Definition', 'name'=>'string', 'value'=>'Componere\Value'],
'componere\definition::addProperty' => ['Componere\Definition', 'name'=>'string', 'value'=>'Componere\Value'],
'componere\definition::getClosure' => ['Closure', 'name'=>'string'],
'componere\definition::getClosures' => ['Closure[]'],
'componere\definition::isRegistered' => ['bool'],
'componere\definition::register' => ['void'],
'componere\method::getReflector' => ['ReflectionMethod'],
'componere\method::setPrivate' => ['Method'],
'componere\method::setProtected' => ['Method'],
'componere\method::setStatic' => ['Method'],
'componere\patch::apply' => ['void'],
'componere\patch::derive' => ['Componere\Patch', 'instance'=>'object'],
'componere\patch::getClosure' => ['Closure', 'name'=>'string'],
'componere\patch::getClosures' => ['Closure[]'],
'componere\patch::isApplied' => ['bool'],
'componere\patch::revert' => ['void'],
'componere\value::hasDefault' => ['bool'],
'componere\value::isPrivate' => ['bool'],
'componere\value::isProtected' => ['bool'],
'componere\value::isStatic' => ['bool'],
'componere\value::setPrivate' => ['Value'],
'componere\value::setProtected' => ['Value'],
'componere\value::setStatic' => ['Value'],
'Cond::broadcast' => ['bool', 'condition'=>'long'],
'Cond::create' => ['long'],
'Cond::destroy' => ['bool', 'condition'=>'long'],
'Cond::signal' => ['bool', 'condition'=>'long'],
'Cond::wait' => ['bool', 'condition'=>'long', 'mutex'=>'long', 'timeout='=>'long'],
'confirm_pdo_ibm_compiled' => [''],
'connection_aborted' => ['int'],
'connection_status' => ['int'],
'connection_timeout' => ['int'],
'constant' => ['mixed', 'const_name'=>'string'],
'convert_cyr_string' => ['string', 'str'=>'string', 'from'=>'string', 'to'=>'string'],
'convert_uudecode' => ['string', 'data'=>'string'],
'convert_uuencode' => ['string', 'data'=>'string'],
'copy' => ['bool', 'source_file'=>'string', 'destination_file'=>'string', 'context='=>'resource'],
'cos' => ['float', 'number'=>'float'],
'cosh' => ['float', 'number'=>'float'],
'Couchbase\AnalyticsQuery::__construct' => ['void'],
'Couchbase\AnalyticsQuery::fromString' => ['Couchbase\AnalyticsQuery', 'statement'=>'string'],
'Couchbase\basicDecoderV1' => ['mixed', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int', 'options'=>'array'],
'Couchbase\basicEncoderV1' => ['array', 'value'=>'mixed', 'options'=>'array'],
'Couchbase\BooleanFieldSearchQuery::__construct' => ['void'],
'Couchbase\BooleanFieldSearchQuery::boost' => ['Couchbase\BooleanFieldSearchQuery', 'boost'=>'float'],
'Couchbase\BooleanFieldSearchQuery::field' => ['Couchbase\BooleanFieldSearchQuery', 'field'=>'string'],
'Couchbase\BooleanFieldSearchQuery::jsonSerialize' => ['array'],
'Couchbase\BooleanSearchQuery::__construct' => ['void'],
'Couchbase\BooleanSearchQuery::boost' => ['Couchbase\BooleanSearchQuery', 'boost'=>'float'],
'Couchbase\BooleanSearchQuery::jsonSerialize' => ['array'],
'Couchbase\BooleanSearchQuery::must' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\BooleanSearchQuery::mustNot' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\BooleanSearchQuery::should' => ['Couchbase\BooleanSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\Bucket::__construct' => ['void'],
'Couchbase\Bucket::__get' => ['int', 'name'=>'string'],
'Couchbase\Bucket::__set' => ['int', 'name'=>'string', 'value'=>'int'],
'Couchbase\Bucket::append' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::counter' => ['Couchbase\Document|array', 'ids'=>'array|string', 'delta='=>'int', 'options='=>'array'],
'Couchbase\Bucket::decryptFields' => ['array', 'document'=>'array', 'fieldOptions'=>'', 'prefix='=>'string'],
'Couchbase\Bucket::diag' => ['array', 'reportId='=>'string'],
'Couchbase\Bucket::encryptFields' => ['array', 'document'=>'array', 'fieldOptions'=>'', 'prefix='=>'string'],
'Couchbase\Bucket::get' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::getAndLock' => ['Couchbase\Document|array', 'ids'=>'array|string', 'lockTime'=>'int', 'options='=>'array'],
'Couchbase\Bucket::getAndTouch' => ['Couchbase\Document|array', 'ids'=>'array|string', 'expiry'=>'int', 'options='=>'array'],
'Couchbase\Bucket::getFromReplica' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::getName' => ['string'],
'Couchbase\Bucket::insert' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::listExists' => ['bool', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listGet' => ['mixed', 'id'=>'string', 'index'=>'int'],
'Couchbase\Bucket::listPush' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listRemove' => ['', 'id'=>'string', 'index'=>'int'],
'Couchbase\Bucket::listSet' => ['', 'id'=>'string', 'index'=>'int', 'value'=>'mixed'],
'Couchbase\Bucket::listShift' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::listSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::lookupIn' => ['Couchbase\LookupInBuilder', 'id'=>'string'],
'Couchbase\Bucket::manager' => ['Couchbase\BucketManager'],
'Couchbase\Bucket::mapAdd' => ['', 'id'=>'string', 'key'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::mapGet' => ['mixed', 'id'=>'string', 'key'=>'string'],
'Couchbase\Bucket::mapRemove' => ['', 'id'=>'string', 'key'=>'string'],
'Couchbase\Bucket::mapSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::mutateIn' => ['Couchbase\MutateInBuilder', 'id'=>'string', 'cas'=>'string'],
'Couchbase\Bucket::ping' => ['array', 'services='=>'int', 'reportId='=>'string'],
'Couchbase\Bucket::prepend' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::query' => ['object', 'query'=>'Couchbase\AnalyticsQuery|Couchbase\N1qlQuery|Couchbase\SearchQuery|Couchbase\SpatialViewQuery|Couchbase\ViewQuery', 'jsonAsArray='=>'bool'],
'Couchbase\Bucket::queueAdd' => ['', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::queueExists' => ['bool', 'id'=>'string', 'value'=>'mixed'],
'Couchbase\Bucket::queueRemove' => ['mixed', 'id'=>'string'],
'Couchbase\Bucket::queueSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::remove' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::replace' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\Bucket::retrieveIn' => ['Couchbase\DocumentFragment', 'id'=>'string', '...paths='=>'array<int,string>'],
'Couchbase\Bucket::setAdd' => ['', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setExists' => ['bool', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setRemove' => ['', 'id'=>'string', 'value'=>'bool|float|int|string'],
'Couchbase\Bucket::setSize' => ['int', 'id'=>'string'],
'Couchbase\Bucket::setTranscoder' => ['', 'encoder'=>'callable', 'decoder'=>'callable'],
'Couchbase\Bucket::touch' => ['Couchbase\Document|array', 'ids'=>'array|string', 'expiry'=>'int', 'options='=>'array'],
'Couchbase\Bucket::unlock' => ['Couchbase\Document|array', 'ids'=>'array|string', 'options='=>'array'],
'Couchbase\Bucket::upsert' => ['Couchbase\Document|array', 'ids'=>'array|string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\BucketManager::__construct' => ['void'],
'Couchbase\BucketManager::createN1qlIndex' => ['', 'name'=>'string', 'fields'=>'array', 'whereClause='=>'string', 'ignoreIfExist='=>'bool', 'defer='=>'bool'],
'Couchbase\BucketManager::createN1qlPrimaryIndex' => ['', 'customName='=>'string', 'ignoreIfExist='=>'bool', 'defer='=>'bool'],
'Couchbase\BucketManager::dropN1qlIndex' => ['', 'name'=>'string', 'ignoreIfNotExist='=>'bool'],
'Couchbase\BucketManager::dropN1qlPrimaryIndex' => ['', 'customName='=>'string', 'ignoreIfNotExist='=>'bool'],
'Couchbase\BucketManager::flush' => [''],
'Couchbase\BucketManager::getDesignDocument' => ['array', 'name'=>'string'],
'Couchbase\BucketManager::info' => ['array'],
'Couchbase\BucketManager::insertDesignDocument' => ['', 'name'=>'string', 'document'=>'array'],
'Couchbase\BucketManager::listDesignDocuments' => ['array'],
'Couchbase\BucketManager::listN1qlIndexes' => ['array'],
'Couchbase\BucketManager::removeDesignDocument' => ['', 'name'=>'string'],
'Couchbase\BucketManager::upsertDesignDocument' => ['', 'name'=>'string', 'document'=>'array'],
'Couchbase\ClassicAuthenticator::bucket' => ['', 'name'=>'string', 'password'=>'string'],
'Couchbase\ClassicAuthenticator::cluster' => ['', 'username'=>'string', 'password'=>'string'],
'Couchbase\Cluster::__construct' => ['void', 'connstr'=>'string'],
'Couchbase\Cluster::authenticate' => ['null', 'authenticator'=>'Couchbase\Authenticator'],
'Couchbase\Cluster::authenticateAs' => ['null', 'username'=>'string', 'password'=>'string'],
'Couchbase\Cluster::manager' => ['Couchbase\ClusterManager', 'username='=>'string', 'password='=>'string'],
'Couchbase\Cluster::openBucket' => ['Couchbase\Bucket', 'name='=>'string', 'password='=>'string'],
'Couchbase\ClusterManager::__construct' => ['void'],
'Couchbase\ClusterManager::createBucket' => ['', 'name'=>'string', 'options='=>'array'],
'Couchbase\ClusterManager::getUser' => ['array', 'username'=>'string', 'domain='=>'int'],
'Couchbase\ClusterManager::info' => ['array'],
'Couchbase\ClusterManager::listBuckets' => ['array'],
'Couchbase\ClusterManager::listUsers' => ['array', 'domain='=>'int'],
'Couchbase\ClusterManager::removeBucket' => ['', 'name'=>'string'],
'Couchbase\ClusterManager::removeUser' => ['', 'name'=>'string', 'domain='=>'int'],
'Couchbase\ClusterManager::upsertUser' => ['', 'name'=>'string', 'settings'=>'Couchbase\UserSettings', 'domain='=>'int'],
'Couchbase\ConjunctionSearchQuery::__construct' => ['void'],
'Couchbase\ConjunctionSearchQuery::boost' => ['Couchbase\ConjunctionSearchQuery', 'boost'=>'float'],
'Couchbase\ConjunctionSearchQuery::every' => ['Couchbase\ConjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\ConjunctionSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchFacet::__construct' => ['void'],
'Couchbase\DateRangeSearchFacet::addRange' => ['Couchbase\DateRangeSearchFacet', 'name'=>'string', 'start'=>'int|string', 'end'=>'int|string'],
'Couchbase\DateRangeSearchFacet::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchQuery::__construct' => ['void'],
'Couchbase\DateRangeSearchQuery::boost' => ['Couchbase\DateRangeSearchQuery', 'boost'=>'float'],
'Couchbase\DateRangeSearchQuery::dateTimeParser' => ['Couchbase\DateRangeSearchQuery', 'dateTimeParser'=>'string'],
'Couchbase\DateRangeSearchQuery::end' => ['Couchbase\DateRangeSearchQuery', 'end'=>'int|string', 'inclusive='=>'bool'],
'Couchbase\DateRangeSearchQuery::field' => ['Couchbase\DateRangeSearchQuery', 'field'=>'string'],
'Couchbase\DateRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DateRangeSearchQuery::start' => ['Couchbase\DateRangeSearchQuery', 'start'=>'int|string', 'inclusive='=>'bool'],
'Couchbase\defaultDecoder' => ['mixed', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int'],
'Couchbase\defaultEncoder' => ['array', 'value'=>'mixed'],
'Couchbase\DisjunctionSearchQuery::__construct' => ['void'],
'Couchbase\DisjunctionSearchQuery::boost' => ['Couchbase\DisjunctionSearchQuery', 'boost'=>'float'],
'Couchbase\DisjunctionSearchQuery::either' => ['Couchbase\DisjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\DisjunctionSearchQuery::jsonSerialize' => ['array'],
'Couchbase\DisjunctionSearchQuery::min' => ['Couchbase\DisjunctionSearchQuery', 'min'=>'int'],
'Couchbase\DocIdSearchQuery::__construct' => ['void'],
'Couchbase\DocIdSearchQuery::boost' => ['Couchbase\DocIdSearchQuery', 'boost'=>'float'],
'Couchbase\DocIdSearchQuery::docIds' => ['Couchbase\DocIdSearchQuery', '...documentIds='=>'array<int,string>'],
'Couchbase\DocIdSearchQuery::field' => ['Couchbase\DocIdSearchQuery', 'field'=>'string'],
'Couchbase\DocIdSearchQuery::jsonSerialize' => ['array'],
'Couchbase\fastlzCompress' => ['string', 'data'=>'string'],
'Couchbase\fastlzDecompress' => ['string', 'data'=>'string'],
'Couchbase\GeoBoundingBoxSearchQuery::__construct' => ['void'],
'Couchbase\GeoBoundingBoxSearchQuery::boost' => ['Couchbase\GeoBoundingBoxSearchQuery', 'boost'=>'float'],
'Couchbase\GeoBoundingBoxSearchQuery::field' => ['Couchbase\GeoBoundingBoxSearchQuery', 'field'=>'string'],
'Couchbase\GeoBoundingBoxSearchQuery::jsonSerialize' => ['array'],
'Couchbase\GeoDistanceSearchQuery::__construct' => ['void'],
'Couchbase\GeoDistanceSearchQuery::boost' => ['Couchbase\GeoDistanceSearchQuery', 'boost'=>'float'],
'Couchbase\GeoDistanceSearchQuery::field' => ['Couchbase\GeoDistanceSearchQuery', 'field'=>'string'],
'Couchbase\GeoDistanceSearchQuery::jsonSerialize' => ['array'],
'Couchbase\LookupInBuilder::__construct' => ['void'],
'Couchbase\LookupInBuilder::execute' => ['Couchbase\DocumentFragment'],
'Couchbase\LookupInBuilder::exists' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\LookupInBuilder::get' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\LookupInBuilder::getCount' => ['Couchbase\LookupInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\MatchAllSearchQuery::__construct' => ['void'],
'Couchbase\MatchAllSearchQuery::boost' => ['Couchbase\MatchAllSearchQuery', 'boost'=>'float'],
'Couchbase\MatchAllSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchNoneSearchQuery::__construct' => ['void'],
'Couchbase\MatchNoneSearchQuery::boost' => ['Couchbase\MatchNoneSearchQuery', 'boost'=>'float'],
'Couchbase\MatchNoneSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchPhraseSearchQuery::__construct' => ['void'],
'Couchbase\MatchPhraseSearchQuery::analyzer' => ['Couchbase\MatchPhraseSearchQuery', 'analyzer'=>'string'],
'Couchbase\MatchPhraseSearchQuery::boost' => ['Couchbase\MatchPhraseSearchQuery', 'boost'=>'float'],
'Couchbase\MatchPhraseSearchQuery::field' => ['Couchbase\MatchPhraseSearchQuery', 'field'=>'string'],
'Couchbase\MatchPhraseSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchSearchQuery::__construct' => ['void'],
'Couchbase\MatchSearchQuery::analyzer' => ['Couchbase\MatchSearchQuery', 'analyzer'=>'string'],
'Couchbase\MatchSearchQuery::boost' => ['Couchbase\MatchSearchQuery', 'boost'=>'float'],
'Couchbase\MatchSearchQuery::field' => ['Couchbase\MatchSearchQuery', 'field'=>'string'],
'Couchbase\MatchSearchQuery::fuzziness' => ['Couchbase\MatchSearchQuery', 'fuzziness'=>'int'],
'Couchbase\MatchSearchQuery::jsonSerialize' => ['array'],
'Couchbase\MatchSearchQuery::prefixLength' => ['Couchbase\MatchSearchQuery', 'prefixLength'=>'int'],
'Couchbase\MutateInBuilder::__construct' => ['void'],
'Couchbase\MutateInBuilder::arrayAddUnique' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayAppend' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayAppendAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayInsert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\MutateInBuilder::arrayInsertAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array'],
'Couchbase\MutateInBuilder::arrayPrepend' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::arrayPrependAll' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'values'=>'array', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::counter' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'delta'=>'int', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::execute' => ['Couchbase\DocumentFragment'],
'Couchbase\MutateInBuilder::insert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::modeDocument' => ['', 'mode'=>'int'],
'Couchbase\MutateInBuilder::remove' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'options='=>'array'],
'Couchbase\MutateInBuilder::replace' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array'],
'Couchbase\MutateInBuilder::upsert' => ['Couchbase\MutateInBuilder', 'path'=>'string', 'value'=>'mixed', 'options='=>'array|bool'],
'Couchbase\MutateInBuilder::withExpiry' => ['Couchbase\MutateInBuilder', 'expiry'=>'Couchbase\expiry'],
'Couchbase\MutationState::__construct' => ['void'],
'Couchbase\MutationState::add' => ['', 'source'=>'Couchbase\Document|Couchbase\DocumentFragment|array'],
'Couchbase\MutationState::from' => ['Couchbase\MutationState', 'source'=>'Couchbase\Document|Couchbase\DocumentFragment|array'],
'Couchbase\MutationToken::__construct' => ['void'],
'Couchbase\MutationToken::bucketName' => ['string'],
'Couchbase\MutationToken::from' => ['', 'bucketName'=>'string', 'vbucketId'=>'int', 'vbucketUuid'=>'string', 'sequenceNumber'=>'string'],
'Couchbase\MutationToken::sequenceNumber' => ['string'],
'Couchbase\MutationToken::vbucketId' => ['int'],
'Couchbase\MutationToken::vbucketUuid' => ['string'],
'Couchbase\N1qlIndex::__construct' => ['void'],
'Couchbase\N1qlQuery::__construct' => ['void'],
'Couchbase\N1qlQuery::adhoc' => ['Couchbase\N1qlQuery', 'adhoc'=>'bool'],
'Couchbase\N1qlQuery::consistency' => ['Couchbase\N1qlQuery', 'consistency'=>'int'],
'Couchbase\N1qlQuery::consistentWith' => ['Couchbase\N1qlQuery', 'state'=>'Couchbase\MutationState'],
'Couchbase\N1qlQuery::crossBucket' => ['Couchbase\N1qlQuery', 'crossBucket'=>'bool'],
'Couchbase\N1qlQuery::fromString' => ['Couchbase\N1qlQuery', 'statement'=>'string'],
'Couchbase\N1qlQuery::maxParallelism' => ['Couchbase\N1qlQuery', 'maxParallelism'=>'int'],
'Couchbase\N1qlQuery::namedParams' => ['Couchbase\N1qlQuery', 'params'=>'array'],
'Couchbase\N1qlQuery::pipelineBatch' => ['Couchbase\N1qlQuery', 'pipelineBatch'=>'int'],
'Couchbase\N1qlQuery::pipelineCap' => ['Couchbase\N1qlQuery', 'pipelineCap'=>'int'],
'Couchbase\N1qlQuery::positionalParams' => ['Couchbase\N1qlQuery', 'params'=>'array'],
'Couchbase\N1qlQuery::profile' => ['', 'profileType'=>'string'],
'Couchbase\N1qlQuery::readonly' => ['Couchbase\N1qlQuery', 'readonly'=>'bool'],
'Couchbase\N1qlQuery::scanCap' => ['Couchbase\N1qlQuery', 'scanCap'=>'int'],
'Couchbase\NumericRangeSearchFacet::__construct' => ['void'],
'Couchbase\NumericRangeSearchFacet::addRange' => ['Couchbase\NumericRangeSearchFacet', 'name'=>'string', 'min'=>'float', 'max'=>'float'],
'Couchbase\NumericRangeSearchFacet::jsonSerialize' => ['array'],
'Couchbase\NumericRangeSearchQuery::__construct' => ['void'],
'Couchbase\NumericRangeSearchQuery::boost' => ['Couchbase\NumericRangeSearchQuery', 'boost'=>'float'],
'Couchbase\NumericRangeSearchQuery::field' => ['Couchbase\NumericRangeSearchQuery', 'field'=>'string'],
'Couchbase\NumericRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\NumericRangeSearchQuery::max' => ['Couchbase\NumericRangeSearchQuery', 'max'=>'float', 'inclusive='=>'bool'],
'Couchbase\NumericRangeSearchQuery::min' => ['Couchbase\NumericRangeSearchQuery', 'min'=>'float', 'inclusive='=>'bool'],
'Couchbase\passthruDecoder' => ['string', 'bytes'=>'string', 'flags'=>'int', 'datatype'=>'int'],
'Couchbase\passthruEncoder' => ['array', 'value'=>'string'],
'Couchbase\PasswordAuthenticator::password' => ['Couchbase\PasswordAuthenticator', 'password'=>'string'],
'Couchbase\PasswordAuthenticator::username' => ['Couchbase\PasswordAuthenticator', 'username'=>'string'],
'Couchbase\PhraseSearchQuery::__construct' => ['void'],
'Couchbase\PhraseSearchQuery::boost' => ['Couchbase\PhraseSearchQuery', 'boost'=>'float'],
'Couchbase\PhraseSearchQuery::field' => ['Couchbase\PhraseSearchQuery', 'field'=>'string'],
'Couchbase\PhraseSearchQuery::jsonSerialize' => ['array'],
'Couchbase\PrefixSearchQuery::__construct' => ['void'],
'Couchbase\PrefixSearchQuery::boost' => ['Couchbase\PrefixSearchQuery', 'boost'=>'float'],
'Couchbase\PrefixSearchQuery::field' => ['Couchbase\PrefixSearchQuery', 'field'=>'string'],
'Couchbase\PrefixSearchQuery::jsonSerialize' => ['array'],
'Couchbase\QueryStringSearchQuery::__construct' => ['void'],
'Couchbase\QueryStringSearchQuery::boost' => ['Couchbase\QueryStringSearchQuery', 'boost'=>'float'],
'Couchbase\QueryStringSearchQuery::jsonSerialize' => ['array'],
'Couchbase\RegexpSearchQuery::__construct' => ['void'],
'Couchbase\RegexpSearchQuery::boost' => ['Couchbase\RegexpSearchQuery', 'boost'=>'float'],
'Couchbase\RegexpSearchQuery::field' => ['Couchbase\RegexpSearchQuery', 'field'=>'string'],
'Couchbase\RegexpSearchQuery::jsonSerialize' => ['array'],
'Couchbase\SearchQuery::__construct' => ['void', 'indexName'=>'string', 'queryPart'=>'Couchbase\SearchQueryPart'],
'Couchbase\SearchQuery::addFacet' => ['Couchbase\SearchQuery', 'name'=>'string', 'facet'=>'Couchbase\SearchFacet'],
'Couchbase\SearchQuery::boolean' => ['Couchbase\BooleanSearchQuery'],
'Couchbase\SearchQuery::booleanField' => ['Couchbase\BooleanFieldSearchQuery', 'value'=>'bool'],
'Couchbase\SearchQuery::conjuncts' => ['Couchbase\ConjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\SearchQuery::consistentWith' => ['Couchbase\SearchQuery', 'state'=>'Couchbase\MutationState'],
'Couchbase\SearchQuery::dateRange' => ['Couchbase\DateRangeSearchQuery'],
'Couchbase\SearchQuery::dateRangeFacet' => ['Couchbase\DateRangeSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::disjuncts' => ['Couchbase\DisjunctionSearchQuery', '...queries='=>'array<int,Couchbase\SearchQueryPart>'],
'Couchbase\SearchQuery::docId' => ['Couchbase\DocIdSearchQuery', '...documentIds='=>'array<int,string>'],
'Couchbase\SearchQuery::explain' => ['Couchbase\SearchQuery', 'explain'=>'bool'],
'Couchbase\SearchQuery::fields' => ['Couchbase\SearchQuery', '...fields='=>'array<int,string>'],
'Couchbase\SearchQuery::geoBoundingBox' => ['Couchbase\GeoBoundingBoxSearchQuery', 'topLeftLongitude'=>'float', 'topLeftLatitude'=>'float', 'bottomRightLongitude'=>'float', 'bottomRightLatitude'=>'float'],
'Couchbase\SearchQuery::geoDistance' => ['Couchbase\GeoDistanceSearchQuery', 'longitude'=>'float', 'latitude'=>'float', 'distance'=>'string'],
'Couchbase\SearchQuery::highlight' => ['Couchbase\SearchQuery', 'style'=>'string', '...fields='=>'array<int,string>'],
'Couchbase\SearchQuery::jsonSerialize' => ['array'],
'Couchbase\SearchQuery::limit' => ['Couchbase\SearchQuery', 'limit'=>'int'],
'Couchbase\SearchQuery::match' => ['Couchbase\MatchSearchQuery', 'match'=>'string'],
'Couchbase\SearchQuery::matchAll' => ['Couchbase\MatchAllSearchQuery'],
'Couchbase\SearchQuery::matchNone' => ['Couchbase\MatchNoneSearchQuery'],
'Couchbase\SearchQuery::matchPhrase' => ['Couchbase\MatchPhraseSearchQuery', '...terms='=>'array<int,string>'],
'Couchbase\SearchQuery::numericRange' => ['Couchbase\NumericRangeSearchQuery'],
'Couchbase\SearchQuery::numericRangeFacet' => ['Couchbase\NumericRangeSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::prefix' => ['Couchbase\PrefixSearchQuery', 'prefix'=>'string'],
'Couchbase\SearchQuery::queryString' => ['Couchbase\QueryStringSearchQuery', 'queryString'=>'string'],
'Couchbase\SearchQuery::regexp' => ['Couchbase\RegexpSearchQuery', 'regexp'=>'string'],
'Couchbase\SearchQuery::serverSideTimeout' => ['Couchbase\SearchQuery', 'serverSideTimeout'=>'int'],
'Couchbase\SearchQuery::skip' => ['Couchbase\SearchQuery', 'skip'=>'int'],
'Couchbase\SearchQuery::sort' => ['Couchbase\SearchQuery', '...sort='=>'array<int,Couchbase\sort>'],
'Couchbase\SearchQuery::term' => ['Couchbase\TermSearchQuery', 'term'=>'string'],
'Couchbase\SearchQuery::termFacet' => ['Couchbase\TermSearchFacet', 'field'=>'string', 'limit'=>'int'],
'Couchbase\SearchQuery::termRange' => ['Couchbase\TermRangeSearchQuery'],
'Couchbase\SearchQuery::wildcard' => ['Couchbase\WildcardSearchQuery', 'wildcard'=>'string'],
'Couchbase\SearchSort::__construct' => ['void'],
'Couchbase\SearchSort::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSort::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSort::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSort::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortField::__construct' => ['void'],
'Couchbase\SearchSortField::descending' => ['Couchbase\SearchSortField', 'descending'=>'bool'],
'Couchbase\SearchSortField::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortField::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortField::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortField::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortField::missing' => ['', 'missing'=>'string'],
'Couchbase\SearchSortField::mode' => ['', 'mode'=>'string'],
'Couchbase\SearchSortField::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortField::type' => ['', 'type'=>'string'],
'Couchbase\SearchSortGeoDistance::__construct' => ['void'],
'Couchbase\SearchSortGeoDistance::descending' => ['Couchbase\SearchSortGeoDistance', 'descending'=>'bool'],
'Couchbase\SearchSortGeoDistance::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortGeoDistance::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortGeoDistance::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortGeoDistance::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortGeoDistance::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortGeoDistance::unit' => ['Couchbase\SearchSortGeoDistance', 'unit'=>'string'],
'Couchbase\SearchSortId::__construct' => ['void'],
'Couchbase\SearchSortId::descending' => ['Couchbase\SearchSortId', 'descending'=>'bool'],
'Couchbase\SearchSortId::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortId::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortId::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortId::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortId::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SearchSortScore::__construct' => ['void'],
'Couchbase\SearchSortScore::descending' => ['Couchbase\SearchSortScore', 'descending'=>'bool'],
'Couchbase\SearchSortScore::field' => ['Couchbase\SearchSortField', 'field'=>'string'],
'Couchbase\SearchSortScore::geoDistance' => ['Couchbase\SearchSortGeoDistance', 'field'=>'string', 'longitude'=>'float', 'latitude'=>'float'],
'Couchbase\SearchSortScore::id' => ['Couchbase\SearchSortId'],
'Couchbase\SearchSortScore::jsonSerialize' => ['mixed'],
'Couchbase\SearchSortScore::score' => ['Couchbase\SearchSortScore'],
'Couchbase\SpatialViewQuery::__construct' => ['void'],
'Couchbase\SpatialViewQuery::bbox' => ['Couchbase\SpatialViewQuery', 'bbox'=>'array'],
'Couchbase\SpatialViewQuery::consistency' => ['Couchbase\SpatialViewQuery', 'consistency'=>'int'],
'Couchbase\SpatialViewQuery::custom' => ['', 'customParameters'=>'array'],
'Couchbase\SpatialViewQuery::encode' => ['array'],
'Couchbase\SpatialViewQuery::endRange' => ['Couchbase\SpatialViewQuery', 'range'=>'array'],
'Couchbase\SpatialViewQuery::limit' => ['Couchbase\SpatialViewQuery', 'limit'=>'int'],
'Couchbase\SpatialViewQuery::order' => ['Couchbase\SpatialViewQuery', 'order'=>'int'],
'Couchbase\SpatialViewQuery::skip' => ['Couchbase\SpatialViewQuery', 'skip'=>'int'],
'Couchbase\SpatialViewQuery::startRange' => ['Couchbase\SpatialViewQuery', 'range'=>'array'],
'Couchbase\TermRangeSearchQuery::__construct' => ['void'],
'Couchbase\TermRangeSearchQuery::boost' => ['Couchbase\TermRangeSearchQuery', 'boost'=>'float'],
'Couchbase\TermRangeSearchQuery::field' => ['Couchbase\TermRangeSearchQuery', 'field'=>'string'],
'Couchbase\TermRangeSearchQuery::jsonSerialize' => ['array'],
'Couchbase\TermRangeSearchQuery::max' => ['Couchbase\TermRangeSearchQuery', 'max'=>'string', 'inclusive='=>'bool'],
'Couchbase\TermRangeSearchQuery::min' => ['Couchbase\TermRangeSearchQuery', 'min'=>'string', 'inclusive='=>'bool'],
'Couchbase\TermSearchFacet::__construct' => ['void'],
'Couchbase\TermSearchFacet::jsonSerialize' => ['array'],
'Couchbase\TermSearchQuery::__construct' => ['void'],
'Couchbase\TermSearchQuery::boost' => ['Couchbase\TermSearchQuery', 'boost'=>'float'],
'Couchbase\TermSearchQuery::field' => ['Couchbase\TermSearchQuery', 'field'=>'string'],
'Couchbase\TermSearchQuery::fuzziness' => ['Couchbase\TermSearchQuery', 'fuzziness'=>'int'],
'Couchbase\TermSearchQuery::jsonSerialize' => ['array'],
'Couchbase\TermSearchQuery::prefixLength' => ['Couchbase\TermSearchQuery', 'prefixLength'=>'int'],
'Couchbase\UserSettings::fullName' => ['Couchbase\UserSettings', 'fullName'=>'string'],
'Couchbase\UserSettings::password' => ['Couchbase\UserSettings', 'password'=>'string'],
'Couchbase\UserSettings::role' => ['Couchbase\UserSettings', 'role'=>'string', 'bucket='=>'string'],
'Couchbase\ViewQuery::__construct' => ['void'],
'Couchbase\ViewQuery::consistency' => ['Couchbase\ViewQuery', 'consistency'=>'int'],
'Couchbase\ViewQuery::custom' => ['Couchbase\ViewQuery', 'customParameters'=>'array'],
'Couchbase\ViewQuery::encode' => ['array'],
'Couchbase\ViewQuery::from' => ['Couchbase\ViewQuery', 'designDocumentName'=>'string', 'viewName'=>'string'],
'Couchbase\ViewQuery::fromSpatial' => ['Couchbase\SpatialViewQuery', 'designDocumentName'=>'string', 'viewName'=>'string'],
'Couchbase\ViewQuery::group' => ['Couchbase\ViewQuery', 'group'=>'bool'],
'Couchbase\ViewQuery::groupLevel' => ['Couchbase\ViewQuery', 'groupLevel'=>'int'],
'Couchbase\ViewQuery::idRange' => ['Couchbase\ViewQuery', 'startKeyDocumentId'=>'string', 'endKeyDocumentId'=>'string'],
'Couchbase\ViewQuery::key' => ['Couchbase\ViewQuery', 'key'=>'mixed'],
'Couchbase\ViewQuery::keys' => ['Couchbase\ViewQuery', 'keys'=>'array'],
'Couchbase\ViewQuery::limit' => ['Couchbase\ViewQuery', 'limit'=>'int'],
'Couchbase\ViewQuery::order' => ['Couchbase\ViewQuery', 'order'=>'int'],
'Couchbase\ViewQuery::range' => ['Couchbase\ViewQuery', 'startKey'=>'mixed', 'endKey'=>'mixed', 'inclusiveEnd='=>'bool'],
'Couchbase\ViewQuery::reduce' => ['Couchbase\ViewQuery', 'reduce'=>'bool'],
'Couchbase\ViewQuery::skip' => ['Couchbase\ViewQuery', 'skip'=>'int'],
'Couchbase\ViewQueryEncodable::encode' => ['array'],
'Couchbase\WildcardSearchQuery::__construct' => ['void'],
'Couchbase\WildcardSearchQuery::boost' => ['Couchbase\WildcardSearchQuery', 'boost'=>'float'],
'Couchbase\WildcardSearchQuery::field' => ['Couchbase\WildcardSearchQuery', 'field'=>'string'],
'Couchbase\WildcardSearchQuery::jsonSerialize' => ['array'],
'Couchbase\zlibCompress' => ['string', 'data'=>'string'],
'Couchbase\zlibDecompress' => ['string', 'data'=>'string'],
'count' => ['int', 'var'=>'Countable|array|SimpleXMLElement|ResourceBundle', 'mode='=>'int'],
'count_chars' => ['mixed', 'input'=>'string', 'mode='=>'int'],
'Countable::count' => ['int'],
'crack_check' => ['bool', 'dictionary'=>'', 'password'=>'string'],
'crack_closedict' => ['bool', 'dictionary='=>'resource'],
'crack_getlastmessage' => ['string'],
'crack_opendict' => ['resource|false', 'dictionary'=>'string'],
'crash' => [''],
'crc32' => ['int', 'str'=>'string'],
'create_function' => ['string', 'args'=>'string', 'code'=>'string'],
'crypt' => ['?string', 'str'=>'string', 'salt='=>'string'],
'ctype_alnum' => ['bool', 'c'=>'string|int'],
'ctype_alpha' => ['bool', 'c'=>'string|int'],
'ctype_cntrl' => ['bool', 'c'=>'string|int'],
'ctype_digit' => ['bool', 'c'=>'string|int'],
'ctype_graph' => ['bool', 'c'=>'string|int'],
'ctype_lower' => ['bool', 'c'=>'string|int'],
'ctype_print' => ['bool', 'c'=>'string|int'],
'ctype_punct' => ['bool', 'c'=>'string|int'],
'ctype_space' => ['bool', 'c'=>'string|int'],
'ctype_upper' => ['bool', 'c'=>'string|int'],
'ctype_xdigit' => ['bool', 'c'=>'string|int'],
'cubrid_affected_rows' => ['int', 'req_identifier='=>''],
'cubrid_bind' => ['bool', 'req_identifier'=>'resource', 'bind_param'=>'int', 'bind_value'=>'mixed', 'bind_value_type='=>'string'],
'cubrid_client_encoding' => ['string', 'conn_identifier='=>''],
'cubrid_close' => ['bool', 'conn_identifier='=>''],
'cubrid_close_prepare' => ['bool', 'req_identifier'=>'resource'],
'cubrid_close_request' => ['bool', 'req_identifier'=>'resource'],
'cubrid_col_get' => ['array', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string'],
'cubrid_col_size' => ['int', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string'],
'cubrid_column_names' => ['array', 'req_identifier'=>'resource'],
'cubrid_column_types' => ['array', 'req_identifier'=>'resource'],
'cubrid_commit' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_connect' => ['resource', 'host'=>'string', 'port'=>'int', 'dbname'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_connect_with_url' => ['resource', 'conn_url'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_current_oid' => ['string', 'req_identifier'=>'resource'],
'cubrid_data_seek' => ['bool', 'req_identifier'=>'', 'row_number'=>'int'],
'cubrid_db_name' => ['string', 'result'=>'array', 'index'=>'int'],
'cubrid_db_parameter' => ['array', 'conn_identifier'=>'resource'],
'cubrid_disconnect' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_errno' => ['int', 'conn_identifier='=>''],
'cubrid_error' => ['string', 'connection='=>''],
'cubrid_error_code' => ['int'],
'cubrid_error_code_facility' => ['int'],
'cubrid_error_msg' => ['string'],
'cubrid_execute' => ['bool', 'conn_identifier'=>'', 'sql'=>'string', 'option='=>'int', 'request_identifier='=>''],
'cubrid_fetch' => ['mixed', 'result'=>'resource', 'type='=>'int'],
'cubrid_fetch_array' => ['array', 'result'=>'resource', 'type='=>'int'],
'cubrid_fetch_assoc' => ['array', 'result'=>'resource'],
'cubrid_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'cubrid_fetch_lengths' => ['array', 'result'=>'resource'],
'cubrid_fetch_object' => ['object', 'result'=>'resource', 'class_name='=>'string', 'params='=>'array'],
'cubrid_fetch_row' => ['array', 'result'=>'resource'],
'cubrid_field_flags' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_len' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_name' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_seek' => ['bool', 'result'=>'resource', 'field_offset='=>'int'],
'cubrid_field_table' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_field_type' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'cubrid_free_result' => ['bool', 'req_identifier'=>'resource'],
'cubrid_get' => ['mixed', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr='=>'mixed'],
'cubrid_get_autocommit' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_get_charset' => ['string', 'conn_identifier'=>'resource'],
'cubrid_get_class_name' => ['string', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_get_client_info' => ['string'],
'cubrid_get_db_parameter' => ['array', 'conn_identifier'=>'resource'],
'cubrid_get_query_timeout' => ['int', 'req_identifier'=>'resource'],
'cubrid_get_server_info' => ['string', 'conn_identifier'=>'resource'],
'cubrid_insert_id' => ['string', 'conn_identifier='=>'resource'],
'cubrid_is_instance' => ['int', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_list_dbs' => ['array', 'conn_identifier'=>'resource'],
'cubrid_load_from_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string', 'file_name'=>'string'],
'cubrid_lob2_bind' => ['bool', 'req_identifier'=>'resource', 'bind_index'=>'int', 'bind_value'=>'mixed', 'bind_value_type='=>'string'],
'cubrid_lob2_close' => ['bool', 'lob_identifier'=>'resource'],
'cubrid_lob2_export' => ['bool', 'lob_identifier'=>'resource', 'file_name'=>'string'],
'cubrid_lob2_import' => ['bool', 'lob_identifier'=>'resource', 'file_name'=>'string'],
'cubrid_lob2_new' => ['resource', 'conn_identifier='=>'resource', 'type='=>'string'],
'cubrid_lob2_read' => ['string', 'lob_identifier'=>'resource', 'len'=>'int'],
'cubrid_lob2_seek' => ['bool', 'lob_identifier'=>'resource', 'offset'=>'int', 'origin='=>'int'],
'cubrid_lob2_seek64' => ['bool', 'lob_identifier'=>'resource', 'offset'=>'string', 'origin='=>'int'],
'cubrid_lob2_size' => ['int', 'lob_identifier'=>'resource'],
'cubrid_lob2_size64' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lob2_tell' => ['int', 'lob_identifier'=>'resource'],
'cubrid_lob2_tell64' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lob2_write' => ['bool', 'lob_identifier'=>'resource', 'buf'=>'string'],
'cubrid_lob_close' => ['bool', 'lob_identifier_array'=>'array'],
'cubrid_lob_export' => ['bool', 'conn_identifier'=>'resource', 'lob_identifier'=>'resource', 'path_name'=>'string'],
'cubrid_lob_get' => ['array', 'conn_identifier'=>'resource', 'sql'=>'string'],
'cubrid_lob_send' => ['bool', 'conn_identifier'=>'resource', 'lob_identifier'=>'resource'],
'cubrid_lob_size' => ['string', 'lob_identifier'=>'resource'],
'cubrid_lock_read' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_lock_write' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string'],
'cubrid_move_cursor' => ['int', 'req_identifier'=>'resource', 'offset'=>'int', 'origin='=>'int'],
'cubrid_new_glo' => ['string', 'conn_identifier'=>'', 'class_name'=>'string', 'file_name'=>'string'],
'cubrid_next_result' => ['bool', 'result'=>'resource'],
'cubrid_num_cols' => ['int', 'req_identifier'=>'resource'],
'cubrid_num_fields' => ['int', 'result'=>'resource'],
'cubrid_num_rows' => ['int', 'req_identifier'=>'resource'],
'cubrid_pconnect' => ['resource', 'host'=>'string', 'port'=>'int', 'dbname'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_pconnect_with_url' => ['resource', 'conn_url'=>'string', 'userid='=>'string', 'passwd='=>'string'],
'cubrid_ping' => ['bool', 'conn_identifier='=>''],
'cubrid_prepare' => ['resource', 'conn_identifier'=>'resource', 'prepare_stmt'=>'string', 'option='=>'int'],
'cubrid_put' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr='=>'string', 'value='=>'mixed'],
'cubrid_query' => ['resource', 'query'=>'string', 'conn_identifier='=>''],
'cubrid_real_escape_string' => ['string', 'unescaped_string'=>'string', 'conn_identifier='=>''],
'cubrid_result' => ['string', 'result'=>'resource', 'row'=>'int', 'field='=>''],
'cubrid_rollback' => ['bool', 'conn_identifier'=>'resource'],
'cubrid_save_to_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string', 'file_name'=>'string'],
'cubrid_schema' => ['array', 'conn_identifier'=>'resource', 'schema_type'=>'int', 'class_name='=>'string', 'attr_name='=>'string'],
'cubrid_send_glo' => ['int', 'conn_identifier'=>'', 'oid'=>'string'],
'cubrid_seq_add' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'seq_element'=>'string'],
'cubrid_seq_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int'],
'cubrid_seq_insert' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int', 'seq_element'=>'string'],
'cubrid_seq_put' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'index'=>'int', 'seq_element'=>'string'],
'cubrid_set_add' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'set_element'=>'string'],
'cubrid_set_autocommit' => ['bool', 'conn_identifier'=>'resource', 'mode'=>'bool'],
'cubrid_set_db_parameter' => ['bool', 'conn_identifier'=>'resource', 'param_type'=>'int', 'param_value'=>'int'],
'cubrid_set_drop' => ['bool', 'conn_identifier'=>'resource', 'oid'=>'string', 'attr_name'=>'string', 'set_element'=>'string'],
'cubrid_set_query_timeout' => ['bool', 'req_identifier'=>'resource', 'timeout'=>'int'],
'cubrid_unbuffered_query' => ['resource', 'query'=>'string', 'conn_identifier='=>''],
'cubrid_version' => ['string'],
'curl_close' => ['void', 'ch'=>'resource'],
'curl_copy_handle' => ['resource', 'ch'=>'resource'],
'curl_errno' => ['int', 'ch'=>'resource'],
'curl_error' => ['string', 'ch'=>'resource'],
'curl_escape' => ['string|false', 'ch'=>'resource', 'str'=>'string'],
'curl_exec' => ['bool|string', 'ch'=>'resource'],
'curl_file_create' => ['CURLFile', 'filename'=>'string', 'mimetype='=>'string', 'postfilename='=>'string'],
'curl_getinfo' => ['mixed', 'ch'=>'resource', 'option='=>'int'],
'curl_init' => ['resource|false', 'url='=>'string'],
'curl_multi_add_handle' => ['int', 'mh'=>'resource', 'ch'=>'resource'],
'curl_multi_close' => ['void', 'mh'=>'resource'],
'curl_multi_errno' => ['int', 'mh'=>'resource'],
'curl_multi_exec' => ['int', 'mh'=>'resource', '&w_still_running'=>'int'],
'curl_multi_getcontent' => ['string', 'ch'=>'resource'],
'curl_multi_info_read' => ['array|false', 'mh'=>'resource', '&w_msgs_in_queue='=>'int'],
'curl_multi_init' => ['resource|false'],
'curl_multi_remove_handle' => ['int', 'mh'=>'resource', 'ch'=>'resource'],
'curl_multi_select' => ['int', 'mh'=>'resource', 'timeout='=>'float'],
'curl_multi_setopt' => ['bool', 'mh'=>'resource', 'option'=>'int', 'value'=>'mixed'],
'curl_multi_strerror' => ['?string', 'code'=>'int'],
'curl_pause' => ['int', 'ch'=>'resource', 'bitmask'=>'int'],
'curl_reset' => ['void', 'ch'=>'resource'],
'curl_setopt' => ['bool', 'ch'=>'resource', 'option'=>'int', 'value'=>'callable|mixed'],
'curl_setopt_array' => ['bool', 'ch'=>'resource', 'options'=>'array'],
'curl_share_close' => ['void', 'sh'=>'resource'],
'curl_share_errno' => ['int', 'sh'=>'resource'],
'curl_share_init' => ['resource'],
'curl_share_setopt' => ['bool', 'sh'=>'resource', 'option'=>'int', 'value'=>'string'],
'curl_share_strerror' => ['string', 'code'=>'int'],
'curl_strerror' => ['?string', 'code'=>'int'],
'curl_unescape' => ['string|false', 'ch'=>'resource', 'str'=>'string'],
'curl_version' => ['array', 'version='=>'int'],
'CURLFile::__construct' => ['void', 'filename'=>'string', 'mimetype='=>'string', 'postfilename='=>'string'],
'CURLFile::__wakeup' => ['void'],
'CURLFile::getFilename' => ['string'],
'CURLFile::getMimeType' => ['string'],
'CURLFile::getPostFilename' => ['string'],
'CURLFile::setMimeType' => ['void', 'mime'=>'string'],
'CURLFile::setPostFilename' => ['void', 'name'=>'string'],
'current' => ['mixed|false', 'array_arg'=>'array'],
'cyrus_authenticate' => ['void', 'connection'=>'resource', 'mechlist='=>'string', 'service='=>'string', 'user='=>'string', 'minssf='=>'int', 'maxssf='=>'int', 'authname='=>'string', 'password='=>'string'],
'cyrus_bind' => ['bool', 'connection'=>'resource', 'callbacks'=>'array'],
'cyrus_close' => ['bool', 'connection'=>'resource'],
'cyrus_connect' => ['resource', 'host='=>'string', 'port='=>'string', 'flags='=>'int'],
'cyrus_query' => ['array', 'connection'=>'resource', 'query'=>'string'],
'cyrus_unbind' => ['bool', 'connection'=>'resource', 'trigger_name'=>'string'],
'date' => ['string|false', 'format'=>'string', 'timestamp='=>'int'],
'date_add' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_create' => ['DateTime|false', 'time='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_from_format' => ['DateTime|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'DateTimeZone'],
'date_create_immutable' => ['DateTimeImmutable|false', 'time='=>'string', 'timezone='=>'?DateTimeZone'],
'date_create_immutable_from_format' => ['DateTimeImmutable|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'date_date_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'date_default_timezone_get' => ['string'],
'date_default_timezone_set' => ['bool', 'timezone_identifier'=>'string'],
'date_diff' => ['DateInterval|false', 'obj1'=>'DateTimeInterface', 'obj2'=>'DateTimeInterface', 'absolute='=>'bool'],
'date_format' => ['string|false', 'obj'=>'DateTimeInterface', 'format'=>'string'],
'date_get_last_errors' => ['array'],
'date_interval_create_from_date_string' => ['DateInterval', 'time'=>'string'],
'date_interval_format' => ['string', 'object'=>'DateInterval', 'format'=>'string'],
'date_isodate_set' => ['DateTime|false', 'object'=>'DateTime', 'year'=>'int', 'week'=>'int', 'day='=>'int|mixed'],
'date_modify' => ['DateTime|false', 'object'=>'DateTime', 'modify'=>'string'],
'date_offset_get' => ['int|false', 'obj'=>'DateTimeInterface'],
'date_parse' => ['array|false', 'date'=>'string'],
'date_parse_from_format' => ['array', 'format'=>'string', 'date'=>'string'],
'date_sub' => ['DateTime|false', 'object'=>'DateTime', 'interval'=>'DateInterval'],
'date_sun_info' => ['array|false', 'time'=>'int', 'latitude'=>'float', 'longitude'=>'float'],
'date_sunrise' => ['mixed', 'time'=>'int', 'format='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'gmt_offset='=>'float'],
'date_sunset' => ['mixed', 'time'=>'int', 'format='=>'int', 'latitude='=>'float', 'longitude='=>'float', 'zenith='=>'float', 'gmt_offset='=>'float'],
'date_time_set' => ['DateTime|false', 'object'=>'DateTime', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'date_timestamp_get' => ['int', 'obj'=>'DateTimeInterface'],
'date_timestamp_set' => ['DateTime|false', 'object'=>'DateTime', 'unixtimestamp'=>'int'],
'date_timezone_get' => ['DateTimeZone|false', 'obj'=>'DateTimeInterface'],
'date_timezone_set' => ['DateTime|false', 'object'=>'DateTime', 'timezone'=>'DateTimeZone'],
'datefmt_create' => ['IntlDateFormatter|false', 'locale'=>'string', 'datetype'=>'int', 'timetype'=>'int', 'timezone='=>'string|DateTimeZone|IntlTimeZone|null', 'calendar='=>'int|IntlCalendar|null', 'pattern='=>'string'],
'datefmt_format' => ['string|false', 'fmt'=>'IntlDateFormatter', 'value'=>'DateTime|IntlCalendar|array|int'],
'datefmt_format_object' => ['string|false', 'object'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'datefmt_get_calendar' => ['int', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_calendar_object' => ['IntlCalendar', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_datetype' => ['int', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_error_code' => ['int', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_error_message' => ['string', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_locale' => ['string|false', 'fmt'=>'IntlDateFormatter', 'which='=>'int'],
'datefmt_get_pattern' => ['string', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_timetype' => ['int', 'fmt'=>'IntlDateFormatter'],
'datefmt_get_timezone' => ['IntlTimeZone|false'],
'datefmt_get_timezone_id' => ['string', 'fmt'=>'IntlDateFormatter'],
'datefmt_is_lenient' => ['bool', 'fmt'=>'IntlDateFormatter'],
'datefmt_localtime' => ['array|false', 'fmt'=>'IntlDateFormatter', 'text_to_parse='=>'string', '&rw_parse_pos='=>'int'],
'datefmt_parse' => ['int|false', 'fmt'=>'IntlDateFormatter', 'text_to_parse='=>'string', '&rw_parse_pos='=>'int'],
'datefmt_set_calendar' => ['bool', 'fmt'=>'IntlDateFormatter', 'which'=>'int'],
'datefmt_set_lenient' => ['?bool', 'fmt'=>'IntlDateFormatter', 'lenient'=>'bool'],
'datefmt_set_pattern' => ['bool', 'fmt'=>'IntlDateFormatter', 'pattern'=>'string'],
'datefmt_set_timezone' => ['bool', 'zone'=>'mixed'],
'datefmt_set_timezone_id' => ['bool', 'fmt'=>'IntlDateFormatter', 'zone'=>'string'],
'DateInterval::__construct' => ['void', 'spec'=>'string'],
'DateInterval::__set_state' => ['DateInterval', 'array'=>'array'],
'DateInterval::__wakeup' => ['void'],
'DateInterval::createFromDateString' => ['DateInterval', 'time'=>'string'],
'DateInterval::format' => ['string', 'format'=>'string'],
'DatePeriod::__construct' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'recur'=>'int', 'options='=>'int'],
'DatePeriod::__construct\'1' => ['void', 'start'=>'DateTimeInterface', 'interval'=>'DateInterval', 'end'=>'DateTimeInterface', 'options='=>'int'],
'DatePeriod::__construct\'2' => ['void', 'iso'=>'string', 'options='=>'int'],
'DatePeriod::__wakeup' => ['void'],
'DatePeriod::getDateInterval' => ['DateInterval'],
'DatePeriod::getEndDate' => ['?DateTimeInterface'],
'DatePeriod::getStartDate' => ['DateTimeInterface'],
'DateTime::__construct' => ['void', 'time='=>'string'],
'DateTime::__construct\'1' => ['void', 'time'=>'?string', 'timezone'=>'?DateTimeZone'],
'DateTime::__set_state' => ['static', 'array'=>'array'],
'DateTime::__wakeup' => ['void'],
'DateTime::add' => ['static', 'interval'=>'DateInterval'],
'DateTime::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTime::createFromImmutable' => ['static', 'datetTimeImmutable'=>'DateTimeImmutable'],
'DateTime::diff' => ['DateInterval|false', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTime::format' => ['string|false', 'format'=>'string'],
'DateTime::getLastErrors' => ['array'],
'DateTime::getOffset' => ['int'],
'DateTime::getTimestamp' => ['int|false'],
'DateTime::getTimezone' => ['DateTimeZone'],
'DateTime::modify' => ['static|false', 'modify'=>'string'],
'DateTime::setDate' => ['static', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'DateTime::setISODate' => ['static', 'year'=>'int', 'week'=>'int', 'day='=>'int'],
'DateTime::setTime' => ['static|false', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'DateTime::setTimestamp' => ['static', 'unixtimestamp'=>'int'],
'DateTime::setTimezone' => ['static', 'timezone'=>'DateTimeZone'],
'DateTime::sub' => ['static', 'interval'=>'DateInterval'],
'DateTimeImmutable::__construct' => ['void', 'time='=>'string'],
'DateTimeImmutable::__construct\'1' => ['void', 'time'=>'?string', 'timezone'=>'?DateTimeZone'],
'DateTimeImmutable::__set_state' => ['static', 'array'=>'array'],
'DateTimeImmutable::__wakeup' => ['void'],
'DateTimeImmutable::add' => ['static', 'interval'=>'DateInterval'],
'DateTimeImmutable::createFromFormat' => ['static|false', 'format'=>'string', 'time'=>'string', 'timezone='=>'?DateTimeZone'],
'DateTimeImmutable::createFromMutable' => ['static', 'datetime'=>'DateTime'],
'DateTimeImmutable::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeImmutable::format' => ['string|false', 'format'=>'string'],
'DateTimeImmutable::getLastErrors' => ['array'],
'DateTimeImmutable::getOffset' => ['int'],
'DateTimeImmutable::getTimestamp' => ['int|false'],
'DateTimeImmutable::getTimezone' => ['DateTimeZone'],
'DateTimeImmutable::modify' => ['static', 'modify'=>'string'],
'DateTimeImmutable::setDate' => ['static|false', 'year'=>'int', 'month'=>'int', 'day'=>'int'],
'DateTimeImmutable::setISODate' => ['static|false', 'year'=>'int', 'week'=>'int', 'day='=>'int'],
'DateTimeImmutable::setTime' => ['static|false', 'hour'=>'int', 'minute'=>'int', 'second='=>'int', 'microseconds='=>'int'],
'DateTimeImmutable::setTimestamp' => ['static|false', 'unixtimestamp'=>'int'],
'DateTimeImmutable::setTimezone' => ['static|false', 'timezone'=>'DateTimeZone'],
'DateTimeImmutable::sub' => ['static|false', 'interval'=>'DateInterval'],
'DateTimeInterface::diff' => ['DateInterval', 'datetime2'=>'DateTimeInterface', 'absolute='=>'bool'],
'DateTimeInterface::format' => ['string', 'format'=>'string'],
'DateTimeInterface::getOffset' => ['int'],
'DateTimeInterface::getTimestamp' => ['int|false'],
'DateTimeInterface::getTimezone' => ['DateTimeZone'],
'DateTimeZone::__construct' => ['void', 'timezone'=>'string'],
'DateTimeZone::__set_state' => ['DateTimeZone', 'array'=>'array'],
'DateTimeZone::__wakeup' => ['void'],
'DateTimeZone::getLocation' => ['array|false'],
'DateTimeZone::getName' => ['string'],
'DateTimeZone::getOffset' => ['int|false', 'datetime'=>'DateTimeInterface'],
'DateTimeZone::getTransitions' => ['array|false', 'timestamp_begin='=>'int', 'timestamp_end='=>'int'],
'DateTimeZone::listAbbreviations' => ['array|false'],
'DateTimeZone::listIdentifiers' => ['array|false', 'what='=>'int', 'country='=>'string'],
'db2_autocommit' => ['mixed', 'connection'=>'resource', 'value='=>'int'],
'db2_bind_param' => ['bool', 'stmt'=>'resource', 'parameter_number'=>'int', 'variable_name'=>'string', 'parameter_type='=>'int', 'data_type='=>'int', 'precision='=>'int', 'scale='=>'int'],
'db2_client_info' => ['object|false', 'connection'=>'resource'],
'db2_close' => ['bool', 'connection'=>'resource'],
'db2_column_privileges' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'db2_columns' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'db2_commit' => ['bool', 'connection'=>'resource'],
'db2_conn_error' => ['string', 'connection='=>'resource'],
'db2_conn_errormsg' => ['string', 'connection='=>'resource'],
'db2_connect' => ['resource|false', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'options='=>'array'],
'db2_cursor_type' => ['int', 'stmt'=>'resource'],
'db2_escape_string' => ['string', 'string_literal'=>'string'],
'db2_exec' => ['resource|false', 'connection'=>'resource', 'statement'=>'string', 'options='=>'array'],
'db2_execute' => ['bool', 'stmt'=>'resource', 'parameters='=>'array'],
'db2_fetch_array' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_assoc' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_both' => ['array|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_object' => ['object|false', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_fetch_row' => ['bool', 'stmt'=>'resource', 'row_number='=>'int'],
'db2_field_display_size' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_name' => ['string|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_num' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_precision' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_scale' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_type' => ['string|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_field_width' => ['int|false', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_foreign_keys' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string'],
'db2_free_result' => ['bool', 'stmt'=>'resource'],
'db2_free_stmt' => ['bool', 'stmt'=>'resource'],
'db2_get_option' => ['string|false', 'resource'=>'resource', 'option'=>'string'],
'db2_last_insert_id' => ['string', 'resource'=>'resource'],
'db2_lob_read' => ['string|false', 'stmt'=>'resource', 'colnum'=>'int', 'length'=>'int'],
'db2_next_result' => ['resource|false', 'stmt'=>'resource'],
'db2_num_fields' => ['int|false', 'stmt'=>'resource'],
'db2_num_rows' => ['int', 'stmt'=>'resource'],
'db2_pclose' => ['bool', 'resource'=>'resource'],
'db2_pconnect' => ['resource|false', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'options='=>'array'],
'db2_prepare' => ['resource|false', 'connection'=>'resource', 'statement'=>'string', 'options='=>'array'],
'db2_primary_keys' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string'],
'db2_primarykeys' => [''],
'db2_procedure_columns' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'procedure'=>'string', 'parameter'=>'string'],
'db2_procedurecolumns' => [''],
'db2_procedures' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'procedure'=>'string'],
'db2_result' => ['mixed', 'stmt'=>'resource', 'column'=>'mixed'],
'db2_rollback' => ['bool', 'connection'=>'resource'],
'db2_server_info' => ['object|false', 'connection'=>'resource'],
'db2_set_option' => ['bool', 'resource'=>'resource', 'options'=>'array', 'type'=>'int'],
'db2_setoption' => [''],
'db2_special_columns' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string', 'scope'=>'int'],
'db2_specialcolumns' => [''],
'db2_statistics' => ['resource|false', 'connection'=>'resource', 'qualifier'=>'string', 'schema'=>'string', 'table_name'=>'string', 'unique'=>'bool'],
'db2_stmt_error' => ['string', 'stmt='=>'resource'],
'db2_stmt_errormsg' => ['string', 'stmt='=>'resource'],
'db2_table_privileges' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string'],
'db2_tableprivileges' => [''],
'db2_tables' => ['resource|false', 'connection'=>'resource', 'qualifier='=>'string', 'schema='=>'string', 'table_name='=>'string', 'table_type='=>'string'],
'dba_close' => ['void', 'handle'=>'resource'],
'dba_delete' => ['bool', 'key'=>'string', 'handle'=>'resource'],
'dba_exists' => ['bool', 'key'=>'string', 'handle'=>'resource'],
'dba_fetch' => ['string|false', 'key'=>'string', 'skip'=>'int', 'handle'=>'resource'],
'dba_fetch\'1' => ['string|false', 'key'=>'string', 'handle'=>'resource'],
'dba_firstkey' => ['string', 'handle'=>'resource'],
'dba_handlers' => ['array', 'full_info='=>'bool'],
'dba_insert' => ['bool', 'key'=>'string', 'value'=>'string', 'handle'=>'resource'],
'dba_key_split' => ['array|false', 'key'=>'string'],
'dba_list' => ['array'],
'dba_nextkey' => ['string', 'handle'=>'resource'],
'dba_open' => ['resource', 'path'=>'string', 'mode'=>'string', 'handlername='=>'string', '...args='=>'string'],
'dba_optimize' => ['bool', 'handle'=>'resource'],
'dba_popen' => ['resource', 'path'=>'string', 'mode'=>'string', 'handlername='=>'string', '...args='=>'string'],
'dba_replace' => ['bool', 'key'=>'string', 'value'=>'string', 'handle'=>'resource'],
'dba_sync' => ['bool', 'handle'=>'resource'],
'dbase_add_record' => ['bool', 'dbase_identifier'=>'int', 'record'=>'array'],
'dbase_close' => ['bool', 'dbase_identifier'=>'int'],
'dbase_create' => ['int', 'filename'=>'string', 'fields'=>'array'],
'dbase_delete_record' => ['bool', 'dbase_identifier'=>'int', 'record_number'=>'int'],
'dbase_get_header_info' => ['array', 'dbase_identifier'=>'int'],
'dbase_get_record' => ['array', 'dbase_identifier'=>'int', 'record_number'=>'int'],
'dbase_get_record_with_names' => ['array', 'dbase_identifier'=>'int', 'record_number'=>'int'],
'dbase_numfields' => ['int', 'dbase_identifier'=>'int'],
'dbase_numrecords' => ['int', 'dbase_identifier'=>'int'],
'dbase_open' => ['int', 'filename'=>'string', 'mode'=>'int'],
'dbase_pack' => ['bool', 'dbase_identifier'=>'int'],
'dbase_replace_record' => ['bool', 'dbase_identifier'=>'int', 'record'=>'array', 'record_number'=>'int'],
'dbplus_add' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_aql' => ['resource', 'query'=>'string', 'server='=>'string', 'dbpath='=>'string'],
'dbplus_chdir' => ['string', 'newdir='=>'string'],
'dbplus_close' => ['mixed', 'relation'=>'resource'],
'dbplus_curr' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_errcode' => ['string', 'errno='=>'int'],
'dbplus_errno' => ['int'],
'dbplus_find' => ['int', 'relation'=>'resource', 'constraints'=>'array', 'tuple'=>'mixed'],
'dbplus_first' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_flush' => ['int', 'relation'=>'resource'],
'dbplus_freealllocks' => ['int'],
'dbplus_freelock' => ['int', 'relation'=>'resource', 'tuple'=>'string'],
'dbplus_freerlocks' => ['int', 'relation'=>'resource'],
'dbplus_getlock' => ['int', 'relation'=>'resource', 'tuple'=>'string'],
'dbplus_getunique' => ['int', 'relation'=>'resource', 'uniqueid'=>'int'],
'dbplus_info' => ['int', 'relation'=>'resource', 'key'=>'string', 'result'=>'array'],
'dbplus_last' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_lockrel' => ['int', 'relation'=>'resource'],
'dbplus_next' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_open' => ['resource', 'name'=>'string'],
'dbplus_prev' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_rchperm' => ['int', 'relation'=>'resource', 'mask'=>'int', 'user'=>'string', 'group'=>'string'],
'dbplus_rcreate' => ['resource', 'name'=>'string', 'domlist'=>'mixed', 'overwrite='=>'bool'],
'dbplus_rcrtexact' => ['mixed', 'name'=>'string', 'relation'=>'resource', 'overwrite='=>'bool'],
'dbplus_rcrtlike' => ['mixed', 'name'=>'string', 'relation'=>'resource', 'overwrite='=>'int'],
'dbplus_resolve' => ['array', 'relation_name'=>'string'],
'dbplus_restorepos' => ['int', 'relation'=>'resource', 'tuple'=>'array'],
'dbplus_rkeys' => ['mixed', 'relation'=>'resource', 'domlist'=>'mixed'],
'dbplus_ropen' => ['resource', 'name'=>'string'],
'dbplus_rquery' => ['resource', 'query'=>'string', 'dbpath='=>'string'],
'dbplus_rrename' => ['int', 'relation'=>'resource', 'name'=>'string'],
'dbplus_rsecindex' => ['mixed', 'relation'=>'resource', 'domlist'=>'mixed', 'type'=>'int'],
'dbplus_runlink' => ['int', 'relation'=>'resource'],
'dbplus_rzap' => ['int', 'relation'=>'resource'],
'dbplus_savepos' => ['int', 'relation'=>'resource'],
'dbplus_setindex' => ['int', 'relation'=>'resource', 'idx_name'=>'string'],
'dbplus_setindexbynumber' => ['int', 'relation'=>'resource', 'idx_number'=>'int'],
'dbplus_sql' => ['resource', 'query'=>'string', 'server='=>'string', 'dbpath='=>'string'],
'dbplus_tcl' => ['string', 'sid'=>'int', 'script'=>'string'],
'dbplus_tremove' => ['int', 'relation'=>'resource', 'tuple'=>'array', 'current='=>'array'],
'dbplus_undo' => ['int', 'relation'=>'resource'],
'dbplus_undoprepare' => ['int', 'relation'=>'resource'],
'dbplus_unlockrel' => ['int', 'relation'=>'resource'],
'dbplus_unselect' => ['int', 'relation'=>'resource'],
'dbplus_update' => ['int', 'relation'=>'resource', 'old'=>'array', 'new'=>'array'],
'dbplus_xlockrel' => ['int', 'relation'=>'resource'],
'dbplus_xunlockrel' => ['int', 'relation'=>'resource'],
'dbx_close' => ['int', 'link_identifier'=>'object'],
'dbx_compare' => ['int', 'row_a'=>'array', 'row_b'=>'array', 'column_key'=>'string', 'flags='=>'int'],
'dbx_connect' => ['object', 'module'=>'mixed', 'host'=>'string', 'database'=>'string', 'username'=>'string', 'password'=>'string', 'persistent='=>'int'],
'dbx_error' => ['string', 'link_identifier'=>'object'],
'dbx_escape_string' => ['string', 'link_identifier'=>'object', 'text'=>'string'],
'dbx_fetch_row' => ['mixed', 'result_identifier'=>'object'],
'dbx_query' => ['mixed', 'link_identifier'=>'object', 'sql_statement'=>'string', 'flags='=>'int'],
'dbx_sort' => ['bool', 'result'=>'object', 'user_compare_function'=>'string'],
'dcgettext' => ['string', 'domain_name'=>'string', 'msgid'=>'string', 'category'=>'int'],
'dcngettext' => ['string', 'domain'=>'string', 'msgid1'=>'string', 'msgid2'=>'string', 'n'=>'int', 'category'=>'int'],
'deaggregate' => ['', 'object'=>'object', 'class_name='=>'string'],
'debug_backtrace' => ['array<int,array>', 'options='=>'int|bool', 'limit='=>'int'],
'debug_print_backtrace' => ['void', 'options='=>'int|bool', 'limit='=>'int'],
'debug_zval_dump' => ['void', '...var'=>'mixed'],
'debugger_connect' => [''],
'debugger_connector_pid' => [''],
'debugger_get_server_start_time' => [''],
'debugger_print' => [''],
'debugger_start_debug' => [''],
'decbin' => ['string', 'decimal_number'=>'int'],
'dechex' => ['string', 'decimal_number'=>'int'],
'decoct' => ['string', 'decimal_number'=>'int'],
'define' => ['bool', 'constant_name'=>'string', 'value'=>'mixed', 'case_insensitive='=>'bool'],
'define_syslog_variables' => ['void'],
'defined' => ['bool', 'name'=>'string'],
'deflate_add' => ['string|false', 'context'=>'resource', 'data'=>'string', 'flush_mode='=>'int'],
'deflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'deg2rad' => ['float', 'number'=>'float'],
'dgettext' => ['string', 'domain_name'=>'string', 'msgid'=>'string'],
'dio_close' => ['void', 'fd'=>'resource'],
'dio_fcntl' => ['mixed', 'fd'=>'resource', 'cmd'=>'int', 'args='=>'mixed'],
'dio_open' => ['resource', 'filename'=>'string', 'flags'=>'int', 'mode='=>'int'],
'dio_read' => ['string', 'fd'=>'resource', 'len='=>'int'],
'dio_seek' => ['int', 'fd'=>'resource', 'pos'=>'int', 'whence='=>'int'],
'dio_stat' => ['?array', 'fd'=>'resource'],
'dio_tcsetattr' => ['bool', 'fd'=>'resource', 'options'=>'array'],
'dio_truncate' => ['bool', 'fd'=>'resource', 'offset'=>'int'],
'dio_write' => ['int', 'fd'=>'resource', 'data'=>'string', 'len='=>'int'],
'dir' => ['Directory|false|null', 'directory'=>'string', 'context='=>'resource'],
'Directory::close' => ['void', 'dir_handle='=>'resource'],
'Directory::read' => ['string|false', 'dir_handle='=>'resource'],
'Directory::rewind' => ['void', 'dir_handle='=>'resource'],
'DirectoryIterator::__construct' => ['void', 'path'=>'string'],
'DirectoryIterator::__toString' => ['string'],
'DirectoryIterator::current' => ['DirectoryIterator'],
'DirectoryIterator::getATime' => ['int'],
'DirectoryIterator::getBasename' => ['string', 'suffix='=>'string'],
'DirectoryIterator::getCTime' => ['int'],
'DirectoryIterator::getExtension' => ['string'],
'DirectoryIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'DirectoryIterator::getFilename' => ['string'],
'DirectoryIterator::getGroup' => ['int'],
'DirectoryIterator::getInode' => ['int'],
'DirectoryIterator::getLinkTarget' => ['string'],
'DirectoryIterator::getMTime' => ['int'],
'DirectoryIterator::getOwner' => ['int'],
'DirectoryIterator::getPath' => ['string'],
'DirectoryIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'DirectoryIterator::getPathname' => ['string'],
'DirectoryIterator::getPerms' => ['int'],
'DirectoryIterator::getRealPath' => ['string'],
'DirectoryIterator::getSize' => ['int'],
'DirectoryIterator::getType' => ['string'],
'DirectoryIterator::isDir' => ['bool'],
'DirectoryIterator::isDot' => ['bool'],
'DirectoryIterator::isExecutable' => ['bool'],
'DirectoryIterator::isFile' => ['bool'],
'DirectoryIterator::isLink' => ['bool'],
'DirectoryIterator::isReadable' => ['bool'],
'DirectoryIterator::isWritable' => ['bool'],
'DirectoryIterator::key' => ['string'],
'DirectoryIterator::next' => ['void'],
'DirectoryIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'DirectoryIterator::rewind' => ['void'],
'DirectoryIterator::seek' => ['void', 'position'=>'int'],
'DirectoryIterator::setFileClass' => ['void', 'class_name='=>'string'],
'DirectoryIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'DirectoryIterator::valid' => ['bool'],
'dirname' => ['string', 'path'=>'string', 'levels='=>'int'],
'disk_free_space' => ['float|false', 'path'=>'string'],
'disk_total_space' => ['float|false', 'path'=>'string'],
'diskfreespace' => ['float|false', 'path'=>'string'],
'display_disabled_function' => [''],
'dl' => ['bool', 'extension_filename'=>'string'],
'dngettext' => ['string', 'domain'=>'string', 'msgid1'=>'string', 'msgid2'=>'string', 'count'=>'int'],
'dns_check_record' => ['bool', 'host'=>'string', 'type='=>'string'],
'dns_get_mx' => ['bool', 'hostname'=>'string', '&w_mxhosts'=>'array', '&w_weight'=>'array'],
'dns_get_record' => ['array|false', 'hostname'=>'string', 'type='=>'int', '&w_authns='=>'array', '&w_addtl='=>'array', 'raw='=>'bool'],
'dom_document_relaxNG_validate_file' => ['bool', 'filename'=>'string'],
'dom_document_relaxNG_validate_xml' => ['bool', 'source'=>'string'],
'dom_document_schema_validate' => ['bool', 'source'=>'string', 'flags'=>'int'],
'dom_document_schema_validate_file' => ['bool', 'filename'=>'string', 'flags'=>'int'],
'dom_document_xinclude' => ['int', 'options'=>'int'],
'dom_import_simplexml' => ['DOMElement|false', 'node'=>'SimpleXMLElement'],
'dom_xpath_evaluate' => ['', 'expr'=>'string', 'context'=>'DOMNode', 'registernodens'=>'bool'],
'dom_xpath_query' => ['DOMNodeList', 'expr'=>'string', 'context'=>'DOMNode', 'registernodens'=>'bool'],
'dom_xpath_register_ns' => ['bool', 'prefix'=>'string', 'uri'=>'string'],
'dom_xpath_register_php_functions' => [''],
'DomainException::__clone' => ['void'],
'DomainException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?DomainException'],
'DomainException::__toString' => ['string'],
'DomainException::__wakeup' => ['void'],
'DomainException::getCode' => ['int'],
'DomainException::getFile' => ['string'],
'DomainException::getLine' => ['int'],
'DomainException::getMessage' => ['string'],
'DomainException::getPrevious' => ['Throwable|DomainException|null'],
'DomainException::getTrace' => ['array'],
'DomainException::getTraceAsString' => ['string'],
'DOMAttr::__construct' => ['void', 'name'=>'string', 'value='=>'string'],
'DOMAttr::getLineNo' => ['int'],
'DOMAttr::getNodePath' => ['?string'],
'DOMAttr::hasAttributes' => ['bool'],
'DOMAttr::hasChildNodes' => ['bool'],
'DOMAttr::insertBefore' => ['DOMNode', 'newnode'=>'DOMNode', 'refnode='=>'DOMNode'],
'DOMAttr::isDefaultNamespace' => ['bool', 'namespaceuri'=>'string'],
'DOMAttr::isId' => ['bool'],
'DOMAttr::isSameNode' => ['bool', 'node'=>'DOMNode'],
'DOMAttr::isSupported' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMAttr::lookupNamespaceUri' => ['string', 'prefix'=>'string'],
'DOMAttr::lookupPrefix' => ['string', 'namespaceuri'=>'string'],
'DOMAttr::normalize' => ['void'],
'DOMAttr::removeChild' => ['DOMNode', 'oldnode'=>'DOMNode'],
'DOMAttr::replaceChild' => ['DOMNode', 'newnode'=>'DOMNode', 'oldnode'=>'DOMNode'],
'DomAttribute::name' => ['string'],
'DomAttribute::set_value' => ['bool', 'content'=>'string'],
'DomAttribute::specified' => ['bool'],
'DomAttribute::value' => ['string'],
'DOMCdataSection::__construct' => ['void', 'value'=>'string'],
'DOMCharacterData::appendData' => ['void', 'data'=>'string'],
'DOMCharacterData::deleteData' => ['void', 'offset'=>'int', 'count'=>'int'],
'DOMCharacterData::insertData' => ['void', 'offset'=>'int', 'data'=>'string'],
'DOMCharacterData::replaceData' => ['void', 'offset'=>'int', 'count'=>'int', 'data'=>'string'],
'DOMCharacterData::substringData' => ['string', 'offset'=>'int', 'count'=>'int'],
'DOMComment::__construct' => ['void', 'value='=>'string'],
'DOMDocument::__construct' => ['void', 'version='=>'string', 'encoding='=>'string'],
'DOMDocument::createAttribute' => ['DOMAttr|false', 'name'=>'string'],
'DOMDocument::createAttributeNS' => ['DOMAttr|false', 'namespaceuri'=>'string', 'qualifiedname'=>'string'],
'DOMDocument::createCDATASection' => ['DOMCDATASection|false', 'data'=>'string'],
'DOMDocument::createComment' => ['DOMComment|false', 'data'=>'string'],
'DOMDocument::createDocumentFragment' => ['DOMDocumentFragment|false'],
'DOMDocument::createElement' => ['DOMElement|false', 'name'=>'string', 'value='=>'string'],
'DOMDocument::createElementNS' => ['DOMElement|false', 'namespaceuri'=>'string', 'qualifiedname'=>'string', 'value='=>'string'],
'DOMDocument::createEntityReference' => ['DOMEntityReference|false', 'name'=>'string'],
'DOMDocument::createProcessingInstruction' => ['DOMProcessingInstruction|false', 'target'=>'string', 'data='=>'string'],
'DOMDocument::createTextNode' => ['DOMText|false', 'content'=>'string'],
'DOMDocument::getElementById' => ['?DOMElement', 'elementid'=>'string'],
'DOMDocument::getElementsByTagName' => ['DOMNodeList', 'name'=>'string'],
'DOMDocument::getElementsByTagNameNS' => ['DOMNodeList', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMDocument::importNode' => ['DOMNode|false', 'importednode'=>'DOMNode', 'deep='=>'bool'],
'DOMDocument::load' => ['DOMDocument|bool', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::loadHTML' => ['bool', 'source'=>'string', 'options='=>'int'],
'DOMDocument::loadHTMLFile' => ['bool', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::loadXML' => ['DOMDocument|bool', 'source'=>'string', 'options='=>'int'],
'DOMDocument::normalizeDocument' => ['void'],
'DOMDocument::registerNodeClass' => ['bool', 'baseclass'=>'string', 'extendedclass'=>'string'],
'DOMDocument::relaxNGValidate' => ['bool', 'filename'=>'string'],
'DOMDocument::relaxNGValidateSource' => ['bool', 'source'=>'string'],
'DOMDocument::save' => ['int|false', 'filename'=>'string', 'options='=>'int'],
'DOMDocument::saveHTML' => ['string|false', 'node='=>'?DOMNode'],
'DOMDocument::saveHTMLFile' => ['int|false', 'filename'=>'string'],
'DOMDocument::saveXML' => ['string', 'node='=>'?DOMNode', 'options='=>'int'],
'DOMDocument::schemaValidate' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'DOMDocument::schemaValidateSource' => ['bool', 'source'=>'string', 'flags='=>'int'],
'DOMDocument::validate' => ['bool'],
'DOMDocument::xinclude' => ['int', 'options='=>'int'],
'DOMDocumentFragment::__construct' => ['void'],
'DOMDocumentFragment::appendXML' => ['bool', 'data'=>'string'],
'DomDocumentType::entities' => ['array'],
'DomDocumentType::internal_subset' => ['bool'],
'DomDocumentType::name' => ['string'],
'DomDocumentType::notations' => ['array'],
'DomDocumentType::public_id' => ['string'],
'DomDocumentType::system_id' => ['string'],
'DOMElement::__construct' => ['void', 'name'=>'string', 'value='=>'string', 'uri='=>'string'],
'DOMElement::get_attribute' => ['string', 'name'=>'string'],
'DOMElement::get_attribute_node' => ['DomAttribute', 'name'=>'string'],
'DOMElement::get_elements_by_tagname' => ['array', 'name'=>'string'],
'DOMElement::getAttribute' => ['string', 'name'=>'string'],
'DOMElement::getAttributeNode' => ['DOMAttr', 'name'=>'string'],
'DOMElement::getAttributeNodeNS' => ['DOMAttr', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::getAttributeNS' => ['string', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::getElementsByTagName' => ['DOMNodeList', 'name'=>'string'],
'DOMElement::getElementsByTagNameNS' => ['DOMNodeList', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::has_attribute' => ['bool', 'name'=>'string'],
'DOMElement::hasAttribute' => ['bool', 'name'=>'string'],
'DOMElement::hasAttributeNS' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::remove_attribute' => ['bool', 'name'=>'string'],
'DOMElement::removeAttribute' => ['bool', 'name'=>'string'],
'DOMElement::removeAttributeNode' => ['bool', 'oldnode'=>'DOMAttr'],
'DOMElement::removeAttributeNS' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMElement::set_attribute' => ['DomAttribute', 'name'=>'string', 'value'=>'string'],
'DOMElement::set_attribute_node' => ['DomNode', 'attr'=>'DOMNode'],
'DOMElement::setAttribute' => ['DOMAttr|false', 'name'=>'string', 'value'=>'string'],
'DOMElement::setAttributeNode' => ['?DOMAttr', 'attr'=>'DOMAttr'],
'DOMElement::setAttributeNodeNS' => ['DOMAttr', 'attr'=>'DOMAttr'],
'DOMElement::setAttributeNS' => ['void', 'namespaceuri'=>'string', 'qualifiedname'=>'string', 'value'=>'string'],
'DOMElement::setIdAttribute' => ['void', 'name'=>'string', 'isid'=>'bool'],
'DOMElement::setIdAttributeNode' => ['void', 'attr'=>'DOMAttr', 'isid'=>'bool'],
'DOMElement::setIdAttributeNS' => ['void', 'namespaceuri'=>'string', 'localname'=>'string', 'isid'=>'bool'],
'DOMElement::tagname' => ['string'],
'DOMEntityReference::__construct' => ['void', 'name'=>'string'],
'DOMImplementation::__construct' => ['void'],
'DOMImplementation::createDocument' => ['DOMDocument', 'namespaceuri='=>'string', 'qualifiedname='=>'string', 'doctype='=>'DOMDocumentType'],
'DOMImplementation::createDocumentType' => ['DOMDocumentType', 'qualifiedname='=>'string', 'publicid='=>'string', 'systemid='=>'string'],
'DOMImplementation::hasFeature' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMNamedNodeMap::count' => ['int'],
'DOMNamedNodeMap::getNamedItem' => ['?DOMNode', 'name'=>'string'],
'DOMNamedNodeMap::getNamedItemNS' => ['?DOMNode', 'namespaceuri'=>'string', 'localname'=>'string'],
'DOMNamedNodeMap::item' => ['?DOMNode', 'index'=>'int'],
'DomNode::add_namespace' => ['bool', 'uri'=>'string', 'prefix'=>'string'],
'DomNode::append_child' => ['DOMNode', 'newnode'=>'DOMNode'],
'DOMNode::appendChild' => ['DOMNode', 'newnode'=>'DOMNode'],
'DOMNode::C14N' => ['string', 'exclusive='=>'bool', 'with_comments='=>'bool', 'xpath='=>'array', 'ns_prefixes='=>'array'],
'DOMNode::C14NFile' => ['int|false', 'uri='=>'string', 'exclusive='=>'bool', 'with_comments='=>'bool', 'xpath='=>'array', 'ns_prefixes='=>'array'],
'DOMNode::cloneNode' => ['DOMNode', 'deep='=>'bool'],
'DOMNode::getLineNo' => ['int'],
'DOMNode::getNodePath' => ['?string'],
'DOMNode::hasAttributes' => ['bool'],
'DOMNode::hasChildNodes' => ['bool'],
'DOMNode::insertBefore' => ['DOMNode', 'newnode'=>'DOMNode', 'refnode='=>'DOMNode|null'],
'DOMNode::isDefaultNamespace' => ['bool', 'namespaceuri'=>'string'],
'DOMNode::isSameNode' => ['bool', 'node'=>'DOMNode'],
'DOMNode::isSupported' => ['bool', 'feature'=>'string', 'version'=>'string'],
'DOMNode::lookupNamespaceURI' => ['string', 'prefix'=>'string'],
'DOMNode::lookupPrefix' => ['string', 'namespaceuri'=>'string'],
'DOMNode::normalize' => ['void'],
'DOMNode::removeChild' => ['DOMNode', 'oldnode'=>'DOMNode'],
'DOMNode::replaceChild' => ['DOMNode|false', 'newnode'=>'DOMNode', 'oldnode'=>'DOMNode'],
'DOMNodeList::count' => ['int'],
'DOMNodeList::item' => ['?DOMNode', 'index'=>'int'],
'DOMProcessingInstruction::__construct' => ['void', 'name'=>'string', 'value'=>'string'],
'DomProcessingInstruction::data' => ['string'],
'DomProcessingInstruction::target' => ['string'],
'DOMText::__construct' => ['void', 'value='=>'string'],
'DOMText::isElementContentWhitespace' => ['bool'],
'DOMText::isWhitespaceInElementContent' => ['bool'],
'DOMText::splitText' => ['DOMText', 'offset'=>'int'],
'domxml_new_doc' => ['DomDocument', 'version'=>'string'],
'domxml_open_file' => ['DomDocument', 'filename'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_open_mem' => ['DomDocument', 'str'=>'string', 'mode='=>'int', 'error='=>'array'],
'domxml_version' => ['string'],
'domxml_xmltree' => ['DomDocument', 'str'=>'string'],
'domxml_xslt_stylesheet' => ['DomXsltStylesheet', 'xsl_buf'=>'string'],
'domxml_xslt_stylesheet_doc' => ['DomXsltStylesheet', 'xsl_doc'=>'DOMDocument'],
'domxml_xslt_stylesheet_file' => ['DomXsltStylesheet', 'xsl_file'=>'string'],
'domxml_xslt_version' => ['int'],
'DOMXPath::__construct' => ['void', 'doc'=>'DOMDocument'],
'DOMXPath::evaluate' => ['mixed', 'expression'=>'string', 'contextnode='=>'DOMNode|null', 'registernodens='=>'bool'],
'DOMXPath::query' => ['DOMNodeList|false', 'expression'=>'string', 'contextnode='=>'DOMNode|null', 'registernodens='=>'bool'],
'DOMXPath::registerNamespace' => ['bool', 'prefix'=>'string', 'namespaceuri'=>'string'],
'DOMXPath::registerPhpFunctions' => ['void', 'restrict='=>'mixed'],
'DomXsltStylesheet::process' => ['DomDocument', 'xml_doc'=>'DOMDocument', 'xslt_params='=>'array', 'is_xpath_param='=>'bool', 'profile_filename='=>'string'],
'DomXsltStylesheet::result_dump_file' => ['string', 'xmldoc'=>'DOMDocument', 'filename'=>'string'],
'DomXsltStylesheet::result_dump_mem' => ['string', 'xmldoc'=>'DOMDocument'],
'DOTNET::__call' => ['mixed', 'name'=>'string', 'args'=>''],
'DOTNET::__construct' => ['void', 'assembly_name'=>'string', 'class_name'=>'string', 'codepage='=>'int'],
'DOTNET::__get' => ['mixed', 'name'=>'string'],
'DOTNET::__set' => ['void', 'name'=>'string', 'value'=>''],
'dotnet_load' => ['int', 'assembly_name'=>'string', 'datatype_name='=>'string', 'codepage='=>'int'],
'doubleval' => ['float', 'var'=>'mixed'],
'Ds\Collection::clear' => ['void'],
'Ds\Collection::copy' => ['Ds\Collection'],
'Ds\Collection::isEmpty' => ['bool'],
'Ds\Collection::toArray' => ['array'],
'Ds\Deque::__construct' => ['void', 'values='=>'mixed'],
'Ds\Deque::allocate' => ['void', 'capacity'=>'int'],
'Ds\Deque::apply' => ['void', 'callback'=>'callable'],
'Ds\Deque::capacity' => ['int'],
'Ds\Deque::clear' => ['void'],
'Ds\Deque::contains' => ['bool', '...values='=>'mixed'],
'Ds\Deque::copy' => ['Ds\Deque'],
'Ds\Deque::count' => ['int'],
'Ds\Deque::filter' => ['Ds\Deque', 'callback='=>'callable'],
'Ds\Deque::find' => ['mixed', 'value'=>'mixed'],
'Ds\Deque::first' => ['mixed'],
'Ds\Deque::get' => ['void', 'index'=>'int'],
'Ds\Deque::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Deque::isEmpty' => ['bool'],
'Ds\Deque::join' => ['string', 'glue='=>'string'],
'Ds\Deque::jsonSerialize' => ['array'],
'Ds\Deque::last' => ['mixed'],
'Ds\Deque::map' => ['Ds\Deque', 'callback'=>'callable'],
'Ds\Deque::merge' => ['Ds\Deque', 'values'=>'mixed'],
'Ds\Deque::pop' => ['mixed'],
'Ds\Deque::push' => ['void', '...values='=>'mixed'],
'Ds\Deque::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Deque::remove' => ['mixed', 'index'=>'int'],
'Ds\Deque::reverse' => ['void'],
'Ds\Deque::reversed' => ['Ds\Deque'],
'Ds\Deque::rotate' => ['void', 'rotations'=>'int'],
'Ds\Deque::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Deque::shift' => ['mixed'],
'Ds\Deque::slice' => ['Ds\Deque', 'index'=>'int', 'length='=>'?int'],
'Ds\Deque::sort' => ['void', 'comparator='=>'callable'],
'Ds\Deque::sorted' => ['Ds\Deque', 'comparator='=>'callable'],
'Ds\Deque::sum' => ['int|float'],
'Ds\Deque::toArray' => ['array'],
'Ds\Deque::unshift' => ['void', '...values='=>'mixed'],
'Ds\Hashable::equals' => ['bool', 'obj'=>'mixed'],
'Ds\Hashable::hash' => ['mixed'],
'Ds\Map::__construct' => ['void', 'values='=>'mixed'],
'Ds\Map::allocate' => ['void', 'capacity'=>'int'],
'Ds\Map::apply' => ['void', 'callback'=>'callable'],
'Ds\Map::capacity' => ['int'],
'Ds\Map::clear' => ['void'],
'Ds\Map::copy' => ['Ds\Map'],
'Ds\Map::count' => ['int'],
'Ds\Map::diff' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::filter' => ['Ds\Map', 'callback='=>'callable'],
'Ds\Map::first' => ['Ds\Pair'],
'Ds\Map::get' => ['mixed', 'key'=>'mixed', 'default='=>'mixed'],
'Ds\Map::hasKey' => ['bool', 'key'=>'mixed'],
'Ds\Map::hasValue' => ['bool', 'value'=>'mixed'],
'Ds\Map::intersect' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::isEmpty' => ['bool'],
'Ds\Map::jsonSerialize' => ['array'],
'Ds\Map::keys' => ['Ds\Set'],
'Ds\Map::ksort' => ['void', 'comparator='=>'callable'],
'Ds\Map::ksorted' => ['Ds\Map', 'comparator='=>'callable'],
'Ds\Map::last' => ['Ds\Pair'],
'Ds\Map::map' => ['Ds\Map', 'callback'=>'callable'],
'Ds\Map::merge' => ['Ds\Map', 'values'=>'mixed'],
'Ds\Map::pairs' => ['Ds\Sequence'],
'Ds\Map::put' => ['void', 'key'=>'mixed', 'value'=>'mixed'],
'Ds\Map::putAll' => ['void', 'values'=>'mixed'],
'Ds\Map::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Map::remove' => ['mixed', 'key'=>'mixed', 'default='=>'mixed'],
'Ds\Map::reverse' => ['void'],
'Ds\Map::reversed' => ['Ds\Map'],
'Ds\Map::skip' => ['Ds\Pair', 'position'=>'int'],
'Ds\Map::slice' => ['Ds\Map', 'index'=>'int', 'length='=>'?int'],
'Ds\Map::sort' => ['void', 'comparator='=>'callable'],
'Ds\Map::sorted' => ['Ds\Map', 'comparator='=>'callable'],
'Ds\Map::sum' => ['int|float'],
'Ds\Map::toArray' => ['array'],
'Ds\Map::union' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Map::values' => ['Ds\Sequence'],
'Ds\Map::xor' => ['Ds\Map', 'map'=>'Ds\Map'],
'Ds\Pair::__construct' => ['void', 'key='=>'mixed', 'value='=>'mixed'],
'Ds\Pair::clear' => ['void'],
'Ds\Pair::copy' => ['Ds\Pair'],
'Ds\Pair::isEmpty' => ['bool'],
'Ds\Pair::jsonSerialize' => ['array'],
'Ds\Pair::toArray' => ['array'],
'Ds\PriorityQueue::__construct' => ['void'],
'Ds\PriorityQueue::allocate' => ['void', 'capacity'=>'int'],
'Ds\PriorityQueue::capacity' => ['int'],
'Ds\PriorityQueue::clear' => ['void'],
'Ds\PriorityQueue::copy' => ['Ds\PriorityQueue'],
'Ds\PriorityQueue::count' => ['int'],
'Ds\PriorityQueue::isEmpty' => ['bool'],
'Ds\PriorityQueue::jsonSerialize' => ['array'],
'Ds\PriorityQueue::peek' => ['mixed'],
'Ds\PriorityQueue::pop' => ['mixed'],
'Ds\PriorityQueue::push' => ['void', 'value'=>'mixed', 'priority'=>'int'],
'Ds\PriorityQueue::toArray' => ['array'],
'Ds\Queue::__construct' => ['void', 'values='=>'mixed'],
'Ds\Queue::allocate' => ['void', 'capacity'=>'int'],
'Ds\Queue::capacity' => ['int'],
'Ds\Queue::clear' => ['void'],
'Ds\Queue::copy' => ['Ds\Queue'],
'Ds\Queue::count' => ['int'],
'Ds\Queue::isEmpty' => ['bool'],
'Ds\Queue::jsonSerialize' => ['array'],
'Ds\Queue::peek' => ['mixed'],
'Ds\Queue::pop' => ['mixed'],
'Ds\Queue::push' => ['void', '...values='=>'mixed'],
'Ds\Queue::toArray' => ['array'],
'Ds\Sequence::allocate' => ['void', 'capacity'=>'int'],
'Ds\Sequence::apply' => ['void', 'callback'=>'callable'],
'Ds\Sequence::capacity' => ['int'],
'Ds\Sequence::contains' => ['bool', '...values='=>'mixed'],
'Ds\Sequence::filter' => ['Ds\Sequence', 'callback='=>'callable'],
'Ds\Sequence::find' => ['mixed', 'value'=>'mixed'],
'Ds\Sequence::first' => ['mixed'],
'Ds\Sequence::get' => ['mixed', 'index'=>'int'],
'Ds\Sequence::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Sequence::join' => ['string', 'glue='=>'string'],
'Ds\Sequence::last' => ['void'],
'Ds\Sequence::map' => ['Ds\Sequence', 'callback'=>'callable'],
'Ds\Sequence::merge' => ['Ds\Sequence', 'values'=>'mixed'],
'Ds\Sequence::pop' => ['mixed'],
'Ds\Sequence::push' => ['void', '...values='=>'mixed'],
'Ds\Sequence::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Sequence::remove' => ['mixed', 'index'=>'int'],
'Ds\Sequence::reverse' => ['void'],
'Ds\Sequence::reversed' => ['Ds\Sequence'],
'Ds\Sequence::rotate' => ['void', 'rotations'=>'int'],
'Ds\Sequence::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Sequence::shift' => ['mixed'],
'Ds\Sequence::slice' => ['Ds\Sequence', 'index'=>'int', 'length='=>'?int'],
'Ds\Sequence::sort' => ['void', 'comparator='=>'callable'],
'Ds\Sequence::sorted' => ['Ds\Sequence', 'comparator='=>'callable'],
'Ds\Sequence::sum' => ['int|float'],
'Ds\Sequence::unshift' => ['void', '...values='=>'mixed'],
'Ds\Set::__construct' => ['void', 'values='=>'mixed'],
'Ds\Set::add' => ['void', '...values='=>'mixed'],
'Ds\Set::allocate' => ['void', 'capacity'=>'int'],
'Ds\Set::capacity' => ['int'],
'Ds\Set::clear' => ['void'],
'Ds\Set::contains' => ['bool', '...values='=>'mixed'],
'Ds\Set::copy' => ['Ds\Set'],
'Ds\Set::count' => ['int'],
'Ds\Set::diff' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::filter' => ['Ds\Set', 'callback='=>'callable'],
'Ds\Set::first' => ['mixed'],
'Ds\Set::get' => ['mixed', 'index'=>'int'],
'Ds\Set::intersect' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::isEmpty' => ['bool'],
'Ds\Set::join' => ['string', 'glue='=>'string'],
'Ds\Set::jsonSerialize' => ['array'],
'Ds\Set::last' => ['mixed'],
'Ds\Set::merge' => ['Ds\Set', 'values'=>'mixed'],
'Ds\Set::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Set::remove' => ['void', '...values='=>'mixed'],
'Ds\Set::reverse' => ['void'],
'Ds\Set::reversed' => ['Ds\Set'],
'Ds\Set::slice' => ['Ds\Set', 'index'=>'int', 'length='=>'?int'],
'Ds\Set::sort' => ['void', 'comparator='=>'callable'],
'Ds\Set::sorted' => ['Ds\Set', 'comparator='=>'callable'],
'Ds\Set::sum' => ['int|float'],
'Ds\Set::toArray' => ['array'],
'Ds\Set::union' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Set::xor' => ['Ds\Set', 'set'=>'Ds\Set'],
'Ds\Stack::__construct' => ['void', 'values='=>'mixed'],
'Ds\Stack::allocate' => ['void', 'capacity'=>'int'],
'Ds\Stack::capacity' => ['int'],
'Ds\Stack::clear' => ['void'],
'Ds\Stack::copy' => ['Ds\Stack'],
'Ds\Stack::count' => ['int'],
'Ds\Stack::isEmpty' => ['bool'],
'Ds\Stack::jsonSerialize' => ['array'],
'Ds\Stack::peek' => ['mixed'],
'Ds\Stack::pop' => ['mixed'],
'Ds\Stack::push' => ['void', '...values='=>'mixed'],
'Ds\Stack::toArray' => ['array'],
'Ds\Vector::__construct' => ['void', 'values='=>'mixed'],
'Ds\Vector::allocate' => ['void', 'capacity'=>'int'],
'Ds\Vector::apply' => ['void', 'callback'=>'callable'],
'Ds\Vector::capacity' => ['int'],
'Ds\Vector::clear' => ['void'],
'Ds\Vector::contains' => ['bool', '...values='=>'mixed'],
'Ds\Vector::copy' => ['Ds\Vector'],
'Ds\Vector::count' => ['int'],
'Ds\Vector::filter' => ['Ds\Vector', 'callback='=>'callable'],
'Ds\Vector::find' => ['mixed', 'value'=>'mixed'],
'Ds\Vector::first' => ['mixed'],
'Ds\Vector::get' => ['mixed', 'index'=>'int'],
'Ds\Vector::insert' => ['void', 'index'=>'int', '...values='=>'mixed'],
'Ds\Vector::isEmpty' => ['bool'],
'Ds\Vector::join' => ['string', 'glue='=>'string'],
'Ds\Vector::jsonSerialize' => ['array'],
'Ds\Vector::last' => ['mixed'],
'Ds\Vector::map' => ['Ds\Vector', 'callback'=>'callable'],
'Ds\Vector::merge' => ['Ds\Vector', 'values'=>'mixed'],
'Ds\Vector::pop' => ['mixed'],
'Ds\Vector::push' => ['void', '...values='=>'mixed'],
'Ds\Vector::reduce' => ['mixed', 'callback'=>'callable', 'initial='=>'mixed'],
'Ds\Vector::remove' => ['mixed', 'index'=>'int'],
'Ds\Vector::reverse' => ['void'],
'Ds\Vector::reversed' => ['Ds\Vector'],
'Ds\Vector::rotate' => ['void', 'rotations'=>'int'],
'Ds\Vector::set' => ['void', 'index'=>'int', 'value'=>'mixed'],
'Ds\Vector::shift' => ['mixed'],
'Ds\Vector::slice' => ['Ds\Vector', 'index'=>'int', 'length='=>'?int'],
'Ds\Vector::sort' => ['void', 'comparator='=>'callable'],
'Ds\Vector::sorted' => ['Ds\Vector', 'comparator='=>'callable'],
'Ds\Vector::sum' => ['int|float'],
'Ds\Vector::toArray' => ['array'],
'Ds\Vector::unshift' => ['void', '...values='=>'mixed'],
'each' => ['array', '&rw_arr'=>'array'],
'easter_date' => ['int', 'year='=>'int'],
'easter_days' => ['int', 'year='=>'int', 'method='=>'int'],
'echo' => ['void', 'arg1'=>'string', '...args='=>'string'],
'eio_busy' => ['resource', 'delay'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_cancel' => ['void', 'req'=>'resource'],
'eio_chmod' => ['resource', 'path'=>'string', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_chown' => ['resource', 'path'=>'string', 'uid'=>'int', 'gid='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_close' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_custom' => ['resource', 'execute'=>'callable', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_dup2' => ['resource', 'fd'=>'mixed', 'fd2'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_event_loop' => ['bool'],
'eio_fallocate' => ['resource', 'fd'=>'mixed', 'mode'=>'int', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fchmod' => ['resource', 'fd'=>'mixed', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fchown' => ['resource', 'fd'=>'mixed', 'uid'=>'int', 'gid='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fdatasync' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_fstat' => ['resource', 'fd'=>'mixed', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_fstatvfs' => ['resource', 'fd'=>'mixed', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_fsync' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_ftruncate' => ['resource', 'fd'=>'mixed', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_futime' => ['resource', 'fd'=>'mixed', 'atime'=>'float', 'mtime'=>'float', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_get_event_stream' => ['mixed'],
'eio_get_last_error' => ['string', 'req'=>'resource'],
'eio_grp' => ['resource', 'callback'=>'callable', 'data='=>'string'],
'eio_grp_add' => ['void', 'grp'=>'resource', 'req'=>'resource'],
'eio_grp_cancel' => ['void', 'grp'=>'resource'],
'eio_grp_limit' => ['void', 'grp'=>'resource', 'limit'=>'int'],
'eio_init' => ['void'],
'eio_link' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_lstat' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_mkdir' => ['resource', 'path'=>'string', 'mode'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_mknod' => ['resource', 'path'=>'string', 'mode'=>'int', 'dev'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_nop' => ['resource', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_npending' => ['int'],
'eio_nready' => ['int'],
'eio_nreqs' => ['int'],
'eio_nthreads' => ['int'],
'eio_open' => ['resource', 'path'=>'string', 'flags'=>'int', 'mode'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_poll' => ['int'],
'eio_read' => ['resource', 'fd'=>'mixed', 'length'=>'int', 'offset'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_readahead' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_readdir' => ['resource', 'path'=>'string', 'flags'=>'int', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_readlink' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_realpath' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'string'],
'eio_rename' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_rmdir' => ['resource', 'path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_seek' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'whence'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sendfile' => ['resource', 'out_fd'=>'mixed', 'in_fd'=>'mixed', 'offset'=>'int', 'length'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'string'],
'eio_set_max_idle' => ['void', 'nthreads'=>'int'],
'eio_set_max_parallel' => ['void', 'nthreads'=>'int'],
'eio_set_max_poll_reqs' => ['void', 'nreqs'=>'int'],
'eio_set_max_poll_time' => ['void', 'nseconds'=>'float'],
'eio_set_min_parallel' => ['void', 'nthreads'=>'string'],
'eio_stat' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_statvfs' => ['resource', 'path'=>'string', 'pri'=>'int', 'callback'=>'callable', 'data='=>'mixed'],
'eio_symlink' => ['resource', 'path'=>'string', 'new_path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sync' => ['resource', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_sync_file_range' => ['resource', 'fd'=>'mixed', 'offset'=>'int', 'nbytes'=>'int', 'flags'=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_syncfs' => ['resource', 'fd'=>'mixed', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_truncate' => ['resource', 'path'=>'string', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_unlink' => ['resource', 'path'=>'string', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_utime' => ['resource', 'path'=>'string', 'atime'=>'float', 'mtime'=>'float', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'eio_write' => ['resource', 'fd'=>'mixed', 'str'=>'string', 'length='=>'int', 'offset='=>'int', 'pri='=>'int', 'callback='=>'callable', 'data='=>'mixed'],
'empty' => ['bool', 'var'=>'mixed'],
'EmptyIterator::current' => ['mixed'],
'EmptyIterator::key' => ['mixed'],
'EmptyIterator::next' => ['void'],
'EmptyIterator::rewind' => ['void'],
'EmptyIterator::valid' => ['bool'],
'enchant_broker_describe' => ['array', 'broker'=>'resource'],
'enchant_broker_dict_exists' => ['bool', 'broker'=>'resource', 'tag'=>'string'],
'enchant_broker_free' => ['bool', 'broker'=>'resource'],
'enchant_broker_free_dict' => ['bool', 'dict'=>'resource'],
'enchant_broker_get_dict_path' => ['string', 'broker'=>'resource', 'dict_type'=>'int'],
'enchant_broker_get_error' => ['string|false', 'broker'=>'resource'],
'enchant_broker_init' => ['resource|false'],
'enchant_broker_list_dicts' => ['array', 'broker'=>'resource'],
'enchant_broker_request_dict' => ['resource|false', 'broker'=>'resource', 'tag'=>'string'],
'enchant_broker_request_pwl_dict' => ['resource|false', 'broker'=>'resource', 'filename'=>'string'],
'enchant_broker_set_dict_path' => ['bool', 'broker'=>'resource', 'dict_type'=>'int', 'value'=>'string'],
'enchant_broker_set_ordering' => ['bool', 'broker'=>'resource', 'tag'=>'string', 'ordering'=>'string'],
'enchant_dict_add_to_personal' => ['void', 'dict'=>'resource', 'word'=>'string'],
'enchant_dict_add_to_session' => ['void', 'dict'=>'resource', 'word'=>'string'],
'enchant_dict_check' => ['bool', 'dict'=>'resource', 'word'=>'string'],
'enchant_dict_describe' => ['array', 'dict'=>'resource'],
'enchant_dict_get_error' => ['string', 'dict'=>'resource'],
'enchant_dict_is_in_session' => ['bool', 'dict'=>'resource', 'word'=>'string'],
'enchant_dict_quick_check' => ['bool', 'dict'=>'resource', 'word'=>'string', '&w_suggestions='=>'array<int,string>'],
'enchant_dict_store_replacement' => ['void', 'dict'=>'resource', 'mis'=>'string', 'cor'=>'string'],
'enchant_dict_suggest' => ['array', 'dict'=>'resource', 'word'=>'string'],
'end' => ['mixed|false', '&rw_array_arg'=>'array|object'],
'Error::__clone' => ['void'],
'Error::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Error'],
'Error::__toString' => ['string'],
'Error::getCode' => ['int'],
'Error::getFile' => ['string'],
'Error::getLine' => ['int'],
'Error::getMessage' => ['string'],
'Error::getPrevious' => ['Throwable|Error|null'],
'Error::getTrace' => ['array'],
'Error::getTraceAsString' => ['string'],
'error_clear_last' => ['void'],
'error_get_last' => ['?array{type:int,message:string,file:string,line:int}'],
'error_log' => ['bool', 'message'=>'string', 'message_type='=>'int', 'destination='=>'string', 'extra_headers='=>'string'],
'error_reporting' => ['int', 'new_error_level='=>'int'],
'ErrorException::__clone' => ['void'],
'ErrorException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'severity='=>'int', 'filename='=>'string', 'lineno='=>'int', 'previous='=>'?Throwable|?ErrorException'],
'ErrorException::__toString' => ['string'],
'ErrorException::getCode' => ['int'],
'ErrorException::getFile' => ['string'],
'ErrorException::getLine' => ['int'],
'ErrorException::getMessage' => ['string'],
'ErrorException::getPrevious' => ['Throwable|ErrorException|null'],
'ErrorException::getSeverity' => ['int'],
'ErrorException::getTrace' => ['array'],
'ErrorException::getTraceAsString' => ['string'],
'escapeshellarg' => ['string', 'arg'=>'string'],
'escapeshellcmd' => ['string', 'command'=>'string'],
'Ev::backend' => ['int'],
'Ev::depth' => ['int'],
'Ev::embeddableBackends' => ['int'],
'Ev::feedSignal' => ['void', 'signum'=>'int'],
'Ev::feedSignalEvent' => ['void', 'signum'=>'int'],
'Ev::iteration' => ['int'],
'Ev::now' => ['float'],
'Ev::nowUpdate' => ['void'],
'Ev::recommendedBackends' => ['int'],
'Ev::resume' => ['void'],
'Ev::run' => ['void', 'flags='=>'int'],
'Ev::sleep' => ['void', 'seconds'=>'float'],
'Ev::stop' => ['void', 'how='=>'int'],
'Ev::supportedBackends' => ['int'],
'Ev::suspend' => ['void'],
'Ev::time' => ['float'],
'Ev::verify' => ['void'],
'eval' => ['mixed', 'code_str'=>'string'],
'EvCheck::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvCheck::clear' => ['int'],
'EvCheck::createStopped' => ['EvCheck', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvCheck::feed' => ['void', 'events'=>'int'],
'EvCheck::getLoop' => ['EvLoop'],
'EvCheck::invoke' => ['void', 'events'=>'int'],
'EvCheck::keepAlive' => ['void', 'value'=>'bool'],
'EvCheck::setCallback' => ['void', 'callback'=>'callable'],
'EvCheck::start' => ['void'],
'EvCheck::stop' => ['void'],
'EvChild::__construct' => ['void', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvChild::clear' => ['int'],
'EvChild::createStopped' => ['EvChild', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvChild::feed' => ['void', 'events'=>'int'],
'EvChild::getLoop' => ['EvLoop'],
'EvChild::invoke' => ['void', 'events'=>'int'],
'EvChild::keepAlive' => ['void', 'value'=>'bool'],
'EvChild::set' => ['void', 'pid'=>'int', 'trace'=>'bool'],
'EvChild::setCallback' => ['void', 'callback'=>'callable'],
'EvChild::start' => ['void'],
'EvChild::stop' => ['void'],
'EvEmbed::__construct' => ['void', 'other'=>'object', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvEmbed::clear' => ['int'],
'EvEmbed::createStopped' => ['EvEmbed', 'other'=>'object', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvEmbed::feed' => ['void', 'events'=>'int'],
'EvEmbed::getLoop' => ['EvLoop'],
'EvEmbed::invoke' => ['void', 'events'=>'int'],
'EvEmbed::keepAlive' => ['void', 'value'=>'bool'],
'EvEmbed::set' => ['void', 'other'=>'object'],
'EvEmbed::setCallback' => ['void', 'callback'=>'callable'],
'EvEmbed::start' => ['void'],
'EvEmbed::stop' => ['void'],
'EvEmbed::sweep' => ['void'],
'Event::__construct' => ['void', 'base'=>'EventBase', 'fd'=>'mixed', 'what'=>'int', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::add' => ['bool', 'timeout='=>'float'],
'Event::addSignal' => ['bool', 'timeout='=>'float'],
'Event::addTimer' => ['bool', 'timeout='=>'float'],
'Event::del' => ['bool'],
'Event::delSignal' => ['bool'],
'Event::delTimer' => ['bool'],
'Event::free' => ['void'],
'Event::getSupportedMethods' => ['array'],
'Event::pending' => ['bool', 'flags'=>'int'],
'Event::set' => ['bool', 'base'=>'EventBase', 'fd'=>'mixed', 'what='=>'int', 'cb='=>'callable', 'arg='=>'mixed'],
'Event::setPriority' => ['bool', 'priority'=>'int'],
'Event::setTimer' => ['bool', 'base'=>'EventBase', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::signal' => ['Event', 'base'=>'EventBase', 'signum'=>'int', 'cb'=>'callable', 'arg='=>'mixed'],
'Event::timer' => ['Event', 'base'=>'EventBase', 'cb'=>'callable', 'arg='=>'mixed'],
'event_add' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_base_free' => ['void', 'event_base'=>'resource'],
'event_base_loop' => ['int', 'event_base'=>'resource', 'flags='=>'int'],
'event_base_loopbreak' => ['bool', 'event_base'=>'resource'],
'event_base_loopexit' => ['bool', 'event_base'=>'resource', 'timeout='=>'int'],
'event_base_new' => ['resource|false'],
'event_base_priority_init' => ['bool', 'event_base'=>'resource', 'npriorities'=>'int'],
'event_base_reinit' => ['bool', 'event_base'=>'resource'],
'event_base_set' => ['bool', 'event'=>'resource', 'event_base'=>'resource'],
'event_buffer_base_set' => ['bool', 'bevent'=>'resource', 'event_base'=>'resource'],
'event_buffer_disable' => ['bool', 'bevent'=>'resource', 'events'=>'int'],
'event_buffer_enable' => ['bool', 'bevent'=>'resource', 'events'=>'int'],
'event_buffer_fd_set' => ['void', 'bevent'=>'resource', 'fd'=>'resource'],
'event_buffer_free' => ['void', 'bevent'=>'resource'],
'event_buffer_new' => ['resource|false', 'stream'=>'resource', 'readcb'=>'callable|null', 'writecb'=>'callable|null', 'errorcb'=>'callable', 'arg='=>'mixed'],
'event_buffer_priority_set' => ['bool', 'bevent'=>'resource', 'priority'=>'int'],
'event_buffer_read' => ['string', 'bevent'=>'resource', 'data_size'=>'int'],
'event_buffer_set_callback' => ['bool', 'event'=>'resource', 'readcb'=>'mixed', 'writecb'=>'mixed', 'errorcb'=>'mixed', 'arg='=>'mixed'],
'event_buffer_timeout_set' => ['void', 'bevent'=>'resource', 'read_timeout'=>'int', 'write_timeout'=>'int'],
'event_buffer_watermark_set' => ['void', 'bevent'=>'resource', 'events'=>'int', 'lowmark'=>'int', 'highmark'=>'int'],
'event_buffer_write' => ['bool', 'bevent'=>'resource', 'data'=>'string', 'data_size='=>'int'],
'event_del' => ['bool', 'event'=>'resource'],
'event_free' => ['void', 'event'=>'resource'],
'event_new' => ['resource|false'],
'event_priority_set' => ['bool', 'event'=>'resource', 'priority'=>'int'],
'event_set' => ['bool', 'event'=>'resource', 'fd'=>'int|resource', 'events'=>'int', 'callback'=>'callable', 'arg='=>'mixed'],
'event_timer_add' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_timer_del' => ['bool', 'event'=>'resource'],
'event_timer_new' => ['resource|false'],
'event_timer_pending' => ['bool', 'event'=>'resource', 'timeout='=>'int'],
'event_timer_set' => ['bool', 'event'=>'resource', 'callback'=>'callable', 'arg='=>'mixed'],
'EventBase::__construct' => ['void', 'cfg='=>'EventConfig'],
'EventBase::dispatch' => ['void'],
'EventBase::exit' => ['bool', 'timeout='=>'float'],
'EventBase::free' => ['void'],
'EventBase::getFeatures' => ['int'],
'EventBase::getMethod' => ['string', 'cfg='=>'EventConfig'],
'EventBase::getTimeOfDayCached' => ['float'],
'EventBase::gotExit' => ['bool'],
'EventBase::gotStop' => ['bool'],
'EventBase::loop' => ['bool', 'flags='=>'int'],
'EventBase::priorityInit' => ['bool', 'n_priorities'=>'int'],
'EventBase::reInit' => ['bool'],
'EventBase::stop' => ['bool'],
'EventBuffer::__construct' => ['void'],
'EventBuffer::add' => ['bool', 'data'=>'string'],
'EventBuffer::addBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBuffer::appendFrom' => ['int', 'buf'=>'EventBuffer', 'len'=>'int'],
'EventBuffer::copyout' => ['int', '&w_data'=>'string', 'max_bytes'=>'int'],
'EventBuffer::drain' => ['bool', 'len'=>'int'],
'EventBuffer::enableLocking' => ['void'],
'EventBuffer::expand' => ['bool', 'len'=>'int'],
'EventBuffer::freeze' => ['bool', 'at_front'=>'bool'],
'EventBuffer::lock' => ['void'],
'EventBuffer::prepend' => ['bool', 'data'=>'string'],
'EventBuffer::prependBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBuffer::pullup' => ['string', 'size'=>'int'],
'EventBuffer::read' => ['string', 'max_bytes'=>'int'],
'EventBuffer::readFrom' => ['int', 'fd'=>'mixed', 'howmuch'=>'int'],
'EventBuffer::readLine' => ['string', 'eol_style'=>'int'],
'EventBuffer::search' => ['mixed', 'what'=>'string', 'start='=>'int', 'end='=>'int'],
'EventBuffer::searchEol' => ['mixed', 'start='=>'int', 'eol_style='=>'int'],
'EventBuffer::substr' => ['string', 'start'=>'int', 'length='=>'int'],
'EventBuffer::unfreeze' => ['bool', 'at_front'=>'bool'],
'EventBuffer::unlock' => ['bool'],
'EventBuffer::write' => ['int', 'fd'=>'mixed', 'howmuch='=>'int'],
'EventBufferEvent::__construct' => ['void', 'base'=>'EventBase', 'socket='=>'mixed', 'options='=>'int', 'readcb='=>'callable', 'writecb='=>'callable', 'eventcb='=>'callable'],
'EventBufferEvent::close' => ['void'],
'EventBufferEvent::connect' => ['bool', 'addr'=>'string'],
'EventBufferEvent::connectHost' => ['bool', 'dns_base'=>'EventDnsBase', 'hostname'=>'string', 'port'=>'int', 'family='=>'int'],
'EventBufferEvent::createPair' => ['array', 'base'=>'EventBase', 'options='=>'int'],
'EventBufferEvent::disable' => ['bool', 'events'=>'int'],
'EventBufferEvent::enable' => ['bool', 'events'=>'int'],
'EventBufferEvent::free' => ['void'],
'EventBufferEvent::getDnsErrorString' => ['string'],
'EventBufferEvent::getEnabled' => ['int'],
'EventBufferEvent::getInput' => ['EventBuffer'],
'EventBufferEvent::getOutput' => ['EventBuffer'],
'EventBufferEvent::read' => ['string', 'size'=>'int'],
'EventBufferEvent::readBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventBufferEvent::setCallbacks' => ['void', 'readcb'=>'callable', 'writecb'=>'callable', 'eventcb'=>'callable', 'arg='=>'string'],
'EventBufferEvent::setPriority' => ['bool', 'priority'=>'int'],
'EventBufferEvent::setTimeouts' => ['bool', 'timeout_read'=>'float', 'timeout_write'=>'float'],
'EventBufferEvent::setWatermark' => ['void', 'events'=>'int', 'lowmark'=>'int', 'highmark'=>'int'],
'EventBufferEvent::sslError' => ['string'],
'EventBufferEvent::sslFilter' => ['EventBufferEvent', 'base'=>'EventBase', 'underlying'=>'EventBufferEvent', 'ctx'=>'EventSslContext', 'state'=>'int', 'options='=>'int'],
'EventBufferEvent::sslGetCipherInfo' => ['string'],
'EventBufferEvent::sslGetCipherName' => ['string'],
'EventBufferEvent::sslGetCipherVersion' => ['string'],
'EventBufferEvent::sslGetProtocol' => ['string'],
'EventBufferEvent::sslRenegotiate' => ['void'],
'EventBufferEvent::sslSocket' => ['EventBufferEvent', 'base'=>'EventBase', 'socket'=>'mixed', 'ctx'=>'EventSslContext', 'state'=>'int', 'options='=>'int'],
'EventBufferEvent::write' => ['bool', 'data'=>'string'],
'EventBufferEvent::writeBuffer' => ['bool', 'buf'=>'EventBuffer'],
'EventConfig::__construct' => ['void'],
'EventConfig::avoidMethod' => ['bool', 'method'=>'string'],
'EventConfig::requireFeatures' => ['bool', 'feature'=>'int'],
'EventConfig::setMaxDispatchInterval' => ['void', 'max_interval'=>'int', 'max_callbacks'=>'int', 'min_priority'=>'int'],
'EventDnsBase::__construct' => ['void', 'base'=>'EventBase', 'initialize'=>'bool'],
'EventDnsBase::addNameserverIp' => ['bool', 'ip'=>'string'],
'EventDnsBase::addSearch' => ['void', 'domain'=>'string'],
'EventDnsBase::clearSearch' => ['void'],
'EventDnsBase::countNameservers' => ['int'],
'EventDnsBase::loadHosts' => ['bool', 'hosts'=>'string'],
'EventDnsBase::parseResolvConf' => ['bool', 'flags'=>'int', 'filename'=>'string'],
'EventDnsBase::setOption' => ['bool', 'option'=>'string', 'value'=>'string'],
'EventDnsBase::setSearchNdots' => ['bool', 'ndots'=>'int'],
'EventHttp::__construct' => ['void', 'base'=>'EventBase', 'ctx='=>'EventSslContext'],
'EventHttp::accept' => ['bool', 'socket'=>'mixed'],
'EventHttp::addServerAlias' => ['bool', 'alias'=>'string'],
'EventHttp::bind' => ['void', 'address'=>'string', 'port'=>'int'],
'EventHttp::removeServerAlias' => ['bool', 'alias'=>'string'],
'EventHttp::setAllowedMethods' => ['void', 'methods'=>'int'],
'EventHttp::setCallback' => ['void', 'path'=>'string', 'cb'=>'string', 'arg='=>'string'],
'EventHttp::setDefaultCallback' => ['void', 'cb'=>'string', 'arg='=>'string'],
'EventHttp::setMaxBodySize' => ['void', 'value'=>'int'],
'EventHttp::setMaxHeadersSize' => ['void', 'value'=>'int'],
'EventHttp::setTimeout' => ['void', 'value'=>'int'],
'EventHttpConnection::__construct' => ['void', 'base'=>'EventBase', 'dns_base'=>'EventDnsBase', 'address'=>'string', 'port'=>'int', 'ctx='=>'EventSslContext'],
'EventHttpConnection::getBase' => ['EventBase'],
'EventHttpConnection::getPeer' => ['void', '&w_address'=>'string', '&w_port'=>'int'],
'EventHttpConnection::makeRequest' => ['bool', 'req'=>'EventHttpRequest', 'type'=>'int', 'uri'=>'string'],
'EventHttpConnection::setCloseCallback' => ['void', 'callback'=>'callable', 'data='=>'mixed'],
'EventHttpConnection::setLocalAddress' => ['void', 'address'=>'string'],
'EventHttpConnection::setLocalPort' => ['void', 'port'=>'int'],
'EventHttpConnection::setMaxBodySize' => ['void', 'max_size'=>'string'],
'EventHttpConnection::setMaxHeadersSize' => ['void', 'max_size'=>'string'],
'EventHttpConnection::setRetries' => ['void', 'retries'=>'int'],
'EventHttpConnection::setTimeout' => ['void', 'timeout'=>'int'],
'EventHttpRequest::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed'],
'EventHttpRequest::addHeader' => ['bool', 'key'=>'string', 'value'=>'string', 'type'=>'int'],
'EventHttpRequest::cancel' => ['void'],
'EventHttpRequest::clearHeaders' => ['void'],
'EventHttpRequest::closeConnection' => ['void'],
'EventHttpRequest::findHeader' => ['void', 'key'=>'string', 'type'=>'string'],
'EventHttpRequest::free' => ['void'],
'EventHttpRequest::getBufferEvent' => ['EventBufferEvent'],
'EventHttpRequest::getCommand' => ['void'],
'EventHttpRequest::getConnection' => ['EventHttpConnection'],
'EventHttpRequest::getHost' => ['string'],
'EventHttpRequest::getInputBuffer' => ['EventBuffer'],
'EventHttpRequest::getInputHeaders' => ['array'],
'EventHttpRequest::getOutputBuffer' => ['EventBuffer'],
'EventHttpRequest::getOutputHeaders' => ['void'],
'EventHttpRequest::getResponseCode' => ['int'],
'EventHttpRequest::getUri' => ['string'],
'EventHttpRequest::removeHeader' => ['void', 'key'=>'string', 'type'=>'string'],
'EventHttpRequest::sendError' => ['void', 'error'=>'int', 'reason='=>'string'],
'EventHttpRequest::sendReply' => ['void', 'code'=>'int', 'reason'=>'string', 'buf='=>'EventBuffer'],
'EventHttpRequest::sendReplyChunk' => ['void', 'buf'=>'EventBuffer'],
'EventHttpRequest::sendReplyEnd' => ['void'],
'EventHttpRequest::sendReplyStart' => ['void', 'code'=>'int', 'reason'=>'string'],
'EventListener::__construct' => ['void', 'base'=>'EventBase', 'cb'=>'callable', 'data'=>'mixed', 'flags'=>'int', 'backlog'=>'int', 'target'=>'mixed'],
'EventListener::disable' => ['bool'],
'EventListener::enable' => ['bool'],
'EventListener::getBase' => ['void'],
'EventListener::getSocketName' => ['bool', '&w_address'=>'string', '&w_port='=>'mixed'],
'EventListener::setCallback' => ['void', 'cb'=>'callable', 'arg='=>'mixed'],
'EventListener::setErrorCallback' => ['void', 'cb'=>'string'],
'EventSslContext::__construct' => ['void', 'method'=>'string', 'options'=>'string'],
'EventUtil::__construct' => ['void'],
'EventUtil::getLastSocketErrno' => ['int', 'socket='=>'mixed'],
'EventUtil::getLastSocketError' => ['string', 'socket='=>'mixed'],
'EventUtil::getSocketFd' => ['int', 'socket'=>'mixed'],
'EventUtil::getSocketName' => ['bool', 'socket'=>'mixed', '&w_address'=>'string', '&w_port='=>'mixed'],
'EventUtil::setSocketOption' => ['bool', 'socket'=>'mixed', 'level'=>'int', 'optname'=>'int', 'optval'=>'mixed'],
'EventUtil::sslRandPoll' => ['void'],
'EvFork::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvFork::clear' => ['int'],
'EvFork::createStopped' => ['EvFork', 'callback'=>'callable', 'data='=>'string', 'priority='=>'string'],
'EvFork::feed' => ['void', 'events'=>'int'],
'EvFork::getLoop' => ['EvLoop'],
'EvFork::invoke' => ['void', 'events'=>'int'],
'EvFork::keepAlive' => ['void', 'value'=>'bool'],
'EvFork::setCallback' => ['void', 'callback'=>'callable'],
'EvFork::start' => ['void'],
'EvFork::stop' => ['void'],
'EvIdle::__construct' => ['void', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIdle::clear' => ['int'],
'EvIdle::createStopped' => ['EvIdle', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIdle::feed' => ['void', 'events'=>'int'],
'EvIdle::getLoop' => ['EvLoop'],
'EvIdle::invoke' => ['void', 'events'=>'int'],
'EvIdle::keepAlive' => ['void', 'value'=>'bool'],
'EvIdle::setCallback' => ['void', 'callback'=>'callable'],
'EvIdle::start' => ['void'],
'EvIdle::stop' => ['void'],
'EvIo::__construct' => ['void', 'fd'=>'mixed', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIo::clear' => ['int'],
'EvIo::createStopped' => ['EvIo', 'fd'=>'resource', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvIo::feed' => ['void', 'events'=>'int'],
'EvIo::getLoop' => ['EvLoop'],
'EvIo::invoke' => ['void', 'events'=>'int'],
'EvIo::keepAlive' => ['void', 'value'=>'bool'],
'EvIo::set' => ['void', 'fd'=>'resource', 'events'=>'int'],
'EvIo::setCallback' => ['void', 'callback'=>'callable'],
'EvIo::start' => ['void'],
'EvIo::stop' => ['void'],
'EvLoop::__construct' => ['void', 'flags='=>'int', 'data='=>'mixed', 'io_interval='=>'float', 'timeout_interval='=>'float'],
'EvLoop::backend' => ['int'],
'EvLoop::check' => ['EvCheck', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::child' => ['EvChild', 'pid'=>'int', 'trace'=>'bool', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::defaultLoop' => ['EvLoop', 'flags='=>'int', 'data='=>'mixed', 'io_interval='=>'float', 'timeout_interval='=>'float'],
'EvLoop::embed' => ['EvEmbed', 'other'=>'EvLoop', 'callback='=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::fork' => ['EvFork', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::idle' => ['EvIdle', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::invokePending' => ['void'],
'EvLoop::io' => ['EvIo', 'fd'=>'resource', 'events'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::loopFork' => ['void'],
'EvLoop::now' => ['float'],
'EvLoop::nowUpdate' => ['void'],
'EvLoop::periodic' => ['EvPeriodic', 'offset'=>'float', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::prepare' => ['EvPrepare', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::resume' => ['void'],
'EvLoop::run' => ['void', 'flags='=>'int'],
'EvLoop::signal' => ['EvSignal', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::stat' => ['EvStat', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::stop' => ['void', 'how='=>'int'],
'EvLoop::suspend' => ['void'],
'EvLoop::timer' => ['EvTimer', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvLoop::verify' => ['void'],
'EvPeriodic::__construct' => ['void', 'offset'=>'float', 'interval'=>'string', 'reschedule_cb'=>'callable', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPeriodic::again' => ['void'],
'EvPeriodic::at' => ['float'],
'EvPeriodic::clear' => ['int'],
'EvPeriodic::createStopped' => ['EvPeriodic', 'offset'=>'float', 'interval'=>'float', 'reschedule_cb'=>'callable', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPeriodic::feed' => ['void', 'events'=>'int'],
'EvPeriodic::getLoop' => ['EvLoop'],
'EvPeriodic::invoke' => ['void', 'events'=>'int'],
'EvPeriodic::keepAlive' => ['void', 'value'=>'bool'],
'EvPeriodic::set' => ['void', 'offset'=>'float', 'interval'=>'float'],
'EvPeriodic::setCallback' => ['void', 'callback'=>'callable'],
'EvPeriodic::start' => ['void'],
'EvPeriodic::stop' => ['void'],
'EvPrepare::__construct' => ['void', 'callback'=>'string', 'data='=>'string', 'priority='=>'string'],
'EvPrepare::clear' => ['int'],
'EvPrepare::createStopped' => ['EvPrepare', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvPrepare::feed' => ['void', 'events'=>'int'],
'EvPrepare::getLoop' => ['EvLoop'],
'EvPrepare::invoke' => ['void', 'events'=>'int'],
'EvPrepare::keepAlive' => ['void', 'value'=>'bool'],
'EvPrepare::setCallback' => ['void', 'callback'=>'callable'],
'EvPrepare::start' => ['void'],
'EvPrepare::stop' => ['void'],
'EvSignal::__construct' => ['void', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvSignal::clear' => ['int'],
'EvSignal::createStopped' => ['EvSignal', 'signum'=>'int', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvSignal::feed' => ['void', 'events'=>'int'],
'EvSignal::getLoop' => ['EvLoop'],
'EvSignal::invoke' => ['void', 'events'=>'int'],
'EvSignal::keepAlive' => ['void', 'value'=>'bool'],
'EvSignal::set' => ['void', 'signum'=>'int'],
'EvSignal::setCallback' => ['void', 'callback'=>'callable'],
'EvSignal::start' => ['void'],
'EvSignal::stop' => ['void'],
'EvStat::__construct' => ['void', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvStat::attr' => ['array'],
'EvStat::clear' => ['int'],
'EvStat::createStopped' => ['EvStat', 'path'=>'string', 'interval'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvStat::feed' => ['void', 'events'=>'int'],
'EvStat::getLoop' => ['EvLoop'],
'EvStat::invoke' => ['void', 'events'=>'int'],
'EvStat::keepAlive' => ['void', 'value'=>'bool'],
'EvStat::prev' => ['array'],
'EvStat::set' => ['void', 'path'=>'string', 'interval'=>'float'],
'EvStat::setCallback' => ['void', 'callback'=>'callable'],
'EvStat::start' => ['void'],
'EvStat::stat' => ['bool'],
'EvStat::stop' => ['void'],
'EvTimer::__construct' => ['void', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvTimer::again' => ['void'],
'EvTimer::clear' => ['int'],
'EvTimer::createStopped' => ['EvTimer', 'after'=>'float', 'repeat'=>'float', 'callback'=>'callable', 'data='=>'mixed', 'priority='=>'int'],
'EvTimer::feed' => ['void', 'events'=>'int'],
'EvTimer::getLoop' => ['EvLoop'],
'EvTimer::invoke' => ['void', 'events'=>'int'],
'EvTimer::keepAlive' => ['void', 'value'=>'bool'],
'EvTimer::set' => ['void', 'after'=>'float', 'repeat'=>'float'],
'EvTimer::setCallback' => ['void', 'callback'=>'callable'],
'EvTimer::start' => ['void'],
'EvTimer::stop' => ['void'],
'EvWatcher::__construct' => ['void'],
'EvWatcher::clear' => ['int'],
'EvWatcher::feed' => ['void', 'revents'=>'int'],
'EvWatcher::getLoop' => ['EvLoop'],
'EvWatcher::invoke' => ['void', 'revents'=>'int'],
'EvWatcher::keepalive' => ['bool', 'value='=>'bool'],
'EvWatcher::setCallback' => ['void', 'callback'=>'callable'],
'EvWatcher::start' => ['void'],
'EvWatcher::stop' => ['void'],
'Exception::__clone' => ['void'],
'Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?Exception'],
'Exception::__toString' => ['string'],
'Exception::getCode' => ['int|string'],
'Exception::getFile' => ['string'],
'Exception::getLine' => ['int'],
'Exception::getMessage' => ['string'],
'Exception::getPrevious' => ['?Throwable|?Exception'],
'Exception::getTrace' => ['array'],
'Exception::getTraceAsString' => ['string'],
'exec' => ['string', 'command'=>'string', '&w_output='=>'array', '&w_return_value='=>'int'],
'exif_imagetype' => ['int|false', 'imagefile'=>'string'],
'exif_read_data' => ['array|false', 'filename'=>'string|resource', 'sections_needed='=>'string', 'sub_arrays='=>'bool', 'read_thumbnail='=>'bool'],
'exif_tagname' => ['string|false', 'index'=>'int'],
'exif_thumbnail' => ['string|false', 'filename'=>'string', '&w_width='=>'int', '&w_height='=>'int', '&w_imagetype='=>'int'],
'exit' => ['', 'status'=>'string|int'],
'exp' => ['float', 'number'=>'float'],
'expect_expectl' => ['int', 'expect'=>'resource', 'cases'=>'array', 'match='=>'array'],
'expect_popen' => ['resource', 'command'=>'string'],
'explode' => ['array<int,string>|false', 'separator'=>'string', 'str'=>'string', 'limit='=>'int'],
'expm1' => ['float', 'number'=>'float'],
'extension_loaded' => ['bool', 'extension_name'=>'string'],
'extract' => ['int', '&rw_var_array'=>'array', 'extract_type='=>'int', 'prefix='=>'?string'],
'ezmlm_hash' => ['int', 'addr'=>'string'],
'fam_cancel_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fam_close' => ['void', 'fam'=>'resource'],
'fam_monitor_collection' => ['resource', 'fam'=>'resource', 'dirname'=>'string', 'depth'=>'int', 'mask'=>'string'],
'fam_monitor_directory' => ['resource', 'fam'=>'resource', 'dirname'=>'string'],
'fam_monitor_file' => ['resource', 'fam'=>'resource', 'filename'=>'string'],
'fam_next_event' => ['array', 'fam'=>'resource'],
'fam_open' => ['resource', 'appname='=>'string'],
'fam_pending' => ['int', 'fam'=>'resource'],
'fam_resume_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fam_suspend_monitor' => ['bool', 'fam'=>'resource', 'fam_monitor'=>'resource'],
'fann_cascadetrain_on_data' => ['bool', 'ann'=>'resource', 'data'=>'resource', 'max_neurons'=>'int', 'neurons_between_reports'=>'int', 'desired_error'=>'float'],
'fann_cascadetrain_on_file' => ['bool', 'ann'=>'resource', 'filename'=>'string', 'max_neurons'=>'int', 'neurons_between_reports'=>'int', 'desired_error'=>'float'],
'fann_clear_scaling_params' => ['bool', 'ann'=>'resource'],
'fann_copy' => ['resource|false', 'ann'=>'resource'],
'fann_create_from_file' => ['resource', 'configuration_file'=>'string'],
'fann_create_shortcut' => ['resource|false', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_shortcut_array' => ['resource|false', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_sparse' => ['resource|false', 'connection_rate'=>'float', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_sparse_array' => ['resource|false', 'connection_rate'=>'float', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_standard' => ['resource|false', 'num_layers'=>'int', 'num_neurons1'=>'int', 'num_neurons2'=>'int', '...args='=>'int'],
'fann_create_standard_array' => ['resource|false', 'num_layers'=>'int', 'layers'=>'array'],
'fann_create_train' => ['resource', 'num_data'=>'int', 'num_input'=>'int', 'num_output'=>'int'],
'fann_create_train_from_callback' => ['resource', 'num_data'=>'int', 'num_input'=>'int', 'num_output'=>'int', 'user_function'=>'callable'],
'fann_descale_input' => ['bool', 'ann'=>'resource', 'input_vector'=>'array'],
'fann_descale_output' => ['bool', 'ann'=>'resource', 'output_vector'=>'array'],
'fann_descale_train' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_destroy' => ['bool', 'ann'=>'resource'],
'fann_destroy_train' => ['bool', 'train_data'=>'resource'],
'fann_duplicate_train_data' => ['resource', 'data'=>'resource'],
'fann_get_activation_function' => ['int|false', 'ann'=>'resource', 'layer'=>'int', 'neuron'=>'int'],
'fann_get_activation_steepness' => ['float|false', 'ann'=>'resource', 'layer'=>'int', 'neuron'=>'int'],
'fann_get_bias_array' => ['array', 'ann'=>'resource'],
'fann_get_bit_fail' => ['int|false', 'ann'=>'resource'],
'fann_get_bit_fail_limit' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_activation_functions' => ['array|false', 'ann'=>'resource'],
'fann_get_cascade_activation_functions_count' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_activation_steepnesses' => ['array|false', 'ann'=>'resource'],
'fann_get_cascade_activation_steepnesses_count' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_change_fraction' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_limit' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_candidate_stagnation_epochs' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_max_cand_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_max_out_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_min_cand_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_min_out_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_num_candidate_groups' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_num_candidates' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_output_change_fraction' => ['float|false', 'ann'=>'resource'],
'fann_get_cascade_output_stagnation_epochs' => ['int|false', 'ann'=>'resource'],
'fann_get_cascade_weight_multiplier' => ['float|false', 'ann'=>'resource'],
'fann_get_connection_array' => ['array', 'ann'=>'resource'],
'fann_get_connection_rate' => ['float|false', 'ann'=>'resource'],
'fann_get_errno' => ['int|false', 'errdat'=>'resource'],
'fann_get_errstr' => ['string|false', 'errdat'=>'resource'],
'fann_get_layer_array' => ['array', 'ann'=>'resource'],
'fann_get_learning_momentum' => ['float|false', 'ann'=>'resource'],
'fann_get_learning_rate' => ['float|false', 'ann'=>'resource'],
'fann_get_MSE' => ['float|false', 'ann'=>'resource'],
'fann_get_network_type' => ['int|false', 'ann'=>'resource'],
'fann_get_num_input' => ['int|false', 'ann'=>'resource'],
'fann_get_num_layers' => ['int|false', 'ann'=>'resource'],
'fann_get_num_output' => ['int|false', 'ann'=>'resource'],
'fann_get_quickprop_decay' => ['float|false', 'ann'=>'resource'],
'fann_get_quickprop_mu' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_decrease_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_max' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_min' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_delta_zero' => ['float|false', 'ann'=>'resource'],
'fann_get_rprop_increase_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_step_error_shift' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_step_error_threshold_factor' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_temperature' => ['float|false', 'ann'=>'resource'],
'fann_get_sarprop_weight_decay_shift' => ['float|false', 'ann'=>'resource'],
'fann_get_total_connections' => ['int|false', 'ann'=>'resource'],
'fann_get_total_neurons' => ['int|false', 'ann'=>'resource'],
'fann_get_train_error_function' => ['int|false', 'ann'=>'resource'],
'fann_get_train_stop_function' => ['int|false', 'ann'=>'resource'],
'fann_get_training_algorithm' => ['int|false', 'ann'=>'resource'],
'fann_init_weights' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_length_train_data' => ['int|false', 'data'=>'resource'],
'fann_merge_train_data' => ['resource|false', 'data1'=>'resource', 'data2'=>'resource'],
'fann_num_input_train_data' => ['int|false', 'data'=>'resource'],
'fann_num_output_train_data' => ['int|false', 'data'=>'resource'],
'fann_print_error' => ['void', 'errdat'=>'string'],
'fann_randomize_weights' => ['bool', 'ann'=>'resource', 'min_weight'=>'float', 'max_weight'=>'float'],
'fann_read_train_from_file' => ['resource', 'filename'=>'string'],
'fann_reset_errno' => ['void', 'errdat'=>'resource'],
'fann_reset_errstr' => ['void', 'errdat'=>'resource'],
'fann_reset_MSE' => ['bool', 'ann'=>'string'],
'fann_run' => ['array|false', 'ann'=>'resource', 'input'=>'array'],
'fann_save' => ['bool', 'ann'=>'resource', 'configuration_file'=>'string'],
'fann_save_train' => ['bool', 'data'=>'resource', 'file_name'=>'string'],
'fann_scale_input' => ['bool', 'ann'=>'resource', 'input_vector'=>'array'],
'fann_scale_input_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_scale_output' => ['bool', 'ann'=>'resource', 'output_vector'=>'array'],
'fann_scale_output_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_scale_train' => ['bool', 'ann'=>'resource', 'train_data'=>'resource'],
'fann_scale_train_data' => ['bool', 'train_data'=>'resource', 'new_min'=>'float', 'new_max'=>'float'],
'fann_set_activation_function' => ['bool', 'ann'=>'resource', 'activation_function'=>'int', 'layer'=>'int', 'neuron'=>'int'],
'fann_set_activation_function_hidden' => ['bool', 'ann'=>'resource', 'activation_function'=>'int'],
'fann_set_activation_function_layer' => ['bool', 'ann'=>'resource', 'activation_function'=>'int', 'layer'=>'int'],
'fann_set_activation_function_output' => ['bool', 'ann'=>'resource', 'activation_function'=>'int'],
'fann_set_activation_steepness' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float', 'layer'=>'int', 'neuron'=>'int'],
'fann_set_activation_steepness_hidden' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float'],
'fann_set_activation_steepness_layer' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float', 'layer'=>'int'],
'fann_set_activation_steepness_output' => ['bool', 'ann'=>'resource', 'activation_steepness'=>'float'],
'fann_set_bit_fail_limit' => ['bool', 'ann'=>'resource', 'bit_fail_limit'=>'float'],
'fann_set_callback' => ['bool', 'ann'=>'resource', 'callback'=>'callable'],
'fann_set_cascade_activation_functions' => ['bool', 'ann'=>'resource', 'cascade_activation_functions'=>'array'],
'fann_set_cascade_activation_steepnesses' => ['bool', 'ann'=>'resource', 'cascade_activation_steepnesses_count'=>'array'],
'fann_set_cascade_candidate_change_fraction' => ['bool', 'ann'=>'resource', 'cascade_candidate_change_fraction'=>'float'],
'fann_set_cascade_candidate_limit' => ['bool', 'ann'=>'resource', 'cascade_candidate_limit'=>'float'],
'fann_set_cascade_candidate_stagnation_epochs' => ['bool', 'ann'=>'resource', 'cascade_candidate_stagnation_epochs'=>'int'],
'fann_set_cascade_max_cand_epochs' => ['bool', 'ann'=>'resource', 'cascade_max_cand_epochs'=>'int'],
'fann_set_cascade_max_out_epochs' => ['bool', 'ann'=>'resource', 'cascade_max_out_epochs'=>'int'],
'fann_set_cascade_min_cand_epochs' => ['bool', 'ann'=>'resource', 'cascade_min_cand_epochs'=>'int'],
'fann_set_cascade_min_out_epochs' => ['bool', 'ann'=>'resource', 'cascade_min_out_epochs'=>'int'],
'fann_set_cascade_num_candidate_groups' => ['bool', 'ann'=>'resource', 'cascade_num_candidate_groups'=>'int'],
'fann_set_cascade_output_change_fraction' => ['bool', 'ann'=>'resource', 'cascade_output_change_fraction'=>'float'],
'fann_set_cascade_output_stagnation_epochs' => ['bool', 'ann'=>'resource', 'cascade_output_stagnation_epochs'=>'int'],
'fann_set_cascade_weight_multiplier' => ['bool', 'ann'=>'resource', 'cascade_weight_multiplier'=>'float'],
'fann_set_error_log' => ['void', 'errdat'=>'resource', 'log_file'=>'string'],
'fann_set_input_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_input_min'=>'float', 'new_input_max'=>'float'],
'fann_set_learning_momentum' => ['bool', 'ann'=>'resource', 'learning_momentum'=>'float'],
'fann_set_learning_rate' => ['bool', 'ann'=>'resource', 'learning_rate'=>'float'],
'fann_set_output_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_output_min'=>'float', 'new_output_max'=>'float'],
'fann_set_quickprop_decay' => ['bool', 'ann'=>'resource', 'quickprop_decay'=>'float'],
'fann_set_quickprop_mu' => ['bool', 'ann'=>'resource', 'quickprop_mu'=>'float'],
'fann_set_rprop_decrease_factor' => ['bool', 'ann'=>'resource', 'rprop_decrease_factor'=>'float'],
'fann_set_rprop_delta_max' => ['bool', 'ann'=>'resource', 'rprop_delta_max'=>'float'],
'fann_set_rprop_delta_min' => ['bool', 'ann'=>'resource', 'rprop_delta_min'=>'float'],
'fann_set_rprop_delta_zero' => ['bool', 'ann'=>'resource', 'rprop_delta_zero'=>'float'],
'fann_set_rprop_increase_factor' => ['bool', 'ann'=>'resource', 'rprop_increase_factor'=>'float'],
'fann_set_sarprop_step_error_shift' => ['bool', 'ann'=>'resource', 'sarprop_step_error_shift'=>'float'],
'fann_set_sarprop_step_error_threshold_factor' => ['bool', 'ann'=>'resource', 'sarprop_step_error_threshold_factor'=>'float'],
'fann_set_sarprop_temperature' => ['bool', 'ann'=>'resource', 'sarprop_temperature'=>'float'],
'fann_set_sarprop_weight_decay_shift' => ['bool', 'ann'=>'resource', 'sarprop_weight_decay_shift'=>'float'],
'fann_set_scaling_params' => ['bool', 'ann'=>'resource', 'train_data'=>'resource', 'new_input_min'=>'float', 'new_input_max'=>'float', 'new_output_min'=>'float', 'new_output_max'=>'float'],
'fann_set_train_error_function' => ['bool', 'ann'=>'resource', 'error_function'=>'int'],
'fann_set_train_stop_function' => ['bool', 'ann'=>'resource', 'stop_function'=>'int'],
'fann_set_training_algorithm' => ['bool', 'ann'=>'resource', 'training_algorithm'=>'int'],
'fann_set_weight' => ['bool', 'ann'=>'resource', 'from_neuron'=>'int', 'to_neuron'=>'int', 'weight'=>'float'],
'fann_set_weight_array' => ['bool', 'ann'=>'resource', 'connections'=>'array'],
'fann_shuffle_train_data' => ['bool', 'train_data'=>'resource'],
'fann_subset_train_data' => ['resource', 'data'=>'resource', 'pos'=>'int', 'length'=>'int'],
'fann_test' => ['bool', 'ann'=>'resource', 'input'=>'array', 'desired_output'=>'array'],
'fann_test_data' => ['float|false', 'ann'=>'resource', 'data'=>'resource'],
'fann_train' => ['bool', 'ann'=>'resource', 'input'=>'array', 'desired_output'=>'array'],
'fann_train_epoch' => ['float|false', 'ann'=>'resource', 'data'=>'resource'],
'fann_train_on_data' => ['bool', 'ann'=>'resource', 'data'=>'resource', 'max_epochs'=>'int', 'epochs_between_reports'=>'int', 'desired_error'=>'float'],
'fann_train_on_file' => ['bool', 'ann'=>'resource', 'filename'=>'string', 'max_epochs'=>'int', 'epochs_between_reports'=>'int', 'desired_error'=>'float'],
'FANNConnection::__construct' => ['void', 'from_neuron'=>'int', 'to_neuron'=>'int', 'weight'=>'float'],
'FANNConnection::getFromNeuron' => ['int'],
'FANNConnection::getToNeuron' => ['int'],
'FANNConnection::getWeight' => ['void'],
'FANNConnection::setWeight' => ['bool', 'weight'=>'float'],
'fastcgi_finish_request' => ['bool'],
'fbsql_affected_rows' => ['int', 'link_identifier='=>'?resource'],
'fbsql_autocommit' => ['bool', 'link_identifier'=>'resource', 'onoff='=>'bool'],
'fbsql_blob_size' => ['int', 'blob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_change_user' => ['bool', 'user'=>'string', 'password'=>'string', 'database='=>'string', 'link_identifier='=>'?resource'],
'fbsql_clob_size' => ['int', 'clob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_close' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_commit' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_connect' => ['resource', 'hostname='=>'string', 'username='=>'string', 'password='=>'string'],
'fbsql_create_blob' => ['string', 'blob_data'=>'string', 'link_identifier='=>'?resource'],
'fbsql_create_clob' => ['string', 'clob_data'=>'string', 'link_identifier='=>'?resource'],
'fbsql_create_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource', 'database_options='=>'string'],
'fbsql_data_seek' => ['bool', 'result'=>'resource', 'row_number'=>'int'],
'fbsql_database' => ['string', 'link_identifier'=>'resource', 'database='=>'string'],
'fbsql_database_password' => ['string', 'link_identifier'=>'resource', 'database_password='=>'string'],
'fbsql_db_query' => ['resource', 'database'=>'string', 'query'=>'string', 'link_identifier='=>'?resource'],
'fbsql_db_status' => ['int', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_drop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_errno' => ['int', 'link_identifier='=>'?resource'],
'fbsql_error' => ['string', 'link_identifier='=>'?resource'],
'fbsql_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'fbsql_fetch_assoc' => ['array', 'result'=>'resource'],
'fbsql_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_fetch_lengths' => ['array', 'result'=>'resource'],
'fbsql_fetch_object' => ['object', 'result'=>'resource'],
'fbsql_fetch_row' => ['array', 'result'=>'resource'],
'fbsql_field_flags' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_len' => ['int', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_name' => ['string', 'result'=>'resource', 'field_index='=>'int'],
'fbsql_field_seek' => ['bool', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_table' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_field_type' => ['string', 'result'=>'resource', 'field_offset='=>'int'],
'fbsql_free_result' => ['bool', 'result'=>'resource'],
'fbsql_get_autostart_info' => ['array', 'link_identifier='=>'?resource'],
'fbsql_hostname' => ['string', 'link_identifier'=>'resource', 'host_name='=>'string'],
'fbsql_insert_id' => ['int', 'link_identifier='=>'?resource'],
'fbsql_list_dbs' => ['resource', 'link_identifier='=>'?resource'],
'fbsql_list_fields' => ['resource', 'database_name'=>'string', 'table_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_list_tables' => ['resource', 'database'=>'string', 'link_identifier='=>'?resource'],
'fbsql_next_result' => ['bool', 'result'=>'resource'],
'fbsql_num_fields' => ['int', 'result'=>'resource'],
'fbsql_num_rows' => ['int', 'result'=>'resource'],
'fbsql_password' => ['string', 'link_identifier'=>'resource', 'password='=>'string'],
'fbsql_pconnect' => ['resource', 'hostname='=>'string', 'username='=>'string', 'password='=>'string'],
'fbsql_query' => ['resource', 'query'=>'string', 'link_identifier='=>'?resource', 'batch_size='=>'int'],
'fbsql_read_blob' => ['string', 'blob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_read_clob' => ['string', 'clob_handle'=>'string', 'link_identifier='=>'?resource'],
'fbsql_result' => ['mixed', 'result'=>'resource', 'row='=>'int', 'field='=>'mixed'],
'fbsql_rollback' => ['bool', 'link_identifier='=>'?resource'],
'fbsql_rows_fetched' => ['int', 'result'=>'resource'],
'fbsql_select_db' => ['bool', 'database_name='=>'string', 'link_identifier='=>'?resource'],
'fbsql_set_characterset' => ['void', 'link_identifier'=>'resource', 'characterset'=>'int', 'in_out_both='=>'int'],
'fbsql_set_lob_mode' => ['bool', 'result'=>'resource', 'lob_mode'=>'int'],
'fbsql_set_password' => ['bool', 'link_identifier'=>'resource', 'user'=>'string', 'password'=>'string', 'old_password'=>'string'],
'fbsql_set_transaction' => ['void', 'link_identifier'=>'resource', 'locking'=>'int', 'isolation'=>'int'],
'fbsql_start_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource', 'database_options='=>'string'],
'fbsql_stop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'fbsql_table_name' => ['string', 'result'=>'resource', 'index'=>'int'],
'fbsql_username' => ['string', 'link_identifier'=>'resource', 'username='=>'string'],
'fbsql_warnings' => ['bool', 'onoff='=>'bool'],
'fclose' => ['bool', 'fp'=>'resource'],
'fdf_add_doc_javascript' => ['bool', 'fdf_document'=>'resource', 'script_name'=>'string', 'script_code'=>'string'],
'fdf_add_template' => ['bool', 'fdf_document'=>'resource', 'newpage'=>'int', 'filename'=>'string', 'template'=>'string', 'rename'=>'int'],
'fdf_close' => ['void', 'fdf_document'=>'resource'],
'fdf_create' => ['resource'],
'fdf_enum_values' => ['bool', 'fdf_document'=>'resource', 'function'=>'callable', 'userdata='=>'mixed'],
'fdf_errno' => ['int'],
'fdf_error' => ['string', 'error_code='=>'int'],
'fdf_get_ap' => ['bool', 'fdf_document'=>'resource', 'field'=>'string', 'face'=>'int', 'filename'=>'string'],
'fdf_get_attachment' => ['array', 'fdf_document'=>'resource', 'fieldname'=>'string', 'savepath'=>'string'],
'fdf_get_encoding' => ['string', 'fdf_document'=>'resource'],
'fdf_get_file' => ['string', 'fdf_document'=>'resource'],
'fdf_get_flags' => ['int', 'fdf_document'=>'resource', 'fieldname'=>'string', 'whichflags'=>'int'],
'fdf_get_opt' => ['mixed', 'fdf_document'=>'resource', 'fieldname'=>'string', 'element='=>'int'],
'fdf_get_status' => ['string', 'fdf_document'=>'resource'],
'fdf_get_value' => ['mixed', 'fdf_document'=>'resource', 'fieldname'=>'string', 'which='=>'int'],
'fdf_get_version' => ['string', 'fdf_document='=>'resource'],
'fdf_header' => ['void'],
'fdf_next_field_name' => ['string', 'fdf_document'=>'resource', 'fieldname='=>'string'],
'fdf_open' => ['resource', 'filename'=>'string'],
'fdf_open_string' => ['resource', 'fdf_data'=>'string'],
'fdf_remove_item' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'item'=>'int'],
'fdf_save' => ['bool', 'fdf_document'=>'resource', 'filename='=>'string'],
'fdf_save_string' => ['string', 'fdf_document'=>'resource'],
'fdf_set_ap' => ['bool', 'fdf_document'=>'resource', 'field_name'=>'string', 'face'=>'int', 'filename'=>'string', 'page_number'=>'int'],
'fdf_set_encoding' => ['bool', 'fdf_document'=>'resource', 'encoding'=>'string'],
'fdf_set_file' => ['bool', 'fdf_document'=>'resource', 'url'=>'string', 'target_frame='=>'string'],
'fdf_set_flags' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'whichflags'=>'int', 'newflags'=>'int'],
'fdf_set_javascript_action' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'trigger'=>'int', 'script'=>'string'],
'fdf_set_on_import_javascript' => ['bool', 'fdf_document'=>'resource', 'script'=>'string', 'before_data_import'=>'bool'],
'fdf_set_opt' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'element'=>'int', 'str1'=>'string', 'str2'=>'string'],
'fdf_set_status' => ['bool', 'fdf_document'=>'resource', 'status'=>'string'],
'fdf_set_submit_form_action' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'trigger'=>'int', 'script'=>'string', 'flags'=>'int'],
'fdf_set_target_frame' => ['bool', 'fdf_document'=>'resource', 'frame_name'=>'string'],
'fdf_set_value' => ['bool', 'fdf_document'=>'resource', 'fieldname'=>'string', 'value'=>'mixed', 'isname='=>'int'],
'fdf_set_version' => ['bool', 'fdf_document'=>'resource', 'version'=>'string'],
'feof' => ['bool', 'fp'=>'resource'],
'fflush' => ['bool', 'fp'=>'resource'],
'ffmpeg_animated_gif::__construct' => ['void', 'output_file_path'=>'string', 'width'=>'int', 'height'=>'int', 'frame_rate'=>'int', 'loop_count='=>'int'],
'ffmpeg_animated_gif::addFrame' => ['', 'frame_to_add'=>'ffmpeg_frame'],
'ffmpeg_frame::__construct' => ['void', 'gd_image'=>'resource'],
'ffmpeg_frame::crop' => ['', 'crop_top'=>'int', 'crop_bottom='=>'int', 'crop_left='=>'int', 'crop_right='=>'int'],
'ffmpeg_frame::getHeight' => ['int'],
'ffmpeg_frame::getPresentationTimestamp' => ['int'],
'ffmpeg_frame::getPTS' => ['int'],
'ffmpeg_frame::getWidth' => ['int'],
'ffmpeg_frame::resize' => ['', 'width'=>'int', 'height'=>'int', 'crop_top='=>'int', 'crop_bottom='=>'int', 'crop_left='=>'int', 'crop_right='=>'int'],
'ffmpeg_frame::toGDImage' => ['resource'],
'ffmpeg_movie::__construct' => ['void', 'path_to_media'=>'string', 'persistent'=>'bool'],
'ffmpeg_movie::getArtist' => ['string'],
'ffmpeg_movie::getAudioBitRate' => ['int'],
'ffmpeg_movie::getAudioChannels' => ['int'],
'ffmpeg_movie::getAudioCodec' => ['string'],
'ffmpeg_movie::getAudioSampleRate' => ['int'],
'ffmpeg_movie::getAuthor' => ['string'],
'ffmpeg_movie::getBitRate' => ['int'],
'ffmpeg_movie::getComment' => ['string'],
'ffmpeg_movie::getCopyright' => ['string'],
'ffmpeg_movie::getDuration' => ['int'],
'ffmpeg_movie::getFilename' => ['string'],
'ffmpeg_movie::getFrame' => ['ffmpeg_frame|false', 'framenumber'=>'int'],
'ffmpeg_movie::getFrameCount' => ['int'],
'ffmpeg_movie::getFrameHeight' => ['int'],
'ffmpeg_movie::getFrameNumber' => ['int'],
'ffmpeg_movie::getFrameRate' => ['int'],
'ffmpeg_movie::getFrameWidth' => ['int'],
'ffmpeg_movie::getGenre' => ['string'],
'ffmpeg_movie::getNextKeyFrame' => ['ffmpeg_frame|false'],
'ffmpeg_movie::getPixelFormat' => [''],
'ffmpeg_movie::getTitle' => ['string'],
'ffmpeg_movie::getTrackNumber' => ['int|string'],
'ffmpeg_movie::getVideoBitRate' => ['int'],
'ffmpeg_movie::getVideoCodec' => ['string'],
'ffmpeg_movie::getYear' => ['int|string'],
'ffmpeg_movie::hasAudio' => ['bool'],
'ffmpeg_movie::hasVideo' => ['bool'],
'fgetc' => ['string|false', 'fp'=>'resource'],
'fgetcsv' => ['?array|?false', 'fp'=>'resource', 'length='=>'int', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'fgets' => ['string|false', 'fp'=>'resource', 'length='=>'int'],
'fgetss' => ['string|false', 'fp'=>'resource', 'length='=>'int', 'allowable_tags='=>'string'],
'file' => ['array<int,string>|false', 'filename'=>'string', 'flags='=>'int', 'context='=>'resource'],
'file_exists' => ['bool', 'filename'=>'string'],
'file_get_contents' => ['string|false', 'filename'=>'string', 'use_include_path='=>'bool', 'context='=>'?resource', 'offset='=>'int', 'maxlen='=>'int'],
'file_put_contents' => ['int|false', 'file'=>'string', 'data'=>'mixed', 'flags='=>'int', 'context='=>'resource'],
'fileatime' => ['int|false', 'filename'=>'string'],
'filectime' => ['int|false', 'filename'=>'string'],
'filegroup' => ['int|false', 'filename'=>'string'],
'fileinode' => ['int|false', 'filename'=>'string'],
'filemtime' => ['int|false', 'filename'=>'string'],
'fileowner' => ['int|false', 'filename'=>'string'],
'fileperms' => ['int|false', 'filename'=>'string'],
'filepro' => ['bool', 'directory'=>'string'],
'filepro_fieldcount' => ['int'],
'filepro_fieldname' => ['string', 'field_number'=>'int'],
'filepro_fieldtype' => ['string', 'field_number'=>'int'],
'filepro_fieldwidth' => ['int', 'field_number'=>'int'],
'filepro_retrieve' => ['string', 'row_number'=>'int', 'field_number'=>'int'],
'filepro_rowcount' => ['int'],
'filesize' => ['int|false', 'filename'=>'string'],
'FilesystemIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'FilesystemIterator::__toString' => ['string'],
'FilesystemIterator::_bad_state_ex' => [''],
'FilesystemIterator::current' => ['mixed'],
'FilesystemIterator::getATime' => ['int'],
'FilesystemIterator::getBasename' => ['string', 'suffix='=>'string'],
'FilesystemIterator::getCTime' => ['int'],
'FilesystemIterator::getExtension' => ['string'],
'FilesystemIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'FilesystemIterator::getFilename' => ['string'],
'FilesystemIterator::getFlags' => ['int'],
'FilesystemIterator::getGroup' => ['int'],
'FilesystemIterator::getInode' => ['int'],
'FilesystemIterator::getLinkTarget' => ['string'],
'FilesystemIterator::getMTime' => ['int'],
'FilesystemIterator::getOwner' => ['int'],
'FilesystemIterator::getPath' => ['string'],
'FilesystemIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'FilesystemIterator::getPathname' => ['string'],
'FilesystemIterator::getPerms' => ['int'],
'FilesystemIterator::getRealPath' => ['string'],
'FilesystemIterator::getSize' => ['int'],
'FilesystemIterator::getType' => ['string'],
'FilesystemIterator::isDir' => ['bool'],
'FilesystemIterator::isDot' => ['bool'],
'FilesystemIterator::isExecutable' => ['bool'],
'FilesystemIterator::isFile' => ['bool'],
'FilesystemIterator::isLink' => ['bool'],
'FilesystemIterator::isReadable' => ['bool'],
'FilesystemIterator::isWritable' => ['bool'],
'FilesystemIterator::key' => ['string'],
'FilesystemIterator::next' => ['void'],
'FilesystemIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'FilesystemIterator::rewind' => ['void'],
'FilesystemIterator::seek' => ['void', 'position'=>'int'],
'FilesystemIterator::setFileClass' => ['void', 'class_name='=>'string'],
'FilesystemIterator::setFlags' => ['void', 'flags='=>'int'],
'FilesystemIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'FilesystemIterator::valid' => ['bool'],
'filetype' => ['string|false', 'filename'=>'string'],
'filter_has_var' => ['bool', 'type'=>'int', 'variable_name'=>'string'],
'filter_id' => ['int|false', 'filtername'=>'string'],
'filter_input' => ['mixed|false', 'type'=>'int', 'variable_name'=>'string', 'filter='=>'int', 'options='=>'array|int'],
'filter_input_array' => ['mixed|false', 'type'=>'int', 'definition='=>'int|array', 'add_empty='=>'bool'],
'filter_list' => ['array'],
'filter_var' => ['mixed|false', 'variable'=>'mixed', 'filter='=>'int', 'options='=>'mixed'],
'filter_var_array' => ['mixed|false', 'data'=>'array', 'definition='=>'mixed', 'add_empty='=>'bool'],
'FilterIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'FilterIterator::accept' => ['bool'],
'FilterIterator::current' => ['mixed'],
'FilterIterator::getInnerIterator' => ['Iterator'],
'FilterIterator::key' => ['mixed'],
'FilterIterator::next' => ['void'],
'FilterIterator::rewind' => ['void'],
'FilterIterator::valid' => ['bool'],
'finfo::__construct' => ['void', 'options='=>'int', 'magic_file='=>'string'],
'finfo::buffer' => ['string|false', 'string'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo::file' => ['string|false', 'file_name'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo::set_flags' => ['bool', 'options'=>'int'],
'finfo_buffer' => ['string|false', 'finfo'=>'resource', 'string'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo_close' => ['bool', 'finfo'=>'resource'],
'finfo_file' => ['string|false', 'finfo'=>'resource', 'file_name'=>'string', 'options='=>'int', 'context='=>'resource'],
'finfo_open' => ['resource|false', 'options='=>'int', 'arg='=>'string'],
'finfo_set_flags' => ['bool', 'finfo'=>'resource', 'options'=>'int'],
'floatval' => ['float', 'var'=>'mixed'],
'flock' => ['bool', 'fp'=>'resource', 'operation'=>'int', '&w_wouldblock='=>'int'],
'floor' => ['float', 'number'=>'float'],
'flush' => ['void'],
'fmod' => ['float', 'x'=>'float', 'y'=>'float'],
'fnmatch' => ['bool', 'pattern'=>'string', 'filename'=>'string', 'flags='=>'int'],
'fopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'forward_static_call' => ['mixed|false', 'function'=>'callable', '...parameters='=>'mixed'],
'forward_static_call_array' => ['mixed|false', 'function'=>'callable', 'parameters'=>'array<int,mixed>'],
'fpassthru' => ['int|false', 'fp'=>'resource'],
'fpm_get_status' => ['array|false'],
'fprintf' => ['int', 'stream'=>'resource', 'format'=>'string', '...args='=>'string|int|float'],
'fputcsv' => ['int|false', 'fp'=>'resource', 'fields'=>'array', 'delimiter='=>'string', 'enclosure='=>'string', 'escape_char='=>'string'],
'fputs' => ['int|false', 'fp'=>'resource', 'str'=>'string', 'length='=>'int'],
'fread' => ['string|false', 'fp'=>'resource', 'length'=>'int'],
'frenchtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'fribidi_log2vis' => ['string', 'str'=>'string', 'direction'=>'string', 'charset'=>'int'],
'fscanf' => ['array', 'stream'=>'resource', 'format'=>'string'],
'fscanf\'1' => ['int', 'stream'=>'resource', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'fseek' => ['int', 'fp'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'fsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_errno='=>'int', '&w_errstr='=>'string', 'timeout='=>'float'],
'fstat' => ['array|false', 'fp'=>'resource'],
'ftell' => ['int|false', 'fp'=>'resource'],
'ftok' => ['int', 'pathname'=>'string', 'proj'=>'string'],
'ftp_alloc' => ['bool', 'stream'=>'resource', 'size'=>'int', '&w_response='=>'string'],
'ftp_append' => ['bool', 'ftp'=>'resource', 'remote_file'=>'string', 'local_file'=>'string', 'mode='=>'int'],
'ftp_cdup' => ['bool', 'stream'=>'resource'],
'ftp_chdir' => ['bool', 'stream'=>'resource', 'directory'=>'string'],
'ftp_chmod' => ['int|false', 'stream'=>'resource', 'mode'=>'int', 'filename'=>'string'],
'ftp_close' => ['bool', 'stream'=>'resource'],
'ftp_connect' => ['resource|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_delete' => ['bool', 'stream'=>'resource', 'file'=>'string'],
'ftp_exec' => ['bool', 'stream'=>'resource', 'command'=>'string'],
'ftp_fget' => ['bool', 'stream'=>'resource', 'fp'=>'resource', 'remote_file'=>'string', 'mode='=>'int', 'resumepos='=>'int'],
'ftp_fput' => ['bool', 'stream'=>'resource', 'remote_file'=>'string', 'fp'=>'resource', 'mode='=>'int', 'startpos='=>'int'],
'ftp_get' => ['bool', 'stream'=>'resource', 'local_file'=>'string', 'remote_file'=>'string', 'mode='=>'int', 'resume_pos='=>'int'],
'ftp_get_option' => ['mixed|false', 'stream'=>'resource', 'option'=>'int'],
'ftp_login' => ['bool', 'stream'=>'resource', 'username'=>'string', 'password'=>'string'],
'ftp_mdtm' => ['int', 'stream'=>'resource', 'filename'=>'string'],
'ftp_mkdir' => ['string|false', 'stream'=>'resource', 'directory'=>'string'],
'ftp_mlsd' => ['array', 'ftp_stream'=>'resource', 'directory'=>'string'],
'ftp_nb_continue' => ['int', 'stream'=>'resource'],
'ftp_nb_fget' => ['int', 'stream'=>'resource', 'fp'=>'resource', 'remote_file'=>'string', 'mode='=>'int', 'resumepos='=>'int'],
'ftp_nb_fput' => ['int', 'stream'=>'resource', 'remote_file'=>'string', 'fp'=>'resource', 'mode='=>'int', 'startpos='=>'int'],
'ftp_nb_get' => ['int', 'stream'=>'resource', 'local_file'=>'string', 'remote_file'=>'string', 'mode='=>'int', 'resume_pos='=>'int'],
'ftp_nb_put' => ['int', 'stream'=>'resource', 'remote_file'=>'string', 'local_file'=>'string', 'mode='=>'int', 'startpos='=>'int'],
'ftp_nlist' => ['array|false', 'stream'=>'resource', 'directory'=>'string'],
'ftp_pasv' => ['bool', 'stream'=>'resource', 'pasv'=>'bool'],
'ftp_put' => ['bool', 'stream'=>'resource', 'remote_file'=>'string', 'local_file'=>'string', 'mode='=>'int', 'startpos='=>'int'],
'ftp_pwd' => ['string|false', 'stream'=>'resource'],
'ftp_quit' => ['bool', 'stream'=>'resource'],
'ftp_raw' => ['array', 'stream'=>'resource', 'command'=>'string'],
'ftp_rawlist' => ['array|false', 'stream'=>'resource', 'directory'=>'string', 'recursive='=>'bool'],
'ftp_rename' => ['bool', 'stream'=>'resource', 'src'=>'string', 'dest'=>'string'],
'ftp_rmdir' => ['bool', 'stream'=>'resource', 'directory'=>'string'],
'ftp_set_option' => ['bool', 'stream'=>'resource', 'option'=>'int', 'value'=>'mixed'],
'ftp_site' => ['bool', 'stream'=>'resource', 'cmd'=>'string'],
'ftp_size' => ['int', 'stream'=>'resource', 'filename'=>'string'],
'ftp_ssl_connect' => ['resource|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'ftp_systype' => ['string|false', 'stream'=>'resource'],
'ftruncate' => ['bool', 'fp'=>'resource', 'size'=>'int'],
'func_get_arg' => ['mixed|false', 'arg_num'=>'int'],
'func_get_args' => ['array'],
'func_num_args' => ['int'],
'function_exists' => ['bool', 'function_name'=>'string'],
'fwrite' => ['int|false', 'fp'=>'resource', 'str'=>'string', 'length='=>'int'],
'gc_collect_cycles' => ['int'],
'gc_disable' => ['void'],
'gc_enable' => ['void'],
'gc_enabled' => ['bool'],
'gc_mem_caches' => ['int'],
'gc_status' => ['array{runs:int,collected:int,threshold:int,roots:int}'],
'gd_info' => ['array'],
'gearman_bugreport' => [''],
'gearman_client_add_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_add_server' => ['', 'client_object'=>'', 'host'=>'', 'port'=>''],
'gearman_client_add_servers' => ['', 'client_object'=>'', 'servers'=>''],
'gearman_client_add_task' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_high' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_high_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_low' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_low_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'context'=>'', 'unique'=>''],
'gearman_client_add_task_status' => ['', 'client_object'=>'', 'job_handle'=>'', 'context'=>''],
'gearman_client_clear_fn' => ['', 'client_object'=>''],
'gearman_client_clone' => ['', 'client_object'=>''],
'gearman_client_context' => ['', 'client_object'=>''],
'gearman_client_create' => ['', 'client_object'=>''],
'gearman_client_do' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_high' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_high_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_job_handle' => ['', 'client_object'=>''],
'gearman_client_do_low' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_low_background' => ['', 'client_object'=>'', 'function_name'=>'', 'workload'=>'', 'unique'=>''],
'gearman_client_do_normal' => ['', 'client_object'=>'', 'function_name'=>'string', 'workload'=>'string', 'unique'=>'string'],
'gearman_client_do_status' => ['', 'client_object'=>''],
'gearman_client_echo' => ['', 'client_object'=>'', 'workload'=>''],
'gearman_client_errno' => ['', 'client_object'=>''],
'gearman_client_error' => ['', 'client_object'=>''],
'gearman_client_job_status' => ['', 'client_object'=>'', 'job_handle'=>''],
'gearman_client_options' => ['', 'client_object'=>''],
'gearman_client_remove_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_return_code' => ['', 'client_object'=>''],
'gearman_client_run_tasks' => ['', 'data'=>''],
'gearman_client_set_complete_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_context' => ['', 'client_object'=>'', 'context'=>''],
'gearman_client_set_created_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_data_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_exception_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_fail_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_options' => ['', 'client_object'=>'', 'option'=>''],
'gearman_client_set_status_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_timeout' => ['', 'client_object'=>'', 'timeout'=>''],
'gearman_client_set_warning_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_set_workload_fn' => ['', 'client_object'=>'', 'callback'=>''],
'gearman_client_timeout' => ['', 'client_object'=>''],
'gearman_client_wait' => ['', 'client_object'=>''],
'gearman_job_function_name' => ['', 'job_object'=>''],
'gearman_job_handle' => ['string'],
'gearman_job_return_code' => ['', 'job_object'=>''],
'gearman_job_send_complete' => ['', 'job_object'=>'', 'result'=>''],
'gearman_job_send_data' => ['', 'job_object'=>'', 'data'=>''],
'gearman_job_send_exception' => ['', 'job_object'=>'', 'exception'=>''],
'gearman_job_send_fail' => ['', 'job_object'=>''],
'gearman_job_send_status' => ['', 'job_object'=>'', 'numerator'=>'', 'denominator'=>''],
'gearman_job_send_warning' => ['', 'job_object'=>'', 'warning'=>''],
'gearman_job_status' => ['array', 'job_handle'=>'string'],
'gearman_job_unique' => ['', 'job_object'=>''],
'gearman_job_workload' => ['', 'job_object'=>''],
'gearman_job_workload_size' => ['', 'job_object'=>''],
'gearman_task_data' => ['', 'task_object'=>''],
'gearman_task_data_size' => ['', 'task_object'=>''],
'gearman_task_denominator' => ['', 'task_object'=>''],
'gearman_task_function_name' => ['', 'task_object'=>''],
'gearman_task_is_known' => ['', 'task_object'=>''],
'gearman_task_is_running' => ['', 'task_object'=>''],
'gearman_task_job_handle' => ['', 'task_object'=>''],
'gearman_task_numerator' => ['', 'task_object'=>''],
'gearman_task_recv_data' => ['', 'task_object'=>'', 'data_len'=>''],
'gearman_task_return_code' => ['', 'task_object'=>''],
'gearman_task_send_workload' => ['', 'task_object'=>'', 'data'=>''],
'gearman_task_unique' => ['', 'task_object'=>''],
'gearman_verbose_name' => ['', 'verbose'=>''],
'gearman_version' => [''],
'gearman_worker_add_function' => ['', 'worker_object'=>'', 'function_name'=>'', 'function'=>'', 'data'=>'', 'timeout'=>''],
'gearman_worker_add_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_add_server' => ['', 'worker_object'=>'', 'host'=>'', 'port'=>''],
'gearman_worker_add_servers' => ['', 'worker_object'=>'', 'servers'=>''],
'gearman_worker_clone' => ['', 'worker_object'=>''],
'gearman_worker_create' => [''],
'gearman_worker_echo' => ['', 'worker_object'=>'', 'workload'=>''],
'gearman_worker_errno' => ['', 'worker_object'=>''],
'gearman_worker_error' => ['', 'worker_object'=>''],
'gearman_worker_grab_job' => ['', 'worker_object'=>''],
'gearman_worker_options' => ['', 'worker_object'=>''],
'gearman_worker_register' => ['', 'worker_object'=>'', 'function_name'=>'', 'timeout'=>''],
'gearman_worker_remove_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_return_code' => ['', 'worker_object'=>''],
'gearman_worker_set_options' => ['', 'worker_object'=>'', 'option'=>''],
'gearman_worker_set_timeout' => ['', 'worker_object'=>'', 'timeout'=>''],
'gearman_worker_timeout' => ['', 'worker_object'=>''],
'gearman_worker_unregister' => ['', 'worker_object'=>'', 'function_name'=>''],
'gearman_worker_unregister_all' => ['', 'worker_object'=>''],
'gearman_worker_wait' => ['', 'worker_object'=>''],
'gearman_worker_work' => ['', 'worker_object'=>''],
'GearmanClient::__construct' => ['void'],
'GearmanClient::addOptions' => ['bool', 'options'=>'int'],
'GearmanClient::addServer' => ['bool', 'host='=>'string', 'port='=>'int'],
'GearmanClient::addServers' => ['bool', 'servers='=>'string'],
'GearmanClient::addTask' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskHigh' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskHighBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskLow' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskLowBackground' => ['GearmanTask|false', 'function_name'=>'string', 'workload'=>'string', 'context='=>'mixed', 'unique='=>'string'],
'GearmanClient::addTaskStatus' => ['GearmanTask', 'job_handle'=>'string', 'context='=>'string'],
'GearmanClient::clearCallbacks' => ['bool'],
'GearmanClient::clone' => ['GearmanClient'],
'GearmanClient::context' => ['string'],
'GearmanClient::data' => ['string'],
'GearmanClient::do' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doHigh' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doHighBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doJobHandle' => ['string'],
'GearmanClient::doLow' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doLowBackground' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doNormal' => ['string', 'function_name'=>'string', 'workload'=>'string', 'unique='=>'string'],
'GearmanClient::doStatus' => ['array'],
'GearmanClient::echo' => ['bool', 'workload'=>'string'],
'GearmanClient::error' => ['string'],
'GearmanClient::getErrno' => ['int'],
'GearmanClient::jobStatus' => ['array', 'job_handle'=>'string'],
'GearmanClient::options' => [''],
'GearmanClient::ping' => ['bool', 'workload'=>'string'],
'GearmanClient::removeOptions' => ['bool', 'options'=>'int'],
'GearmanClient::returnCode' => ['int'],
'GearmanClient::runTasks' => ['bool'],
'GearmanClient::setClientCallback' => ['void', 'callback'=>'callable'],
'GearmanClient::setCompleteCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setContext' => ['bool', 'context'=>'string'],
'GearmanClient::setCreatedCallback' => ['bool', 'callback'=>'string'],
'GearmanClient::setData' => ['bool', 'data'=>'string'],
'GearmanClient::setDataCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setExceptionCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setFailCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setOptions' => ['bool', 'options'=>'int'],
'GearmanClient::setStatusCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setTimeout' => ['bool', 'timeout'=>'int'],
'GearmanClient::setWarningCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::setWorkloadCallback' => ['bool', 'callback'=>'callable'],
'GearmanClient::timeout' => ['int'],
'GearmanClient::wait' => [''],
'GearmanJob::__construct' => ['void'],
'GearmanJob::complete' => ['bool', 'result'=>'string'],
'GearmanJob::data' => ['bool', 'data'=>'string'],
'GearmanJob::exception' => ['bool', 'exception'=>'string'],
'GearmanJob::fail' => ['bool'],
'GearmanJob::functionName' => ['string'],
'GearmanJob::handle' => ['string'],
'GearmanJob::returnCode' => ['int'],
'GearmanJob::sendComplete' => ['bool', 'result'=>'string'],
'GearmanJob::sendData' => ['bool', 'data'=>'string'],
'GearmanJob::sendException' => ['bool', 'exception'=>'string'],
'GearmanJob::sendFail' => ['bool'],
'GearmanJob::sendStatus' => ['bool', 'numerator'=>'int', 'denominator'=>'int'],
'GearmanJob::sendWarning' => ['bool', 'warning'=>'string'],
'GearmanJob::setReturn' => ['bool', 'gearman_return_t'=>'string'],
'GearmanJob::status' => ['bool', 'numerator'=>'int', 'denominator'=>'int'],
'GearmanJob::unique' => ['string'],
'GearmanJob::warning' => ['bool', 'warning'=>'string'],
'GearmanJob::workload' => ['string'],
'GearmanJob::workloadSize' => ['int'],
'GearmanTask::__construct' => ['void'],
'GearmanTask::create' => ['GearmanTask'],
'GearmanTask::data' => ['string|false'],
'GearmanTask::dataSize' => ['int|false'],
'GearmanTask::function' => ['string'],
'GearmanTask::functionName' => ['string'],
'GearmanTask::isKnown' => ['bool'],
'GearmanTask::isRunning' => ['bool'],
'GearmanTask::jobHandle' => ['string'],
'GearmanTask::recvData' => ['array|false', 'data_len'=>'int'],
'GearmanTask::returnCode' => ['int'],
'GearmanTask::sendData' => ['int', 'data'=>'string'],
'GearmanTask::sendWorkload' => ['int|false', 'data'=>'string'],
'GearmanTask::taskDenominator' => ['int|false'],
'GearmanTask::taskNumerator' => ['int|false'],
'GearmanTask::unique' => ['string|false'],
'GearmanTask::uuid' => ['string'],
'GearmanWorker::__construct' => ['void'],
'GearmanWorker::addFunction' => ['bool', 'function_name'=>'string', 'function'=>'callable', 'context='=>'mixed', 'timeout='=>'int'],
'GearmanWorker::addOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::addServer' => ['bool', 'host='=>'string', 'port='=>'int'],
'GearmanWorker::addServers' => ['bool', 'servers'=>'string'],
'GearmanWorker::clone' => ['void'],
'GearmanWorker::echo' => ['bool', 'workload'=>'string'],
'GearmanWorker::error' => ['string'],
'GearmanWorker::getErrno' => ['int'],
'GearmanWorker::grabJob' => [''],
'GearmanWorker::options' => ['int'],
'GearmanWorker::register' => ['bool', 'function_name'=>'string', 'timeout='=>'int'],
'GearmanWorker::removeOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::returnCode' => ['int'],
'GearmanWorker::setId' => ['bool', 'id'=>'string'],
'GearmanWorker::setOptions' => ['bool', 'option'=>'int'],
'GearmanWorker::setTimeout' => ['bool', 'timeout'=>'int'],
'GearmanWorker::timeout' => ['int'],
'GearmanWorker::unregister' => ['bool', 'function_name'=>'string'],
'GearmanWorker::unregisterAll' => ['bool'],
'GearmanWorker::wait' => ['bool'],
'GearmanWorker::work' => ['bool'],
'Gender\Gender::__construct' => ['void', 'dsn='=>'string'],
'Gender\Gender::connect' => ['bool', 'dsn'=>'string'],
'Gender\Gender::country' => ['array', 'country'=>'int'],
'Gender\Gender::get' => ['int', 'name'=>'string', 'country='=>'int'],
'Gender\Gender::isNick' => ['array', 'name0'=>'string', 'name1'=>'string', 'country='=>'int'],
'Gender\Gender::similarNames' => ['array', 'name'=>'string', 'country='=>'int'],
'Generator::__wakeup' => ['void'],
'Generator::current' => ['mixed'],
'Generator::getReturn' => ['mixed'],
'Generator::key' => ['mixed'],
'Generator::next' => ['void'],
'Generator::rewind' => ['void'],
'Generator::send' => ['mixed', 'value'=>'mixed'],
'Generator::throw' => ['mixed', 'exception'=>'Exception|Throwable'],
'Generator::valid' => ['bool'],
'geoip_asnum_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_continent_code_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_code3_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_code_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_country_name_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_database_info' => ['string', 'database='=>'int'],
'geoip_db_avail' => ['bool', 'database'=>'int'],
'geoip_db_filename' => ['string', 'database'=>'int'],
'geoip_db_get_all_info' => ['array'],
'geoip_domain_by_name' => ['string', 'hostname'=>'string'],
'geoip_id_by_name' => ['int', 'hostname'=>'string'],
'geoip_isp_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_netspeedcell_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_org_by_name' => ['string|false', 'hostname'=>'string'],
'geoip_record_by_name' => ['array|false', 'hostname'=>'string'],
'geoip_region_by_name' => ['array|false', 'hostname'=>'string'],
'geoip_region_name_by_code' => ['string|false', 'country_code'=>'string', 'region_code'=>'string'],
'geoip_setup_custom_directory' => ['void', 'path'=>'string'],
'geoip_time_zone_by_country_and_region' => ['string|false', 'country_code'=>'string', 'region_code='=>'string'],
'get_browser' => ['array|object|false', 'browser_name='=>'string', 'return_array='=>'bool'],
'get_call_stack' => [''],
'get_called_class' => ['class-string'],
'get_cfg_var' => ['string|false', 'option_name'=>'string'],
'get_class' => ['class-string|false', 'object='=>'object'],
'get_class_methods' => ['array<int,string>|null', 'class'=>'mixed'],
'get_class_vars' => ['array<string,mixed>', 'class_name'=>'string'],
'get_current_user' => ['string'],
'get_declared_classes' => ['array<int,class-string>'],
'get_declared_interfaces' => ['array<int,class-string>'],
'get_declared_traits' => ['array<int,class-string>|null'],
'get_defined_constants' => ['array<string,int|string|float|bool|null|array|resource>', 'categorize='=>'bool'],
'get_defined_functions' => ['array<string,array<string,callable-string>>', 'exclude_disabled='=>'bool'],
'get_defined_vars' => ['array'],
'get_extension_funcs' => ['array<int,callable-string>|false', 'extension_name'=>'string'],
'get_headers' => ['array|false', 'url'=>'string', 'format='=>'int', 'context='=>'resource'],
'get_html_translation_table' => ['array', 'table='=>'int', 'flags='=>'int', 'encoding='=>'string'],
'get_include_path' => ['string'],
'get_included_files' => ['array<int,string>'],
'get_loaded_extensions' => ['array<int,string>', 'zend_extensions='=>'bool'],
'get_magic_quotes_gpc' => ['int|false'],
'get_magic_quotes_runtime' => ['int|false'],
'get_meta_tags' => ['array', 'filename'=>'string', 'use_include_path='=>'bool'],
'get_object_vars' => ['array<string,mixed>|null', 'obj'=>'object'],
'get_parent_class' => ['class-string|false', 'object='=>'mixed'],
'get_required_files' => ['string[]'],
'get_resource_type' => ['string', 'res'=>'resource'],
'get_resources' => ['array<int,resource>', 'resource_type='=>'string'],
'getallheaders' => ['array|false'],
'getcwd' => ['string|false'],
'getdate' => ['array', 'timestamp='=>'int'],
'getenv' => ['string|false', 'varname'=>'string', 'local_only='=>'bool'],
'getenv\'1' => ['array<string,string>'],
'gethostbyaddr' => ['string|false', 'ip_address'=>'string'],
'gethostbyname' => ['string', 'hostname'=>'string'],
'gethostbynamel' => ['array|false', 'hostname'=>'string'],
'gethostname' => ['string|false'],
'getimagesize' => ['array|false', 'imagefile'=>'string', '&w_info='=>'array'],
'getimagesizefromstring' => ['array|false', 'data'=>'string', '&w_info='=>'array'],
'getlastmod' => ['int|false'],
'getmxrr' => ['bool', 'hostname'=>'string', '&w_mxhosts'=>'array', '&w_weight='=>'array'],
'getmygid' => ['int|false'],
'getmyinode' => ['int|false'],
'getmypid' => ['int|false'],
'getmyuid' => ['int|false'],
'getopt' => ['array<string,string>|array<string,false>|array<string,array<int,mixed>>|false', 'options'=>'string', 'longopts='=>'array', '&w_optind='=>'int'],
'getprotobyname' => ['int|false', 'name'=>'string'],
'getprotobynumber' => ['string', 'proto'=>'int'],
'getrandmax' => ['int'],
'getrusage' => ['array', 'who='=>'int'],
'getservbyname' => ['int|false', 'service'=>'string', 'protocol'=>'string'],
'getservbyport' => ['string|false', 'port'=>'int', 'protocol'=>'string'],
'gettext' => ['string', 'msgid'=>'string'],
'gettimeofday' => ['array'],
'gettimeofday\'1' => ['float', 'get_as_float='=>'true'],
'gettype' => ['string', 'var'=>'mixed'],
'glob' => ['array<int,string>|false', 'pattern'=>'string', 'flags='=>'int'],
'GlobIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'GlobIterator::count' => ['int'],
'GlobIterator::current' => ['FilesystemIterator|SplFileInfo|string'],
'GlobIterator::getATime' => [''],
'GlobIterator::getBasename' => ['', 'suffix='=>'string'],
'GlobIterator::getCTime' => [''],
'GlobIterator::getExtension' => [''],
'GlobIterator::getFileInfo' => [''],
'GlobIterator::getFilename' => [''],
'GlobIterator::getFlags' => ['int'],
'GlobIterator::getGroup' => [''],
'GlobIterator::getInode' => [''],
'GlobIterator::getLinkTarget' => [''],
'GlobIterator::getMTime' => [''],
'GlobIterator::getOwner' => [''],
'GlobIterator::getPath' => [''],
'GlobIterator::getPathInfo' => [''],
'GlobIterator::getPathname' => [''],
'GlobIterator::getPerms' => [''],
'GlobIterator::getRealPath' => [''],
'GlobIterator::getSize' => [''],
'GlobIterator::getType' => [''],
'GlobIterator::isDir' => [''],
'GlobIterator::isDot' => [''],
'GlobIterator::isExecutable' => [''],
'GlobIterator::isFile' => [''],
'GlobIterator::isLink' => [''],
'GlobIterator::isReadable' => [''],
'GlobIterator::isWritable' => [''],
'GlobIterator::key' => ['string'],
'GlobIterator::next' => ['void'],
'GlobIterator::openFile' => [''],
'GlobIterator::rewind' => ['void'],
'GlobIterator::seek' => ['void', 'position'=>'int'],
'GlobIterator::setFileClass' => [''],
'GlobIterator::setFlags' => ['void', 'flags='=>'int'],
'GlobIterator::setInfoClass' => [''],
'GlobIterator::valid' => [''],
'Gmagick::__construct' => ['void', 'filename='=>'string'],
'Gmagick::addimage' => ['Gmagick', 'gmagick'=>'gmagick'],
'Gmagick::addnoiseimage' => ['Gmagick', 'noise'=>'int'],
'Gmagick::annotateimage' => ['Gmagick', 'gmagickdraw'=>'gmagickdraw', 'x'=>'float', 'y'=>'float', 'angle'=>'float', 'text'=>'string'],
'Gmagick::blurimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Gmagick::borderimage' => ['Gmagick', 'color'=>'gmagickpixel', 'width'=>'int', 'height'=>'int'],
'Gmagick::charcoalimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float'],
'Gmagick::chopimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::clear' => ['Gmagick'],
'Gmagick::commentimage' => ['Gmagick', 'comment'=>'string'],
'Gmagick::compositeimage' => ['Gmagick', 'source'=>'gmagick', 'compose'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::cropimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Gmagick::cropthumbnailimage' => ['Gmagick', 'width'=>'int', 'height'=>'int'],
'Gmagick::current' => ['Gmagick'],
'Gmagick::cyclecolormapimage' => ['Gmagick', 'displace'=>'int'],
'Gmagick::deconstructimages' => ['Gmagick'],
'Gmagick::despeckleimage' => ['Gmagick'],
'Gmagick::destroy' => ['bool'],
'Gmagick::drawimage' => ['Gmagick', 'gmagickdraw'=>'gmagickdraw'],
'Gmagick::edgeimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::embossimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float'],
'Gmagick::enhanceimage' => ['Gmagick'],
'Gmagick::equalizeimage' => ['Gmagick'],
'Gmagick::flipimage' => ['Gmagick'],
'Gmagick::flopimage' => ['Gmagick'],
'Gmagick::frameimage' => ['Gmagick', 'color'=>'gmagickpixel', 'width'=>'int', 'height'=>'int', 'inner_bevel'=>'int', 'outer_bevel'=>'int'],
'Gmagick::gammaimage' => ['Gmagick', 'gamma'=>'float'],
'Gmagick::getcopyright' => ['string'],
'Gmagick::getfilename' => ['string'],
'Gmagick::getimagebackgroundcolor' => ['GmagickPixel'],
'Gmagick::getimageblueprimary' => ['array'],
'Gmagick::getimagebordercolor' => ['GmagickPixel'],
'Gmagick::getimagechanneldepth' => ['int', 'channel_type'=>'int'],
'Gmagick::getimagecolors' => ['int'],
'Gmagick::getimagecolorspace' => ['int'],
'Gmagick::getimagecompose' => ['int'],
'Gmagick::getimagedelay' => ['int'],
'Gmagick::getimagedepth' => ['int'],
'Gmagick::getimagedispose' => ['int'],
'Gmagick::getimageextrema' => ['array'],
'Gmagick::getimagefilename' => ['string'],
'Gmagick::getimageformat' => ['string'],
'Gmagick::getimagegamma' => ['float'],
'Gmagick::getimagegreenprimary' => ['array'],
'Gmagick::getimageheight' => ['int'],
'Gmagick::getimagehistogram' => ['array'],
'Gmagick::getimageindex' => ['int'],
'Gmagick::getimageinterlacescheme' => ['int'],
'Gmagick::getimageiterations' => ['int'],
'Gmagick::getimagematte' => ['int'],
'Gmagick::getimagemattecolor' => ['GmagickPixel'],
'Gmagick::getimageprofile' => ['string', 'name'=>'string'],
'Gmagick::getimageredprimary' => ['array'],
'Gmagick::getimagerenderingintent' => ['int'],
'Gmagick::getimageresolution' => ['array'],
'Gmagick::getimagescene' => ['int'],
'Gmagick::getimagesignature' => ['string'],
'Gmagick::getimagetype' => ['int'],
'Gmagick::getimageunits' => ['int'],
'Gmagick::getimagewhitepoint' => ['array'],
'Gmagick::getimagewidth' => ['int'],
'Gmagick::getpackagename' => ['string'],
'Gmagick::getquantumdepth' => ['array'],
'Gmagick::getreleasedate' => ['string'],
'Gmagick::getsamplingfactors' => ['array'],
'Gmagick::getsize' => ['array'],
'Gmagick::getversion' => ['array'],
'Gmagick::hasnextimage' => ['bool'],
'Gmagick::haspreviousimage' => ['bool'],
'Gmagick::implodeimage' => ['mixed', 'radius'=>'float'],
'Gmagick::labelimage' => ['mixed', 'label'=>'string'],
'Gmagick::levelimage' => ['mixed', 'blackpoint'=>'float', 'gamma'=>'float', 'whitepoint'=>'float', 'channel='=>'int'],
'Gmagick::magnifyimage' => ['mixed'],
'Gmagick::mapimage' => ['Gmagick', 'gmagick'=>'gmagick', 'dither'=>'bool'],
'Gmagick::medianfilterimage' => ['void', 'radius'=>'float'],
'Gmagick::minifyimage' => ['Gmagick'],
'Gmagick::modulateimage' => ['Gmagick', 'brightness'=>'float', 'saturation'=>'float', 'hue'=>'float'],
'Gmagick::motionblurimage' => ['Gmagick', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float'],
'Gmagick::newimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'background'=>'string', 'format='=>'string'],
'Gmagick::nextimage' => ['bool'],
'Gmagick::normalizeimage' => ['Gmagick', 'channel='=>'int'],
'Gmagick::oilpaintimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::previousimage' => ['bool'],
'Gmagick::profileimage' => ['Gmagick', 'name'=>'string', 'profile'=>'string'],
'Gmagick::quantizeimage' => ['Gmagick', 'numcolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Gmagick::quantizeimages' => ['Gmagick', 'numcolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Gmagick::queryfontmetrics' => ['array', 'draw'=>'gmagickdraw', 'text'=>'string'],
'Gmagick::queryfonts' => ['array', 'pattern='=>'string'],
'Gmagick::queryformats' => ['array', 'pattern='=>'string'],
'Gmagick::radialblurimage' => ['Gmagick', 'angle'=>'float', 'channel='=>'int'],
'Gmagick::raiseimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int', 'raise'=>'bool'],
'Gmagick::read' => ['Gmagick', 'filename'=>'string'],
'Gmagick::readimage' => ['Gmagick', 'filename'=>'string'],
'Gmagick::readimageblob' => ['Gmagick', 'imagecontents'=>'string', 'filename='=>'string'],
'Gmagick::readimagefile' => ['Gmagick', 'fp'=>'resource', 'filename='=>'string'],
'Gmagick::reducenoiseimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::removeimage' => ['Gmagick'],
'Gmagick::removeimageprofile' => ['string', 'name'=>'string'],
'Gmagick::resampleimage' => ['Gmagick', 'xresolution'=>'float', 'yresolution'=>'float', 'filter'=>'int', 'blur'=>'float'],
'Gmagick::resizeimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'filter'=>'int', 'blur'=>'float', 'fit='=>'bool'],
'Gmagick::rollimage' => ['Gmagick', 'x'=>'int', 'y'=>'int'],
'Gmagick::rotateimage' => ['Gmagick', 'color'=>'mixed', 'degrees'=>'float'],
'Gmagick::scaleimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'fit='=>'bool'],
'Gmagick::separateimagechannel' => ['Gmagick', 'channel'=>'int'],
'Gmagick::setCompressionQuality' => ['Gmagick', 'quality'=>'int'],
'Gmagick::setfilename' => ['Gmagick', 'filename'=>'string'],
'Gmagick::setimagebackgroundcolor' => ['Gmagick', 'color'=>'gmagickpixel'],
'Gmagick::setimageblueprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimagebordercolor' => ['Gmagick', 'color'=>'gmagickpixel'],
'Gmagick::setimagechanneldepth' => ['Gmagick', 'channel'=>'int', 'depth'=>'int'],
'Gmagick::setimagecolorspace' => ['Gmagick', 'colorspace'=>'int'],
'Gmagick::setimagecompose' => ['Gmagick', 'composite'=>'int'],
'Gmagick::setimagedelay' => ['Gmagick', 'delay'=>'int'],
'Gmagick::setimagedepth' => ['Gmagick', 'depth'=>'int'],
'Gmagick::setimagedispose' => ['Gmagick', 'disposetype'=>'int'],
'Gmagick::setimagefilename' => ['Gmagick', 'filename'=>'string'],
'Gmagick::setimageformat' => ['Gmagick', 'imageformat'=>'string'],
'Gmagick::setimagegamma' => ['Gmagick', 'gamma'=>'float'],
'Gmagick::setimagegreenprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimageindex' => ['Gmagick', 'index'=>'int'],
'Gmagick::setimageinterlacescheme' => ['Gmagick', 'interlace'=>'int'],
'Gmagick::setimageiterations' => ['Gmagick', 'iterations'=>'int'],
'Gmagick::setimageprofile' => ['Gmagick', 'name'=>'string', 'profile'=>'string'],
'Gmagick::setimageredprimary' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setimagerenderingintent' => ['Gmagick', 'rendering_intent'=>'int'],
'Gmagick::setimageresolution' => ['Gmagick', 'xresolution'=>'float', 'yresolution'=>'float'],
'Gmagick::setimagescene' => ['Gmagick', 'scene'=>'int'],
'Gmagick::setimagetype' => ['Gmagick', 'imgtype'=>'int'],
'Gmagick::setimageunits' => ['Gmagick', 'resolution'=>'int'],
'Gmagick::setimagewhitepoint' => ['Gmagick', 'x'=>'float', 'y'=>'float'],
'Gmagick::setsamplingfactors' => ['Gmagick', 'factors'=>'array'],
'Gmagick::setsize' => ['Gmagick', 'columns'=>'int', 'rows'=>'int'],
'Gmagick::shearimage' => ['Gmagick', 'color'=>'mixed', 'xshear'=>'float', 'yshear'=>'float'],
'Gmagick::solarizeimage' => ['Gmagick', 'threshold'=>'int'],
'Gmagick::spreadimage' => ['Gmagick', 'radius'=>'float'],
'Gmagick::stripimage' => ['Gmagick'],
'Gmagick::swirlimage' => ['Gmagick', 'degrees'=>'float'],
'Gmagick::thumbnailimage' => ['Gmagick', 'width'=>'int', 'height'=>'int', 'fit='=>'bool'],
'Gmagick::trimimage' => ['Gmagick', 'fuzz'=>'float'],
'Gmagick::write' => ['Gmagick', 'filename'=>'string'],
'Gmagick::writeimage' => ['Gmagick', 'filename'=>'string', 'all_frames='=>'bool'],
'GmagickDraw::annotate' => ['GmagickDraw', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'GmagickDraw::arc' => ['GmagickDraw', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float', 'sd'=>'float', 'ed'=>'float'],
'GmagickDraw::bezier' => ['GmagickDraw', 'coordinate_array'=>'array'],
'GmagickDraw::ellipse' => ['GmagickDraw', 'ox'=>'float', 'oy'=>'float', 'rx'=>'float', 'ry'=>'float', 'start'=>'float', 'end'=>'float'],
'GmagickDraw::getfillcolor' => ['GmagickPixel'],
'GmagickDraw::getfillopacity' => ['float'],
'GmagickDraw::getfont' => ['string|false'],
'GmagickDraw::getfontsize' => ['float'],
'GmagickDraw::getfontstyle' => ['int'],
'GmagickDraw::getfontweight' => ['int'],
'GmagickDraw::getstrokecolor' => ['GmagickPixel'],
'GmagickDraw::getstrokeopacity' => ['float'],
'GmagickDraw::getstrokewidth' => ['float'],
'GmagickDraw::gettextdecoration' => ['int'],
'GmagickDraw::gettextencoding' => ['string|false'],
'GmagickDraw::line' => ['GmagickDraw', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float'],
'GmagickDraw::point' => ['GmagickDraw', 'x'=>'float', 'y'=>'float'],
'GmagickDraw::polygon' => ['GmagickDraw', 'coordinates'=>'array'],
'GmagickDraw::polyline' => ['GmagickDraw', 'coordinate_array'=>'array'],
'GmagickDraw::rectangle' => ['GmagickDraw', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'GmagickDraw::rotate' => ['GmagickDraw', 'degrees'=>'float'],
'GmagickDraw::roundrectangle' => ['GmagickDraw', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'rx'=>'float', 'ry'=>'float'],
'GmagickDraw::scale' => ['GmagickDraw', 'x'=>'float', 'y'=>'float'],
'GmagickDraw::setfillcolor' => ['GmagickDraw', 'color'=>'string'],
'GmagickDraw::setfillopacity' => ['GmagickDraw', 'fill_opacity'=>'float'],
'GmagickDraw::setfont' => ['GmagickDraw', 'font'=>'string'],
'GmagickDraw::setfontsize' => ['GmagickDraw', 'pointsize'=>'float'],
'GmagickDraw::setfontstyle' => ['GmagickDraw', 'style'=>'int'],
'GmagickDraw::setfontweight' => ['GmagickDraw', 'weight'=>'int'],
'GmagickDraw::setstrokecolor' => ['GmagickDraw', 'color'=>'gmagickpixel'],
'GmagickDraw::setstrokeopacity' => ['GmagickDraw', 'stroke_opacity'=>'float'],
'GmagickDraw::setstrokewidth' => ['GmagickDraw', 'width'=>'float'],
'GmagickDraw::settextdecoration' => ['GmagickDraw', 'decoration'=>'int'],
'GmagickDraw::settextencoding' => ['GmagickDraw', 'encoding'=>'string'],
'GmagickPixel::__construct' => ['void', 'color='=>'string'],
'GmagickPixel::getcolor' => ['mixed', 'as_array='=>'bool', 'normalize_array='=>'bool'],
'GmagickPixel::getcolorcount' => ['int'],
'GmagickPixel::getcolorvalue' => ['float', 'color'=>'int'],
'GmagickPixel::setcolor' => ['GmagickPixel', 'color'=>'string'],
'GmagickPixel::setcolorvalue' => ['GmagickPixel', 'color'=>'int', 'value'=>'float'],
'gmdate' => ['string|false', 'format'=>'string', 'timestamp='=>'int'],
'gmmktime' => ['int|false', 'hour='=>'int', 'min='=>'int', 'sec='=>'int', 'mon='=>'int', 'day='=>'int', 'year='=>'int'],
'GMP::__construct' => ['void'],
'GMP::__toString' => ['string'],
'GMP::serialize' => ['string'],
'GMP::unserialize' => ['void', 'serialized'=>'string'],
'gmp_abs' => ['GMP', 'a'=>'GMP|string|int'],
'gmp_add' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_and' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_binomial' => ['GMP|false', 'n'=>'GMP|string|int', 'k'=>'int'],
'gmp_clrbit' => ['void', 'a'=>'GMP|string|int', 'index'=>'int'],
'gmp_cmp' => ['int', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_com' => ['GMP', 'a'=>'GMP|string|int'],
'gmp_div' => ['GMP', 'a'=>'GMP|resource|string', 'b'=>'GMP|resource|string', 'round='=>'int'],
'gmp_div_q' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int', 'round='=>'int'],
'gmp_div_qr' => ['array<int,GMP>', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int', 'round='=>'int'],
'gmp_div_r' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int', 'round='=>'int'],
'gmp_divexact' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_export' => ['string|false', 'gmpnumber'=>'GMP|string|int', 'word_size='=>'int', 'options='=>'int'],
'gmp_fact' => ['GMP', 'a'=>'int'],
'gmp_gcd' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_gcdext' => ['array<string,GMP>', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_hamdist' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_import' => ['GMP|false', 'data'=>'string', 'word_size='=>'int', 'options='=>'int'],
'gmp_init' => ['GMP', 'number'=>'int|string', 'base='=>'int'],
'gmp_intval' => ['int', 'gmpnumber'=>'GMP|string|int'],
'gmp_invert' => ['GMP|false', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_jacobi' => ['int', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_kronecker' => ['int', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_lcm' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_legendre' => ['int', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_mod' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_mul' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_neg' => ['GMP', 'a'=>'GMP|string|int'],
'gmp_nextprime' => ['GMP', 'a'=>'GMP|string|int'],
'gmp_or' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_perfect_power' => ['bool', 'a'=>'GMP|string|int'],
'gmp_perfect_square' => ['bool', 'a'=>'GMP|string|int'],
'gmp_popcount' => ['int', 'a'=>'GMP|string|int'],
'gmp_pow' => ['GMP', 'base'=>'GMP|string|int', 'exp'=>'int'],
'gmp_powm' => ['GMP', 'base'=>'GMP|string|int', 'exp'=>'GMP|string|int', 'mod'=>'GMP|string|int'],
'gmp_prob_prime' => ['int', 'a'=>'GMP|string|int', 'reps='=>'int'],
'gmp_random' => ['GMP', 'limiter='=>'int'],
'gmp_random_bits' => ['GMP', 'bits'=>'int'],
'gmp_random_range' => ['GMP', 'min'=>'GMP|string|int', 'max'=>'GMP|string|int'],
'gmp_random_seed' => ['void|false', 'seed'=>'GMP|string|int'],
'gmp_root' => ['GMP', 'a'=>'GMP|string|int', 'nth'=>'int'],
'gmp_rootrem' => ['array<int,GMP>', 'a'=>'GMP|string|int', 'nth'=>'int'],
'gmp_scan0' => ['int', 'a'=>'GMP|string|int', 'start'=>'int'],
'gmp_scan1' => ['int', 'a'=>'GMP|string|int', 'start'=>'int'],
'gmp_setbit' => ['void', 'a'=>'GMP|string|int', 'index'=>'int', 'set_clear='=>'bool'],
'gmp_sign' => ['int', 'a'=>'GMP|string|int'],
'gmp_sqrt' => ['GMP', 'a'=>'GMP|string|int'],
'gmp_sqrtrem' => ['array', 'a'=>'GMP|string|int'],
'gmp_strval' => ['string', 'gmpnumber'=>'GMP|string|int', 'base='=>'int'],
'gmp_sub' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmp_testbit' => ['bool', 'a'=>'GMP|string|int', 'index'=>'int'],
'gmp_xor' => ['GMP', 'a'=>'GMP|string|int', 'b'=>'GMP|string|int'],
'gmstrftime' => ['string', 'format'=>'string', 'timestamp='=>'int'],
'gnupg::adddecryptkey' => ['bool', 'fingerprint'=>'string', 'passphrase'=>'string'],
'gnupg::addencryptkey' => ['bool', 'fingerprint'=>'string'],
'gnupg::addsignkey' => ['bool', 'fingerprint'=>'string', 'passphrase='=>'string'],
'gnupg::cleardecryptkeys' => ['bool'],
'gnupg::clearencryptkeys' => ['bool'],
'gnupg::clearsignkeys' => ['bool'],
'gnupg::decrypt' => ['string|false', 'text'=>'string'],
'gnupg::decryptverify' => ['array|false', 'text'=>'string', '&plaintext'=>'string'],
'gnupg::encrypt' => ['string|false', 'plaintext'=>'string'],
'gnupg::encryptsign' => ['string|false', 'plaintext'=>'string'],
'gnupg::export' => ['string|false', 'fingerprint'=>'string'],
'gnupg::geterror' => ['string|false'],
'gnupg::getprotocol' => ['int'],
'gnupg::import' => ['array|false', 'keydata'=>'string'],
'gnupg::init' => ['resource'],
'gnupg::keyinfo' => ['array', 'pattern'=>'string'],
'gnupg::setarmor' => ['bool', 'armor'=>'int'],
'gnupg::seterrormode' => ['void', 'errormode'=>'int'],
'gnupg::setsignmode' => ['bool', 'signmode'=>'int'],
'gnupg::sign' => ['string|false', 'plaintext'=>'string'],
'gnupg::verify' => ['array|false', 'signed_text'=>'string', 'signature'=>'string', '&plaintext='=>'string'],
'gnupg_adddecryptkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string', 'passphrase'=>'string'],
'gnupg_addencryptkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string'],
'gnupg_addsignkey' => ['bool', 'identifier'=>'resource', 'fingerprint'=>'string', 'passphrase='=>'string'],
'gnupg_cleardecryptkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_clearencryptkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_clearsignkeys' => ['bool', 'identifier'=>'resource'],
'gnupg_decrypt' => ['string', 'identifier'=>'resource', 'text'=>'string'],
'gnupg_decryptverify' => ['array', 'identifier'=>'resource', 'text'=>'string', 'plaintext'=>'string'],
'gnupg_encrypt' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_encryptsign' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_export' => ['string', 'identifier'=>'resource', 'fingerprint'=>'string'],
'gnupg_geterror' => ['string', 'identifier'=>'resource'],
'gnupg_getprotocol' => ['int', 'identifier'=>'resource'],
'gnupg_import' => ['array', 'identifier'=>'resource', 'keydata'=>'string'],
'gnupg_init' => ['resource'],
'gnupg_keyinfo' => ['array', 'identifier'=>'resource', 'pattern'=>'string'],
'gnupg_setarmor' => ['bool', 'identifier'=>'resource', 'armor'=>'int'],
'gnupg_seterrormode' => ['void', 'identifier'=>'resource', 'errormode'=>'int'],
'gnupg_setsignmode' => ['bool', 'identifier'=>'resource', 'signmode'=>'int'],
'gnupg_sign' => ['string', 'identifier'=>'resource', 'plaintext'=>'string'],
'gnupg_verify' => ['array', 'identifier'=>'resource', 'signed_text'=>'string', 'signature'=>'string', 'plaintext='=>'string'],
'gopher_parsedir' => ['array', 'dirent'=>'string'],
'grapheme_extract' => ['string|false', 'str'=>'string', 'size'=>'int', 'extract_type='=>'int', 'start='=>'int', '&w_next='=>'int'],
'grapheme_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'part='=>'bool'],
'grapheme_strlen' => ['int|false|null', 'str'=>'string'],
'grapheme_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int'],
'grapheme_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'part='=>'bool'],
'grapheme_substr' => ['string|false', 'str'=>'string', 'start'=>'int', 'length='=>'int'],
'gregoriantojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'gridObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'Grpc\Call::__construct' => ['void', 'channel'=>'Grpc\Channel', 'method'=>'string', 'absolute_deadline'=>'Grpc\Timeval', 'host_override='=>'mixed'],
'Grpc\Call::cancel' => [''],
'Grpc\Call::getPeer' => ['string'],
'Grpc\Call::setCredentials' => ['int', 'creds_obj'=>'Grpc\CallCredentials'],
'Grpc\Call::startBatch' => ['object', 'batch'=>'array'],
'Grpc\CallCredentials::createComposite' => ['Grpc\CallCredentials', 'cred1'=>'Grpc\CallCredentials', 'cred2'=>'Grpc\CallCredentials'],
'Grpc\CallCredentials::createFromPlugin' => ['Grpc\CallCredentials', 'callback'=>'Closure'],
'Grpc\Channel::__construct' => ['void', 'target'=>'string', 'args='=>'array'],
'Grpc\Channel::close' => [''],
'Grpc\Channel::getConnectivityState' => ['int', 'try_to_connect='=>'bool'],
'Grpc\Channel::getTarget' => ['string'],
'Grpc\Channel::watchConnectivityState' => ['bool', 'last_state'=>'int', 'deadline_obj'=>'Grpc\Timeval'],
'Grpc\ChannelCredentials::createComposite' => ['Grpc\ChannelCredentials', 'cred1'=>'Grpc\ChannelCredentials', 'cred2'=>'Grpc\CallCredentials'],
'Grpc\ChannelCredentials::createDefault' => ['Grpc\ChannelCredentials'],
'Grpc\ChannelCredentials::createInsecure' => ['null'],
'Grpc\ChannelCredentials::createSsl' => ['Grpc\ChannelCredentials', 'pem_root_certs'=>'string', 'pem_private_key='=>'string', 'pem_cert_chain='=>'string'],
'Grpc\ChannelCredentials::setDefaultRootsPem' => ['', 'pem_roots'=>'string'],
'Grpc\Server::__construct' => ['void', 'args'=>'array'],
'Grpc\Server::addHttp2Port' => ['bool', 'addr'=>'string'],
'Grpc\Server::addSecureHttp2Port' => ['bool', 'addr'=>'string', 'creds_obj'=>'Grpc\ServerCredentials'],
'Grpc\Server::requestCall' => ['', 'tag_new'=>'int', 'tag_cancel'=>'int'],
'Grpc\Server::start' => [''],
'Grpc\ServerCredentials::createSsl' => ['object', 'pem_root_certs'=>'string', 'pem_private_key'=>'string', 'pem_cert_chain'=>'string'],
'Grpc\Timeval::__construct' => ['void', 'usec'=>'int'],
'Grpc\Timeval::add' => ['Grpc\Timeval', 'other'=>'Grpc\Timeval'],
'Grpc\Timeval::compare' => ['int', 'a'=>'Grpc\Timeval', 'b'=>'Grpc\Timeval'],
'Grpc\Timeval::infFuture' => ['Grpc\Timeval'],
'Grpc\Timeval::infPast' => ['Grpc\Timeval'],
'Grpc\Timeval::now' => ['Grpc\Timeval'],
'Grpc\Timeval::similar' => ['bool', 'a'=>'Grpc\Timeval', 'b'=>'Grpc\Timeval', 'threshold'=>'Grpc\Timeval'],
'Grpc\Timeval::sleepUntil' => [''],
'Grpc\Timeval::subtract' => ['Grpc\Timeval', 'other'=>'Grpc\Timeval'],
'Grpc\Timeval::zero' => ['Grpc\Timeval'],
'gupnp_context_get_host_ip' => ['string', 'context'=>'resource'],
'gupnp_context_get_port' => ['int', 'context'=>'resource'],
'gupnp_context_get_subscription_timeout' => ['int', 'context'=>'resource'],
'gupnp_context_host_path' => ['bool', 'context'=>'resource', 'local_path'=>'string', 'server_path'=>'string'],
'gupnp_context_new' => ['resource', 'host_ip='=>'string', 'port='=>'int'],
'gupnp_context_set_subscription_timeout' => ['void', 'context'=>'resource', 'timeout'=>'int'],
'gupnp_context_timeout_add' => ['bool', 'context'=>'resource', 'timeout'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_context_unhost_path' => ['bool', 'context'=>'resource', 'server_path'=>'string'],
'gupnp_control_point_browse_start' => ['bool', 'cpoint'=>'resource'],
'gupnp_control_point_browse_stop' => ['bool', 'cpoint'=>'resource'],
'gupnp_control_point_callback_set' => ['bool', 'cpoint'=>'resource', 'signal'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_control_point_new' => ['resource', 'context'=>'resource', 'target'=>'string'],
'gupnp_device_action_callback_set' => ['bool', 'root_device'=>'resource', 'signal'=>'int', 'action_name'=>'string', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_device_info_get' => ['array', 'root_device'=>'resource'],
'gupnp_device_info_get_service' => ['resource', 'root_device'=>'resource', 'type'=>'string'],
'gupnp_root_device_get_available' => ['bool', 'root_device'=>'resource'],
'gupnp_root_device_get_relative_location' => ['string', 'root_device'=>'resource'],
'gupnp_root_device_new' => ['resource', 'context'=>'resource', 'location'=>'string', 'description_dir'=>'string'],
'gupnp_root_device_set_available' => ['bool', 'root_device'=>'resource', 'available'=>'bool'],
'gupnp_root_device_start' => ['bool', 'root_device'=>'resource'],
'gupnp_root_device_stop' => ['bool', 'root_device'=>'resource'],
'gupnp_service_action_get' => ['mixed', 'action'=>'resource', 'name'=>'string', 'type'=>'int'],
'gupnp_service_action_return' => ['bool', 'action'=>'resource'],
'gupnp_service_action_return_error' => ['bool', 'action'=>'resource', 'error_code'=>'int', 'error_description='=>'string'],
'gupnp_service_action_set' => ['bool', 'action'=>'resource', 'name'=>'string', 'type'=>'int', 'value'=>'mixed'],
'gupnp_service_freeze_notify' => ['bool', 'service'=>'resource'],
'gupnp_service_info_get' => ['array', 'proxy'=>'resource'],
'gupnp_service_info_get_introspection' => ['mixed', 'proxy'=>'resource', 'callback='=>'mixed', 'arg='=>'mixed'],
'gupnp_service_introspection_get_state_variable' => ['array', 'introspection'=>'resource', 'variable_name'=>'string'],
'gupnp_service_notify' => ['bool', 'service'=>'resource', 'name'=>'string', 'type'=>'int', 'value'=>'mixed'],
'gupnp_service_proxy_action_get' => ['mixed', 'proxy'=>'resource', 'action'=>'string', 'name'=>'string', 'type'=>'int'],
'gupnp_service_proxy_action_set' => ['bool', 'proxy'=>'resource', 'action'=>'string', 'name'=>'string', 'value'=>'mixed', 'type'=>'int'],
'gupnp_service_proxy_add_notify' => ['bool', 'proxy'=>'resource', 'value'=>'string', 'type'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_service_proxy_callback_set' => ['bool', 'proxy'=>'resource', 'signal'=>'int', 'callback'=>'mixed', 'arg='=>'mixed'],
'gupnp_service_proxy_get_subscribed' => ['bool', 'proxy'=>'resource'],
'gupnp_service_proxy_remove_notify' => ['bool', 'proxy'=>'resource', 'value'=>'string'],
'gupnp_service_proxy_send_action' => ['array', 'proxy'=>'resource', 'action'=>'string', 'in_params'=>'array', 'out_params'=>'array'],
'gupnp_service_proxy_set_subscribed' => ['bool', 'proxy'=>'resource', 'subscribed'=>'bool'],
'gupnp_service_thaw_notify' => ['bool', 'service'=>'resource'],
'gzclose' => ['bool', 'zp'=>'resource'],
'gzcompress' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzdecode' => ['string|false', 'data'=>'string', 'length='=>'int'],
'gzdeflate' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding='=>'int'],
'gzencode' => ['string|false', 'data'=>'string', 'level='=>'int', 'encoding_mode='=>'int'],
'gzeof' => ['bool|int', 'zp'=>'resource'],
'gzfile' => ['array', 'filename'=>'string', 'use_include_path='=>'int'],
'gzgetc' => ['string|false', 'zp'=>'resource'],
'gzgets' => ['string|false', 'zp'=>'resource', 'length='=>'int'],
'gzgetss' => ['string|false', 'zp'=>'resource', 'length'=>'int', 'allowable_tags='=>'string'],
'gzinflate' => ['string|false', 'data'=>'string', 'length='=>'int'],
'gzopen' => ['resource|false', 'filename'=>'string', 'mode'=>'string', 'use_include_path='=>'int'],
'gzpassthru' => ['int|false', 'zp'=>'resource'],
'gzputs' => ['int', 'zp'=>'resource', 'string'=>'string', 'length='=>'int'],
'gzread' => ['string', 'zp'=>'resource', 'length'=>'int'],
'gzrewind' => ['bool', 'zp'=>'resource'],
'gzseek' => ['int', 'zp'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'gztell' => ['int|false', 'zp'=>'resource'],
'gzuncompress' => ['string|false', 'data'=>'string', 'length='=>'int'],
'gzwrite' => ['int', 'zp'=>'resource', 'string'=>'string', 'length='=>'int'],
'HaruAnnotation::setBorderStyle' => ['bool', 'width'=>'float', 'dash_on'=>'int', 'dash_off'=>'int'],
'HaruAnnotation::setHighlightMode' => ['bool', 'mode'=>'int'],
'HaruAnnotation::setIcon' => ['bool', 'icon'=>'int'],
'HaruAnnotation::setOpened' => ['bool', 'opened'=>'bool'],
'HaruDestination::setFit' => ['bool'],
'HaruDestination::setFitB' => ['bool'],
'HaruDestination::setFitBH' => ['bool', 'top'=>'float'],
'HaruDestination::setFitBV' => ['bool', 'left'=>'float'],
'HaruDestination::setFitH' => ['bool', 'top'=>'float'],
'HaruDestination::setFitR' => ['bool', 'left'=>'float', 'bottom'=>'float', 'right'=>'float', 'top'=>'float'],
'HaruDestination::setFitV' => ['bool', 'left'=>'float'],
'HaruDestination::setXYZ' => ['bool', 'left'=>'float', 'top'=>'float', 'zoom'=>'float'],
'HaruDoc::__construct' => ['void'],
'HaruDoc::addPage' => ['object'],
'HaruDoc::addPageLabel' => ['bool', 'first_page'=>'int', 'style'=>'int', 'first_num'=>'int', 'prefix='=>'string'],
'HaruDoc::createOutline' => ['object', 'title'=>'string', 'parent_outline='=>'object', 'encoder='=>'object'],
'HaruDoc::getCurrentEncoder' => ['object'],
'HaruDoc::getCurrentPage' => ['object'],
'HaruDoc::getEncoder' => ['object', 'encoding'=>'string'],
'HaruDoc::getFont' => ['object', 'fontname'=>'string', 'encoding='=>'string'],
'HaruDoc::getInfoAttr' => ['string', 'type'=>'int'],
'HaruDoc::getPageLayout' => ['int'],
'HaruDoc::getPageMode' => ['int'],
'HaruDoc::getStreamSize' => ['int'],
'HaruDoc::insertPage' => ['object', 'page'=>'object'],
'HaruDoc::loadJPEG' => ['object', 'filename'=>'string'],
'HaruDoc::loadPNG' => ['object', 'filename'=>'string', 'deferred='=>'bool'],
'HaruDoc::loadRaw' => ['object', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'color_space'=>'int'],
'HaruDoc::loadTTC' => ['string', 'fontfile'=>'string', 'index'=>'int', 'embed='=>'bool'],
'HaruDoc::loadTTF' => ['string', 'fontfile'=>'string', 'embed='=>'bool'],
'HaruDoc::loadType1' => ['string', 'afmfile'=>'string', 'pfmfile='=>'string'],
'HaruDoc::output' => ['bool'],
'HaruDoc::readFromStream' => ['string', 'bytes'=>'int'],
'HaruDoc::resetError' => ['bool'],
'HaruDoc::resetStream' => ['bool'],
'HaruDoc::save' => ['bool', 'file'=>'string'],
'HaruDoc::saveToStream' => ['bool'],
'HaruDoc::setCompressionMode' => ['bool', 'mode'=>'int'],
'HaruDoc::setCurrentEncoder' => ['bool', 'encoding'=>'string'],
'HaruDoc::setEncryptionMode' => ['bool', 'mode'=>'int', 'key_len='=>'int'],
'HaruDoc::setInfoAttr' => ['bool', 'type'=>'int', 'info'=>'string'],
'HaruDoc::setInfoDateAttr' => ['bool', 'type'=>'int', 'year'=>'int', 'month'=>'int', 'day'=>'int', 'hour'=>'int', 'min'=>'int', 'sec'=>'int', 'ind'=>'string', 'off_hour'=>'int', 'off_min'=>'int'],
'HaruDoc::setOpenAction' => ['bool', 'destination'=>'object'],
'HaruDoc::setPageLayout' => ['bool', 'layout'=>'int'],
'HaruDoc::setPageMode' => ['bool', 'mode'=>'int'],
'HaruDoc::setPagesConfiguration' => ['bool', 'page_per_pages'=>'int'],
'HaruDoc::setPassword' => ['bool', 'owner_password'=>'string', 'user_password'=>'string'],
'HaruDoc::setPermission' => ['bool', 'permission'=>'int'],
'HaruDoc::useCNSEncodings' => ['bool'],
'HaruDoc::useCNSFonts' => ['bool'],
'HaruDoc::useCNTEncodings' => ['bool'],
'HaruDoc::useCNTFonts' => ['bool'],
'HaruDoc::useJPEncodings' => ['bool'],
'HaruDoc::useJPFonts' => ['bool'],
'HaruDoc::useKREncodings' => ['bool'],
'HaruDoc::useKRFonts' => ['bool'],
'HaruEncoder::getByteType' => ['int', 'text'=>'string', 'index'=>'int'],
'HaruEncoder::getType' => ['int'],
'HaruEncoder::getUnicode' => ['int', 'character'=>'int'],
'HaruEncoder::getWritingMode' => ['int'],
'HaruFont::getAscent' => ['int'],
'HaruFont::getCapHeight' => ['int'],
'HaruFont::getDescent' => ['int'],
'HaruFont::getEncodingName' => ['string'],
'HaruFont::getFontName' => ['string'],
'HaruFont::getTextWidth' => ['array', 'text'=>'string'],
'HaruFont::getUnicodeWidth' => ['int', 'character'=>'int'],
'HaruFont::getXHeight' => ['int'],
'HaruFont::measureText' => ['int', 'text'=>'string', 'width'=>'float', 'font_size'=>'float', 'char_space'=>'float', 'word_space'=>'float', 'word_wrap='=>'bool'],
'HaruImage::getBitsPerComponent' => ['int'],
'HaruImage::getColorSpace' => ['string'],
'HaruImage::getHeight' => ['int'],
'HaruImage::getSize' => ['array'],
'HaruImage::getWidth' => ['int'],
'HaruImage::setColorMask' => ['bool', 'rmin'=>'int', 'rmax'=>'int', 'gmin'=>'int', 'gmax'=>'int', 'bmin'=>'int', 'bmax'=>'int'],
'HaruImage::setMaskImage' => ['bool', 'mask_image'=>'object'],
'HaruOutline::setDestination' => ['bool', 'destination'=>'object'],
'HaruOutline::setOpened' => ['bool', 'opened'=>'bool'],
'HaruPage::arc' => ['bool', 'x'=>'float', 'y'=>'float', 'ray'=>'float', 'ang1'=>'float', 'ang2'=>'float'],
'HaruPage::beginText' => ['bool'],
'HaruPage::circle' => ['bool', 'x'=>'float', 'y'=>'float', 'ray'=>'float'],
'HaruPage::closePath' => ['bool'],
'HaruPage::concat' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'HaruPage::createDestination' => ['object'],
'HaruPage::createLinkAnnotation' => ['object', 'rectangle'=>'array', 'destination'=>'object'],
'HaruPage::createTextAnnotation' => ['object', 'rectangle'=>'array', 'text'=>'string', 'encoder='=>'object'],
'HaruPage::createURLAnnotation' => ['object', 'rectangle'=>'array', 'url'=>'string'],
'HaruPage::curveTo' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::curveTo2' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::curveTo3' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x3'=>'float', 'y3'=>'float'],
'HaruPage::drawImage' => ['bool', 'image'=>'object', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'HaruPage::ellipse' => ['bool', 'x'=>'float', 'y'=>'float', 'xray'=>'float', 'yray'=>'float'],
'HaruPage::endPath' => ['bool'],
'HaruPage::endText' => ['bool'],
'HaruPage::eofill' => ['bool'],
'HaruPage::eoFillStroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::fill' => ['bool'],
'HaruPage::fillStroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::getCharSpace' => ['float'],
'HaruPage::getCMYKFill' => ['array'],
'HaruPage::getCMYKStroke' => ['array'],
'HaruPage::getCurrentFont' => ['object'],
'HaruPage::getCurrentFontSize' => ['float'],
'HaruPage::getCurrentPos' => ['array'],
'HaruPage::getCurrentTextPos' => ['array'],
'HaruPage::getDash' => ['array'],
'HaruPage::getFillingColorSpace' => ['int'],
'HaruPage::getFlatness' => ['float'],
'HaruPage::getGMode' => ['int'],
'HaruPage::getGrayFill' => ['float'],
'HaruPage::getGrayStroke' => ['float'],
'HaruPage::getHeight' => ['float'],
'HaruPage::getHorizontalScaling' => ['float'],
'HaruPage::getLineCap' => ['int'],
'HaruPage::getLineJoin' => ['int'],
'HaruPage::getLineWidth' => ['float'],
'HaruPage::getMiterLimit' => ['float'],
'HaruPage::getRGBFill' => ['array'],
'HaruPage::getRGBStroke' => ['array'],
'HaruPage::getStrokingColorSpace' => ['int'],
'HaruPage::getTextLeading' => ['float'],
'HaruPage::getTextMatrix' => ['array'],
'HaruPage::getTextRenderingMode' => ['int'],
'HaruPage::getTextRise' => ['float'],
'HaruPage::getTextWidth' => ['float', 'text'=>'string'],
'HaruPage::getTransMatrix' => ['array'],
'HaruPage::getWidth' => ['float'],
'HaruPage::getWordSpace' => ['float'],
'HaruPage::lineTo' => ['bool', 'x'=>'float', 'y'=>'float'],
'HaruPage::measureText' => ['int', 'text'=>'string', 'width'=>'float', 'wordwrap='=>'bool'],
'HaruPage::moveTextPos' => ['bool', 'x'=>'float', 'y'=>'float', 'set_leading='=>'bool'],
'HaruPage::moveTo' => ['bool', 'x'=>'float', 'y'=>'float'],
'HaruPage::moveToNextLine' => ['bool'],
'HaruPage::rectangle' => ['bool', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'HaruPage::setCharSpace' => ['bool', 'char_space'=>'float'],
'HaruPage::setCMYKFill' => ['bool', 'c'=>'float', 'm'=>'float', 'y'=>'float', 'k'=>'float'],
'HaruPage::setCMYKStroke' => ['bool', 'c'=>'float', 'm'=>'float', 'y'=>'float', 'k'=>'float'],
'HaruPage::setDash' => ['bool', 'pattern'=>'array', 'phase'=>'int'],
'HaruPage::setFlatness' => ['bool', 'flatness'=>'float'],
'HaruPage::setFontAndSize' => ['bool', 'font'=>'object', 'size'=>'float'],
'HaruPage::setGrayFill' => ['bool', 'value'=>'float'],
'HaruPage::setGrayStroke' => ['bool', 'value'=>'float'],
'HaruPage::setHeight' => ['bool', 'height'=>'float'],
'HaruPage::setHorizontalScaling' => ['bool', 'scaling'=>'float'],
'HaruPage::setLineCap' => ['bool', 'cap'=>'int'],
'HaruPage::setLineJoin' => ['bool', 'join'=>'int'],
'HaruPage::setLineWidth' => ['bool', 'width'=>'float'],
'HaruPage::setMiterLimit' => ['bool', 'limit'=>'float'],
'HaruPage::setRGBFill' => ['bool', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'HaruPage::setRGBStroke' => ['bool', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'HaruPage::setRotate' => ['bool', 'angle'=>'int'],
'HaruPage::setSize' => ['bool', 'size'=>'int', 'direction'=>'int'],
'HaruPage::setSlideShow' => ['bool', 'type'=>'int', 'disp_time'=>'float', 'trans_time'=>'float'],
'HaruPage::setTextLeading' => ['bool', 'text_leading'=>'float'],
'HaruPage::setTextMatrix' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'HaruPage::setTextRenderingMode' => ['bool', 'mode'=>'int'],
'HaruPage::setTextRise' => ['bool', 'rise'=>'float'],
'HaruPage::setWidth' => ['bool', 'width'=>'float'],
'HaruPage::setWordSpace' => ['bool', 'word_space'=>'float'],
'HaruPage::showText' => ['bool', 'text'=>'string'],
'HaruPage::showTextNextLine' => ['bool', 'text'=>'string', 'word_space='=>'float', 'char_space='=>'float'],
'HaruPage::stroke' => ['bool', 'close_path='=>'bool'],
'HaruPage::textOut' => ['bool', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'HaruPage::textRect' => ['bool', 'left'=>'float', 'top'=>'float', 'right'=>'float', 'bottom'=>'float', 'text'=>'string', 'align='=>'int'],
'hash' => ['string', 'algo'=>'string', 'data'=>'string', 'raw_output='=>'bool'],
'hash_algos' => ['array'],
'hash_copy' => ['HashContext', 'context'=>'HashContext|resource'],
'hash_equals' => ['bool', 'known_string'=>'string', 'user_string'=>'string'],
'hash_file' => ['string', 'algo'=>'string', 'filename'=>'string', 'raw_output='=>'bool'],
'hash_final' => ['string', 'context'=>'HashContext|resource', 'raw_output='=>'bool'],
'hash_hkdf' => ['string|false', 'algo'=>'string', 'ikm'=>'string', 'length='=>'int', 'info='=>'string', 'salt='=>'string'],
'hash_hmac' => ['string', 'algo'=>'string', 'data'=>'string', 'key'=>'string', 'raw_output='=>'bool'],
'hash_hmac_algos' => ['array<int,string>'],
'hash_hmac_file' => ['string', 'algo'=>'string', 'filename'=>'string', 'key'=>'string', 'raw_output='=>'bool'],
'hash_init' => ['HashContext', 'algo'=>'string', 'options='=>'int', 'key='=>'string'],
'hash_pbkdf2' => ['string', 'algo'=>'string', 'password'=>'string', 'salt'=>'string', 'iterations'=>'int', 'length='=>'int', 'raw_output='=>'bool'],
'hash_update' => ['bool', 'context'=>'HashContext', 'data'=>'string'],
'hash_update_file' => ['bool', 'context'=>'HashContext', 'filename'=>'string', 'scontext='=>'?HashContext'],
'hash_update_stream' => ['int', 'context'=>'HashContext', 'handle'=>'resource', 'length='=>'int'],
'hashTableObj::clear' => ['void'],
'hashTableObj::get' => ['string', 'key'=>'string'],
'hashTableObj::nextkey' => ['string', 'previousKey'=>'string'],
'hashTableObj::remove' => ['int', 'key'=>'string'],
'hashTableObj::set' => ['int', 'key'=>'string', 'value'=>'string'],
'header' => ['void', 'header'=>'string', 'replace='=>'bool', 'http_response_code='=>'int'],
'header_register_callback' => ['bool', 'callback'=>'callable():void'],
'header_remove' => ['void', 'name='=>'string'],
'headers_list' => ['array<int,string>'],
'headers_sent' => ['bool', '&w_file='=>'string', '&w_line='=>'int'],
'hebrev' => ['string', 'str'=>'string', 'max_chars_per_line='=>'int'],
'hebrevc' => ['string', 'str'=>'string', 'max_chars_per_line='=>'int'],
'hex2bin' => ['string|false', 'data'=>'string'],
'hexdec' => ['int|float', 'hexadecimal_number'=>'string'],
'highlight_file' => ['string|bool', 'file_name'=>'string', 'return='=>'bool'],
'highlight_string' => ['string|bool', 'string'=>'string', 'return='=>'bool'],
'hrtime' => ['array{0:int,1:int}|false', 'get_as_number='=>'false'],
'hrtime\'1' => ['int|float|false', 'get_as_number='=>'true'],
'HRTime\PerformanceCounter::getElapsedTicks' => ['int'],
'HRTime\PerformanceCounter::getFrequency' => ['int'],
'HRTime\PerformanceCounter::getLastElapsedTicks' => ['int'],
'HRTime\PerformanceCounter::getTicks' => ['int'],
'HRTime\PerformanceCounter::getTicksSince' => ['int', 'start'=>'int'],
'HRTime\PerformanceCounter::isRunning' => ['bool'],
'HRTime\PerformanceCounter::start' => ['void'],
'HRTime\PerformanceCounter::stop' => ['void'],
'HRTime\StopWatch::getElapsedTicks' => ['int'],
'HRTime\StopWatch::getElapsedTime' => ['float', 'unit='=>'int'],
'HRTime\StopWatch::getLastElapsedTicks' => ['int'],
'HRTime\StopWatch::getLastElapsedTime' => ['float', 'unit='=>'int'],
'HRTime\StopWatch::isRunning' => ['bool'],
'HRTime\StopWatch::start' => ['void'],
'HRTime\StopWatch::stop' => ['void'],
'html_entity_decode' => ['string', 'string'=>'string', 'quote_style='=>'int', 'encoding='=>'string'],
'htmlentities' => ['string', 'string'=>'string', 'quote_style='=>'int', 'encoding='=>'string', 'double_encode='=>'bool'],
'htmlspecialchars' => ['string', 'string'=>'string', 'quote_style='=>'int', 'encoding='=>'string', 'double_encode='=>'bool'],
'htmlspecialchars_decode' => ['string', 'string'=>'string', 'quote_style='=>'int'],
'http\Client::__construct' => ['void', 'driver='=>'string', 'persistent_handle_id='=>'string'],
'http\Client::addCookies' => ['http\Client', 'cookies='=>'?array'],
'http\Client::addSslOptions' => ['http\Client', 'ssl_options='=>'?array'],
'http\Client::attach' => ['void', 'observer'=>'SplObserver'],
'http\Client::configure' => ['http\Client', 'settings'=>'array'],
'http\Client::count' => ['int'],
'http\Client::dequeue' => ['http\Client', 'request'=>'http\Client\Request'],
'http\Client::detach' => ['void', 'observer'=>'SplObserver'],
'http\Client::enableEvents' => ['http\Client', 'enable='=>'mixed'],
'http\Client::enablePipelining' => ['http\Client', 'enable='=>'mixed'],
'http\Client::enqueue' => ['http\Client', 'request'=>'http\Client\Request', 'callable='=>'mixed'],
'http\Client::getAvailableConfiguration' => ['array'],
'http\Client::getAvailableDrivers' => ['array'],
'http\Client::getAvailableOptions' => ['array'],
'http\Client::getCookies' => ['array'],
'http\Client::getHistory' => ['http\Message'],
'http\Client::getObservers' => ['SplObjectStorage'],
'http\Client::getOptions' => ['array'],
'http\Client::getProgressInfo' => ['null|object', 'request'=>'http\Client\Request'],
'http\Client::getResponse' => ['http\Client\Response|null', 'request='=>'?http\Client\Request'],
'http\Client::getSslOptions' => ['array'],
'http\Client::getTransferInfo' => ['object', 'request'=>'http\Client\Request'],
'http\Client::notify' => ['void', 'request='=>'?http\Client\Request'],
'http\Client::once' => ['bool'],
'http\Client::requeue' => ['http\Client', 'request'=>'http\Client\Request', 'callable='=>'mixed'],
'http\Client::reset' => ['http\Client'],
'http\Client::send' => ['http\Client'],
'http\Client::setCookies' => ['http\Client', 'cookies='=>'?array'],
'http\Client::setDebug' => ['http\Client', 'callback'=>'callable'],
'http\Client::setOptions' => ['http\Client', 'options='=>'?array'],
'http\Client::setSslOptions' => ['http\Client', 'ssl_option='=>'?array'],
'http\Client::wait' => ['bool', 'timeout='=>'mixed'],
'http\Client\Curl\User::init' => ['', 'run'=>'callable'],
'http\Client\Curl\User::once' => [''],
'http\Client\Curl\User::send' => [''],
'http\Client\Curl\User::socket' => ['', 'socket'=>'resource', 'action'=>'int'],
'http\Client\Curl\User::timer' => ['', 'timeout_ms'=>'int'],
'http\Client\Curl\User::wait' => ['', 'timeout_ms='=>'mixed'],
'http\Client\Request::__construct' => ['void', 'method='=>'mixed', 'url='=>'mixed', 'headers='=>'?array', 'body='=>'?http\Message\Body'],
'http\Client\Request::__toString' => ['string'],
'http\Client\Request::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Request::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Client\Request::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Client\Request::addQuery' => ['http\Client\Request', 'query_data'=>'mixed'],
'http\Client\Request::addSslOptions' => ['http\Client\Request', 'ssl_options='=>'?array'],
'http\Client\Request::count' => ['int'],
'http\Client\Request::current' => ['mixed'],
'http\Client\Request::detach' => ['http\Message'],
'http\Client\Request::getBody' => ['http\Message\Body'],
'http\Client\Request::getContentType' => ['null|string'],
'http\Client\Request::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Client\Request::getHeaders' => ['array'],
'http\Client\Request::getHttpVersion' => ['string'],
'http\Client\Request::getInfo' => ['null|string'],
'http\Client\Request::getOptions' => ['array'],
'http\Client\Request::getParentMessage' => ['http\Message'],
'http\Client\Request::getQuery' => ['null|string'],
'http\Client\Request::getRequestMethod' => ['false|string'],
'http\Client\Request::getRequestUrl' => ['false|string'],
'http\Client\Request::getResponseCode' => ['false|int'],
'http\Client\Request::getResponseStatus' => ['false|string'],
'http\Client\Request::getSslOptions' => ['array'],
'http\Client\Request::getType' => ['int'],
'http\Client\Request::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Client\Request::key' => ['int|string'],
'http\Client\Request::next' => ['void'],
'http\Client\Request::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Client\Request::reverse' => ['http\Message'],
'http\Client\Request::rewind' => ['void'],
'http\Client\Request::serialize' => ['string'],
'http\Client\Request::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Request::setContentType' => ['http\Client\Request', 'content_type'=>'string'],
'http\Client\Request::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Client\Request::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Client\Request::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Client\Request::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Client\Request::setOptions' => ['http\Client\Request', 'options='=>'?array'],
'http\Client\Request::setQuery' => ['http\Client\Request', 'query_data='=>'mixed'],
'http\Client\Request::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Client\Request::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Client\Request::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Client\Request::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Client\Request::setSslOptions' => ['http\Client\Request', 'ssl_options='=>'?array'],
'http\Client\Request::setType' => ['http\Message', 'type'=>'int'],
'http\Client\Request::splitMultipartBody' => ['http\Message'],
'http\Client\Request::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Client\Request::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Client\Request::toString' => ['string', 'include_parent='=>'mixed'],
'http\Client\Request::unserialize' => ['void', 'serialized'=>'string'],
'http\Client\Request::valid' => ['bool'],
'http\Client\Response::__construct' => ['Iterator'],
'http\Client\Response::__toString' => ['string'],
'http\Client\Response::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Response::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Client\Response::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Client\Response::count' => ['int'],
'http\Client\Response::current' => ['mixed'],
'http\Client\Response::detach' => ['http\Message'],
'http\Client\Response::getBody' => ['http\Message\Body'],
'http\Client\Response::getCookies' => ['array', 'flags='=>'mixed', 'allowed_extras='=>'mixed'],
'http\Client\Response::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Client\Response::getHeaders' => ['array'],
'http\Client\Response::getHttpVersion' => ['string'],
'http\Client\Response::getInfo' => ['null|string'],
'http\Client\Response::getParentMessage' => ['http\Message'],
'http\Client\Response::getRequestMethod' => ['false|string'],
'http\Client\Response::getRequestUrl' => ['false|string'],
'http\Client\Response::getResponseCode' => ['false|int'],
'http\Client\Response::getResponseStatus' => ['false|string'],
'http\Client\Response::getTransferInfo' => ['mixed|object', 'element='=>'mixed'],
'http\Client\Response::getType' => ['int'],
'http\Client\Response::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Client\Response::key' => ['int|string'],
'http\Client\Response::next' => ['void'],
'http\Client\Response::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Client\Response::reverse' => ['http\Message'],
'http\Client\Response::rewind' => ['void'],
'http\Client\Response::serialize' => ['string'],
'http\Client\Response::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Client\Response::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Client\Response::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Client\Response::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Client\Response::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Client\Response::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Client\Response::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Client\Response::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Client\Response::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Client\Response::setType' => ['http\Message', 'type'=>'int'],
'http\Client\Response::splitMultipartBody' => ['http\Message'],
'http\Client\Response::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Client\Response::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Client\Response::toString' => ['string', 'include_parent='=>'mixed'],
'http\Client\Response::unserialize' => ['void', 'serialized'=>'string'],
'http\Client\Response::valid' => ['bool'],
'http\Cookie::__construct' => ['void', 'cookie_string='=>'mixed', 'parser_flags='=>'int', 'allowed_extras='=>'array'],
'http\Cookie::__toString' => ['string'],
'http\Cookie::addCookie' => ['http\Cookie', 'cookie_name'=>'string', 'cookie_value'=>'string'],
'http\Cookie::addCookies' => ['http\Cookie', 'cookies'=>'array'],
'http\Cookie::addExtra' => ['http\Cookie', 'extra_name'=>'string', 'extra_value'=>'string'],
'http\Cookie::addExtras' => ['http\Cookie', 'extras'=>'array'],
'http\Cookie::getCookie' => ['null|string', 'name'=>'string'],
'http\Cookie::getCookies' => ['array'],
'http\Cookie::getDomain' => ['string'],
'http\Cookie::getExpires' => ['int'],
'http\Cookie::getExtra' => ['string', 'name'=>'string'],
'http\Cookie::getExtras' => ['array'],
'http\Cookie::getFlags' => ['int'],
'http\Cookie::getMaxAge' => ['int'],
'http\Cookie::getPath' => ['string'],
'http\Cookie::setCookie' => ['http\Cookie', 'cookie_name'=>'string', 'cookie_value='=>'mixed'],
'http\Cookie::setCookies' => ['http\Cookie', 'cookies='=>'mixed'],
'http\Cookie::setDomain' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setExpires' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setExtra' => ['http\Cookie', 'extra_name'=>'string', 'extra_value='=>'mixed'],
'http\Cookie::setExtras' => ['http\Cookie', 'extras='=>'mixed'],
'http\Cookie::setFlags' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setMaxAge' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::setPath' => ['http\Cookie', 'value='=>'mixed'],
'http\Cookie::toArray' => ['array'],
'http\Cookie::toString' => ['string'],
'http\Encoding\Stream::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream::done' => ['bool'],
'http\Encoding\Stream::finish' => ['string'],
'http\Encoding\Stream::flush' => ['string'],
'http\Encoding\Stream::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Debrotli::__construct' => ['void', 'flags='=>'int'],
'http\Encoding\Stream\Debrotli::decode' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Debrotli::done' => ['bool'],
'http\Encoding\Stream\Debrotli::finish' => ['string'],
'http\Encoding\Stream\Debrotli::flush' => ['string'],
'http\Encoding\Stream\Debrotli::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Dechunk::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Dechunk::decode' => ['false|string', 'data'=>'string', '&decoded_len='=>'mixed'],
'http\Encoding\Stream\Dechunk::done' => ['bool'],
'http\Encoding\Stream\Dechunk::finish' => ['string'],
'http\Encoding\Stream\Dechunk::flush' => ['string'],
'http\Encoding\Stream\Dechunk::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Deflate::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Deflate::done' => ['bool'],
'http\Encoding\Stream\Deflate::encode' => ['string', 'data'=>'string', 'flags='=>'mixed'],
'http\Encoding\Stream\Deflate::finish' => ['string'],
'http\Encoding\Stream\Deflate::flush' => ['string'],
'http\Encoding\Stream\Deflate::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Enbrotli::__construct' => ['void', 'flags='=>'int'],
'http\Encoding\Stream\Enbrotli::done' => ['bool'],
'http\Encoding\Stream\Enbrotli::encode' => ['string', 'data'=>'string', 'flags='=>'int'],
'http\Encoding\Stream\Enbrotli::finish' => ['string'],
'http\Encoding\Stream\Enbrotli::flush' => ['string'],
'http\Encoding\Stream\Enbrotli::update' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Inflate::__construct' => ['void', 'flags='=>'mixed'],
'http\Encoding\Stream\Inflate::decode' => ['string', 'data'=>'string'],
'http\Encoding\Stream\Inflate::done' => ['bool'],
'http\Encoding\Stream\Inflate::finish' => ['string'],
'http\Encoding\Stream\Inflate::flush' => ['string'],
'http\Encoding\Stream\Inflate::update' => ['string', 'data'=>'string'],
'http\Env::getRequestBody' => ['http\Message\Body', 'body_class_name='=>'mixed'],
'http\Env::getRequestHeader' => ['array|null|string', 'header_name='=>'mixed'],
'http\Env::getResponseCode' => ['int'],
'http\Env::getResponseHeader' => ['array|null|string', 'header_name='=>'mixed'],
'http\Env::getResponseStatusForAllCodes' => ['array'],
'http\Env::getResponseStatusForCode' => ['string', 'code'=>'int'],
'http\Env::negotiate' => ['null|string', 'params'=>'string', 'supported'=>'array', 'primary_type_separator='=>'mixed', '&result_array='=>'mixed'],
'http\Env::negotiateCharset' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateContentType' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateEncoding' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::negotiateLanguage' => ['null|string', 'supported'=>'array', '&result_array='=>'mixed'],
'http\Env::setResponseCode' => ['bool', 'code'=>'int'],
'http\Env::setResponseHeader' => ['bool', 'header_name'=>'string', 'header_value='=>'mixed', 'response_code='=>'mixed', 'replace_header='=>'mixed'],
'http\Env\Request::__construct' => ['void'],
'http\Env\Request::__toString' => ['string'],
'http\Env\Request::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Request::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Env\Request::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Env\Request::count' => ['int'],
'http\Env\Request::current' => ['mixed'],
'http\Env\Request::detach' => ['http\Message'],
'http\Env\Request::getBody' => ['http\Message\Body'],
'http\Env\Request::getCookie' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getFiles' => ['array'],
'http\Env\Request::getForm' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Env\Request::getHeaders' => ['array'],
'http\Env\Request::getHttpVersion' => ['string'],
'http\Env\Request::getInfo' => ['null|string'],
'http\Env\Request::getParentMessage' => ['http\Message'],
'http\Env\Request::getQuery' => ['mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'http\Env\Request::getRequestMethod' => ['false|string'],
'http\Env\Request::getRequestUrl' => ['false|string'],
'http\Env\Request::getResponseCode' => ['false|int'],
'http\Env\Request::getResponseStatus' => ['false|string'],
'http\Env\Request::getType' => ['int'],
'http\Env\Request::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Env\Request::key' => ['int|string'],
'http\Env\Request::next' => ['void'],
'http\Env\Request::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Env\Request::reverse' => ['http\Message'],
'http\Env\Request::rewind' => ['void'],
'http\Env\Request::serialize' => ['string'],
'http\Env\Request::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Request::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Env\Request::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Env\Request::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Env\Request::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Env\Request::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Env\Request::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Env\Request::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Env\Request::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Env\Request::setType' => ['http\Message', 'type'=>'int'],
'http\Env\Request::splitMultipartBody' => ['http\Message'],
'http\Env\Request::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Env\Request::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Env\Request::toString' => ['string', 'include_parent='=>'mixed'],
'http\Env\Request::unserialize' => ['void', 'serialized'=>'string'],
'http\Env\Request::valid' => ['bool'],
'http\Env\Response::__construct' => ['void'],
'http\Env\Response::__invoke' => ['bool', 'data'=>'string', 'ob_flags='=>'int'],
'http\Env\Response::__toString' => ['string'],
'http\Env\Response::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Response::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Env\Response::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Env\Response::count' => ['int'],
'http\Env\Response::current' => ['mixed'],
'http\Env\Response::detach' => ['http\Message'],
'http\Env\Response::getBody' => ['http\Message\Body'],
'http\Env\Response::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Env\Response::getHeaders' => ['array'],
'http\Env\Response::getHttpVersion' => ['string'],
'http\Env\Response::getInfo' => ['?string'],
'http\Env\Response::getParentMessage' => ['http\Message'],
'http\Env\Response::getRequestMethod' => ['false|string'],
'http\Env\Response::getRequestUrl' => ['false|string'],
'http\Env\Response::getResponseCode' => ['false|int'],
'http\Env\Response::getResponseStatus' => ['false|string'],
'http\Env\Response::getType' => ['int'],
'http\Env\Response::isCachedByETag' => ['int', 'header_name='=>'string'],
'http\Env\Response::isCachedByLastModified' => ['int', 'header_name='=>'string'],
'http\Env\Response::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Env\Response::key' => ['int|string'],
'http\Env\Response::next' => ['void'],
'http\Env\Response::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Env\Response::reverse' => ['http\Message'],
'http\Env\Response::rewind' => ['void'],
'http\Env\Response::send' => ['bool', 'stream='=>'resource'],
'http\Env\Response::serialize' => ['string'],
'http\Env\Response::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Env\Response::setCacheControl' => ['http\Env\Response', 'cache_control'=>'string'],
'http\Env\Response::setContentDisposition' => ['http\Env\Response', 'disposition_params'=>'array'],
'http\Env\Response::setContentEncoding' => ['http\Env\Response', 'content_encoding'=>'int'],
'http\Env\Response::setContentType' => ['http\Env\Response', 'content_type'=>'string'],
'http\Env\Response::setCookie' => ['http\Env\Response', 'cookie'=>'mixed'],
'http\Env\Response::setEnvRequest' => ['http\Env\Response', 'env_request'=>'http\Message'],
'http\Env\Response::setEtag' => ['http\Env\Response', 'etag'=>'string'],
'http\Env\Response::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Env\Response::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Env\Response::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Env\Response::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Env\Response::setLastModified' => ['http\Env\Response', 'last_modified'=>'int'],
'http\Env\Response::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Env\Response::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Env\Response::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Env\Response::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Env\Response::setThrottleRate' => ['http\Env\Response', 'chunk_size'=>'int', 'delay='=>'float|int'],
'http\Env\Response::setType' => ['http\Message', 'type'=>'int'],
'http\Env\Response::splitMultipartBody' => ['http\Message'],
'http\Env\Response::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Env\Response::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Env\Response::toString' => ['string', 'include_parent='=>'mixed'],
'http\Env\Response::unserialize' => ['void', 'serialized'=>'string'],
'http\Env\Response::valid' => ['bool'],
'http\Header::__construct' => ['void', 'name='=>'mixed', 'value='=>'mixed'],
'http\Header::__toString' => ['string'],
'http\Header::getParams' => ['http\Params', 'param_sep='=>'mixed', 'arg_sep='=>'mixed', 'val_sep='=>'mixed', 'flags='=>'mixed'],
'http\Header::match' => ['bool', 'value'=>'string', 'flags='=>'mixed'],
'http\Header::negotiate' => ['null|string', 'supported'=>'array', '&result='=>'mixed'],
'http\Header::parse' => ['array|false', 'string'=>'string', 'header_class='=>'mixed'],
'http\Header::serialize' => ['string'],
'http\Header::toString' => ['string'],
'http\Header::unserialize' => ['void', 'serialized'=>'string'],
'http\Header\Parser::getState' => ['int'],
'http\Header\Parser::parse' => ['int', 'data'=>'string', 'flags'=>'int', '&headers'=>'array'],
'http\Header\Parser::stream' => ['int', 'stream'=>'resource', 'flags'=>'int', '&headers'=>'array'],
'http\Message::__construct' => ['void', 'message='=>'mixed', 'greedy='=>'bool'],
'http\Message::__toString' => ['string'],
'http\Message::addBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Message::addHeader' => ['http\Message', 'header'=>'string', 'value'=>'mixed'],
'http\Message::addHeaders' => ['http\Message', 'headers'=>'array', 'append='=>'mixed'],
'http\Message::count' => ['int'],
'http\Message::current' => ['mixed'],
'http\Message::detach' => ['http\Message'],
'http\Message::getBody' => ['http\Message\Body'],
'http\Message::getHeader' => ['http\Header|mixed', 'header'=>'string', 'into_class='=>'mixed'],
'http\Message::getHeaders' => ['array'],
'http\Message::getHttpVersion' => ['string'],
'http\Message::getInfo' => ['null|string'],
'http\Message::getParentMessage' => ['http\Message'],
'http\Message::getRequestMethod' => ['false|string'],
'http\Message::getRequestUrl' => ['false|string'],
'http\Message::getResponseCode' => ['false|int'],
'http\Message::getResponseStatus' => ['false|string'],
'http\Message::getType' => ['int'],
'http\Message::isMultipart' => ['bool', '&boundary='=>'mixed'],
'http\Message::key' => ['int|string'],
'http\Message::next' => ['void'],
'http\Message::prepend' => ['http\Message', 'message'=>'http\Message', 'top='=>'mixed'],
'http\Message::reverse' => ['http\Message'],
'http\Message::rewind' => ['void'],
'http\Message::serialize' => ['string'],
'http\Message::setBody' => ['http\Message', 'body'=>'http\Message\Body'],
'http\Message::setHeader' => ['http\Message', 'header'=>'string', 'value='=>'mixed'],
'http\Message::setHeaders' => ['http\Message', 'headers'=>'array'],
'http\Message::setHttpVersion' => ['http\Message', 'http_version'=>'string'],
'http\Message::setInfo' => ['http\Message', 'http_info'=>'string'],
'http\Message::setRequestMethod' => ['http\Message', 'request_method'=>'string'],
'http\Message::setRequestUrl' => ['http\Message', 'url'=>'string'],
'http\Message::setResponseCode' => ['http\Message', 'response_code'=>'int', 'strict='=>'mixed'],
'http\Message::setResponseStatus' => ['http\Message', 'response_status'=>'string'],
'http\Message::setType' => ['http\Message', 'type'=>'int'],
'http\Message::splitMultipartBody' => ['http\Message'],
'http\Message::toCallback' => ['http\Message', 'callback'=>'callable'],
'http\Message::toStream' => ['http\Message', 'stream'=>'resource'],
'http\Message::toString' => ['string', 'include_parent='=>'mixed'],
'http\Message::unserialize' => ['void', 'serialized'=>'string'],
'http\Message::valid' => ['bool'],
'http\Message\Body::__construct' => ['void', 'stream='=>'resource'],
'http\Message\Body::__toString' => ['string'],
'http\Message\Body::addForm' => ['http\Message\Body', 'fields='=>'?array', 'files='=>'?array'],
'http\Message\Body::addPart' => ['http\Message\Body', 'message'=>'http\Message'],
'http\Message\Body::append' => ['http\Message\Body', 'string'=>'string'],
'http\Message\Body::etag' => ['false|string'],
'http\Message\Body::getBoundary' => ['null|string'],
'http\Message\Body::getResource' => ['resource'],
'http\Message\Body::serialize' => ['string'],
'http\Message\Body::stat' => ['int|object', 'field='=>'mixed'],
'http\Message\Body::toCallback' => ['http\Message\Body', 'callback'=>'callable', 'offset='=>'mixed', 'maxlen='=>'mixed'],
'http\Message\Body::toStream' => ['http\Message\Body', 'stream'=>'resource', 'offset='=>'mixed', 'maxlen='=>'mixed'],
'http\Message\Body::toString' => ['string'],
'http\Message\Body::unserialize' => ['void', 'serialized'=>'string'],
'http\Message\Parser::getState' => ['int'],
'http\Message\Parser::parse' => ['int', 'data'=>'string', 'flags'=>'int', '&message'=>'http\Message'],
'http\Message\Parser::stream' => ['int', 'stream'=>'resource', 'flags'=>'int', '&message'=>'http\Message'],
'http\Params::__construct' => ['void', 'params='=>'mixed', 'param_sep='=>'mixed', 'arg_sep='=>'mixed', 'val_sep='=>'mixed', 'flags='=>'mixed'],
'http\Params::__toString' => ['string'],
'http\Params::offsetExists' => ['bool', 'name'=>'mixed'],
'http\Params::offsetGet' => ['mixed', 'name'=>'mixed'],
'http\Params::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'http\Params::offsetUnset' => ['void', 'name'=>'mixed'],
'http\Params::toArray' => ['array'],
'http\Params::toString' => ['string'],
'http\QueryString::__construct' => ['void', 'querystring'=>'string'],
'http\QueryString::__toString' => ['string'],
'http\QueryString::get' => ['http\QueryString|string|mixed', 'name='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getArray' => ['array|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getBool' => ['bool|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getFloat' => ['float|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getGlobalInstance' => ['http\QueryString'],
'http\QueryString::getInt' => ['int|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getIterator' => ['IteratorAggregate'],
'http\QueryString::getObject' => ['object|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::getString' => ['string|mixed', 'name'=>'string', 'defval='=>'mixed', 'delete='=>'bool|false'],
'http\QueryString::mod' => ['http\QueryString', 'params='=>'mixed'],
'http\QueryString::offsetExists' => ['bool', 'offset'=>'mixed'],
'http\QueryString::offsetGet' => ['mixed|null', 'offset'=>'mixed'],
'http\QueryString::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'http\QueryString::offsetUnset' => ['void', 'offset'=>'mixed'],
'http\QueryString::serialize' => ['string'],
'http\QueryString::set' => ['http\QueryString', 'params'=>'mixed'],
'http\QueryString::toArray' => ['array'],
'http\QueryString::toString' => ['string'],
'http\QueryString::unserialize' => ['void', 'serialized'=>'string'],
'http\QueryString::xlate' => ['http\QueryString'],
'http\Url::__construct' => ['void', 'old_url='=>'mixed', 'new_url='=>'mixed', 'flags='=>'int'],
'http\Url::__toString' => ['string'],
'http\Url::mod' => ['http\Url', 'parts'=>'mixed', 'flags='=>'float|int|mixed'],
'http\Url::toArray' => ['string[]'],
'http\Url::toString' => ['string'],
'http_build_cookie' => ['string', 'cookie'=>'array'],
'http_build_query' => ['string', 'querydata'=>'array|object', 'prefix='=>'string', 'arg_separator='=>'string', 'enc_type='=>'int'],
'http_build_str' => ['string', 'query'=>'array', 'prefix='=>'?string', 'arg_separator='=>'string'],
'http_build_url' => ['string', 'url='=>'string|array', 'parts='=>'string|array', 'flags='=>'int', 'new_url='=>'array'],
'http_cache_etag' => ['bool', 'etag='=>'string'],
'http_cache_last_modified' => ['bool', 'timestamp_or_expires='=>'int'],
'http_chunked_decode' => ['string|false', 'encoded'=>'string'],
'http_date' => ['string', 'timestamp='=>'int'],
'http_deflate' => ['?string', 'data'=>'string', 'flags='=>'int'],
'http_get' => ['string', 'url'=>'string', 'options='=>'array', 'info='=>'array'],
'http_get_request_body' => ['?string'],
'http_get_request_body_stream' => ['?resource'],
'http_get_request_headers' => ['array'],
'http_head' => ['string', 'url'=>'string', 'options='=>'array', 'info='=>'array'],
'http_inflate' => ['?string', 'data'=>'string'],
'http_match_etag' => ['bool', 'etag'=>'string', 'for_range='=>'bool'],
'http_match_modified' => ['bool', 'timestamp='=>'int', 'for_range='=>'bool'],
'http_match_request_header' => ['bool', 'header'=>'string', 'value'=>'string', 'match_case='=>'bool'],
'http_negotiate_charset' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_negotiate_content_type' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_negotiate_language' => ['string', 'supported'=>'array', 'result='=>'array'],
'http_parse_cookie' => ['stdClass|false', 'cookie'=>'string', 'flags='=>'int', 'allowed_extras='=>'array'],
'http_parse_headers' => ['array|false', 'header'=>'string'],
'http_parse_message' => ['object', 'message'=>'string'],
'http_parse_params' => ['stdClass', 'param'=>'string', 'flags='=>'int'],
'http_persistent_handles_clean' => ['string', 'ident='=>'string'],
'http_persistent_handles_count' => ['stdClass|false'],
'http_persistent_handles_ident' => ['string|false', 'ident='=>'string'],
'http_post_data' => ['string', 'url'=>'string', 'data'=>'string', 'options='=>'array', 'info='=>'array'],
'http_post_fields' => ['string', 'url'=>'string', 'data'=>'array', 'files='=>'array', 'options='=>'array', 'info='=>'array'],
'http_put_data' => ['string', 'url'=>'string', 'data'=>'string', 'options='=>'array', 'info='=>'array'],
'http_put_file' => ['string', 'url'=>'string', 'file'=>'string', 'options='=>'array', 'info='=>'array'],
'http_put_stream' => ['string', 'url'=>'string', 'stream'=>'resource', 'options='=>'array', 'info='=>'array'],
'http_redirect' => ['int|false', 'url='=>'string', 'params='=>'array', 'session='=>'bool', 'status='=>'int'],
'http_request' => ['string', 'method'=>'int', 'url'=>'string', 'body='=>'string', 'options='=>'array', 'info='=>'array'],
'http_request_body_encode' => ['string|false', 'fields'=>'array', 'files'=>'array'],
'http_request_method_exists' => ['bool', 'method'=>'mixed'],
'http_request_method_name' => ['string|false', 'method'=>'int'],
'http_request_method_register' => ['int|false', 'method'=>'string'],
'http_request_method_unregister' => ['bool', 'method'=>'mixed'],
'http_response_code' => ['int|bool', 'response_code='=>'int'],
'http_send_content_disposition' => ['bool', 'filename'=>'string', 'inline='=>'bool'],
'http_send_content_type' => ['bool', 'content_type='=>'string'],
'http_send_data' => ['bool', 'data'=>'string'],
'http_send_file' => ['bool', 'file'=>'string'],
'http_send_last_modified' => ['bool', 'timestamp='=>'int'],
'http_send_status' => ['bool', 'status'=>'int'],
'http_send_stream' => ['bool', 'stream'=>'resource'],
'http_support' => ['int', 'feature='=>'int'],
'http_throttle' => ['void', 'sec'=>'float', 'bytes='=>'int'],
'HttpDeflateStream::__construct' => ['void', 'flags='=>'int'],
'HttpDeflateStream::factory' => ['HttpDeflateStream', 'flags='=>'int', 'class_name='=>'string'],
'HttpDeflateStream::finish' => ['string', 'data='=>'string'],
'HttpDeflateStream::flush' => ['string|false', 'data='=>'string'],
'HttpDeflateStream::update' => ['string|false', 'data'=>'string'],
'HttpInflateStream::__construct' => ['void', 'flags='=>'int'],
'HttpInflateStream::factory' => ['HttpInflateStream', 'flags='=>'int', 'class_name='=>'string'],
'HttpInflateStream::finish' => ['string', 'data='=>'string'],
'HttpInflateStream::flush' => ['string|false', 'data='=>'string'],
'HttpInflateStream::update' => ['string|false', 'data'=>'string'],
'HttpMessage::__construct' => ['void', 'message='=>'string'],
'HttpMessage::__toString' => ['string'],
'HttpMessage::addHeaders' => ['void', 'headers'=>'array', 'append='=>'bool'],
'HttpMessage::count' => ['int'],
'HttpMessage::current' => ['mixed'],
'HttpMessage::detach' => ['HttpMessage'],
'HttpMessage::factory' => ['?HttpMessage', 'raw_message='=>'string', 'class_name='=>'string'],
'HttpMessage::fromEnv' => ['?HttpMessage', 'message_type'=>'int', 'class_name='=>'string'],
'HttpMessage::fromString' => ['?HttpMessage', 'raw_message='=>'string', 'class_name='=>'string'],
'HttpMessage::getBody' => ['string'],
'HttpMessage::getHeader' => ['?string', 'header'=>'string'],
'HttpMessage::getHeaders' => ['array'],
'HttpMessage::getHttpVersion' => ['string'],
'HttpMessage::getInfo' => [''],
'HttpMessage::getParentMessage' => ['HttpMessage'],
'HttpMessage::getRequestMethod' => ['string|false'],
'HttpMessage::getRequestUrl' => ['string|false'],
'HttpMessage::getResponseCode' => ['int'],
'HttpMessage::getResponseStatus' => ['string'],
'HttpMessage::getType' => ['int'],
'HttpMessage::guessContentType' => ['string|false', 'magic_file'=>'string', 'magic_mode='=>'int'],
'HttpMessage::key' => ['int|string'],
'HttpMessage::next' => ['void'],
'HttpMessage::prepend' => ['void', 'message'=>'HttpMessage', 'top='=>'bool'],
'HttpMessage::reverse' => ['HttpMessage'],
'HttpMessage::rewind' => ['void'],
'HttpMessage::send' => ['bool'],
'HttpMessage::serialize' => ['string'],
'HttpMessage::setBody' => ['void', 'body'=>'string'],
'HttpMessage::setHeaders' => ['void', 'headers'=>'array'],
'HttpMessage::setHttpVersion' => ['bool', 'version'=>'string'],
'HttpMessage::setInfo' => ['', 'http_info'=>''],
'HttpMessage::setRequestMethod' => ['bool', 'method'=>'string'],
'HttpMessage::setRequestUrl' => ['bool', 'url'=>'string'],
'HttpMessage::setResponseCode' => ['bool', 'code'=>'int'],
'HttpMessage::setResponseStatus' => ['bool', 'status'=>'string'],
'HttpMessage::setType' => ['void', 'type'=>'int'],
'HttpMessage::toMessageTypeObject' => ['HttpRequest|HttpResponse|null'],
'HttpMessage::toString' => ['string', 'include_parent='=>'bool'],
'HttpMessage::unserialize' => ['void', 'serialized'=>'string'],
'HttpMessage::valid' => ['bool'],
'HttpQueryString::__construct' => ['void', 'global='=>'bool', 'add='=>'mixed'],
'HttpQueryString::__toString' => ['string'],
'HttpQueryString::factory' => ['', 'global'=>'', 'params'=>'', 'class_name'=>''],
'HttpQueryString::get' => ['mixed', 'key='=>'string', 'type='=>'mixed', 'defval='=>'mixed', 'delete='=>'bool'],
'HttpQueryString::getArray' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getBool' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getFloat' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getInt' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getObject' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::getString' => ['', 'name'=>'', 'defval'=>'', 'delete'=>''],
'HttpQueryString::mod' => ['HttpQueryString', 'params'=>'mixed'],
'HttpQueryString::offsetExists' => ['bool', 'offset'=>'mixed'],
'HttpQueryString::offsetGet' => ['mixed', 'offset'=>'mixed'],
'HttpQueryString::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'HttpQueryString::offsetUnset' => ['void', 'offset'=>'mixed'],
'HttpQueryString::serialize' => ['string'],
'HttpQueryString::set' => ['string', 'params'=>'mixed'],
'HttpQueryString::singleton' => ['HttpQueryString', 'global='=>'bool'],
'HttpQueryString::toArray' => ['array'],
'HttpQueryString::toString' => ['string'],
'HttpQueryString::unserialize' => ['void', 'serialized'=>'string'],
'HttpQueryString::xlate' => ['bool', 'ie'=>'string', 'oe'=>'string'],
'HttpRequest::__construct' => ['void', 'url='=>'string', 'request_method='=>'int', 'options='=>'array'],
'HttpRequest::addBody' => ['', 'request_body_data'=>''],
'HttpRequest::addCookies' => ['bool', 'cookies'=>'array'],
'HttpRequest::addHeaders' => ['bool', 'headers'=>'array'],
'HttpRequest::addPostFields' => ['bool', 'post_data'=>'array'],
'HttpRequest::addPostFile' => ['bool', 'name'=>'string', 'file'=>'string', 'content_type='=>'string'],
'HttpRequest::addPutData' => ['bool', 'put_data'=>'string'],
'HttpRequest::addQueryData' => ['bool', 'query_params'=>'array'],
'HttpRequest::addRawPostData' => ['bool', 'raw_post_data'=>'string'],
'HttpRequest::addSslOptions' => ['bool', 'options'=>'array'],
'HttpRequest::clearHistory' => ['void'],
'HttpRequest::enableCookies' => ['bool'],
'HttpRequest::encodeBody' => ['', 'fields'=>'', 'files'=>''],
'HttpRequest::factory' => ['', 'url'=>'', 'method'=>'', 'options'=>'', 'class_name'=>''],
'HttpRequest::flushCookies' => [''],
'HttpRequest::get' => ['', 'url'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::getBody' => [''],
'HttpRequest::getContentType' => ['string'],
'HttpRequest::getCookies' => ['array'],
'HttpRequest::getHeaders' => ['array'],
'HttpRequest::getHistory' => ['HttpMessage'],
'HttpRequest::getMethod' => ['int'],
'HttpRequest::getOptions' => ['array'],
'HttpRequest::getPostFields' => ['array'],
'HttpRequest::getPostFiles' => ['array'],
'HttpRequest::getPutData' => ['string'],
'HttpRequest::getPutFile' => ['string'],
'HttpRequest::getQueryData' => ['string'],
'HttpRequest::getRawPostData' => ['string'],
'HttpRequest::getRawRequestMessage' => ['string'],
'HttpRequest::getRawResponseMessage' => ['string'],
'HttpRequest::getRequestMessage' => ['HttpMessage'],
'HttpRequest::getResponseBody' => ['string'],
'HttpRequest::getResponseCode' => ['int'],
'HttpRequest::getResponseCookies' => ['stdClass[]', 'flags='=>'int', 'allowed_extras='=>'array'],
'HttpRequest::getResponseData' => ['array'],
'HttpRequest::getResponseHeader' => ['mixed', 'name='=>'string'],
'HttpRequest::getResponseInfo' => ['mixed', 'name='=>'string'],
'HttpRequest::getResponseMessage' => ['HttpMessage'],
'HttpRequest::getResponseStatus' => ['string'],
'HttpRequest::getSslOptions' => ['array'],
'HttpRequest::getUrl' => ['string'],
'HttpRequest::head' => ['', 'url'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::methodExists' => ['', 'method'=>''],
'HttpRequest::methodName' => ['', 'method_id'=>''],
'HttpRequest::methodRegister' => ['', 'method_name'=>''],
'HttpRequest::methodUnregister' => ['', 'method'=>''],
'HttpRequest::postData' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::postFields' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putData' => ['', 'url'=>'', 'data'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putFile' => ['', 'url'=>'', 'file'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::putStream' => ['', 'url'=>'', 'stream'=>'', 'options'=>'', '&info'=>''],
'HttpRequest::resetCookies' => ['bool', 'session_only='=>'bool'],
'HttpRequest::send' => ['HttpMessage'],
'HttpRequest::setBody' => ['bool', 'request_body_data='=>'string'],
'HttpRequest::setContentType' => ['bool', 'content_type'=>'string'],
'HttpRequest::setCookies' => ['bool', 'cookies='=>'array'],
'HttpRequest::setHeaders' => ['bool', 'headers='=>'array'],
'HttpRequest::setMethod' => ['bool', 'request_method'=>'int'],
'HttpRequest::setOptions' => ['bool', 'options='=>'array'],
'HttpRequest::setPostFields' => ['bool', 'post_data'=>'array'],
'HttpRequest::setPostFiles' => ['bool', 'post_files'=>'array'],
'HttpRequest::setPutData' => ['bool', 'put_data='=>'string'],
'HttpRequest::setPutFile' => ['bool', 'file='=>'string'],
'HttpRequest::setQueryData' => ['bool', 'query_data'=>'mixed'],
'HttpRequest::setRawPostData' => ['bool', 'raw_post_data='=>'string'],
'HttpRequest::setSslOptions' => ['bool', 'options='=>'array'],
'HttpRequest::setUrl' => ['bool', 'url'=>'string'],
'HttpRequestDataShare::__construct' => ['void'],
'HttpRequestDataShare::__destruct' => ['void'],
'HttpRequestDataShare::attach' => ['', 'request'=>'HttpRequest'],
'HttpRequestDataShare::count' => ['int'],
'HttpRequestDataShare::detach' => ['', 'request'=>'HttpRequest'],
'HttpRequestDataShare::factory' => ['', 'global'=>'', 'class_name'=>''],
'HttpRequestDataShare::reset' => [''],
'HttpRequestDataShare::singleton' => ['', 'global'=>''],
'HttpRequestPool::__construct' => ['void', 'request='=>'HttpRequest'],
'HttpRequestPool::__destruct' => ['void'],
'HttpRequestPool::attach' => ['bool', 'request'=>'HttpRequest'],
'HttpRequestPool::count' => ['int'],
'HttpRequestPool::current' => ['mixed'],
'HttpRequestPool::detach' => ['bool', 'request'=>'HttpRequest'],
'HttpRequestPool::enableEvents' => ['', 'enable'=>''],
'HttpRequestPool::enablePipelining' => ['', 'enable'=>''],
'HttpRequestPool::getAttachedRequests' => ['array'],
'HttpRequestPool::getFinishedRequests' => ['array'],
'HttpRequestPool::key' => ['int|string'],
'HttpRequestPool::next' => ['void'],
'HttpRequestPool::reset' => ['void'],
'HttpRequestPool::rewind' => ['void'],
'HttpRequestPool::send' => ['bool'],
'HttpRequestPool::socketPerform' => ['bool'],
'HttpRequestPool::socketSelect' => ['bool', 'timeout='=>'float'],
'HttpRequestPool::valid' => ['bool'],
'HttpResponse::capture' => ['void'],
'HttpResponse::getBufferSize' => ['int'],
'HttpResponse::getCache' => ['bool'],
'HttpResponse::getCacheControl' => ['string'],
'HttpResponse::getContentDisposition' => ['string'],
'HttpResponse::getContentType' => ['string'],
'HttpResponse::getData' => ['string'],
'HttpResponse::getETag' => ['string'],
'HttpResponse::getFile' => ['string'],
'HttpResponse::getGzip' => ['bool'],
'HttpResponse::getHeader' => ['mixed', 'name='=>'string'],
'HttpResponse::getLastModified' => ['int'],
'HttpResponse::getRequestBody' => ['string'],
'HttpResponse::getRequestBodyStream' => ['resource'],
'HttpResponse::getRequestHeaders' => ['array'],
'HttpResponse::getStream' => ['resource'],
'HttpResponse::getThrottleDelay' => ['float'],
'HttpResponse::guessContentType' => ['string|false', 'magic_file'=>'string', 'magic_mode='=>'int'],
'HttpResponse::redirect' => ['void', 'url='=>'string', 'params='=>'array', 'session='=>'bool', 'status='=>'int'],
'HttpResponse::send' => ['bool', 'clean_ob='=>'bool'],
'HttpResponse::setBufferSize' => ['bool', 'bytes'=>'int'],
'HttpResponse::setCache' => ['bool', 'cache'=>'bool'],
'HttpResponse::setCacheControl' => ['bool', 'control'=>'string', 'max_age='=>'int', 'must_revalidate='=>'bool'],
'HttpResponse::setContentDisposition' => ['bool', 'filename'=>'string', 'inline='=>'bool'],
'HttpResponse::setContentType' => ['bool', 'content_type'=>'string'],
'HttpResponse::setData' => ['bool', 'data'=>'mixed'],
'HttpResponse::setETag' => ['bool', 'etag'=>'string'],
'HttpResponse::setFile' => ['bool', 'file'=>'string'],
'HttpResponse::setGzip' => ['bool', 'gzip'=>'bool'],
'HttpResponse::setHeader' => ['bool', 'name'=>'string', 'value='=>'mixed', 'replace='=>'bool'],
'HttpResponse::setLastModified' => ['bool', 'timestamp'=>'int'],
'HttpResponse::setStream' => ['bool', 'stream'=>'resource'],
'HttpResponse::setThrottleDelay' => ['bool', 'seconds'=>'float'],
'HttpResponse::status' => ['bool', 'status'=>'int'],
'HttpUtil::buildCookie' => ['', 'cookie_array'=>''],
'HttpUtil::buildStr' => ['', 'query'=>'', 'prefix'=>'', 'arg_sep'=>''],
'HttpUtil::buildUrl' => ['', 'url'=>'', 'parts'=>'', 'flags'=>'', '&composed'=>''],
'HttpUtil::chunkedDecode' => ['', 'encoded_string'=>''],
'HttpUtil::date' => ['', 'timestamp'=>''],
'HttpUtil::deflate' => ['', 'plain'=>'', 'flags'=>''],
'HttpUtil::inflate' => ['', 'encoded'=>''],
'HttpUtil::matchEtag' => ['', 'plain_etag'=>'', 'for_range'=>''],
'HttpUtil::matchModified' => ['', 'last_modified'=>'', 'for_range'=>''],
'HttpUtil::matchRequestHeader' => ['', 'header_name'=>'', 'header_value'=>'', 'case_sensitive'=>''],
'HttpUtil::negotiateCharset' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::negotiateContentType' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::negotiateLanguage' => ['', 'supported'=>'', '&result'=>''],
'HttpUtil::parseCookie' => ['', 'cookie_string'=>''],
'HttpUtil::parseHeaders' => ['', 'headers_string'=>''],
'HttpUtil::parseMessage' => ['', 'message_string'=>''],
'HttpUtil::parseParams' => ['', 'param_string'=>'', 'flags'=>''],
'HttpUtil::support' => ['', 'feature'=>''],
'hw_api::checkin' => ['bool', 'parameter'=>'array'],
'hw_api::checkout' => ['bool', 'parameter'=>'array'],
'hw_api::children' => ['array', 'parameter'=>'array'],
'hw_api::content' => ['HW_API_Content', 'parameter'=>'array'],
'hw_api::copy' => ['hw_api_content', 'parameter'=>'array'],
'hw_api::dbstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::dcstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::dstanchors' => ['array', 'parameter'=>'array'],
'hw_api::dstofsrcanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::find' => ['array', 'parameter'=>'array'],
'hw_api::ftstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::hwstat' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::identify' => ['bool', 'parameter'=>'array'],
'hw_api::info' => ['array', 'parameter'=>'array'],
'hw_api::insert' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertcollection' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::insertdocument' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::link' => ['bool', 'parameter'=>'array'],
'hw_api::lock' => ['bool', 'parameter'=>'array'],
'hw_api::move' => ['bool', 'parameter'=>'array'],
'hw_api::object' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::objectbyanchor' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::parents' => ['array', 'parameter'=>'array'],
'hw_api::remove' => ['bool', 'parameter'=>'array'],
'hw_api::replace' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::setcommittedversion' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::srcanchors' => ['array', 'parameter'=>'array'],
'hw_api::srcsofdst' => ['array', 'parameter'=>'array'],
'hw_api::unlock' => ['bool', 'parameter'=>'array'],
'hw_api::user' => ['hw_api_object', 'parameter'=>'array'],
'hw_api::userlist' => ['array', 'parameter'=>'array'],
'hw_api_attribute' => ['HW_API_Attribute', 'name='=>'string', 'value='=>'string'],
'hw_api_attribute::key' => ['string'],
'hw_api_attribute::langdepvalue' => ['string', 'language'=>'string'],
'hw_api_attribute::value' => ['string'],
'hw_api_attribute::values' => ['array'],
'hw_api_content' => ['HW_API_Content', 'content'=>'string', 'mimetype'=>'string'],
'hw_api_content::mimetype' => ['string'],
'hw_api_content::read' => ['string', 'buffer'=>'string', 'len'=>'int'],
'hw_api_error::count' => ['int'],
'hw_api_error::reason' => ['HW_API_Reason'],
'hw_api_object' => ['hw_api_object', 'parameter'=>'array'],
'hw_api_object::assign' => ['bool', 'parameter'=>'array'],
'hw_api_object::attreditable' => ['bool', 'parameter'=>'array'],
'hw_api_object::count' => ['int', 'parameter'=>'array'],
'hw_api_object::insert' => ['bool', 'attribute'=>'hw_api_attribute'],
'hw_api_object::remove' => ['bool', 'name'=>'string'],
'hw_api_object::title' => ['string', 'parameter'=>'array'],
'hw_api_object::value' => ['string', 'name'=>'string'],
'hw_api_reason::description' => ['string'],
'hw_api_reason::type' => ['HW_API_Reason'],
'hw_Array2Objrec' => ['string', 'object_array'=>'array'],
'hw_changeobject' => ['bool', 'link'=>'int', 'objid'=>'int', 'attributes'=>'array'],
'hw_Children' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_ChildrenObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_Close' => ['bool', 'connection'=>'int'],
'hw_Connect' => ['int', 'host'=>'string', 'port'=>'int', 'username='=>'string', 'password='=>'string'],
'hw_connection_info' => ['', 'link'=>'int'],
'hw_cp' => ['int', 'connection'=>'int', 'object_id_array'=>'array', 'destination_id'=>'int'],
'hw_Deleteobject' => ['bool', 'connection'=>'int', 'object_to_delete'=>'int'],
'hw_DocByAnchor' => ['int', 'connection'=>'int', 'anchorid'=>'int'],
'hw_DocByAnchorObj' => ['string', 'connection'=>'int', 'anchorid'=>'int'],
'hw_Document_Attributes' => ['string', 'hw_document'=>'int'],
'hw_Document_BodyTag' => ['string', 'hw_document'=>'int', 'prefix='=>'string'],
'hw_Document_Content' => ['string', 'hw_document'=>'int'],
'hw_Document_SetContent' => ['bool', 'hw_document'=>'int', 'content'=>'string'],
'hw_Document_Size' => ['int', 'hw_document'=>'int'],
'hw_dummy' => ['string', 'link'=>'int', 'id'=>'int', 'msgid'=>'int'],
'hw_EditText' => ['bool', 'connection'=>'int', 'hw_document'=>'int'],
'hw_Error' => ['int', 'connection'=>'int'],
'hw_ErrorMsg' => ['string', 'connection'=>'int'],
'hw_Free_Document' => ['bool', 'hw_document'=>'int'],
'hw_GetAnchors' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetAnchorsObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetAndLock' => ['string', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildColl' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildDocColl' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetChildDocCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetObject' => ['', 'connection'=>'int', 'objectid'=>'', 'query='=>'string'],
'hw_GetObjectByQuery' => ['array', 'connection'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryColl' => ['array', 'connection'=>'int', 'objectid'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryCollObj' => ['array', 'connection'=>'int', 'objectid'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetObjectByQueryObj' => ['array', 'connection'=>'int', 'query'=>'string', 'max_hits'=>'int'],
'hw_GetParents' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetParentsObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_getrellink' => ['string', 'link'=>'int', 'rootid'=>'int', 'sourceid'=>'int', 'destid'=>'int'],
'hw_GetRemote' => ['int', 'connection'=>'int', 'objectid'=>'int'],
'hw_getremotechildren' => ['', 'connection'=>'int', 'object_record'=>'string'],
'hw_GetSrcByDestObj' => ['array', 'connection'=>'int', 'objectid'=>'int'],
'hw_GetText' => ['int', 'connection'=>'int', 'objectid'=>'int', 'prefix='=>''],
'hw_getusername' => ['string', 'connection'=>'int'],
'hw_Identify' => ['string', 'link'=>'int', 'username'=>'string', 'password'=>'string'],
'hw_InCollections' => ['array', 'connection'=>'int', 'object_id_array'=>'array', 'collection_id_array'=>'array', 'return_collections'=>'int'],
'hw_Info' => ['string', 'connection'=>'int'],
'hw_InsColl' => ['int', 'connection'=>'int', 'objectid'=>'int', 'object_array'=>'array'],
'hw_InsDoc' => ['int', 'connection'=>'', 'parentid'=>'int', 'object_record'=>'string', 'text='=>'string'],
'hw_insertanchors' => ['bool', 'hwdoc'=>'int', 'anchorecs'=>'array', 'dest'=>'array', 'urlprefixes='=>'array'],
'hw_InsertDocument' => ['int', 'connection'=>'int', 'parent_id'=>'int', 'hw_document'=>'int'],
'hw_InsertObject' => ['int', 'connection'=>'int', 'object_rec'=>'string', 'parameter'=>'string'],
'hw_mapid' => ['int', 'connection'=>'int', 'server_id'=>'int', 'object_id'=>'int'],
'hw_Modifyobject' => ['bool', 'connection'=>'int', 'object_to_change'=>'int', 'remove'=>'array', 'add'=>'array', 'mode='=>'int'],
'hw_mv' => ['int', 'connection'=>'int', 'object_id_array'=>'array', 'source_id'=>'int', 'destination_id'=>'int'],
'hw_New_Document' => ['int', 'object_record'=>'string', 'document_data'=>'string', 'document_size'=>'int'],
'hw_objrec2array' => ['array', 'object_record'=>'string', 'format='=>'array'],
'hw_Output_Document' => ['bool', 'hw_document'=>'int'],
'hw_pConnect' => ['int', 'host'=>'string', 'port'=>'int', 'username='=>'string', 'password='=>'string'],
'hw_PipeDocument' => ['int', 'connection'=>'int', 'objectid'=>'int', 'url_prefixes='=>'array'],
'hw_Root' => ['int'],
'hw_setlinkroot' => ['int', 'link'=>'int', 'rootid'=>'int'],
'hw_stat' => ['string', 'link'=>'int'],
'hw_Unlock' => ['bool', 'connection'=>'int', 'objectid'=>'int'],
'hw_Who' => ['array', 'connection'=>'int'],
'hwapi_attribute_new' => ['HW_API_Attribute', 'name='=>'string', 'value='=>'string'],
'hwapi_content_new' => ['HW_API_Content', 'content'=>'string', 'mimetype'=>'string'],
'hwapi_hgcsp' => ['HW_API', 'hostname'=>'string', 'port='=>'int'],
'hwapi_object_new' => ['hw_api_object', 'parameter'=>'array'],
'hypot' => ['float', 'num1'=>'float', 'num2'=>'float'],
'ibase_add_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password'=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_affected_rows' => ['int', 'link_identifier='=>'resource'],
'ibase_backup' => ['mixed', 'service_handle'=>'resource', 'source_db'=>'string', 'dest_file'=>'string', 'options='=>'int', 'verbose='=>'bool'],
'ibase_blob_add' => ['void', 'blob_handle'=>'resource', 'data'=>'string'],
'ibase_blob_cancel' => ['bool', 'blob_handle'=>'resource'],
'ibase_blob_close' => ['string|bool', 'blob_handle'=>'resource'],
'ibase_blob_create' => ['resource', 'link_identifier='=>'resource'],
'ibase_blob_echo' => ['bool', 'link_identifier'=>'', 'blob_id'=>'string'],
'ibase_blob_echo\'1' => ['bool', 'blob_id'=>'string'],
'ibase_blob_get' => ['string|false', 'blob_handle'=>'resource', 'len'=>'int'],
'ibase_blob_import' => ['string|false', 'link_identifier'=>'resource', 'file_handle'=>'resource'],
'ibase_blob_info' => ['array', 'link_identifier'=>'resource', 'blob_id'=>'string'],
'ibase_blob_info\'1' => ['array', 'blob_id'=>'string'],
'ibase_blob_open' => ['resource', 'link_identifier'=>'resource', 'blob_id'=>'string'],
'ibase_blob_open\'1' => ['resource', 'blob_id'=>'string'],
'ibase_close' => ['bool', 'link_identifier='=>'resource'],
'ibase_commit' => ['bool', 'link_identifier='=>'resource'],
'ibase_commit_ret' => ['bool', 'link_identifier='=>'resource'],
'ibase_connect' => ['resource|false', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'charset='=>'string', 'buffers='=>'int', 'dialect='=>'int', 'role='=>'string'],
'ibase_db_info' => ['string', 'service_handle'=>'resource', 'db'=>'string', 'action'=>'int', 'argument='=>'int'],
'ibase_delete_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password='=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_drop_db' => ['bool', 'link_identifier='=>'resource'],
'ibase_errcode' => ['int|false'],
'ibase_errmsg' => ['string|false'],
'ibase_execute' => ['resource|false', 'query'=>'resource', 'bind_arg='=>'mixed', '...args='=>'mixed'],
'ibase_fetch_assoc' => ['array|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_fetch_object' => ['object|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_fetch_row' => ['array|false', 'result'=>'resource', 'fetch_flags='=>'int'],
'ibase_field_info' => ['array', 'query_result'=>'resource', 'field_number'=>'int'],
'ibase_free_event_handler' => ['bool', 'event'=>'resource'],
'ibase_free_query' => ['bool', 'query'=>'resource'],
'ibase_free_result' => ['bool', 'result'=>'resource'],
'ibase_gen_id' => ['int|string', 'generator'=>'string', 'increment='=>'int', 'link_identifier='=>'resource'],
'ibase_maintain_db' => ['bool', 'service_handle'=>'resource', 'db'=>'string', 'action'=>'int', 'argument='=>'int'],
'ibase_modify_user' => ['bool', 'service_handle'=>'resource', 'user_name'=>'string', 'password'=>'string', 'first_name='=>'string', 'middle_name='=>'string', 'last_name='=>'string'],
'ibase_name_result' => ['bool', 'result'=>'resource', 'name'=>'string'],
'ibase_num_fields' => ['int', 'query_result'=>'resource'],
'ibase_num_params' => ['int', 'query'=>'resource'],
'ibase_num_rows' => ['int', 'result_identifier'=>''],
'ibase_param_info' => ['array', 'query'=>'resource', 'field_number'=>'int'],
'ibase_pconnect' => ['resource|false', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'charset='=>'string', 'buffers='=>'int', 'dialect='=>'int', 'role='=>'string'],
'ibase_prepare' => ['resource|false', 'link_identifier'=>'', 'query'=>'string', 'trans_identifier'=>''],
'ibase_query' => ['resource|false', 'link_identifier='=>'resource', 'string='=>'string', 'bind_arg='=>'int', '...args='=>''],
'ibase_restore' => ['mixed', 'service_handle'=>'resource', 'source_file'=>'string', 'dest_db'=>'string', 'options='=>'int', 'verbose='=>'bool'],
'ibase_rollback' => ['bool', 'link_identifier='=>'resource'],
'ibase_rollback_ret' => ['bool', 'link_identifier='=>'resource'],
'ibase_server_info' => ['string', 'service_handle'=>'resource', 'action'=>'int'],
'ibase_service_attach' => ['resource', 'host'=>'string', 'dba_username'=>'string', 'dba_password'=>'string'],
'ibase_service_detach' => ['bool', 'service_handle'=>'resource'],
'ibase_set_event_handler' => ['resource', 'link_identifier'=>'', 'callback'=>'callable', 'event='=>'string', '...args='=>''],
'ibase_set_event_handler\'1' => ['resource', 'callback'=>'callable', 'event'=>'string', '...args'=>''],
'ibase_timefmt' => ['bool', 'format'=>'string', 'columntype='=>'int'],
'ibase_trans' => ['resource|false', 'trans_args='=>'int', 'link_identifier='=>'', '...args='=>''],
'ibase_wait_event' => ['string', 'link_identifier'=>'', 'event='=>'string', '...args='=>''],
'ibase_wait_event\'1' => ['string', 'event'=>'string', '...args'=>''],
'iconv' => ['string|false', 'in_charset'=>'string', 'out_charset'=>'string', 'str'=>'string'],
'iconv_get_encoding' => ['mixed', 'type='=>'string'],
'iconv_mime_decode' => ['string|false', 'encoded_string'=>'string', 'mode='=>'int', 'charset='=>'string'],
'iconv_mime_decode_headers' => ['array|false', 'headers'=>'string', 'mode='=>'int', 'charset='=>'string'],
'iconv_mime_encode' => ['string|false', 'field_name'=>'string', 'field_value'=>'string', 'preference='=>'array'],
'iconv_set_encoding' => ['bool', 'type'=>'string', 'charset'=>'string'],
'iconv_strlen' => ['int|false', 'str'=>'string', 'charset='=>'string'],
'iconv_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'charset='=>'string'],
'iconv_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'charset='=>'string'],
'iconv_substr' => ['string|false', 'str'=>'string', 'offset'=>'int', 'length='=>'int', 'charset='=>'string'],
'id3_get_frame_long_name' => ['string', 'frameid'=>'string'],
'id3_get_frame_short_name' => ['string', 'frameid'=>'string'],
'id3_get_genre_id' => ['int', 'genre'=>'string'],
'id3_get_genre_list' => ['array'],
'id3_get_genre_name' => ['string', 'genre_id'=>'int'],
'id3_get_tag' => ['array', 'filename'=>'string', 'version='=>'int'],
'id3_get_version' => ['int', 'filename'=>'string'],
'id3_remove_tag' => ['bool', 'filename'=>'string', 'version='=>'int'],
'id3_set_tag' => ['bool', 'filename'=>'string', 'tag'=>'array', 'version='=>'int'],
'idate' => ['int', 'format'=>'string', 'timestamp='=>'int'],
'idn_strerror' => ['string', 'errorcode'=>'int'],
'idn_to_ascii' => ['string|false', 'domain'=>'string', 'options='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'idn_to_utf8' => ['string|false', 'domain'=>'string', 'options='=>'int', 'variant='=>'int', '&w_idna_info='=>'array'],
'ifx_affected_rows' => ['int', 'result_id'=>'resource'],
'ifx_blobinfile_mode' => ['bool', 'mode'=>'int'],
'ifx_byteasvarchar' => ['bool', 'mode'=>'int'],
'ifx_close' => ['bool', 'link_identifier='=>'resource'],
'ifx_connect' => ['resource', 'database='=>'string', 'userid='=>'string', 'password='=>'string'],
'ifx_copy_blob' => ['int', 'bid'=>'int'],
'ifx_create_blob' => ['int', 'type'=>'int', 'mode'=>'int', 'param'=>'string'],
'ifx_create_char' => ['int', 'param'=>'string'],
'ifx_do' => ['bool', 'result_id'=>'resource'],
'ifx_error' => ['string', 'link_identifier='=>'resource'],
'ifx_errormsg' => ['string', 'errorcode='=>'int'],
'ifx_fetch_row' => ['array', 'result_id'=>'resource', 'position='=>'mixed'],
'ifx_fieldproperties' => ['array', 'result_id'=>'resource'],
'ifx_fieldtypes' => ['array', 'result_id'=>'resource'],
'ifx_free_blob' => ['bool', 'bid'=>'int'],
'ifx_free_char' => ['bool', 'bid'=>'int'],
'ifx_free_result' => ['bool', 'result_id'=>'resource'],
'ifx_get_blob' => ['string', 'bid'=>'int'],
'ifx_get_char' => ['string', 'bid'=>'int'],
'ifx_getsqlca' => ['array', 'result_id'=>'resource'],
'ifx_htmltbl_result' => ['int', 'result_id'=>'resource', 'html_table_options='=>'string'],
'ifx_nullformat' => ['bool', 'mode'=>'int'],
'ifx_num_fields' => ['int', 'result_id'=>'resource'],
'ifx_num_rows' => ['int', 'result_id'=>'resource'],
'ifx_pconnect' => ['resource', 'database='=>'string', 'userid='=>'string', 'password='=>'string'],
'ifx_prepare' => ['resource', 'query'=>'string', 'link_identifier'=>'resource', 'cursor_def='=>'int', 'blobidarray='=>'mixed'],
'ifx_query' => ['resource', 'query'=>'string', 'link_identifier'=>'resource', 'cursor_type='=>'int', 'blobidarray='=>'mixed'],
'ifx_textasvarchar' => ['bool', 'mode'=>'int'],
'ifx_update_blob' => ['bool', 'bid'=>'int', 'content'=>'string'],
'ifx_update_char' => ['bool', 'bid'=>'int', 'content'=>'string'],
'ifxus_close_slob' => ['bool', 'bid'=>'int'],
'ifxus_create_slob' => ['int', 'mode'=>'int'],
'ifxus_free_slob' => ['bool', 'bid'=>'int'],
'ifxus_open_slob' => ['int', 'bid'=>'int', 'mode'=>'int'],
'ifxus_read_slob' => ['string', 'bid'=>'int', 'nbytes'=>'int'],
'ifxus_seek_slob' => ['int', 'bid'=>'int', 'mode'=>'int', 'offset'=>'int'],
'ifxus_tell_slob' => ['int', 'bid'=>'int'],
'ifxus_write_slob' => ['int', 'bid'=>'int', 'content'=>'string'],
'igbinary_serialize' => ['string|false', 'value'=>'mixed'],
'igbinary_unserialize' => ['mixed', 'str'=>'string'],
'ignore_user_abort' => ['int', 'value='=>'bool'],
'iis_add_server' => ['int', 'path'=>'string', 'comment'=>'string', 'server_ip'=>'string', 'port'=>'int', 'host_name'=>'string', 'rights'=>'int', 'start_server'=>'int'],
'iis_get_dir_security' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string'],
'iis_get_script_map' => ['string', 'server_instance'=>'int', 'virtual_path'=>'string', 'script_extension'=>'string'],
'iis_get_server_by_comment' => ['int', 'comment'=>'string'],
'iis_get_server_by_path' => ['int', 'path'=>'string'],
'iis_get_server_rights' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string'],
'iis_get_service_state' => ['int', 'service_id'=>'string'],
'iis_remove_server' => ['int', 'server_instance'=>'int'],
'iis_set_app_settings' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'application_scope'=>'string'],
'iis_set_dir_security' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'directory_flags'=>'int'],
'iis_set_script_map' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'script_extension'=>'string', 'engine_path'=>'string', 'allow_scripting'=>'int'],
'iis_set_server_rights' => ['int', 'server_instance'=>'int', 'virtual_path'=>'string', 'directory_flags'=>'int'],
'iis_start_server' => ['int', 'server_instance'=>'int'],
'iis_start_service' => ['int', 'service_id'=>'string'],
'iis_stop_server' => ['int', 'server_instance'=>'int'],
'iis_stop_service' => ['int', 'service_id'=>'string'],
'image2wbmp' => ['bool', 'im'=>'resource', 'filename='=>'?string', 'threshold='=>'int'],
'image_type_to_extension' => ['string', 'imagetype'=>'int', 'include_dot='=>'bool'],
'image_type_to_mime_type' => ['string', 'imagetype'=>'int'],
'imageaffine' => ['resource|false', 'src'=>'resource', 'affine'=>'array', 'clip='=>'array'],
'imageaffineconcat' => ['array|false', 'm1'=>'array', 'm2'=>'array'],
'imageaffinematrixconcat' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'm1'=>'array', 'm2'=>'array'],
'imageaffinematrixget' => ['array{0:float,1:float,2:float,3:float,4:float,5:float}|false', 'type'=>'int', 'options'=>'array|float'],
'imagealphablending' => ['bool', 'im'=>'resource', 'on'=>'bool'],
'imageantialias' => ['bool', 'im'=>'resource', 'on'=>'bool'],
'imagearc' => ['bool', 'im'=>'resource', 'cx'=>'int', 'cy'=>'int', 'w'=>'int', 'h'=>'int', 's'=>'int', 'e'=>'int', 'col'=>'int'],
'imagebmp' => ['bool', 'image'=>'resource', 'to='=>'mixed', 'compressed='=>'bool'],
'imagechar' => ['bool', 'im'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'c'=>'string', 'col'=>'int'],
'imagecharup' => ['bool', 'im'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'c'=>'string', 'col'=>'int'],
'imagecolorallocate' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorallocatealpha' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorat' => ['int|false', 'im'=>'resource', 'x'=>'int', 'y'=>'int'],
'imagecolorclosest' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorclosestalpha' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorclosesthwb' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolordeallocate' => ['bool', 'im'=>'resource', 'index'=>'int'],
'imagecolorexact' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorexactalpha' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolormatch' => ['bool', 'im1'=>'resource', 'im2'=>'resource'],
'imagecolorresolve' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'imagecolorresolvealpha' => ['int|false', 'im'=>'resource', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha'=>'int'],
'imagecolorset' => ['void', 'im'=>'resource', 'col'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'imagecolorsforindex' => ['array|false', 'im'=>'resource', 'col'=>'int'],
'imagecolorstotal' => ['int|false', 'im'=>'resource'],
'imagecolortransparent' => ['int|false', 'im'=>'resource', 'col='=>'int'],
'imageconvolution' => ['bool', 'src_im'=>'resource', 'matrix3x3'=>'array', 'div'=>'float', 'offset'=>'float'],
'imagecopy' => ['bool', 'dst_im'=>'resource', 'src_im'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_w'=>'int', 'src_h'=>'int'],
'imagecopymerge' => ['bool', 'src_im'=>'resource', 'dst_im'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_w'=>'int', 'src_h'=>'int', 'pct'=>'int'],
'imagecopymergegray' => ['bool', 'src_im'=>'resource', 'dst_im'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'src_w'=>'int', 'src_h'=>'int', 'pct'=>'int'],
'imagecopyresampled' => ['bool', 'dst_im'=>'resource', 'src_im'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_w'=>'int', 'dst_h'=>'int', 'src_w'=>'int', 'src_h'=>'int'],
'imagecopyresized' => ['bool', 'dst_im'=>'resource', 'src_im'=>'resource', 'dst_x'=>'int', 'dst_y'=>'int', 'src_x'=>'int', 'src_y'=>'int', 'dst_w'=>'int', 'dst_h'=>'int', 'src_w'=>'int', 'src_h'=>'int'],
'imagecreate' => ['resource|false', 'x_size'=>'int', 'y_size'=>'int'],
'imagecreatefrombmp' => ['resource|false', 'filename'=>'string'],
'imagecreatefromgd' => ['resource|false', 'filename'=>'string'],
'imagecreatefromgd2' => ['resource|false', 'filename'=>'string'],
'imagecreatefromgd2part' => ['resource|false', 'filename'=>'string', 'srcx'=>'int', 'srcy'=>'int', 'width'=>'int', 'height'=>'int'],
'imagecreatefromgif' => ['resource|false', 'filename'=>'string'],
'imagecreatefromjpeg' => ['resource|false', 'filename'=>'string'],
'imagecreatefrompng' => ['resource|false', 'filename'=>'string'],
'imagecreatefromstring' => ['resource|false', 'image'=>'string'],
'imagecreatefromwbmp' => ['resource|false', 'filename'=>'string'],
'imagecreatefromwebp' => ['resource|false', 'filename'=>'string'],
'imagecreatefromxbm' => ['resource|false', 'filename'=>'string'],
'imagecreatefromxpm' => ['resource|false', 'filename'=>'string'],
'imagecreatetruecolor' => ['resource|false', 'x_size'=>'int', 'y_size'=>'int'],
'imagecrop' => ['resource|false', 'im'=>'resource', 'rect'=>'array'],
'imagecropauto' => ['resource|false', 'im'=>'resource', 'mode'=>'int', 'threshold'=>'float', 'color'=>'int'],
'imagedashedline' => ['bool', 'im'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'col'=>'int'],
'imagedestroy' => ['bool', 'im'=>'resource'],
'imageellipse' => ['bool', 'im'=>'resource', 'cx'=>'int', 'cy'=>'int', 'w'=>'int', 'h'=>'int', 'color'=>'int'],
'imagefill' => ['bool', 'im'=>'resource', 'x'=>'int', 'y'=>'int', 'col'=>'int'],
'imagefilledarc' => ['bool', 'im'=>'resource', 'cx'=>'int', 'cy'=>'int', 'w'=>'int', 'h'=>'int', 's'=>'int', 'e'=>'int', 'col'=>'int', 'style'=>'int'],
'imagefilledellipse' => ['bool', 'im'=>'resource', 'cx'=>'int', 'cy'=>'int', 'w'=>'int', 'h'=>'int', 'color'=>'int'],
'imagefilledpolygon' => ['bool', 'im'=>'resource', 'point'=>'array', 'num_points'=>'int', 'col'=>'int'],
'imagefilledrectangle' => ['bool', 'im'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'col'=>'int'],
'imagefilltoborder' => ['bool', 'im'=>'resource', 'x'=>'int', 'y'=>'int', 'border'=>'int', 'col'=>'int'],
'imagefilter' => ['bool', 'src_im'=>'resource', 'filtertype'=>'int', 'arg1='=>'int', 'arg2='=>'int', 'arg3='=>'int', 'arg4='=>'int'],
'imageflip' => ['bool', 'im'=>'resource', 'mode'=>'int'],
'imagefontheight' => ['int', 'font'=>'int'],
'imagefontwidth' => ['int', 'font'=>'int'],
'imageftbbox' => ['array|false', 'size'=>'float', 'angle'=>'float', 'font_file'=>'string', 'text'=>'string', 'extrainfo='=>'array'],
'imagefttext' => ['array|false', 'im'=>'resource', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'col'=>'int', 'font_file'=>'string', 'text'=>'string', 'extrainfo='=>'array'],
'imagegammacorrect' => ['bool', 'im'=>'resource', 'inputgamma'=>'float', 'outputgamma'=>'float'],
'imagegd' => ['bool', 'im'=>'resource', 'filename='=>'?string'],
'imagegd2' => ['bool', 'im'=>'resource', 'filename='=>'?string', 'chunk_size='=>'int', 'type='=>'int'],
'imagegetclip' => ['array|false', 'im'=>'resource'],
'imagegif' => ['bool', 'im'=>'resource', 'filename='=>'?string'],
'imagegrabscreen' => ['resource'],
'imagegrabwindow' => ['resource', 'window_handle'=>'int', 'client_area='=>'int'],
'imageinterlace' => ['int|false', 'im'=>'resource', 'interlace='=>'int'],
'imageistruecolor' => ['bool', 'im'=>'resource'],
'imagejpeg' => ['bool', 'im'=>'resource', 'filename='=>'?string', 'quality='=>'int'],
'imagelayereffect' => ['bool', 'im'=>'resource', 'effect'=>'int'],
'imageline' => ['bool', 'im'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'col'=>'int'],
'imageloadfont' => ['int|false', 'filename'=>'string'],
'imageObj::pasteImage' => ['void', 'srcImg'=>'imageObj', 'transparentColorHex'=>'int', 'dstX'=>'int', 'dstY'=>'int', 'angle'=>'int'],
'imageObj::saveImage' => ['int', 'filename'=>'string', 'oMap'=>'mapObj'],
'imageObj::saveWebImage' => ['string'],
'imageopenpolygon' => ['bool', 'image'=>'resource', 'points'=>'array', 'num_points'=>'int', 'color'=>'int'],
'imagepalettecopy' => ['void', 'dst'=>'resource', 'src'=>'resource'],
'imagepalettetotruecolor' => ['bool', 'src'=>'resource'],
'imagepng' => ['bool', 'im'=>'resource', 'filename='=>'?string|?resource', 'quality='=>'int', 'filters='=>'int'],
'imagepolygon' => ['bool', 'im'=>'resource', 'point'=>'array', 'num_points'=>'int', 'col'=>'int'],
'imagerectangle' => ['bool', 'im'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int', 'col'=>'int'],
'imageresolution' => ['array|bool', 'image'=>'resource', 'res_x='=>'int', 'res_y='=>'int'],
'imagerotate' => ['resource|false', 'src_im'=>'resource', 'angle'=>'float', 'bgdcolor'=>'int', 'ignoretransparent='=>'int'],
'imagesavealpha' => ['bool', 'im'=>'resource', 'on'=>'bool'],
'imagescale' => ['resource|false', 'im'=>'resource', 'new_width'=>'int', 'new_height='=>'int', 'method='=>'int'],
'imagesetbrush' => ['bool', 'image'=>'resource', 'brush'=>'resource'],
'imagesetclip' => ['bool', 'im'=>'resource', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int'],
'imagesetinterpolation' => ['bool', 'im'=>'resource', 'method'=>'int'],
'imagesetpixel' => ['bool', 'im'=>'resource', 'x'=>'int', 'y'=>'int', 'col'=>'int'],
'imagesetstyle' => ['bool', 'im'=>'resource', 'styles'=>'array'],
'imagesetthickness' => ['bool', 'im'=>'resource', 'thickness'=>'int'],
'imagesettile' => ['bool', 'image'=>'resource', 'tile'=>'resource'],
'imagestring' => ['bool', 'im'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'str'=>'string', 'col'=>'int'],
'imagestringup' => ['bool', 'im'=>'resource', 'font'=>'int', 'x'=>'int', 'y'=>'int', 'str'=>'string', 'col'=>'int'],
'imagesx' => ['int|false', 'im'=>'resource'],
'imagesy' => ['int|false', 'im'=>'resource'],
'imagetruecolortopalette' => ['bool', 'im'=>'resource', 'ditherflag'=>'bool', 'colorswanted'=>'int'],
'imagettfbbox' => ['false|array', 'size'=>'float', 'angle'=>'float', 'font_file'=>'string', 'text'=>'string'],
'imagettftext' => ['false|array', 'im'=>'resource', 'size'=>'float', 'angle'=>'float', 'x'=>'int', 'y'=>'int', 'col'=>'int', 'font_file'=>'string', 'text'=>'string'],
'imagetypes' => ['int'],
'imagewbmp' => ['bool', 'im'=>'resource', 'filename='=>'?string', 'foreground='=>'int'],
'imagewebp' => ['bool', 'im'=>'resource', 'filename='=>'?string', 'quality='=>'int'],
'imagexbm' => ['bool', 'im'=>'resource', 'filename'=>'?string', 'foreground='=>'int'],
'Imagick::__construct' => ['void', 'files='=>'string|string[]'],
'Imagick::__toString' => ['string'],
'Imagick::adaptiveBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::adaptiveResizeImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'bestfit='=>'bool'],
'Imagick::adaptiveSharpenImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::adaptiveThresholdImage' => ['bool', 'width'=>'int', 'height'=>'int', 'offset'=>'int'],
'Imagick::addImage' => ['bool', 'source'=>'imagick'],
'Imagick::addNoiseImage' => ['bool', 'noise_type'=>'int', 'channel='=>'int'],
'Imagick::affineTransformImage' => ['bool', 'matrix'=>'imagickdraw'],
'Imagick::animateImages' => ['bool', 'x_server'=>'string'],
'Imagick::annotateImage' => ['bool', 'draw_settings'=>'imagickdraw', 'x'=>'float', 'y'=>'float', 'angle'=>'float', 'text'=>'string'],
'Imagick::appendImages' => ['Imagick', 'stack'=>'bool'],
'Imagick::autoGammaImage' => ['bool', 'channel='=>'int'],
'Imagick::autoLevelImage' => ['void', 'CHANNEL='=>'string'],
'Imagick::autoOrient' => ['bool'],
'Imagick::averageImages' => ['Imagick'],
'Imagick::blackThresholdImage' => ['bool', 'threshold'=>'mixed'],
'Imagick::blueShiftImage' => ['void', 'factor='=>'float'],
'Imagick::blurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::borderImage' => ['bool', 'bordercolor'=>'mixed', 'width'=>'int', 'height'=>'int'],
'Imagick::brightnessContrastImage' => ['void', 'brightness'=>'string', 'contrast'=>'string', 'CHANNEL='=>'string'],
'Imagick::charcoalImage' => ['bool', 'radius'=>'float', 'sigma'=>'float'],
'Imagick::chopImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::clampImage' => ['void', 'CHANNEL='=>'string'],
'Imagick::clear' => ['bool'],
'Imagick::clipImage' => ['bool'],
'Imagick::clipImagePath' => ['void', 'pathname'=>'string', 'inside'=>'string'],
'Imagick::clipPathImage' => ['bool', 'pathname'=>'string', 'inside'=>'bool'],
'Imagick::clone' => ['Imagick'],
'Imagick::clutImage' => ['bool', 'lookup_table'=>'imagick', 'channel='=>'float'],
'Imagick::coalesceImages' => ['Imagick'],
'Imagick::colorFloodfillImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int'],
'Imagick::colorizeImage' => ['bool', 'colorize'=>'mixed', 'opacity'=>'mixed'],
'Imagick::colorMatrixImage' => ['void', 'color_matrix'=>'string'],
'Imagick::combineImages' => ['Imagick', 'channeltype'=>'int'],
'Imagick::commentImage' => ['bool', 'comment'=>'string'],
'Imagick::compareImageChannels' => ['array', 'image'=>'imagick', 'channeltype'=>'int', 'metrictype'=>'int'],
'Imagick::compareImageLayers' => ['Imagick', 'method'=>'int'],
'Imagick::compareImages' => ['array', 'compare'=>'imagick', 'metric'=>'int'],
'Imagick::compositeImage' => ['bool', 'composite_object'=>'imagick', 'composite'=>'int', 'x'=>'int', 'y'=>'int', 'channel='=>'int'],
'Imagick::compositeImageGravity' => ['bool', 'imagick'=>'Imagick', 'COMPOSITE_CONSTANT'=>'int', 'GRAVITY_CONSTANT'=>'int'],
'Imagick::contrastImage' => ['bool', 'sharpen'=>'bool'],
'Imagick::contrastStretchImage' => ['bool', 'black_point'=>'float', 'white_point'=>'float', 'channel='=>'int'],
'Imagick::convolveImage' => ['bool', 'kernel'=>'array', 'channel='=>'int'],
'Imagick::count' => ['void', 'mode='=>'string'],
'Imagick::cropImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::cropThumbnailImage' => ['bool', 'width'=>'int', 'height'=>'int'],
'Imagick::current' => ['Imagick'],
'Imagick::cycleColormapImage' => ['bool', 'displace'=>'int'],
'Imagick::decipherImage' => ['bool', 'passphrase'=>'string'],
'Imagick::deconstructImages' => ['Imagick'],
'Imagick::deleteImageArtifact' => ['bool', 'artifact'=>'string'],
'Imagick::deleteImageProperty' => ['void', 'name'=>'string'],
'Imagick::deskewImage' => ['bool', 'threshold'=>'float'],
'Imagick::despeckleImage' => ['bool'],
'Imagick::destroy' => ['bool'],
'Imagick::displayImage' => ['bool', 'servername'=>'string'],
'Imagick::displayImages' => ['bool', 'servername'=>'string'],
'Imagick::distortImage' => ['bool', 'method'=>'int', 'arguments'=>'array', 'bestfit'=>'bool'],
'Imagick::drawImage' => ['bool', 'draw'=>'imagickdraw'],
'Imagick::edgeImage' => ['bool', 'radius'=>'float'],
'Imagick::embossImage' => ['bool', 'radius'=>'float', 'sigma'=>'float'],
'Imagick::encipherImage' => ['bool', 'passphrase'=>'string'],
'Imagick::enhanceImage' => ['bool'],
'Imagick::equalizeImage' => ['bool'],
'Imagick::evaluateImage' => ['bool', 'op'=>'int', 'constant'=>'float', 'channel='=>'int'],
'Imagick::evaluateImages' => ['bool', 'EVALUATE_CONSTANT'=>'int'],
'Imagick::exportImagePixels' => ['array', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int', 'map'=>'string', 'storage'=>'int'],
'Imagick::extentImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::filter' => ['void', 'ImagickKernel'=>'ImagickKernel', 'CHANNEL='=>'int'],
'Imagick::flattenImages' => ['Imagick'],
'Imagick::flipImage' => ['bool'],
'Imagick::floodFillPaintImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'target'=>'mixed', 'x'=>'int', 'y'=>'int', 'invert'=>'bool', 'channel='=>'int'],
'Imagick::flopImage' => ['bool'],
'Imagick::forwardFourierTransformimage' => ['void', 'magnitude'=>'bool'],
'Imagick::frameImage' => ['bool', 'matte_color'=>'mixed', 'width'=>'int', 'height'=>'int', 'inner_bevel'=>'int', 'outer_bevel'=>'int'],
'Imagick::functionImage' => ['bool', 'function'=>'int', 'arguments'=>'array', 'channel='=>'int'],
'Imagick::fxImage' => ['Imagick', 'expression'=>'string', 'channel='=>'int'],
'Imagick::gammaImage' => ['bool', 'gamma'=>'float', 'channel='=>'int'],
'Imagick::gaussianBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::getColorspace' => ['int'],
'Imagick::getCompression' => ['int'],
'Imagick::getCompressionQuality' => ['int'],
'Imagick::getConfigureOptions' => ['string'],
'Imagick::getCopyright' => ['string'],
'Imagick::getFeatures' => ['string'],
'Imagick::getFilename' => ['string'],
'Imagick::getFont' => ['string|false'],
'Imagick::getFormat' => ['string'],
'Imagick::getGravity' => ['int'],
'Imagick::getHDRIEnabled' => ['int'],
'Imagick::getHomeURL' => ['string'],
'Imagick::getImage' => ['Imagick'],
'Imagick::getImageAlphaChannel' => ['int'],
'Imagick::getImageArtifact' => ['string', 'artifact'=>'string'],
'Imagick::getImageAttribute' => ['string', 'key'=>'string'],
'Imagick::getImageBackgroundColor' => ['ImagickPixel'],
'Imagick::getImageBlob' => ['string'],
'Imagick::getImageBluePrimary' => ['array'],
'Imagick::getImageBorderColor' => ['ImagickPixel'],
'Imagick::getImageChannelDepth' => ['int', 'channel'=>'int'],
'Imagick::getImageChannelDistortion' => ['float', 'reference'=>'imagick', 'channel'=>'int', 'metric'=>'int'],
'Imagick::getImageChannelDistortions' => ['float', 'reference'=>'imagick', 'metric'=>'int', 'channel='=>'int'],
'Imagick::getImageChannelExtrema' => ['array', 'channel'=>'int'],
'Imagick::getImageChannelKurtosis' => ['array', 'channel='=>'int'],
'Imagick::getImageChannelMean' => ['array', 'channel'=>'int'],
'Imagick::getImageChannelRange' => ['array', 'channel'=>'int'],
'Imagick::getImageChannelStatistics' => ['array'],
'Imagick::getImageClipMask' => ['Imagick'],
'Imagick::getImageColormapColor' => ['ImagickPixel', 'index'=>'int'],
'Imagick::getImageColors' => ['int'],
'Imagick::getImageColorspace' => ['int'],
'Imagick::getImageCompose' => ['int'],
'Imagick::getImageCompression' => ['int'],
'Imagick::getImageCompressionQuality' => ['int'],
'Imagick::getImageDelay' => ['int'],
'Imagick::getImageDepth' => ['int'],
'Imagick::getImageDispose' => ['int'],
'Imagick::getImageDistortion' => ['float', 'reference'=>'magickwand', 'metric'=>'int'],
'Imagick::getImageExtrema' => ['array'],
'Imagick::getImageFilename' => ['string'],
'Imagick::getImageFormat' => ['string'],
'Imagick::getImageGamma' => ['float'],
'Imagick::getImageGeometry' => ['array'],
'Imagick::getImageGravity' => ['int'],
'Imagick::getImageGreenPrimary' => ['array'],
'Imagick::getImageHeight' => ['int'],
'Imagick::getImageHistogram' => ['array'],
'Imagick::getImageIndex' => ['int'],
'Imagick::getImageInterlaceScheme' => ['int'],
'Imagick::getImageInterpolateMethod' => ['int'],
'Imagick::getImageIterations' => ['int'],
'Imagick::getImageLength' => ['int'],
'Imagick::getImageMagickLicense' => ['string'],
'Imagick::getImageMatte' => ['bool'],
'Imagick::getImageMatteColor' => ['ImagickPixel'],
'Imagick::getImageMimeType' => ['string'],
'Imagick::getImageOrientation' => ['int'],
'Imagick::getImagePage' => ['array'],
'Imagick::getImagePixelColor' => ['ImagickPixel', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageProfile' => ['string', 'name'=>'string'],
'Imagick::getImageProfiles' => ['array', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperties' => ['array', 'pattern='=>'string', 'only_names='=>'bool'],
'Imagick::getImageProperty' => ['string|false', 'name'=>'string'],
'Imagick::getImageRedPrimary' => ['array'],
'Imagick::getImageRegion' => ['Imagick', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::getImageRenderingIntent' => ['int'],
'Imagick::getImageResolution' => ['array'],
'Imagick::getImagesBlob' => ['string'],
'Imagick::getImageScene' => ['int'],
'Imagick::getImageSignature' => ['string'],
'Imagick::getImageSize' => ['int'],
'Imagick::getImageTicksPerSecond' => ['int'],
'Imagick::getImageTotalInkDensity' => ['float'],
'Imagick::getImageType' => ['int'],
'Imagick::getImageUnits' => ['int'],
'Imagick::getImageVirtualPixelMethod' => ['int'],
'Imagick::getImageWhitePoint' => ['array'],
'Imagick::getImageWidth' => ['int'],
'Imagick::getInterlaceScheme' => ['int'],
'Imagick::getIteratorIndex' => ['int'],
'Imagick::getNumberImages' => ['int'],
'Imagick::getOption' => ['string', 'key'=>'string'],
'Imagick::getPackageName' => ['string'],
'Imagick::getPage' => ['array'],
'Imagick::getPixelIterator' => ['ImagickPixelIterator'],
'Imagick::getPixelRegionIterator' => ['ImagickPixelIterator', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'Imagick::getPointSize' => ['float'],
'Imagick::getQuantum' => ['int'],
'Imagick::getQuantumDepth' => ['array'],
'Imagick::getQuantumRange' => ['array'],
'Imagick::getRegistry' => ['string|false', 'key'=>'string'],
'Imagick::getReleaseDate' => ['string'],
'Imagick::getResource' => ['int', 'type'=>'int'],
'Imagick::getResourceLimit' => ['int', 'type'=>'int'],
'Imagick::getSamplingFactors' => ['array'],
'Imagick::getSize' => ['array'],
'Imagick::getSizeOffset' => ['int'],
'Imagick::getVersion' => ['array'],
'Imagick::haldClutImage' => ['bool', 'clut'=>'imagick', 'channel='=>'int'],
'Imagick::hasNextImage' => ['bool'],
'Imagick::hasPreviousImage' => ['bool'],
'Imagick::identifyFormat' => ['string|false', 'embedText'=>'string'],
'Imagick::identifyImage' => ['array', 'appendrawoutput='=>'bool'],
'Imagick::identifyImageType' => ['int'],
'Imagick::implodeImage' => ['bool', 'radius'=>'float'],
'Imagick::importImagePixels' => ['bool', 'x'=>'int', 'y'=>'int', 'width'=>'int', 'height'=>'int', 'map'=>'string', 'storage'=>'int', 'pixels'=>'array'],
'Imagick::inverseFourierTransformImage' => ['void', 'complement'=>'string', 'magnitude'=>'string'],
'Imagick::key' => ['int|string'],
'Imagick::labelImage' => ['bool', 'label'=>'string'],
'Imagick::levelImage' => ['bool', 'blackpoint'=>'float', 'gamma'=>'float', 'whitepoint'=>'float', 'channel='=>'int'],
'Imagick::linearStretchImage' => ['bool', 'blackpoint'=>'float', 'whitepoint'=>'float'],
'Imagick::liquidRescaleImage' => ['bool', 'width'=>'int', 'height'=>'int', 'delta_x'=>'float', 'rigidity'=>'float'],
'Imagick::listRegistry' => ['array'],
'Imagick::localContrastImage' => ['bool', 'radius'=>'float', 'strength'=>'float'],
'Imagick::magnifyImage' => ['bool'],
'Imagick::mapImage' => ['bool', 'map'=>'imagick', 'dither'=>'bool'],
'Imagick::matteFloodfillImage' => ['bool', 'alpha'=>'float', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int'],
'Imagick::medianFilterImage' => ['bool', 'radius'=>'float'],
'Imagick::mergeImageLayers' => ['Imagick', 'layer_method'=>'int'],
'Imagick::minifyImage' => ['bool'],
'Imagick::modulateImage' => ['bool', 'brightness'=>'float', 'saturation'=>'float', 'hue'=>'float'],
'Imagick::montageImage' => ['Imagick', 'draw'=>'imagickdraw', 'tile_geometry'=>'string', 'thumbnail_geometry'=>'string', 'mode'=>'int', 'frame'=>'string'],
'Imagick::morphImages' => ['Imagick', 'number_frames'=>'int'],
'Imagick::morphology' => ['void', 'morphologyMethod'=>'int', 'iterations'=>'int', 'ImagickKernel'=>'ImagickKernel', 'CHANNEL='=>'string'],
'Imagick::mosaicImages' => ['Imagick'],
'Imagick::motionBlurImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float', 'channel='=>'int'],
'Imagick::negateImage' => ['bool', 'gray'=>'bool', 'channel='=>'int'],
'Imagick::newImage' => ['bool', 'cols'=>'int', 'rows'=>'int', 'background'=>'mixed', 'format='=>'string'],
'Imagick::newPseudoImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'pseudostring'=>'string'],
'Imagick::next' => ['void'],
'Imagick::nextImage' => ['bool'],
'Imagick::normalizeImage' => ['bool', 'channel='=>'int'],
'Imagick::oilPaintImage' => ['bool', 'radius'=>'float'],
'Imagick::opaquePaintImage' => ['bool', 'target'=>'mixed', 'fill'=>'mixed', 'fuzz'=>'float', 'invert'=>'bool', 'channel='=>'int'],
'Imagick::optimizeImageLayers' => ['bool'],
'Imagick::orderedPosterizeImage' => ['bool', 'threshold_map'=>'string', 'channel='=>'int'],
'Imagick::paintFloodfillImage' => ['bool', 'fill'=>'mixed', 'fuzz'=>'float', 'bordercolor'=>'mixed', 'x'=>'int', 'y'=>'int', 'channel='=>'int'],
'Imagick::paintOpaqueImage' => ['bool', 'target'=>'mixed', 'fill'=>'mixed', 'fuzz'=>'float', 'channel='=>'int'],
'Imagick::paintTransparentImage' => ['bool', 'target'=>'mixed', 'alpha'=>'float', 'fuzz'=>'float'],
'Imagick::pingImage' => ['bool', 'filename'=>'string'],
'Imagick::pingImageBlob' => ['bool', 'image'=>'string'],
'Imagick::pingImageFile' => ['bool', 'filehandle'=>'resource', 'filename='=>'string'],
'Imagick::polaroidImage' => ['bool', 'properties'=>'imagickdraw', 'angle'=>'float'],
'Imagick::posterizeImage' => ['bool', 'levels'=>'int', 'dither'=>'bool'],
'Imagick::previewImages' => ['bool', 'preview'=>'int'],
'Imagick::previousImage' => ['bool'],
'Imagick::profileImage' => ['bool', 'name'=>'string', 'profile'=>'string'],
'Imagick::quantizeImage' => ['bool', 'numbercolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Imagick::quantizeImages' => ['bool', 'numbercolors'=>'int', 'colorspace'=>'int', 'treedepth'=>'int', 'dither'=>'bool', 'measureerror'=>'bool'],
'Imagick::queryFontMetrics' => ['array', 'properties'=>'imagickdraw', 'text'=>'string', 'multiline='=>'bool'],
'Imagick::queryFonts' => ['array', 'pattern='=>'string'],
'Imagick::queryFormats' => ['array', 'pattern='=>'string'],
'Imagick::radialBlurImage' => ['bool', 'angle'=>'float', 'channel='=>'int'],
'Imagick::raiseImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int', 'raise'=>'bool'],
'Imagick::randomThresholdImage' => ['bool', 'low'=>'float', 'high'=>'float', 'channel='=>'int'],
'Imagick::readImage' => ['bool', 'filename'=>'string'],
'Imagick::readImageBlob' => ['bool', 'image'=>'string', 'filename='=>'string'],
'Imagick::readImageFile' => ['bool', 'filehandle'=>'resource', 'filename='=>'string'],
'Imagick::readImages' => ['Imagick', 'filenames'=>'string'],
'Imagick::recolorImage' => ['bool', 'matrix'=>'array'],
'Imagick::reduceNoiseImage' => ['bool', 'radius'=>'float'],
'Imagick::remapImage' => ['bool', 'replacement'=>'imagick', 'dither'=>'int'],
'Imagick::removeImage' => ['bool'],
'Imagick::removeImageProfile' => ['string', 'name'=>'string'],
'Imagick::render' => ['bool'],
'Imagick::resampleImage' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float', 'filter'=>'int', 'blur'=>'float'],
'Imagick::resetImagePage' => ['bool', 'page'=>'string'],
'Imagick::resetIterator' => [''],
'Imagick::resizeImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'filter'=>'int', 'blur'=>'float', 'bestfit='=>'bool'],
'Imagick::rewind' => ['void'],
'Imagick::rollImage' => ['bool', 'x'=>'int', 'y'=>'int'],
'Imagick::rotateImage' => ['bool', 'background'=>'mixed', 'degrees'=>'float'],
'Imagick::rotationalBlurImage' => ['void', 'angle'=>'string', 'CHANNEL='=>'string'],
'Imagick::roundCorners' => ['bool', 'x_rounding'=>'float', 'y_rounding'=>'float', 'stroke_width='=>'float', 'displace='=>'float', 'size_correction='=>'float'],
'Imagick::roundCornersImage' => ['', 'xRounding'=>'', 'yRounding'=>'', 'strokeWidth'=>'', 'displace'=>'', 'sizeCorrection'=>''],
'Imagick::sampleImage' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::scaleImage' => ['bool', 'cols'=>'int', 'rows'=>'int', 'bestfit='=>'bool'],
'Imagick::segmentImage' => ['bool', 'colorspace'=>'int', 'cluster_threshold'=>'float', 'smooth_threshold'=>'float', 'verbose='=>'bool'],
'Imagick::selectiveBlurImage' => ['void', 'radius'=>'float', 'sigma'=>'float', 'threshold'=>'float', 'CHANNEL'=>'int'],
'Imagick::separateImageChannel' => ['bool', 'channel'=>'int'],
'Imagick::sepiaToneImage' => ['bool', 'threshold'=>'float'],
'Imagick::setAntiAlias' => ['int', 'antialias'=>'bool'],
'Imagick::setBackgroundColor' => ['bool', 'background'=>'mixed'],
'Imagick::setColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::setCompression' => ['bool', 'compression'=>'int'],
'Imagick::setCompressionQuality' => ['bool', 'quality'=>'int'],
'Imagick::setFilename' => ['bool', 'filename'=>'string'],
'Imagick::setFirstIterator' => ['bool'],
'Imagick::setFont' => ['bool', 'font'=>'string'],
'Imagick::setFormat' => ['bool', 'format'=>'string'],
'Imagick::setGravity' => ['bool', 'gravity'=>'int'],
'Imagick::setImage' => ['bool', 'replace'=>'imagick'],
'Imagick::setImageAlpha' => ['bool', 'alpha'=>'float'],
'Imagick::setImageAlphaChannel' => ['bool', 'mode'=>'int'],
'Imagick::setImageArtifact' => ['bool', 'artifact'=>'string', 'value'=>'string'],
'Imagick::setImageAttribute' => ['void', 'key'=>'string', 'value'=>'string'],
'Imagick::setImageBackgroundColor' => ['bool', 'background'=>'mixed'],
'Imagick::setImageBias' => ['bool', 'bias'=>'float'],
'Imagick::setImageBiasQuantum' => ['void', 'bias'=>'string'],
'Imagick::setImageBluePrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageBorderColor' => ['bool', 'border'=>'mixed'],
'Imagick::setImageChannelDepth' => ['bool', 'channel'=>'int', 'depth'=>'int'],
'Imagick::setImageChannelMask' => ['', 'channel'=>'int'],
'Imagick::setImageClipMask' => ['bool', 'clip_mask'=>'imagick'],
'Imagick::setImageColormapColor' => ['bool', 'index'=>'int', 'color'=>'imagickpixel'],
'Imagick::setImageColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::setImageCompose' => ['bool', 'compose'=>'int'],
'Imagick::setImageCompression' => ['bool', 'compression'=>'int'],
'Imagick::setImageCompressionQuality' => ['bool', 'quality'=>'int'],
'Imagick::setImageDelay' => ['bool', 'delay'=>'int'],
'Imagick::setImageDepth' => ['bool', 'depth'=>'int'],
'Imagick::setImageDispose' => ['bool', 'dispose'=>'int'],
'Imagick::setImageExtent' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::setImageFilename' => ['bool', 'filename'=>'string'],
'Imagick::setImageFormat' => ['bool', 'format'=>'string'],
'Imagick::setImageGamma' => ['bool', 'gamma'=>'float'],
'Imagick::setImageGravity' => ['bool', 'gravity'=>'int'],
'Imagick::setImageGreenPrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageIndex' => ['bool', 'index'=>'int'],
'Imagick::setImageInterlaceScheme' => ['bool', 'interlace_scheme'=>'int'],
'Imagick::setImageInterpolateMethod' => ['bool', 'method'=>'int'],
'Imagick::setImageIterations' => ['bool', 'iterations'=>'int'],
'Imagick::setImageMatte' => ['bool', 'matte'=>'bool'],
'Imagick::setImageMatteColor' => ['bool', 'matte'=>'mixed'],
'Imagick::setImageOpacity' => ['bool', 'opacity'=>'float'],
'Imagick::setImageOrientation' => ['bool', 'orientation'=>'int'],
'Imagick::setImagePage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::setImageProfile' => ['bool', 'name'=>'string', 'profile'=>'string'],
'Imagick::setImageProgressMonitor' => ['', 'filename'=>''],
'Imagick::setImageProperty' => ['bool', 'name'=>'string', 'value'=>'string'],
'Imagick::setImageRedPrimary' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setImageRenderingIntent' => ['bool', 'rendering_intent'=>'int'],
'Imagick::setImageResolution' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'Imagick::setImageScene' => ['bool', 'scene'=>'int'],
'Imagick::setImageTicksPerSecond' => ['bool', 'ticks_per_second'=>'int'],
'Imagick::setImageType' => ['bool', 'image_type'=>'int'],
'Imagick::setImageUnits' => ['bool', 'units'=>'int'],
'Imagick::setImageVirtualPixelMethod' => ['bool', 'method'=>'int'],
'Imagick::setImageWhitePoint' => ['bool', 'x'=>'float', 'y'=>'float'],
'Imagick::setInterlaceScheme' => ['bool', 'interlace_scheme'=>'int'],
'Imagick::setIteratorIndex' => ['bool', 'index'=>'int'],
'Imagick::setLastIterator' => ['bool'],
'Imagick::setOption' => ['bool', 'key'=>'string', 'value'=>'string'],
'Imagick::setPage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::setPointSize' => ['bool', 'point_size'=>'float'],
'Imagick::setProgressMonitor' => ['void', 'callback'=>'callable'],
'Imagick::setRegistry' => ['void', 'key'=>'string', 'value'=>'string'],
'Imagick::setResolution' => ['bool', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'Imagick::setResourceLimit' => ['bool', 'type'=>'int', 'limit'=>'int'],
'Imagick::setSamplingFactors' => ['bool', 'factors'=>'array'],
'Imagick::setSize' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::setSizeOffset' => ['bool', 'columns'=>'int', 'rows'=>'int', 'offset'=>'int'],
'Imagick::setType' => ['bool', 'image_type'=>'int'],
'Imagick::shadeImage' => ['bool', 'gray'=>'bool', 'azimuth'=>'float', 'elevation'=>'float'],
'Imagick::shadowImage' => ['bool', 'opacity'=>'float', 'sigma'=>'float', 'x'=>'int', 'y'=>'int'],
'Imagick::sharpenImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'channel='=>'int'],
'Imagick::shaveImage' => ['bool', 'columns'=>'int', 'rows'=>'int'],
'Imagick::shearImage' => ['bool', 'background'=>'mixed', 'x_shear'=>'float', 'y_shear'=>'float'],
'Imagick::sigmoidalContrastImage' => ['bool', 'sharpen'=>'bool', 'alpha'=>'float', 'beta'=>'float', 'channel='=>'int'],
'Imagick::similarityImage' => ['Imagick', 'imagick'=>'Imagick', '&bestMatch'=>'array', '&similarity'=>'float', 'similarity_threshold'=>'float', 'metric'=>'int'],
'Imagick::sketchImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'angle'=>'float'],
'Imagick::smushImages' => ['Imagick', 'stack'=>'string', 'offset'=>'string'],
'Imagick::solarizeImage' => ['bool', 'threshold'=>'int'],
'Imagick::sparseColorImage' => ['bool', 'sparse_method'=>'int', 'arguments'=>'array', 'channel='=>'int'],
'Imagick::spliceImage' => ['bool', 'width'=>'int', 'height'=>'int', 'x'=>'int', 'y'=>'int'],
'Imagick::spreadImage' => ['bool', 'radius'=>'float'],
'Imagick::statisticImage' => ['void', 'type'=>'int', 'width'=>'int', 'height'=>'int', 'CHANNEL='=>'string'],
'Imagick::steganoImage' => ['Imagick', 'watermark_wand'=>'imagick', 'offset'=>'int'],
'Imagick::stereoImage' => ['bool', 'offset_wand'=>'imagick'],
'Imagick::stripImage' => ['bool'],
'Imagick::subImageMatch' => ['Imagick', 'Imagick'=>'Imagick', '&w_offset='=>'array', '&w_similarity='=>'float'],
'Imagick::swirlImage' => ['bool', 'degrees'=>'float'],
'Imagick::textureImage' => ['bool', 'texture_wand'=>'imagick'],
'Imagick::thresholdImage' => ['bool', 'threshold'=>'float', 'channel='=>'int'],
'Imagick::thumbnailImage' => ['bool', 'columns'=>'int', 'rows'=>'int', 'bestfit='=>'bool', 'fill='=>'bool'],
'Imagick::tintImage' => ['bool', 'tint'=>'mixed', 'opacity'=>'mixed'],
'Imagick::transformImage' => ['Imagick', 'crop'=>'string', 'geometry'=>'string'],
'Imagick::transformImageColorspace' => ['bool', 'colorspace'=>'int'],
'Imagick::transparentPaintImage' => ['bool', 'target'=>'mixed', 'alpha'=>'float', 'fuzz'=>'float', 'invert'=>'bool'],
'Imagick::transposeImage' => ['bool'],
'Imagick::transverseImage' => ['bool'],
'Imagick::trimImage' => ['bool', 'fuzz'=>'float'],
'Imagick::uniqueImageColors' => ['bool'],
'Imagick::unsharpMaskImage' => ['bool', 'radius'=>'float', 'sigma'=>'float', 'amount'=>'float', 'threshold'=>'float', 'channel='=>'int'],
'Imagick::valid' => ['bool'],
'Imagick::vignetteImage' => ['bool', 'blackpoint'=>'float', 'whitepoint'=>'float', 'x'=>'int', 'y'=>'int'],
'Imagick::waveImage' => ['bool', 'amplitude'=>'float', 'length'=>'float'],
'Imagick::whiteThresholdImage' => ['bool', 'threshold'=>'mixed'],
'Imagick::writeImage' => ['bool', 'filename='=>'string'],
'Imagick::writeImageFile' => ['bool', 'filehandle'=>'resource'],
'Imagick::writeImages' => ['bool', 'filename'=>'string', 'adjoin'=>'bool'],
'Imagick::writeImagesFile' => ['bool', 'filehandle'=>'resource'],
'ImagickDraw::__construct' => ['void'],
'ImagickDraw::affine' => ['bool', 'affine'=>'array'],
'ImagickDraw::annotation' => ['bool', 'x'=>'float', 'y'=>'float', 'text'=>'string'],
'ImagickDraw::arc' => ['bool', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float', 'sd'=>'float', 'ed'=>'float'],
'ImagickDraw::bezier' => ['bool', 'coordinates'=>'array'],
'ImagickDraw::circle' => ['bool', 'ox'=>'float', 'oy'=>'float', 'px'=>'float', 'py'=>'float'],
'ImagickDraw::clear' => ['bool'],
'ImagickDraw::clone' => ['ImagickDraw'],
'ImagickDraw::color' => ['bool', 'x'=>'float', 'y'=>'float', 'paintmethod'=>'int'],
'ImagickDraw::comment' => ['bool', 'comment'=>'string'],
'ImagickDraw::composite' => ['bool', 'compose'=>'int', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float', 'compositewand'=>'imagick'],
'ImagickDraw::destroy' => ['bool'],
'ImagickDraw::ellipse' => ['bool', 'ox'=>'float', 'oy'=>'float', 'rx'=>'float', 'ry'=>'float', 'start'=>'float', 'end'=>'float'],
'ImagickDraw::getBorderColor' => ['ImagickPixel'],
'ImagickDraw::getClipPath' => ['string|false'],
'ImagickDraw::getClipRule' => ['int'],
'ImagickDraw::getClipUnits' => ['int'],
'ImagickDraw::getDensity' => ['?string'],
'ImagickDraw::getFillColor' => ['ImagickPixel'],
'ImagickDraw::getFillOpacity' => ['float'],
'ImagickDraw::getFillRule' => ['int'],
'ImagickDraw::getFont' => ['string|false'],
'ImagickDraw::getFontFamily' => ['string|false'],
'ImagickDraw::getFontResolution' => ['array'],
'ImagickDraw::getFontSize' => ['float'],
'ImagickDraw::getFontStretch' => ['int'],
'ImagickDraw::getFontStyle' => ['int'],
'ImagickDraw::getFontWeight' => ['int'],
'ImagickDraw::getGravity' => ['int'],
'ImagickDraw::getOpacity' => ['float'],
'ImagickDraw::getStrokeAntialias' => ['bool'],
'ImagickDraw::getStrokeColor' => ['ImagickPixel'],
'ImagickDraw::getStrokeDashArray' => ['array'],
'ImagickDraw::getStrokeDashOffset' => ['float'],
'ImagickDraw::getStrokeLineCap' => ['int'],
'ImagickDraw::getStrokeLineJoin' => ['int'],
'ImagickDraw::getStrokeMiterLimit' => ['int'],
'ImagickDraw::getStrokeOpacity' => ['float'],
'ImagickDraw::getStrokeWidth' => ['float'],
'ImagickDraw::getTextAlignment' => ['int'],
'ImagickDraw::getTextAntialias' => ['bool'],
'ImagickDraw::getTextDecoration' => ['int'],
'ImagickDraw::getTextDirection' => ['bool'],
'ImagickDraw::getTextEncoding' => ['string'],
'ImagickDraw::getTextInterlineSpacing' => ['float'],
'ImagickDraw::getTextInterwordSpacing' => ['float'],
'ImagickDraw::getTextKerning' => ['float'],
'ImagickDraw::getTextUnderColor' => ['ImagickPixel'],
'ImagickDraw::getVectorGraphics' => ['string'],
'ImagickDraw::line' => ['bool', 'sx'=>'float', 'sy'=>'float', 'ex'=>'float', 'ey'=>'float'],
'ImagickDraw::matte' => ['bool', 'x'=>'float', 'y'=>'float', 'paintmethod'=>'int'],
'ImagickDraw::pathClose' => ['bool'],
'ImagickDraw::pathCurveToAbsolute' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierAbsolute' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierRelative' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToQuadraticBezierSmoothRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToRelative' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToSmoothAbsolute' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathCurveToSmoothRelative' => ['bool', 'x2'=>'float', 'y2'=>'float', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathEllipticArcAbsolute' => ['bool', 'rx'=>'float', 'ry'=>'float', 'x_axis_rotation'=>'float', 'large_arc_flag'=>'bool', 'sweep_flag'=>'bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathEllipticArcRelative' => ['bool', 'rx'=>'float', 'ry'=>'float', 'x_axis_rotation'=>'float', 'large_arc_flag'=>'bool', 'sweep_flag'=>'bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathFinish' => ['bool'],
'ImagickDraw::pathLineToAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathLineToHorizontalAbsolute' => ['bool', 'x'=>'float'],
'ImagickDraw::pathLineToHorizontalRelative' => ['bool', 'x'=>'float'],
'ImagickDraw::pathLineToRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathLineToVerticalAbsolute' => ['bool', 'y'=>'float'],
'ImagickDraw::pathLineToVerticalRelative' => ['bool', 'y'=>'float'],
'ImagickDraw::pathMoveToAbsolute' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathMoveToRelative' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::pathStart' => ['bool'],
'ImagickDraw::point' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::polygon' => ['bool', 'coordinates'=>'array'],
'ImagickDraw::polyline' => ['bool', 'coordinates'=>'array'],
'ImagickDraw::pop' => ['bool'],
'ImagickDraw::popClipPath' => ['bool'],
'ImagickDraw::popDefs' => ['bool'],
'ImagickDraw::popPattern' => ['bool'],
'ImagickDraw::push' => ['bool'],
'ImagickDraw::pushClipPath' => ['bool', 'clip_mask_id'=>'string'],
'ImagickDraw::pushDefs' => ['bool'],
'ImagickDraw::pushPattern' => ['bool', 'pattern_id'=>'string', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'ImagickDraw::rectangle' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'ImagickDraw::render' => ['bool'],
'ImagickDraw::resetVectorGraphics' => ['void'],
'ImagickDraw::rotate' => ['bool', 'degrees'=>'float'],
'ImagickDraw::roundRectangle' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'rx'=>'float', 'ry'=>'float'],
'ImagickDraw::scale' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::setBorderColor' => ['bool', 'color'=>'ImagickPixel|string'],
'ImagickDraw::setClipPath' => ['bool', 'clip_mask'=>'string'],
'ImagickDraw::setClipRule' => ['bool', 'fill_rule'=>'int'],
'ImagickDraw::setClipUnits' => ['bool', 'clip_units'=>'int'],
'ImagickDraw::setDensity' => ['bool', 'density_string'=>'string'],
'ImagickDraw::setFillAlpha' => ['bool', 'opacity'=>'float'],
'ImagickDraw::setFillColor' => ['bool', 'fill_pixel'=>'ImagickPixel|string'],
'ImagickDraw::setFillOpacity' => ['bool', 'fillopacity'=>'float'],
'ImagickDraw::setFillPatternURL' => ['bool', 'fill_url'=>'string'],
'ImagickDraw::setFillRule' => ['bool', 'fill_rule'=>'int'],
'ImagickDraw::setFont' => ['bool', 'font_name'=>'string'],
'ImagickDraw::setFontFamily' => ['bool', 'font_family'=>'string'],
'ImagickDraw::setFontResolution' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickDraw::setFontSize' => ['bool', 'pointsize'=>'float'],
'ImagickDraw::setFontStretch' => ['bool', 'fontstretch'=>'int'],
'ImagickDraw::setFontStyle' => ['bool', 'style'=>'int'],
'ImagickDraw::setFontWeight' => ['bool', 'font_weight'=>'int'],
'ImagickDraw::setGravity' => ['bool', 'gravity'=>'int'],
'ImagickDraw::setOpacity' => ['void', 'opacity'=>'float'],
'ImagickDraw::setResolution' => ['void', 'x_resolution'=>'float', 'y_resolution'=>'float'],
'ImagickDraw::setStrokeAlpha' => ['bool', 'opacity'=>'float'],
'ImagickDraw::setStrokeAntialias' => ['bool', 'stroke_antialias'=>'bool'],
'ImagickDraw::setStrokeColor' => ['bool', 'stroke_pixel'=>'ImagickPixel|string'],
'ImagickDraw::setStrokeDashArray' => ['bool', 'dasharray'=>'array'],
'ImagickDraw::setStrokeDashOffset' => ['bool', 'dash_offset'=>'float'],
'ImagickDraw::setStrokeLineCap' => ['bool', 'linecap'=>'int'],
'ImagickDraw::setStrokeLineJoin' => ['bool', 'linejoin'=>'int'],
'ImagickDraw::setStrokeMiterLimit' => ['bool', 'miterlimit'=>'int'],
'ImagickDraw::setStrokeOpacity' => ['bool', 'stroke_opacity'=>'float'],
'ImagickDraw::setStrokePatternURL' => ['bool', 'stroke_url'=>'string'],
'ImagickDraw::setStrokeWidth' => ['bool', 'stroke_width'=>'float'],
'ImagickDraw::setTextAlignment' => ['bool', 'alignment'=>'int'],
'ImagickDraw::setTextAntialias' => ['bool', 'antialias'=>'bool'],
'ImagickDraw::setTextDecoration' => ['bool', 'decoration'=>'int'],
'ImagickDraw::setTextDirection' => ['bool', 'direction'=>'int'],
'ImagickDraw::setTextEncoding' => ['bool', 'encoding'=>'string'],
'ImagickDraw::setTextInterlineSpacing' => ['void', 'spacing'=>'float'],
'ImagickDraw::setTextInterwordSpacing' => ['void', 'spacing'=>'float'],
'ImagickDraw::setTextKerning' => ['void', 'kerning'=>'float'],
'ImagickDraw::setTextUnderColor' => ['bool', 'under_color'=>'ImagickPixel|string'],
'ImagickDraw::setVectorGraphics' => ['bool', 'xml'=>'string'],
'ImagickDraw::setViewbox' => ['bool', 'x1'=>'int', 'y1'=>'int', 'x2'=>'int', 'y2'=>'int'],
'ImagickDraw::skewX' => ['bool', 'degrees'=>'float'],
'ImagickDraw::skewY' => ['bool', 'degrees'=>'float'],
'ImagickDraw::translate' => ['bool', 'x'=>'float', 'y'=>'float'],
'ImagickKernel::addKernel' => ['void', 'ImagickKernel'=>'ImagickKernel'],
'ImagickKernel::addUnityKernel' => ['void'],
'ImagickKernel::fromBuiltin' => ['ImagickKernel', 'kernelType'=>'string', 'kernelString'=>'string'],
'ImagickKernel::fromMatrix' => ['ImagickKernel', 'matrix'=>'array', 'origin='=>'array'],
'ImagickKernel::getMatrix' => ['array'],
'ImagickKernel::scale' => ['void'],
'ImagickKernel::separate' => ['array'],
'ImagickKernel::seperate' => ['void'],
'ImagickPixel::__construct' => ['void', 'color='=>'string'],
'ImagickPixel::clear' => ['bool'],
'ImagickPixel::clone' => ['void'],
'ImagickPixel::destroy' => ['bool'],
'ImagickPixel::getColor' => ['array', 'normalized='=>'bool'],
'ImagickPixel::getColorAsString' => ['string'],
'ImagickPixel::getColorCount' => ['int'],
'ImagickPixel::getColorQuantum' => ['mixed'],
'ImagickPixel::getColorValue' => ['float', 'color'=>'int'],
'ImagickPixel::getColorValueQuantum' => ['mixed'],
'ImagickPixel::getHSL' => ['array'],
'ImagickPixel::getIndex' => ['int'],
'ImagickPixel::isPixelSimilar' => ['bool', 'color'=>'ImagickPixel', 'fuzz'=>'float'],
'ImagickPixel::isPixelSimilarQuantum' => ['bool', 'color'=>'string', 'fuzz='=>'string'],
'ImagickPixel::isSimilar' => ['bool', 'color'=>'imagickpixel', 'fuzz'=>'float'],
'ImagickPixel::setColor' => ['bool', 'color'=>'string'],
'ImagickPixel::setcolorcount' => ['void', 'colorCount'=>'string'],
'ImagickPixel::setColorFromPixel' => ['bool', 'srcPixel'=>'ImagickPixel'],
'ImagickPixel::setColorValue' => ['bool', 'color'=>'int', 'value'=>'float'],
'ImagickPixel::setColorValueQuantum' => ['void', 'color'=>'int', 'value'=>'mixed'],
'ImagickPixel::setHSL' => ['bool', 'hue'=>'float', 'saturation'=>'float', 'luminosity'=>'float'],
'ImagickPixel::setIndex' => ['void', 'index'=>'int'],
'ImagickPixelIterator::__construct' => ['void', 'wand'=>'imagick'],
'ImagickPixelIterator::clear' => ['bool'],
'ImagickPixelIterator::current' => ['mixed'],
'ImagickPixelIterator::destroy' => ['bool'],
'ImagickPixelIterator::getCurrentIteratorRow' => ['array'],
'ImagickPixelIterator::getIteratorRow' => ['int'],
'ImagickPixelIterator::getNextIteratorRow' => ['array'],
'ImagickPixelIterator::getpixeliterator' => ['', 'Imagick'=>'Imagick'],
'ImagickPixelIterator::getpixelregioniterator' => ['', 'Imagick'=>'Imagick', 'x'=>'', 'y'=>'', 'columns'=>'', 'rows'=>''],
'ImagickPixelIterator::getPreviousIteratorRow' => ['array'],
'ImagickPixelIterator::key' => ['int|string'],
'ImagickPixelIterator::newPixelIterator' => ['bool', 'wand'=>'imagick'],
'ImagickPixelIterator::newPixelRegionIterator' => ['bool', 'wand'=>'imagick', 'x'=>'int', 'y'=>'int', 'columns'=>'int', 'rows'=>'int'],
'ImagickPixelIterator::next' => ['void'],
'ImagickPixelIterator::resetIterator' => ['bool'],
'ImagickPixelIterator::rewind' => ['void'],
'ImagickPixelIterator::setIteratorFirstRow' => ['bool'],
'ImagickPixelIterator::setIteratorLastRow' => ['bool'],
'ImagickPixelIterator::setIteratorRow' => ['bool', 'row'=>'int'],
'ImagickPixelIterator::syncIterator' => ['bool'],
'ImagickPixelIterator::valid' => ['bool'],
'imap_8bit' => ['string|false', 'text'=>'string'],
'imap_alerts' => ['array|false'],
'imap_append' => ['bool', 'stream_id'=>'resource', 'folder'=>'string', 'message'=>'string', 'options='=>'string', 'internal_date='=>'string'],
'imap_base64' => ['string|false', 'text'=>'string'],
'imap_binary' => ['string|false', 'text'=>'string'],
'imap_body' => ['string|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'options='=>'int'],
'imap_bodystruct' => ['stdClass|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'section'=>'string'],
'imap_check' => ['stdClass|false', 'stream_id'=>'resource'],
'imap_clearflag_full' => ['bool', 'stream_id'=>'resource', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_close' => ['bool', 'stream_id'=>'resource', 'options='=>'int'],
'imap_create' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string'],
'imap_createmailbox' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string'],
'imap_delete' => ['bool', 'stream_id'=>'resource', 'msg_no'=>'int', 'options='=>'int'],
'imap_deletemailbox' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string'],
'imap_errors' => ['array|false'],
'imap_expunge' => ['bool', 'stream_id'=>'resource'],
'imap_fetch_overview' => ['array|false', 'stream_id'=>'resource', 'sequence'=>'string', 'options='=>'int'],
'imap_fetchbody' => ['string|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'section'=>'string', 'options='=>'int'],
'imap_fetchheader' => ['string|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'options='=>'int'],
'imap_fetchmime' => ['string|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'section'=>'string', 'options='=>'int'],
'imap_fetchstructure' => ['stdClass|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'options='=>'int'],
'imap_fetchtext' => ['string|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'options='=>'int'],
'imap_gc' => ['bool', 'stream_id'=>'resource', 'flags'=>'int'],
'imap_get_quota' => ['array|false', 'stream_id'=>'resource', 'qroot'=>'string'],
'imap_get_quotaroot' => ['array|false', 'stream_id'=>'resource', 'mbox'=>'string'],
'imap_getacl' => ['array|false', 'stream_id'=>'resource', 'mailbox'=>'string'],
'imap_getmailboxes' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string'],
'imap_getsubscribed' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string'],
'imap_header' => ['stdClass|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string'],
'imap_headerinfo' => ['stdClass|false', 'stream_id'=>'resource', 'msg_no'=>'int', 'from_length='=>'int', 'subject_length='=>'int', 'default_host='=>'string|null'],
'imap_headers' => ['array|false', 'stream_id'=>'resource'],
'imap_last_error' => ['string|false'],
'imap_list' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string'],
'imap_listmailbox' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string'],
'imap_listscan' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_listsubscribed' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string'],
'imap_lsub' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string'],
'imap_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string', 'cc='=>'string', 'bcc='=>'string', 'rpath='=>'string'],
'imap_mail_compose' => ['string|false', 'envelope'=>'array', 'body'=>'array'],
'imap_mail_copy' => ['bool', 'stream_id'=>'resource', 'msglist'=>'string', 'mailbox'=>'string', 'options='=>'int'],
'imap_mail_move' => ['bool', 'stream_id'=>'resource', 'sequence'=>'string', 'mailbox'=>'string', 'options='=>'int'],
'imap_mailboxmsginfo' => ['stdClass|false', 'stream_id'=>'resource'],
'imap_mime_header_decode' => ['array|false', 'str'=>'string'],
'imap_msgno' => ['int|false', 'stream_id'=>'resource', 'unique_msg_id'=>'int'],
'imap_mutf7_to_utf8' => ['string|false', 'in'=>'string'],
'imap_num_msg' => ['int|false', 'stream_id'=>'resource'],
'imap_num_recent' => ['int|false', 'stream_id'=>'resource'],
'imap_open' => ['resource|false', 'mailbox'=>'string', 'user'=>'string', 'password'=>'string', 'options='=>'int', 'n_retries='=>'int', 'params='=>'?array'],
'imap_ping' => ['bool', 'stream_id'=>'resource'],
'imap_qprint' => ['string|false', 'text'=>'string'],
'imap_rename' => ['bool', 'stream_id'=>'resource', 'old_name'=>'string', 'new_name'=>'string'],
'imap_renamemailbox' => ['bool', 'stream_id'=>'resource', 'old_name'=>'string', 'new_name'=>'string'],
'imap_reopen' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string', 'options='=>'int', 'n_retries='=>'int'],
'imap_rfc822_parse_adrlist' => ['array', 'address_string'=>'string', 'default_host'=>'string'],
'imap_rfc822_parse_headers' => ['stdClass', 'headers'=>'string', 'default_host='=>'string'],
'imap_rfc822_write_address' => ['string|false', 'mailbox'=>'?string', 'host'=>'?string', 'personal'=>'?string'],
'imap_savebody' => ['bool', 'stream_id'=>'resource', 'file'=>'string|resource', 'msg_no'=>'int', 'section='=>'string', 'options='=>'int'],
'imap_scan' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_scanmailbox' => ['array|false', 'stream_id'=>'resource', 'ref'=>'string', 'pattern'=>'string', 'content'=>'string'],
'imap_search' => ['array|false', 'stream_id'=>'resource', 'criteria'=>'string', 'options='=>'int', 'charset='=>'string'],
'imap_set_quota' => ['bool', 'stream_id'=>'resource', 'qroot'=>'string', 'mailbox_size'=>'int'],
'imap_setacl' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string', 'id'=>'string', 'rights'=>'string'],
'imap_setflag_full' => ['bool', 'stream_id'=>'resource', 'sequence'=>'string', 'flag'=>'string', 'options='=>'int'],
'imap_sort' => ['array|false', 'stream_id'=>'resource', 'criteria'=>'int', 'reverse'=>'int', 'options='=>'int', 'search_criteria='=>'string', 'charset='=>'string'],
'imap_status' => ['stdClass|false', 'stream_id'=>'resource', 'mailbox'=>'string', 'options'=>'int'],
'imap_subscribe' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string'],
'imap_thread' => ['array|false', 'stream_id'=>'resource', 'options='=>'int'],
'imap_timeout' => ['int|bool', 'timeout_type'=>'int', 'timeout='=>'int'],
'imap_uid' => ['int|false', 'stream_id'=>'resource', 'msg_no'=>'int'],
'imap_undelete' => ['bool', 'stream_id'=>'resource', 'msg_no'=>'int', 'flags='=>'int'],
'imap_unsubscribe' => ['bool', 'stream_id'=>'resource', 'mailbox'=>'string'],
'imap_utf7_decode' => ['string|false', 'buf'=>'string'],
'imap_utf7_encode' => ['string', 'buf'=>'string'],
'imap_utf8' => ['string', 'mime_encoded_text'=>'string'],
'imap_utf8_to_mutf7' => ['string|false', 'in'=>'string'],
'implode' => ['string', 'glue'=>'string', 'pieces'=>'array'],
'implode\'1' => ['string', 'pieces'=>'array'],
'import_request_variables' => ['bool', 'types'=>'string', 'prefix='=>'string'],
'in_array' => ['bool', 'needle'=>'mixed', 'haystack'=>'array', 'strict='=>'bool'],
'inclued_get_data' => ['array'],
'inet_ntop' => ['string|false', 'in_addr'=>'string'],
'inet_pton' => ['string|false', 'ip_address'=>'string'],
'InfiniteIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'InfiniteIterator::current' => ['mixed'],
'InfiniteIterator::getInnerIterator' => ['Traversable'],
'InfiniteIterator::key' => ['bool|float|int|string'],
'InfiniteIterator::next' => ['void'],
'InfiniteIterator::rewind' => ['void'],
'InfiniteIterator::valid' => ['bool'],
'inflate_add' => ['string|false', 'context'=>'resource', 'encoded_data'=>'string', 'flush_mode='=>'int'],
'inflate_get_read_len' => ['int|false', 'resource'=>'resource'],
'inflate_get_status' => ['int|false', 'resource'=>'resource'],
'inflate_init' => ['resource|false', 'encoding'=>'int', 'options='=>'array'],
'ingres_autocommit' => ['bool', 'link'=>'resource'],
'ingres_autocommit_state' => ['bool', 'link'=>'resource'],
'ingres_charset' => ['string', 'link'=>'resource'],
'ingres_close' => ['bool', 'link'=>'resource'],
'ingres_commit' => ['bool', 'link'=>'resource'],
'ingres_connect' => ['resource', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'options='=>'array'],
'ingres_cursor' => ['string', 'result'=>'resource'],
'ingres_errno' => ['int', 'link='=>'resource'],
'ingres_error' => ['string', 'link='=>'resource'],
'ingres_errsqlstate' => ['string', 'link='=>'resource'],
'ingres_escape_string' => ['string', 'link'=>'resource', 'source_string'=>'string'],
'ingres_execute' => ['bool', 'result'=>'resource', 'params='=>'array', 'types='=>'string'],
'ingres_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'ingres_fetch_assoc' => ['array', 'result'=>'resource'],
'ingres_fetch_object' => ['object', 'result'=>'resource', 'result_type='=>'int'],
'ingres_fetch_proc_return' => ['int', 'result'=>'resource'],
'ingres_fetch_row' => ['array', 'result'=>'resource'],
'ingres_field_length' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_name' => ['string', 'result'=>'resource', 'index'=>'int'],
'ingres_field_nullable' => ['bool', 'result'=>'resource', 'index'=>'int'],
'ingres_field_precision' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_scale' => ['int', 'result'=>'resource', 'index'=>'int'],
'ingres_field_type' => ['string', 'result'=>'resource', 'index'=>'int'],
'ingres_free_result' => ['bool', 'result'=>'resource'],
'ingres_next_error' => ['bool', 'link='=>'resource'],
'ingres_num_fields' => ['int', 'result'=>'resource'],
'ingres_num_rows' => ['int', 'result'=>'resource'],
'ingres_pconnect' => ['resource', 'database='=>'string', 'username='=>'string', 'password='=>'string', 'options='=>'array'],
'ingres_prepare' => ['mixed', 'link'=>'resource', 'query'=>'string'],
'ingres_query' => ['mixed', 'link'=>'resource', 'query'=>'string', 'params='=>'array', 'types='=>'string'],
'ingres_result_seek' => ['bool', 'result'=>'resource', 'position'=>'int'],
'ingres_rollback' => ['bool', 'link'=>'resource'],
'ingres_set_environment' => ['bool', 'link'=>'resource', 'options'=>'array'],
'ingres_unbuffered_query' => ['mixed', 'link'=>'resource', 'query'=>'string', 'params='=>'array', 'types='=>'string'],
'ini_alter' => ['string|false', 'varname'=>'string', 'newvalue'=>'string'],
'ini_get' => ['string|false', 'varname'=>'string'],
'ini_get_all' => ['array|false', 'extension='=>'?string', 'details='=>'bool'],
'ini_restore' => ['void', 'varname'=>'string'],
'ini_set' => ['string|false', 'varname'=>'string', 'newvalue'=>'string'],
'inotify_add_watch' => ['int', 'inotify_instance'=>'resource', 'pathname'=>'string', 'mask'=>'int'],
'inotify_init' => ['resource|false'],
'inotify_queue_len' => ['int', 'inotify_instance'=>'resource'],
'inotify_read' => ['array|false', 'inotify_instance'=>'resource'],
'inotify_rm_watch' => ['bool', 'inotify_instance'=>'resource', 'watch_descriptor'=>'int'],
'intdiv' => ['int', 'numerator'=>'int', 'divisor'=>'int'],
'interface_exists' => ['bool', 'classname'=>'string', 'autoload='=>'bool'],
'intl_error_name' => ['string', 'error_code'=>'int'],
'intl_get_error_code' => ['int'],
'intl_get_error_message' => ['string'],
'intl_is_failure' => ['bool', 'error_code'=>'int'],
'IntlBreakIterator::__construct' => ['void'],
'IntlBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlBreakIterator::current' => ['int'],
'IntlBreakIterator::first' => ['int'],
'IntlBreakIterator::following' => ['int', 'offset'=>'int'],
'IntlBreakIterator::getErrorCode' => ['int'],
'IntlBreakIterator::getErrorMessage' => ['string'],
'IntlBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'int'],
'IntlBreakIterator::getText' => ['string'],
'IntlBreakIterator::isBoundary' => ['bool', 'offset'=>'int'],
'IntlBreakIterator::last' => ['int'],
'IntlBreakIterator::next' => ['int', 'offset='=>'int'],
'IntlBreakIterator::preceding' => ['int', 'offset'=>'int'],
'IntlBreakIterator::previous' => ['int'],
'IntlBreakIterator::setText' => ['bool', 'text'=>'string'],
'intlcal_add' => ['bool', 'cal'=>'IntlCalendar', 'field'=>'int', 'amount'=>'int'],
'intlcal_after' => ['bool', 'cal'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_before' => ['bool', 'cal'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_clear' => ['bool', 'cal'=>'IntlCalendar', 'field='=>'int'],
'intlcal_create_instance' => ['IntlCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'intlcal_equals' => ['bool', 'cal'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_field_difference' => ['int', 'cal'=>'IntlCalendar', 'when'=>'float', 'field'=>'int'],
'intlcal_from_date_time' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'intlcal_get' => ['mixed', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_maximum' => ['int', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_actual_minimum' => ['int', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_available_locales' => ['array'],
'intlcal_get_day_of_week_type' => ['int', 'cal'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_get_first_day_of_week' => ['int', 'cal'=>'IntlCalendar'],
'intlcal_get_greatest_minimum' => ['int', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_keyword_values_for_locale' => ['Iterator|false', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'intlcal_get_least_maximum' => ['int', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_locale' => ['string', 'cal'=>'IntlCalendar', 'localeType'=>'int'],
'intlcal_get_maximum' => ['int|false', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_minimal_days_in_first_week' => ['int', 'cal'=>'IntlCalendar'],
'intlcal_get_minimum' => ['int', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_get_now' => ['float'],
'intlcal_get_repeated_wall_time_option' => ['int', 'cal'=>'IntlCalendar'],
'intlcal_get_skipped_wall_time_option' => ['int', 'cal'=>'IntlCalendar'],
'intlcal_get_time' => ['float', 'cal'=>'IntlCalendar'],
'intlcal_get_time_zone' => ['IntlTimeZone', 'cal'=>'IntlCalendar'],
'intlcal_get_type' => ['string', 'cal'=>'IntlCalendar'],
'intlcal_get_weekend_transition' => ['int', 'cal'=>'IntlCalendar', 'dayOfWeek'=>'string'],
'intlcal_in_daylight_time' => ['bool', 'cal'=>'IntlCalendar'],
'intlcal_is_equivalent_to' => ['bool', 'cal'=>'IntlCalendar', 'other'=>'IntlCalendar'],
'intlcal_is_lenient' => ['bool', 'cal'=>'IntlCalendar'],
'intlcal_is_set' => ['bool', 'cal'=>'IntlCalendar', 'field'=>'int'],
'intlcal_is_weekend' => ['bool', 'cal'=>'IntlCalendar', 'date='=>'float'],
'intlcal_roll' => ['bool', 'cal'=>'IntlCalendar', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'intlcal_set' => ['bool', 'cal'=>'IntlCalendar', 'field'=>'int', 'value'=>'int'],
'intlcal_set\'1' => ['bool', 'cal'=>'IntlCalendar', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'intlcal_set_first_day_of_week' => ['bool', 'cal'=>'IntlCalendar', 'dayOfWeek'=>'int'],
'intlcal_set_lenient' => ['bool', 'cal'=>'IntlCalendar', 'isLenient'=>'bool'],
'intlcal_set_repeated_wall_time_option' => ['bool', 'cal'=>'IntlCalendar', 'wallTimeOption'=>'int'],
'intlcal_set_skipped_wall_time_option' => ['bool', 'cal'=>'IntlCalendar', 'wallTimeOption'=>'int'],
'intlcal_set_time' => ['bool', 'cal'=>'IntlCalendar', 'date'=>'float'],
'intlcal_set_time_zone' => ['bool', 'cal'=>'IntlCalendar', 'timeZone'=>'mixed'],
'intlcal_to_date_time' => ['DateTime|false', 'cal'=>'IntlCalendar'],
'IntlCalendar::__construct' => ['void'],
'IntlCalendar::add' => ['bool', 'field'=>'int', 'amount'=>'int'],
'IntlCalendar::after' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::before' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::clear' => ['bool', 'field='=>'int'],
'IntlCalendar::createInstance' => ['IntlCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'IntlCalendar::equals' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::fieldDifference' => ['int', 'when'=>'float', 'field'=>'int'],
'IntlCalendar::fromDateTime' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'IntlCalendar::get' => ['int', 'field'=>'int'],
'IntlCalendar::getActualMaximum' => ['int', 'field'=>'int'],
'IntlCalendar::getActualMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getAvailableLocales' => ['array'],
'IntlCalendar::getDayOfWeekType' => ['int', 'dayOfWeek'=>'int'],
'IntlCalendar::getErrorCode' => ['int'],
'IntlCalendar::getErrorMessage' => ['string'],
'IntlCalendar::getFirstDayOfWeek' => ['int'],
'IntlCalendar::getGreatestMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getKeywordValuesForLocale' => ['Iterator|false', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'IntlCalendar::getLeastMaximum' => ['int', 'field'=>'int'],
'IntlCalendar::getLocale' => ['string', 'localeType'=>'int'],
'IntlCalendar::getMaximum' => ['int|false', 'field'=>'int'],
'IntlCalendar::getMinimalDaysInFirstWeek' => ['int'],
'IntlCalendar::getMinimum' => ['int', 'field'=>'int'],
'IntlCalendar::getNow' => ['float'],
'IntlCalendar::getRepeatedWallTimeOption' => ['int'],
'IntlCalendar::getSkippedWallTimeOption' => ['int'],
'IntlCalendar::getTime' => ['float'],
'IntlCalendar::getTimeZone' => ['IntlTimeZone'],
'IntlCalendar::getType' => ['string'],
'IntlCalendar::getWeekendTransition' => ['int', 'dayOfWeek'=>'string'],
'IntlCalendar::inDaylightTime' => ['bool'],
'IntlCalendar::isEquivalentTo' => ['bool', 'other'=>'IntlCalendar'],
'IntlCalendar::isLenient' => ['bool'],
'IntlCalendar::isSet' => ['bool', 'field'=>'int'],
'IntlCalendar::isWeekend' => ['bool', 'date='=>'float'],
'IntlCalendar::roll' => ['bool', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'IntlCalendar::set' => ['bool', 'field'=>'int', 'value'=>'int'],
'IntlCalendar::set\'1' => ['bool', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'IntlCalendar::setFirstDayOfWeek' => ['bool', 'dayOfWeek'=>'int'],
'IntlCalendar::setLenient' => ['bool', 'isLenient'=>'string'],
'IntlCalendar::setMinimalDaysInFirstWeek' => ['bool', 'minimalDays'=>'int'],
'IntlCalendar::setRepeatedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlCalendar::setSkippedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlCalendar::setTime' => ['bool', 'date'=>'float'],
'IntlCalendar::setTimeZone' => ['bool', 'timeZone'=>'mixed'],
'IntlCalendar::toDateTime' => ['DateTime|false'],
'IntlChar::charAge' => ['array', 'char'=>'int|string'],
'IntlChar::charDigitValue' => ['int', 'codepoint'=>'mixed'],
'IntlChar::charDirection' => ['int', 'codepoint'=>'mixed'],
'IntlChar::charFromName' => ['?int', 'name'=>'string', 'namechoice='=>'int'],
'IntlChar::charMirror' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::charName' => ['string', 'char'=>'int|string', 'namechoice='=>'int'],
'IntlChar::charType' => ['int', 'codepoint'=>'mixed'],
'IntlChar::chr' => ['string', 'codepoint'=>'mixed'],
'IntlChar::digit' => ['int|false', 'char'=>'int|string', 'radix='=>'int'],
'IntlChar::enumCharNames' => ['void', 'start'=>'mixed', 'limit'=>'mixed', 'callback'=>'callable', 'nameChoice='=>'int'],
'IntlChar::enumCharTypes' => ['void', 'cb='=>'callable'],
'IntlChar::foldCase' => ['int|string', 'char'=>'int|string', 'options='=>'int'],
'IntlChar::forDigit' => ['int', 'digit'=>'int', 'radix'=>'int'],
'IntlChar::getBidiPairedBracket' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::getBlockCode' => ['int', 'char'=>'int|string'],
'IntlChar::getCombiningClass' => ['int', 'codepoint'=>'mixed'],
'IntlChar::getFC_NFKC_Closure' => ['string', 'char'=>'int|string'],
'IntlChar::getIntPropertyMaxValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyMinValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyMxValue' => ['int', 'property'=>'int'],
'IntlChar::getIntPropertyValue' => ['int', 'char'=>'int|string', 'property'=>'int'],
'IntlChar::getNumericValue' => ['float', 'char'=>'int|string'],
'IntlChar::getPropertyEnum' => ['int', 'alias'=>'string'],
'IntlChar::getPropertyName' => ['string|false', 'property'=>'int', 'namechoice='=>'int'],
'IntlChar::getPropertyValueEnum' => ['int', 'property'=>'int', 'name'=>'string'],
'IntlChar::getPropertyValueName' => ['string|false', 'prop'=>'int', 'val'=>'int', 'namechoice='=>'int'],
'IntlChar::getUnicodeVersion' => ['array'],
'IntlChar::hasBinaryProperty' => ['bool', 'char'=>'int|string', 'property'=>'int'],
'IntlChar::isalnum' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isalpha' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isbase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isblank' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::iscntrl' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isdefined' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isdigit' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isgraph' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDIgnorable' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDPart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isIDStart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isISOControl' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaIDPart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaIDStart' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isJavaSpaceChar' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::islower' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isMirrored' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isprint' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::ispunct' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isspace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::istitle' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUAlphabetic' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isULowercase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isupper' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUUppercase' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isUWhiteSpace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isWhitespace' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::isxdigit' => ['bool', 'codepoint'=>'mixed'],
'IntlChar::ord' => ['int', 'character'=>'mixed'],
'IntlChar::tolower' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::totitle' => ['mixed', 'codepoint'=>'mixed'],
'IntlChar::toupper' => ['mixed', 'codepoint'=>'mixed'],
'IntlCodePointBreakIterator::__construct' => ['void'],
'IntlCodePointBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlCodePointBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlCodePointBreakIterator::current' => ['int'],
'IntlCodePointBreakIterator::first' => ['int'],
'IntlCodePointBreakIterator::following' => ['int', 'offset'=>'string'],
'IntlCodePointBreakIterator::getErrorCode' => ['int'],
'IntlCodePointBreakIterator::getErrorMessage' => ['string'],
'IntlCodePointBreakIterator::getLastCodePoint' => ['int'],
'IntlCodePointBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlCodePointBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'string'],
'IntlCodePointBreakIterator::getText' => ['string'],
'IntlCodePointBreakIterator::isBoundary' => ['bool', 'offset'=>'string'],
'IntlCodePointBreakIterator::last' => ['int'],
'IntlCodePointBreakIterator::next' => ['int', 'offset='=>'string'],
'IntlCodePointBreakIterator::preceding' => ['int', 'offset'=>'string'],
'IntlCodePointBreakIterator::previous' => ['int'],
'IntlCodePointBreakIterator::setText' => ['bool', 'text'=>'string'],
'IntlDateFormatter::__construct' => ['void', 'locale'=>'string', 'datetype'=>'?int', 'timetype'=>'?int', 'timezone='=>'null|string|IntlTimeZone|DateTimeZone', 'calendar='=>'null|int|IntlCalendar', 'pattern='=>'string'],
'IntlDateFormatter::create' => ['IntlDateFormatter|false', 'locale'=>'string', 'datetype'=>'int', 'timetype'=>'int', 'timezone='=>'null|string|IntlTimeZone|DateTimeZone', 'calendar='=>'int|IntlCalendar', 'pattern='=>'string'],
'IntlDateFormatter::format' => ['string|false', 'args'=>''],
'IntlDateFormatter::formatObject' => ['string|false', 'object'=>'object', 'format='=>'mixed', 'locale='=>'string'],
'IntlDateFormatter::getCalendar' => ['int'],
'IntlDateFormatter::getCalendarObject' => ['IntlCalendar'],
'IntlDateFormatter::getDateType' => ['int'],
'IntlDateFormatter::getErrorCode' => ['int'],
'IntlDateFormatter::getErrorMessage' => ['string'],
'IntlDateFormatter::getLocale' => ['string|false'],
'IntlDateFormatter::getPattern' => ['string'],
'IntlDateFormatter::getTimeType' => ['int'],
'IntlDateFormatter::getTimeZone' => ['IntlTimeZone|false'],
'IntlDateFormatter::getTimeZoneId' => ['string'],
'IntlDateFormatter::isLenient' => ['bool'],
'IntlDateFormatter::localtime' => ['array', 'text_to_parse'=>'string', '&w_parse_pos='=>'int'],
'IntlDateFormatter::parse' => ['int|false', 'text_to_parse'=>'string', '&rw_parse_pos='=>'int'],
'IntlDateFormatter::setCalendar' => ['bool', 'calendar'=>''],
'IntlDateFormatter::setLenient' => ['bool', 'lenient'=>'bool'],
'IntlDateFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'IntlDateFormatter::setTimeZone' => ['bool', 'timezone'=>''],
'IntlDateFormatter::setTimeZoneId' => ['bool', 'zone'=>'string', 'fmt='=>'IntlDateFormatter'],
'IntlException::__clone' => ['void'],
'IntlException::__construct' => ['void'],
'IntlException::__toString' => ['string'],
'IntlException::__wakeup' => ['void'],
'IntlException::getCode' => ['int'],
'IntlException::getFile' => ['string'],
'IntlException::getLine' => ['int'],
'IntlException::getMessage' => ['string'],
'IntlException::getPrevious' => ['?Throwable'],
'IntlException::getTrace' => ['array<int,array<string,mixed>>'],
'IntlException::getTraceAsString' => ['string'],
'intlgregcal_create_instance' => ['IntlGregorianCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'intlgregcal_get_gregorian_change' => ['float', 'obj'=>'IntlGregorianCalendar'],
'intlgregcal_is_leap_year' => ['bool', 'year'=>'int'],
'intlgregcal_set_gregorian_change' => ['void', 'obj'=>'IntlGregorianCalendar', 'change'=>'float'],
'IntlGregorianCalendar::__construct' => ['void'],
'IntlGregorianCalendar::add' => ['bool', 'field'=>'int', 'amount'=>'int'],
'IntlGregorianCalendar::after' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::before' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::clear' => ['bool', 'field='=>'int'],
'IntlGregorianCalendar::createInstance' => ['IntlGregorianCalendar', 'timeZone='=>'mixed', 'locale='=>'string'],
'IntlGregorianCalendar::equals' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::fieldDifference' => ['int', 'when'=>'float', 'field'=>'int'],
'IntlGregorianCalendar::fromDateTime' => ['IntlCalendar', 'dateTime'=>'DateTime|string'],
'IntlGregorianCalendar::get' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getActualMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getActualMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getAvailableLocales' => ['array'],
'IntlGregorianCalendar::getDayOfWeekType' => ['int', 'dayOfWeek'=>'int'],
'IntlGregorianCalendar::getErrorCode' => ['int'],
'IntlGregorianCalendar::getErrorMessage' => ['string'],
'IntlGregorianCalendar::getFirstDayOfWeek' => ['int'],
'IntlGregorianCalendar::getGreatestMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getGregorianChange' => ['float'],
'IntlGregorianCalendar::getKeywordValuesForLocale' => ['Iterator', 'key'=>'string', 'locale'=>'string', 'commonlyUsed'=>'bool'],
'IntlGregorianCalendar::getLeastMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getLocale' => ['string', 'localeType'=>'int'],
'IntlGregorianCalendar::getMaximum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getMinimalDaysInFirstWeek' => ['int'],
'IntlGregorianCalendar::getMinimum' => ['int', 'field'=>'int'],
'IntlGregorianCalendar::getNow' => ['float'],
'IntlGregorianCalendar::getRepeatedWallTimeOption' => ['int'],
'IntlGregorianCalendar::getSkippedWallTimeOption' => ['int'],
'IntlGregorianCalendar::getTime' => ['float'],
'IntlGregorianCalendar::getTimeZone' => ['IntlTimeZone'],
'IntlGregorianCalendar::getType' => ['string'],
'IntlGregorianCalendar::getWeekendTransition' => ['int', 'dayOfWeek'=>'string'],
'IntlGregorianCalendar::inDaylightTime' => ['bool'],
'IntlGregorianCalendar::isEquivalentTo' => ['bool', 'other'=>'IntlCalendar'],
'IntlGregorianCalendar::isLeapYear' => ['bool', 'year'=>'int'],
'IntlGregorianCalendar::isLenient' => ['bool'],
'IntlGregorianCalendar::isSet' => ['bool', 'field'=>'int'],
'IntlGregorianCalendar::isWeekend' => ['bool', 'date='=>'float'],
'IntlGregorianCalendar::roll' => ['bool', 'field'=>'int', 'amountOrUpOrDown'=>'mixed'],
'IntlGregorianCalendar::set' => ['bool', 'field'=>'int', 'value'=>'int'],
'IntlGregorianCalendar::set\'1' => ['bool', 'year'=>'int', 'month'=>'int', 'dayOfMonth='=>'int', 'hour='=>'int', 'minute='=>'int', 'second='=>'int'],
'IntlGregorianCalendar::setFirstDayOfWeek' => ['bool', 'dayOfWeek'=>'int'],
'IntlGregorianCalendar::setGregorianChange' => ['bool', 'date'=>'float'],
'IntlGregorianCalendar::setLenient' => ['bool', 'isLenient'=>'string'],
'IntlGregorianCalendar::setMinimalDaysInFirstWeek' => ['bool', 'minimalDays'=>'int'],
'IntlGregorianCalendar::setRepeatedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlGregorianCalendar::setSkippedWallTimeOption' => ['bool', 'wallTimeOption'=>'int'],
'IntlGregorianCalendar::setTime' => ['bool', 'date'=>'float'],
'IntlGregorianCalendar::setTimeZone' => ['bool', 'timeZone'=>'mixed'],
'IntlGregorianCalendar::toDateTime' => ['DateTime'],
'IntlIterator::__construct' => ['void'],
'IntlIterator::current' => ['mixed'],
'IntlIterator::key' => ['string'],
'IntlIterator::next' => ['void'],
'IntlIterator::rewind' => ['void'],
'IntlIterator::valid' => ['bool'],
'IntlPartsIterator::getBreakIterator' => ['IntlBreakIterator'],
'IntlRuleBasedBreakIterator::__construct' => ['void', 'rules'=>'string', 'areCompiled='=>'string'],
'IntlRuleBasedBreakIterator::createCharacterInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createCodePointInstance' => ['IntlCodePointBreakIterator'],
'IntlRuleBasedBreakIterator::createLineInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createSentenceInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createTitleInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::createWordInstance' => ['IntlRuleBasedBreakIterator', 'locale='=>'string'],
'IntlRuleBasedBreakIterator::current' => ['int'],
'IntlRuleBasedBreakIterator::first' => ['int'],
'IntlRuleBasedBreakIterator::following' => ['int', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::getBinaryRules' => ['string'],
'IntlRuleBasedBreakIterator::getErrorCode' => ['int'],
'IntlRuleBasedBreakIterator::getErrorMessage' => ['string'],
'IntlRuleBasedBreakIterator::getLocale' => ['string', 'locale_type'=>'string'],
'IntlRuleBasedBreakIterator::getPartsIterator' => ['IntlPartsIterator', 'key_type='=>'int'],
'IntlRuleBasedBreakIterator::getRules' => ['string'],
'IntlRuleBasedBreakIterator::getRuleStatus' => ['int'],
'IntlRuleBasedBreakIterator::getRuleStatusVec' => ['array'],
'IntlRuleBasedBreakIterator::getText' => ['string'],
'IntlRuleBasedBreakIterator::isBoundary' => ['bool', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::last' => ['int'],
'IntlRuleBasedBreakIterator::next' => ['int', 'offset='=>'int'],
'IntlRuleBasedBreakIterator::preceding' => ['int', 'offset'=>'int'],
'IntlRuleBasedBreakIterator::previous' => ['int'],
'IntlRuleBasedBreakIterator::setText' => ['bool', 'text'=>'string'],
'IntlTimeZone::countEquivalentIDs' => ['int|false', 'zoneId'=>'string'],
'IntlTimeZone::createDefault' => ['IntlTimeZone'],
'IntlTimeZone::createEnumeration' => ['IntlIterator|false', 'countryOrRawOffset='=>'mixed'],
'IntlTimeZone::createTimeZone' => ['IntlTimeZone|false', 'zoneId'=>'string'],
'IntlTimeZone::createTimeZoneIDEnumeration' => ['IntlIterator|false', 'zoneType'=>'int', 'region='=>'string', 'rawOffset='=>'int'],
'IntlTimeZone::fromDateTimeZone' => ['?IntlTimeZone', 'zoneId'=>'DateTimeZone'],
'IntlTimeZone::getCanonicalID' => ['string|false', 'zoneId'=>'string', '&w_isSystemID='=>'bool'],
'IntlTimeZone::getDisplayName' => ['string|false', 'isDaylight='=>'bool', 'style='=>'int', 'locale='=>'string'],
'IntlTimeZone::getDSTSavings' => ['int'],
'IntlTimeZone::getEquivalentID' => ['string|false', 'zoneId'=>'string', 'index'=>'int'],
'IntlTimeZone::getErrorCode' => ['int'],
'IntlTimeZone::getErrorMessage' => ['string'],
'IntlTimeZone::getGMT' => ['IntlTimeZone'],
'IntlTimeZone::getID' => ['string'],
'IntlTimeZone::getIDForWindowsID' => ['string', 'timezone'=>'string', 'region='=>'string'],
'IntlTimeZone::getOffset' => ['int', 'date'=>'float', 'local'=>'bool', '&w_rawOffset'=>'int', '&w_dstOffset'=>'int'],
'IntlTimeZone::getRawOffset' => ['int'],
'IntlTimeZone::getRegion' => ['string|false', 'zoneId'=>'string'],
'IntlTimeZone::getTZDataVersion' => ['string'],
'IntlTimeZone::getUnknown' => ['IntlTimeZone'],
'IntlTimeZone::getWindowsID' => ['string|false', 'timezone'=>'string'],
'IntlTimeZone::hasSameRules' => ['bool', 'otherTimeZone'=>'IntlTimeZone'],
'IntlTimeZone::toDateTimeZone' => ['DateTimeZone|false'],
'IntlTimeZone::useDaylightTime' => ['bool'],
'intltz_count_equivalent_ids' => ['int', 'zoneId'=>'string'],
'intltz_create_enumeration' => ['IntlIterator', 'countryOrRawOffset'=>'mixed'],
'intltz_create_time_zone' => ['IntlTimeZone', 'zoneId'=>'string'],
'intltz_from_date_time_zone' => ['IntlTimeZone', 'zoneId'=>'DateTimeZone'],
'intltz_get_canonical_id' => ['string', 'zoneId'=>'string', '&isSystemID'=>'bool'],
'intltz_get_display_name' => ['string', 'obj'=>'IntlTimeZone', 'isDaylight'=>'bool', 'style'=>'int', 'locale'=>'string'],
'intltz_get_dst_savings' => ['int', 'obj'=>'IntlTimeZone'],
'intltz_get_equivalent_id' => ['string', 'zoneId'=>'string', 'index'=>'int'],
'intltz_get_error_code' => ['int', 'obj'=>'IntlTimeZone'],
'intltz_get_error_message' => ['string', 'obj'=>'IntlTimeZone'],
'intltz_get_id' => ['string', 'obj'=>'IntlTimeZone'],
'intltz_get_offset' => ['int', 'obj'=>'IntlTimeZone', 'date'=>'float', 'local'=>'bool', '&rawOffset'=>'int', '&dstOffset'=>'int'],
'intltz_get_raw_offset' => ['int', 'obj'=>'IntlTimeZone'],
'intltz_get_tz_data_version' => ['string', 'obj'=>'IntlTimeZone'],
'intltz_getGMT' => ['IntlTimeZone'],
'intltz_has_same_rules' => ['bool', 'obj'=>'IntlTimeZone', 'otherTimeZone'=>'IntlTimeZone'],
'intltz_to_date_time_zone' => ['DateTimeZone', 'obj'=>'IntlTimeZone'],
'intltz_use_daylight_time' => ['bool', 'obj'=>'IntlTimeZone'],
'intlz_create_default' => ['IntlTimeZone'],
'intval' => ['int', 'var'=>'mixed', 'base='=>'int'],
'InvalidArgumentException::__clone' => ['void'],
'InvalidArgumentException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?InvalidArgumentException'],
'InvalidArgumentException::__toString' => ['string'],
'InvalidArgumentException::getCode' => ['int'],
'InvalidArgumentException::getFile' => ['string'],
'InvalidArgumentException::getLine' => ['int'],
'InvalidArgumentException::getMessage' => ['string'],
'InvalidArgumentException::getPrevious' => ['Throwable|InvalidArgumentException|null'],
'InvalidArgumentException::getTrace' => ['array'],
'InvalidArgumentException::getTraceAsString' => ['string'],
'ip2long' => ['int|false', 'ip_address'=>'string'],
'iptcembed' => ['mixed|false', 'iptcdata'=>'string', 'jpeg_file_name'=>'string', 'spool='=>'int'],
'iptcparse' => ['array|false', 'iptcdata'=>'string'],
'is_a' => ['bool', 'object_or_string'=>'object|string', 'class_name'=>'string', 'allow_string='=>'bool'],
'is_array' => ['bool', 'var'=>'mixed'],
'is_bool' => ['bool', 'var'=>'mixed'],
'is_callable' => ['bool', 'var'=>'callable|mixed', 'syntax_only='=>'bool', '&w_callable_name='=>'string'],
'is_countable' => ['bool', 'var'=>'mixed'],
'is_dir' => ['bool', 'filename'=>'string'],
'is_double' => ['bool', 'var'=>'mixed'],
'is_executable' => ['bool', 'filename'=>'string'],
'is_file' => ['bool', 'filename'=>'string'],
'is_finite' => ['bool', 'val'=>'float'],
'is_float' => ['bool', 'var'=>'mixed'],
'is_infinite' => ['bool', 'val'=>'float'],
'is_int' => ['bool', 'var'=>'mixed'],
'is_integer' => ['bool', 'var'=>'mixed'],
'is_iterable' => ['bool', 'var'=>'mixed'],
'is_link' => ['bool', 'filename'=>'string'],
'is_long' => ['bool', 'var'=>'mixed'],
'is_nan' => ['bool', 'val'=>'float'],
'is_null' => ['bool', 'var'=>'mixed'],
'is_numeric' => ['bool', 'value'=>'mixed'],
'is_object' => ['bool', 'var'=>'mixed'],
'is_readable' => ['bool', 'filename'=>'string'],
'is_real' => ['bool', 'var'=>'mixed'],
'is_resource' => ['bool', 'var'=>'mixed'],
'is_scalar' => ['bool', 'value'=>'mixed'],
'is_soap_fault' => ['bool', 'object'=>'mixed'],
'is_string' => ['bool', 'var'=>'mixed'],
'is_subclass_of' => ['bool', 'object_or_string'=>'object|string', 'class_name'=>'string', 'allow_string='=>'bool'],
'is_tainted' => ['bool', 'string'=>'string'],
'is_uploaded_file' => ['bool', 'path'=>'string'],
'is_writable' => ['bool', 'filename'=>'string'],
'is_writeable' => ['bool', 'filename'=>'string'],
'isset' => ['bool', 'var'=>'mixed', '...rest='=>'mixed'],
'Iterator::current' => ['mixed'],
'Iterator::key' => ['mixed'],
'Iterator::next' => ['void'],
'Iterator::rewind' => ['void'],
'Iterator::valid' => ['bool'],
'iterator_apply' => ['int', 'it'=>'Traversable', 'function'=>'callable(mixed):bool', 'params='=>'array'],
'iterator_count' => ['int', 'it'=>'Traversable'],
'iterator_to_array' => ['array', 'it'=>'Traversable', 'use_keys='=>'bool'],
'IteratorAggregate::getIterator' => ['Traversable'],
'IteratorIterator::__construct' => ['void', 'it'=>'Traversable'],
'IteratorIterator::current' => ['mixed'],
'IteratorIterator::getInnerIterator' => ['Traversable'],
'IteratorIterator::key' => ['mixed'],
'IteratorIterator::next' => ['void'],
'IteratorIterator::rewind' => ['void'],
'IteratorIterator::valid' => ['bool'],
'java_last_exception_clear' => ['void'],
'java_last_exception_get' => ['object'],
'java_reload' => ['array', 'new_jarpath'=>'string'],
'java_require' => ['array', 'new_classpath'=>'string'],
'java_set_encoding' => ['array', 'encoding'=>'string'],
'java_set_ignore_case' => ['void', 'ignore'=>'bool'],
'java_throw_exceptions' => ['void', 'throw'=>'bool'],
'JavaException::getCause' => ['object'],
'jddayofweek' => ['mixed', 'juliandaycount'=>'int', 'mode='=>'int'],
'jdmonthname' => ['string', 'juliandaycount'=>'int', 'mode'=>'int'],
'jdtofrench' => ['string', 'juliandaycount'=>'int'],
'jdtogregorian' => ['string', 'juliandaycount'=>'int'],
'jdtojewish' => ['string', 'juliandaycount'=>'int', 'hebrew='=>'bool', 'fl='=>'int'],
'jdtojulian' => ['string', 'juliandaycount'=>'int'],
'jdtounix' => ['int|false', 'jday'=>'int'],
'jewishtojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'jobqueue_license_info' => ['array'],
'join' => ['string', 'glue'=>'string', 'pieces'=>'array'],
'join\'1' => ['string', 'pieces'=>'array'],
'jpeg2wbmp' => ['bool', 'jpegname'=>'string', 'wbmpname'=>'string', 'dest_height'=>'int', 'dest_width'=>'int', 'threshold'=>'int'],
'json_decode' => ['mixed', 'json'=>'string', 'assoc='=>'bool', 'depth='=>'int', 'options='=>'int'],
'json_encode' => ['string|false', 'data'=>'mixed', 'options='=>'int', 'depth='=>'int'],
'json_last_error' => ['int'],
'json_last_error_msg' => ['string'],
'JsonException::__clone' => ['void'],
'JsonException::__construct' => ['void'],
'JsonException::__toString' => ['string'],
'JsonException::__wakeup' => ['void'],
'JsonException::getCode' => ['int'],
'JsonException::getFile' => ['string'],
'JsonException::getLine' => ['int'],
'JsonException::getMessage' => ['string'],
'JsonException::getPrevious' => ['?Throwable'],
'JsonException::getTrace' => ['array<int,array<string,mixed>>'],
'JsonException::getTraceAsString' => ['string'],
'JsonIncrementalParser::__construct' => ['void', 'depth'=>'', 'options'=>''],
'JsonIncrementalParser::get' => ['', 'options'=>''],
'JsonIncrementalParser::getError' => [''],
'JsonIncrementalParser::parse' => ['', 'json'=>''],
'JsonIncrementalParser::parseFile' => ['', 'filename'=>''],
'JsonIncrementalParser::reset' => [''],
'JsonSerializable::jsonSerialize' => ['mixed'],
'Judy::__construct' => ['void', 'judy_type'=>'int'],
'Judy::__destruct' => ['void'],
'Judy::byCount' => ['int', 'nth_index'=>'int'],
'Judy::count' => ['int', 'index_start='=>'int', 'index_end='=>'int'],
'Judy::first' => ['mixed', 'index='=>'mixed'],
'Judy::firstEmpty' => ['mixed', 'index='=>'mixed'],
'Judy::free' => ['int'],
'Judy::getType' => ['int'],
'Judy::last' => ['mixed', 'index='=>'string'],
'Judy::lastEmpty' => ['mixed', 'index='=>'int'],
'Judy::memoryUsage' => ['int'],
'Judy::next' => ['mixed', 'index'=>'mixed'],
'Judy::nextEmpty' => ['mixed', 'index'=>'mixed'],
'Judy::offsetExists' => ['bool', 'offset'=>'mixed'],
'Judy::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Judy::offsetSet' => ['bool', 'offset'=>'mixed', 'value'=>'mixed'],
'Judy::offsetUnset' => ['bool', 'offset'=>'mixed'],
'Judy::prev' => ['mixed', 'index'=>'mixed'],
'Judy::prevEmpty' => ['mixed', 'index'=>'mixed'],
'Judy::size' => ['int'],
'judy_type' => ['int', 'array'=>'judy'],
'judy_version' => ['string'],
'juliantojd' => ['int', 'month'=>'int', 'day'=>'int', 'year'=>'int'],
'kadm5_chpass_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'password'=>'string'],
'kadm5_create_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'password='=>'string', 'options='=>'array'],
'kadm5_delete_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string'],
'kadm5_destroy' => ['bool', 'handle'=>'resource'],
'kadm5_flush' => ['bool', 'handle'=>'resource'],
'kadm5_get_policies' => ['array', 'handle'=>'resource'],
'kadm5_get_principal' => ['array', 'handle'=>'resource', 'principal'=>'string'],
'kadm5_get_principals' => ['array', 'handle'=>'resource'],
'kadm5_init_with_password' => ['resource', 'admin_server'=>'string', 'realm'=>'string', 'principal'=>'string', 'password'=>'string'],
'kadm5_modify_principal' => ['bool', 'handle'=>'resource', 'principal'=>'string', 'options'=>'array'],
'key' => ['int|string|null', 'array_arg'=>'array'],
'key_exists' => ['bool', 'key'=>'string|int', 'search'=>'array'],
'krsort' => ['bool', '&rw_array_arg'=>'array', 'sort_flags='=>'int'],
'ksort' => ['bool', '&rw_array_arg'=>'array', 'sort_flags='=>'int'],
'KTaglib_ID3v2_AttachedPictureFrame::getDescription' => ['string'],
'KTaglib_ID3v2_AttachedPictureFrame::getMimeType' => ['string'],
'KTaglib_ID3v2_AttachedPictureFrame::getType' => ['int'],
'KTaglib_ID3v2_AttachedPictureFrame::savePicture' => ['bool', 'filename'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setMimeType' => ['string', 'type'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setPicture' => ['', 'filename'=>'string'],
'KTaglib_ID3v2_AttachedPictureFrame::setType' => ['', 'type'=>'int'],
'KTaglib_ID3v2_Frame::__toString' => ['string'],
'KTaglib_ID3v2_Frame::getDescription' => ['string'],
'KTaglib_ID3v2_Frame::getMimeType' => ['string'],
'KTaglib_ID3v2_Frame::getSize' => ['int'],
'KTaglib_ID3v2_Frame::getType' => ['int'],
'KTaglib_ID3v2_Frame::savePicture' => ['bool', 'filename'=>'string'],
'KTaglib_ID3v2_Frame::setMimeType' => ['string', 'type'=>'string'],
'KTaglib_ID3v2_Frame::setPicture' => ['void', 'filename'=>'string'],
'KTaglib_ID3v2_Frame::setType' => ['void', 'type'=>'int'],
'KTaglib_ID3v2_Tag::addFrame' => ['bool', 'frame'=>'KTaglib_ID3v2_Frame'],
'KTaglib_ID3v2_Tag::getFrameList' => ['array'],
'KTaglib_MPEG_AudioProperties::getBitrate' => ['int'],
'KTaglib_MPEG_AudioProperties::getChannels' => ['int'],
'KTaglib_MPEG_AudioProperties::getLayer' => ['int'],
'KTaglib_MPEG_AudioProperties::getLength' => ['int'],
'KTaglib_MPEG_AudioProperties::getSampleBitrate' => ['int'],
'KTaglib_MPEG_AudioProperties::getVersion' => ['int'],
'KTaglib_MPEG_AudioProperties::isCopyrighted' => ['bool'],
'KTaglib_MPEG_AudioProperties::isOriginal' => ['bool'],
'KTaglib_MPEG_AudioProperties::isProtectionEnabled' => ['bool'],
'KTaglib_MPEG_File::getAudioProperties' => ['KTaglib_MPEG_File'],
'KTaglib_MPEG_File::getID3v1Tag' => ['KTaglib_ID3v1_Tag', 'create='=>'bool'],
'KTaglib_MPEG_File::getID3v2Tag' => ['KTaglib_ID3v2_Tag', 'create='=>'bool'],
'KTaglib_Tag::getAlbum' => ['string'],
'KTaglib_Tag::getArtist' => ['string'],
'KTaglib_Tag::getComment' => ['string'],
'KTaglib_Tag::getGenre' => ['string'],
'KTaglib_Tag::getTitle' => ['string'],
'KTaglib_Tag::getTrack' => ['int'],
'KTaglib_Tag::getYear' => ['int'],
'KTaglib_Tag::isEmpty' => ['bool'],
'labelcacheObj::freeCache' => ['bool'],
'labelObj::__construct' => ['void'],
'labelObj::convertToString' => ['string'],
'labelObj::deleteStyle' => ['int', 'index'=>'int'],
'labelObj::free' => ['void'],
'labelObj::getBinding' => ['string', 'labelbinding'=>'mixed'],
'labelObj::getExpressionString' => ['string'],
'labelObj::getStyle' => ['styleObj', 'index'=>'int'],
'labelObj::getTextString' => ['string'],
'labelObj::moveStyleDown' => ['int', 'index'=>'int'],
'labelObj::moveStyleUp' => ['int', 'index'=>'int'],
'labelObj::removeBinding' => ['int', 'labelbinding'=>'mixed'],
'labelObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'labelObj::setBinding' => ['int', 'labelbinding'=>'mixed', 'value'=>'string'],
'labelObj::setExpression' => ['int', 'expression'=>'string'],
'labelObj::setText' => ['int', 'text'=>'string'],
'labelObj::updateFromString' => ['int', 'snippet'=>'string'],
'Lapack::eigenValues' => ['array', 'a'=>'array', 'left='=>'array', 'right='=>'array'],
'Lapack::identity' => ['array', 'n'=>'int'],
'Lapack::leastSquaresByFactorisation' => ['array', 'a'=>'array', 'b'=>'array'],
'Lapack::leastSquaresBySVD' => ['array', 'a'=>'array', 'b'=>'array'],
'Lapack::pseudoInverse' => ['array', 'a'=>'array'],
'Lapack::singularValues' => ['array', 'a'=>'array'],
'Lapack::solveLinearEquation' => ['array', 'a'=>'array', 'b'=>'array'],
'layerObj::addFeature' => ['int', 'shape'=>'shapeObj'],
'layerObj::applySLD' => ['int', 'sldxml'=>'string', 'namedlayer'=>'string'],
'layerObj::applySLDURL' => ['int', 'sldurl'=>'string', 'namedlayer'=>'string'],
'layerObj::clearProcessing' => ['void'],
'layerObj::close' => ['void'],
'layerObj::convertToString' => ['string'],
'layerObj::draw' => ['int', 'image'=>'imageObj'],
'layerObj::drawQuery' => ['int', 'image'=>'imageObj'],
'layerObj::free' => ['void'],
'layerObj::generateSLD' => ['string'],
'layerObj::getClass' => ['classObj', 'classIndex'=>'int'],
'layerObj::getClassIndex' => ['int', 'shape'=>'', 'classgroup'=>'', 'numclasses'=>''],
'layerObj::getExtent' => ['rectObj'],
'layerObj::getFilterString' => ['?string'],
'layerObj::getGridIntersectionCoordinates' => ['array'],
'layerObj::getItems' => ['array'],
'layerObj::getMetaData' => ['int', 'name'=>'string'],
'layerObj::getNumResults' => ['int'],
'layerObj::getProcessing' => ['array'],
'layerObj::getProjection' => ['string'],
'layerObj::getResult' => ['resultObj', 'index'=>'int'],
'layerObj::getResultsBounds' => ['rectObj'],
'layerObj::getShape' => ['shapeObj', 'result'=>'resultObj'],
'layerObj::getWMSFeatureInfoURL' => ['string', 'clickX'=>'int', 'clickY'=>'int', 'featureCount'=>'int', 'infoFormat'=>'string'],
'layerObj::isVisible' => ['bool'],
'layerObj::moveclassdown' => ['int', 'index'=>'int'],
'layerObj::moveclassup' => ['int', 'index'=>'int'],
'layerObj::ms_newLayerObj' => ['layerObj', 'map'=>'mapObj', 'layer'=>'layerObj'],
'layerObj::nextShape' => ['shapeObj'],
'layerObj::open' => ['int'],
'layerObj::queryByAttributes' => ['int', 'qitem'=>'string', 'qstring'=>'string', 'mode'=>'int'],
'layerObj::queryByFeatures' => ['int', 'slayer'=>'int'],
'layerObj::queryByPoint' => ['int', 'point'=>'pointObj', 'mode'=>'int', 'buffer'=>'float'],
'layerObj::queryByRect' => ['int', 'rect'=>'rectObj'],
'layerObj::queryByShape' => ['int', 'shape'=>'shapeObj'],
'layerObj::removeClass' => ['?classObj', 'index'=>'int'],
'layerObj::removeMetaData' => ['int', 'name'=>'string'],
'layerObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'layerObj::setConnectionType' => ['int', 'connectiontype'=>'int', 'plugin_library'=>'string'],
'layerObj::setFilter' => ['int', 'expression'=>'string'],
'layerObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'layerObj::setProjection' => ['int', 'proj_params'=>'string'],
'layerObj::setWKTProjection' => ['int', 'proj_params'=>'string'],
'layerObj::updateFromString' => ['int', 'snippet'=>'string'],
'lcfirst' => ['string', 'str'=>'string'],
'lcg_value' => ['float'],
'lchgrp' => ['bool', 'filename'=>'string', 'group'=>'string|int'],
'lchown' => ['bool', 'filename'=>'string', 'user'=>'string|int'],
'ldap_8859_to_t61' => ['string', 'value'=>'string'],
'ldap_add' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array', 'serverctrls='=>'array'],
'ldap_add_ext' => ['resource|false', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array', 'serverctrls='=>'array'],
'ldap_bind' => ['bool', 'link_identifier'=>'resource', 'bind_rdn='=>'string|null', 'bind_password='=>'string|null', 'serverctrls=' => 'array'],
'ldap_bind_ext' => ['resource|false', 'link_identifier'=>'resource', 'bind_rdn='=>'string|null', 'bind_password='=>'string|null', 'serverctrls' => 'array'],
'ldap_close' => ['bool', 'link_identifier'=>'resource'],
'ldap_compare' => ['bool|int', 'link_identifier'=>'resource', 'dn'=>'string', 'attr'=>'string', 'value'=>'string'],
'ldap_connect' => ['resource|false', 'host='=>'string', 'port='=>'int', 'wallet='=>'string', 'wallet_passwd='=>'string', 'authmode='=>'int'],
'ldap_control_paged_result' => ['bool', 'link_identifier'=>'resource', 'pagesize'=>'int', 'iscritical='=>'bool', 'cookie='=>'string'],
'ldap_control_paged_result_response' => ['bool', 'link_identifier'=>'resource', 'result_identifier'=>'resource', '&w_cookie'=>'string', '&w_estimated'=>'int'],
'ldap_count_entries' => ['int|false', 'link_identifier'=>'resource', 'result'=>'resource'],
'ldap_delete' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string'],
'ldap_delete_ext' => ['resource|false', 'link_identifier'=>'resource', 'dn'=>'string', 'serverctrls='=>'array'],
'ldap_dn2ufn' => ['string', 'dn'=>'string'],
'ldap_err2str' => ['string', 'errno'=>'int'],
'ldap_errno' => ['int', 'link_identifier'=>'resource'],
'ldap_error' => ['string', 'link_identifier'=>'resource'],
'ldap_escape' => ['string', 'value'=>'string', 'ignore='=>'string', 'flags='=>'int'],
'ldap_exop' => ['mixed', 'link'=>'resource', 'reqoid'=>'string', 'reqdata='=>'string', 'serverctrls='=>'array|null', '&w_retdata='=>'string', '&w_retoid='=>'string'],
'ldap_exop_passwd' => ['mixed', 'link'=>'resource', 'user='=>'string', 'oldpw='=>'string', 'newpw='=>'string', 'serverctrls='=>'array'],
'ldap_exop_refresh' => ['int|false', 'link'=>'resource', 'dn'=>'string', 'ttl'=>'int'],
'ldap_exop_whoami' => ['string|false', 'link'=>'resource'],
'ldap_explode_dn' => ['array|false', 'dn'=>'string', 'with_attrib'=>'int'],
'ldap_first_attribute' => ['string|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource'],
'ldap_first_entry' => ['resource|false', 'link_identifier'=>'resource', 'result_identifier'=>'resource'],
'ldap_first_reference' => ['resource|false', 'link_identifier'=>'resource', 'result_identifier'=>'resource'],
'ldap_free_result' => ['bool', 'result_identifier'=>'resource'],
'ldap_get_attributes' => ['array|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource'],
'ldap_get_dn' => ['string|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource'],
'ldap_get_entries' => ['array|false', 'link_identifier'=>'resource', 'result_identifier'=>'resource'],
'ldap_get_option' => ['bool', 'link_identifier'=>'resource', 'option'=>'int', '&w_retval'=>'mixed'],
'ldap_get_values' => ['array|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource', 'attribute'=>'string'],
'ldap_get_values_len' => ['array|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource', 'attribute'=>'string'],
'ldap_list' => ['resource|false', 'link'=>'resource|array', 'base_dn'=>'string', 'filter'=>'string', 'attrs='=>'array', 'attrsonly='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_mod_add' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_add_ext' => ['resource|false', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array', 'serverctrls='=>'array'],
'ldap_mod_del' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_del_ext' => ['resource|false', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array', 'serverctrls='=>'array'],
'ldap_mod_replace' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_mod_replace_ext' => ['resource|false', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array', 'serverctrls='=>'array'],
'ldap_modify' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'entry'=>'array'],
'ldap_modify_batch' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'modifs'=>'array'],
'ldap_next_attribute' => ['string|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource'],
'ldap_next_entry' => ['resource|false', 'link_identifier'=>'resource', 'result_entry_identifier'=>'resource'],
'ldap_next_reference' => ['resource|false', 'link_identifier'=>'resource', 'reference_entry_identifier'=>'resource'],
'ldap_parse_exop' => ['bool', 'link'=>'resource', 'result'=>'resource', '&w_retdata='=>'string', '&w_retoid='=>'string'],
'ldap_parse_reference' => ['bool', 'link_identifier'=>'resource', 'reference_entry_identifier'=>'resource', 'referrals'=>'array'],
'ldap_parse_result' => ['bool', 'link_identifier'=>'resource', 'result'=>'resource', '&w_errcode'=>'int', '&w_matcheddn='=>'string', '&w_errmsg='=>'string', '&w_referrals='=>'array', '&w_serverctrls='=>'array'],
'ldap_read' => ['resource|false', 'link'=>'resource|array', 'base_dn'=>'string', 'filter'=>'string', 'attrs='=>'array', 'attrsonly='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_rename' => ['bool', 'link_identifier'=>'resource', 'dn'=>'string', 'newrdn'=>'string', 'newparent'=>'string', 'deleteoldrdn'=>'bool'],
'ldap_rename_ext' => ['resource|false', 'link_identifier'=>'resource', 'dn'=>'string', 'newrdn'=>'string', 'newparent'=>'string', 'deleteoldrdn'=>'bool', 'serverctrls='=>'array'],
'ldap_sasl_bind' => ['bool', 'link_identifier'=>'resource', 'binddn='=>'string', 'password='=>'string', 'sasl_mech='=>'string', 'sasl_realm='=>'string', 'sasl_authc_id='=>'string', 'sasl_authz_id='=>'string', 'props='=>'string'],
'ldap_search' => ['resource|false', 'link_identifier'=>'resource|resource[]', 'base_dn'=>'string', 'filter'=>'string', 'attrs='=>'array', 'attrsonly='=>'int', 'sizelimit='=>'int', 'timelimit='=>'int', 'deref='=>'int'],
'ldap_set_option' => ['bool', 'link_identifier'=>'resource|null', 'option'=>'int', 'newval'=>'mixed'],
'ldap_set_rebind_proc' => ['bool', 'link_identifier'=>'resource', 'callback'=>'string'],
'ldap_sort' => ['bool', 'link_identifier'=>'resource', 'result_identifier'=>'resource', 'sortfilter'=>'string'],
'ldap_start_tls' => ['bool', 'link_identifier'=>'resource'],
'ldap_t61_to_8859' => ['string', 'value'=>'string'],
'ldap_unbind' => ['bool', 'link_identifier'=>'resource'],
'leak' => ['', 'num_bytes'=>'int'],
'leak_variable' => ['', 'variable'=>'', 'leak_data'=>'bool'],
'legendObj::convertToString' => ['string'],
'legendObj::free' => ['void'],
'legendObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'legendObj::updateFromString' => ['int', 'snippet'=>'string'],
'LengthException::__clone' => ['void'],
'LengthException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?LengthException'],
'LengthException::__toString' => ['string'],
'LengthException::getCode' => ['int'],
'LengthException::getFile' => ['string'],
'LengthException::getLine' => ['int'],
'LengthException::getMessage' => ['string'],
'LengthException::getPrevious' => ['Throwable|LengthException|null'],
'LengthException::getTrace' => ['array'],
'LengthException::getTraceAsString' => ['string'],
'LevelDB::__construct' => ['void', 'name'=>'string', 'options='=>'array', 'read_options='=>'array', 'write_options='=>'array'],
'LevelDB::close' => [''],
'LevelDB::compactRange' => ['', 'start'=>'', 'limit'=>''],
'LevelDB::delete' => ['bool', 'key'=>'string', 'write_options='=>'array'],
'LevelDB::destroy' => ['', 'name'=>'', 'options='=>'array'],
'LevelDB::get' => ['bool|string', 'key'=>'string', 'read_options='=>'array'],
'LevelDB::getApproximateSizes' => ['', 'start'=>'', 'limit'=>''],
'LevelDB::getIterator' => ['LevelDBIterator', 'options='=>'array'],
'LevelDB::getProperty' => ['mixed', 'name'=>'string'],
'LevelDB::getSnapshot' => ['LevelDBSnapshot'],
'LevelDB::put' => ['', 'key'=>'string', 'value'=>'string', 'write_options='=>'array'],
'LevelDB::repair' => ['', 'name'=>'', 'options='=>'array'],
'LevelDB::set' => ['', 'key'=>'string', 'value'=>'string', 'write_options='=>'array'],
'LevelDB::write' => ['', 'batch'=>'LevelDBWriteBatch', 'write_options='=>'array'],
'LevelDBIterator::__construct' => ['void', 'db'=>'LevelDB', 'read_options='=>'array'],
'LevelDBIterator::current' => ['mixed'],
'LevelDBIterator::destroy' => [''],
'LevelDBIterator::getError' => [''],
'LevelDBIterator::key' => ['int|string'],
'LevelDBIterator::last' => [''],
'LevelDBIterator::next' => ['void'],
'LevelDBIterator::prev' => [''],
'LevelDBIterator::rewind' => ['void'],
'LevelDBIterator::seek' => ['', 'key'=>''],
'LevelDBIterator::valid' => ['bool'],
'LevelDBSnapshot::__construct' => ['void', 'db'=>'LevelDB'],
'LevelDBSnapshot::release' => [''],
'LevelDBWriteBatch::__construct' => ['void', 'name'=>'', 'options='=>'array', 'read_options='=>'array', 'write_options='=>'array'],
'LevelDBWriteBatch::clear' => [''],
'LevelDBWriteBatch::delete' => ['', 'key'=>'', 'write_options='=>'array'],
'LevelDBWriteBatch::put' => ['', 'key'=>'', 'value'=>'', 'write_options='=>'array'],
'LevelDBWriteBatch::set' => ['', 'key'=>'', 'value'=>'', 'write_options='=>'array'],
'levenshtein' => ['int', 'str1'=>'string', 'str2'=>'string'],
'levenshtein\'1' => ['int', 'str1'=>'string', 'str2'=>'string', 'cost_ins'=>'int', 'cost_rep'=>'int', 'cost_del'=>'int'],
'libxml_clear_errors' => ['void'],
'libxml_disable_entity_loader' => ['bool', 'disable='=>'bool'],
'libxml_get_errors' => ['array<int,libXMLError>'],
'libxml_get_last_error' => ['libXMLError|false'],
'libxml_set_external_entity_loader' => ['bool', 'resolver_function'=>'callable'],
'libxml_set_streams_context' => ['void', 'streams_context'=>'resource'],
'libxml_use_internal_errors' => ['bool', 'use_errors='=>'bool'],
'LimitIterator::__construct' => ['void', 'iterator'=>'Iterator', 'offset='=>'int', 'count='=>'int'],
'LimitIterator::current' => ['mixed'],
'LimitIterator::getInnerIterator' => ['Iterator'],
'LimitIterator::getPosition' => ['int'],
'LimitIterator::key' => ['mixed'],
'LimitIterator::next' => ['void'],
'LimitIterator::rewind' => ['void'],
'LimitIterator::seek' => ['int', 'position'=>'int'],
'LimitIterator::valid' => ['bool'],
'lineObj::__construct' => ['void'],
'lineObj::add' => ['int', 'point'=>'pointObj'],
'lineObj::addXY' => ['int', 'x'=>'float', 'y'=>'float', 'm'=>'float'],
'lineObj::addXYZ' => ['int', 'x'=>'float', 'y'=>'float', 'z'=>'float', 'm'=>'float'],
'lineObj::ms_newLineObj' => ['lineObj'],
'lineObj::point' => ['pointObj', 'i'=>'int'],
'lineObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'link' => ['bool', 'target'=>'string', 'link'=>'string'],
'linkinfo' => ['int|false', 'filename'=>'string'],
'litespeed_request_headers' => ['array'],
'litespeed_response_headers' => ['array'],
'Locale::acceptFromHttp' => ['string|false', 'header'=>'string'],
'Locale::canonicalize' => ['string', 'locale'=>'string'],
'Locale::composeLocale' => ['string', 'subtags'=>'array'],
'Locale::filterMatches' => ['bool', 'langtag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'Locale::getAllVariants' => ['array', 'locale'=>'string'],
'Locale::getDefault' => ['string'],
'Locale::getDisplayLanguage' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayName' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayRegion' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayScript' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getDisplayVariant' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'Locale::getKeywords' => ['array|false', 'locale'=>'string'],
'Locale::getPrimaryLanguage' => ['string', 'locale'=>'string'],
'Locale::getRegion' => ['string', 'locale'=>'string'],
'Locale::getScript' => ['string', 'locale'=>'string'],
'Locale::lookup' => ['string', 'langtag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'default='=>'string'],
'Locale::parseLocale' => ['array', 'locale'=>'string'],
'Locale::setDefault' => ['bool', 'locale'=>'string'],
'locale_accept_from_http' => ['string|false', 'header'=>'string'],
'locale_canonicalize' => ['string', 'arg1'=>'string'],
'locale_compose' => ['string|false', 'subtags'=>'array'],
'locale_filter_matches' => ['bool', 'langtag'=>'string', 'locale'=>'string', 'canonicalize='=>'bool'],
'locale_get_all_variants' => ['array', 'locale'=>'string'],
'locale_get_default' => ['string'],
'locale_get_display_language' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'locale_get_display_name' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'locale_get_display_region' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'locale_get_display_script' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'locale_get_display_variant' => ['string', 'locale'=>'string', 'in_locale='=>'string'],
'locale_get_keywords' => ['array|false', 'locale'=>'string'],
'locale_get_primary_language' => ['string', 'locale'=>'string'],
'locale_get_region' => ['string', 'locale'=>'string'],
'locale_get_script' => ['string', 'locale'=>'string'],
'locale_lookup' => ['string', 'langtag'=>'array', 'locale'=>'string', 'canonicalize='=>'bool', 'default='=>'string'],
'locale_parse' => ['array', 'locale'=>'string'],
'locale_set_default' => ['bool', 'locale'=>'string'],
'localeconv' => ['array'],
'localtime' => ['array', 'timestamp='=>'int', 'associative_array='=>'bool'],
'log' => ['float', 'number'=>'float', 'base='=>'float'],
'log10' => ['float', 'number'=>'float'],
'log1p' => ['float', 'number'=>'float'],
'LogicException::__clone' => ['void'],
'LogicException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?LogicException'],
'LogicException::__toString' => ['string'],
'LogicException::getCode' => ['int'],
'LogicException::getFile' => ['string'],
'LogicException::getLine' => ['int'],
'LogicException::getMessage' => ['string'],
'LogicException::getPrevious' => ['Throwable|LogicException|null'],
'LogicException::getTrace' => ['array'],
'LogicException::getTraceAsString' => ['string'],
'long2ip' => ['string', 'proper_address'=>'string|int'],
'lstat' => ['array|false', 'filename'=>'string'],
'ltrim' => ['string', 'str'=>'string', 'character_mask='=>'string'],
'Lua::__call' => ['mixed', 'lua_func'=>'callable', 'args='=>'array', 'use_self='=>'int'],
'Lua::__construct' => ['void', 'lua_script_file'=>'string'],
'Lua::assign' => ['?Lua', 'name'=>'string', 'value'=>'mixed'],
'Lua::call' => ['mixed', 'lua_func'=>'callable', 'args='=>'array', 'use_self='=>'int'],
'Lua::eval' => ['mixed', 'statements'=>'string'],
'Lua::getVersion' => ['string'],
'Lua::include' => ['mixed', 'file'=>'string'],
'Lua::registerCallback' => ['Lua|null|false', 'name'=>'string', 'function'=>'callable'],
'LuaClosure::__invoke' => ['void', 'arg'=>'mixed', '...args='=>'mixed'],
'lzf_compress' => ['string', 'data'=>'string'],
'lzf_decompress' => ['string', 'data'=>'string'],
'lzf_optimized_for' => ['int'],
'm_checkstatus' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_completeauthorizations' => ['int', 'conn'=>'resource', 'array'=>'int'],
'm_connect' => ['int', 'conn'=>'resource'],
'm_connectionerror' => ['string', 'conn'=>'resource'],
'm_deletetrans' => ['bool', 'conn'=>'resource', 'identifier'=>'int'],
'm_destroyconn' => ['bool', 'conn'=>'resource'],
'm_destroyengine' => ['void'],
'm_getcell' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column'=>'string', 'row'=>'int'],
'm_getcellbynum' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column'=>'int', 'row'=>'int'],
'm_getcommadelimited' => ['string', 'conn'=>'resource', 'identifier'=>'int'],
'm_getheader' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'column_num'=>'int'],
'm_initconn' => ['resource'],
'm_initengine' => ['int', 'location'=>'string'],
'm_iscommadelimited' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_maxconntimeout' => ['bool', 'conn'=>'resource', 'secs'=>'int'],
'm_monitor' => ['int', 'conn'=>'resource'],
'm_numcolumns' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_numrows' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_parsecommadelimited' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_responsekeys' => ['array', 'conn'=>'resource', 'identifier'=>'int'],
'm_responseparam' => ['string', 'conn'=>'resource', 'identifier'=>'int', 'key'=>'string'],
'm_returnstatus' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_setblocking' => ['int', 'conn'=>'resource', 'tf'=>'int'],
'm_setdropfile' => ['int', 'conn'=>'resource', 'directory'=>'string'],
'm_setip' => ['int', 'conn'=>'resource', 'host'=>'string', 'port'=>'int'],
'm_setssl' => ['int', 'conn'=>'resource', 'host'=>'string', 'port'=>'int'],
'm_setssl_cafile' => ['int', 'conn'=>'resource', 'cafile'=>'string'],
'm_setssl_files' => ['int', 'conn'=>'resource', 'sslkeyfile'=>'string', 'sslcertfile'=>'string'],
'm_settimeout' => ['int', 'conn'=>'resource', 'seconds'=>'int'],
'm_sslcert_gen_hash' => ['string', 'filename'=>'string'],
'm_transactionssent' => ['int', 'conn'=>'resource'],
'm_transinqueue' => ['int', 'conn'=>'resource'],
'm_transkeyval' => ['int', 'conn'=>'resource', 'identifier'=>'int', 'key'=>'string', 'value'=>'string'],
'm_transnew' => ['int', 'conn'=>'resource'],
'm_transsend' => ['int', 'conn'=>'resource', 'identifier'=>'int'],
'm_uwait' => ['int', 'microsecs'=>'int'],
'm_validateidentifier' => ['int', 'conn'=>'resource', 'tf'=>'int'],
'm_verifyconnection' => ['bool', 'conn'=>'resource', 'tf'=>'int'],
'm_verifysslcert' => ['bool', 'conn'=>'resource', 'tf'=>'int'],
'magic_quotes_runtime' => ['bool', 'new_setting'=>'bool'],
'mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array|null', 'additional_parameters='=>'string'],
'mailparse_determine_best_xfer_encoding' => ['string', 'fp'=>'resource'],
'mailparse_msg_create' => ['resource'],
'mailparse_msg_extract_part' => ['void', 'mimemail'=>'resource', 'msgbody'=>'string', 'callbackfunc='=>'callable'],
'mailparse_msg_extract_part_file' => ['string', 'mimemail'=>'resource', 'filename'=>'mixed', 'callbackfunc='=>'callable'],
'mailparse_msg_extract_whole_part_file' => ['string', 'mimemail'=>'resource', 'filename'=>'string', 'callbackfunc='=>'callable'],
'mailparse_msg_free' => ['bool', 'mimemail'=>'resource'],
'mailparse_msg_get_part' => ['resource', 'mimemail'=>'resource', 'mimesection'=>'string'],
'mailparse_msg_get_part_data' => ['array', 'mimemail'=>'resource'],
'mailparse_msg_get_structure' => ['array', 'mimemail'=>'resource'],
'mailparse_msg_parse' => ['bool', 'mimemail'=>'resource', 'data'=>'string'],
'mailparse_msg_parse_file' => ['resource|false', 'filename'=>'string'],
'mailparse_rfc822_parse_addresses' => ['array', 'addresses'=>'string'],
'mailparse_stream_encode' => ['bool', 'sourcefp'=>'resource', 'destfp'=>'resource', 'encoding'=>'string'],
'mailparse_uudecode_all' => ['array', 'fp'=>'resource'],
'mapObj::__construct' => ['void', 'map_file_name'=>'string', 'new_map_path'=>'string'],
'mapObj::appendOutputFormat' => ['int', 'outputFormat'=>'outputformatObj'],
'mapObj::applyconfigoptions' => ['int'],
'mapObj::applySLD' => ['int', 'sldxml'=>'string'],
'mapObj::applySLDURL' => ['int', 'sldurl'=>'string'],
'mapObj::convertToString' => ['string'],
'mapObj::draw' => ['?imageObj'],
'mapObj::drawLabelCache' => ['int', 'image'=>'imageObj'],
'mapObj::drawLegend' => ['imageObj'],
'mapObj::drawQuery' => ['?imageObj'],
'mapObj::drawReferenceMap' => ['imageObj'],
'mapObj::drawScaleBar' => ['imageObj'],
'mapObj::embedLegend' => ['int', 'image'=>'imageObj'],
'mapObj::embedScalebar' => ['int', 'image'=>'imageObj'],
'mapObj::free' => ['void'],
'mapObj::generateSLD' => ['string'],
'mapObj::getAllGroupNames' => ['array'],
'mapObj::getAllLayerNames' => ['array'],
'mapObj::getColorbyIndex' => ['colorObj', 'iCloIndex'=>'int'],
'mapObj::getConfigOption' => ['string', 'key'=>'string'],
'mapObj::getLabel' => ['labelcacheMemberObj', 'index'=>'int'],
'mapObj::getLayer' => ['layerObj', 'index'=>'int'],
'mapObj::getLayerByName' => ['layerObj', 'layer_name'=>'string'],
'mapObj::getLayersDrawingOrder' => ['array'],
'mapObj::getLayersIndexByGroup' => ['array', 'groupname'=>'string'],
'mapObj::getMetaData' => ['int', 'name'=>'string'],
'mapObj::getNumSymbols' => ['int'],
'mapObj::getOutputFormat' => ['?outputformatObj', 'index'=>'int'],
'mapObj::getProjection' => ['string'],
'mapObj::getSymbolByName' => ['int', 'symbol_name'=>'string'],
'mapObj::getSymbolObjectById' => ['symbolObj', 'symbolid'=>'int'],
'mapObj::loadMapContext' => ['int', 'filename'=>'string', 'unique_layer_name'=>'bool'],
'mapObj::loadOWSParameters' => ['int', 'request'=>'OwsrequestObj', 'version'=>'string'],
'mapObj::moveLayerDown' => ['int', 'layerindex'=>'int'],
'mapObj::moveLayerUp' => ['int', 'layerindex'=>'int'],
'mapObj::ms_newMapObjFromString' => ['mapObj', 'map_file_string'=>'string', 'new_map_path'=>'string'],
'mapObj::offsetExtent' => ['int', 'x'=>'float', 'y'=>'float'],
'mapObj::owsDispatch' => ['int', 'request'=>'OwsrequestObj'],
'mapObj::prepareImage' => ['imageObj'],
'mapObj::prepareQuery' => ['void'],
'mapObj::processLegendTemplate' => ['string', 'params'=>'array'],
'mapObj::processQueryTemplate' => ['string', 'params'=>'array', 'generateimages'=>'bool'],
'mapObj::processTemplate' => ['string', 'params'=>'array', 'generateimages'=>'bool'],
'mapObj::queryByFeatures' => ['int', 'slayer'=>'int'],
'mapObj::queryByIndex' => ['int', 'layerindex'=>'', 'tileindex'=>'', 'shapeindex'=>'', 'addtoquery'=>''],
'mapObj::queryByPoint' => ['int', 'point'=>'pointObj', 'mode'=>'int', 'buffer'=>'float'],
'mapObj::queryByRect' => ['int', 'rect'=>'rectObj'],
'mapObj::queryByShape' => ['int', 'shape'=>'shapeObj'],
'mapObj::removeLayer' => ['layerObj', 'nIndex'=>'int'],
'mapObj::removeMetaData' => ['int', 'name'=>'string'],
'mapObj::removeOutputFormat' => ['int', 'name'=>'string'],
'mapObj::save' => ['int', 'filename'=>'string'],
'mapObj::saveMapContext' => ['int', 'filename'=>'string'],
'mapObj::saveQuery' => ['int', 'filename'=>'string', 'results'=>'int'],
'mapObj::scaleExtent' => ['int', 'zoomfactor'=>'float', 'minscaledenom'=>'float', 'maxscaledenom'=>'float'],
'mapObj::selectOutputFormat' => ['int', 'type'=>'string'],
'mapObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'mapObj::setCenter' => ['int', 'center'=>'pointObj'],
'mapObj::setConfigOption' => ['int', 'key'=>'string', 'value'=>'string'],
'mapObj::setExtent' => ['void', 'minx'=>'float', 'miny'=>'float', 'maxx'=>'float', 'maxy'=>'float'],
'mapObj::setFontSet' => ['int', 'fileName'=>'string'],
'mapObj::setMetaData' => ['int', 'name'=>'string', 'value'=>'string'],
'mapObj::setProjection' => ['int', 'proj_params'=>'string', 'bSetUnitsAndExtents'=>'bool'],
'mapObj::setRotation' => ['int', 'rotation_angle'=>'float'],
'mapObj::setSize' => ['int', 'width'=>'int', 'height'=>'int'],
'mapObj::setSymbolSet' => ['int', 'fileName'=>'string'],
'mapObj::setWKTProjection' => ['int', 'proj_params'=>'string', 'bSetUnitsAndExtents'=>'bool'],
'mapObj::zoomPoint' => ['int', 'nZoomFactor'=>'int', 'oPixelPos'=>'pointObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj'],
'mapObj::zoomRectangle' => ['int', 'oPixelExt'=>'rectObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj'],
'mapObj::zoomScale' => ['int', 'nScaleDenom'=>'float', 'oPixelPos'=>'pointObj', 'nImageWidth'=>'int', 'nImageHeight'=>'int', 'oGeorefExt'=>'rectObj', 'oMaxGeorefExt'=>'rectObj'],
'max' => ['mixed', 'arg1'=>'array'],
'max\'1' => ['mixed', 'arg1'=>'', 'arg2'=>'', '...args='=>''],
'maxdb::__construct' => ['void', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb::affected_rows' => ['int', 'link'=>''],
'maxdb::auto_commit' => ['bool', 'link'=>'', 'mode'=>'bool'],
'maxdb::change_user' => ['bool', 'link'=>'', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'maxdb::character_set_name' => ['string', 'link'=>''],
'maxdb::close' => ['bool', 'link'=>''],
'maxdb::commit' => ['bool', 'link'=>''],
'maxdb::disable_reads_from_master' => ['', 'link'=>''],
'maxdb::errno' => ['int', 'link'=>''],
'maxdb::error' => ['string', 'link'=>''],
'maxdb::field_count' => ['int', 'link'=>''],
'maxdb::get_host_info' => ['string', 'link'=>''],
'maxdb::info' => ['string', 'link'=>''],
'maxdb::insert_id' => ['', 'link'=>''],
'maxdb::kill' => ['bool', 'link'=>'', 'processid'=>'int'],
'maxdb::more_results' => ['bool', 'link'=>''],
'maxdb::multi_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::next_result' => ['bool', 'link'=>''],
'maxdb::num_rows' => ['int', 'result'=>''],
'maxdb::options' => ['bool', 'link'=>'', 'option'=>'int', 'value'=>''],
'maxdb::ping' => ['bool', 'link'=>''],
'maxdb::prepare' => ['maxdb_stmt', 'link'=>'', 'query'=>'string'],
'maxdb::protocol_version' => ['string', 'link'=>''],
'maxdb::query' => ['', 'link'=>'', 'query'=>'string', 'resultmode='=>'int'],
'maxdb::real_connect' => ['bool', 'link'=>'', 'hostname='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb::real_escape_string' => ['string', 'link'=>'', 'escapestr'=>'string'],
'maxdb::real_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::rollback' => ['bool', 'link'=>''],
'maxdb::rpl_query_type' => ['int', 'link'=>''],
'maxdb::select_db' => ['bool', 'link'=>'', 'dbname'=>'string'],
'maxdb::send_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb::server_info' => ['string', 'link'=>''],
'maxdb::server_version' => ['int', 'link'=>''],
'maxdb::sqlstate' => ['string', 'link'=>''],
'maxdb::ssl_set' => ['bool', 'link'=>'', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'maxdb::stat' => ['string', 'link'=>''],
'maxdb::stmt_init' => ['object', 'link'=>''],
'maxdb::store_result' => ['bool', 'link'=>''],
'maxdb::thread_id' => ['int', 'link'=>''],
'maxdb::use_result' => ['resource', 'link'=>''],
'maxdb::warning_count' => ['int', 'link'=>''],
'maxdb_affected_rows' => ['int', 'link'=>'resource'],
'maxdb_autocommit' => ['bool', 'link'=>'', 'mode'=>'bool'],
'maxdb_change_user' => ['bool', 'link'=>'', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'maxdb_character_set_name' => ['string', 'link'=>''],
'maxdb_close' => ['bool', 'link'=>''],
'maxdb_commit' => ['bool', 'link'=>''],
'maxdb_connect' => ['resource', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb_connect_errno' => ['int'],
'maxdb_connect_error' => ['string'],
'maxdb_data_seek' => ['bool', 'result'=>'', 'offset'=>'int'],
'maxdb_debug' => ['void', 'debug'=>'string'],
'maxdb_disable_reads_from_master' => ['', 'link'=>''],
'maxdb_disable_rpl_parse' => ['bool', 'link'=>'resource'],
'maxdb_dump_debug_info' => ['bool', 'link'=>'resource'],
'maxdb_embedded_connect' => ['resource', 'dbname='=>'string'],
'maxdb_enable_reads_from_master' => ['bool', 'link'=>'resource'],
'maxdb_enable_rpl_parse' => ['bool', 'link'=>'resource'],
'maxdb_errno' => ['int', 'link'=>'resource'],
'maxdb_error' => ['string', 'link'=>'resource'],
'maxdb_fetch_array' => ['', 'result'=>'', 'resulttype='=>'int'],
'maxdb_fetch_assoc' => ['array', 'result'=>''],
'maxdb_fetch_field' => ['', 'result'=>''],
'maxdb_fetch_field_direct' => ['', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_fetch_fields' => ['', 'result'=>''],
'maxdb_fetch_lengths' => ['array', 'result'=>'resource'],
'maxdb_fetch_object' => ['object', 'result'=>'object'],
'maxdb_fetch_row' => ['', 'result'=>''],
'maxdb_field_count' => ['int', 'link'=>''],
'maxdb_field_seek' => ['bool', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_field_tell' => ['int', 'result'=>'resource'],
'maxdb_free_result' => ['', 'result'=>''],
'maxdb_get_client_info' => ['string'],
'maxdb_get_client_version' => ['int'],
'maxdb_get_host_info' => ['string', 'link'=>'resource'],
'maxdb_get_proto_info' => ['string', 'link'=>'resource'],
'maxdb_get_server_info' => ['string', 'link'=>'resource'],
'maxdb_get_server_version' => ['int', 'link'=>'resource'],
'maxdb_info' => ['string', 'link'=>'resource'],
'maxdb_init' => ['resource'],
'maxdb_insert_id' => ['mixed', 'link'=>'resource'],
'maxdb_kill' => ['bool', 'link'=>'', 'processid'=>'int'],
'maxdb_master_query' => ['bool', 'link'=>'resource', 'query'=>'string'],
'maxdb_more_results' => ['bool', 'link'=>'resource'],
'maxdb_multi_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_next_result' => ['bool', 'link'=>'resource'],
'maxdb_num_fields' => ['int', 'result'=>'resource'],
'maxdb_num_rows' => ['int', 'result'=>'resource'],
'maxdb_options' => ['bool', 'link'=>'', 'option'=>'int', 'value'=>''],
'maxdb_ping' => ['bool', 'link'=>''],
'maxdb_prepare' => ['maxdb_stmt', 'link'=>'', 'query'=>'string'],
'maxdb_query' => ['', 'link'=>'', 'query'=>'string', 'resultmode='=>'int'],
'maxdb_real_connect' => ['bool', 'link'=>'', 'hostname='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'maxdb_real_escape_string' => ['string', 'link'=>'', 'escapestr'=>'string'],
'maxdb_real_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_report' => ['bool', 'flags'=>'int'],
'maxdb_result::current_field' => ['int', 'result'=>''],
'maxdb_result::data_seek' => ['bool', 'result'=>'', 'offset'=>'int'],
'maxdb_result::fetch_array' => ['', 'result'=>'', 'resulttype='=>'int'],
'maxdb_result::fetch_assoc' => ['array', 'result'=>''],
'maxdb_result::fetch_field' => ['', 'result'=>''],
'maxdb_result::fetch_field_direct' => ['', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_result::fetch_fields' => ['', 'result'=>''],
'maxdb_result::fetch_object' => ['object', 'result'=>'object'],
'maxdb_result::fetch_row' => ['', 'result'=>''],
'maxdb_result::field_count' => ['int', 'result'=>''],
'maxdb_result::field_seek' => ['bool', 'result'=>'', 'fieldnr'=>'int'],
'maxdb_result::free' => ['', 'result'=>''],
'maxdb_result::lengths' => ['array', 'result'=>''],
'maxdb_rollback' => ['bool', 'link'=>''],
'maxdb_rpl_parse_enabled' => ['int', 'link'=>'resource'],
'maxdb_rpl_probe' => ['bool', 'link'=>'resource'],
'maxdb_rpl_query_type' => ['int', 'link'=>''],
'maxdb_select_db' => ['bool', 'link'=>'resource', 'dbname'=>'string'],
'maxdb_send_query' => ['bool', 'link'=>'', 'query'=>'string'],
'maxdb_server_end' => ['void'],
'maxdb_server_init' => ['bool', 'server='=>'array', 'groups='=>'array'],
'maxdb_sqlstate' => ['string', 'link'=>'resource'],
'maxdb_ssl_set' => ['bool', 'link'=>'', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'maxdb_stat' => ['string', 'link'=>''],
'maxdb_stmt::affected_rows' => ['int', 'stmt'=>''],
'maxdb_stmt::bind_param' => ['bool', 'stmt'=>'', 'types'=>'string', '&...rw_var'=>''],
'maxdb_stmt::bind_param\'1' => ['bool', 'stmt'=>'', 'types'=>'string', '&rw_var'=>'array'],
'maxdb_stmt::bind_result' => ['bool', 'stmt'=>'', '&w_var1'=>'', '&...w_vars='=>''],
'maxdb_stmt::close' => ['bool', 'stmt'=>''],
'maxdb_stmt::close_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int'],
'maxdb_stmt::data_seek' => ['bool', 'statement'=>'', 'offset'=>'int'],
'maxdb_stmt::errno' => ['int', 'stmt'=>''],
'maxdb_stmt::error' => ['string', 'stmt'=>''],
'maxdb_stmt::execute' => ['bool', 'stmt'=>''],
'maxdb_stmt::fetch' => ['bool', 'stmt'=>''],
'maxdb_stmt::free_result' => ['', 'stmt'=>''],
'maxdb_stmt::num_rows' => ['int', 'stmt'=>''],
'maxdb_stmt::param_count' => ['int', 'stmt'=>''],
'maxdb_stmt::prepare' => ['', 'stmt'=>'', 'query'=>'string'],
'maxdb_stmt::reset' => ['bool', 'stmt'=>''],
'maxdb_stmt::result_metadata' => ['resource', 'stmt'=>''],
'maxdb_stmt::send_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt::stmt_send_long_data' => ['bool', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt::store_result' => ['bool'],
'maxdb_stmt_affected_rows' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_bind_param' => ['bool', 'stmt'=>'', 'types'=>'string', 'var1'=>'', '...args='=>'', 'var='=>'array'],
'maxdb_stmt_bind_result' => ['bool', 'stmt'=>'', '&w_var1'=>'', '&...w_vars='=>''],
'maxdb_stmt_close' => ['bool', 'stmt'=>''],
'maxdb_stmt_close_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int'],
'maxdb_stmt_data_seek' => ['bool', 'statement'=>'', 'offset'=>'int'],
'maxdb_stmt_errno' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_error' => ['string', 'stmt'=>'resource'],
'maxdb_stmt_execute' => ['bool', 'stmt'=>''],
'maxdb_stmt_fetch' => ['bool', 'stmt'=>''],
'maxdb_stmt_free_result' => ['', 'stmt'=>''],
'maxdb_stmt_init' => ['object', 'link'=>''],
'maxdb_stmt_num_rows' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_param_count' => ['int', 'stmt'=>'resource'],
'maxdb_stmt_prepare' => ['', 'stmt'=>'', 'query'=>'string'],
'maxdb_stmt_reset' => ['bool', 'stmt'=>''],
'maxdb_stmt_result_metadata' => ['resource', 'stmt'=>''],
'maxdb_stmt_send_long_data' => ['bool', 'stmt'=>'', 'param_nr'=>'int', 'data'=>'string'],
'maxdb_stmt_sqlstate' => ['string', 'stmt'=>'resource'],
'maxdb_stmt_store_result' => ['bool', 'stmt'=>''],
'maxdb_store_result' => ['bool', 'link'=>''],
'maxdb_thread_id' => ['int', 'link'=>'resource'],
'maxdb_thread_safe' => ['bool'],
'maxdb_use_result' => ['resource', 'link'=>''],
'maxdb_warning_count' => ['int', 'link'=>'resource'],
'mb_check_encoding' => ['bool', 'var='=>'string', 'encoding='=>'string'],
'mb_chr' => ['string|false', 'cp'=>'int', 'encoding='=>'string'],
'mb_convert_case' => ['string|false', 'sourcestring'=>'string', 'mode'=>'int', 'encoding='=>'string'],
'mb_convert_encoding' => ['string|false', 'str'=>'string', 'to_encoding'=>'string', 'from_encoding='=>'string|string[]'],
'mb_convert_kana' => ['string|false', 'str'=>'string', 'option='=>'string', 'encoding='=>'string'],
'mb_convert_variables' => ['string|false', 'to_encoding'=>'string', 'from_encoding'=>'array|string', '&rw_vars'=>'string|array|object', '&...rw_vars='=>'string|array|object'],
'mb_decode_mimeheader' => ['string', 'string'=>'string'],
'mb_decode_numericentity' => ['string|false', 'string'=>'string', 'convmap'=>'array', 'encoding='=>'string', 'is_hex='=>'bool'],
'mb_detect_encoding' => ['string|false', 'str'=>'string', 'encoding_list='=>'mixed', 'strict='=>'bool'],
'mb_detect_order' => ['bool|string[]', 'encoding_list='=>'mixed'],
'mb_encode_mimeheader' => ['string|false', 'str'=>'string', 'charset='=>'string', 'transfer_encoding='=>'string', 'linefeed='=>'string', 'indent='=>'int'],
'mb_encode_numericentity' => ['string|false', 'string'=>'string', 'convmap'=>'array', 'encoding='=>'string', 'is_hex='=>'bool'],
'mb_encoding_aliases' => ['string[]|false', 'encoding'=>'string'],
'mb_ereg' => ['int|false', 'pattern'=>'string', 'string'=>'string', '&w_registers='=>'array'],
'mb_ereg_match' => ['bool', 'pattern'=>'string', 'string'=>'string', 'option='=>'string'],
'mb_ereg_replace' => ['string|false', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'option='=>'string'],
'mb_ereg_replace_callback' => ['string|false', 'pattern'=>'string', 'callback'=>'callable', 'string'=>'string', 'option='=>'string'],
'mb_ereg_search' => ['bool', 'pattern='=>'string', 'option='=>'string'],
'mb_ereg_search_getpos' => ['int'],
'mb_ereg_search_getregs' => ['string[]|false'],
'mb_ereg_search_init' => ['bool', 'string'=>'string', 'pattern='=>'string', 'option='=>'string'],
'mb_ereg_search_pos' => ['int[]|false', 'pattern='=>'string', 'option='=>'string'],
'mb_ereg_search_regs' => ['string[]|false', 'pattern='=>'string', 'option='=>'string'],
'mb_ereg_search_setpos' => ['bool', 'position'=>'int'],
'mb_eregi' => ['int|false', 'pattern'=>'string', 'string'=>'string', '&w_registers='=>'array'],
'mb_eregi_replace' => ['string|false', 'pattern'=>'string', 'replacement'=>'string', 'string'=>'string', 'option='=>'string'],
'mb_get_info' => ['array|mixed', 'type='=>'string'],
'mb_http_input' => ['string|false', 'type='=>'string'],
'mb_http_output' => ['string|bool', 'encoding='=>'string'],
'mb_internal_encoding' => ['string|bool', 'encoding='=>'string'],
'mb_language' => ['string|bool', 'language='=>'string'],
'mb_list_encodings' => ['string[]'],
'mb_ord' => ['int|false', 'str'=>'string', 'enc='=>'string'],
'mb_output_handler' => ['string', 'contents'=>'string', 'status'=>'int'],
'mb_parse_str' => ['bool', 'encoded_string'=>'string', '&w_result='=>'array'],
'mb_preferred_mime_name' => ['string|false', 'encoding'=>'string'],
'mb_regex_encoding' => ['string|bool', 'encoding='=>'string'],
'mb_regex_set_options' => ['string', 'options='=>'string'],
'mb_scrub' => ['string|false', 'str'=>'string', 'enc='=>'string'],
'mb_send_mail' => ['bool', 'to'=>'string', 'subject'=>'string', 'message'=>'string', 'additional_headers='=>'string|array', 'additional_parameter='=>'string'],
'mb_split' => ['array<int,string>', 'pattern'=>'string', 'string'=>'string', 'limit='=>'int'],
'mb_strcut' => ['string|false', 'str'=>'string', 'start'=>'int', 'length='=>'int', 'encoding='=>'string'],
'mb_strimwidth' => ['string|false', 'str'=>'string', 'start'=>'int', 'width'=>'int', 'trimmarker='=>'string', 'encoding='=>'string'],
'mb_stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'part='=>'bool', 'encoding='=>'string'],
'mb_strlen' => ['int|false', 'str'=>'string', 'encoding='=>'string'],
'mb_strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'part='=>'bool', 'encoding='=>'string'],
'mb_strrichr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'part='=>'bool', 'encoding='=>'string'],
'mb_strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'encoding='=>'string'],
'mb_strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'string', 'part='=>'bool', 'encoding='=>'string'],
'mb_strtolower' => ['string|false', 'str'=>'string', 'encoding='=>'string'],
'mb_strtoupper' => ['string|false', 'str'=>'string', 'encoding='=>'string'],
'mb_strwidth' => ['int|false', 'str'=>'string', 'encoding='=>'string'],
'mb_substitute_character' => ['bool|int|string', 'substchar='=>'mixed'],
'mb_substr' => ['string|false', 'str'=>'string', 'start'=>'int', 'length='=>'?int', 'encoding='=>'string'],
'mb_substr_count' => ['int|false', 'haystack'=>'string', 'needle'=>'string', 'encoding='=>'string'],
'mcrypt_cbc' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_cfb' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_create_iv' => ['string|false', 'size'=>'int', 'source='=>'int'],
'mcrypt_decrypt' => ['string', 'cipher'=>'string', 'key'=>'string', 'data'=>'string', 'mode'=>'string', 'iv='=>'string'],
'mcrypt_ecb' => ['string', 'cipher'=>'string|int', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'mcrypt_enc_get_algorithms_name' => ['string', 'td'=>'resource'],
'mcrypt_enc_get_block_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_iv_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_key_size' => ['int', 'td'=>'resource'],
'mcrypt_enc_get_modes_name' => ['string', 'td'=>'resource'],
'mcrypt_enc_get_supported_key_sizes' => ['array', 'td'=>'resource'],
'mcrypt_enc_is_block_algorithm' => ['bool', 'td'=>'resource'],
'mcrypt_enc_is_block_algorithm_mode' => ['bool', 'td'=>'resource'],
'mcrypt_enc_is_block_mode' => ['bool', 'td'=>'resource'],
'mcrypt_enc_self_test' => ['int|false', 'td'=>'resource'],
'mcrypt_encrypt' => ['string', 'cipher'=>'string', 'key'=>'string', 'data'=>'string', 'mode'=>'string', 'iv='=>'string'],
'mcrypt_generic' => ['string', 'td'=>'resource', 'data'=>'string'],
'mcrypt_generic_deinit' => ['bool', 'td'=>'resource'],
'mcrypt_generic_end' => ['bool', 'td'=>'resource'],
'mcrypt_generic_init' => ['int|false', 'td'=>'resource', 'key'=>'string', 'iv'=>'string'],
'mcrypt_get_block_size' => ['int', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_get_cipher_name' => ['string|false', 'cipher'=>'int|string'],
'mcrypt_get_iv_size' => ['int|false', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_get_key_size' => ['int', 'cipher'=>'int|string', 'module'=>'string'],
'mcrypt_list_algorithms' => ['array', 'lib_dir='=>'string'],
'mcrypt_list_modes' => ['array', 'lib_dir='=>'string'],
'mcrypt_module_close' => ['bool', 'td'=>'resource'],
'mcrypt_module_get_algo_block_size' => ['int', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_get_algo_key_size' => ['int', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_get_supported_key_sizes' => ['array', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_algorithm' => ['bool', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_algorithm_mode' => ['bool', 'mode'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_is_block_mode' => ['bool', 'mode'=>'string', 'lib_dir='=>'string'],
'mcrypt_module_open' => ['resource|false', 'cipher'=>'string', 'cipher_directory'=>'string', 'mode'=>'string', 'mode_directory'=>'string'],
'mcrypt_module_self_test' => ['bool', 'algorithm'=>'string', 'lib_dir='=>'string'],
'mcrypt_ofb' => ['string', 'cipher'=>'int|string', 'key'=>'string', 'data'=>'string', 'mode'=>'int', 'iv='=>'string'],
'md5' => ['string', 'str'=>'string', 'raw_output='=>'bool'],
'md5_file' => ['string|false', 'filename'=>'string', 'raw_output='=>'bool'],
'mdecrypt_generic' => ['string', 'td'=>'resource', 'data'=>'string'],
'Memcache::add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::addServer' => ['bool', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable', 'timeoutms='=>'int'],
'Memcache::append' => [''],
'Memcache::cas' => [''],
'Memcache::close' => ['bool'],
'Memcache::connect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'Memcache::decrement' => ['int', 'key'=>'string', 'value='=>'int'],
'Memcache::delete' => ['bool', 'key'=>'string', 'timeout='=>'int'],
'Memcache::findServer' => [''],
'Memcache::flush' => ['bool'],
'Memcache::get' => ['array', 'key'=>'string', 'flags='=>'array', 'keys='=>'array'],
'Memcache::getExtendedStats' => ['array', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'Memcache::getServerStatus' => ['int', 'host'=>'string', 'port='=>'int'],
'Memcache::getStats' => ['array', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'Memcache::getVersion' => ['string'],
'Memcache::increment' => ['int', 'key'=>'string', 'value='=>'int'],
'Memcache::pconnect' => ['Memcache|false', 'host'=>'string', 'port='=>'int', 'timeout='=>'int'],
'Memcache::prepend' => ['string'],
'Memcache::replace' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::set' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'Memcache::setCompressThreshold' => ['bool', 'threshold'=>'int', 'min_savings='=>'float'],
'Memcache::setFailureCallback' => [''],
'Memcache::setServerParams' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'callable'],
'memcache_add' => ['void'],
'memcache_add_server' => ['void'],
'memcache_append' => ['void'],
'memcache_cas' => ['void'],
'memcache_close' => ['void'],
'memcache_connect' => ['bool', 'host'=>'string', 'port'=>'int', 'timeout='=>'int'],
'memcache_debug' => ['bool', 'on_off'=>'bool'],
'memcache_decrement' => ['void'],
'memcache_delete' => ['void'],
'memcache_flush' => ['void'],
'memcache_get' => ['void'],
'memcache_get_extended_stats' => ['void'],
'memcache_get_server_status' => ['void'],
'memcache_get_stats' => ['void'],
'memcache_get_version' => ['void'],
'memcache_increment' => ['void'],
'memcache_pconnect' => ['Memcache', 'host'=>'', 'port='=>'null', 'timeout='=>'int'],
'memcache_prepend' => ['void'],
'memcache_replace' => ['void'],
'memcache_set' => ['void'],
'memcache_set_compress_threshold' => ['void'],
'memcache_set_failure_callback' => ['void'],
'memcache_set_server_params' => ['void'],
'Memcached::__construct' => ['void', 'persistent_id='=>'mixed|string', 'on_new_object_cb='=>'mixed'],
'Memcached::add' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::addByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::addServer' => ['bool', 'host'=>'string', 'port'=>'int', 'weight='=>'int'],
'Memcached::addServers' => ['bool', 'servers'=>'array'],
'Memcached::append' => ['bool', 'key'=>'string', 'value'=>'string'],
'Memcached::appendByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'string'],
'Memcached::cas' => ['bool', 'cas_token'=>'float', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::casByKey' => ['bool', 'cas_token'=>'float', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::decrement' => ['int|false', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::decrementByKey' => ['int|false', 'server_key'=>'string', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::delete' => ['bool', 'key'=>'string', 'time='=>'int'],
'Memcached::deleteByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'time='=>'int'],
'Memcached::deleteMulti' => ['array', 'keys'=>'array', 'time='=>'int'],
'Memcached::deleteMultiByKey' => ['bool', 'server_key'=>'string', 'keys'=>'array', 'time='=>'int'],
'Memcached::fetch' => ['array|false'],
'Memcached::fetchAll' => ['array|false'],
'Memcached::flush' => ['bool', 'delay='=>'int'],
'Memcached::flushBuffers' => [''],
'Memcached::get' => ['mixed|false', 'key'=>'string', 'cache_cb='=>'?callable', 'flags='=>'int'],
'Memcached::getAllKeys' => ['array|false'],
'Memcached::getByKey' => ['mixed|false', 'server_key'=>'string', 'key'=>'string', 'value_cb='=>'?callable', 'flags='=>'int'],
'Memcached::getDelayed' => ['bool', 'keys'=>'array', 'with_cas='=>'bool', 'value_cb='=>'callable'],
'Memcached::getDelayedByKey' => ['bool', 'server_key'=>'string', 'keys'=>'array', 'with_cas='=>'bool', 'value_cb='=>'?callable'],
'Memcached::getLastDisconnectedServer' => [''],
'Memcached::getLastErrorCode' => [''],
'Memcached::getLastErrorErrno' => [''],
'Memcached::getLastErrorMessage' => [''],
'Memcached::getMulti' => ['array|false', 'keys'=>'array', 'flags='=>'int'],
'Memcached::getMultiByKey' => ['array|false', 'server_key'=>'string', 'keys'=>'array', 'flags='=>'int'],
'Memcached::getOption' => ['mixed|false', 'option'=>'int'],
'Memcached::getResultCode' => ['int'],
'Memcached::getResultMessage' => ['string'],
'Memcached::getServerByKey' => ['array', 'server_key'=>'string'],
'Memcached::getServerList' => ['array'],
'Memcached::getStats' => ['array', 'type='=>'?string'],
'Memcached::getVersion' => ['array'],
'Memcached::increment' => ['int|false', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::incrementByKey' => ['int|false', 'server_key'=>'string', 'key'=>'string', 'offset='=>'int', 'initial_value='=>'int', 'expiry='=>'int'],
'Memcached::isPersistent' => ['bool'],
'Memcached::isPristine' => ['bool'],
'Memcached::prepend' => ['bool', 'key'=>'string', 'value'=>'string'],
'Memcached::prependByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'string'],
'Memcached::quit' => ['bool'],
'Memcached::replace' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::replaceByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::resetServerList' => ['bool'],
'Memcached::set' => ['bool', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::setBucket' => ['', 'host_map'=>'array', 'forward_map'=>'array', 'replicas'=>''],
'Memcached::setByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'value'=>'mixed', 'expiration='=>'int'],
'Memcached::setEncodingKey' => ['', 'key'=>''],
'Memcached::setMulti' => ['bool', 'items'=>'array', 'expiration='=>'int'],
'Memcached::setMultiByKey' => ['bool', 'server_key'=>'string', 'items'=>'array', 'expiration='=>'int'],
'Memcached::setOption' => ['bool', 'option'=>'int', 'value'=>'mixed'],
'Memcached::setOptions' => ['bool', 'options'=>'array'],
'Memcached::setSaslAuthData' => ['void', 'username'=>'string', 'password'=>'string'],
'Memcached::touch' => ['bool', 'key'=>'string', 'expiration'=>'int'],
'Memcached::touchByKey' => ['bool', 'server_key'=>'string', 'key'=>'string', 'expiration'=>'int'],
'MemcachePool::add' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::addServer' => ['bool', 'host'=>'string', 'port='=>'int', 'persistent='=>'bool', 'weight='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'?callable', 'timeoutms='=>'int'],
'MemcachePool::append' => [''],
'MemcachePool::cas' => [''],
'MemcachePool::close' => ['bool'],
'MemcachePool::connect' => ['bool', 'host'=>'string', 'port'=>'int', 'timeout='=>'int'],
'MemcachePool::decrement' => ['int|false', 'key'=>'', 'value='=>'int|mixed'],
'MemcachePool::delete' => ['bool', 'key'=>'', 'timeout='=>'int|mixed'],
'MemcachePool::findServer' => [''],
'MemcachePool::flush' => ['bool'],
'MemcachePool::get' => ['array|string|false', 'key'=>'array|string', '&flags='=>'array|int'],
'MemcachePool::getExtendedStats' => ['array|false', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'MemcachePool::getServerStatus' => ['int', 'host'=>'string', 'port='=>'int'],
'MemcachePool::getStats' => ['array|false', 'type='=>'string', 'slabid='=>'int', 'limit='=>'int'],
'MemcachePool::getVersion' => ['string|false'],
'MemcachePool::increment' => ['int|false', 'key'=>'', 'value='=>'int|mixed'],
'MemcachePool::prepend' => ['string'],
'MemcachePool::replace' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::set' => ['bool', 'key'=>'string', 'var'=>'mixed', 'flag='=>'int', 'expire='=>'int'],
'MemcachePool::setCompressThreshold' => ['bool', 'thresold'=>'int', 'min_saving='=>'float'],
'MemcachePool::setFailureCallback' => [''],
'MemcachePool::setServerParams' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'int', 'retry_interval='=>'int', 'status='=>'bool', 'failure_callback='=>'?callable'],
'memory_get_peak_usage' => ['int', 'real_usage='=>'bool'],
'memory_get_usage' => ['int', 'real_usage='=>'bool'],
'MessageFormatter::__construct' => ['void', 'locale'=>'string', 'pattern'=>'string'],
'MessageFormatter::create' => ['MessageFormatter', 'locale'=>'string', 'pattern'=>'string'],
'MessageFormatter::format' => ['false|string', 'args'=>'array'],
'MessageFormatter::formatMessage' => ['false|string', 'locale'=>'string', 'pattern'=>'string', 'args'=>'array'],
'MessageFormatter::getErrorCode' => ['int'],
'MessageFormatter::getErrorMessage' => ['string'],
'MessageFormatter::getLocale' => ['string'],
'MessageFormatter::getPattern' => ['string'],
'MessageFormatter::parse' => ['array|false', 'value'=>'string'],
'MessageFormatter::parseMessage' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'source'=>'string'],
'MessageFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'metaphone' => ['string|false', 'text'=>'string', 'phones='=>'int'],
'method_exists' => ['bool', 'object'=>'object|class-string', 'method'=>'string'],
'mhash' => ['string', 'hash'=>'int', 'data'=>'string', 'key='=>'string'],
'mhash_count' => ['int'],
'mhash_get_block_size' => ['int|false', 'hash'=>'int'],
'mhash_get_hash_name' => ['string|false', 'hash'=>'int'],
'mhash_keygen_s2k' => ['string|false', 'hash'=>'int', 'input_password'=>'string', 'salt'=>'string', 'bytes'=>'int'],
'microtime' => ['string', 'get_as_float='=>'false'],
'microtime\'1' => ['float', 'get_as_float='=>'true'],
'mime_content_type' => ['string|false', 'filename_or_stream'=>'string'],
'min' => ['mixed', 'arg1'=>'array'],
'min\'1' => ['mixed', 'arg1'=>'', 'arg2'=>'', '...args='=>''],
'ming_keypress' => ['int', 'char'=>'string'],
'ming_setcubicthreshold' => ['void', 'threshold'=>'int'],
'ming_setscale' => ['void', 'scale'=>'float'],
'ming_setswfcompression' => ['void', 'level'=>'int'],
'ming_useconstants' => ['void', 'use'=>'int'],
'ming_useswfversion' => ['void', 'version'=>'int'],
'mkdir' => ['bool', 'pathname'=>'string', 'mode='=>'int', 'recursive='=>'bool', 'context='=>'resource'],
'mktime' => ['int|false', 'hour='=>'int', 'min='=>'int', 'sec='=>'int', 'mon='=>'int', 'day='=>'int', 'year='=>'int'],
'money_format' => ['string', 'format'=>'string', 'value'=>'float'],
'Mongo::__construct' => ['void', 'server='=>'string', 'options='=>'array', 'driver_options='=>'array'],
'Mongo::__get' => ['MongoDB', 'dbname'=>'string'],
'Mongo::__toString' => ['string'],
'Mongo::close' => ['bool'],
'Mongo::connect' => ['bool'],
'Mongo::connectUtil' => ['bool'],
'Mongo::dropDB' => ['array', 'db'=>'mixed'],
'Mongo::forceError' => ['bool'],
'Mongo::getConnections' => ['array'],
'Mongo::getHosts' => ['array'],
'Mongo::getPoolSize' => ['int'],
'Mongo::getReadPreference' => ['array'],
'Mongo::getSlave' => ['?string'],
'Mongo::getSlaveOkay' => ['bool'],
'Mongo::getWriteConcern' => ['array'],
'Mongo::killCursor' => ['', 'server_hash'=>'string', 'id'=>'MongoInt64|int'],
'Mongo::lastError' => ['?array'],
'Mongo::listDBs' => ['array'],
'Mongo::pairConnect' => ['bool'],
'Mongo::pairPersistConnect' => ['bool', 'username='=>'string', 'password='=>'string'],
'Mongo::persistConnect' => ['bool', 'username='=>'string', 'password='=>'string'],
'Mongo::poolDebug' => ['array'],
'Mongo::prevError' => ['array'],
'Mongo::resetError' => ['array'],
'Mongo::selectCollection' => ['MongoCollection', 'db'=>'string', 'collection'=>'string'],
'Mongo::selectDB' => ['MongoDB', 'name'=>'string'],
'Mongo::setPoolSize' => ['bool', 'size'=>'int'],
'Mongo::setReadPreference' => ['bool', 'readPreference'=>'string', 'tags='=>'array'],
'Mongo::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'Mongo::switchSlave' => ['string'],
'MongoBinData::__construct' => ['void', 'data'=>'string', 'type='=>'int'],
'MongoBinData::__toString' => ['string'],
'MongoClient::__construct' => ['void', 'server='=>'string', 'options='=>'array', 'driver_options='=>'array'],
'MongoClient::__get' => ['MongoDB', 'dbname'=>'string'],
'MongoClient::__toString' => ['string'],
'MongoClient::close' => ['bool', 'connection='=>'bool|string'],
'MongoClient::connect' => ['bool'],
'MongoClient::dropDB' => ['array', 'db'=>'mixed'],
'MongoClient::getConnections' => ['array'],
'MongoClient::getHosts' => ['array'],
'MongoClient::getReadPreference' => ['array'],
'MongoClient::getWriteConcern' => ['array'],
'MongoClient::killCursor' => ['bool', 'server_hash'=>'string', 'id'=>'int|MongoInt64'],
'MongoClient::listDBs' => ['array'],
'MongoClient::selectCollection' => ['MongoCollection', 'db'=>'string', 'collection'=>'string'],
'MongoClient::selectDB' => ['MongoDB', 'name'=>'string'],
'MongoClient::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoClient::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoClient::switchSlave' => ['string'],
'MongoCode::__construct' => ['void', 'code'=>'string', 'scope='=>'array'],
'MongoCode::__toString' => ['string'],
'MongoCollection::__construct' => ['void', 'db'=>'MongoDB', 'name'=>'string'],
'MongoCollection::__get' => ['MongoCollection', 'name'=>'string'],
'MongoCollection::__toString' => ['string'],
'MongoCollection::aggregate' => ['array', 'op'=>'array', 'op='=>'array', '...args='=>'array'],
'MongoCollection::aggregate\'1' => ['array', 'pipeline'=>'array', 'options='=>'array'],
'MongoCollection::aggregateCursor' => ['MongoCommandCursor', 'command'=>'array', 'options='=>'array'],
'MongoCollection::batchInsert' => ['array|bool', 'a'=>'array', 'options='=>'array'],
'MongoCollection::count' => ['int', 'query='=>'array', 'limit='=>'int', 'skip='=>'int'],
'MongoCollection::createDBRef' => ['array', 'a'=>'array'],
'MongoCollection::createIndex' => ['array', 'keys'=>'array', 'options='=>'array'],
'MongoCollection::deleteIndex' => ['array', 'keys'=>'string|array'],
'MongoCollection::deleteIndexes' => ['array'],
'MongoCollection::distinct' => ['array|false', 'key'=>'string', 'query='=>'array'],
'MongoCollection::drop' => ['array'],
'MongoCollection::ensureIndex' => ['bool', 'keys'=>'array', 'options='=>'array'],
'MongoCollection::find' => ['MongoCursor', 'query='=>'array', 'fields='=>'array'],
'MongoCollection::findAndModify' => ['array', 'query'=>'array', 'update='=>'array', 'fields='=>'array', 'options='=>'array'],
'MongoCollection::findOne' => ['?array', 'query='=>'array', 'fields='=>'array'],
'MongoCollection::getDBRef' => ['array', 'ref'=>'array'],
'MongoCollection::getIndexInfo' => ['array'],
'MongoCollection::getName' => ['string'],
'MongoCollection::getReadPreference' => ['array'],
'MongoCollection::getSlaveOkay' => ['bool'],
'MongoCollection::getWriteConcern' => ['array'],
'MongoCollection::group' => ['array', 'keys'=>'mixed', 'initial'=>'array', 'reduce'=>'MongoCode', 'options='=>'array'],
'MongoCollection::insert' => ['bool|array', 'a'=>'array|object', 'options='=>'array'],
'MongoCollection::parallelCollectionScan' => ['MongoCommandCursor[]', 'num_cursors'=>'int'],
'MongoCollection::remove' => ['bool|array', 'criteria='=>'array', 'options='=>'array'],
'MongoCollection::save' => ['bool|array', 'a'=>'array|object', 'options='=>'array'],
'MongoCollection::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCollection::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoCollection::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoCollection::toIndexString' => ['string', 'keys'=>'mixed'],
'MongoCollection::update' => ['bool', 'criteria'=>'array', 'newobj'=>'array', 'options='=>'array'],
'MongoCollection::validate' => ['array', 'scan_data='=>'bool'],
'MongoCommandCursor::__construct' => ['void', 'connection'=>'MongoClient', 'ns'=>'string', 'command'=>'array'],
'MongoCommandCursor::batchSize' => ['MongoCommandCursor', 'batchSize'=>'int'],
'MongoCommandCursor::createFromDocument' => ['MongoCommandCursor', 'connection'=>'MongoClient', 'hash'=>'string', 'document'=>'array'],
'MongoCommandCursor::current' => ['array'],
'MongoCommandCursor::dead' => ['bool'],
'MongoCommandCursor::getReadPreference' => ['array'],
'MongoCommandCursor::info' => ['array'],
'MongoCommandCursor::key' => ['int'],
'MongoCommandCursor::next' => ['void'],
'MongoCommandCursor::rewind' => ['array'],
'MongoCommandCursor::setReadPreference' => ['MongoCommandCursor', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCommandCursor::timeout' => ['MongoCommandCursor', 'ms'=>'int'],
'MongoCommandCursor::valid' => ['bool'],
'MongoCursor::__construct' => ['void', 'connection'=>'MongoClient', 'ns'=>'string', 'query='=>'array', 'fields='=>'array'],
'MongoCursor::addOption' => ['MongoCursor', 'key'=>'string', 'value'=>'mixed'],
'MongoCursor::awaitData' => ['MongoCursor', 'wait='=>'bool'],
'MongoCursor::batchSize' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::count' => ['int', 'foundonly='=>'bool'],
'MongoCursor::current' => ['array'],
'MongoCursor::dead' => ['bool'],
'MongoCursor::doQuery' => ['void'],
'MongoCursor::explain' => ['array'],
'MongoCursor::fields' => ['MongoCursor', 'f'=>'array'],
'MongoCursor::getNext' => ['array'],
'MongoCursor::getReadPreference' => ['array'],
'MongoCursor::hasNext' => ['bool'],
'MongoCursor::hint' => ['MongoCursor', 'key_pattern'=>'string|array|object'],
'MongoCursor::immortal' => ['MongoCursor', 'liveforever='=>'bool'],
'MongoCursor::info' => ['array'],
'MongoCursor::key' => ['string'],
'MongoCursor::limit' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::maxTimeMS' => ['MongoCursor', 'ms'=>'int'],
'MongoCursor::next' => ['array'],
'MongoCursor::partial' => ['MongoCursor', 'okay='=>'bool'],
'MongoCursor::reset' => ['void'],
'MongoCursor::rewind' => ['void'],
'MongoCursor::setFlag' => ['MongoCursor', 'flag'=>'int', 'set='=>'bool'],
'MongoCursor::setReadPreference' => ['MongoCursor', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCursor::skip' => ['MongoCursor', 'num'=>'int'],
'MongoCursor::slaveOkay' => ['MongoCursor', 'okay='=>'bool'],
'MongoCursor::snapshot' => ['MongoCursor'],
'MongoCursor::sort' => ['MongoCursor', 'fields'=>'array'],
'MongoCursor::tailable' => ['MongoCursor', 'tail='=>'bool'],
'MongoCursor::timeout' => ['MongoCursor', 'ms'=>'int'],
'MongoCursor::valid' => ['bool'],
'MongoCursorException::__clone' => ['void'],
'MongoCursorException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoCursorException::__toString' => ['string'],
'MongoCursorException::__wakeup' => ['void'],
'MongoCursorException::getCode' => ['int'],
'MongoCursorException::getFile' => ['string'],
'MongoCursorException::getHost' => ['string'],
'MongoCursorException::getLine' => ['int'],
'MongoCursorException::getMessage' => ['string'],
'MongoCursorException::getPrevious' => ['Exception|Throwable'],
'MongoCursorException::getTrace' => ['array'],
'MongoCursorException::getTraceAsString' => ['string'],
'MongoCursorInterface::__construct' => ['void'],
'MongoCursorInterface::batchSize' => ['MongoCursorInterface', 'batchSize'=>'int'],
'MongoCursorInterface::current' => ['mixed'],
'MongoCursorInterface::dead' => ['bool'],
'MongoCursorInterface::getReadPreference' => ['array'],
'MongoCursorInterface::info' => ['array'],
'MongoCursorInterface::key' => ['int|string'],
'MongoCursorInterface::next' => ['void'],
'MongoCursorInterface::rewind' => ['void'],
'MongoCursorInterface::setReadPreference' => ['MongoCursorInterface', 'read_preference'=>'string', 'tags='=>'array'],
'MongoCursorInterface::timeout' => ['MongoCursorInterface', 'ms'=>'int'],
'MongoCursorInterface::valid' => ['bool'],
'MongoDate::__construct' => ['void', 'sec='=>'int', 'usec='=>'int'],
'MongoDate::__toString' => ['string'],
'MongoDate::toDateTime' => ['DateTime'],
'MongoDB::__construct' => ['void', 'conn'=>'MongoClient', 'name'=>'string'],
'MongoDB::__get' => ['MongoCollection', 'name'=>'string'],
'MongoDB::__toString' => ['string'],
'MongoDB::authenticate' => ['array', 'username'=>'string', 'password'=>'string'],
'MongoDB::command' => ['array', 'command'=>'array'],
'MongoDB::createCollection' => ['MongoCollection', 'name'=>'string', 'capped='=>'bool', 'size='=>'int', 'max='=>'int'],
'MongoDB::createDBRef' => ['array', 'collection'=>'string', 'a'=>'mixed'],
'MongoDB::drop' => ['array'],
'MongoDB::dropCollection' => ['array', 'coll'=>'MongoCollection|string'],
'MongoDB::execute' => ['array', 'code'=>'MongoCode|string', 'args='=>'array'],
'MongoDB::forceError' => ['bool'],
'MongoDB::getCollectionInfo' => ['array', 'options='=>'array'],
'MongoDB::getCollectionNames' => ['array', 'options='=>'array'],
'MongoDB::getDBRef' => ['array', 'ref'=>'array'],
'MongoDB::getGridFS' => ['MongoGridFS', 'prefix='=>'string'],
'MongoDB::getProfilingLevel' => ['int'],
'MongoDB::getReadPreference' => ['array'],
'MongoDB::getSlaveOkay' => ['bool'],
'MongoDB::getWriteConcern' => ['array'],
'MongoDB::lastError' => ['array'],
'MongoDB::listCollections' => ['array'],
'MongoDB::prevError' => ['array'],
'MongoDB::repair' => ['array', 'preserve_cloned_files='=>'bool', 'backup_original_files='=>'bool'],
'MongoDB::resetError' => ['array'],
'MongoDB::selectCollection' => ['MongoCollection', 'name'=>'string'],
'MongoDB::setProfilingLevel' => ['int', 'level'=>'int'],
'MongoDB::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags='=>'array'],
'MongoDB::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoDB::setWriteConcern' => ['bool', 'w'=>'mixed', 'wtimeout='=>'int'],
'MongoDB\BSON\Binary::__construct' => ['void', 'data'=>'string', 'type'=>'int'],
'MongoDB\BSON\Binary::__toString' => ['string'],
'MongoDB\BSON\Binary::getData' => ['string'],
'MongoDB\BSON\Binary::getType' => ['int'],
'MongoDB\BSON\binary::jsonSerialize' => ['mixed'],
'MongoDB\BSON\binary::serialize' => ['string'],
'MongoDB\BSON\binary::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\binaryinterface::__toString' => ['string'],
'MongoDB\BSON\binaryinterface::getData' => ['string'],
'MongoDB\BSON\binaryinterface::getType' => ['int'],
'MongoDB\BSON\dbpointer::__construct' => ['void'],
'MongoDB\BSON\dbpointer::__toString' => ['string'],
'MongoDB\BSON\dbpointer::jsonSerialize' => ['mixed'],
'MongoDB\BSON\dbpointer::serialize' => ['string'],
'MongoDB\BSON\dbpointer::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Decimal128::__construct' => ['void', 'value='=>'string'],
'MongoDB\BSON\Decimal128::__toString' => ['string'],
'MongoDB\BSON\decimal128::jsonSerialize' => ['mixed'],
'MongoDB\BSON\decimal128::serialize' => ['string'],
'MongoDB\BSON\decimal128::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\decimal128interface::__toString' => ['string'],
'MongoDB\BSON\fromJSON' => ['string', 'json'=>'string'],
'MongoDB\BSON\fromPHP' => ['string', 'value'=>'array|object'],
'MongoDB\BSON\int64::__construct' => ['void'],
'MongoDB\BSON\int64::__toString' => ['string'],
'MongoDB\BSON\int64::jsonSerialize' => ['mixed'],
'MongoDB\BSON\int64::serialize' => ['string'],
'MongoDB\BSON\int64::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Javascript::__construct' => ['void', 'code'=>'string', 'scope='=>'array|object'],
'MongoDB\BSON\javascript::__toString' => ['string'],
'MongoDB\BSON\javascript::getCode' => ['string'],
'MongoDB\BSON\javascript::getScope' => ['?object'],
'MongoDB\BSON\javascript::jsonSerialize' => ['mixed'],
'MongoDB\BSON\javascript::serialize' => ['string'],
'MongoDB\BSON\javascript::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\javascriptinterface::__toString' => ['string'],
'MongoDB\BSON\javascriptinterface::getCode' => ['string'],
'MongoDB\BSON\javascriptinterface::getScope' => ['?object'],
'MongoDB\BSON\maxkey::__construct' => ['void'],
'MongoDB\BSON\maxkey::jsonSerialize' => ['mixed'],
'MongoDB\BSON\maxkey::serialize' => ['string'],
'MongoDB\BSON\maxkey::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\minkey::__construct' => ['void'],
'MongoDB\BSON\minkey::jsonSerialize' => ['mixed'],
'MongoDB\BSON\minkey::serialize' => ['string'],
'MongoDB\BSON\minkey::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\ObjectId::__construct' => ['void', 'id='=>'string'],
'MongoDB\BSON\ObjectId::__toString' => ['string'],
'MongoDB\BSON\objectid::getTimestamp' => ['int'],
'MongoDB\BSON\objectid::jsonSerialize' => ['mixed'],
'MongoDB\BSON\objectid::serialize' => ['string'],
'MongoDB\BSON\objectid::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\objectidinterface::__toString' => ['string'],
'MongoDB\BSON\objectidinterface::getTimestamp' => ['int'],
'MongoDB\BSON\Regex::__construct' => ['void', 'pattern'=>'string', 'flags='=>'string'],
'MongoDB\BSON\Regex::__toString' => ['string'],
'MongoDB\BSON\Regex::getFlags' => ['string'],
'MongoDB\BSON\Regex::getPattern' => ['string'],
'MongoDB\BSON\regex::jsonSerialize' => ['mixed'],
'MongoDB\BSON\regex::serialize' => ['string'],
'MongoDB\BSON\regex::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\regexinterface::__toString' => ['string'],
'MongoDB\BSON\regexinterface::getFlags' => ['string'],
'MongoDB\BSON\regexinterface::getPattern' => ['string'],
'MongoDB\BSON\Serializable::bsonSerialize' => ['array|object'],
'MongoDB\BSON\symbol::__construct' => ['void'],
'MongoDB\BSON\symbol::__toString' => ['string'],
'MongoDB\BSON\symbol::jsonSerialize' => ['mixed'],
'MongoDB\BSON\symbol::serialize' => ['string'],
'MongoDB\BSON\symbol::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Timestamp::__construct' => ['void', 'increment'=>'int', 'timestamp'=>'int'],
'MongoDB\BSON\Timestamp::__toString' => ['string'],
'MongoDB\BSON\timestamp::getIncrement' => ['int'],
'MongoDB\BSON\timestamp::getTimestamp' => ['int'],
'MongoDB\BSON\timestamp::jsonSerialize' => ['mixed'],
'MongoDB\BSON\timestamp::serialize' => ['string'],
'MongoDB\BSON\timestamp::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\timestampinterface::__toString' => ['string'],
'MongoDB\BSON\timestampinterface::getIncrement' => ['int'],
'MongoDB\BSON\timestampinterface::getTimestamp' => ['int'],
'MongoDB\BSON\toJSON' => ['string', 'bson'=>'string'],
'MongoDB\BSON\toPHP' => ['object', 'bson'=>'string', 'typeMap'=>'array'],
'MongoDB\BSON\undefined::__construct' => ['void'],
'MongoDB\BSON\undefined::__toString' => ['string'],
'MongoDB\BSON\undefined::jsonSerialize' => ['mixed'],
'MongoDB\BSON\undefined::serialize' => ['string'],
'MongoDB\BSON\undefined::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\Unserializable::bsonUnserialize' => ['void', 'data'=>'array'],
'MongoDB\BSON\UTCDateTime::__construct' => ['void', 'milliseconds='=>'int|DateTimeInterface'],
'MongoDB\BSON\UTCDateTime::__toString' => ['string'],
'MongoDB\BSON\utcdatetime::jsonSerialize' => ['mixed'],
'MongoDB\BSON\utcdatetime::serialize' => ['string'],
'MongoDB\BSON\UTCDateTime::toDateTime' => ['DateTime'],
'MongoDB\BSON\utcdatetime::unserialize' => ['void', 'serialized'=>'string'],
'MongoDB\BSON\utcdatetimeinterface::__toString' => ['string'],
'MongoDB\BSON\utcdatetimeinterface::toDateTime' => ['DateTime'],
'MongoDB\Driver\BulkWrite::__construct' => ['void', 'ordered='=>'bool'],
'MongoDB\Driver\BulkWrite::count' => ['int'],
'MongoDB\Driver\BulkWrite::delete' => ['void', 'filter'=>'array|object', 'deleteOptions='=>'array'],
'MongoDB\Driver\BulkWrite::insert' => ['void|MongoDB\BSON\ObjectId', 'document'=>'array|object'],
'MongoDB\Driver\BulkWrite::update' => ['void', 'filter'=>'array|object', 'newObj'=>'array|object', 'updateOptions='=>'array'],
'MongoDB\Driver\Command::__construct' => ['void', 'document'=>'array|object'],
'MongoDB\Driver\Cursor::__construct' => ['void', 'server'=>'Server', 'responseDocument'=>'string'],
'MongoDB\Driver\Cursor::getId' => ['MongoDB\Driver\CursorId'],
'MongoDB\Driver\Cursor::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\Cursor::isDead' => ['bool'],
'MongoDB\Driver\Cursor::setTypeMap' => ['void', 'typemap'=>'array'],
'MongoDB\Driver\Cursor::toArray' => ['array'],
'MongoDB\Driver\CursorId::__construct' => ['void', 'id'=>'string'],
'MongoDB\Driver\CursorId::__toString' => ['string'],
'mongodb\driver\exception\commandexception::getResultDocument' => ['object'],
'MongoDB\Driver\Exception\RuntimeException::__clone' => ['void'],
'MongoDB\Driver\Exception\RuntimeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?RuntimeException|?Throwable'],
'MongoDB\Driver\Exception\RuntimeException::__toString' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::__wakeup' => ['void'],
'MongoDB\Driver\Exception\RuntimeException::getCode' => ['int'],
'MongoDB\Driver\Exception\RuntimeException::getFile' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::getLine' => ['int'],
'MongoDB\Driver\Exception\RuntimeException::getMessage' => ['string'],
'MongoDB\Driver\Exception\RuntimeException::getPrevious' => ['RuntimeException|Throwable'],
'MongoDB\Driver\Exception\RuntimeException::getTrace' => ['array'],
'MongoDB\Driver\Exception\RuntimeException::getTraceAsString' => ['string'],
'mongodb\driver\exception\runtimeexception::hasErrorLabel' => ['bool', 'errorLabel'=>'string'],
'MongoDB\Driver\Exception\WriteException::__clone' => ['void'],
'MongoDB\Driver\Exception\WriteException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?RuntimeException|?Throwable'],
'MongoDB\Driver\Exception\WriteException::__toString' => ['string'],
'MongoDB\Driver\Exception\WriteException::__wakeup' => ['void'],
'MongoDB\Driver\Exception\WriteException::getCode' => ['int'],
'MongoDB\Driver\Exception\WriteException::getFile' => ['string'],
'MongoDB\Driver\Exception\WriteException::getLine' => ['int'],
'MongoDB\Driver\Exception\WriteException::getMessage' => ['string'],
'MongoDB\Driver\Exception\WriteException::getPrevious' => ['RuntimeException|Throwable'],
'MongoDB\Driver\Exception\WriteException::getTrace' => ['array'],
'MongoDB\Driver\Exception\WriteException::getTraceAsString' => ['string'],
'MongoDB\Driver\Exception\WriteException::getWriteResult' => ['MongoDB\Driver\WriteResult'],
'MongoDB\Driver\Manager::__construct' => ['void', 'uri'=>'string', 'options='=>'array', 'driverOptions='=>'array'],
'MongoDB\Driver\Manager::executeBulkWrite' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'bulk'=>'MongoDB\Driver\BulkWrite', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'readPreference='=>'MongoDB\Driver\ReadPreference'],
'MongoDB\Driver\Manager::executeDelete' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'filter'=>'array|object', 'deleteOptions='=>'array', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeInsert' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'document'=>'array|object', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::executeQuery' => ['MongoDB\Driver\Cursor', 'namespace'=>'string', 'query'=>'MongoDB\Driver\Query', 'readPreference='=>'MongoDB\Driver\ReadPreference'],
'mongodb\driver\manager::executeReadCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\manager::executeReadWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Manager::executeUpdate' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'filter'=>'array|object', 'newObj'=>'array|object', 'updateOptions='=>'array', 'writeConcern='=>'MongoDB\Driver\WriteConcern'],
'mongodb\driver\manager::executeWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Manager::getReadConcern' => ['MongoDB\Driver\ReadConcern'],
'MongoDB\Driver\Manager::getReadPreference' => ['MongoDB\Driver\ReadPreference'],
'MongoDB\Driver\Manager::getServers' => ['MongoDB\Driver\Server[]'],
'MongoDB\Driver\Manager::getWriteConcern' => ['MongoDB\Driver\WriteConcern'],
'MongoDB\Driver\Manager::selectServer' => ['MongoDB\Driver\Server', 'readPreference'=>'MongoDB\Driver\ReadPreference'],
'mongodb\driver\manager::startSession' => ['MongoDB\Driver\Session', 'options='=>'array'],
'mongodb\driver\monitoring\commandfailedevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getDurationMicros' => ['int'],
'mongodb\driver\monitoring\commandfailedevent::getError' => ['Exception'],
'mongodb\driver\monitoring\commandfailedevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getReply' => ['object'],
'mongodb\driver\monitoring\commandfailedevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandfailedevent::getServer' => ['MongoDB\Driver\Server'],
'mongodb\driver\monitoring\commandstartedevent::getCommand' => ['object'],
'mongodb\driver\monitoring\commandstartedevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getDatabaseName' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandstartedevent::getServer' => ['MongoDB\Driver\Server'],
'mongodb\driver\monitoring\commandsubscriber::commandFailed' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandFailedEvent'],
'mongodb\driver\monitoring\commandsubscriber::commandStarted' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandStartedEvent'],
'mongodb\driver\monitoring\commandsubscriber::commandSucceeded' => ['void', 'event'=>'MongoDB\Driver\Monitoring\CommandSucceededEvent'],
'mongodb\driver\monitoring\commandsucceededevent::getCommandName' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getDurationMicros' => ['int'],
'mongodb\driver\monitoring\commandsucceededevent::getOperationId' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getReply' => ['object'],
'mongodb\driver\monitoring\commandsucceededevent::getRequestId' => ['string'],
'mongodb\driver\monitoring\commandsucceededevent::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\Query::__construct' => ['void', 'filter'=>'array|object', 'queryOptions='=>'array'],
'MongoDB\Driver\ReadConcern::__construct' => ['void', 'level='=>'string'],
'MongoDB\Driver\ReadConcern::bsonSerialize' => ['object'],
'MongoDB\Driver\ReadConcern::getLevel' => ['?string'],
'mongodb\driver\readconcern::isDefault' => ['bool'],
'MongoDB\Driver\ReadPreference::__construct' => ['void', 'readPreference'=>'string', 'tagSets='=>'array', 'options='=>'array'],
'MongoDB\Driver\ReadPreference::bsonSerialize' => ['object'],
'mongodb\driver\readpreference::getMaxStalenessSeconds' => ['int'],
'MongoDB\Driver\ReadPreference::getMode' => ['int'],
'MongoDB\Driver\ReadPreference::getTagSets' => ['array'],
'MongoDB\Driver\Server::__construct' => ['void', 'host'=>'string', 'port'=>'string', 'options='=>'array', 'driverOptions='=>'array'],
'MongoDB\Driver\Server::executeBulkWrite' => ['MongoDB\Driver\WriteResult', 'namespace'=>'string', 'zwrite'=>'BulkWrite'],
'MongoDB\Driver\Server::executeCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command'],
'MongoDB\Driver\Server::executeQuery' => ['MongoDB\Driver\Cursor', 'namespace'=>'string', 'zquery'=>'Query'],
'mongodb\driver\server::executeReadCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\server::executeReadWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'mongodb\driver\server::executeWriteCommand' => ['MongoDB\Driver\Cursor', 'db'=>'string', 'command'=>'MongoDB\Driver\Command', 'options='=>'array'],
'MongoDB\Driver\Server::getHost' => ['string'],
'MongoDB\Driver\Server::getInfo' => ['array'],
'MongoDB\Driver\Server::getLatency' => ['int'],
'MongoDB\Driver\Server::getPort' => ['int'],
'MongoDB\Driver\Server::getState' => [''],
'MongoDB\Driver\Server::getTags' => ['array'],
'MongoDB\Driver\Server::getType' => ['int'],
'MongoDB\Driver\Server::isArbiter' => ['bool'],
'MongoDB\Driver\Server::isDelayed' => [''],
'MongoDB\Driver\Server::isHidden' => ['bool'],
'MongoDB\Driver\Server::isPassive' => ['bool'],
'MongoDB\Driver\Server::isPrimary' => ['bool'],
'MongoDB\Driver\Server::isSecondary' => ['bool'],
'mongodb\driver\session::__construct' => ['void'],
'mongodb\driver\session::abortTransaction' => ['void'],
'mongodb\driver\session::advanceClusterTime' => ['void', 'clusterTime'=>'array|object'],
'mongodb\driver\session::advanceOperationTime' => ['void', 'operationTime'=>'MongoDB\BSON\TimestampInterface'],
'mongodb\driver\session::commitTransaction' => ['void'],
'mongodb\driver\session::endSession' => ['void'],
'mongodb\driver\session::getClusterTime' => ['?object'],
'mongodb\driver\session::getLogicalSessionId' => ['object'],
'mongodb\driver\session::getOperationTime' => ['MongoDB\BSON\Timestamp|null'],
'mongodb\driver\session::startTransaction' => ['void', 'options'=>'array|object'],
'MongoDB\Driver\WriteConcern::__construct' => ['void', 'wstring'=>'string', 'wtimeout='=>'int', 'journal='=>'bool', 'fsync='=>'bool'],
'mongodb\driver\writeconcern::bsonSerialize' => ['object'],
'mongodb\driver\writeconcern::getJournal' => ['?bool'],
'MongoDB\Driver\WriteConcern::getJurnal' => ['?bool'],
'MongoDB\Driver\WriteConcern::getW' => ['int|null|string'],
'MongoDB\Driver\WriteConcern::getWtimeout' => ['int'],
'mongodb\driver\writeconcern::isDefault' => ['bool'],
'MongoDB\Driver\WriteConcernError::getCode' => ['int'],
'MongoDB\Driver\WriteConcernError::getInfo' => ['mixed'],
'MongoDB\Driver\WriteConcernError::getMessage' => ['string'],
'MongoDB\Driver\WriteError::getCode' => ['int'],
'MongoDB\Driver\WriteError::getIndex' => ['int'],
'MongoDB\Driver\WriteError::getInfo' => ['mixed'],
'MongoDB\Driver\WriteError::getMessage' => ['string'],
'MongoDB\Driver\WriteException::getWriteResult' => [''],
'MongoDB\Driver\WriteResult::getDeletedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getInfo' => [''],
'MongoDB\Driver\WriteResult::getInsertedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getMatchedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getModifiedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getServer' => ['MongoDB\Driver\Server'],
'MongoDB\Driver\WriteResult::getUpsertedCount' => ['?int'],
'MongoDB\Driver\WriteResult::getUpsertedIds' => ['array'],
'MongoDB\Driver\WriteResult::getWriteConcernError' => ['MongoDB\Driver\WriteConcernError|null'],
'MongoDB\Driver\WriteResult::getWriteErrors' => ['MongoDB\Driver\WriteError[]'],
'MongoDB\Driver\WriteResult::isAcknowledged' => ['bool'],
'MongoDBRef::create' => ['array', 'collection'=>'string', 'id'=>'mixed', 'database='=>'string'],
'MongoDBRef::get' => ['?array', 'db'=>'MongoDB', 'ref'=>'array'],
'MongoDBRef::isRef' => ['bool', 'ref'=>'mixed'],
'MongoDeleteBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoException::__clone' => ['void'],
'MongoException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoException::__toString' => ['string'],
'MongoException::__wakeup' => ['void'],
'MongoException::getCode' => ['int'],
'MongoException::getFile' => ['string'],
'MongoException::getLine' => ['int'],
'MongoException::getMessage' => ['string'],
'MongoException::getPrevious' => ['Exception|Throwable'],
'MongoException::getTrace' => ['array'],
'MongoException::getTraceAsString' => ['string'],
'MongoGridFS::__construct' => ['void', 'db'=>'MongoDB', 'prefix='=>'string', 'chunks='=>'mixed'],
'MongoGridFS::__get' => ['MongoCollection', 'name'=>'string'],
'MongoGridFS::__toString' => ['string'],
'MongoGridFS::aggregate' => ['array', 'pipeline'=>'array', 'op'=>'array', 'pipelineOperators'=>'array'],
'MongoGridFS::aggregateCursor' => ['MongoCommandCursor', 'pipeline'=>'array', 'options'=>'array'],
'MongoGridFS::batchInsert' => ['mixed', 'a'=>'array', 'options='=>'array'],
'MongoGridFS::count' => ['int', 'query='=>'stdClass|array'],
'MongoGridFS::createDBRef' => ['array', 'a'=>'array'],
'MongoGridFS::createIndex' => ['array', 'keys'=>'array', 'options='=>'array'],
'MongoGridFS::delete' => ['bool', 'id'=>'mixed'],
'MongoGridFS::deleteIndex' => ['array', 'keys'=>'array|string'],
'MongoGridFS::deleteIndexes' => ['array'],
'MongoGridFS::distinct' => ['array|bool', 'key'=>'string', 'query='=>'?array'],
'MongoGridFS::drop' => ['array'],
'MongoGridFS::ensureIndex' => ['bool', 'keys'=>'array', 'options='=>'array'],
'MongoGridFS::find' => ['MongoGridFSCursor', 'query='=>'array', 'fields='=>'array'],
'MongoGridFS::findAndModify' => ['array', 'query'=>'array', 'update='=>'?array', 'fields='=>'?array', 'options='=>'?array'],
'MongoGridFS::findOne' => ['?MongoGridFSFile', 'query='=>'mixed', 'fields='=>'mixed'],
'MongoGridFS::get' => ['?MongoGridFSFile', 'id'=>'mixed'],
'MongoGridFS::getDBRef' => ['array', 'ref'=>'array'],
'MongoGridFS::getIndexInfo' => ['array'],
'MongoGridFS::getName' => ['string'],
'MongoGridFS::getReadPreference' => ['array'],
'MongoGridFS::getSlaveOkay' => ['bool'],
'MongoGridFS::group' => ['array', 'keys'=>'mixed', 'initial'=>'array', 'reduce'=>'MongoCode', 'condition='=>'array'],
'MongoGridFS::insert' => ['array|bool', 'a'=>'array|object', 'options='=>'array'],
'MongoGridFS::put' => ['mixed', 'filename'=>'string', 'extra='=>'array'],
'MongoGridFS::remove' => ['bool', 'criteria='=>'array', 'options='=>'array'],
'MongoGridFS::save' => ['array|bool', 'a'=>'array|object', 'options='=>'array'],
'MongoGridFS::setReadPreference' => ['bool', 'read_preference'=>'string', 'tags'=>'array'],
'MongoGridFS::setSlaveOkay' => ['bool', 'ok='=>'bool'],
'MongoGridFS::storeBytes' => ['mixed', 'bytes'=>'string', 'extra='=>'array', 'options='=>'array'],
'MongoGridFS::storeFile' => ['mixed', 'filename'=>'string', 'extra='=>'array', 'options='=>'array'],
'MongoGridFS::storeUpload' => ['mixed', 'name'=>'string', 'filename='=>'string'],
'MongoGridFS::toIndexString' => ['string', 'keys'=>'mixed'],
'MongoGridFS::update' => ['bool', 'criteria'=>'array', 'newobj'=>'array', 'options='=>'array'],
'MongoGridFS::validate' => ['array', 'scan_data='=>'bool'],
'MongoGridFSCursor::__construct' => ['void', 'gridfs'=>'MongoGridFS', 'connection'=>'resource', 'ns'=>'string', 'query'=>'array', 'fields'=>'array'],
'MongoGridFSCursor::addOption' => ['MongoCursor', 'key'=>'string', 'value'=>'mixed'],
'MongoGridFSCursor::awaitData' => ['MongoCursor', 'wait='=>'bool'],
'MongoGridFSCursor::batchSize' => ['MongoCursor', 'batchSize'=>'int'],
'MongoGridFSCursor::count' => ['int', 'all='=>'bool'],
'MongoGridFSCursor::current' => ['MongoGridFSFile'],
'MongoGridFSCursor::dead' => ['bool'],
'MongoGridFSCursor::doQuery' => ['void'],
'MongoGridFSCursor::explain' => ['array'],
'MongoGridFSCursor::fields' => ['MongoCursor', 'f'=>'array'],
'MongoGridFSCursor::getNext' => ['MongoGridFSFile'],
'MongoGridFSCursor::getReadPreference' => ['array'],
'MongoGridFSCursor::hasNext' => ['bool'],
'MongoGridFSCursor::hint' => ['MongoCursor', 'key_pattern'=>'mixed'],
'MongoGridFSCursor::immortal' => ['MongoCursor', 'liveForever='=>'bool'],
'MongoGridFSCursor::info' => ['array'],
'MongoGridFSCursor::key' => ['string'],
'MongoGridFSCursor::limit' => ['MongoCursor', 'num'=>'int'],
'MongoGridFSCursor::maxTimeMS' => ['MongoCursor', 'ms'=>'int'],
'MongoGridFSCursor::next' => ['void'],
'MongoGridFSCursor::partial' => ['MongoCursor', 'okay='=>'bool'],
'MongoGridFSCursor::reset' => ['void'],
'MongoGridFSCursor::rewind' => ['void'],
'MongoGridFSCursor::setFlag' => ['MongoCursor', 'flag'=>'int', 'set='=>'bool'],
'MongoGridFSCursor::setReadPreference' => ['MongoCursor', 'read_preference'=>'string', 'tags'=>'array'],
'MongoGridFSCursor::skip' => ['MongoCursor', 'num'=>'int'],
'MongoGridFSCursor::slaveOkay' => ['MongoCursor', 'okay='=>'bool'],
'MongoGridFSCursor::snapshot' => ['MongoCursor'],
'MongoGridFSCursor::sort' => ['MongoCursor', 'fields'=>'array'],
'MongoGridFSCursor::tailable' => ['MongoCursor', 'tail='=>'bool'],
'MongoGridFSCursor::timeout' => ['MongoCursor', 'ms'=>'int'],
'MongoGridFSCursor::valid' => ['bool'],
'MongoGridfsFile::__construct' => ['void', 'gridfs'=>'MongoGridFS', 'file'=>'array'],
'MongoGridFSFile::getBytes' => ['string'],
'MongoGridFSFile::getFilename' => ['string'],
'MongoGridFSFile::getResource' => ['resource'],
'MongoGridFSFile::getSize' => ['int'],
'MongoGridFSFile::write' => ['int', 'filename='=>'string'],
'MongoId::__construct' => ['void', 'id='=>'string|MongoId'],
'MongoId::__set_state' => ['MongoId', 'props'=>'array'],
'MongoId::__toString' => ['string'],
'MongoId::getHostname' => ['string'],
'MongoId::getInc' => ['int'],
'MongoId::getPID' => ['int'],
'MongoId::getTimestamp' => ['int'],
'MongoId::isValid' => ['bool', 'value'=>'mixed'],
'MongoInsertBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoInt32::__construct' => ['void', 'value'=>'string'],
'MongoInt32::__toString' => ['string'],
'MongoInt64::__construct' => ['void', 'value'=>'string'],
'MongoInt64::__toString' => ['string'],
'MongoLog::getCallback' => ['callable'],
'MongoLog::getLevel' => ['int'],
'MongoLog::getModule' => ['int'],
'MongoLog::setCallback' => ['void', 'log_function'=>'callable'],
'MongoLog::setLevel' => ['void', 'level'=>'int'],
'MongoLog::setModule' => ['void', 'module'=>'int'],
'MongoPool::getSize' => ['int'],
'MongoPool::info' => ['array'],
'MongoPool::setSize' => ['bool', 'size'=>'int'],
'MongoRegex::__construct' => ['void', 'regex'=>'string'],
'MongoRegex::__toString' => ['string'],
'MongoResultException::__clone' => ['void'],
'MongoResultException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoResultException::__toString' => ['string'],
'MongoResultException::__wakeup' => ['void'],
'MongoResultException::getCode' => ['int'],
'MongoResultException::getDocument' => ['array'],
'MongoResultException::getFile' => ['string'],
'MongoResultException::getLine' => ['int'],
'MongoResultException::getMessage' => ['string'],
'MongoResultException::getPrevious' => ['Exception|Throwable'],
'MongoResultException::getTrace' => ['array'],
'MongoResultException::getTraceAsString' => ['string'],
'MongoTimestamp::__construct' => ['void', 'sec='=>'int', 'inc='=>'int'],
'MongoTimestamp::__toString' => ['string'],
'MongoUpdateBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'write_options='=>'array'],
'MongoUpdateBatch::add' => ['bool', 'item'=>'array'],
'MongoUpdateBatch::execute' => ['array', 'write_options'=>'array'],
'MongoWriteBatch::__construct' => ['void', 'collection'=>'MongoCollection', 'batch_type'=>'string', 'write_options'=>'array'],
'MongoWriteBatch::add' => ['bool', 'item'=>'array'],
'MongoWriteBatch::execute' => ['array', 'write_options'=>'array'],
'MongoWriteConcernException::__clone' => ['void'],
'MongoWriteConcernException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'MongoWriteConcernException::__toString' => ['string'],
'MongoWriteConcernException::__wakeup' => ['void'],
'MongoWriteConcernException::getCode' => ['int'],
'MongoWriteConcernException::getDocument' => ['array'],
'MongoWriteConcernException::getFile' => ['string'],
'MongoWriteConcernException::getLine' => ['int'],
'MongoWriteConcernException::getMessage' => ['string'],
'MongoWriteConcernException::getPrevious' => ['Exception|Throwable'],
'MongoWriteConcernException::getTrace' => ['array'],
'MongoWriteConcernException::getTraceAsString' => ['string'],
'monitor_custom_event' => ['void', 'class'=>'string', 'text'=>'string', 'severe='=>'int', 'user_data='=>'mixed'],
'monitor_httperror_event' => ['void', 'error_code'=>'int', 'url'=>'string', 'severe='=>'int'],
'monitor_license_info' => ['array'],
'monitor_pass_error' => ['void', 'errno'=>'int', 'errstr'=>'string', 'errfile'=>'string', 'errline'=>'int'],
'monitor_set_aggregation_hint' => ['void', 'hint'=>'string'],
'move_uploaded_file' => ['bool', 'path'=>'string', 'new_path'=>'string'],
'mqseries_back' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_begin' => ['void', 'hconn'=>'resource', 'beginoptions'=>'array', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_close' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'options'=>'int', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_cmit' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_conn' => ['void', 'qmanagername'=>'string', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_connx' => ['void', 'qmanagername'=>'string', 'connoptions'=>'array', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_disc' => ['void', 'hconn'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_get' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'md'=>'array', 'gmo'=>'array', 'bufferlength'=>'int', 'msg'=>'string', 'data_length'=>'int', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_inq' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'selectorcount'=>'int', 'selectors'=>'array', 'intattrcount'=>'int', 'intattr'=>'resource', 'charattrlength'=>'int', 'charattr'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_open' => ['void', 'hconn'=>'resource', 'objdesc'=>'array', 'option'=>'int', 'hobj'=>'resource', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_put' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'md'=>'array', 'pmo'=>'array', 'message'=>'string', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_put1' => ['void', 'hconn'=>'resource', 'objdesc'=>'resource', 'msgdesc'=>'resource', 'pmo'=>'resource', 'buffer'=>'string', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_set' => ['void', 'hconn'=>'resource', 'hobj'=>'resource', 'selectorcount'=>'int', 'selectors'=>'array', 'intattrcount'=>'int', 'intattrs'=>'array', 'charattrlength'=>'int', 'charattrs'=>'array', 'compcode'=>'resource', 'reason'=>'resource'],
'mqseries_strerror' => ['string', 'reason'=>'int'],
'ms_GetErrorObj' => ['errorObj'],
'ms_GetVersion' => ['string'],
'ms_GetVersionInt' => ['int'],
'ms_iogetStdoutBufferBytes' => ['int'],
'ms_iogetstdoutbufferstring' => ['void'],
'ms_ioinstallstdinfrombuffer' => ['void'],
'ms_ioinstallstdouttobuffer' => ['void'],
'ms_ioresethandlers' => ['void'],
'ms_iostripstdoutbuffercontentheaders' => ['void'],
'ms_iostripstdoutbuffercontenttype' => ['string'],
'ms_ResetErrorList' => ['void'],
'ms_TokenizeMap' => ['array', 'map_file_name'=>'string'],
'msession_connect' => ['bool', 'host'=>'string', 'port'=>'string'],
'msession_count' => ['int'],
'msession_create' => ['bool', 'session'=>'string', 'classname='=>'string', 'data='=>'string'],
'msession_destroy' => ['bool', 'name'=>'string'],
'msession_disconnect' => ['void'],
'msession_find' => ['array', 'name'=>'string', 'value'=>'string'],
'msession_get' => ['string', 'session'=>'string', 'name'=>'string', 'value'=>'string'],
'msession_get_array' => ['array', 'session'=>'string'],
'msession_get_data' => ['string', 'session'=>'string'],
'msession_inc' => ['string', 'session'=>'string', 'name'=>'string'],
'msession_list' => ['array'],
'msession_listvar' => ['array', 'name'=>'string'],
'msession_lock' => ['int', 'name'=>'string'],
'msession_plugin' => ['string', 'session'=>'string', 'val'=>'string', 'param='=>'string'],
'msession_randstr' => ['string', 'param'=>'int'],
'msession_set' => ['bool', 'session'=>'string', 'name'=>'string', 'value'=>'string'],
'msession_set_array' => ['void', 'session'=>'string', 'tuples'=>'array'],
'msession_set_data' => ['bool', 'session'=>'string', 'value'=>'string'],
'msession_timeout' => ['int', 'session'=>'string', 'param='=>'int'],
'msession_uniq' => ['string', 'param'=>'int', 'classname='=>'string', 'data='=>'string'],
'msession_unlock' => ['int', 'session'=>'string', 'key'=>'int'],
'msg_get_queue' => ['resource', 'key'=>'int', 'perms='=>'int'],
'msg_queue_exists' => ['bool', 'key'=>'int'],
'msg_receive' => ['bool', 'queue'=>'resource', 'desiredmsgtype'=>'int', '&w_msgtype'=>'int', 'maxsize'=>'int', '&w_message'=>'mixed', 'unserialize='=>'bool', 'flags='=>'int', '&w_errorcode='=>'int'],
'msg_remove_queue' => ['bool', 'queue'=>'resource'],
'msg_send' => ['bool', 'queue'=>'resource', 'msgtype'=>'int', 'message'=>'mixed', 'serialize='=>'bool', 'blocking='=>'bool', '&w_errorcode='=>'int'],
'msg_set_queue' => ['bool', 'queue'=>'resource', 'data'=>'array'],
'msg_stat_queue' => ['array', 'queue'=>'resource'],
'msgfmt_create' => ['MessageFormatter', 'locale'=>'string', 'pattern'=>'string'],
'msgfmt_format' => ['string|false', 'fmt'=>'MessageFormatter', 'args'=>'array'],
'msgfmt_format_message' => ['string|false', 'locale'=>'string', 'pattern'=>'string', 'args'=>'array'],
'msgfmt_get_error_code' => ['int', 'fmt'=>'MessageFormatter'],
'msgfmt_get_error_message' => ['string', 'fmt'=>'MessageFormatter'],
'msgfmt_get_locale' => ['string', 'formatter'=>'MessageFormatter'],
'msgfmt_get_pattern' => ['string', 'fmt'=>'MessageFormatter'],
'msgfmt_parse' => ['array|false', 'fmt'=>'MessageFormatter', 'value'=>'string'],
'msgfmt_parse_message' => ['array|false', 'locale'=>'string', 'pattern'=>'string', 'source'=>'string'],
'msgfmt_set_pattern' => ['bool', 'fmt'=>'MessageFormatter', 'pattern'=>'string'],
'msql_affected_rows' => ['int', 'result'=>'resource'],
'msql_close' => ['bool', 'link_identifier='=>'?resource'],
'msql_connect' => ['resource', 'hostname='=>'string'],
'msql_create_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'msql_data_seek' => ['bool', 'result'=>'resource', 'row_number'=>'int'],
'msql_db_query' => ['resource', 'database'=>'string', 'query'=>'string', 'link_identifier='=>'?resource'],
'msql_drop_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'msql_error' => ['string'],
'msql_fetch_array' => ['array', 'result'=>'resource', 'result_type='=>'int'],
'msql_fetch_field' => ['object', 'result'=>'resource', 'field_offset='=>'int'],
'msql_fetch_object' => ['object', 'result'=>'resource'],
'msql_fetch_row' => ['array', 'result'=>'resource'],
'msql_field_flags' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_len' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_name' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_seek' => ['bool', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_table' => ['int', 'result'=>'resource', 'field_offset'=>'int'],
'msql_field_type' => ['string', 'result'=>'resource', 'field_offset'=>'int'],
'msql_free_result' => ['bool', 'result'=>'resource'],
'msql_list_dbs' => ['resource', 'link_identifier='=>'?resource'],
'msql_list_fields' => ['resource', 'database'=>'string', 'tablename'=>'string', 'link_identifier='=>'?resource'],
'msql_list_tables' => ['resource', 'database'=>'string', 'link_identifier='=>'?resource'],
'msql_num_fields' => ['int', 'result'=>'resource'],
'msql_num_rows' => ['int', 'query_identifier'=>'resource'],
'msql_pconnect' => ['resource', 'hostname='=>'string'],
'msql_query' => ['resource', 'query'=>'string', 'link_identifier='=>'?resource'],
'msql_result' => ['string', 'result'=>'resource', 'row'=>'int', 'field='=>'mixed'],
'msql_select_db' => ['bool', 'database_name'=>'string', 'link_identifier='=>'?resource'],
'mt_getrandmax' => ['int'],
'mt_rand' => ['int', 'min'=>'int', 'max'=>'int'],
'mt_rand\'1' => ['int'],
'mt_srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'MultipleIterator::__construct' => ['void', 'flags='=>'int'],
'MultipleIterator::attachIterator' => ['void', 'iterator'=>'Iterator', 'infos='=>'string'],
'MultipleIterator::containsIterator' => ['bool', 'iterator'=>'Iterator'],
'MultipleIterator::countIterators' => ['int'],
'MultipleIterator::current' => ['array|false'],
'MultipleIterator::detachIterator' => ['void', 'iterator'=>'Iterator'],
'MultipleIterator::getFlags' => ['int'],
'MultipleIterator::key' => ['array'],
'MultipleIterator::next' => ['void'],
'MultipleIterator::rewind' => ['void'],
'MultipleIterator::setFlags' => ['int', 'flags'=>'int'],
'MultipleIterator::valid' => ['bool'],
'Mutex::create' => ['long', 'lock='=>'bool'],
'Mutex::destroy' => ['bool', 'mutex'=>'long'],
'Mutex::lock' => ['bool', 'mutex'=>'long'],
'Mutex::trylock' => ['bool', 'mutex'=>'long'],
'Mutex::unlock' => ['bool', 'mutex'=>'long', 'destroy='=>'bool'],
'mysql_xdevapi\baseresult::getWarnings' => ['array'],
'mysql_xdevapi\baseresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\collection::add' => ['mysql_xdevapi\CollectionAdd', 'document'=>'mixed'],
'mysql_xdevapi\collection::addOrReplaceOne' => ['mysql_xdevapi\Result', 'id'=>'string', 'doc'=>'string'],
'mysql_xdevapi\collection::count' => ['integer'],
'mysql_xdevapi\collection::createIndex' => ['void', 'index_name'=>'string', 'index_desc_json'=>'string'],
'mysql_xdevapi\collection::dropIndex' => ['bool', 'index_name'=>'string'],
'mysql_xdevapi\collection::existsInDatabase' => ['bool'],
'mysql_xdevapi\collection::find' => ['mysql_xdevapi\CollectionFind', 'search_condition='=>'string'],
'mysql_xdevapi\collection::getName' => ['string'],
'mysql_xdevapi\collection::getOne' => ['Document', 'id'=>'string'],
'mysql_xdevapi\collection::getSchema' => ['mysql_xdevapi\schema'],
'mysql_xdevapi\collection::getSession' => ['Session'],
'mysql_xdevapi\collection::modify' => ['mysql_xdevapi\CollectionModify', 'search_condition'=>'string'],
'mysql_xdevapi\collection::remove' => ['mysql_xdevapi\CollectionRemove', 'search_condition'=>'string'],
'mysql_xdevapi\collection::removeOne' => ['mysql_xdevapi\Result', 'id'=>'string'],
'mysql_xdevapi\collection::replaceOne' => ['mysql_xdevapi\Result', 'id'=>'string', 'doc'=>'string'],
'mysql_xdevapi\collectionadd::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionfind::bind' => ['mysql_xdevapi\CollectionFind', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionfind::execute' => ['mysql_xdevapi\DocResult'],
'mysql_xdevapi\collectionfind::fields' => ['mysql_xdevapi\CollectionFind', 'projection'=>'string'],
'mysql_xdevapi\collectionfind::groupBy' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionfind::having' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionfind::limit' => ['mysql_xdevapi\CollectionFind', 'rows'=>'integer'],
'mysql_xdevapi\collectionfind::lockExclusive' => ['mysql_xdevapi\CollectionFind', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\collectionfind::lockShared' => ['mysql_xdevapi\CollectionFind', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\collectionfind::offset' => ['mysql_xdevapi\CollectionFind', 'position'=>'integer'],
'mysql_xdevapi\collectionfind::sort' => ['mysql_xdevapi\CollectionFind', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionmodify::arrayAppend' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::arrayInsert' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::bind' => ['mysql_xdevapi\CollectionModify', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionmodify::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionmodify::limit' => ['mysql_xdevapi\CollectionModify', 'rows'=>'integer'],
'mysql_xdevapi\collectionmodify::patch' => ['mysql_xdevapi\CollectionModify', 'document'=>'string'],
'mysql_xdevapi\collectionmodify::replace' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::set' => ['mysql_xdevapi\CollectionModify', 'collection_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\collectionmodify::skip' => ['mysql_xdevapi\CollectionModify', 'position'=>'integer'],
'mysql_xdevapi\collectionmodify::sort' => ['mysql_xdevapi\CollectionModify', 'sort_expr'=>'string'],
'mysql_xdevapi\collectionmodify::unset' => ['mysql_xdevapi\CollectionModify', 'fields'=>'array'],
'mysql_xdevapi\collectionremove::bind' => ['mysql_xdevapi\CollectionRemove', 'placeholder_values'=>'array'],
'mysql_xdevapi\collectionremove::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\collectionremove::limit' => ['mysql_xdevapi\CollectionRemove', 'rows'=>'integer'],
'mysql_xdevapi\collectionremove::sort' => ['mysql_xdevapi\CollectionRemove', 'sort_expr'=>'string'],
'mysql_xdevapi\columnresult::getCharacterSetName' => ['string'],
'mysql_xdevapi\columnresult::getCollationName' => ['string'],
'mysql_xdevapi\columnresult::getColumnLabel' => ['string'],
'mysql_xdevapi\columnresult::getColumnName' => ['string'],
'mysql_xdevapi\columnresult::getFractionalDigits' => ['integer'],
'mysql_xdevapi\columnresult::getLength' => ['integer'],
'mysql_xdevapi\columnresult::getSchemaName' => ['string'],
'mysql_xdevapi\columnresult::getTableLabel' => ['string'],
'mysql_xdevapi\columnresult::getTableName' => ['string'],
'mysql_xdevapi\columnresult::getType' => ['integer'],
'mysql_xdevapi\columnresult::isNumberSigned' => ['integer'],
'mysql_xdevapi\columnresult::isPadded' => ['integer'],
'mysql_xdevapi\crudoperationbindable::bind' => ['mysql_xdevapi\CrudOperationBindable', 'placeholder_values'=>'array'],
'mysql_xdevapi\crudoperationlimitable::limit' => ['mysql_xdevapi\CrudOperationLimitable', 'rows'=>'integer'],
'mysql_xdevapi\crudoperationskippable::skip' => ['mysql_xdevapi\CrudOperationSkippable', 'skip'=>'integer'],
'mysql_xdevapi\crudoperationsortable::sort' => ['mysql_xdevapi\CrudOperationSortable', 'sort_expr'=>'string'],
'mysql_xdevapi\databaseobject::existsInDatabase' => ['bool'],
'mysql_xdevapi\databaseobject::getName' => ['string'],
'mysql_xdevapi\databaseobject::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\docresult::fetchAll' => ['Array'],
'mysql_xdevapi\docresult::fetchOne' => ['Object'],
'mysql_xdevapi\docresult::getWarnings' => ['Array'],
'mysql_xdevapi\docresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\executable::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\getsession' => ['mysql_xdevapi\Session', 'uri'=>'string'],
'mysql_xdevapi\result::getAutoIncrementValue' => ['int'],
'mysql_xdevapi\result::getGeneratedIds' => ['ArrayOfInt'],
'mysql_xdevapi\result::getWarnings' => ['array'],
'mysql_xdevapi\result::getWarningsCount' => ['integer'],
'mysql_xdevapi\rowresult::fetchAll' => ['array'],
'mysql_xdevapi\rowresult::fetchOne' => ['object'],
'mysql_xdevapi\rowresult::getColumnCount' => ['integer'],
'mysql_xdevapi\rowresult::getColumnNames' => ['array'],
'mysql_xdevapi\rowresult::getColumns' => ['array'],
'mysql_xdevapi\rowresult::getWarnings' => ['array'],
'mysql_xdevapi\rowresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\schema::createCollection' => ['mysql_xdevapi\Collection', 'name'=>'string'],
'mysql_xdevapi\schema::dropCollection' => ['bool', 'collection_name'=>'string'],
'mysql_xdevapi\schema::existsInDatabase' => ['bool'],
'mysql_xdevapi\schema::getCollection' => ['mysql_xdevapi\Collection', 'name'=>'string'],
'mysql_xdevapi\schema::getCollectionAsTable' => ['mysql_xdevapi\Table', 'name'=>'string'],
'mysql_xdevapi\schema::getCollections' => ['array'],
'mysql_xdevapi\schema::getName' => ['string'],
'mysql_xdevapi\schema::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\schema::getTable' => ['mysql_xdevapi\Table', 'name'=>'string'],
'mysql_xdevapi\schema::getTables' => ['array'],
'mysql_xdevapi\schemaobject::getSchema' => ['mysql_xdevapi\Schema'],
'mysql_xdevapi\session::close' => ['bool'],
'mysql_xdevapi\session::commit' => ['Object'],
'mysql_xdevapi\session::createSchema' => ['mysql_xdevapi\Schema', 'schema_name'=>'string'],
'mysql_xdevapi\session::dropSchema' => ['bool', 'schema_name'=>'string'],
'mysql_xdevapi\session::executeSql' => ['Object', 'statement'=>'string'],
'mysql_xdevapi\session::generateUUID' => ['string'],
'mysql_xdevapi\session::getClientId' => ['integer'],
'mysql_xdevapi\session::getSchema' => ['mysql_xdevapi\Schema', 'schema_name'=>'string'],
'mysql_xdevapi\session::getSchemas' => ['array'],
'mysql_xdevapi\session::getServerVersion' => ['integer'],
'mysql_xdevapi\session::killClient' => ['object', 'client_id'=>'integer'],
'mysql_xdevapi\session::listClients' => ['array'],
'mysql_xdevapi\session::quoteName' => ['string', 'name'=>'string'],
'mysql_xdevapi\session::releaseSavepoint' => ['void', 'name'=>'string'],
'mysql_xdevapi\session::rollback' => ['void'],
'mysql_xdevapi\session::rollbackTo' => ['void', 'name'=>'string'],
'mysql_xdevapi\session::setSavepoint' => ['string', 'name='=>'string'],
'mysql_xdevapi\session::sql' => ['mysql_xdevapi\SqlStatement', 'query'=>'string'],
'mysql_xdevapi\session::startTransaction' => ['void'],
'mysql_xdevapi\sqlstatement::bind' => ['mysql_xdevapi\SqlStatement', 'param'=>'string'],
'mysql_xdevapi\sqlstatement::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::getNextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::getResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\sqlstatement::hasMoreResults' => ['bool'],
'mysql_xdevapi\sqlstatementresult::fetchAll' => ['array'],
'mysql_xdevapi\sqlstatementresult::fetchOne' => ['object'],
'mysql_xdevapi\sqlstatementresult::getAffectedItemsCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::getColumnCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::getColumnNames' => ['array'],
'mysql_xdevapi\sqlstatementresult::getColumns' => ['Array'],
'mysql_xdevapi\sqlstatementresult::getGeneratedIds' => ['array'],
'mysql_xdevapi\sqlstatementresult::getLastInsertId' => ['String'],
'mysql_xdevapi\sqlstatementresult::getWarnings' => ['array'],
'mysql_xdevapi\sqlstatementresult::getWarningsCount' => ['integer'],
'mysql_xdevapi\sqlstatementresult::hasData' => ['bool'],
'mysql_xdevapi\sqlstatementresult::nextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::getNextResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::getResult' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\statement::hasMoreResults' => ['bool'],
'mysql_xdevapi\table::count' => ['integer'],
'mysql_xdevapi\table::delete' => ['mysql_xdevapi\TableDelete'],
'mysql_xdevapi\table::existsInDatabase' => ['bool'],
'mysql_xdevapi\table::getName' => ['string'],
'mysql_xdevapi\table::getSchema' => ['mysql_xdevapi\Schema'],
'mysql_xdevapi\table::getSession' => ['mysql_xdevapi\Session'],
'mysql_xdevapi\table::insert' => ['mysql_xdevapi\TableInsert', 'columns'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\table::isView' => ['bool'],
'mysql_xdevapi\table::select' => ['mysql_xdevapi\TableSelect', 'columns'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\table::update' => ['mysql_xdevapi\TableUpdate'],
'mysql_xdevapi\tabledelete::bind' => ['mysql_xdevapi\TableDelete', 'placeholder_values'=>'array'],
'mysql_xdevapi\tabledelete::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\tabledelete::limit' => ['mysql_xdevapi\TableDelete', 'rows'=>'integer'],
'mysql_xdevapi\tabledelete::offset' => ['mysql_xdevapi\TableDelete', 'position'=>'integer'],
'mysql_xdevapi\tabledelete::orderby' => ['mysql_xdevapi\TableDelete', 'orderby_expr'=>'string'],
'mysql_xdevapi\tabledelete::where' => ['mysql_xdevapi\TableDelete', 'where_expr'=>'string'],
'mysql_xdevapi\tableinsert::execute' => ['mysql_xdevapi\Result'],
'mysql_xdevapi\tableinsert::values' => ['mysql_xdevapi\TableInsert', 'row_values'=>'array'],
'mysql_xdevapi\tableselect::bind' => ['mysql_xdevapi\TableSelect', 'placeholder_values'=>'array'],
'mysql_xdevapi\tableselect::execute' => ['mysql_xdevapi\RowResult'],
'mysql_xdevapi\tableselect::groupBy' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'mixed'],
'mysql_xdevapi\tableselect::having' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'string'],
'mysql_xdevapi\tableselect::limit' => ['mysql_xdevapi\TableSelect', 'rows'=>'integer'],
'mysql_xdevapi\tableselect::lockExclusive' => ['mysql_xdevapi\TableSelect', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\tableselect::lockShared' => ['mysql_xdevapi\TableSelect', 'lock_waiting_option='=>'integer'],
'mysql_xdevapi\tableselect::offset' => ['mysql_xdevapi\TableSelect', 'position'=>'integer'],
'mysql_xdevapi\tableselect::orderby' => ['mysql_xdevapi\TableSelect', 'sort_expr'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\tableselect::where' => ['mysql_xdevapi\TableSelect', 'where_expr'=>'string'],
'mysql_xdevapi\tableupdate::bind' => ['mysql_xdevapi\TableUpdate', 'placeholder_values'=>'array'],
'mysql_xdevapi\tableupdate::execute' => ['mysql_xdevapi\TableUpdate'],
'mysql_xdevapi\tableupdate::limit' => ['mysql_xdevapi\TableUpdate', 'rows'=>'integer'],
'mysql_xdevapi\tableupdate::orderby' => ['mysql_xdevapi\TableUpdate', 'orderby_expr'=>'mixed', '...args='=>'mixed'],
'mysql_xdevapi\tableupdate::set' => ['mysql_xdevapi\TableUpdate', 'table_field'=>'string', 'expression_or_literal'=>'string'],
'mysql_xdevapi\tableupdate::where' => ['mysql_xdevapi\TableUpdate', 'where_expr'=>'string'],
'mysqli::__construct' => ['void', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'mysqli::autocommit' => ['bool', 'mode'=>'bool'],
'mysqli::begin_transaction' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::change_user' => ['bool', 'user'=>'string', 'password'=>'string', 'database'=>'string'],
'mysqli::character_set_name' => ['string'],
'mysqli::close' => ['bool'],
'mysqli::commit' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::debug' => ['bool', 'message'=>'string'],
'mysqli::disable_reads_from_master' => ['bool'],
'mysqli::dump_debug_info' => ['bool'],
'mysqli::escape_string' => ['string', 'escapestr'=>'string'],
'mysqli::get_charset' => ['object'],
'mysqli::get_client_info' => ['string'],
'mysqli::get_connection_stats' => ['array|false'],
'mysqli::get_warnings' => ['mysqli_warning'],
'mysqli::init' => ['mysqli'],
'mysqli::kill' => ['bool', 'processid'=>'int'],
'mysqli::more_results' => ['bool'],
'mysqli::multi_query' => ['bool', 'query'=>'string'],
'mysqli::next_result' => ['bool'],
'mysqli::options' => ['bool', 'option'=>'int', 'value'=>'mixed'],
'mysqli::ping' => ['bool'],
'mysqli::poll' => ['int|false', '&w_read'=>'array', '&w_error'=>'array', '&w_reject'=>'array', 'sec'=>'int', 'usec='=>'int'],
'mysqli::prepare' => ['mysqli_stmt|false', 'query'=>'string'],
'mysqli::query' => ['bool|mysqli_result', 'query'=>'string', 'resultmode='=>'int'],
'mysqli::real_connect' => ['bool', 'host='=>'string|null', 'username='=>'string', 'passwd='=>'string|null', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string', 'flags='=>'int'],
'mysqli::real_escape_string' => ['string', 'escapestr'=>'string'],
'mysqli::real_query' => ['bool', 'query'=>'string'],
'mysqli::reap_async_query' => ['mysqli_result|false'],
'mysqli::refresh' => ['bool', 'options'=>'int'],
'mysqli::release_savepoint' => ['bool', 'name'=>'string'],
'mysqli::rollback' => ['bool', 'flags='=>'int', 'name='=>'string'],
'mysqli::rpl_query_type' => ['int', 'query'=>'string'],
'mysqli::savepoint' => ['bool', 'name'=>'string'],
'mysqli::select_db' => ['bool', 'dbname'=>'string'],
'mysqli::send_query' => ['bool', 'query'=>'string'],
'mysqli::set_charset' => ['bool', 'charset'=>'string'],
'mysqli::set_local_infile_default' => ['void'],
'mysqli::set_local_infile_handler' => ['bool', 'read_func='=>'callable'],
'mysqli::ssl_set' => ['bool', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'mysqli::stat' => ['string|false'],
'mysqli::stmt_init' => ['mysqli_stmt'],
'mysqli::store_result' => ['mysqli_result|false', 'option='=>'int'],
'mysqli::thread_safe' => ['bool'],
'mysqli::use_result' => ['mysqli_result|false'],
'mysqli_affected_rows' => ['int', 'link'=>'mysqli'],
'mysqli_autocommit' => ['bool', 'link'=>'mysqli', 'mode'=>'bool'],
'mysqli_begin_transaction' => ['bool', 'link'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_change_user' => ['bool', 'link'=>'mysqli', 'user'=>'string', 'password'=>'string', 'database'=>'?string'],
'mysqli_character_set_name' => ['string', 'link'=>'mysqli'],
'mysqli_close' => ['bool', 'link'=>'mysqli'],
'mysqli_commit' => ['bool', 'link'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_connect' => ['mysqli|false', 'host='=>'string', 'username='=>'string', 'passwd='=>'string', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string'],
'mysqli_connect_errno' => ['int'],
'mysqli_connect_error' => ['string'],
'mysqli_data_seek' => ['bool', 'result'=>'mysqli_result', 'offset'=>'int'],
'mysqli_debug' => ['bool', 'message'=>'string'],
'mysqli_disable_reads_from_master' => ['bool', 'link'=>'mysqli'],
'mysqli_disable_rpl_parse' => ['bool', 'link'=>'mysqli'],
'mysqli_driver::embedded_server_end' => ['void'],
'mysqli_driver::embedded_server_start' => ['bool', 'start'=>'int', 'arguments'=>'array', 'groups'=>'array'],
'mysqli_dump_debug_info' => ['bool', 'link'=>'mysqli'],
'mysqli_embedded_server_end' => ['void'],
'mysqli_embedded_server_start' => ['bool', 'start'=>'int', 'arguments'=>'array', 'groups'=>'array'],
'mysqli_enable_reads_from_master' => ['bool', 'link'=>'mysqli'],
'mysqli_enable_rpl_parse' => ['bool', 'link'=>'mysqli'],
'mysqli_errno' => ['int', 'link'=>'mysqli'],
'mysqli_error' => ['string', 'link'=>'mysqli'],
'mysqli_error_list' => ['array', 'connection'=>'mysqli'],
'mysqli_escape_string' => ['string', 'link'=>'mysqli', 'escapestr'=>'string'],
'mysqli_execute' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_fetch_all' => ['array', 'result'=>'mysqli_result', 'resulttype='=>'int'],
'mysqli_fetch_array' => ['?array', 'result'=>'mysqli_result', 'resulttype='=>'int'],
'mysqli_fetch_assoc' => ['array<string,string>|null', 'result'=>'mysqli_result'],
'mysqli_fetch_field' => ['object|false', 'result'=>'mysqli_result'],
'mysqli_fetch_field_direct' => ['object|false', 'result'=>'mysqli_result', 'fieldnr'=>'int'],
'mysqli_fetch_fields' => ['array|false', 'result'=>'mysqli_result'],
'mysqli_fetch_lengths' => ['array|false', 'result'=>'mysqli_result'],
'mysqli_fetch_object' => ['?object', 'result'=>'mysqli_result', 'class_name='=>'string', 'params='=>'?array'],
'mysqli_fetch_row' => ['?array', 'result'=>'mysqli_result'],
'mysqli_field_count' => ['int', 'link'=>'mysqli'],
'mysqli_field_seek' => ['bool', 'result'=>'mysqli_result', 'fieldnr'=>'int'],
'mysqli_field_tell' => ['int', 'result'=>'mysqli_result'],
'mysqli_free_result' => ['void', 'link'=>'mysqli_result'],
'mysqli_get_cache_stats' => ['array|false'],
'mysqli_get_charset' => ['object', 'link'=>'mysqli'],
'mysqli_get_client_info' => ['string', 'link'=>'mysqli'],
'mysqli_get_client_stats' => ['array|false'],
'mysqli_get_client_version' => ['int', 'link'=>'mysqli'],
'mysqli_get_connection_stats' => ['array|false', 'link'=>'mysqli'],
'mysqli_get_host_info' => ['string', 'link'=>'mysqli'],
'mysqli_get_links_stats' => ['array'],
'mysqli_get_proto_info' => ['int', 'link'=>'mysqli'],
'mysqli_get_server_info' => ['string', 'link'=>'mysqli'],
'mysqli_get_server_version' => ['int', 'link'=>'mysqli'],
'mysqli_get_warnings' => ['mysqli_warning', 'link'=>'mysqli'],
'mysqli_info' => ['?string', 'link'=>'mysqli'],
'mysqli_init' => ['mysqli'],
'mysqli_insert_id' => ['int|string', 'link'=>'mysqli'],
'mysqli_kill' => ['bool', 'link'=>'mysqli', 'processid'=>'int'],
'mysqli_link_construct' => ['object'],
'mysqli_master_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_more_results' => ['bool', 'link'=>'mysqli'],
'mysqli_multi_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_next_result' => ['bool', 'link'=>'mysqli'],
'mysqli_num_fields' => ['int', 'link'=>'mysqli_result'],
'mysqli_num_rows' => ['int', 'link'=>'mysqli_result'],
'mysqli_options' => ['bool', 'link'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_ping' => ['bool', 'link'=>'mysqli'],
'mysqli_poll' => ['int|false', 'read'=>'array', 'error'=>'array', 'reject'=>'array', 'sec'=>'int', 'usec='=>'int'],
'mysqli_prepare' => ['mysqli_stmt|false', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_query' => ['mysqli_result|bool', 'link'=>'mysqli', 'query'=>'string', 'resultmode='=>'int'],
'mysqli_real_connect' => ['bool', 'link='=>'mysqli', 'host='=>'string|null', 'username='=>'string', 'passwd='=>'string|null', 'dbname='=>'string', 'port='=>'int', 'socket='=>'string', 'flags='=>'int'],
'mysqli_real_escape_string' => ['string', 'link'=>'mysqli', 'escapestr'=>'string'],
'mysqli_real_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_reap_async_query' => ['mysqli_result|false', 'link'=>'mysqli'],
'mysqli_refresh' => ['bool', 'link'=>'mysqli', 'options'=>'int'],
'mysqli_release_savepoint' => ['bool', 'link'=>'mysqli', 'name'=>'string'],
'mysqli_report' => ['bool', 'flags'=>'int'],
'mysqli_result::__construct' => ['void', 'link'=>'mysqli', 'resultmode='=>'int'],
'mysqli_result::close' => ['void'],
'mysqli_result::data_seek' => ['bool', 'offset'=>'int'],
'mysqli_result::fetch_all' => ['array', 'resulttype='=>'int'],
'mysqli_result::fetch_array' => ['?array', 'resulttype='=>'int'],
'mysqli_result::fetch_assoc' => ['array<string,string>|null'],
'mysqli_result::fetch_field' => ['object|false'],
'mysqli_result::fetch_field_direct' => ['object|false', 'fieldnr'=>'int'],
'mysqli_result::fetch_fields' => ['array|false'],
'mysqli_result::fetch_object' => ['object|stdClass|null', 'class_name='=>'string', 'params='=>'array'],
'mysqli_result::fetch_row' => ['?array'],
'mysqli_result::field_seek' => ['bool', 'fieldnr'=>'int'],
'mysqli_result::free' => ['void'],
'mysqli_result::free_result' => ['void'],
'mysqli_rollback' => ['bool', 'link'=>'mysqli', 'flags='=>'int', 'name='=>'string'],
'mysqli_rpl_parse_enabled' => ['int', 'link'=>'mysqli'],
'mysqli_rpl_probe' => ['bool', 'link'=>'mysqli'],
'mysqli_rpl_query_type' => ['int', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_savepoint' => ['bool', 'link'=>'mysqli', 'name'=>'string'],
'mysqli_savepoint_libmysql' => ['bool'],
'mysqli_select_db' => ['bool', 'link'=>'mysqli', 'dbname'=>'string'],
'mysqli_send_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_set_charset' => ['bool', 'link'=>'mysqli', 'charset'=>'string'],
'mysqli_set_local_infile_default' => ['void', 'link'=>'mysqli'],
'mysqli_set_local_infile_handler' => ['bool', 'link'=>'mysqli', 'read_func'=>'callable'],
'mysqli_set_opt' => ['bool', 'link'=>'mysqli', 'option'=>'int', 'value'=>'mixed'],
'mysqli_slave_query' => ['bool', 'link'=>'mysqli', 'query'=>'string'],
'mysqli_sqlstate' => ['string', 'link'=>'mysqli'],
'mysqli_ssl_set' => ['bool', 'link'=>'mysqli', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'mysqli_stat' => ['string|false', 'link'=>'mysqli'],
'mysqli_stmt::__construct' => ['void', 'query='=>'string'],
'mysqli_stmt::attr_get' => ['false|int', 'attr'=>'int'],
'mysqli_stmt::attr_set' => ['bool', 'attr'=>'int', 'mode'=>'int'],
'mysqli_stmt::bind_param' => ['bool', 'types'=>'string', '&var1'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt::bind_result' => ['bool', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt::close' => ['bool'],
'mysqli_stmt::data_seek' => ['void', 'offset'=>'int'],
'mysqli_stmt::execute' => ['bool'],
'mysqli_stmt::fetch' => ['?bool'],
'mysqli_stmt::free_result' => ['void'],
'mysqli_stmt::get_result' => ['mysqli_result|false'],
'mysqli_stmt::get_warnings' => ['object'],
'mysqli_stmt::more_results' => ['bool'],
'mysqli_stmt::next_result' => ['bool'],
'mysqli_stmt::num_rows' => ['int'],
'mysqli_stmt::prepare' => ['bool', 'query'=>'string'],
'mysqli_stmt::reset' => ['bool'],
'mysqli_stmt::result_metadata' => ['mysqli_result|false'],
'mysqli_stmt::send_long_data' => ['bool', 'param_nr'=>'int', 'data'=>'string'],
'mysqli_stmt::store_result' => ['bool'],
'mysqli_stmt_affected_rows' => ['int|string', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_attr_get' => ['int|false', 'stmt'=>'mysqli_stmt', 'attr'=>'int'],
'mysqli_stmt_attr_set' => ['bool', 'stmt'=>'mysqli_stmt', 'attr'=>'int', 'mode'=>'int'],
'mysqli_stmt_bind_param' => ['bool', 'stmt'=>'mysqli_stmt', 'types'=>'string', '&var1'=>'mixed', '&...args='=>'mixed'],
'mysqli_stmt_bind_result' => ['bool', 'stmt'=>'mysqli_stmt', '&w_var1'=>'', '&...w_vars='=>''],
'mysqli_stmt_close' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_data_seek' => ['void', 'stmt'=>'mysqli_stmt', 'offset'=>'int'],
'mysqli_stmt_errno' => ['int', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_error' => ['string', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_error_list' => ['array', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_execute' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_fetch' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_field_count' => ['int', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_free_result' => ['void', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_get_result' => ['mysqli_result|false', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_get_warnings' => ['object', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_init' => ['mysqli_stmt', 'link'=>'mysqli'],
'mysqli_stmt_insert_id' => ['mixed', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_more_results' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_next_result' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_num_rows' => ['int', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_param_count' => ['int', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_prepare' => ['bool', 'stmt'=>'mysqli_stmt', 'query'=>'string'],
'mysqli_stmt_reset' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_result_metadata' => ['mysqli_result|false', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_send_long_data' => ['bool', 'stmt'=>'mysqli_stmt', 'param_nr'=>'int', 'data'=>'string'],
'mysqli_stmt_sqlstate' => ['string', 'stmt'=>'mysqli_stmt'],
'mysqli_stmt_store_result' => ['bool', 'stmt'=>'mysqli_stmt'],
'mysqli_store_result' => ['mysqli_result|false', 'link'=>'mysqli', 'option='=>'int'],
'mysqli_thread_id' => ['int', 'link'=>'mysqli'],
'mysqli_thread_safe' => ['bool'],
'mysqli_use_result' => ['mysqli_result|false', 'link'=>'mysqli'],
'mysqli_warning::__construct' => ['void'],
'mysqli_warning::next' => ['bool'],
'mysqli_warning_count' => ['int', 'link'=>'mysqli'],
'mysqlnd_memcache_get_config' => ['array', 'connection'=>'mixed'],
'mysqlnd_memcache_set' => ['bool', 'mysql_connection'=>'mixed', 'memcache_connection='=>'Memcached', 'pattern='=>'string', 'callback='=>'callable'],
'mysqlnd_ms_dump_servers' => ['array', 'connection'=>'mixed'],
'mysqlnd_ms_fabric_select_global' => ['array', 'connection'=>'mixed', 'table_name'=>'mixed'],
'mysqlnd_ms_fabric_select_shard' => ['array', 'connection'=>'mixed', 'table_name'=>'mixed', 'shard_key'=>'mixed'],
'mysqlnd_ms_get_last_gtid' => ['string', 'connection'=>'mixed'],
'mysqlnd_ms_get_last_used_connection' => ['array', 'connection'=>'mixed'],
'mysqlnd_ms_get_stats' => ['array'],
'mysqlnd_ms_match_wild' => ['bool', 'table_name'=>'string', 'wildcard'=>'string'],
'mysqlnd_ms_query_is_select' => ['int', 'query'=>'string'],
'mysqlnd_ms_set_qos' => ['bool', 'connection'=>'mixed', 'service_level'=>'int', 'service_level_option='=>'int', 'option_value='=>'mixed'],
'mysqlnd_ms_set_user_pick_server' => ['bool', 'function'=>'string'],
'mysqlnd_ms_xa_begin' => ['int', 'connection'=>'mixed', 'gtrid'=>'string', 'timeout='=>'int'],
'mysqlnd_ms_xa_commit' => ['int', 'connection'=>'mixed', 'gtrid'=>'string'],
'mysqlnd_ms_xa_gc' => ['int', 'connection'=>'mixed', 'gtrid='=>'string', 'ignore_max_retries='=>'bool'],
'mysqlnd_ms_xa_rollback' => ['int', 'connection'=>'mixed', 'gtrid'=>'string'],
'mysqlnd_qc_change_handler' => ['bool', 'handler'=>''],
'mysqlnd_qc_clear_cache' => ['bool'],
'mysqlnd_qc_get_available_handlers' => ['array'],
'mysqlnd_qc_get_cache_info' => ['array'],
'mysqlnd_qc_get_core_stats' => ['array'],
'mysqlnd_qc_get_handler' => ['array'],
'mysqlnd_qc_get_normalized_query_trace_log' => ['array'],
'mysqlnd_qc_get_query_trace_log' => ['array'],
'mysqlnd_qc_set_cache_condition' => ['bool', 'condition_type'=>'int', 'condition'=>'mixed', 'condition_option'=>'mixed'],
'mysqlnd_qc_set_is_select' => ['mixed', 'callback'=>'string'],
'mysqlnd_qc_set_storage_handler' => ['bool', 'handler'=>'string'],
'mysqlnd_qc_set_user_handlers' => ['bool', 'get_hash'=>'string', 'find_query_in_cache'=>'string', 'return_to_cache'=>'string', 'add_query_to_cache_if_not_exists'=>'string', 'query_is_select'=>'string', 'update_query_run_time_stats'=>'string', 'get_stats'=>'string', 'clear_cache'=>'string'],
'mysqlnd_uh_convert_to_mysqlnd' => ['resource', '&rw_mysql_connection'=>'mysqli'],
'mysqlnd_uh_set_connection_proxy' => ['bool', '&rw_connection_proxy'=>'MysqlndUhConnection', '&rw_mysqli_connection='=>'mysqli'],
'mysqlnd_uh_set_statement_proxy' => ['bool', '&rw_statement_proxy'=>'MysqlndUhStatement'],
'MysqlndUhConnection::__construct' => ['void'],
'MysqlndUhConnection::changeUser' => ['bool', 'connection'=>'mysqlnd_connection', 'user'=>'string', 'password'=>'string', 'database'=>'string', 'silent'=>'bool', 'passwd_len'=>'int'],
'MysqlndUhConnection::charsetName' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::close' => ['bool', 'connection'=>'mysqlnd_connection', 'close_type'=>'int'],
'MysqlndUhConnection::connect' => ['bool', 'connection'=>'mysqlnd_connection', 'host'=>'string', 'use'=>'string', 'password'=>'string', 'database'=>'string', 'port'=>'int', 'socket'=>'string', 'mysql_flags'=>'int'],
'MysqlndUhConnection::endPSession' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::escapeString' => ['string', 'connection'=>'mysqlnd_connection', 'escape_string'=>'string'],
'MysqlndUhConnection::getAffectedRows' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getErrorNumber' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getErrorString' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getFieldCount' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getHostInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getLastInsertId' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getLastMessage' => ['void', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getProtocolInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerInformation' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerStatistics' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getServerVersion' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getSqlstate' => ['string', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getStatistics' => ['array', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getThreadId' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::getWarningCount' => ['int', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::init' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::killConnection' => ['bool', 'connection'=>'mysqlnd_connection', 'pid'=>'int'],
'MysqlndUhConnection::listFields' => ['array', 'connection'=>'mysqlnd_connection', 'table'=>'string', 'achtung_wild'=>'string'],
'MysqlndUhConnection::listMethod' => ['void', 'connection'=>'mysqlnd_connection', 'query'=>'string', 'achtung_wild'=>'string', 'par1'=>'string'],
'MysqlndUhConnection::moreResults' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::nextResult' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::ping' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::query' => ['bool', 'connection'=>'mysqlnd_connection', 'query'=>'string'],
'MysqlndUhConnection::queryReadResultsetHeader' => ['bool', 'connection'=>'mysqlnd_connection', 'mysqlnd_stmt'=>'mysqlnd_statement'],
'MysqlndUhConnection::reapQuery' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::refreshServer' => ['bool', 'connection'=>'mysqlnd_connection', 'options'=>'int'],
'MysqlndUhConnection::restartPSession' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::selectDb' => ['bool', 'connection'=>'mysqlnd_connection', 'database'=>'string'],
'MysqlndUhConnection::sendClose' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::sendQuery' => ['bool', 'connection'=>'mysqlnd_connection', 'query'=>'string'],
'MysqlndUhConnection::serverDumpDebugInformation' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::setAutocommit' => ['bool', 'connection'=>'mysqlnd_connection', 'mode'=>'int'],
'MysqlndUhConnection::setCharset' => ['bool', 'connection'=>'mysqlnd_connection', 'charset'=>'string'],
'MysqlndUhConnection::setClientOption' => ['bool', 'connection'=>'mysqlnd_connection', 'option'=>'int', 'value'=>'int'],
'MysqlndUhConnection::setServerOption' => ['void', 'connection'=>'mysqlnd_connection', 'option'=>'int'],
'MysqlndUhConnection::shutdownServer' => ['void', 'MYSQLND_UH_RES_MYSQLND_NAME'=>'string', 'level'=>'string'],
'MysqlndUhConnection::simpleCommand' => ['bool', 'connection'=>'mysqlnd_connection', 'command'=>'int', 'arg'=>'string', 'ok_packet'=>'int', 'silent'=>'bool', 'ignore_upsert_status'=>'bool'],
'MysqlndUhConnection::simpleCommandHandleResponse' => ['bool', 'connection'=>'mysqlnd_connection', 'ok_packet'=>'int', 'silent'=>'bool', 'command'=>'int', 'ignore_upsert_status'=>'bool'],
'MysqlndUhConnection::sslSet' => ['bool', 'connection'=>'mysqlnd_connection', 'key'=>'string', 'cert'=>'string', 'ca'=>'string', 'capath'=>'string', 'cipher'=>'string'],
'MysqlndUhConnection::stmtInit' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::storeResult' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::txCommit' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::txRollback' => ['bool', 'connection'=>'mysqlnd_connection'],
'MysqlndUhConnection::useResult' => ['resource', 'connection'=>'mysqlnd_connection'],
'MysqlndUhPreparedStatement::__construct' => ['void'],
'MysqlndUhPreparedStatement::execute' => ['bool', 'statement'=>'mysqlnd_prepared_statement'],
'MysqlndUhPreparedStatement::prepare' => ['bool', 'statement'=>'mysqlnd_prepared_statement', 'query'=>'string'],
'natcasesort' => ['bool', '&rw_array_arg'=>'array'],
'natsort' => ['bool', '&rw_array_arg'=>'array'],
'ncurses_addch' => ['int', 'ch'=>'int'],
'ncurses_addchnstr' => ['int', 's'=>'string', 'n'=>'int'],
'ncurses_addchstr' => ['int', 's'=>'string'],
'ncurses_addnstr' => ['int', 's'=>'string', 'n'=>'int'],
'ncurses_addstr' => ['int', 'text'=>'string'],
'ncurses_assume_default_colors' => ['int', 'fg'=>'int', 'bg'=>'int'],
'ncurses_attroff' => ['int', 'attributes'=>'int'],
'ncurses_attron' => ['int', 'attributes'=>'int'],
'ncurses_attrset' => ['int', 'attributes'=>'int'],
'ncurses_baudrate' => ['int'],
'ncurses_beep' => ['int'],
'ncurses_bkgd' => ['int', 'attrchar'=>'int'],
'ncurses_bkgdset' => ['void', 'attrchar'=>'int'],
'ncurses_border' => ['int', 'left'=>'int', 'right'=>'int', 'top'=>'int', 'bottom'=>'int', 'tl_corner'=>'int', 'tr_corner'=>'int', 'bl_corner'=>'int', 'br_corner'=>'int'],
'ncurses_bottom_panel' => ['int', 'panel'=>'resource'],
'ncurses_can_change_color' => ['bool'],
'ncurses_cbreak' => ['bool'],
'ncurses_clear' => ['bool'],
'ncurses_clrtobot' => ['bool'],
'ncurses_clrtoeol' => ['bool'],
'ncurses_color_content' => ['int', 'color'=>'int', 'r'=>'int', 'g'=>'int', 'b'=>'int'],
'ncurses_color_set' => ['int', 'pair'=>'int'],
'ncurses_curs_set' => ['int', 'visibility'=>'int'],
'ncurses_def_prog_mode' => ['bool'],
'ncurses_def_shell_mode' => ['bool'],
'ncurses_define_key' => ['int', 'definition'=>'string', 'keycode'=>'int'],
'ncurses_del_panel' => ['bool', 'panel'=>'resource'],
'ncurses_delay_output' => ['int', 'milliseconds'=>'int'],
'ncurses_delch' => ['bool'],
'ncurses_deleteln' => ['bool'],
'ncurses_delwin' => ['bool', 'window'=>'resource'],
'ncurses_doupdate' => ['bool'],
'ncurses_echo' => ['bool'],
'ncurses_echochar' => ['int', 'character'=>'int'],
'ncurses_end' => ['int'],
'ncurses_erase' => ['bool'],
'ncurses_erasechar' => ['string'],
'ncurses_filter' => ['void'],
'ncurses_flash' => ['bool'],
'ncurses_flushinp' => ['bool'],
'ncurses_getch' => ['int'],
'ncurses_getmaxyx' => ['void', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_getmouse' => ['bool', 'mevent'=>'array'],
'ncurses_getyx' => ['void', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_halfdelay' => ['int', 'tenth'=>'int'],
'ncurses_has_colors' => ['bool'],
'ncurses_has_ic' => ['bool'],
'ncurses_has_il' => ['bool'],
'ncurses_has_key' => ['int', 'keycode'=>'int'],
'ncurses_hide_panel' => ['int', 'panel'=>'resource'],
'ncurses_hline' => ['int', 'charattr'=>'int', 'n'=>'int'],
'ncurses_inch' => ['string'],
'ncurses_init' => ['void'],
'ncurses_init_color' => ['int', 'color'=>'int', 'r'=>'int', 'g'=>'int', 'b'=>'int'],
'ncurses_init_pair' => ['int', 'pair'=>'int', 'fg'=>'int', 'bg'=>'int'],
'ncurses_insch' => ['int', 'character'=>'int'],
'ncurses_insdelln' => ['int', 'count'=>'int'],
'ncurses_insertln' => ['int'],
'ncurses_insstr' => ['int', 'text'=>'string'],
'ncurses_instr' => ['int', 'buffer'=>'string'],
'ncurses_isendwin' => ['bool'],
'ncurses_keyok' => ['int', 'keycode'=>'int', 'enable'=>'bool'],
'ncurses_keypad' => ['int', 'window'=>'resource', 'bf'=>'bool'],
'ncurses_killchar' => ['string'],
'ncurses_longname' => ['string'],
'ncurses_meta' => ['int', 'window'=>'resource', '_8bit'=>'bool'],
'ncurses_mouse_trafo' => ['bool', 'y'=>'int', 'x'=>'int', 'toscreen'=>'bool'],
'ncurses_mouseinterval' => ['int', 'milliseconds'=>'int'],
'ncurses_mousemask' => ['int', 'newmask'=>'int', 'oldmask'=>'int'],
'ncurses_move' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_move_panel' => ['int', 'panel'=>'resource', 'startx'=>'int', 'starty'=>'int'],
'ncurses_mvaddch' => ['int', 'y'=>'int', 'x'=>'int', 'c'=>'int'],
'ncurses_mvaddchnstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string', 'n'=>'int'],
'ncurses_mvaddchstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string'],
'ncurses_mvaddnstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string', 'n'=>'int'],
'ncurses_mvaddstr' => ['int', 'y'=>'int', 'x'=>'int', 's'=>'string'],
'ncurses_mvcur' => ['int', 'old_y'=>'int', 'old_x'=>'int', 'new_y'=>'int', 'new_x'=>'int'],
'ncurses_mvdelch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvgetch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvhline' => ['int', 'y'=>'int', 'x'=>'int', 'attrchar'=>'int', 'n'=>'int'],
'ncurses_mvinch' => ['int', 'y'=>'int', 'x'=>'int'],
'ncurses_mvvline' => ['int', 'y'=>'int', 'x'=>'int', 'attrchar'=>'int', 'n'=>'int'],
'ncurses_mvwaddstr' => ['int', 'window'=>'resource', 'y'=>'int', 'x'=>'int', 'text'=>'string'],
'ncurses_napms' => ['int', 'milliseconds'=>'int'],
'ncurses_new_panel' => ['resource', 'window'=>'resource'],
'ncurses_newpad' => ['resource', 'rows'=>'int', 'cols'=>'int'],
'ncurses_newwin' => ['resource', 'rows'=>'int', 'cols'=>'int', 'y'=>'int', 'x'=>'int'],
'ncurses_nl' => ['bool'],
'ncurses_nocbreak' => ['bool'],
'ncurses_noecho' => ['bool'],
'ncurses_nonl' => ['bool'],
'ncurses_noqiflush' => ['void'],
'ncurses_noraw' => ['bool'],
'ncurses_pair_content' => ['int', 'pair'=>'int', 'f'=>'int', 'b'=>'int'],
'ncurses_panel_above' => ['resource', 'panel'=>'resource'],
'ncurses_panel_below' => ['resource', 'panel'=>'resource'],
'ncurses_panel_window' => ['resource', 'panel'=>'resource'],
'ncurses_pnoutrefresh' => ['int', 'pad'=>'resource', 'pminrow'=>'int', 'pmincol'=>'int', 'sminrow'=>'int', 'smincol'=>'int', 'smaxrow'=>'int', 'smaxcol'=>'int'],
'ncurses_prefresh' => ['int', 'pad'=>'resource', 'pminrow'=>'int', 'pmincol'=>'int', 'sminrow'=>'int', 'smincol'=>'int', 'smaxrow'=>'int', 'smaxcol'=>'int'],
'ncurses_putp' => ['int', 'text'=>'string'],
'ncurses_qiflush' => ['void'],
'ncurses_raw' => ['bool'],
'ncurses_refresh' => ['int', 'ch'=>'int'],
'ncurses_replace_panel' => ['int', 'panel'=>'resource', 'window'=>'resource'],
'ncurses_reset_prog_mode' => ['int'],
'ncurses_reset_shell_mode' => ['int'],
'ncurses_resetty' => ['bool'],
'ncurses_savetty' => ['bool'],
'ncurses_scr_dump' => ['int', 'filename'=>'string'],
'ncurses_scr_init' => ['int', 'filename'=>'string'],
'ncurses_scr_restore' => ['int', 'filename'=>'string'],
'ncurses_scr_set' => ['int', 'filename'=>'string'],
'ncurses_scrl' => ['int', 'count'=>'int'],
'ncurses_show_panel' => ['int', 'panel'=>'resource'],
'ncurses_slk_attr' => ['int'],
'ncurses_slk_attroff' => ['int', 'intarg'=>'int'],
'ncurses_slk_attron' => ['int', 'intarg'=>'int'],
'ncurses_slk_attrset' => ['int', 'intarg'=>'int'],
'ncurses_slk_clear' => ['bool'],
'ncurses_slk_color' => ['int', 'intarg'=>'int'],
'ncurses_slk_init' => ['bool', 'format'=>'int'],
'ncurses_slk_noutrefresh' => ['bool'],
'ncurses_slk_refresh' => ['int'],
'ncurses_slk_restore' => ['int'],
'ncurses_slk_set' => ['bool', 'labelnr'=>'int', 'label'=>'string', 'format'=>'int'],
'ncurses_slk_touch' => ['int'],
'ncurses_standend' => ['int'],
'ncurses_standout' => ['int'],
'ncurses_start_color' => ['int'],
'ncurses_termattrs' => ['bool'],
'ncurses_termname' => ['string'],
'ncurses_timeout' => ['void', 'millisec'=>'int'],
'ncurses_top_panel' => ['int', 'panel'=>'resource'],
'ncurses_typeahead' => ['int', 'fd'=>'int'],
'ncurses_ungetch' => ['int', 'keycode'=>'int'],
'ncurses_ungetmouse' => ['bool', 'mevent'=>'array'],
'ncurses_update_panels' => ['void'],
'ncurses_use_default_colors' => ['bool'],
'ncurses_use_env' => ['void', 'flag'=>'bool'],
'ncurses_use_extended_names' => ['int', 'flag'=>'bool'],
'ncurses_vidattr' => ['int', 'intarg'=>'int'],
'ncurses_vline' => ['int', 'charattr'=>'int', 'n'=>'int'],
'ncurses_waddch' => ['int', 'window'=>'resource', 'ch'=>'int'],
'ncurses_waddstr' => ['int', 'window'=>'resource', 'str'=>'string', 'n='=>'int'],
'ncurses_wattroff' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wattron' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wattrset' => ['int', 'window'=>'resource', 'attrs'=>'int'],
'ncurses_wborder' => ['int', 'window'=>'resource', 'left'=>'int', 'right'=>'int', 'top'=>'int', 'bottom'=>'int', 'tl_corner'=>'int', 'tr_corner'=>'int', 'bl_corner'=>'int', 'br_corner'=>'int'],
'ncurses_wclear' => ['int', 'window'=>'resource'],
'ncurses_wcolor_set' => ['int', 'window'=>'resource', 'color_pair'=>'int'],
'ncurses_werase' => ['int', 'window'=>'resource'],
'ncurses_wgetch' => ['int', 'window'=>'resource'],
'ncurses_whline' => ['int', 'window'=>'resource', 'charattr'=>'int', 'n'=>'int'],
'ncurses_wmouse_trafo' => ['bool', 'window'=>'resource', 'y'=>'int', 'x'=>'int', 'toscreen'=>'bool'],
'ncurses_wmove' => ['int', 'window'=>'resource', 'y'=>'int', 'x'=>'int'],
'ncurses_wnoutrefresh' => ['int', 'window'=>'resource'],
'ncurses_wrefresh' => ['int', 'window'=>'resource'],
'ncurses_wstandend' => ['int', 'window'=>'resource'],
'ncurses_wstandout' => ['int', 'window'=>'resource'],
'ncurses_wvline' => ['int', 'window'=>'resource', 'charattr'=>'int', 'n'=>'int'],
'net_get_interfaces' => ['array<string,array<string,mixed>>|false'],
'newrelic_add_custom_parameter' => ['bool', 'key'=>'string', 'value'=>'bool|float|int|string'],
'newrelic_add_custom_tracer' => ['bool', 'function_name'=>'string'],
'newrelic_background_job' => ['void', 'flag='=>'bool'],
'newrelic_capture_params' => ['void', 'enable='=>'bool'],
'newrelic_custom_metric' => ['bool', 'metric_name'=>'string', 'value'=>'float'],
'newrelic_disable_autorum' => ['true'],
'newrelic_end_of_transaction' => ['void'],
'newrelic_end_transaction' => ['bool', 'ignore='=>'bool'],
'newrelic_get_browser_timing_footer' => ['string', 'include_tags='=>'bool'],
'newrelic_get_browser_timing_header' => ['string', 'include_tags='=>'bool'],
'newrelic_ignore_apdex' => ['void'],
'newrelic_ignore_transaction' => ['void'],
'newrelic_name_transaction' => ['bool', 'name'=>'string'],
'newrelic_notice_error' => ['void', 'message'=>'string', 'exception='=>'Exception|Throwable'],
'newrelic_notice_error\'1' => ['void', 'unused_1'=>'string', 'message'=>'string', 'unused_2'=>'string', 'unused_3'=>'int', 'unused_4='=>''],
'newrelic_record_custom_event' => ['void', 'name'=>'string', 'attributes'=>'array'],
'newrelic_record_datastore_segment' => ['mixed', 'func'=>'callable', 'parameters'=>'array'],
'newrelic_set_appname' => ['bool', 'name'=>'string', 'license='=>'string', 'xmit='=>'bool'],
'newrelic_set_user_attributes' => ['bool', 'user'=>'string', 'account'=>'string', 'product'=>'string'],
'newrelic_start_transaction' => ['bool', 'appname'=>'string', 'license='=>'string'],
'newt_bell' => ['void'],
'newt_button' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_button_bar' => ['resource', 'buttons'=>'array'],
'newt_centered_window' => ['int', 'width'=>'int', 'height'=>'int', 'title='=>'string'],
'newt_checkbox' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'def_value'=>'string', 'seq='=>'string'],
'newt_checkbox_get_value' => ['string', 'checkbox'=>'resource'],
'newt_checkbox_set_flags' => ['void', 'checkbox'=>'resource', 'flags'=>'int', 'sense'=>'int'],
'newt_checkbox_set_value' => ['void', 'checkbox'=>'resource', 'value'=>'string'],
'newt_checkbox_tree' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_checkbox_tree_add_item' => ['void', 'checkboxtree'=>'resource', 'text'=>'string', 'data'=>'mixed', 'flags'=>'int', 'index'=>'int', '...args='=>'int'],
'newt_checkbox_tree_find_item' => ['array', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_get_current' => ['mixed', 'checkboxtree'=>'resource'],
'newt_checkbox_tree_get_entry_value' => ['string', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_get_multi_selection' => ['array', 'checkboxtree'=>'resource', 'seqnum'=>'string'],
'newt_checkbox_tree_get_selection' => ['array', 'checkboxtree'=>'resource'],
'newt_checkbox_tree_multi' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'seq'=>'string', 'flags='=>'int'],
'newt_checkbox_tree_set_current' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed'],
'newt_checkbox_tree_set_entry' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed', 'text'=>'string'],
'newt_checkbox_tree_set_entry_value' => ['void', 'checkboxtree'=>'resource', 'data'=>'mixed', 'value'=>'string'],
'newt_checkbox_tree_set_width' => ['void', 'checkbox_tree'=>'resource', 'width'=>'int'],
'newt_clear_key_buffer' => ['void'],
'newt_cls' => ['void'],
'newt_compact_button' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_component_add_callback' => ['void', 'component'=>'resource', 'func_name'=>'mixed', 'data'=>'mixed'],
'newt_component_takes_focus' => ['void', 'component'=>'resource', 'takes_focus'=>'bool'],
'newt_create_grid' => ['resource', 'cols'=>'int', 'rows'=>'int'],
'newt_cursor_off' => ['void'],
'newt_cursor_on' => ['void'],
'newt_delay' => ['void', 'microseconds'=>'int'],
'newt_draw_form' => ['void', 'form'=>'resource'],
'newt_draw_root_text' => ['void', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_entry' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'init_value='=>'string', 'flags='=>'int'],
'newt_entry_get_value' => ['string', 'entry'=>'resource'],
'newt_entry_set' => ['void', 'entry'=>'resource', 'value'=>'string', 'cursor_at_end='=>'bool'],
'newt_entry_set_filter' => ['void', 'entry'=>'resource', 'filter'=>'callable', 'data'=>'mixed'],
'newt_entry_set_flags' => ['void', 'entry'=>'resource', 'flags'=>'int', 'sense'=>'int'],
'newt_finished' => ['int'],
'newt_form' => ['resource', 'vert_bar='=>'resource', 'help='=>'string', 'flags='=>'int'],
'newt_form_add_component' => ['void', 'form'=>'resource', 'component'=>'resource'],
'newt_form_add_components' => ['void', 'form'=>'resource', 'components'=>'array'],
'newt_form_add_hot_key' => ['void', 'form'=>'resource', 'key'=>'int'],
'newt_form_destroy' => ['void', 'form'=>'resource'],
'newt_form_get_current' => ['resource', 'form'=>'resource'],
'newt_form_run' => ['void', 'form'=>'resource', 'exit_struct'=>'array'],
'newt_form_set_background' => ['void', 'from'=>'resource', 'background'=>'int'],
'newt_form_set_height' => ['void', 'form'=>'resource', 'height'=>'int'],
'newt_form_set_size' => ['void', 'form'=>'resource'],
'newt_form_set_timer' => ['void', 'form'=>'resource', 'milliseconds'=>'int'],
'newt_form_set_width' => ['void', 'form'=>'resource', 'width'=>'int'],
'newt_form_watch_fd' => ['void', 'form'=>'resource', 'stream'=>'resource', 'flags='=>'int'],
'newt_get_screen_size' => ['void', 'cols'=>'int', 'rows'=>'int'],
'newt_grid_add_components_to_form' => ['void', 'grid'=>'resource', 'form'=>'resource', 'recurse'=>'bool'],
'newt_grid_basic_window' => ['resource', 'text'=>'resource', 'middle'=>'resource', 'buttons'=>'resource'],
'newt_grid_free' => ['void', 'grid'=>'resource', 'recurse'=>'bool'],
'newt_grid_get_size' => ['void', 'grid'=>'resource', 'width'=>'int', 'height'=>'int'],
'newt_grid_h_close_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_h_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_place' => ['void', 'grid'=>'resource', 'left'=>'int', 'top'=>'int'],
'newt_grid_set_field' => ['void', 'grid'=>'resource', 'col'=>'int', 'row'=>'int', 'type'=>'int', 'val'=>'resource', 'pad_left'=>'int', 'pad_top'=>'int', 'pad_right'=>'int', 'pad_bottom'=>'int', 'anchor'=>'int', 'flags='=>'int'],
'newt_grid_simple_window' => ['resource', 'text'=>'resource', 'middle'=>'resource', 'buttons'=>'resource'],
'newt_grid_v_close_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_v_stacked' => ['resource', 'element1_type'=>'int', 'element1'=>'resource', '...args='=>'resource'],
'newt_grid_wrapped_window' => ['void', 'grid'=>'resource', 'title'=>'string'],
'newt_grid_wrapped_window_at' => ['void', 'grid'=>'resource', 'title'=>'string', 'left'=>'int', 'top'=>'int'],
'newt_init' => ['int'],
'newt_label' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string'],
'newt_label_set_text' => ['void', 'label'=>'resource', 'text'=>'string'],
'newt_listbox' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_listbox_append_entry' => ['void', 'listbox'=>'resource', 'text'=>'string', 'data'=>'mixed'],
'newt_listbox_clear' => ['void', 'listobx'=>'resource'],
'newt_listbox_clear_selection' => ['void', 'listbox'=>'resource'],
'newt_listbox_delete_entry' => ['void', 'listbox'=>'resource', 'key'=>'mixed'],
'newt_listbox_get_current' => ['string', 'listbox'=>'resource'],
'newt_listbox_get_selection' => ['array', 'listbox'=>'resource'],
'newt_listbox_insert_entry' => ['void', 'listbox'=>'resource', 'text'=>'string', 'data'=>'mixed', 'key'=>'mixed'],
'newt_listbox_item_count' => ['int', 'listbox'=>'resource'],
'newt_listbox_select_item' => ['void', 'listbox'=>'resource', 'key'=>'mixed', 'sense'=>'int'],
'newt_listbox_set_current' => ['void', 'listbox'=>'resource', 'num'=>'int'],
'newt_listbox_set_current_by_key' => ['void', 'listbox'=>'resource', 'key'=>'mixed'],
'newt_listbox_set_data' => ['void', 'listbox'=>'resource', 'num'=>'int', 'data'=>'mixed'],
'newt_listbox_set_entry' => ['void', 'listbox'=>'resource', 'num'=>'int', 'text'=>'string'],
'newt_listbox_set_width' => ['void', 'listbox'=>'resource', 'width'=>'int'],
'newt_listitem' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'is_default'=>'bool', 'prev_item'=>'resource', 'data'=>'mixed', 'flags='=>'int'],
'newt_listitem_get_data' => ['mixed', 'item'=>'resource'],
'newt_listitem_set' => ['void', 'item'=>'resource', 'text'=>'string'],
'newt_open_window' => ['int', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'height'=>'int', 'title='=>'string'],
'newt_pop_help_line' => ['void'],
'newt_pop_window' => ['void'],
'newt_push_help_line' => ['void', 'text='=>'string'],
'newt_radio_get_current' => ['resource', 'set_member'=>'resource'],
'newt_radiobutton' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'string', 'is_default'=>'bool', 'prev_button='=>'resource'],
'newt_redraw_help_line' => ['void'],
'newt_reflow_text' => ['string', 'text'=>'string', 'width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'actual_width'=>'int', 'actual_height'=>'int'],
'newt_refresh' => ['void'],
'newt_resize_screen' => ['void', 'redraw='=>'bool'],
'newt_resume' => ['void'],
'newt_run_form' => ['resource', 'form'=>'resource'],
'newt_scale' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'full_value'=>'int'],
'newt_scale_set' => ['void', 'scale'=>'resource', 'amount'=>'int'],
'newt_scrollbar_set' => ['void', 'scrollbar'=>'resource', 'where'=>'int', 'total'=>'int'],
'newt_set_help_callback' => ['void', 'function'=>'mixed'],
'newt_set_suspend_callback' => ['void', 'function'=>'callable', 'data'=>'mixed'],
'newt_suspend' => ['void'],
'newt_textbox' => ['resource', 'left'=>'int', 'top'=>'int', 'width'=>'int', 'height'=>'int', 'flags='=>'int'],
'newt_textbox_get_num_lines' => ['int', 'textbox'=>'resource'],
'newt_textbox_reflowed' => ['resource', 'left'=>'int', 'top'=>'int', 'text'=>'char', 'width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'flags='=>'int'],
'newt_textbox_set_height' => ['void', 'textbox'=>'resource', 'height'=>'int'],
'newt_textbox_set_text' => ['void', 'textbox'=>'resource', 'text'=>'string'],
'newt_vertical_scrollbar' => ['resource', 'left'=>'int', 'top'=>'int', 'height'=>'int', 'normal_colorset='=>'int', 'thumb_colorset='=>'int'],
'newt_wait_for_key' => ['void'],
'newt_win_choice' => ['int', 'title'=>'string', 'button1_text'=>'string', 'button2_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'newt_win_entries' => ['int', 'title'=>'string', 'text'=>'string', 'suggested_width'=>'int', 'flex_down'=>'int', 'flex_up'=>'int', 'data_width'=>'int', 'items'=>'array', 'button1'=>'string', '...args='=>'string'],
'newt_win_menu' => ['int', 'title'=>'string', 'text'=>'string', 'suggestedwidth'=>'int', 'flexdown'=>'int', 'flexup'=>'int', 'maxlistheight'=>'int', 'items'=>'array', 'listitem'=>'int', 'button1='=>'string', '...args='=>'string'],
'newt_win_message' => ['void', 'title'=>'string', 'button_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'newt_win_messagev' => ['void', 'title'=>'string', 'button_text'=>'string', 'format'=>'string', 'args'=>'array'],
'newt_win_ternary' => ['int', 'title'=>'string', 'button1_text'=>'string', 'button2_text'=>'string', 'button3_text'=>'string', 'format'=>'string', 'args='=>'mixed', '...args='=>'mixed'],
'next' => ['mixed', '&rw_array_arg'=>'array'],
'ngettext' => ['string', 'msgid1'=>'string', 'msgid2'=>'string', 'n'=>'int'],
'nl2br' => ['string', 'str'=>'string', 'is_xhtml='=>'bool'],
'nl_langinfo' => ['string|false', 'item'=>'int'],
'NoRewindIterator::__construct' => ['void', 'iterator'=>'Iterator'],
'NoRewindIterator::current' => ['mixed'],
'NoRewindIterator::getInnerIterator' => ['Iterator'],
'NoRewindIterator::key' => ['mixed'],
'NoRewindIterator::next' => ['void'],
'NoRewindIterator::rewind' => ['void'],
'NoRewindIterator::valid' => ['bool'],
'Normalizer::getRawDecomposition' => ['string|null', 'input'=>'string'],
'Normalizer::isNormalized' => ['bool', 'input'=>'string', 'form='=>'int'],
'Normalizer::normalize' => ['string', 'input'=>'string', 'form='=>'int'],
'normalizer_get_raw_decomposition' => ['string|null', 'input'=>'string'],
'normalizer_is_normalized' => ['bool', 'input'=>'string', 'form='=>'int'],
'normalizer_normalize' => ['string', 'input'=>'string', 'form='=>'int'],
'notes_body' => ['array', 'server'=>'string', 'mailbox'=>'string', 'msg_number'=>'int'],
'notes_copy_db' => ['bool', 'from_database_name'=>'string', 'to_database_name'=>'string'],
'notes_create_db' => ['bool', 'database_name'=>'string'],
'notes_create_note' => ['bool', 'database_name'=>'string', 'form_name'=>'string'],
'notes_drop_db' => ['bool', 'database_name'=>'string'],
'notes_find_note' => ['int', 'database_name'=>'string', 'name'=>'string', 'type='=>'string'],
'notes_header_info' => ['object', 'server'=>'string', 'mailbox'=>'string', 'msg_number'=>'int'],
'notes_list_msgs' => ['bool', 'db'=>'string'],
'notes_mark_read' => ['bool', 'database_name'=>'string', 'user_name'=>'string', 'note_id'=>'string'],
'notes_mark_unread' => ['bool', 'database_name'=>'string', 'user_name'=>'string', 'note_id'=>'string'],
'notes_nav_create' => ['bool', 'database_name'=>'string', 'name'=>'string'],
'notes_search' => ['array', 'database_name'=>'string', 'keywords'=>'string'],
'notes_unread' => ['array', 'database_name'=>'string', 'user_name'=>'string'],
'notes_version' => ['float', 'database_name'=>'string'],
'nsapi_request_headers' => ['array'],
'nsapi_response_headers' => ['array'],
'nsapi_virtual' => ['bool', 'uri'=>'string'],
'nthmac' => ['string', 'clent'=>'string', 'data'=>'string'],
'number_format' => ['string', 'number'=>'float|int', 'num_decimal_places='=>'int'],
'number_format\'1' => ['string', 'number'=>'float|int', 'num_decimal_places'=>'int', 'dec_separator'=>'string', 'thousands_separator'=>'string'],
'NumberFormatter::__construct' => ['void', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'NumberFormatter::create' => ['NumberFormatter|false', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'NumberFormatter::format' => ['string|false', 'num'=>'', 'type='=>'int'],
'NumberFormatter::formatCurrency' => ['string', 'num'=>'float', 'currency'=>'string'],
'NumberFormatter::getAttribute' => ['int|false', 'attr'=>'int'],
'NumberFormatter::getErrorCode' => ['int'],
'NumberFormatter::getErrorMessage' => ['string'],
'NumberFormatter::getLocale' => ['string', 'type='=>'int'],
'NumberFormatter::getPattern' => ['string|false'],
'NumberFormatter::getSymbol' => ['string|false', 'attr'=>'int'],
'NumberFormatter::getTextAttribute' => ['string|false', 'attr'=>'int'],
'NumberFormatter::parse' => ['float|false', 'str'=>'string', 'type='=>'int', '&rw_position='=>'int'],
'NumberFormatter::parseCurrency' => ['float|false', 'str'=>'string', '&w_currency'=>'string', '&rw_position='=>'int'],
'NumberFormatter::setAttribute' => ['bool', 'attr'=>'int', 'value'=>''],
'NumberFormatter::setPattern' => ['bool', 'pattern'=>'string'],
'NumberFormatter::setSymbol' => ['bool', 'attr'=>'int', 'symbol'=>'string'],
'NumberFormatter::setTextAttribute' => ['bool', 'attr'=>'int', 'value'=>'string'],
'numfmt_create' => ['NumberFormatter|false', 'locale'=>'string', 'style'=>'int', 'pattern='=>'string'],
'numfmt_format' => ['string|false', 'fmt'=>'NumberFormatter', 'value'=>'int|float', 'type='=>'int'],
'numfmt_format_currency' => ['string|false', 'fmt'=>'NumberFormatter', 'value'=>'float', 'currency'=>'string'],
'numfmt_get_attribute' => ['int|false', 'fmt'=>'NumberFormatter', 'attr'=>'int'],
'numfmt_get_error_code' => ['int', 'fmt'=>'NumberFormatter'],
'numfmt_get_error_message' => ['string', 'fmt'=>'NumberFormatter'],
'numfmt_get_locale' => ['string', 'fmt'=>'NumberFormatter', 'type='=>'int'],
'numfmt_get_pattern' => ['string|false', 'fmt'=>'NumberFormatter'],
'numfmt_get_symbol' => ['string|false', 'fmt'=>'NumberFormatter', 'attr'=>'int'],
'numfmt_get_text_attribute' => ['string|false', 'fmt'=>'NumberFormatter', 'attr'=>'int'],
'numfmt_parse' => ['float|int|false', 'fmt'=>'NumberFormatter', 'value'=>'string', 'type='=>'int', '&rw_position='=>'int'],
'numfmt_parse_currency' => ['float|false', 'fmt'=>'NumberFormatter', 'value'=>'string', '&w_currency'=>'string', '&rw_position='=>'int'],
'numfmt_set_attribute' => ['bool', 'fmt'=>'NumberFormatter', 'attr'=>'int', 'value'=>'int'],
'numfmt_set_pattern' => ['bool', 'fmt'=>'NumberFormatter', 'pattern'=>'string'],
'numfmt_set_symbol' => ['bool', 'fmt'=>'NumberFormatter', 'attr'=>'int', 'value'=>'string'],
'numfmt_set_text_attribute' => ['bool', 'fmt'=>'NumberFormatter', 'attr'=>'int', 'value'=>'string'],
'OAuth::__construct' => ['void', 'consumer_key'=>'string', 'consumer_secret'=>'string', 'signature_method='=>'string', 'auth_type='=>'int'],
'OAuth::__destruct' => ['void'],
'OAuth::disableDebug' => ['bool'],
'OAuth::disableRedirects' => ['bool'],
'OAuth::disableSSLChecks' => ['bool'],
'OAuth::enableDebug' => ['bool'],
'OAuth::enableRedirects' => ['bool'],
'OAuth::enableSSLChecks' => ['bool'],
'OAuth::fetch' => ['mixed', 'protected_resource_url'=>'string', 'extra_parameters='=>'array', 'http_method='=>'string', 'http_headers='=>'array'],
'OAuth::generateSignature' => ['string', 'http_method'=>'string', 'url'=>'string', 'extra_parameters='=>'mixed'],
'OAuth::getAccessToken' => ['array|false', 'access_token_url'=>'string', 'auth_session_handle='=>'string', 'verifier_token='=>'string'],
'OAuth::getCAPath' => ['array'],
'OAuth::getLastResponse' => ['string'],
'OAuth::getLastResponseHeaders' => ['string|false'],
'OAuth::getLastResponseInfo' => ['array'],
'OAuth::getRequestHeader' => ['string|false', 'http_method'=>'string', 'url'=>'string', 'extra_parameters='=>'mixed'],
'OAuth::getRequestToken' => ['array|false', 'request_token_url'=>'string', 'callback_url='=>'string'],
'OAuth::setAuthType' => ['bool', 'auth_type'=>'int'],
'OAuth::setCAPath' => ['mixed', 'ca_path='=>'string', 'ca_info='=>'string'],
'OAuth::setNonce' => ['mixed', 'nonce'=>'string'],
'OAuth::setRequestEngine' => ['void', 'reqengine'=>'int'],
'OAuth::setRSACertificate' => ['mixed', 'cert'=>'string'],
'OAuth::setSSLChecks' => ['bool', 'sslcheck'=>'int'],
'OAuth::setTimeout' => ['void', 'timeout'=>'int'],
'OAuth::setTimestamp' => ['mixed', 'timestamp'=>'string'],
'OAuth::setToken' => ['bool', 'token'=>'string', 'token_secret'=>'string'],
'OAuth::setVersion' => ['bool', 'version'=>'string'],
'oauth_get_sbs' => ['string', 'http_method'=>'string', 'uri'=>'string', 'request_parameters='=>'array'],
'oauth_urlencode' => ['string', 'uri'=>'string'],
'OAuthProvider::__construct' => ['void', 'params_array='=>'array'],
'OAuthProvider::addRequiredParameter' => ['bool', 'req_params'=>'string'],
'OAuthProvider::callconsumerHandler' => ['void'],
'OAuthProvider::callTimestampNonceHandler' => ['void'],
'OAuthProvider::calltokenHandler' => ['void'],
'OAuthProvider::checkOAuthRequest' => ['void', 'uri='=>'string', 'method='=>'string'],
'OAuthProvider::consumerHandler' => ['void', 'callback_function'=>'callable'],
'OAuthProvider::generateToken' => ['string', 'size'=>'int', 'strong='=>'bool'],
'OAuthProvider::is2LeggedEndpoint' => ['void', 'params_array'=>'mixed'],
'OAuthProvider::isRequestTokenEndpoint' => ['void', 'will_issue_request_token'=>'bool'],
'OAuthProvider::removeRequiredParameter' => ['bool', 'req_params'=>'string'],
'OAuthProvider::reportProblem' => ['string', 'oauthexception'=>'string', 'send_headers='=>'bool'],
'OAuthProvider::setParam' => ['bool', 'param_key'=>'string', 'param_val='=>'mixed'],
'OAuthProvider::setRequestTokenPath' => ['bool', 'path'=>'string'],
'OAuthProvider::timestampNonceHandler' => ['void', 'callback_function'=>'callable'],
'OAuthProvider::tokenHandler' => ['void', 'callback_function'=>'callable'],
'ob_clean' => ['bool'],
'ob_deflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_end_clean' => ['bool'],
'ob_end_flush' => ['bool'],
'ob_etaghandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_flush' => ['bool'],
'ob_get_clean' => ['string|false'],
'ob_get_contents' => ['string|false'],
'ob_get_flush' => ['string|false'],
'ob_get_length' => ['int|false'],
'ob_get_level' => ['int'],
'ob_get_status' => ['array', 'full_status='=>'bool'],
'ob_gzhandler' => ['string|false', 'data'=>'string', 'flags'=>'int'],
'ob_iconv_handler' => ['string', 'contents'=>'string', 'status'=>'int'],
'ob_implicit_flush' => ['void', 'flag='=>'int'],
'ob_inflatehandler' => ['string', 'data'=>'string', 'mode'=>'int'],
'ob_list_handlers' => ['false|array'],
'ob_start' => ['bool', 'user_function='=>'string|array|?callable', 'chunk_size='=>'int', 'flags='=>'int'],
'ob_tidyhandler' => ['string', 'input'=>'string', 'mode='=>'int'],
'oci_bind_array_by_name' => ['bool', 'stmt'=>'resource', 'name'=>'string', '&rw_var'=>'array', 'max_table_length'=>'int', 'max_item_length='=>'int', 'type='=>'int'],
'oci_bind_by_name' => ['bool', 'stmt'=>'resource', 'name'=>'string', '&rw_var'=>'mixed', 'maxlength='=>'int', 'type='=>'int'],
'oci_cancel' => ['bool', 'stmt'=>'resource'],
'oci_client_version' => ['string'],
'oci_close' => ['bool', 'connection'=>'resource'],
'OCI_Collection::append' => ['bool', 'value'=>'mixed'],
'OCI_Collection::assign' => ['bool', 'from'=>'OCI_Collection'],
'OCI_Collection::assignElem' => ['bool', 'index'=>'int', 'value'=>'mixed'],
'OCI_Collection::free' => ['bool'],
'OCI_Collection::getElem' => ['mixed', 'index'=>'int'],
'OCI_Collection::max' => ['int|false'],
'OCI_Collection::size' => ['int|false'],
'OCI_Collection::trim' => ['bool', 'num'=>'int'],
'oci_collection_append' => ['bool', 'value'=>'string'],
'oci_collection_assign' => ['bool', 'from'=>'object'],
'oci_collection_element_assign' => ['bool', 'index'=>'int', 'val'=>'string'],
'oci_collection_element_get' => ['string', 'ndx'=>'int'],
'oci_collection_max' => ['int'],
'oci_collection_size' => ['int'],
'oci_collection_trim' => ['bool', 'num'=>'int'],
'oci_commit' => ['bool', 'connection'=>'resource'],
'oci_connect' => ['resource|false', 'user'=>'string', 'pass'=>'string', 'db='=>'string', 'charset='=>'string', 'session_mode='=>'int'],
'oci_define_by_name' => ['bool', 'stmt'=>'resource', 'name'=>'string', '&w_var'=>'mixed', 'type='=>'int'],
'oci_error' => ['array|false', 'resource='=>'resource'],
'oci_execute' => ['bool', 'stmt'=>'resource', 'mode='=>'int'],
'oci_fetch' => ['bool', 'stmt'=>'resource'],
'oci_fetch_all' => ['int|false', 'stmt'=>'resource', '&w_output'=>'array', 'skip='=>'int', 'maxrows='=>'int', 'flags='=>'int'],
'oci_fetch_array' => ['array|false', 'stmt'=>'resource', 'mode='=>'int'],
'oci_fetch_assoc' => ['array|false', 'stmt'=>'resource'],
'oci_fetch_object' => ['object|false', 'stmt'=>'resource'],
'oci_fetch_row' => ['array|false', 'stmt'=>'resource'],
'oci_field_is_null' => ['bool', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_field_name' => ['string|false', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_field_precision' => ['int|false', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_field_scale' => ['int|false', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_field_size' => ['int|false', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_field_type' => ['mixed|false', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_field_type_raw' => ['int|false', 'stmt'=>'resource', 'col'=>'mixed'],
'oci_free_collection' => ['bool'],
'oci_free_cursor' => ['bool', 'stmt'=>'resource'],
'oci_free_descriptor' => ['bool'],
'oci_free_statement' => ['bool', 'stmt'=>'resource'],
'oci_get_implicit' => ['bool', 'stmt'=>''],
'oci_get_implicit_resultset' => ['resource|false', 'statement'=>'resource'],
'oci_internal_debug' => ['void', 'onoff'=>'bool'],
'OCI_Lob::append' => ['bool', 'lob_from'=>'OCI_Lob'],
'OCI_Lob::close' => ['bool'],
'OCI_Lob::eof' => ['bool'],
'OCI_Lob::erase' => ['int|false', 'offset='=>'int', 'length='=>'int'],
'OCI_Lob::export' => ['bool', 'filename'=>'string', 'start='=>'int', 'length='=>'int'],
'OCI_Lob::flush' => ['bool', 'flag='=>'int'],
'OCI_Lob::free' => ['bool'],
'OCI_Lob::getbuffering' => ['bool'],
'OCI_Lob::import' => ['bool', 'filename'=>'string'],
'OCI_Lob::load' => ['string|false'],
'OCI_Lob::read' => ['string|false', 'length'=>'int'],
'OCI_Lob::rewind' => ['bool'],
'OCI_Lob::save' => ['bool', 'data'=>'string', 'offset='=>'int'],
'OCI_Lob::savefile' => ['bool', 'filename'=>''],
'OCI_Lob::seek' => ['bool', 'offset'=>'int', 'whence='=>'int'],
'OCI_Lob::setbuffering' => ['bool', 'on_off'=>'bool'],
'OCI_Lob::size' => ['int|false'],
'OCI_Lob::tell' => ['int|false'],
'OCI_Lob::truncate' => ['bool', 'length='=>'int'],
'OCI_Lob::write' => ['int|false', 'data'=>'string', 'length='=>'int'],
'OCI_Lob::writeTemporary' => ['bool', 'data'=>'string', 'lob_type='=>'int'],
'OCI_Lob::writetofile' => ['bool', 'filename'=>'', 'start'=>'', 'length'=>''],
'oci_lob_append' => ['bool', 'lob'=>'object'],
'oci_lob_close' => ['bool'],
'oci_lob_copy' => ['bool', 'lob_to'=>'OCI_Lob', 'lob_from'=>'OCI_Lob', 'length='=>'int'],
'oci_lob_eof' => ['bool'],
'oci_lob_erase' => ['int', 'offset'=>'int', 'length'=>'int'],
'oci_lob_export' => ['bool', 'filename'=>'string', 'start'=>'int', 'length'=>'int'],
'oci_lob_flush' => ['bool', 'flag'=>'int'],
'oci_lob_import' => ['bool', 'filename'=>'string'],
'oci_lob_is_equal' => ['bool', 'lob1'=>'OCI_Lob', 'lob2'=>'OCI_Lob'],
'oci_lob_load' => ['string'],
'oci_lob_read' => ['string', 'length'=>'int'],
'oci_lob_rewind' => ['bool'],
'oci_lob_save' => ['bool', 'data'=>'string', 'offset'=>'int'],
'oci_lob_seek' => ['bool', 'offset'=>'int', 'whence'=>'int'],
'oci_lob_size' => ['int'],
'oci_lob_tell' => ['int'],
'oci_lob_truncate' => ['bool', 'length'=>'int'],
'oci_lob_write' => ['int', 'string'=>'string', 'length'=>'int'],
'oci_lob_write_temporary' => ['bool', 'var'=>'string', 'lob_type'=>'int'],
'oci_new_collection' => ['OCI_Collection|false', 'connection'=>'resource', 'tdo'=>'string', 'schema='=>'string'],
'oci_new_connect' => ['resource|false', 'user'=>'string', 'pass'=>'string', 'db='=>'string', 'charset='=>'string', 'session_mode='=>'int'],
'oci_new_cursor' => ['resource|false', 'connection'=>'resource'],
'oci_new_descriptor' => ['OCI_Lob|false', 'connection'=>'resource', 'type='=>'int'],
'oci_num_fields' => ['int|false', 'stmt'=>'resource'],
'oci_num_rows' => ['int|false', 'stmt'=>'resource'],
'oci_parse' => ['resource|false', 'connection'=>'resource', 'statement'=>'string'],
'oci_password_change' => ['bool', 'connection'=>'resource', 'username'=>'string', 'old_password'=>'string', 'new_password'=>'string'],
'oci_pconnect' => ['resource|false', 'user'=>'string', 'pass'=>'string', 'db='=>'string', 'charset='=>'string', 'session_mode='=>'int'],
'oci_register_taf_callback' => ['bool', 'connection'=>'resource', 'callback='=>'callable'],
'oci_result' => ['mixed|false', 'stmt'=>'resource', 'column'=>'mixed'],
'oci_rollback' => ['bool', 'connection'=>'resource'],
'oci_server_version' => ['string|false', 'connection'=>'resource'],
'oci_set_action' => ['bool', 'connection'=>'resource', 'value'=>'string'],
'oci_set_call_timeout' => ['bool', 'connection'=>'resource', 'time_out'=>'int'],
'oci_set_client_identifier' => ['bool', 'connection'=>'resource', 'value'=>'string'],
'oci_set_client_info' => ['bool', 'connection'=>'resource', 'value'=>'string'],
'oci_set_db_operation' => ['bool', 'connection'=>'resource', 'value'=>'string'],
'oci_set_edition' => ['bool', 'value'=>'string'],
'oci_set_module_name' => ['bool', 'connection'=>'resource', 'value'=>'string'],
'oci_set_prefetch' => ['bool', 'stmt'=>'resource', 'prefetch_rows'=>'int'],
'oci_statement_type' => ['string|false', 'stmt'=>'resource'],
'oci_unregister_taf_callback' => ['bool', 'connection'=>'resource'],
'ocifetchinto' => ['int|bool', 'stmt'=>'resource', '&w_output'=>'array', 'mode='=>'int'],
'ocigetbufferinglob' => ['bool'],
'ocisetbufferinglob' => ['bool', 'flag'=>'bool'],
'octdec' => ['int|float', 'octal_number'=>'string'],
'odbc_autocommit' => ['mixed', 'connection_id'=>'resource', 'onoff='=>'bool'],
'odbc_binmode' => ['bool', 'result_id'=>'resource', 'mode'=>'int'],
'odbc_close' => ['void', 'connection_id'=>'resource'],
'odbc_close_all' => ['void'],
'odbc_columnprivileges' => ['resource|false', 'connection_id'=>'resource', 'catalog'=>'string', 'schema'=>'string', 'table'=>'string', 'column'=>'string'],
'odbc_columns' => ['resource|false', 'connection_id'=>'resource', 'qualifier='=>'string', 'owner='=>'string', 'table_name='=>'string', 'column_name='=>'string'],
'odbc_commit' => ['bool', 'connection_id'=>'resource'],
'odbc_connect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_cursor' => ['string', 'result_id'=>'resource'],
'odbc_data_source' => ['array|false', 'connection_id'=>'resource', 'fetch_type'=>'int'],
'odbc_do' => ['resource', 'connection_id'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_error' => ['string', 'connection_id='=>'resource'],
'odbc_errormsg' => ['string', 'connection_id='=>'resource'],
'odbc_exec' => ['resource', 'connection_id'=>'resource', 'query'=>'string', 'flags='=>'int'],
'odbc_execute' => ['bool', 'result_id'=>'resource', 'parameters_array='=>'array'],
'odbc_fetch_array' => ['array|false', 'result'=>'resource', 'rownumber='=>'int'],
'odbc_fetch_into' => ['int', 'result_id'=>'resource', '&w_result_array'=>'array', 'rownumber='=>'int'],
'odbc_fetch_object' => ['object|false', 'result'=>'resource', 'rownumber='=>'int'],
'odbc_fetch_row' => ['bool', 'result_id'=>'resource', 'row_number='=>'int'],
'odbc_field_len' => ['int|false', 'result_id'=>'resource', 'field_number'=>'int'],
'odbc_field_name' => ['string|false', 'result_id'=>'resource', 'field_number'=>'int'],
'odbc_field_num' => ['int|false', 'result_id'=>'resource', 'field_name'=>'string'],
'odbc_field_precision' => ['int', 'result_id'=>'resource', 'field_number'=>'int'],
'odbc_field_scale' => ['int|false', 'result_id'=>'resource', 'field_number'=>'int'],
'odbc_field_type' => ['string|false', 'result_id'=>'resource', 'field_number'=>'int'],
'odbc_foreignkeys' => ['resource|false', 'connection_id'=>'resource', 'pk_qualifier'=>'string', 'pk_owner'=>'string', 'pk_table'=>'string', 'fk_qualifier'=>'string', 'fk_owner'=>'string', 'fk_table'=>'string'],
'odbc_free_result' => ['bool', 'result_id'=>'resource'],
'odbc_gettypeinfo' => ['resource', 'connection_id'=>'resource', 'data_type='=>'int'],
'odbc_longreadlen' => ['bool', 'result_id'=>'resource', 'length'=>'int'],
'odbc_next_result' => ['bool', 'result_id'=>'resource'],
'odbc_num_fields' => ['int', 'result_id'=>'resource'],
'odbc_num_rows' => ['int', 'result_id'=>'resource'],
'odbc_pconnect' => ['resource|false', 'dsn'=>'string', 'user'=>'string', 'password'=>'string', 'cursor_option='=>'int'],
'odbc_prepare' => ['resource|false', 'connection_id'=>'resource', 'query'=>'string'],
'odbc_primarykeys' => ['resource|false', 'connection_id'=>'resource', 'qualifier'=>'string', 'owner'=>'string', 'table'=>'string'],
'odbc_procedurecolumns' => ['resource|false', 'connection_id'=>'resource', 'qualifier'=>'string', 'owner'=>'string', 'proc'=>'string', 'column'=>'string'],
'odbc_procedures' => ['resource|false', 'connection_id'=>'resource', 'qualifier'=>'string', 'owner'=>'string', 'name'=>'string'],
'odbc_result' => ['mixed|false', 'result_id'=>'resource', 'field'=>'mixed'],
'odbc_result_all' => ['int|false', 'result_id'=>'resource', 'format='=>'string'],
'odbc_rollback' => ['bool', 'connection_id'=>'resource'],
'odbc_setoption' => ['bool', 'result_id'=>'resource', 'which'=>'int', 'option'=>'int', 'value'=>'int'],
'odbc_specialcolumns' => ['resource|false', 'connection_id'=>'resource', 'type'=>'int', 'qualifier'=>'string', 'owner'=>'string', 'table'=>'string', 'scope'=>'int', 'nullable'=>'int'],
'odbc_statistics' => ['resource|false', 'connection_id'=>'resource', 'qualifier'=>'string', 'owner'=>'string', 'name'=>'string', 'unique'=>'int', 'accuracy'=>'int'],
'odbc_tableprivileges' => ['resource|false', 'connection_id'=>'resource', 'qualifier'=>'string', 'owner'=>'string', 'name'=>'string'],
'odbc_tables' => ['resource|false', 'connection_id'=>'resource', 'qualifier='=>'string', 'owner='=>'string', 'name='=>'string', 'table_types='=>'string'],
'opcache_compile_file' => ['bool', 'file'=>'string'],
'opcache_get_configuration' => ['array'],
'opcache_get_status' => ['array|false', 'get_scripts='=>'bool'],
'opcache_invalidate' => ['bool', 'script'=>'string', 'force='=>'bool'],
'opcache_is_script_cached' => ['bool', 'script'=>'string'],
'opcache_reset' => ['bool'],
'openal_buffer_create' => ['resource'],
'openal_buffer_data' => ['bool', 'buffer'=>'resource', 'format'=>'int', 'data'=>'string', 'freq'=>'int'],
'openal_buffer_destroy' => ['bool', 'buffer'=>'resource'],
'openal_buffer_get' => ['int', 'buffer'=>'resource', 'property'=>'int'],
'openal_buffer_loadwav' => ['bool', 'buffer'=>'resource', 'wavfile'=>'string'],
'openal_context_create' => ['resource', 'device'=>'resource'],
'openal_context_current' => ['bool', 'context'=>'resource'],
'openal_context_destroy' => ['bool', 'context'=>'resource'],
'openal_context_process' => ['bool', 'context'=>'resource'],
'openal_context_suspend' => ['bool', 'context'=>'resource'],
'openal_device_close' => ['bool', 'device'=>'resource'],
'openal_device_open' => ['resource', 'device_desc='=>'string'],
'openal_listener_get' => ['mixed', 'property'=>'int'],
'openal_listener_set' => ['bool', 'property'=>'int', 'setting'=>'mixed'],
'openal_source_create' => ['resource'],
'openal_source_destroy' => ['bool', 'source'=>'resource'],
'openal_source_get' => ['mixed', 'source'=>'resource', 'property'=>'int'],
'openal_source_pause' => ['bool', 'source'=>'resource'],
'openal_source_play' => ['bool', 'source'=>'resource'],
'openal_source_rewind' => ['bool', 'source'=>'resource'],
'openal_source_set' => ['bool', 'source'=>'resource', 'property'=>'int', 'setting'=>'mixed'],
'openal_source_stop' => ['bool', 'source'=>'resource'],
'openal_stream' => ['resource', 'source'=>'resource', 'format'=>'int', 'rate'=>'int'],
'opendir' => ['resource|false', 'path'=>'string', 'context='=>'resource'],
'openlog' => ['bool', 'ident'=>'string', 'option'=>'int', 'facility'=>'int'],
'openssl_cipher_iv_length' => ['int|false', 'method'=>'string'],
'openssl_csr_export' => ['bool', 'csr'=>'string|resource', '&w_out'=>'string', 'notext='=>'bool'],
'openssl_csr_export_to_file' => ['bool', 'csr'=>'string|resource', 'outfilename'=>'string', 'notext='=>'bool'],
'openssl_csr_get_public_key' => ['resource|false', 'csr'=>'string|resource', 'use_shortnames='=>'bool'],
'openssl_csr_get_subject' => ['array|false', 'csr'=>'string|resource', 'use_shortnames='=>'bool'],
'openssl_csr_new' => ['resource|false', 'dn'=>'array', '&w_privkey'=>'resource', 'configargs='=>'array', 'extraattribs='=>'array'],
'openssl_csr_sign' => ['resource|false', 'csr'=>'string|resource', 'x509'=>'string|resource|null', 'priv_key'=>'string|resource|array', 'days'=>'int', 'config_args='=>'array', 'serial='=>'int'],
'openssl_decrypt' => ['string|false', 'data'=>'string', 'method'=>'string', 'key'=>'string', 'options='=>'int', 'iv='=>'string', 'tag='=>'string', 'aad='=>'string'],
'openssl_dh_compute_key' => ['string|false', 'pub_key'=>'string', 'dh_key'=>'resource'],
'openssl_digest' => ['string|false', 'data'=>'string', 'method'=>'string', 'raw_output='=>'bool'],
'openssl_encrypt' => ['string|false', 'data'=>'string', 'method'=>'string', 'key'=>'string', 'options='=>'int', 'iv='=>'string', '&w_tag='=>'string', 'aad='=>'string', 'tag_length='=>'int'],
'openssl_error_string' => ['string|false'],
'openssl_free_key' => ['void', 'key_identifier'=>'resource'],
'openssl_get_cert_locations' => ['array'],
'openssl_get_cipher_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_curve_names' => ['array<int,string>'],
'openssl_get_md_methods' => ['array', 'aliases='=>'bool'],
'openssl_get_privatekey' => ['resource|false', 'key'=>'string', 'passphrase='=>'string'],
'openssl_get_publickey' => ['resource|false', 'cert'=>'resource|string'],
'openssl_open' => ['bool', 'sealed_data'=>'string', '&w_open_data'=>'string', 'env_key'=>'string', 'priv_key_id'=>'string|array|resource', 'method='=>'string', 'iv='=>'string'],
'openssl_pbkdf2' => ['string|false', 'password'=>'string', 'salt'=>'string', 'key_length'=>'int', 'iterations'=>'int', 'digest_algorithm='=>'string'],
'openssl_pkcs12_export' => ['bool', 'x509'=>'string|resource', '&w_out'=>'string', 'priv_key'=>'string|array|resource', 'pass'=>'string', 'args='=>'array'],
'openssl_pkcs12_export_to_file' => ['bool', 'x509'=>'string|resource', 'filename'=>'string', 'priv_key'=>'string|array|resource', 'pass'=>'string', 'args='=>'array'],
'openssl_pkcs12_read' => ['bool', 'pkcs12'=>'string', '&w_certs'=>'array', 'pass'=>'string'],
'openssl_pkcs7_decrypt' => ['bool', 'infilename'=>'string', 'outfilename'=>'string', 'recipcert'=>'string|resource', 'recipkey='=>'string|resource|array'],
'openssl_pkcs7_encrypt' => ['bool', 'infile'=>'string', 'outfile'=>'string', 'recipcerts'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'cipherid='=>'int'],
'openssl_pkcs7_read' => ['bool', 'infilename'=>'string', '&w_certs'=>'array'],
'openssl_pkcs7_sign' => ['bool', 'infile'=>'string', 'outfile'=>'string', 'signcert'=>'string|resource', 'privkey'=>'string|resource|array', 'headers'=>'array', 'flags='=>'int', 'extracerts='=>'string'],
'openssl_pkcs7_verify' => ['bool|int', 'filename'=>'string', 'flags'=>'int', 'outfilename='=>'string', 'cainfo='=>'array', 'extracerts='=>'string', 'content='=>'string', 'p7bfilename='=>'string'],
'openssl_pkey_derive' => ['string|false', 'peer_pub_key'=>'mixed', 'priv_key'=>'mixed', 'keylen='=>'?int'],
'openssl_pkey_export' => ['bool', 'key'=>'resource', '&w_out'=>'string', 'passphrase='=>'?string', 'configargs='=>'array'],
'openssl_pkey_export_to_file' => ['bool', 'key'=>'resource|string|array', 'outfilename'=>'string', 'passphrase='=>'?string', 'configargs='=>'array'],
'openssl_pkey_free' => ['void', 'key'=>'resource'],
'openssl_pkey_get_details' => ['array|false', 'key'=>'resource'],
'openssl_pkey_get_private' => ['resource|false', 'key'=>'string', 'passphrase='=>'string'],
'openssl_pkey_get_public' => ['resource|false', 'certificate'=>'resource|string'],
'openssl_pkey_new' => ['resource|false', 'configargs='=>'array'],
'openssl_private_decrypt' => ['bool', 'data'=>'string', '&w_decrypted'=>'string', 'key'=>'string|resource|array', 'padding='=>'int'],
'openssl_private_encrypt' => ['bool', 'data'=>'string', '&w_crypted'=>'string', 'key'=>'string|resource|array', 'padding='=>'int'],
'openssl_public_decrypt' => ['bool', 'data'=>'string', '&w_decrypted'=>'string', 'key'=>'string|resource', 'padding='=>'int'],
'openssl_public_encrypt' => ['bool', 'data'=>'string', '&w_crypted'=>'string', 'key'=>'string|resource', 'padding='=>'int'],
'openssl_random_pseudo_bytes' => ['string|false', 'length'=>'int', '&w_crypto_strong='=>'bool'],
'openssl_seal' => ['int|false', 'data'=>'string', '&w_sealed_data'=>'string', '&rw_env_keys'=>'array', 'pub_key_ids'=>'array', 'method='=>'string', '&iv='=>'string'],
'openssl_sign' => ['bool', 'data'=>'string', '&w_signature'=>'string', 'priv_key_id'=>'resource|string', 'signature_alg='=>'int|string'],
'openssl_spki_export' => ['?string', 'spkac'=>'string'],
'openssl_spki_export_challenge' => ['?string', 'spkac'=>'string'],
'openssl_spki_new' => ['?string', 'privkey'=>'resource', 'challenge'=>'string', 'algorithm='=>'int'],
'openssl_spki_verify' => ['bool', 'spkac'=>'string'],
'openssl_verify' => ['int', 'data'=>'string', 'signature'=>'string', 'pub_key_id'=>'resource|string', 'signature_alg='=>'int|string'],
'openssl_x509_check_private_key' => ['bool', 'cert'=>'string|resource', 'key'=>'string|resource|array'],
'openssl_x509_checkpurpose' => ['bool|int', 'x509cert'=>'string|resource', 'purpose'=>'int', 'cainfo='=>'array', 'untrustedfile='=>'string'],
'openssl_x509_export' => ['bool', 'x509'=>'string|resource', '&w_output'=>'string', 'notext='=>'bool'],
'openssl_x509_export_to_file' => ['bool', 'x509'=>'string|resource', 'outfilename'=>'string', 'notext='=>'bool'],
'openssl_x509_fingerprint' => ['string|false', 'x509'=>'string|resource', 'hash_algorithm='=>'string', 'raw_output='=>'bool'],
'openssl_x509_free' => ['void', 'x509'=>'resource'],
'openssl_x509_parse' => ['array|false', 'x509cert'=>'string|resource', 'shortnames='=>'bool'],
'openssl_x509_read' => ['resource|false', 'x509certdata'=>'string|resource'],
'ord' => ['int', 'character'=>'string'],
'OuterIterator::current' => ['mixed'],
'OuterIterator::getInnerIterator' => ['Iterator'],
'OuterIterator::key' => ['int|string'],
'OuterIterator::next' => ['void'],
'OuterIterator::rewind' => ['void'],
'OuterIterator::valid' => ['bool'],
'OutOfBoundsException::__clone' => ['void'],
'OutOfBoundsException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OutOfBoundsException'],
'OutOfBoundsException::__toString' => ['string'],
'OutOfBoundsException::getCode' => ['int'],
'OutOfBoundsException::getFile' => ['string'],
'OutOfBoundsException::getLine' => ['int'],
'OutOfBoundsException::getMessage' => ['string'],
'OutOfBoundsException::getPrevious' => ['Throwable|OutOfBoundsException|null'],
'OutOfBoundsException::getTrace' => ['array'],
'OutOfBoundsException::getTraceAsString' => ['string'],
'OutOfRangeException::__clone' => ['void'],
'OutOfRangeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OutOfRangeException'],
'OutOfRangeException::__toString' => ['string'],
'OutOfRangeException::getCode' => ['int'],
'OutOfRangeException::getFile' => ['string'],
'OutOfRangeException::getLine' => ['int'],
'OutOfRangeException::getMessage' => ['string'],
'OutOfRangeException::getPrevious' => ['Throwable|OutOfRangeException|null'],
'OutOfRangeException::getTrace' => ['array'],
'OutOfRangeException::getTraceAsString' => ['string'],
'output_add_rewrite_var' => ['bool', 'name'=>'string', 'value'=>'string'],
'output_cache_disable' => ['void'],
'output_cache_disable_compression' => ['void'],
'output_cache_exists' => ['bool', 'key'=>'string', 'lifetime'=>'int'],
'output_cache_fetch' => ['string', 'key'=>'string', 'function'=>'', 'lifetime'=>'int'],
'output_cache_get' => ['mixed|false', 'key'=>'string', 'lifetime'=>'int'],
'output_cache_output' => ['string', 'key'=>'string', 'function'=>'', 'lifetime'=>'int'],
'output_cache_put' => ['bool', 'key'=>'string', 'data'=>'mixed'],
'output_cache_remove' => ['bool', 'filename'=>''],
'output_cache_remove_key' => ['bool', 'key'=>'string'],
'output_cache_remove_url' => ['bool', 'url'=>'string'],
'output_cache_stop' => ['void'],
'output_reset_rewrite_vars' => ['bool'],
'outputformatObj::getOption' => ['string', 'property_name'=>'string'],
'outputformatObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'outputformatObj::setOption' => ['void', 'property_name'=>'string', 'new_value'=>'string'],
'outputformatObj::validate' => ['int'],
'OverflowException::__clone' => ['void'],
'OverflowException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?OverflowException'],
'OverflowException::__toString' => ['string'],
'OverflowException::getCode' => ['int'],
'OverflowException::getFile' => ['string'],
'OverflowException::getLine' => ['int'],
'OverflowException::getMessage' => ['string'],
'OverflowException::getPrevious' => ['Throwable|OverflowException|null'],
'OverflowException::getTrace' => ['array'],
'OverflowException::getTraceAsString' => ['string'],
'overload' => ['', 'class_name'=>'string'],
'override_function' => ['bool', 'function_name'=>'string', 'function_args'=>'string', 'function_code'=>'string'],
'OwsrequestObj::__construct' => ['void'],
'OwsrequestObj::addParameter' => ['int', 'name'=>'string', 'value'=>'string'],
'OwsrequestObj::getName' => ['string', 'index'=>'int'],
'OwsrequestObj::getValue' => ['string', 'index'=>'int'],
'OwsrequestObj::getValueByName' => ['string', 'name'=>'string'],
'OwsrequestObj::loadParams' => ['int'],
'OwsrequestObj::setParameter' => ['int', 'name'=>'string', 'value'=>'string'],
'pack' => ['string|false', 'format'=>'string', '...args='=>'mixed'],
'parallel\Future::done' => ['bool'],
'parallel\Future::select' => ['mixed', '&resolving'=>'parallel\Future[]', '&w_resolved'=>'parallel\Future[]', '&w_errored'=>'parallel\Future[]', '&w_timedout='=>'parallel\Future[]', 'timeout='=>'int'],
'parallel\Future::value' => ['mixed', 'timeout='=>'int'],
'parallel\Runtime::__construct' => ['void', 'arg'=>'string|array'],
'parallel\Runtime::__construct\'1' => ['void', 'bootstrap'=>'string', 'configuration'=>'array<string,mixed>'],
'parallel\Runtime::close' => ['void'],
'parallel\Runtime::run' => ['?parallel\Future', 'closure'=>'Closure', 'args='=>'array'],
'parallel\Runtime::kill' => ['void'],
'ParentIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator'],
'ParentIterator::accept' => ['bool'],
'ParentIterator::getChildren' => ['ParentIterator'],
'ParentIterator::hasChildren' => ['bool'],
'ParentIterator::next' => ['void'],
'ParentIterator::rewind' => ['void'],
'ParentIterator::valid' => [''],
'Parle\Lexer::advance' => ['void'],
'Parle\Lexer::build' => ['void'],
'Parle\Lexer::callout' => ['void', 'id'=>'int', 'callback'=>'callable'],
'Parle\Lexer::consume' => ['void', 'data'=>'string'],
'Parle\Lexer::dump' => ['void'],
'Parle\Lexer::getToken' => ['Parle\Token'],
'Parle\Lexer::insertMacro' => ['void', 'name'=>'string', 'regex'=>'string'],
'Parle\Lexer::push' => ['void', 'regex'=>'string', 'id'=>'int'],
'Parle\Lexer::reset' => ['void', 'pos'=>'int'],
'Parle\Parser::advance' => ['void'],
'Parle\Parser::build' => ['void'],
'Parle\Parser::consume' => ['void', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\Parser::dump' => ['void'],
'Parle\Parser::errorInfo' => ['Parle\ErrorInfo'],
'Parle\Parser::left' => ['void', 'token'=>'string'],
'Parle\Parser::nonassoc' => ['void', 'token'=>'string'],
'Parle\Parser::precedence' => ['void', 'token'=>'string'],
'Parle\Parser::push' => ['int', 'name'=>'string', 'rule'=>'string'],
'Parle\Parser::reset' => ['void', 'tokenId'=>'int'],
'Parle\Parser::right' => ['void', 'token'=>'string'],
'Parle\Parser::sigil' => ['string', 'idx'=>'array'],
'Parle\Parser::token' => ['void', 'token'=>'string'],
'Parle\Parser::tokenId' => ['int', 'token'=>'string'],
'Parle\Parser::trace' => ['string'],
'Parle\Parser::validate' => ['bool', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\RLexer::advance' => ['void'],
'Parle\RLexer::build' => ['void'],
'Parle\RLexer::callout' => ['void', 'id'=>'int', 'callback'=>'callable'],
'Parle\RLexer::consume' => ['void', 'data'=>'string'],
'Parle\RLexer::dump' => ['void'],
'Parle\RLexer::getToken' => ['Parle\Token'],
'parle\rlexer::insertMacro' => ['void', 'name'=>'string', 'regex'=>'string'],
'Parle\RLexer::push' => ['void', 'state'=>'string', 'regex'=>'string', 'newState'=>'string'],
'Parle\RLexer::pushState' => ['int', 'state'=>'string'],
'Parle\RLexer::reset' => ['void', 'pos'=>'int'],
'Parle\RParser::advance' => ['void'],
'Parle\RParser::build' => ['void'],
'Parle\RParser::consume' => ['void', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\RParser::dump' => ['void'],
'Parle\RParser::errorInfo' => ['Parle\ErrorInfo'],
'Parle\RParser::left' => ['void', 'token'=>'string'],
'Parle\RParser::nonassoc' => ['void', 'token'=>'string'],
'Parle\RParser::precedence' => ['void', 'token'=>'string'],
'Parle\RParser::push' => ['int', 'name'=>'string', 'rule'=>'string'],
'Parle\RParser::reset' => ['void', 'tokenId'=>'int'],
'Parle\RParser::right' => ['void', 'token'=>'string'],
'Parle\RParser::sigil' => ['string', 'idx'=>'array'],
'Parle\RParser::token' => ['void', 'token'=>'string'],
'Parle\RParser::tokenId' => ['int', 'token'=>'string'],
'Parle\RParser::trace' => ['string'],
'Parle\RParser::validate' => ['bool', 'data'=>'string', 'lexer'=>'Parle\Lexer'],
'Parle\Stack::pop' => ['void'],
'Parle\Stack::push' => ['void', 'item'=>'mixed'],
'parse_ini_file' => ['array|false', 'filename'=>'string', 'process_sections='=>'bool', 'scanner_mode='=>'int'],
'parse_ini_string' => ['array|false', 'ini_string'=>'string', 'process_sections='=>'bool', 'scanner_mode='=>'int'],
'parse_str' => ['void', 'encoded_string'=>'string', '&w_result='=>'array'],
'parse_url' => ['mixed|false', 'url'=>'string', 'url_component='=>'int'],
'ParseError::__clone' => ['void'],
'ParseError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?ParseError'],
'ParseError::__toString' => ['string'],
'ParseError::getCode' => ['int'],
'ParseError::getFile' => ['string'],
'ParseError::getLine' => ['int'],
'ParseError::getMessage' => ['string'],
'ParseError::getPrevious' => ['Throwable|ParseError|null'],
'ParseError::getTrace' => ['array'],
'ParseError::getTraceAsString' => ['string'],
'parsekit_compile_file' => ['array', 'filename'=>'string', 'errors='=>'array', 'options='=>'int'],
'parsekit_compile_string' => ['array', 'phpcode'=>'string', 'errors='=>'array', 'options='=>'int'],
'parsekit_func_arginfo' => ['array', 'function'=>'mixed'],
'passthru' => ['void', 'command'=>'string', '&w_return_value='=>'int'],
'password_get_info' => ['array', 'hash'=>'string'],
'password_hash' => ['string|null', 'password'=>'string', 'algo'=>'int|string|null', 'options='=>'array'],
'password_make_salt' => ['bool', 'password'=>'string', 'hash'=>'string'],
'password_needs_rehash' => ['bool', 'hash'=>'string', 'algo'=>'int|string|null', 'options='=>'array'],
'password_verify' => ['bool', 'password'=>'string', 'hash'=>'string'],
'pathinfo' => ['array|string', 'path'=>'string', 'options='=>'int'],
'pclose' => ['int', 'fp'=>'resource'],
'pcnlt_sigwaitinfo' => ['int', 'set'=>'array', '&w_siginfo'=>'array'],
'pcntl_alarm' => ['int', 'seconds'=>'int'],
'pcntl_async_signals' => ['bool', 'on='=>'bool'],
'pcntl_errno' => ['int'],
'pcntl_exec' => ['null|false', 'path'=>'string', 'args='=>'array', 'envs='=>'array'],
'pcntl_fork' => ['int'],
'pcntl_get_last_error' => ['int'],
'pcntl_getpriority' => ['int', 'pid='=>'int', 'process_identifier='=>'int'],
'pcntl_setpriority' => ['bool', 'priority'=>'int', 'pid='=>'int', 'process_identifier='=>'int'],
'pcntl_signal' => ['bool', 'signo'=>'int', 'handle'=>'callable():void|callable(int):void|callable(int,array):void|int', 'restart_syscalls='=>'bool'],
'pcntl_signal_dispatch' => ['bool'],
'pcntl_signal_get_handler' => ['int|string', 'signo'=>'int'],
'pcntl_sigprocmask' => ['bool', 'how'=>'int', 'set'=>'array', '&w_oldset='=>'array'],
'pcntl_sigtimedwait' => ['int', 'set'=>'array', '&w_siginfo='=>'array', 'seconds='=>'int', 'nanoseconds='=>'int'],
'pcntl_sigwaitinfo' => ['int', 'set'=>'array', '&w_siginfo='=>'array'],
'pcntl_strerror' => ['string|false', 'errno'=>'int'],
'pcntl_wait' => ['int', '&w_status'=>'int', 'options='=>'int', '&w_rusage='=>'array'],
'pcntl_waitpid' => ['int', 'pid'=>'int', '&w_status'=>'int', 'options='=>'int', '&w_rusage='=>'array'],
'pcntl_wexitstatus' => ['int', 'status'=>'int'],
'pcntl_wifcontinued' => ['bool', 'status'=>'int'],
'pcntl_wifexited' => ['bool', 'status'=>'int'],
'pcntl_wifsignaled' => ['bool', 'status'=>'int'],
'pcntl_wifstopped' => ['bool', 'status'=>'int'],
'pcntl_wstopsig' => ['int', 'status'=>'int'],
'pcntl_wtermsig' => ['int', 'status'=>'int'],
'PDF_activate_item' => ['bool', 'pdfdoc'=>'resource', 'id'=>'int'],
'PDF_add_launchlink' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'PDF_add_locallink' => ['bool', 'pdfdoc'=>'resource', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'page'=>'int', 'dest'=>'string'],
'PDF_add_nameddest' => ['bool', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_add_note' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'PDF_add_pdflink' => ['bool', 'pdfdoc'=>'resource', 'bottom_left_x'=>'float', 'bottom_left_y'=>'float', 'up_right_x'=>'float', 'up_right_y'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'PDF_add_table_cell' => ['int', 'pdfdoc'=>'resource', 'table'=>'int', 'column'=>'int', 'row'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDF_add_textflow' => ['int', 'pdfdoc'=>'resource', 'textflow'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDF_add_thumbnail' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int'],
'PDF_add_weblink' => ['bool', 'pdfdoc'=>'resource', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'url'=>'string'],
'PDF_arc' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDF_arcn' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDF_attach_file' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'description'=>'string', 'author'=>'string', 'mimetype'=>'string', 'icon'=>'string'],
'PDF_begin_document' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_begin_font' => ['bool', 'pdfdoc'=>'resource', 'filename'=>'string', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float', 'optlist'=>'string'],
'PDF_begin_glyph' => ['bool', 'pdfdoc'=>'resource', 'glyphname'=>'string', 'wx'=>'float', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float'],
'PDF_begin_item' => ['int', 'pdfdoc'=>'resource', 'tag'=>'string', 'optlist'=>'string'],
'PDF_begin_layer' => ['bool', 'pdfdoc'=>'resource', 'layer'=>'int'],
'PDF_begin_page' => ['bool', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'PDF_begin_page_ext' => ['bool', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDF_begin_pattern' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'PDF_begin_template' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'PDF_begin_template_ext' => ['int', 'pdfdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDF_circle' => ['bool', 'pdfdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'r'=>'float'],
'PDF_clip' => ['bool', 'p'=>'resource'],
'PDF_close' => ['bool', 'p'=>'resource'],
'PDF_close_image' => ['bool', 'p'=>'resource', 'image'=>'int'],
'PDF_close_pdi' => ['bool', 'p'=>'resource', 'doc'=>'int'],
'PDF_close_pdi_page' => ['bool', 'p'=>'resource', 'page'=>'int'],
'PDF_closepath' => ['bool', 'p'=>'resource'],
'PDF_closepath_fill_stroke' => ['bool', 'p'=>'resource'],
'PDF_closepath_stroke' => ['bool', 'p'=>'resource'],
'PDF_concat' => ['bool', 'p'=>'resource', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDF_continue_text' => ['bool', 'p'=>'resource', 'text'=>'string'],
'PDF_create_3dview' => ['int', 'pdfdoc'=>'resource', 'username'=>'string', 'optlist'=>'string'],
'PDF_create_action' => ['int', 'pdfdoc'=>'resource', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_annotation' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_bookmark' => ['int', 'pdfdoc'=>'resource', 'text'=>'string', 'optlist'=>'string'],
'PDF_create_field' => ['bool', 'pdfdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'name'=>'string', 'type'=>'string', 'optlist'=>'string'],
'PDF_create_fieldgroup' => ['bool', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_create_gstate' => ['int', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_create_pvf' => ['bool', 'pdfdoc'=>'resource', 'filename'=>'string', 'data'=>'string', 'optlist'=>'string'],
'PDF_create_textflow' => ['int', 'pdfdoc'=>'resource', 'text'=>'string', 'optlist'=>'string'],
'PDF_curveto' => ['bool', 'p'=>'resource', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'PDF_define_layer' => ['int', 'pdfdoc'=>'resource', 'name'=>'string', 'optlist'=>'string'],
'PDF_delete' => ['bool', 'pdfdoc'=>'resource'],
'PDF_delete_pvf' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string'],
'PDF_delete_table' => ['bool', 'pdfdoc'=>'resource', 'table'=>'int', 'optlist'=>'string'],
'PDF_delete_textflow' => ['bool', 'pdfdoc'=>'resource', 'textflow'=>'int'],
'PDF_encoding_set_char' => ['bool', 'pdfdoc'=>'resource', 'encoding'=>'string', 'slot'=>'int', 'glyphname'=>'string', 'uv'=>'int'],
'PDF_end_document' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_end_font' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_glyph' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_item' => ['bool', 'pdfdoc'=>'resource', 'id'=>'int'],
'PDF_end_layer' => ['bool', 'pdfdoc'=>'resource'],
'PDF_end_page' => ['bool', 'p'=>'resource'],
'PDF_end_page_ext' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_end_pattern' => ['bool', 'p'=>'resource'],
'PDF_end_template' => ['bool', 'p'=>'resource'],
'PDF_endpath' => ['bool', 'p'=>'resource'],
'PDF_fill' => ['bool', 'p'=>'resource'],
'PDF_fill_imageblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'image'=>'int', 'optlist'=>'string'],
'PDF_fill_pdfblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'contents'=>'int', 'optlist'=>'string'],
'PDF_fill_stroke' => ['bool', 'p'=>'resource'],
'PDF_fill_textblock' => ['int', 'pdfdoc'=>'resource', 'page'=>'int', 'blockname'=>'string', 'text'=>'string', 'optlist'=>'string'],
'PDF_findfont' => ['int', 'p'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'embed'=>'int'],
'PDF_fit_image' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_fit_pdi_page' => ['bool', 'pdfdoc'=>'resource', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_fit_table' => ['string', 'pdfdoc'=>'resource', 'table'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDF_fit_textflow' => ['string', 'pdfdoc'=>'resource', 'textflow'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDF_fit_textline' => ['bool', 'pdfdoc'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDF_get_apiname' => ['string', 'pdfdoc'=>'resource'],
'PDF_get_buffer' => ['string', 'p'=>'resource'],
'PDF_get_errmsg' => ['string', 'pdfdoc'=>'resource'],
'PDF_get_errnum' => ['int', 'pdfdoc'=>'resource'],
'PDF_get_majorversion' => ['int'],
'PDF_get_minorversion' => ['int'],
'PDF_get_parameter' => ['string', 'p'=>'resource', 'key'=>'string', 'modifier'=>'float'],
'PDF_get_pdi_parameter' => ['string', 'p'=>'resource', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDF_get_pdi_value' => ['float', 'p'=>'resource', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDF_get_value' => ['float', 'p'=>'resource', 'key'=>'string', 'modifier'=>'float'],
'PDF_info_font' => ['float', 'pdfdoc'=>'resource', 'font'=>'int', 'keyword'=>'string', 'optlist'=>'string'],
'PDF_info_matchbox' => ['float', 'pdfdoc'=>'resource', 'boxname'=>'string', 'num'=>'int', 'keyword'=>'string'],
'PDF_info_table' => ['float', 'pdfdoc'=>'resource', 'table'=>'int', 'keyword'=>'string'],
'PDF_info_textflow' => ['float', 'pdfdoc'=>'resource', 'textflow'=>'int', 'keyword'=>'string'],
'PDF_info_textline' => ['float', 'pdfdoc'=>'resource', 'text'=>'string', 'keyword'=>'string', 'optlist'=>'string'],
'PDF_initgraphics' => ['bool', 'p'=>'resource'],
'PDF_lineto' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_load_3ddata' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_load_font' => ['int', 'pdfdoc'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'optlist'=>'string'],
'PDF_load_iccprofile' => ['int', 'pdfdoc'=>'resource', 'profilename'=>'string', 'optlist'=>'string'],
'PDF_load_image' => ['int', 'pdfdoc'=>'resource', 'imagetype'=>'string', 'filename'=>'string', 'optlist'=>'string'],
'PDF_makespotcolor' => ['int', 'p'=>'resource', 'spotname'=>'string'],
'PDF_moveto' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_new' => ['resource'],
'PDF_open_ccitt' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'bitreverse'=>'int', 'k'=>'int', 'blackls1'=>'int'],
'PDF_open_file' => ['bool', 'p'=>'resource', 'filename'=>'string'],
'PDF_open_image' => ['int', 'p'=>'resource', 'imagetype'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'PDF_open_image_file' => ['int', 'p'=>'resource', 'imagetype'=>'string', 'filename'=>'string', 'stringparam'=>'string', 'intparam'=>'int'],
'PDF_open_memory_image' => ['int', 'p'=>'resource', 'image'=>'resource'],
'PDF_open_pdi' => ['int', 'pdfdoc'=>'resource', 'filename'=>'string', 'optlist'=>'string', 'len'=>'int'],
'PDF_open_pdi_document' => ['int', 'p'=>'resource', 'filename'=>'string', 'optlist'=>'string'],
'PDF_open_pdi_page' => ['int', 'p'=>'resource', 'doc'=>'int', 'pagenumber'=>'int', 'optlist'=>'string'],
'PDF_pcos_get_number' => ['float', 'p'=>'resource', 'doc'=>'int', 'path'=>'string'],
'PDF_pcos_get_stream' => ['string', 'p'=>'resource', 'doc'=>'int', 'optlist'=>'string', 'path'=>'string'],
'PDF_pcos_get_string' => ['string', 'p'=>'resource', 'doc'=>'int', 'path'=>'string'],
'PDF_place_image' => ['bool', 'pdfdoc'=>'resource', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'PDF_place_pdi_page' => ['bool', 'pdfdoc'=>'resource', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'sx'=>'float', 'sy'=>'float'],
'PDF_process_pdi' => ['int', 'pdfdoc'=>'resource', 'doc'=>'int', 'page'=>'int', 'optlist'=>'string'],
'PDF_rect' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'PDF_restore' => ['bool', 'p'=>'resource'],
'PDF_resume_page' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_rotate' => ['bool', 'p'=>'resource', 'phi'=>'float'],
'PDF_save' => ['bool', 'p'=>'resource'],
'PDF_scale' => ['bool', 'p'=>'resource', 'sx'=>'float', 'sy'=>'float'],
'PDF_set_border_color' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_set_border_dash' => ['bool', 'pdfdoc'=>'resource', 'black'=>'float', 'white'=>'float'],
'PDF_set_border_style' => ['bool', 'pdfdoc'=>'resource', 'style'=>'string', 'width'=>'float'],
'PDF_set_gstate' => ['bool', 'pdfdoc'=>'resource', 'gstate'=>'int'],
'PDF_set_info' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'PDF_set_layer_dependency' => ['bool', 'pdfdoc'=>'resource', 'type'=>'string', 'optlist'=>'string'],
'PDF_set_parameter' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'string'],
'PDF_set_text_pos' => ['bool', 'p'=>'resource', 'x'=>'float', 'y'=>'float'],
'PDF_set_value' => ['bool', 'p'=>'resource', 'key'=>'string', 'value'=>'float'],
'PDF_setcolor' => ['bool', 'p'=>'resource', 'fstype'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'PDF_setdash' => ['bool', 'pdfdoc'=>'resource', 'b'=>'float', 'w'=>'float'],
'PDF_setdashpattern' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_setflat' => ['bool', 'pdfdoc'=>'resource', 'flatness'=>'float'],
'PDF_setfont' => ['bool', 'pdfdoc'=>'resource', 'font'=>'int', 'fontsize'=>'float'],
'PDF_setgray' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setgray_fill' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setgray_stroke' => ['bool', 'p'=>'resource', 'g'=>'float'],
'PDF_setlinecap' => ['bool', 'p'=>'resource', 'linecap'=>'int'],
'PDF_setlinejoin' => ['bool', 'p'=>'resource', 'value'=>'int'],
'PDF_setlinewidth' => ['bool', 'p'=>'resource', 'width'=>'float'],
'PDF_setmatrix' => ['bool', 'p'=>'resource', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDF_setmiterlimit' => ['bool', 'pdfdoc'=>'resource', 'miter'=>'float'],
'PDF_setrgbcolor' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_setrgbcolor_fill' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_setrgbcolor_stroke' => ['bool', 'p'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDF_shading' => ['int', 'pdfdoc'=>'resource', 'shtype'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'PDF_shading_pattern' => ['int', 'pdfdoc'=>'resource', 'shading'=>'int', 'optlist'=>'string'],
'PDF_shfill' => ['bool', 'pdfdoc'=>'resource', 'shading'=>'int'],
'PDF_show' => ['bool', 'pdfdoc'=>'resource', 'text'=>'string'],
'PDF_show_boxed' => ['int', 'p'=>'resource', 'text'=>'string', 'left'=>'float', 'top'=>'float', 'width'=>'float', 'height'=>'float', 'mode'=>'string', 'feature'=>'string'],
'PDF_show_xy' => ['bool', 'p'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'PDF_skew' => ['bool', 'p'=>'resource', 'alpha'=>'float', 'beta'=>'float'],
'PDF_stringwidth' => ['float', 'p'=>'resource', 'text'=>'string', 'font'=>'int', 'fontsize'=>'float'],
'PDF_stroke' => ['bool', 'p'=>'resource'],
'PDF_suspend_page' => ['bool', 'pdfdoc'=>'resource', 'optlist'=>'string'],
'PDF_translate' => ['bool', 'p'=>'resource', 'tx'=>'float', 'ty'=>'float'],
'PDF_utf16_to_utf8' => ['string', 'pdfdoc'=>'resource', 'utf16string'=>'string'],
'PDF_utf32_to_utf16' => ['string', 'pdfdoc'=>'resource', 'utf32string'=>'string', 'ordering'=>'string'],
'PDF_utf8_to_utf16' => ['string', 'pdfdoc'=>'resource', 'utf8string'=>'string', 'ordering'=>'string'],
'PDFlib::activate_item' => ['bool', 'id'=>''],
'PDFlib::add_launchlink' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'PDFlib::add_locallink' => ['bool', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'page'=>'int', 'dest'=>'string'],
'PDFlib::add_nameddest' => ['bool', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::add_note' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'PDFlib::add_pdflink' => ['bool', 'bottom_left_x'=>'float', 'bottom_left_y'=>'float', 'up_right_x'=>'float', 'up_right_y'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'PDFlib::add_table_cell' => ['int', 'table'=>'int', 'column'=>'int', 'row'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::add_textflow' => ['int', 'textflow'=>'int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::add_thumbnail' => ['bool', 'image'=>'int'],
'PDFlib::add_weblink' => ['bool', 'lowerleftx'=>'float', 'lowerlefty'=>'float', 'upperrightx'=>'float', 'upperrighty'=>'float', 'url'=>'string'],
'PDFlib::arc' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::arcn' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::attach_file' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'description'=>'string', 'author'=>'string', 'mimetype'=>'string', 'icon'=>'string'],
'PDFlib::begin_document' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::begin_font' => ['bool', 'filename'=>'string', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float', 'optlist'=>'string'],
'PDFlib::begin_glyph' => ['bool', 'glyphname'=>'string', 'wx'=>'float', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float'],
'PDFlib::begin_item' => ['int', 'tag'=>'string', 'optlist'=>'string'],
'PDFlib::begin_layer' => ['bool', 'layer'=>'int'],
'PDFlib::begin_page' => ['bool', 'width'=>'float', 'height'=>'float'],
'PDFlib::begin_page_ext' => ['bool', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDFlib::begin_pattern' => ['int', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'PDFlib::begin_template' => ['int', 'width'=>'float', 'height'=>'float'],
'PDFlib::begin_template_ext' => ['int', 'width'=>'float', 'height'=>'float', 'optlist'=>'string'],
'PDFlib::circle' => ['bool', 'x'=>'float', 'y'=>'float', 'r'=>'float'],
'PDFlib::clip' => ['bool'],
'PDFlib::close' => ['bool'],
'PDFlib::close_image' => ['bool', 'image'=>'int'],
'PDFlib::close_pdi' => ['bool', 'doc'=>'int'],
'PDFlib::close_pdi_page' => ['bool', 'page'=>'int'],
'PDFlib::closepath' => ['bool'],
'PDFlib::closepath_fill_stroke' => ['bool'],
'PDFlib::closepath_stroke' => ['bool'],
'PDFlib::concat' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDFlib::continue_text' => ['bool', 'text'=>'string'],
'PDFlib::create_3dview' => ['int', 'username'=>'string', 'optlist'=>'string'],
'PDFlib::create_action' => ['int', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_annotation' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_bookmark' => ['int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::create_field' => ['bool', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'name'=>'string', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::create_fieldgroup' => ['bool', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::create_gstate' => ['int', 'optlist'=>'string'],
'PDFlib::create_pvf' => ['bool', 'filename'=>'string', 'data'=>'string', 'optlist'=>'string'],
'PDFlib::create_textflow' => ['int', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::curveto' => ['bool', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'PDFlib::define_layer' => ['int', 'name'=>'string', 'optlist'=>'string'],
'PDFlib::delete' => ['bool'],
'PDFlib::delete_pvf' => ['int', 'filename'=>'string'],
'PDFlib::delete_table' => ['bool', 'table'=>'int', 'optlist'=>'string'],
'PDFlib::delete_textflow' => ['bool', 'textflow'=>'int'],
'PDFlib::encoding_set_char' => ['bool', 'encoding'=>'string', 'slot'=>'int', 'glyphname'=>'string', 'uv'=>'int'],
'PDFlib::end_document' => ['bool', 'optlist'=>'string'],
'PDFlib::end_font' => ['bool'],
'PDFlib::end_glyph' => ['bool'],
'PDFlib::end_item' => ['bool', 'id'=>'int'],
'PDFlib::end_layer' => ['bool'],
'PDFlib::end_page' => ['bool', 'p'=>''],
'PDFlib::end_page_ext' => ['bool', 'optlist'=>'string'],
'PDFlib::end_pattern' => ['bool', 'p'=>''],
'PDFlib::end_template' => ['bool', 'p'=>''],
'PDFlib::endpath' => ['bool', 'p'=>''],
'PDFlib::fill' => ['bool'],
'PDFlib::fill_imageblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'image'=>'int', 'optlist'=>'string'],
'PDFlib::fill_pdfblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'contents'=>'int', 'optlist'=>'string'],
'PDFlib::fill_stroke' => ['bool'],
'PDFlib::fill_textblock' => ['int', 'page'=>'int', 'blockname'=>'string', 'text'=>'string', 'optlist'=>'string'],
'PDFlib::findfont' => ['int', 'fontname'=>'string', 'encoding'=>'string', 'embed'=>'int'],
'PDFlib::fit_image' => ['bool', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::fit_pdi_page' => ['bool', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::fit_table' => ['string', 'table'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDFlib::fit_textflow' => ['string', 'textflow'=>'int', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'optlist'=>'string'],
'PDFlib::fit_textline' => ['bool', 'text'=>'string', 'x'=>'float', 'y'=>'float', 'optlist'=>'string'],
'PDFlib::get_apiname' => ['string'],
'PDFlib::get_buffer' => ['string'],
'PDFlib::get_errmsg' => ['string'],
'PDFlib::get_errnum' => ['int'],
'PDFlib::get_majorversion' => ['int'],
'PDFlib::get_minorversion' => ['int'],
'PDFlib::get_parameter' => ['string', 'key'=>'string', 'modifier'=>'float'],
'PDFlib::get_pdi_parameter' => ['string', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDFlib::get_pdi_value' => ['float', 'key'=>'string', 'doc'=>'int', 'page'=>'int', 'reserved'=>'int'],
'PDFlib::get_value' => ['float', 'key'=>'string', 'modifier'=>'float'],
'PDFlib::info_font' => ['float', 'font'=>'int', 'keyword'=>'string', 'optlist'=>'string'],
'PDFlib::info_matchbox' => ['float', 'boxname'=>'string', 'num'=>'int', 'keyword'=>'string'],
'PDFlib::info_table' => ['float', 'table'=>'int', 'keyword'=>'string'],
'PDFlib::info_textflow' => ['float', 'textflow'=>'int', 'keyword'=>'string'],
'PDFlib::info_textline' => ['float', 'text'=>'string', 'keyword'=>'string', 'optlist'=>'string'],
'PDFlib::initgraphics' => ['bool'],
'PDFlib::lineto' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::load_3ddata' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::load_font' => ['int', 'fontname'=>'string', 'encoding'=>'string', 'optlist'=>'string'],
'PDFlib::load_iccprofile' => ['int', 'profilename'=>'string', 'optlist'=>'string'],
'PDFlib::load_image' => ['int', 'imagetype'=>'string', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::makespotcolor' => ['int', 'spotname'=>'string'],
'PDFlib::moveto' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::open_ccitt' => ['int', 'filename'=>'string', 'width'=>'int', 'height'=>'int', 'BitReverse'=>'int', 'k'=>'int', 'Blackls1'=>'int'],
'PDFlib::open_file' => ['bool', 'filename'=>'string'],
'PDFlib::open_image' => ['int', 'imagetype'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'PDFlib::open_image_file' => ['int', 'imagetype'=>'string', 'filename'=>'string', 'stringparam'=>'string', 'intparam'=>'int'],
'PDFlib::open_memory_image' => ['int', 'image'=>'resource'],
'PDFlib::open_pdi' => ['int', 'filename'=>'string', 'optlist'=>'string', 'len'=>'int'],
'PDFlib::open_pdi_document' => ['int', 'filename'=>'string', 'optlist'=>'string'],
'PDFlib::open_pdi_page' => ['int', 'doc'=>'int', 'pagenumber'=>'int', 'optlist'=>'string'],
'PDFlib::pcos_get_number' => ['float', 'doc'=>'int', 'path'=>'string'],
'PDFlib::pcos_get_stream' => ['string', 'doc'=>'int', 'optlist'=>'string', 'path'=>'string'],
'PDFlib::pcos_get_string' => ['string', 'doc'=>'int', 'path'=>'string'],
'PDFlib::place_image' => ['bool', 'image'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'PDFlib::place_pdi_page' => ['bool', 'page'=>'int', 'x'=>'float', 'y'=>'float', 'sx'=>'float', 'sy'=>'float'],
'PDFlib::process_pdi' => ['int', 'doc'=>'int', 'page'=>'int', 'optlist'=>'string'],
'PDFlib::rect' => ['bool', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'PDFlib::restore' => ['bool', 'p'=>''],
'PDFlib::resume_page' => ['bool', 'optlist'=>'string'],
'PDFlib::rotate' => ['bool', 'phi'=>'float'],
'PDFlib::save' => ['bool', 'p'=>''],
'PDFlib::scale' => ['bool', 'sx'=>'float', 'sy'=>'float'],
'PDFlib::set_border_color' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::set_border_dash' => ['bool', 'black'=>'float', 'white'=>'float'],
'PDFlib::set_border_style' => ['bool', 'style'=>'string', 'width'=>'float'],
'PDFlib::set_gstate' => ['bool', 'gstate'=>'int'],
'PDFlib::set_info' => ['bool', 'key'=>'string', 'value'=>'string'],
'PDFlib::set_layer_dependency' => ['bool', 'type'=>'string', 'optlist'=>'string'],
'PDFlib::set_parameter' => ['bool', 'key'=>'string', 'value'=>'string'],
'PDFlib::set_text_pos' => ['bool', 'x'=>'float', 'y'=>'float'],
'PDFlib::set_value' => ['bool', 'key'=>'string', 'value'=>'float'],
'PDFlib::setcolor' => ['bool', 'fstype'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'PDFlib::setdash' => ['bool', 'b'=>'float', 'w'=>'float'],
'PDFlib::setdashpattern' => ['bool', 'optlist'=>'string'],
'PDFlib::setflat' => ['bool', 'flatness'=>'float'],
'PDFlib::setfont' => ['bool', 'font'=>'int', 'fontsize'=>'float'],
'PDFlib::setgray' => ['bool', 'g'=>'float'],
'PDFlib::setgray_fill' => ['bool', 'g'=>'float'],
'PDFlib::setgray_stroke' => ['bool', 'g'=>'float'],
'PDFlib::setlinecap' => ['bool', 'linecap'=>'int'],
'PDFlib::setlinejoin' => ['bool', 'value'=>'int'],
'PDFlib::setlinewidth' => ['bool', 'width'=>'float'],
'PDFlib::setmatrix' => ['bool', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'e'=>'float', 'f'=>'float'],
'PDFlib::setmiterlimit' => ['bool', 'miter'=>'float'],
'PDFlib::setrgbcolor' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::setrgbcolor_fill' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::setrgbcolor_stroke' => ['bool', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'PDFlib::shading' => ['int', 'shtype'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'PDFlib::shading_pattern' => ['int', 'shading'=>'int', 'optlist'=>'string'],
'PDFlib::shfill' => ['bool', 'shading'=>'int'],
'PDFlib::show' => ['bool', 'text'=>'string'],
'PDFlib::show_boxed' => ['int', 'text'=>'string', 'left'=>'float', 'top'=>'float', 'width'=>'float', 'height'=>'float', 'mode'=>'string', 'feature'=>'string'],
'PDFlib::show_xy' => ['bool', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'PDFlib::skew' => ['bool', 'alpha'=>'float', 'beta'=>'float'],
'PDFlib::stringwidth' => ['float', 'text'=>'string', 'font'=>'int', 'fontsize'=>'float'],
'PDFlib::stroke' => ['bool', 'p'=>''],
'PDFlib::suspend_page' => ['bool', 'optlist'=>'string'],
'PDFlib::translate' => ['bool', 'tx'=>'float', 'ty'=>'float'],
'PDFlib::utf16_to_utf8' => ['string', 'utf16string'=>'string'],
'PDFlib::utf32_to_utf16' => ['string', 'utf32string'=>'string', 'ordering'=>'string'],
'PDFlib::utf8_to_utf16' => ['string', 'utf8string'=>'string', 'ordering'=>'string'],
'PDO::__construct' => ['void', 'dsn'=>'string', 'username='=>'?string', 'passwd='=>'?string', 'options='=>'?array'],
'PDO::__sleep' => ['string[]'],
'PDO::__wakeup' => ['void'],
'PDO::beginTransaction' => ['bool'],
'PDO::commit' => ['bool'],
'PDO::cubrid_schema' => ['array', 'schema_type'=>'int', 'table_name='=>'string', 'col_name='=>'string'],
'PDO::errorCode' => ['?string'],
'PDO::errorInfo' => ['array'],
'PDO::exec' => ['int|false', 'query'=>'string'],
'PDO::getAttribute' => ['', 'attribute'=>'int'],
'PDO::getAvailableDrivers' => ['array'],
'PDO::inTransaction' => ['bool'],
'PDO::lastInsertId' => ['string', 'name='=>'string|null'],
'PDO::pgsqlCopyFromArray' => ['bool', 'table_name'=>'string', 'rows'=>'array', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyFromFile' => ['bool', 'table_name'=>'string', 'filename'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyToArray' => ['array', 'table_name'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlCopyToFile' => ['bool', 'table_name'=>'string', 'filename'=>'string', 'delimiter'=>'string', 'null_as'=>'string', 'fields'=>'string'],
'PDO::pgsqlGetNotify' => ['array', 'result_type'=>'int', 'ms_timeout'=>'int'],
'PDO::pgsqlGetPid' => ['int'],
'PDO::pgsqlLOBCreate' => ['string'],
'PDO::pgsqlLOBOpen' => ['resource', 'oid'=>'string', 'mode='=>'string'],
'PDO::pgsqlLOBUnlink' => ['bool', 'oid'=>'string'],
'PDO::prepare' => ['PDOStatement|false', 'statement'=>'string', 'options='=>'array'],
'PDO::query' => ['PDOStatement|false', 'sql'=>'string'],
'PDO::query\'1' => ['PDOStatement|false', 'sql'=>'string', 'fetch_column'=>'int', 'colno'=>'int'],
'PDO::query\'2' => ['PDOStatement|false', 'sql'=>'string', 'fetch_class'=>'int', 'classname'=>'string', 'ctorargs'=>'array'],
'PDO::query\'3' => ['PDOStatement|false', 'sql'=>'string', 'fetch_into'=>'int', 'object'=>'object'],
'PDO::quote' => ['string|false', 'string'=>'string', 'paramtype='=>'int'],
'PDO::rollBack' => ['bool'],
'PDO::setAttribute' => ['bool', 'attribute'=>'int', 'value'=>''],
'PDO::sqliteCreateAggregate' => ['bool', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'PDO::sqliteCreateCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'PDO::sqliteCreateFunction' => ['bool', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'pdo_drivers' => ['array'],
'PDOException::getCode' => ['string'],
'PDOException::getFile' => ['string'],
'PDOException::getLine' => ['int'],
'PDOException::getMessage' => ['string'],
'PDOException::getPrevious' => ['?Throwable'],
'PDOException::getTrace' => ['array<int,array<string,mixed>>'],
'PDOException::getTraceAsString' => ['string'],
'PDOStatement::__sleep' => ['string[]'],
'PDOStatement::__wakeup' => ['void'],
'PDOStatement::bindColumn' => ['bool', 'column'=>'mixed', '&rw_param'=>'mixed', 'type='=>'int', 'maxlen='=>'int', 'driverdata='=>'mixed'],
'PDOStatement::bindParam' => ['bool', 'paramno'=>'mixed', '&rw_param'=>'mixed', 'type='=>'int', 'maxlen='=>'int', 'driverdata='=>'mixed'],
'PDOStatement::bindValue' => ['bool', 'paramno'=>'mixed', 'param'=>'mixed', 'type='=>'int'],
'PDOStatement::closeCursor' => ['bool'],
'PDOStatement::columnCount' => ['int'],
'PDOStatement::debugDumpParams' => ['void'],
'PDOStatement::errorCode' => ['string'],
'PDOStatement::errorInfo' => ['array'],
'PDOStatement::execute' => ['bool', 'bound_input_params='=>'?array'],
'PDOStatement::fetch' => ['mixed', 'how='=>'int', 'orientation='=>'int', 'offset='=>'int'],
'PDOStatement::fetchAll' => ['array|false', 'how='=>'int', 'fetch_argument='=>'int|string|callable', 'ctor_args='=>'?array'],
'PDOStatement::fetchColumn' => ['string|null|false', 'column_number='=>'int'],
'PDOStatement::fetchObject' => ['mixed|false', 'class_name='=>'string', 'ctor_args='=>'?array'],
'PDOStatement::getAttribute' => ['mixed', 'attribute'=>'int'],
'PDOStatement::getColumnMeta' => ['array|false', 'column'=>'int'],
'PDOStatement::nextRowset' => ['bool'],
'PDOStatement::rowCount' => ['int'],
'PDOStatement::setAttribute' => ['bool', 'attribute'=>'int', 'value'=>'mixed'],
'PDOStatement::setFetchMode' => ['bool', 'mode'=>'int'],
'PDOStatement::setFetchMode\'1' => ['bool', 'fetch_column'=>'int', 'colno'=>'int'],
'PDOStatement::setFetchMode\'2' => ['bool', 'fetch_class'=>'int', 'classname'=>'string', 'ctorargs'=>'array'],
'PDOStatement::setFetchMode\'3' => ['bool', 'fetch_into'=>'int', 'object'=>'object'],
'pfsockopen' => ['resource|false', 'hostname'=>'string', 'port='=>'int', '&w_errno='=>'int', '&w_errstr='=>'string', 'timeout='=>'float'],
'pg_affected_rows' => ['int', 'result'=>'resource'],
'pg_cancel_query' => ['bool', 'connection'=>'resource'],
'pg_client_encoding' => ['string|false', 'connection='=>'resource'],
'pg_close' => ['bool', 'connection='=>'resource'],
'pg_connect' => ['resource|false', 'connection_string'=>'string', 'connect_type='=>'int'],
'pg_connect_poll' => ['int', 'connection'=>'resource'],
'pg_connection_busy' => ['bool', 'connection'=>'resource'],
'pg_connection_reset' => ['bool', 'connection'=>'resource'],
'pg_connection_status' => ['int', 'connection'=>'resource'],
'pg_consume_input' => ['bool', 'connection'=>'resource'],
'pg_convert' => ['array', 'db'=>'resource', 'table'=>'string', 'values'=>'array', 'options='=>'int'],
'pg_copy_from' => ['bool', 'connection'=>'resource', 'table_name'=>'string', 'rows'=>'array', 'delimiter='=>'string', 'null_as='=>'string'],
'pg_copy_to' => ['array|false', 'connection'=>'resource', 'table_name'=>'string', 'delimiter='=>'string', 'null_as='=>'string'],
'pg_dbname' => ['string|false', 'connection='=>'resource'],
'pg_delete' => ['string|bool', 'db'=>'resource', 'table'=>'string', 'ids'=>'array', 'options='=>'int'],
'pg_end_copy' => ['bool', 'connection='=>'resource'],
'pg_escape_bytea' => ['string', 'connection'=>'resource', 'data'=>'string'],
'pg_escape_bytea\'1' => ['string', 'data'=>'string'],
'pg_escape_identifier' => ['string', 'connection'=>'resource', 'data'=>'string'],
'pg_escape_identifier\'1' => ['string', 'data'=>'string'],
'pg_escape_literal' => ['string', 'connection'=>'resource', 'data'=>'string'],
'pg_escape_literal\'1' => ['string', 'data'=>'string'],
'pg_escape_string' => ['string', 'connection'=>'resource', 'data'=>'string'],
'pg_escape_string\'1' => ['string', 'data'=>'string'],
'pg_execute' => ['resource|false', 'connection'=>'resource', 'stmtname'=>'string', 'params'=>'array'],
'pg_execute\'1' => ['resource|false', 'stmtname'=>'string', 'params'=>'array'],
'pg_fetch_all' => ['array|false', 'result'=>'resource', 'result_type='=>'int'],
'pg_fetch_all_columns' => ['array|false', 'result'=>'resource', 'column_number='=>'int'],
'pg_fetch_array' => ['array|false', 'result'=>'resource', 'row='=>'?int', 'result_type='=>'int'],
'pg_fetch_assoc' => ['array|false', 'result'=>'resource', 'row='=>'?int'],
'pg_fetch_object' => ['object', 'result'=>'resource', 'row='=>'?int', 'result_type='=>'int'],
'pg_fetch_object\'1' => ['object', 'result'=>'resource', 'row='=>'?int', 'class_name='=>'string', 'ctor_params='=>'array'],
'pg_fetch_result' => ['string', 'result'=>'resource', 'field_name'=>'string|int'],
'pg_fetch_result\'1' => ['string', 'result'=>'resource', 'row'=>'?int', 'field_name'=>'string|int'],
'pg_fetch_row' => ['array', 'result'=>'resource', 'row='=>'?int', 'result_type='=>'int'],
'pg_field_is_null' => ['int', 'result'=>'resource', 'field_name_or_number'=>'string|int'],
'pg_field_is_null\'1' => ['int', 'result'=>'resource', 'row'=>'int', 'field_name_or_number'=>'string|int'],
'pg_field_name' => ['string|false', 'result'=>'resource', 'field_number'=>'int'],
'pg_field_num' => ['int', 'result'=>'resource', 'field_name'=>'string'],
'pg_field_prtlen' => ['int|false', 'result'=>'resource', 'field_name_or_number'=>''],
'pg_field_prtlen\'1' => ['int', 'result'=>'resource', 'row'=>'int', 'field_name_or_number'=>'string|int'],
'pg_field_size' => ['int', 'result'=>'resource', 'field_number'=>'int'],
'pg_field_table' => ['mixed|false', 'result'=>'resource', 'field_number'=>'int', 'oid_only='=>'bool'],
'pg_field_type' => ['string|false', 'result'=>'resource', 'field_number'=>'int'],
'pg_field_type_oid' => ['int|false', 'result'=>'resource', 'field_number'=>'int'],
'pg_flush' => ['mixed', 'connection'=>'resource'],
'pg_free_result' => ['bool', 'result'=>'resource'],
'pg_get_notify' => ['array|false', 'connection'=>'resource', 'result_type='=>'int'],
'pg_get_pid' => ['int|false', 'connection'=>'resource'],
'pg_get_result' => ['resource|false', 'connection='=>'resource'],
'pg_host' => ['string|false', 'connection='=>'resource'],
'pg_insert' => ['resource|string|false', 'db'=>'resource', 'table'=>'string', 'values'=>'array', 'options='=>'int'],
'pg_last_error' => ['string', 'connection='=>'resource', 'operation='=>'int'],
'pg_last_notice' => ['string|array|bool', 'connection'=>'resource', 'option='=>'int'],
'pg_last_oid' => ['string', 'result'=>'resource'],
'pg_lo_close' => ['bool', 'large_object'=>'resource'],
'pg_lo_create' => ['int|false', 'connection='=>'resource', 'large_object_oid='=>''],
'pg_lo_export' => ['bool', 'connection'=>'resource', 'oid'=>'int', 'filename'=>'string'],
'pg_lo_export\'1' => ['bool', 'oid'=>'int', 'pathname'=>'string'],
'pg_lo_import' => ['int', 'connection'=>'resource', 'pathname'=>'string', 'oid'=>''],
'pg_lo_import\'1' => ['int', 'pathname'=>'string', 'oid'=>''],
'pg_lo_open' => ['resource|false', 'connection'=>'resource', 'oid'=>'int', 'mode'=>'string'],
'pg_lo_read' => ['string', 'large_object'=>'resource', 'len='=>'int'],
'pg_lo_read_all' => ['int|false', 'large_object'=>'resource'],
'pg_lo_seek' => ['bool', 'large_object'=>'resource', 'offset'=>'int', 'whence='=>'int'],
'pg_lo_tell' => ['int', 'large_object'=>'resource'],
'pg_lo_truncate' => ['bool', 'large_object'=>'resource', 'size'=>'int'],
'pg_lo_unlink' => ['bool', 'connection'=>'resource', 'oid'=>'int'],
'pg_lo_write' => ['int|false', 'large_object'=>'resource', 'data'=>'string', 'len='=>'int'],
'pg_meta_data' => ['array', 'db'=>'resource', 'table'=>'string', 'extended='=>'bool'],
'pg_num_fields' => ['int', 'result'=>'resource'],
'pg_num_rows' => ['int', 'result'=>'resource'],
'pg_options' => ['string', 'connection='=>'resource'],
'pg_parameter_status' => ['string|false', 'connection'=>'resource', 'param_name'=>'string'],
'pg_parameter_status\'1' => ['string|false', 'param_name'=>'string'],
'pg_pconnect' => ['resource|false', 'connection_string'=>'string', 'host='=>'string', 'port='=>'string|int', 'options='=>'string', 'tty='=>'string', 'database='=>'string'],
'pg_ping' => ['bool', 'connection='=>'resource'],
'pg_port' => ['int', 'connection='=>'resource'],
'pg_prepare' => ['resource|false', 'connection'=>'resource', 'stmtname'=>'string', 'query'=>'string'],
'pg_prepare\'1' => ['resource|false', 'stmtname'=>'string', 'query'=>'string'],
'pg_put_line' => ['bool', 'connection'=>'resource', 'data'=>'string'],
'pg_put_line\'1' => ['bool', 'data'=>'string'],
'pg_query' => ['resource|false', 'connection'=>'resource', 'query'=>'string'],
'pg_query\'1' => ['resource|false', 'query'=>'string'],
'pg_query_params' => ['resource|false', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_query_params\'1' => ['resource|false', 'query'=>'string', 'params'=>'array'],
'pg_result_error' => ['string|false', 'result'=>'resource'],
'pg_result_error_field' => ['string|?false', 'result'=>'resource', 'fieldcode'=>'int'],
'pg_result_seek' => ['bool', 'result'=>'resource', 'offset'=>'int'],
'pg_result_status' => ['mixed', 'result'=>'resource', 'result_type='=>'int'],
'pg_select' => ['string|bool', 'db'=>'resource', 'table'=>'string', 'ids'=>'array', 'options='=>'int', 'result_type='=>'int'],
'pg_send_execute' => ['bool', 'connection'=>'resource', 'stmtname'=>'string', 'params'=>'array'],
'pg_send_prepare' => ['bool', 'connection'=>'resource', 'stmtname'=>'string', 'query'=>'string'],
'pg_send_query' => ['bool', 'connection'=>'resource', 'query'=>'string'],
'pg_send_query_params' => ['bool', 'connection'=>'resource', 'query'=>'string', 'params'=>'array'],
'pg_set_client_encoding' => ['int', 'connection'=>'resource', 'encoding'=>'string'],
'pg_set_client_encoding\'1' => ['int', 'encoding'=>'string'],
'pg_set_error_verbosity' => ['int', 'connection'=>'resource', 'verbosity'=>'int'],
'pg_set_error_verbosity\'1' => ['int', 'verbosity'=>'int'],
'pg_socket' => ['resource|false', 'connection'=>'resource'],
'pg_trace' => ['bool', 'filename'=>'string', 'mode='=>'string', 'connection='=>'resource'],
'pg_transaction_status' => ['int', 'connection'=>'resource'],
'pg_tty' => ['string', 'connection='=>'resource'],
'pg_tty\'1' => ['string'],
'pg_unescape_bytea' => ['string', 'data'=>'string'],
'pg_untrace' => ['bool', 'connection='=>'resource'],
'pg_untrace\'1' => ['bool'],
'pg_update' => ['mixed', 'db'=>'resource', 'table'=>'string', 'fields'=>'array', 'ids'=>'array', 'options='=>'int'],
'pg_version' => ['array', 'connection='=>'resource'],
'Phar::__construct' => ['void', 'fname'=>'string', 'flags='=>'int', 'alias='=>'string'],
'Phar::addEmptyDir' => ['void', 'dirname'=>'string'],
'Phar::addFile' => ['void', 'file'=>'string', 'localname='=>'string'],
'Phar::addFromString' => ['void', 'localname'=>'string', 'contents'=>'string'],
'Phar::apiVersion' => ['string'],
'Phar::buildFromDirectory' => ['array', 'base_dir'=>'string', 'regex='=>'string'],
'Phar::buildFromIterator' => ['array', 'iter'=>'Iterator', 'base_directory='=>'string'],
'Phar::canCompress' => ['bool', 'method='=>'int'],
'Phar::canWrite' => ['bool'],
'Phar::compress' => ['object', 'compression'=>'int', 'extension='=>'string'],
'Phar::compressAllFilesBZIP2' => ['bool'],
'Phar::compressAllFilesGZ' => ['bool'],
'Phar::compressFiles' => ['void', 'compression'=>'int'],
'Phar::convertToData' => ['PharData', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'Phar::convertToExecutable' => ['Phar', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'Phar::copy' => ['bool', 'oldfile'=>'string', 'newfile'=>'string'],
'Phar::count' => ['int'],
'Phar::createDefaultStub' => ['string', 'indexfile='=>'string', 'webindexfile='=>'string'],
'Phar::decompress' => ['object', 'extension='=>'string'],
'Phar::decompressFiles' => ['bool'],
'Phar::delete' => ['bool', 'entry'=>'string'],
'Phar::delMetadata' => ['bool'],
'Phar::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string|array|null', 'overwrite='=>'bool'],
'Phar::getAlias' => ['string'],
'Phar::getMetadata' => ['mixed'],
'Phar::getModified' => ['bool'],
'Phar::getPath' => ['string'],
'Phar::getSignature' => ['array'],
'Phar::getStub' => ['string'],
'Phar::getSupportedCompression' => ['array'],
'Phar::getSupportedSignatures' => ['array'],
'Phar::getVersion' => ['string'],
'Phar::hasMetadata' => ['bool'],
'Phar::interceptFileFuncs' => ['void'],
'Phar::isBuffering' => ['bool'],
'Phar::isCompressed' => ['mixed|false'],
'Phar::isFileFormat' => ['bool', 'format'=>'int'],
'Phar::isValidPharFilename' => ['bool', 'filename'=>'string', 'executable='=>'bool'],
'Phar::isWritable' => ['bool'],
'Phar::loadPhar' => ['bool', 'filename'=>'string', 'alias='=>'string'],
'Phar::mapPhar' => ['bool', 'alias='=>'string', 'dataoffset='=>'int'],
'Phar::mount' => ['void', 'pharpath'=>'string', 'externalpath'=>'string'],
'Phar::mungServer' => ['void', 'munglist'=>'array'],
'Phar::offsetExists' => ['bool', 'offset'=>'string'],
'Phar::offsetGet' => ['PharFileInfo', 'offset'=>'string'],
'Phar::offsetSet' => ['void', 'offset'=>'string', 'value'=>'string'],
'Phar::offsetUnset' => ['bool', 'offset'=>'string'],
'Phar::running' => ['string', 'retphar='=>'bool'],
'Phar::setAlias' => ['bool', 'alias'=>'string'],
'Phar::setDefaultStub' => ['bool', 'index='=>'string', 'webindex='=>'string'],
'Phar::setMetadata' => ['void', 'metadata'=>''],
'Phar::setSignatureAlgorithm' => ['void', 'sigtype'=>'int', 'privatekey='=>'string'],
'Phar::setStub' => ['bool', 'stub'=>'string', 'len='=>'int'],
'Phar::startBuffering' => ['void'],
'Phar::stopBuffering' => ['void'],
'Phar::uncompressAllFiles' => ['bool'],
'Phar::unlinkArchive' => ['bool', 'archive'=>'string'],
'Phar::webPhar' => ['', 'alias='=>'string', 'index='=>'string', 'f404='=>'string', 'mimetypes='=>'array', 'rewrites='=>'array'],
'PharData::__construct' => ['void', 'fname'=>'string', 'flags='=>'?int', 'alias='=>'?string', 'format='=>'int'],
'PharData::addEmptyDir' => ['bool', 'dirname'=>'string'],
'PharData::addFile' => ['void', 'file'=>'string', 'localname='=>'string'],
'PharData::addFromString' => ['bool', 'localname'=>'string', 'contents'=>'string'],
'PharData::buildFromDirectory' => ['array', 'base_dir'=>'string', 'regex='=>'string'],
'PharData::buildFromIterator' => ['array', 'iter'=>'Iterator', 'base_directory='=>'string'],
'PharData::compress' => ['object', 'compression'=>'int', 'extension='=>'string'],
'PharData::compressFiles' => ['bool', 'compression'=>'int'],
'PharData::convertToData' => ['PharData', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'PharData::convertToExecutable' => ['Phar', 'format='=>'int', 'compression='=>'int', 'extension='=>'string'],
'PharData::copy' => ['bool', 'oldfile'=>'string', 'newfile'=>'string'],
'PharData::decompress' => ['object', 'extension='=>'string'],
'PharData::decompressFiles' => ['bool'],
'PharData::delete' => ['bool', 'entry'=>'string'],
'PharData::delMetadata' => ['bool'],
'PharData::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string|array|null', 'overwrite='=>'bool'],
'PharData::isWritable' => ['bool'],
'PharData::offsetSet' => ['void', 'offset'=>'string', 'value'=>'string'],
'PharData::offsetUnset' => ['bool', 'offset'=>'string'],
'PharData::setAlias' => ['bool', 'alias'=>'string'],
'PharData::setDefaultStub' => ['bool', 'index='=>'string', 'webindex='=>'string'],
'phardata::setMetadata' => ['void', 'metadata'=>'mixed'],
'phardata::setSignatureAlgorithm' => ['void', 'sigtype'=>'int'],
'PharData::setStub' => ['bool', 'stub'=>'string', 'len='=>'int'],
'PharFileInfo::__construct' => ['void', 'entry'=>'string'],
'PharFileInfo::chmod' => ['void', 'permissions'=>'int'],
'PharFileInfo::compress' => ['bool', 'compression'=>'int'],
'PharFileInfo::decompress' => ['bool'],
'PharFileInfo::delMetadata' => ['bool'],
'PharFileInfo::getCompressedSize' => ['int'],
'PharFileInfo::getContent' => ['string'],
'PharFileInfo::getCRC32' => ['int'],
'PharFileInfo::getMetadata' => ['mixed'],
'PharFileInfo::getPharFlags' => ['int'],
'PharFileInfo::hasMetadata' => ['bool'],
'PharFileInfo::isCompressed' => ['bool', 'compression_type='=>'int'],
'PharFileInfo::isCompressedBZIP2' => ['bool'],
'PharFileInfo::isCompressedGZ' => ['bool'],
'PharFileInfo::isCRCChecked' => ['bool'],
'PharFileInfo::setCompressedBZIP2' => ['bool'],
'PharFileInfo::setCompressedGZ' => ['bool'],
'PharFileInfo::setMetadata' => ['void', 'metadata'=>'mixed'],
'PharFileInfo::setUncompressed' => ['bool'],
'phdfs::__construct' => ['void', 'ip'=>'string', 'port'=>'string'],
'phdfs::__destruct' => ['void'],
'phdfs::connect' => ['bool'],
'phdfs::copy' => ['bool', 'source_file'=>'string', 'destination_file'=>'string'],
'phdfs::create_directory' => ['bool', 'path'=>'string'],
'phdfs::delete' => ['bool', 'path'=>'string'],
'phdfs::disconnect' => ['bool'],
'phdfs::exists' => ['bool', 'path'=>'string'],
'phdfs::file_info' => ['array', 'path'=>'string'],
'phdfs::list_directory' => ['array', 'path'=>'string'],
'phdfs::read' => ['string', 'path'=>'string', 'length='=>'string'],
'phdfs::rename' => ['bool', 'old_path'=>'string', 'new_path'=>'string'],
'phdfs::tell' => ['int', 'path'=>'string'],
'phdfs::write' => ['bool', 'path'=>'string', 'buffer'=>'string', 'mode='=>'string'],
'php_check_syntax' => ['bool', 'filename'=>'string', 'error_message='=>'string'],
'php_ini_loaded_file' => ['string|false'],
'php_ini_scanned_files' => ['string|false'],
'php_logo_guid' => ['string'],
'php_sapi_name' => ['string'],
'php_strip_whitespace' => ['string', 'file_name'=>'string'],
'php_uname' => ['string', 'mode='=>'string'],
'php_user_filter::filter' => ['int', 'in'=>'resource', 'out'=>'resource', '&rw_consumed'=>'int', 'closing'=>'bool'],
'php_user_filter::onClose' => ['void'],
'php_user_filter::onCreate' => ['bool'],
'phpcredits' => ['bool', 'flag='=>'int'],
'phpdbg_break_file' => ['void', 'file'=>'string', 'line'=>'int'],
'phpdbg_break_function' => ['void', 'function'=>'string'],
'phpdbg_break_method' => ['void', 'class'=>'string', 'method'=>'string'],
'phpdbg_break_next' => ['void'],
'phpdbg_clear' => ['void'],
'phpdbg_color' => ['void', 'element'=>'int', 'color'=>'string'],
'phpdbg_end_oplog' => ['array', 'options='=>'array'],
'phpdbg_exec' => ['mixed', 'context='=>'string'],
'phpdbg_get_executable' => ['array', 'options='=>'array'],
'phpdbg_prompt' => ['void', 'prompt'=>'string'],
'phpdbg_start_oplog' => ['void'],
'phpinfo' => ['bool', 'what='=>'int'],
'phpversion' => ['string|false', 'extension='=>'string'],
'pht\AtomicInteger::__construct' => ['void', 'value='=>'int'],
'pht\AtomicInteger::dec' => ['void'],
'pht\AtomicInteger::get' => ['int'],
'pht\AtomicInteger::inc' => ['void'],
'pht\AtomicInteger::lock' => ['void'],
'pht\AtomicInteger::set' => ['void', 'value'=>'int'],
'pht\AtomicInteger::unlock' => ['void'],
'pht\HashTable::lock' => ['void'],
'pht\HashTable::size' => ['int'],
'pht\HashTable::unlock' => ['void'],
'pht\Queue::front' => ['mixed'],
'pht\Queue::lock' => ['void'],
'pht\Queue::pop' => ['mixed'],
'pht\Queue::push' => ['void', 'value'=>'mixed'],
'pht\Queue::size' => ['int'],
'pht\Queue::unlock' => ['void'],
'pht\Runnable::run' => ['void'],
'pht\thread::addClassTask' => ['void', 'className'=>'string', '...ctorArgs='=>'mixed'],
'pht\thread::addFileTask' => ['void', 'fileName'=>'string', '...globals='=>'mixed'],
'pht\thread::addFunctionTask' => ['void', 'func'=>'callable', '...funcArgs='=>'mixed'],
'pht\thread::join' => ['void'],
'pht\thread::start' => ['void'],
'pht\thread::taskCount' => ['int'],
'pht\threaded::lock' => ['void'],
'pht\threaded::unlock' => ['void'],
'pht\Vector::__construct' => ['void', 'size='=>'int', 'value='=>'mixed'],
'pht\Vector::deleteAt' => ['void', 'offset'=>'int'],
'pht\Vector::insertAt' => ['void', 'value'=>'mixed', 'offset'=>'int'],
'pht\Vector::lock' => ['void'],
'pht\Vector::pop' => ['mixed'],
'pht\Vector::push' => ['void', 'value'=>'mixed'],
'pht\Vector::resize' => ['void', 'size'=>'int', 'value='=>'mixed'],
'pht\Vector::shift' => ['mixed'],
'pht\Vector::size' => ['int'],
'pht\Vector::unlock' => ['void'],
'pht\Vector::unshift' => ['void', 'value'=>'mixed'],
'pht\Vector::updateAt' => ['void', 'value'=>'mixed', 'offset'=>'int'],
'pi' => ['float'],
'png2wbmp' => ['bool', 'pngname'=>'string', 'wbmpname'=>'string', 'dest_height'=>'int', 'dest_width'=>'int', 'threshold'=>'int'],
'pointObj::__construct' => ['void'],
'pointObj::distanceToLine' => ['float', 'p1'=>'pointObj', 'p2'=>'pointObj'],
'pointObj::distanceToPoint' => ['float', 'poPoint'=>'pointObj'],
'pointObj::distanceToShape' => ['float', 'shape'=>'shapeObj'],
'pointObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj', 'class_index'=>'int', 'text'=>'string'],
'pointObj::ms_newPointObj' => ['pointObj'],
'pointObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'pointObj::setXY' => ['int', 'x'=>'float', 'y'=>'float', 'm'=>'float'],
'pointObj::setXYZ' => ['int', 'x'=>'float', 'y'=>'float', 'z'=>'float', 'm'=>'float'],
'Pool::__construct' => ['void', 'size'=>'int', 'class'=>'string', 'ctor='=>'array'],
'Pool::collect' => ['int', 'collector='=>'Callable'],
'Pool::resize' => ['void', 'size'=>'int'],
'Pool::shutdown' => ['void'],
'Pool::submit' => ['int', 'task'=>'Threaded'],
'Pool::submitTo' => ['int', 'worker'=>'int', 'task'=>'Threaded'],
'popen' => ['resource|false', 'command'=>'string', 'mode'=>'string'],
'pos' => ['mixed', 'array_arg'=>'array'],
'posix_access' => ['bool', 'file'=>'string', 'mode='=>'int'],
'posix_ctermid' => ['string|false'],
'posix_errno' => ['int'],
'posix_get_last_error' => ['int'],
'posix_getcwd' => ['string'],
'posix_getegid' => ['int'],
'posix_geteuid' => ['int'],
'posix_getgid' => ['int'],
'posix_getgrgid' => ['array', 'gid'=>'int'],
'posix_getgrnam' => ['array|false', 'groupname'=>'string'],
'posix_getgroups' => ['array'],
'posix_getlogin' => ['string'],
'posix_getpgid' => ['int|false', 'pid'=>'int'],
'posix_getpgrp' => ['int'],
'posix_getpid' => ['int'],
'posix_getppid' => ['int'],
'posix_getpwnam' => ['array|false', 'groupname'=>'string'],
'posix_getpwuid' => ['array', 'uid'=>'int'],
'posix_getrlimit' => ['array'],
'posix_getsid' => ['int', 'pid'=>'int'],
'posix_getuid' => ['int'],
'posix_initgroups' => ['bool', 'name'=>'string', 'base_group_id'=>'int'],
'posix_isatty' => ['bool', 'fd'=>'resource|int'],
'posix_kill' => ['bool', 'pid'=>'int', 'sig'=>'int'],
'posix_mkfifo' => ['bool', 'pathname'=>'string', 'mode'=>'int'],
'posix_mknod' => ['bool', 'pathname'=>'string', 'mode'=>'int', 'major='=>'int', 'minor='=>'int'],
'posix_setegid' => ['bool', 'uid'=>'int'],
'posix_seteuid' => ['bool', 'uid'=>'int'],
'posix_setgid' => ['bool', 'uid'=>'int'],
'posix_setpgid' => ['bool', 'pid'=>'int', 'pgid'=>'int'],
'posix_setrlimit' => ['bool', 'resource'=>'int', 'softlimit'=>'int', 'hardlimit'=>'int'],
'posix_setsid' => ['int'],
'posix_setuid' => ['bool', 'uid'=>'int'],
'posix_strerror' => ['string', 'errno'=>'int'],
'posix_times' => ['array'],
'posix_ttyname' => ['string|false', 'fd'=>'resource|int'],
'posix_uname' => ['array'],
'Postal\Expand::expand_address' => ['string[]', 'address'=>'string', 'options='=>'array<string, mixed>'],
'Postal\Parser::parse_address' => ['array<string,string>', 'address'=>'string', 'options='=>'array<string, string>'],
'pow' => ['float|int', 'base'=>'int|float', 'exponent'=>'int|float'],
'preg_filter' => ['null|string|string[]', 'regex'=>'mixed', 'replace'=>'mixed', 'subject'=>'mixed', 'limit='=>'int', '&w_count='=>'int'],
'preg_grep' => ['array', 'regex'=>'string', 'input'=>'array', 'flags='=>'int'],
'preg_last_error' => ['int'],
'preg_match' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_subpatterns='=>'string[]', 'flags='=>'0|', 'offset='=>'int'],
'preg_match\'1' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_subpatterns='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_match_all' => ['int|false', 'pattern'=>'string', 'subject'=>'string', '&w_subpatterns='=>'array', 'flags='=>'int', 'offset='=>'int'],
'preg_quote' => ['string', 'str'=>'string', 'delim_char='=>'string'],
'preg_replace' => ['string|string[]|null', 'regex'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback' => ['string|null', 'regex'=>'string|array', 'callback'=>'callable(array<int, string>):string', 'subject'=>'string', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback\'1' => ['string[]|null', 'regex'=>'string|array', 'callback'=>'callable(array<int, string>):string', 'subject'=>'string[]', 'limit='=>'int', '&w_count='=>'int'],
'preg_replace_callback_array' => ['string|string[]|null', 'pattern'=>'array<string,callable(array):string>', 'subject'=>'string|array', 'limit='=>'int', '&w_count='=>'int'],
'preg_split' => ['array<int,string>|false', 'pattern'=>'string', 'subject'=>'string', 'limit'=>'?int', 'flags='=>'null'],
'preg_split\'1' => ['array<int,string>|array[]|false', 'pattern'=>'string', 'subject'=>'string', 'limit='=>'?int', 'flags='=>'int'],
'prev' => ['mixed', '&rw_array_arg'=>'array'],
'print' => ['int', 'arg'=>'string'],
'print_r' => ['string', 'var'=>'mixed'],
'print_r\'1' => ['true', 'var'=>'mixed', 'return='=>'bool'],
'printf' => ['int', 'format'=>'string', '...args='=>'string|int|float'],
'proc_close' => ['int', 'process'=>'resource'],
'proc_get_status' => ['array|false', 'process'=>'resource'],
'proc_nice' => ['bool', 'priority'=>'int'],
'proc_open' => ['resource|false', 'command'=>'string', 'descriptorspec'=>'array', '&w_pipes'=>'resource[]', 'cwd='=>'?string', 'env='=>'?array', 'other_options='=>'array'],
'proc_terminate' => ['bool', 'process'=>'resource', 'signal='=>'int'],
'projectionObj::__construct' => ['void', 'projectionString'=>'string'],
'projectionObj::getUnits' => ['int'],
'projectionObj::ms_newProjectionObj' => ['projectionObj', 'projectionString'=>'string'],
'property_exists' => ['bool', 'object_or_class'=>'object|string', 'property_name'=>'string'],
'ps_add_bookmark' => ['int', 'psdoc'=>'resource', 'text'=>'string', 'parent='=>'int', 'open='=>'int'],
'ps_add_launchlink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string'],
'ps_add_locallink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'page'=>'int', 'dest'=>'string'],
'ps_add_note' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'contents'=>'string', 'title'=>'string', 'icon'=>'string', 'open'=>'int'],
'ps_add_pdflink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'filename'=>'string', 'page'=>'int', 'dest'=>'string'],
'ps_add_weblink' => ['bool', 'psdoc'=>'resource', 'llx'=>'float', 'lly'=>'float', 'urx'=>'float', 'ury'=>'float', 'url'=>'string'],
'ps_arc' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'ps_arcn' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float', 'alpha'=>'float', 'beta'=>'float'],
'ps_begin_page' => ['bool', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'ps_begin_pattern' => ['int', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float', 'xstep'=>'float', 'ystep'=>'float', 'painttype'=>'int'],
'ps_begin_template' => ['int', 'psdoc'=>'resource', 'width'=>'float', 'height'=>'float'],
'ps_circle' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'radius'=>'float'],
'ps_clip' => ['bool', 'psdoc'=>'resource'],
'ps_close' => ['bool', 'psdoc'=>'resource'],
'ps_close_image' => ['void', 'psdoc'=>'resource', 'imageid'=>'int'],
'ps_closepath' => ['bool', 'psdoc'=>'resource'],
'ps_closepath_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_continue_text' => ['bool', 'psdoc'=>'resource', 'text'=>'string'],
'ps_curveto' => ['bool', 'psdoc'=>'resource', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'ps_delete' => ['bool', 'psdoc'=>'resource'],
'ps_end_page' => ['bool', 'psdoc'=>'resource'],
'ps_end_pattern' => ['bool', 'psdoc'=>'resource'],
'ps_end_template' => ['bool', 'psdoc'=>'resource'],
'ps_fill' => ['bool', 'psdoc'=>'resource'],
'ps_fill_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_findfont' => ['int', 'psdoc'=>'resource', 'fontname'=>'string', 'encoding'=>'string', 'embed='=>'bool'],
'ps_get_buffer' => ['string', 'psdoc'=>'resource'],
'ps_get_parameter' => ['string', 'psdoc'=>'resource', 'name'=>'string', 'modifier='=>'float'],
'ps_get_value' => ['float', 'psdoc'=>'resource', 'name'=>'string', 'modifier='=>'float'],
'ps_hyphenate' => ['array', 'psdoc'=>'resource', 'text'=>'string'],
'ps_include_file' => ['bool', 'psdoc'=>'resource', 'file'=>'string'],
'ps_lineto' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_makespotcolor' => ['int', 'psdoc'=>'resource', 'name'=>'string', 'reserved='=>'int'],
'ps_moveto' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_new' => ['resource'],
'ps_open_file' => ['bool', 'psdoc'=>'resource', 'filename='=>'string'],
'ps_open_image' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'source'=>'string', 'data'=>'string', 'length'=>'int', 'width'=>'int', 'height'=>'int', 'components'=>'int', 'bpc'=>'int', 'params'=>'string'],
'ps_open_image_file' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'filename'=>'string', 'stringparam='=>'string', 'intparam='=>'int'],
'ps_open_memory_image' => ['int', 'psdoc'=>'resource', 'gd'=>'int'],
'ps_place_image' => ['bool', 'psdoc'=>'resource', 'imageid'=>'int', 'x'=>'float', 'y'=>'float', 'scale'=>'float'],
'ps_rect' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float', 'width'=>'float', 'height'=>'float'],
'ps_restore' => ['bool', 'psdoc'=>'resource'],
'ps_rotate' => ['bool', 'psdoc'=>'resource', 'rot'=>'float'],
'ps_save' => ['bool', 'psdoc'=>'resource'],
'ps_scale' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_set_border_color' => ['bool', 'psdoc'=>'resource', 'red'=>'float', 'green'=>'float', 'blue'=>'float'],
'ps_set_border_dash' => ['bool', 'psdoc'=>'resource', 'black'=>'float', 'white'=>'float'],
'ps_set_border_style' => ['bool', 'psdoc'=>'resource', 'style'=>'string', 'width'=>'float'],
'ps_set_info' => ['bool', 'p'=>'resource', 'key'=>'string', 'val'=>'string'],
'ps_set_parameter' => ['bool', 'psdoc'=>'resource', 'name'=>'string', 'value'=>'string'],
'ps_set_text_pos' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'ps_set_value' => ['bool', 'psdoc'=>'resource', 'name'=>'string', 'value'=>'float'],
'ps_setcolor' => ['bool', 'psdoc'=>'resource', 'type'=>'string', 'colorspace'=>'string', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float'],
'ps_setdash' => ['bool', 'psdoc'=>'resource', 'on'=>'float', 'off'=>'float'],
'ps_setflat' => ['bool', 'psdoc'=>'resource', 'value'=>'float'],
'ps_setfont' => ['bool', 'psdoc'=>'resource', 'fontid'=>'int', 'size'=>'float'],
'ps_setgray' => ['bool', 'psdoc'=>'resource', 'gray'=>'float'],
'ps_setlinecap' => ['bool', 'psdoc'=>'resource', 'type'=>'int'],
'ps_setlinejoin' => ['bool', 'psdoc'=>'resource', 'type'=>'int'],
'ps_setlinewidth' => ['bool', 'psdoc'=>'resource', 'width'=>'float'],
'ps_setmiterlimit' => ['bool', 'psdoc'=>'resource', 'value'=>'float'],
'ps_setoverprintmode' => ['bool', 'psdoc'=>'resource', 'mode'=>'int'],
'ps_setpolydash' => ['bool', 'psdoc'=>'resource', 'arr'=>'float'],
'ps_shading' => ['int', 'psdoc'=>'resource', 'type'=>'string', 'x0'=>'float', 'y0'=>'float', 'x1'=>'float', 'y1'=>'float', 'c1'=>'float', 'c2'=>'float', 'c3'=>'float', 'c4'=>'float', 'optlist'=>'string'],
'ps_shading_pattern' => ['int', 'psdoc'=>'resource', 'shadingid'=>'int', 'optlist'=>'string'],
'ps_shfill' => ['bool', 'psdoc'=>'resource', 'shadingid'=>'int'],
'ps_show' => ['bool', 'psdoc'=>'resource', 'text'=>'string'],
'ps_show2' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'len'=>'int'],
'ps_show_boxed' => ['int', 'psdoc'=>'resource', 'text'=>'string', 'left'=>'float', 'bottom'=>'float', 'width'=>'float', 'height'=>'float', 'hmode'=>'string', 'feature='=>'string'],
'ps_show_xy' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'x'=>'float', 'y'=>'float'],
'ps_show_xy2' => ['bool', 'psdoc'=>'resource', 'text'=>'string', 'len'=>'int', 'xcoor'=>'float', 'ycoor'=>'float'],
'ps_string_geometry' => ['array', 'psdoc'=>'resource', 'text'=>'string', 'fontid='=>'int', 'size='=>'float'],
'ps_stringwidth' => ['float', 'psdoc'=>'resource', 'text'=>'string', 'fontid='=>'int', 'size='=>'float'],
'ps_stroke' => ['bool', 'psdoc'=>'resource'],
'ps_symbol' => ['bool', 'psdoc'=>'resource', 'ord'=>'int'],
'ps_symbol_name' => ['string', 'psdoc'=>'resource', 'ord'=>'int', 'fontid='=>'int'],
'ps_symbol_width' => ['float', 'psdoc'=>'resource', 'ord'=>'int', 'fontid='=>'int', 'size='=>'float'],
'ps_translate' => ['bool', 'psdoc'=>'resource', 'x'=>'float', 'y'=>'float'],
'pspell_add_to_personal' => ['bool', 'pspell'=>'int', 'word'=>'string'],
'pspell_add_to_session' => ['bool', 'pspell'=>'int', 'word'=>'string'],
'pspell_check' => ['bool', 'pspell'=>'int', 'word'=>'string'],
'pspell_clear_session' => ['bool', 'pspell'=>'int'],
'pspell_config_create' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string'],
'pspell_config_data_dir' => ['bool', 'conf'=>'int', 'directory'=>'string'],
'pspell_config_dict_dir' => ['bool', 'conf'=>'int', 'directory'=>'string'],
'pspell_config_ignore' => ['bool', 'conf'=>'int', 'ignore'=>'int'],
'pspell_config_mode' => ['bool', 'conf'=>'int', 'mode'=>'int'],
'pspell_config_personal' => ['bool', 'conf'=>'int', 'personal'=>'string'],
'pspell_config_repl' => ['bool', 'conf'=>'int', 'repl'=>'string'],
'pspell_config_runtogether' => ['bool', 'conf'=>'int', 'runtogether'=>'bool'],
'pspell_config_save_repl' => ['bool', 'conf'=>'int', 'save'=>'bool'],
'pspell_new' => ['int|false', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_new_config' => ['int|false', 'config'=>'int'],
'pspell_new_personal' => ['int|false', 'personal'=>'string', 'language'=>'string', 'spelling='=>'string', 'jargon='=>'string', 'encoding='=>'string', 'mode='=>'int'],
'pspell_save_wordlist' => ['bool', 'pspell'=>'int'],
'pspell_store_replacement' => ['bool', 'pspell'=>'int', 'misspell'=>'string', 'correct'=>'string'],
'pspell_suggest' => ['array', 'pspell'=>'int', 'word'=>'string'],
'putenv' => ['bool', 'setting'=>'string'],
'px_close' => ['bool', 'pxdoc'=>'resource'],
'px_create_fp' => ['bool', 'pxdoc'=>'resource', 'file'=>'resource', 'fielddesc'=>'array'],
'px_date2string' => ['string', 'pxdoc'=>'resource', 'value'=>'int', 'format'=>'string'],
'px_delete' => ['bool', 'pxdoc'=>'resource'],
'px_delete_record' => ['bool', 'pxdoc'=>'resource', 'num'=>'int'],
'px_get_field' => ['array', 'pxdoc'=>'resource', 'fieldno'=>'int'],
'px_get_info' => ['array', 'pxdoc'=>'resource'],
'px_get_parameter' => ['string', 'pxdoc'=>'resource', 'name'=>'string'],
'px_get_record' => ['array', 'pxdoc'=>'resource', 'num'=>'int', 'mode='=>'int'],
'px_get_schema' => ['array', 'pxdoc'=>'resource', 'mode='=>'int'],
'px_get_value' => ['float', 'pxdoc'=>'resource', 'name'=>'string'],
'px_insert_record' => ['int', 'pxdoc'=>'resource', 'data'=>'array'],
'px_new' => ['resource'],
'px_numfields' => ['int', 'pxdoc'=>'resource'],
'px_numrecords' => ['int', 'pxdoc'=>'resource'],
'px_open_fp' => ['bool', 'pxdoc'=>'resource', 'file'=>'resource'],
'px_put_record' => ['bool', 'pxdoc'=>'resource', 'record'=>'array', 'recpos='=>'int'],
'px_retrieve_record' => ['array', 'pxdoc'=>'resource', 'num'=>'int', 'mode='=>'int'],
'px_set_blob_file' => ['bool', 'pxdoc'=>'resource', 'filename'=>'string'],
'px_set_parameter' => ['bool', 'pxdoc'=>'resource', 'name'=>'string', 'value'=>'string'],
'px_set_tablename' => ['void', 'pxdoc'=>'resource', 'name'=>'string'],
'px_set_targetencoding' => ['bool', 'pxdoc'=>'resource', 'encoding'=>'string'],
'px_set_value' => ['bool', 'pxdoc'=>'resource', 'name'=>'string', 'value'=>'float'],
'px_timestamp2string' => ['string', 'pxdoc'=>'resource', 'value'=>'float', 'format'=>'string'],
'px_update_record' => ['bool', 'pxdoc'=>'resource', 'data'=>'array', 'num'=>'int'],
'qdom_error' => ['string'],
'qdom_tree' => ['QDomDocument', 'doc'=>'string'],
'querymapObj::convertToString' => ['string'],
'querymapObj::free' => ['void'],
'querymapObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'querymapObj::updateFromString' => ['int', 'snippet'=>'string'],
'QuickHashIntHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntHash::add' => ['bool', 'key'=>'int', 'value='=>'int'],
'QuickHashIntHash::delete' => ['bool', 'key'=>'int'],
'QuickHashIntHash::exists' => ['bool', 'key'=>'int'],
'QuickHashIntHash::get' => ['int', 'key'=>'int'],
'QuickHashIntHash::getSize' => ['int'],
'QuickHashIntHash::loadFromFile' => ['QuickHashIntHash', 'filename'=>'string', 'options='=>'int'],
'QuickHashIntHash::loadFromString' => ['QuickHashIntHash', 'contents'=>'string', 'options='=>'int'],
'QuickHashIntHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntHash::saveToString' => ['string'],
'QuickHashIntHash::set' => ['bool', 'key'=>'int', 'value'=>'int'],
'QuickHashIntHash::update' => ['bool', 'key'=>'int', 'value'=>'int'],
'QuickHashIntSet::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntSet::add' => ['bool', 'key'=>'int'],
'QuickHashIntSet::delete' => ['bool', 'key'=>'int'],
'QuickHashIntSet::exists' => ['bool', 'key'=>'int'],
'QuickHashIntSet::getSize' => ['int'],
'QuickHashIntSet::loadFromFile' => ['QuickHashIntSet', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntSet::loadFromString' => ['QuickHashIntSet', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntSet::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntSet::saveToString' => ['string'],
'QuickHashIntStringHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashIntStringHash::add' => ['bool', 'key'=>'int', 'value'=>'string'],
'QuickHashIntStringHash::delete' => ['bool', 'key'=>'int'],
'QuickHashIntStringHash::exists' => ['bool', 'key'=>'int'],
'QuickHashIntStringHash::get' => ['mixed', 'key'=>'int'],
'QuickHashIntStringHash::getSize' => ['int'],
'QuickHashIntStringHash::loadFromFile' => ['QuickHashIntStringHash', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntStringHash::loadFromString' => ['QuickHashIntStringHash', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashIntStringHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashIntStringHash::saveToString' => ['string'],
'QuickHashIntStringHash::set' => ['int', 'key'=>'int', 'value'=>'string'],
'QuickHashIntStringHash::update' => ['bool', 'key'=>'int', 'value'=>'string'],
'QuickHashStringIntHash::__construct' => ['void', 'size'=>'int', 'options='=>'int'],
'QuickHashStringIntHash::add' => ['bool', 'key'=>'string', 'value'=>'int'],
'QuickHashStringIntHash::delete' => ['bool', 'key'=>'string'],
'QuickHashStringIntHash::exists' => ['bool', 'key'=>'string'],
'QuickHashStringIntHash::get' => ['mixed', 'key'=>'string'],
'QuickHashStringIntHash::getSize' => ['int'],
'QuickHashStringIntHash::loadFromFile' => ['QuickHashStringIntHash', 'filename'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashStringIntHash::loadFromString' => ['QuickHashStringIntHash', 'contents'=>'string', 'size='=>'int', 'options='=>'int'],
'QuickHashStringIntHash::saveToFile' => ['void', 'filename'=>'string'],
'QuickHashStringIntHash::saveToString' => ['string'],
'QuickHashStringIntHash::set' => ['int', 'key'=>'string', 'value'=>'int'],
'QuickHashStringIntHash::update' => ['bool', 'key'=>'string', 'value'=>'int'],
'quoted_printable_decode' => ['string', 'str'=>'string'],
'quoted_printable_encode' => ['string', 'str'=>'string'],
'quotemeta' => ['string', 'str'=>'string'],
'rad2deg' => ['float', 'number'=>'float'],
'radius_acct_open' => ['resource|false'],
'radius_add_server' => ['bool', 'radius_handle'=>'resource', 'hostname'=>'string', 'port'=>'int', 'secret'=>'string', 'timeout'=>'int', 'max_tries'=>'int'],
'radius_auth_open' => ['resource|false'],
'radius_close' => ['bool', 'radius_handle'=>'resource'],
'radius_config' => ['bool', 'radius_handle'=>'resource', 'file'=>'string'],
'radius_create_request' => ['bool', 'radius_handle'=>'resource', 'type'=>'int'],
'radius_cvt_addr' => ['string', 'data'=>'string'],
'radius_cvt_int' => ['int', 'data'=>'string'],
'radius_cvt_string' => ['string', 'data'=>'string'],
'radius_demangle' => ['string', 'radius_handle'=>'resource', 'mangled'=>'string'],
'radius_demangle_mppe_key' => ['string', 'radius_handle'=>'resource', 'mangled'=>'string'],
'radius_get_attr' => ['mixed', 'radius_handle'=>'resource'],
'radius_get_tagged_attr_data' => ['string', 'data'=>'string'],
'radius_get_tagged_attr_tag' => ['int', 'data'=>'string'],
'radius_get_vendor_attr' => ['array', 'data'=>'string'],
'radius_put_addr' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'addr'=>'string'],
'radius_put_attr' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'string'],
'radius_put_int' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'int'],
'radius_put_string' => ['bool', 'radius_handle'=>'resource', 'type'=>'int', 'value'=>'string'],
'radius_put_vendor_addr' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'addr'=>'string'],
'radius_put_vendor_attr' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'string'],
'radius_put_vendor_int' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'int'],
'radius_put_vendor_string' => ['bool', 'radius_handle'=>'resource', 'vendor'=>'int', 'type'=>'int', 'value'=>'string'],
'radius_request_authenticator' => ['string', 'radius_handle'=>'resource'],
'radius_salt_encrypt_attr' => ['string', 'radius_handle'=>'resource', 'data'=>'string'],
'radius_send_request' => ['int', 'radius_handle'=>'resource'],
'radius_server_secret' => ['string', 'radius_handle'=>'resource'],
'radius_strerror' => ['string', 'radius_handle'=>'resource'],
'rand' => ['int', 'min'=>'int', 'max'=>'int'],
'rand\'1' => ['int'],
'random_bytes' => ['string', 'length'=>'int'],
'random_int' => ['int', 'min'=>'int', 'max'=>'int'],
'range' => ['array', 'low'=>'mixed', 'high'=>'mixed', 'step='=>'int|float'],
'RangeException::__clone' => ['void'],
'RangeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?RangeException'],
'RangeException::__toString' => ['string'],
'RangeException::getCode' => ['int'],
'RangeException::getFile' => ['string'],
'RangeException::getLine' => ['int'],
'RangeException::getMessage' => ['string'],
'RangeException::getPrevious' => ['Throwable|RangeException|null'],
'RangeException::getTrace' => ['array'],
'RangeException::getTraceAsString' => ['string'],
'rar_allow_broken_set' => ['bool', 'rarfile'=>'RarArchive', 'allow_broken'=>'bool'],
'rar_broken_is' => ['bool', 'rarfile'=>'rararchive'],
'rar_close' => ['bool', 'rarfile'=>'rararchive'],
'rar_comment_get' => ['string', 'rarfile'=>'rararchive'],
'rar_entry_get' => ['RarEntry', 'rarfile'=>'RarArchive', 'entryname'=>'string'],
'rar_list' => ['RarArchive', 'rarfile'=>'rararchive'],
'rar_open' => ['RarArchive', 'filename'=>'string', 'password='=>'string', 'volume_callback='=>'callable'],
'rar_solid_is' => ['bool', 'rarfile'=>'rararchive'],
'rar_wrapper_cache_stats' => ['string'],
'RarArchive::__toString' => ['string'],
'RarArchive::close' => ['bool'],
'RarArchive::getComment' => ['string|null'],
'RarArchive::getEntries' => ['RarEntry[]|false'],
'RarArchive::getEntry' => ['RarEntry|false', 'entryname'=>'string'],
'RarArchive::isBroken' => ['bool'],
'RarArchive::isSolid' => ['bool'],
'RarArchive::open' => ['RarArchive|false', 'filename'=>'string', 'password='=>'string', 'volume_callback='=>'callable'],
'RarArchive::setAllowBroken' => ['bool', 'allow_broken'=>'bool'],
'RarEntry::__toString' => ['string'],
'RarEntry::extract' => ['bool', 'dir'=>'string', 'filepath='=>'string', 'password='=>'string', 'extended_data='=>'bool'],
'RarEntry::getAttr' => ['int|false'],
'RarEntry::getCrc' => ['string|false'],
'RarEntry::getFileTime' => ['string|false'],
'RarEntry::getHostOs' => ['int|false'],
'RarEntry::getMethod' => ['int|false'],
'RarEntry::getName' => ['string|false'],
'RarEntry::getPackedSize' => ['int|false'],
'RarEntry::getStream' => ['resource|false', 'password='=>'string'],
'RarEntry::getUnpackedSize' => ['int|false'],
'RarEntry::getVersion' => ['int|false'],
'RarEntry::isDirectory' => ['bool'],
'RarEntry::isEncrypted' => ['bool'],
'RarException::getCode' => ['int'],
'RarException::getFile' => ['string'],
'RarException::getLine' => ['int'],
'RarException::getMessage' => ['string'],
'RarException::getPrevious' => ['Exception|Throwable'],
'RarException::getTrace' => ['array'],
'RarException::getTraceAsString' => ['string'],
'RarException::isUsingExceptions' => ['bool'],
'RarException::setUsingExceptions' => ['RarEntry', 'using_exceptions'=>'bool'],
'rawurldecode' => ['string', 'str'=>'string'],
'rawurlencode' => ['string', 'str'=>'string'],
'rd_kafka_err2str' => ['string', 'err'=>'int'],
'rd_kafka_errno' => ['int'],
'rd_kafka_errno2err' => ['int', 'errnox'=>'int'],
'rd_kafka_offset_tail' => ['int', 'cnt'=>'int'],
'RdKafka::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka::getOutQLen' => ['int'],
'RdKafka::newQueue' => ['RdKafka\Queue'],
'RdKafka::newTopic' => ['RdKafka\Topic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\Conf::dump' => ['array'],
'RdKafka\Conf::set' => ['void', 'name'=>'string', 'value'=>'string'],
'RdKafka\Conf::setDefaultTopicConf' => ['void', 'topic_conf'=>'RdKafka\TopicConf'],
'RdKafka\Conf::setDrMsgCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setErrorCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setRebalanceCb' => ['void', 'callback'=>'callable'],
'RdKafka\Conf::setStatsCb' => ['void', 'callback'=>'callable'],
'RdKafka\Consumer::__construct' => ['void', 'conf='=>'?RdKafka\Conf'],
'RdKafka\Consumer::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka\Consumer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka\Consumer::getOutQLen' => ['int'],
'RdKafka\Consumer::newQueue' => ['RdKafka\Queue'],
'RdKafka\Consumer::newTopic' => ['RdKafka\ConsumerTopic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka\Consumer::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka\Consumer::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\ConsumerTopic::__construct' => ['void'],
'RdKafka\ConsumerTopic::consume' => ['RdKafka\Message', 'partition'=>'int', 'timeout_ms'=>'int'],
'RdKafka\ConsumerTopic::consumeQueueStart' => ['void', 'partition'=>'int', 'offset'=>'int', 'queue'=>'RdKafka\Queue'],
'RdKafka\ConsumerTopic::consumeStart' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\ConsumerTopic::consumeStop' => ['void', 'partition'=>'int'],
'RdKafka\ConsumerTopic::getName' => ['string'],
'RdKafka\ConsumerTopic::offsetStore' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\KafkaConsumer::__construct' => ['void', 'conf'=>'RdKafka\Conf'],
'RdKafka\KafkaConsumer::assign' => ['void', 'topic_partitions='=>'RdKafka\TopicPartition[]'],
'RdKafka\KafkaConsumer::commit' => ['void', 'message_or_offsets='=>'RdKafka\Message|RdKafka\TopicPartition[]|null'],
'RdKafka\KafkaConsumer::commitAsync' => ['void', 'message_or_offsets='=>'string'],
'RdKafka\KafkaConsumer::consume' => ['RdKafka\Message', 'timeout_ms'=>'string'],
'RdKafka\KafkaConsumer::getAssignment' => ['RdKafka\TopicPartition[]'],
'RdKafka\KafkaConsumer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\KafkaConsumerTopic', 'timeout_ms'=>'int'],
'RdKafka\KafkaConsumer::getSubscription' => ['array'],
'RdKafka\KafkaConsumer::subscribe' => ['void', 'topics'=>'array'],
'RdKafka\KafkaConsumer::unsubscribe' => ['void'],
'RdKafka\KafkaConsumerTopic::getName' => ['string'],
'RdKafka\KafkaConsumerTopic::offsetStore' => ['void', 'partition'=>'int', 'offset'=>'int'],
'RdKafka\Message::errstr' => ['string'],
'RdKafka\Metadata::getBrokers' => ['RdKafka\Metadata\Collection'],
'RdKafka\Metadata::getOrigBrokerId' => ['int'],
'RdKafka\Metadata::getOrigBrokerName' => ['string'],
'RdKafka\Metadata::getTopics' => ['RdKafka\Metadata\Collection|RdKafka\Metadata\Topic[]'],
'RdKafka\Metadata\Collection::__construct' => ['void'],
'RdKafka\Metadata\Collection::count' => ['int'],
'RdKafka\Metadata\Collection::current' => ['mixed'],
'RdKafka\Metadata\Collection::key' => ['mixed'],
'RdKafka\Metadata\Collection::next' => ['void'],
'RdKafka\Metadata\Collection::rewind' => ['void'],
'RdKafka\Metadata\Collection::valid' => ['bool'],
'RdKafka\Metadata\Partition::getErr' => ['mixed'],
'RdKafka\Metadata\Partition::getId' => ['int'],
'RdKafka\Metadata\Partition::getIsrs' => ['mixed'],
'RdKafka\Metadata\Partition::getLeader' => ['mixed'],
'RdKafka\Metadata\Partition::getReplicas' => ['mixed'],
'RdKafka\Metadata\Topic::getErr' => ['mixed'],
'RdKafka\Metadata\Topic::getPartitions' => ['RdKafka\Metadata\Partition[]'],
'RdKafka\Metadata\Topic::getTopic' => ['string'],
'RdKafka\Producer::__construct' => ['void', 'conf='=>'?RdKafka\Conf'],
'RdKafka\Producer::addBrokers' => ['int', 'broker_list'=>'string'],
'RdKafka\Producer::getMetadata' => ['RdKafka\Metadata', 'all_topics'=>'bool', 'only_topic='=>'RdKafka\Topic', 'timeout_ms'=>'int'],
'RdKafka\Producer::getOutQLen' => ['int'],
'RdKafka\Producer::newQueue' => ['RdKafka\Queue'],
'RdKafka\Producer::newTopic' => ['RdKafka\ProducerTopic', 'topic_name'=>'string', 'topic_conf='=>'?RdKafka\TopicConf'],
'RdKafka\Producer::poll' => ['void', 'timeout_ms'=>'int'],
'RdKafka\Producer::setLogLevel' => ['void', 'level'=>'int'],
'RdKafka\ProducerTopic::__construct' => ['void'],
'RdKafka\ProducerTopic::getName' => ['string'],
'RdKafka\ProducerTopic::produce' => ['void', 'partition'=>'int', 'msgflags'=>'int', 'payload'=>'string', 'key='=>'string'],
'RdKafka\Queue::__construct' => ['void'],
'RdKafka\Queue::consume' => ['?RdKafka\Message', 'timeout_ms'=>'string'],
'RdKafka\Topic::getName' => ['string'],
'RdKafka\TopicConf::dump' => ['array'],
'RdKafka\TopicConf::set' => ['void', 'name'=>'string', 'value'=>'string'],
'RdKafka\TopicConf::setPartitioner' => ['void', 'partitioner'=>'int'],
'RdKafka\TopicPartition::__construct' => ['void', 'topic'=>'string', 'partition'=>'int', 'offset='=>'int'],
'RdKafka\TopicPartition::getOffset' => ['int'],
'RdKafka\TopicPartition::getPartition' => ['int'],
'RdKafka\TopicPartition::getTopic' => ['string'],
'RdKafka\TopicPartition::setOffset' => ['void', 'offset'=>'string'],
'RdKafka\TopicPartition::setPartition' => ['void', 'partition'=>'string'],
'RdKafka\TopicPartition::setTopic' => ['void', 'topic_name'=>'string'],
'read_exif_data' => ['array', 'filename'=>'string|resource', 'sections_needed='=>'string', 'sub_arrays='=>'bool', 'read_thumbnail='=>'bool'],
'readdir' => ['string|false', 'dir_handle='=>'resource'],
'readfile' => ['int|false', 'filename'=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'readgzfile' => ['int|false', 'filename'=>'string', 'use_include_path='=>'int'],
'readline' => ['string', 'prompt='=>'?string'],
'readline_add_history' => ['bool', 'prompt'=>'string'],
'readline_callback_handler_install' => ['bool', 'prompt'=>'string', 'callback'=>'callable'],
'readline_callback_handler_remove' => ['bool'],
'readline_callback_read_char' => ['void'],
'readline_clear_history' => ['bool'],
'readline_completion_function' => ['bool', 'funcname'=>'callable'],
'readline_info' => ['mixed', 'varname='=>'string', 'newvalue='=>'string'],
'readline_list_history' => ['array'],
'readline_on_new_line' => ['void'],
'readline_read_history' => ['bool', 'filename='=>'string'],
'readline_redisplay' => ['void'],
'readline_write_history' => ['bool', 'filename='=>'string'],
'readlink' => ['string|false', 'filename'=>'string'],
'realpath' => ['string|false', 'path'=>'string'],
'realpath_cache_get' => ['array'],
'realpath_cache_size' => ['int'],
'recode' => ['string', 'request'=>'string', 'str'=>'string'],
'recode_file' => ['bool', 'request'=>'string', 'input'=>'resource', 'output'=>'resource'],
'recode_string' => ['string|false', 'request'=>'string', 'str'=>'string'],
'rectObj::__construct' => ['void'],
'rectObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj', 'class_index'=>'int', 'text'=>'string'],
'rectObj::fit' => ['float', 'width'=>'int', 'height'=>'int'],
'rectObj::ms_newRectObj' => ['rectObj'],
'rectObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'rectObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'rectObj::setextent' => ['void', 'minx'=>'float', 'miny'=>'float', 'maxx'=>'float', 'maxy'=>'float'],
'RecursiveArrayIterator::__construct' => ['void', 'array='=>'array|object', 'flags='=>'int'],
'RecursiveArrayIterator::append' => ['void', 'value'=>'mixed'],
'RecursiveArrayIterator::asort' => ['void'],
'RecursiveArrayIterator::count' => ['int'],
'RecursiveArrayIterator::current' => ['mixed'],
'RecursiveArrayIterator::getArrayCopy' => ['array'],
'RecursiveArrayIterator::getChildren' => ['RecursiveArrayIterator'],
'RecursiveArrayIterator::getFlags' => ['void'],
'RecursiveArrayIterator::hasChildren' => ['bool'],
'RecursiveArrayIterator::key' => ['false|int|string'],
'RecursiveArrayIterator::ksort' => ['void'],
'RecursiveArrayIterator::natcasesort' => ['void'],
'RecursiveArrayIterator::natsort' => ['void'],
'RecursiveArrayIterator::next' => ['void'],
'RecursiveArrayIterator::offsetExists' => ['void', 'index'=>'string'],
'RecursiveArrayIterator::offsetGet' => ['mixed', 'index'=>'string'],
'RecursiveArrayIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'string'],
'RecursiveArrayIterator::offsetUnset' => ['void', 'index'=>'string'],
'RecursiveArrayIterator::rewind' => ['void'],
'RecursiveArrayIterator::seek' => ['void', 'position'=>'int'],
'RecursiveArrayIterator::serialize' => ['string'],
'RecursiveArrayIterator::setFlags' => ['void', 'flags'=>'string'],
'RecursiveArrayIterator::uasort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'RecursiveArrayIterator::uksort' => ['void', 'cmp_function'=>'callable(mixed,mixed):int'],
'RecursiveArrayIterator::unserialize' => ['string', 'serialized'=>'string'],
'RecursiveArrayIterator::valid' => ['bool'],
'RecursiveCachingIterator::__construct' => ['void', 'it'=>'Iterator', 'flags='=>'int'],
'RecursiveCachingIterator::__toString' => ['string'],
'RecursiveCachingIterator::count' => ['int'],
'RecursiveCachingIterator::current' => ['void'],
'RecursiveCachingIterator::getCache' => ['array'],
'RecursiveCachingIterator::getChildren' => ['RecursiveCachingIterator'],
'RecursiveCachingIterator::getFlags' => ['int'],
'RecursiveCachingIterator::getInnerIterator' => ['Iterator'],
'RecursiveCachingIterator::hasChildren' => ['bool'],
'RecursiveCachingIterator::hasNext' => ['bool'],
'RecursiveCachingIterator::key' => ['bool|float|int|string'],
'RecursiveCachingIterator::next' => ['void'],
'RecursiveCachingIterator::offsetExists' => ['bool', 'index'=>'string'],
'RecursiveCachingIterator::offsetGet' => ['string', 'index'=>'string'],
'RecursiveCachingIterator::offsetSet' => ['void', 'index'=>'string', 'newval'=>'string'],
'RecursiveCachingIterator::offsetUnset' => ['void', 'index'=>'string'],
'RecursiveCachingIterator::rewind' => ['void'],
'RecursiveCachingIterator::setFlags' => ['void', 'flags'=>'int'],
'RecursiveCachingIterator::valid' => ['bool'],
'RecursiveCallbackFilterIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator', 'func'=>'callable'],
'RecursiveCallbackFilterIterator::accept' => ['bool'],
'RecursiveCallbackFilterIterator::current' => ['mixed'],
'RecursiveCallbackFilterIterator::getChildren' => ['RecursiveCallbackFilterIterator'],
'RecursiveCallbackFilterIterator::getInnerIterator' => ['Iterator'],
'RecursiveCallbackFilterIterator::hasChildren' => ['bool'],
'RecursiveCallbackFilterIterator::key' => ['bool|float|int|string'],
'RecursiveCallbackFilterIterator::next' => ['void'],
'RecursiveCallbackFilterIterator::rewind' => ['void'],
'RecursiveCallbackFilterIterator::valid' => ['bool'],
'RecursiveDirectoryIterator::__construct' => ['void', 'path'=>'string', 'flags='=>'int'],
'RecursiveDirectoryIterator::__toString' => ['string'],
'RecursiveDirectoryIterator::_bad_state_ex' => [''],
'RecursiveDirectoryIterator::current' => ['string|SplFileInfo|FilesystemIterator'],
'RecursiveDirectoryIterator::getATime' => ['int'],
'RecursiveDirectoryIterator::getBasename' => ['string', 'suffix='=>'string'],
'RecursiveDirectoryIterator::getChildren' => ['RecursiveDirectoryIterator'],
'RecursiveDirectoryIterator::getCTime' => ['int'],
'RecursiveDirectoryIterator::getExtension' => ['string'],
'RecursiveDirectoryIterator::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'RecursiveDirectoryIterator::getFilename' => ['string'],
'RecursiveDirectoryIterator::getFlags' => ['int'],
'RecursiveDirectoryIterator::getGroup' => ['int'],
'RecursiveDirectoryIterator::getInode' => ['int'],
'RecursiveDirectoryIterator::getLinkTarget' => ['string'],
'RecursiveDirectoryIterator::getMTime' => ['int'],
'RecursiveDirectoryIterator::getOwner' => ['int'],
'RecursiveDirectoryIterator::getPath' => ['string'],
'RecursiveDirectoryIterator::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'RecursiveDirectoryIterator::getPathname' => ['string'],
'RecursiveDirectoryIterator::getPerms' => ['int'],
'RecursiveDirectoryIterator::getRealPath' => ['string'],
'RecursiveDirectoryIterator::getSize' => ['int'],
'RecursiveDirectoryIterator::getSubPath' => ['string'],
'RecursiveDirectoryIterator::getSubPathname' => ['string'],
'RecursiveDirectoryIterator::getType' => ['string'],
'RecursiveDirectoryIterator::hasChildren' => ['bool', 'allow_links='=>'bool'],
'RecursiveDirectoryIterator::isDir' => ['bool'],
'RecursiveDirectoryIterator::isDot' => ['bool'],
'RecursiveDirectoryIterator::isExecutable' => ['bool'],
'RecursiveDirectoryIterator::isFile' => ['bool'],
'RecursiveDirectoryIterator::isLink' => ['bool'],
'RecursiveDirectoryIterator::isReadable' => ['bool'],
'RecursiveDirectoryIterator::isWritable' => ['bool'],
'RecursiveDirectoryIterator::key' => ['string'],
'RecursiveDirectoryIterator::next' => ['void'],
'RecursiveDirectoryIterator::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'RecursiveDirectoryIterator::rewind' => ['void'],
'RecursiveDirectoryIterator::seek' => ['void', 'position'=>'int'],
'RecursiveDirectoryIterator::setFileClass' => ['void', 'class_name='=>'string'],
'RecursiveDirectoryIterator::setFlags' => ['void', 'flags='=>'int'],
'RecursiveDirectoryIterator::setInfoClass' => ['void', 'class_name='=>'string'],
'RecursiveDirectoryIterator::valid' => ['bool'],
'RecursiveFilterIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator'],
'RecursiveFilterIterator::accept' => ['bool'],
'RecursiveFilterIterator::current' => ['mixed'],
'RecursiveFilterIterator::getChildren' => ['RecursiveFilterIterator'],
'RecursiveFilterIterator::getInnerIterator' => ['Iterator'],
'RecursiveFilterIterator::hasChildren' => ['bool'],
'RecursiveFilterIterator::key' => ['mixed'],
'RecursiveFilterIterator::next' => ['void'],
'RecursiveFilterIterator::rewind' => ['void'],
'RecursiveFilterIterator::valid' => ['bool'],
'RecursiveIterator::__construct' => ['void'],
'RecursiveIterator::current' => ['mixed'],
'RecursiveIterator::getChildren' => ['RecursiveIterator'],
'RecursiveIterator::hasChildren' => ['bool'],
'RecursiveIterator::key' => ['int|string'],
'RecursiveIterator::next' => ['void'],
'RecursiveIterator::rewind' => ['void'],
'RecursiveIterator::valid' => ['bool'],
'RecursiveIteratorIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator|IteratorAggregate', 'mode='=>'int', 'flags='=>'int'],
'RecursiveIteratorIterator::beginChildren' => ['void'],
'RecursiveIteratorIterator::beginIteration' => ['RecursiveIterator'],
'RecursiveIteratorIterator::callGetChildren' => ['RecursiveIterator'],
'RecursiveIteratorIterator::callHasChildren' => ['bool'],
'RecursiveIteratorIterator::current' => ['mixed'],
'RecursiveIteratorIterator::endChildren' => ['void'],
'RecursiveIteratorIterator::endIteration' => ['RecursiveIterator'],
'RecursiveIteratorIterator::getDepth' => ['int'],
'RecursiveIteratorIterator::getInnerIterator' => ['RecursiveIterator'],
'RecursiveIteratorIterator::getMaxDepth' => ['int|false'],
'RecursiveIteratorIterator::getSubIterator' => ['RecursiveIterator', 'level='=>'int'],
'RecursiveIteratorIterator::key' => ['mixed'],
'RecursiveIteratorIterator::next' => ['void'],
'RecursiveIteratorIterator::nextElement' => ['void'],
'RecursiveIteratorIterator::rewind' => ['void'],
'RecursiveIteratorIterator::setMaxDepth' => ['void', 'max_depth='=>'int'],
'RecursiveIteratorIterator::valid' => ['bool'],
'RecursiveRegexIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator', 'regex'=>'string', 'mode='=>'int', 'flags='=>'int', 'preg_flags='=>'int'],
'RecursiveRegexIterator::accept' => ['bool'],
'RecursiveRegexIterator::current' => [''],
'RecursiveRegexIterator::getChildren' => ['RecursiveRegexIterator'],
'RecursiveRegexIterator::getFlags' => ['int'],
'RecursiveRegexIterator::getInnerIterator' => [''],
'RecursiveRegexIterator::getMode' => ['int'],
'RecursiveRegexIterator::getPregFlags' => ['int'],
'RecursiveRegexIterator::getRegex' => ['string'],
'RecursiveRegexIterator::hasChildren' => ['bool'],
'RecursiveRegexIterator::key' => [''],
'RecursiveRegexIterator::next' => [''],
'RecursiveRegexIterator::rewind' => [''],
'RecursiveRegexIterator::setFlags' => ['void', 'new_flags'=>'int'],
'RecursiveRegexIterator::setMode' => ['void', 'new_mode'=>'int'],
'RecursiveRegexIterator::setPregFlags' => ['void', 'new_flags'=>'int'],
'RecursiveRegexIterator::valid' => [''],
'RecursiveTreeIterator::__construct' => ['void', 'iterator'=>'RecursiveIterator|IteratorAggregate', 'flags='=>'int', 'cit_flags='=>'int', 'mode'=>'int'],
'RecursiveTreeIterator::beginChildren' => ['void'],
'RecursiveTreeIterator::beginIteration' => ['RecursiveIterator'],
'RecursiveTreeIterator::callGetChildren' => ['RecursiveIterator'],
'RecursiveTreeIterator::callHasChildren' => ['bool'],
'RecursiveTreeIterator::current' => ['string'],
'RecursiveTreeIterator::endChildren' => ['void'],
'RecursiveTreeIterator::endIteration' => ['void'],
'RecursiveTreeIterator::getDepth' => ['int'],
'RecursiveTreeIterator::getEntry' => ['string'],
'RecursiveTreeIterator::getInnerIterator' => ['RecursiveIterator'],
'RecursiveTreeIterator::getMaxDepth' => ['false|int'],
'RecursiveTreeIterator::getPostfix' => ['string'],
'RecursiveTreeIterator::getPrefix' => ['string'],
'RecursiveTreeIterator::getSubIterator' => ['RecursiveIterator', 'level='=>'int'],
'RecursiveTreeIterator::key' => ['string'],
'RecursiveTreeIterator::next' => ['void'],
'RecursiveTreeIterator::nextElement' => ['void'],
'RecursiveTreeIterator::rewind' => ['void'],
'RecursiveTreeIterator::setMaxDepth' => ['void', 'max_depth='=>'int'],
'RecursiveTreeIterator::setPostfix' => ['void', 'prefix'=>'string'],
'RecursiveTreeIterator::setPrefixPart' => ['void', 'part'=>'int', 'prefix'=>'string'],
'RecursiveTreeIterator::valid' => ['bool'],
'Redis::__construct' => ['void'],
'Redis::__destruct' => ['void'],
'Redis::_prefix' => ['string', 'value'=>'mixed'],
'Redis::_serialize' => ['mixed', 'value'=>'mixed'],
'Redis::_unserialize' => ['mixed', 'value'=>'string'],
'Redis::append' => ['int', 'key'=>'string', 'value'=>'string'],
'Redis::auth' => ['bool', 'password'=>'string'],
'Redis::bgRewriteAOF' => ['bool'],
'Redis::bgSave' => ['bool'],
'Redis::bitCount' => ['int', 'key'=>'string'],
'Redis::bitOp' => ['int', 'operation'=>'string', 'ret_key'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::bitpos' => ['int', 'key'=>'string', 'bit'=>'int', 'start='=>'int', 'end='=>'int'],
'Redis::blPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'Redis::brPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'Redis::brpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string', 'timeout'=>'int'],
'Redis::clearLastError' => ['bool'],
'Redis::client' => ['mixed', 'command'=>'string', 'arg='=>'string'],
'Redis::close' => ['bool'],
'Redis::command' => ['', '...args'=>''],
'Redis::config' => ['string', 'operation'=>'string', 'key'=>'string', 'value='=>'string'],
'Redis::connect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'reserved='=>'null', 'retry_interval='=>'?int', 'read_timeout='=>'float'],
'Redis::dbSize' => ['int'],
'Redis::debug' => ['', 'key'=>''],
'Redis::decr' => ['int', 'key'=>'string'],
'Redis::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'Redis::decrByFloat' => ['float', 'key'=>'string', 'value'=>'float'],
'Redis::del' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::del\'1' => ['int', 'key'=>'string[]'],
'Redis::delete' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::delete\'1' => ['int', 'key'=>'string[]'],
'Redis::discard' => [''],
'Redis::dump' => ['string|false', 'key'=>'string'],
'Redis::echo' => ['string', 'message'=>'string'],
'Redis::eval' => ['mixed', 'script'=>'', 'args='=>'', 'numKeys='=>''],
'Redis::evalSha' => ['mixed', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::evaluate' => ['mixed', 'script'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::evaluateSha' => ['', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'Redis::exec' => ['array'],
'Redis::exists' => ['int', 'keys'=>'string|string[]'],
'Redis::exists\'1' => ['int', '...keys'=>'string'],
'Redis::expire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'Redis::expireAt' => ['bool', 'key'=>'string', 'expiry'=>'int'],
'Redis::flushAll' => ['bool', 'async='=>'bool'],
'Redis::flushDb' => ['bool', 'async='=>'bool'],
'Redis::geoAdd' => ['int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string', '...other_triples='=>'string|int|float'],
'Redis::geoDist' => ['float', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'Redis::geoHash' => ['array<int,string>', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::geoPos' => ['array<int,array{0:string,1:string}>', 'key'=>'string', 'member'=>'string', '...members'=>'string'],
'Redis::geoRadius' => ['array<int,mixed>|int', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'unit'=>'float', 'options='=>'array<string,mixed>'],
'Redis::geoRadiusByMember' => ['array<int,mixed>|int', 'key'=>'string', 'member'=>'string', 'radius'=>'float', 'units'=>'string', 'options='=>'array<string,mixed>'],
'Redis::get' => ['string|false', 'key'=>'string'],
'Redis::getAuth' => ['string|false|null'],
'Redis::getBit' => ['int', 'key'=>'string', 'offset'=>'int'],
'Redis::getDBNum' => ['int'],
'Redis::getHost' => ['string'],
'Redis::getKeys' => ['array<int,string>', 'pattern'=>'string'],
'Redis::getLastError' => ['?string'],
'Redis::getMode' => ['int'],
'Redis::getMultiple' => ['array', 'keys'=>'string[]'],
'Redis::getOption' => ['int', 'name'=>'int'],
'Redis::getPersistentID' => ['string|false|null'],
'Redis::getPort' => ['int|false'],
'Redis::getRange' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::getReadTimeout' => ['float|false'],
'Redis::getSet' => ['string', 'key'=>'string', 'string'=>'string'],
'Redis::getTimeout' => ['float|false'],
'Redis::hDel' => ['int|false', 'key'=>'string', 'hashKey1'=>'string', '...otherHashKeys='=>'string'],
'Redis::hExists' => ['bool', 'key'=>'string', 'hashKey'=>'string'],
'Redis::hGet' => ['string|false', 'key'=>'string', 'hashKey'=>'string'],
'Redis::hGetAll' => ['array', 'key'=>'string'],
'Redis::hIncrBy' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'int'],
'Redis::hIncrByFloat' => ['float', 'key'=>'string', 'field'=>'string', 'increment'=>'float'],
'Redis::hKeys' => ['array', 'key'=>'string'],
'Redis::hLen' => ['int|false', 'key'=>'string'],
'Redis::hMGet' => ['array', 'key'=>'string', 'hashKeys'=>'array'],
'Redis::hMSet' => ['bool', 'key'=>'string', 'hashKeys'=>'array'],
'Redis::hScan' => ['array', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::hSet' => ['int|false', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'Redis::hSetNx' => ['bool', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'Redis::hStrLen' => ['', 'key'=>'', 'member'=>''],
'Redis::hVals' => ['array', 'key'=>'string'],
'Redis::incr' => ['int', 'key'=>'string'],
'Redis::incrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'Redis::incrByFloat' => ['float', 'key'=>'string', 'value'=>'float'],
'Redis::info' => ['array', 'option='=>'string'],
'Redis::isConnected' => ['bool'],
'Redis::keys' => ['array<int,string>', 'pattern'=>'string'],
'Redis::lastSave' => ['int'],
'Redis::lGet' => ['string', 'key'=>'string', 'index'=>'int'],
'Redis::lGetRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::lIndex' => ['string|false', 'key'=>'string', 'index'=>'int'],
'Redis::lInsert' => ['int', 'key'=>'string', 'position'=>'int', 'pivot'=>'string', 'value'=>'string'],
'Redis::listTrim' => ['', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'Redis::lLen' => ['int|false', 'key'=>'string'],
'Redis::lPop' => ['string|false', 'key'=>'string'],
'Redis::lPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::lPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'Redis::lRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::lRem' => ['int|false', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'Redis::lRemove' => ['int', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'Redis::lSet' => ['bool', 'key'=>'string', 'index'=>'int', 'value'=>'string'],
'Redis::lSize' => ['int', 'key'=>'string'],
'Redis::lTrim' => ['array|false', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'Redis::mGet' => ['array', 'keys'=>'string[]'],
'Redis::migrate' => ['bool', 'host'=>'string', 'port'=>'int', 'key'=>'string|string[]', 'db'=>'int', 'timeout'=>'int', 'copy='=>'bool', 'replace='=>'bool'],
'Redis::move' => ['bool', 'key'=>'string', 'dbindex'=>'int'],
'Redis::mSet' => ['bool', 'pairs'=>'array'],
'Redis::mSetNx' => ['bool', 'pairs'=>'array'],
'Redis::multi' => ['Redis', 'mode='=>'int'],
'Redis::object' => ['string|long|false', 'info'=>'string', 'key'=>'string'],
'Redis::open' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'reserved='=>'null', 'retry_interval='=>'?int', 'read_timeout='=>'float'],
'Redis::pconnect' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'persistent_id='=>'string', 'retry_interval='=>'?int'],
'Redis::persist' => ['bool', 'key'=>'string'],
'Redis::pExpire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'Redis::pexpireAt' => ['bool', 'key'=>'string', 'expiry'=>'int'],
'Redis::pfAdd' => ['bool', 'key'=>'string', 'elements'=>'array'],
'Redis::pfCount' => ['int', 'key'=>'array|string'],
'Redis::pfMerge' => ['bool', 'destkey'=>'string', 'sourcekeys'=>'array'],
'Redis::ping' => ['string'],
'Redis::pipeline' => ['Redis'],
'Redis::popen' => ['bool', 'host'=>'string', 'port='=>'int', 'timeout='=>'float', 'persistent_id='=>'string', 'retry_interval='=>'?int'],
'Redis::psetex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::psubscribe' => ['', 'patterns'=>'array', 'callback'=>'array|string'],
'Redis::pttl' => ['int|false', 'key'=>'string'],
'Redis::publish' => ['int', 'channel'=>'string', 'message'=>'string'],
'Redis::pubsub' => ['array|int', 'keyword'=>'string', 'argument'=>'array|string'],
'Redis::punsubscribe' => ['', 'pattern'=>'string', '...other_patterns='=>'string'],
'Redis::randomKey' => ['string'],
'Redis::rawCommand' => ['mixed', 'command'=>'string', '...arguments='=>'mixed'],
'Redis::rename' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::renameKey' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::renameNx' => ['bool', 'srckey'=>'string', 'dstkey'=>'string'],
'Redis::resetStat' => ['bool'],
'Redis::restore' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::role' => ['array'],
'Redis::rPop' => ['string|false', 'key'=>'string'],
'Redis::rpoplpush' => ['string', 'srcKey'=>'string', 'dstKey'=>'string'],
'Redis::rPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::rPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'Redis::sAdd' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'Redis::sAddArray' => ['bool', 'key'=>'string', 'values'=>'array'],
'Redis::save' => ['bool'],
'Redis::scan' => ['array<int,string>|false', '&rw_iterator'=>'?int', 'pattern='=>'?string', 'count='=>'?int'],
'Redis::sCard' => ['int', 'key'=>'string'],
'Redis::sContains' => ['', 'key'=>'string', 'value'=>'string'],
'Redis::script' => ['mixed', 'command'=>'string', '...args='=>'mixed'],
'Redis::sDiff' => ['array', 'key1'=>'string', '...other_keys='=>'string'],
'Redis::sDiffStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::select' => ['bool', 'dbindex'=>'int'],
'Redis::sendEcho' => ['string', 'msg'=>'string'],
'Redis::set' => ['bool', 'key'=>'string', 'value'=>'string', 'options='=>'array'],
'Redis::set\'1' => ['bool', 'key'=>'string', 'value'=>'string', 'timeout='=>'int'],
'Redis::setBit' => ['int', 'key'=>'string', 'offset'=>'int', 'value'=>'int'],
'Redis::setEx' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'Redis::setNx' => ['bool', 'key'=>'string', 'value'=>'string'],
'Redis::setOption' => ['bool', 'name'=>'int', 'value'=>'int|string'],
'Redis::setRange' => ['int', 'key'=>'string', 'offset'=>'int', 'end'=>'int'],
'Redis::setTimeout' => ['', 'key'=>'string', 'ttl'=>'int'],
'Redis::sGetMembers' => ['', 'key'=>'string'],
'Redis::sInter' => ['array|false', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sInterStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'Redis::slave' => ['bool', 'host'=>'string', 'port'=>'int'],
'Redis::slave\'1' => ['bool', 'host'=>'string', 'port'=>'int'],
'Redis::slaveof' => ['bool', 'host='=>'string', 'port='=>'int'],
'Redis::slowLog' => ['mixed', 'operation'=>'string', 'length='=>'int'],
'Redis::sMembers' => ['array', 'key'=>'string'],
'Redis::sMove' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string', 'member'=>'string'],
'Redis::sort' => ['array|int', 'key'=>'string', 'options='=>'array'],
'Redis::sortAsc' => ['array', 'key'=>'string', 'pattern='=>'string', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortAscAlpha' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortDesc' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sortDescAlpha' => ['array', 'key'=>'string', 'pattern='=>'', 'get='=>'string', 'start='=>'int', 'end='=>'int', 'getList='=>'bool'],
'Redis::sPop' => ['string|false', 'key'=>'string'],
'Redis::sRandMember' => ['array|string|false', 'key'=>'string', 'count='=>'int'],
'Redis::sRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'Redis::sRemove' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'Redis::sScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::sSize' => ['int', 'key'=>'string'],
'Redis::strLen' => ['int', 'key'=>'string'],
'Redis::subscribe' => ['', 'channels'=>'array', 'callback'=>'string'],
'Redis::substr' => ['', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::sUnion' => ['array', 'key'=>'string', '...other_keys='=>'string'],
'Redis::sUnionStore' => ['int', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'Redis::swapdb' => ['bool', 'srcdb'=>'int', 'dstdb'=>'int'],
'Redis::time' => ['array'],
'Redis::ttl' => ['int|false', 'key'=>'string'],
'Redis::type' => ['int', 'key'=>'string'],
'Redis::unlink' => ['int', 'key'=>'string', '...args'=>'string'],
'Redis::unlink\'1' => ['int', 'key'=>'string[]'],
'Redis::unsubscribe' => ['', 'channel'=>'string', '...other_channels='=>'string'],
'Redis::unwatch' => [''],
'Redis::wait' => ['int', 'numSlaves'=>'int', 'timeout'=>'int'],
'Redis::watch' => ['void', 'key'=>'string', '...other_keys='=>'string'],
'Redis::xack' => ['', 'str_key'=>'string', 'str_group'=>'string', 'arr_ids'=>'array'],
'Redis::xadd' => ['', 'str_key'=>'string', 'str_id'=>'string', 'arr_fields'=>'array', 'i_maxlen='=>'', 'boo_approximate='=>''],
'Redis::xclaim' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_consumer'=>'string', 'i_min_idle'=>'', 'arr_ids'=>'array', 'arr_opts='=>'array'],
'Redis::xdel' => ['', 'str_key'=>'string', 'arr_ids'=>'array'],
'Redis::xgroup' => ['', 'str_operation'=>'string', 'str_key='=>'string', 'str_arg1='=>'', 'str_arg2='=>'', 'str_arg3='=>''],
'Redis::xinfo' => ['', 'str_cmd'=>'string', 'str_key='=>'string', 'str_group='=>'string'],
'Redis::xlen' => ['', 'key'=>''],
'Redis::xpending' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_start='=>'', 'str_end='=>'', 'i_count='=>'', 'str_consumer='=>'string'],
'Redis::xrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'Redis::xread' => ['', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'Redis::xreadgroup' => ['', 'str_group'=>'string', 'str_consumer'=>'string', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'Redis::xrevrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'Redis::xtrim' => ['', 'str_key'=>'string', 'i_maxlen'=>'', 'boo_approximate='=>''],
'Redis::zAdd' => ['int', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'Redis::zCard' => ['int', 'key'=>'string'],
'Redis::zCount' => ['int', 'key'=>'string', 'start'=>'string', 'end'=>'string'],
'Redis::zDelete' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zDeleteRangeByRank' => ['', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zDeleteRangeByScore' => ['', 'key'=>'string', 'start'=>'float', 'end'=>'float'],
'Redis::zIncrBy' => ['float', 'key'=>'string', 'value'=>'float', 'member'=>'string'],
'Redis::zInter' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zInterStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zLexCount' => ['int', 'key'=>'string', 'min'=>'string', 'max'=>'string'],
'Redis::zRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscores='=>'bool'],
'Redis::zRangeByLex' => ['array|false', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRangeByScore' => ['array', 'key'=>'string', 'start'=>'int|string', 'end'=>'int|string', 'options='=>'array'],
'Redis::zRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zRem' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zRemove' => ['int', 'key'=>'string', 'member'=>'string', '...other_members='=>'string'],
'Redis::zRemoveRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zRemoveRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'Redis::zRemRangeByLex' => ['int', 'key'=>'string', 'min'=>'string', 'max'=>'string'],
'Redis::zRemRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'Redis::zRemRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'Redis::zReverseRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'Redis::zRevRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'Redis::zRevRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'Redis::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'Redis::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'Redis::zScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'Redis::zScore' => ['float', 'key'=>'string', 'member'=>'string'],
'Redis::zSize' => ['', 'key'=>'string'],
'Redis::zUnion' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Redis::zUnionStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'RedisArray::__call' => ['mixed', 'function_name'=>'string', 'arguments'=>'array'],
'RedisArray::__construct' => ['void', 'name='=>'string', 'hosts='=>'?array', 'opts='=>'?array'],
'RedisArray::_continuum' => [''],
'RedisArray::_distributor' => [''],
'RedisArray::_function' => ['string'],
'RedisArray::_hosts' => ['array'],
'RedisArray::_instance' => ['', 'host'=>''],
'RedisArray::_rehash' => [''],
'RedisArray::_target' => ['string', 'key'=>'string'],
'RedisArray::bgsave' => [''],
'RedisArray::del' => ['bool', 'key'=>'string', '...args'=>'string'],
'RedisArray::delete' => ['bool', 'key'=>'string', '...args'=>'string'],
'RedisArray::delete\'1' => ['bool', 'key'=>'string[]'],
'RedisArray::discard' => [''],
'RedisArray::exec' => ['array'],
'RedisArray::flushAll' => ['bool', 'async='=>'bool'],
'RedisArray::flushDb' => ['bool', 'async='=>'bool'],
'RedisArray::getMultiple' => ['', 'keys'=>''],
'RedisArray::getOption' => ['', 'opt'=>''],
'RedisArray::info' => ['array'],
'RedisArray::keys' => ['array<int,string>', 'pattern'=>''],
'RedisArray::mGet' => ['array', 'keys'=>'string[]'],
'RedisArray::mSet' => ['bool', 'pairs'=>'array'],
'RedisArray::multi' => ['RedisArray', 'host'=>'string', 'mode='=>'int'],
'RedisArray::ping' => ['string'],
'RedisArray::save' => ['bool'],
'RedisArray::select' => ['', 'index'=>''],
'RedisArray::setOption' => ['', 'opt'=>'', 'value'=>''],
'RedisArray::unlink' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisArray::unwatch' => [''],
'RedisCluster::__construct' => ['void', 'name'=>'string', 'seeds'=>'array', 'timeout='=>'float', 'readTimeout='=>'float', 'persistent='=>'bool'],
'RedisCluster::_masters' => ['array'],
'RedisCluster::_prefix' => ['string', 'value'=>'mixed'],
'RedisCluster::_redir' => [''],
'RedisCluster::_serialize' => ['mixed', 'value'=>'mixed'],
'RedisCluster::_unserialize' => ['mixed', 'value'=>'string'],
'RedisCluster::append' => ['int', 'key'=>'string', 'value'=>'string'],
'RedisCluster::bgrewriteaof' => ['bool', 'nodeParams'=>'string'],
'RedisCluster::bgsave' => ['bool', 'nodeParams'=>'string'],
'RedisCluster::bitCount' => ['int', 'key'=>'string'],
'RedisCluster::bitOp' => ['int', 'operation'=>'string', 'retKey'=>'string', 'key1'=>'string', 'key2'=>'string', 'key3='=>'string'],
'RedisCluster::bitpos' => ['int', 'key'=>'string', 'bit'=>'int', 'start='=>'int', 'end='=>'int'],
'RedisCluster::blPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'RedisCluster::brPop' => ['array', 'keys'=>'array', 'timeout'=>'int'],
'RedisCluster::brpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string', 'timeout'=>'int'],
'RedisCluster::clearLastError' => ['bool'],
'RedisCluster::client' => ['', 'nodeParams'=>'string', 'subCmd'=>'', 'args'=>''],
'RedisCluster::close' => [''],
'RedisCluster::cluster' => ['mixed', 'nodeParams'=>'string', 'command'=>'string', 'arguments'=>'mixed'],
'RedisCluster::command' => ['array|bool'],
'RedisCluster::config' => ['array', 'nodeParams'=>'string', 'operation'=>'string', 'key'=>'string', 'value'=>'string'],
'RedisCluster::dbSize' => ['int', 'nodeParams'=>'string'],
'RedisCluster::decr' => ['int', 'key'=>'string'],
'RedisCluster::decrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::del' => ['int', 'key1'=>'int', 'key2='=>'string', 'key3='=>'string'],
'RedisCluster::discard' => [''],
'RedisCluster::dump' => ['string|false', 'key'=>'string'],
'RedisCluster::echo' => ['mixed', 'nodeParams'=>'string', 'msg'=>'string'],
'RedisCluster::eval' => ['mixed', 'script'=>'', 'args='=>'', 'numKeys='=>''],
'RedisCluster::evalSha' => ['mixed', 'scriptSha'=>'string', 'args='=>'array', 'numKeys='=>'int'],
'RedisCluster::exec' => ['array|void'],
'RedisCluster::exists' => ['bool', 'key'=>'string'],
'RedisCluster::expire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'RedisCluster::expireAt' => ['bool', 'key'=>'string', 'timestamp'=>'int'],
'RedisCluster::flushAll' => ['bool', 'nodeParams'=>'string'],
'RedisCluster::flushDB' => ['bool', 'nodeParams'=>'string'],
'RedisCluster::geoAdd' => ['', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'member'=>'string'],
'RedisCluster::geoDist' => ['', 'key'=>'string', 'member1'=>'string', 'member2'=>'string', 'unit='=>'string'],
'RedisCluster::geohash' => ['', 'key'=>'', 'member1'=>'', 'member2='=>'mixed', 'memberN='=>'mixed'],
'RedisCluster::geopos' => ['', 'key'=>'', 'member1'=>'', 'member2='=>'mixed', 'memberN='=>'mixed'],
'RedisCluster::geoRadius' => ['', 'key'=>'string', 'longitude'=>'float', 'latitude'=>'float', 'radius'=>'float', 'radiusUnit'=>'string', 'options'=>'array'],
'RedisCluster::geoRadiusByMember' => ['', 'key'=>'string', 'member'=>'string', 'radius'=>'float', 'radiusUnit'=>'string', 'options'=>'array'],
'RedisCluster::get' => ['string|false', 'key'=>'string'],
'RedisCluster::getBit' => ['int', 'key'=>'string', 'offset'=>'int'],
'RedisCluster::getLastError' => ['?string'],
'RedisCluster::getMode' => ['int'],
'RedisCluster::getOption' => ['int', 'name'=>'string'],
'RedisCluster::getRange' => ['string', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::getSet' => ['string', 'key'=>'string', 'value'=>'string'],
'RedisCluster::hDel' => ['int', 'key'=>'string', 'hashKey1'=>'string', 'hashKey2='=>'string', 'hashKeyN='=>'string'],
'RedisCluster::hExists' => ['bool', 'key'=>'string', 'hashKey'=>'string'],
'RedisCluster::hGet' => ['string|false', 'key'=>'string', 'hashKey'=>'string'],
'RedisCluster::hGetAll' => ['array', 'key'=>'string'],
'RedisCluster::hIncrBy' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'int'],
'RedisCluster::hIncrByFloat' => ['float', 'key'=>'string', 'field'=>'string', 'increment'=>'float'],
'RedisCluster::hKeys' => ['array', 'key'=>'string'],
'RedisCluster::hLen' => ['int|false', 'key'=>'string'],
'RedisCluster::hMGet' => ['array', 'key'=>'string', 'hashKeys'=>'array'],
'RedisCluster::hMSet' => ['bool', 'key'=>'string', 'hashKeys'=>'array'],
'RedisCluster::hScan' => ['array', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::hSet' => ['int', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'RedisCluster::hSetNx' => ['bool', 'key'=>'string', 'hashKey'=>'string', 'value'=>'string'],
'RedisCluster::hStrlen' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::hVals' => ['array', 'key'=>'string'],
'RedisCluster::incr' => ['int', 'key'=>'string'],
'RedisCluster::incrBy' => ['int', 'key'=>'string', 'value'=>'int'],
'RedisCluster::incrByFloat' => ['float', 'key'=>'string', 'increment'=>'float'],
'RedisCluster::info' => ['string', 'option='=>'string'],
'RedisCluster::keys' => ['array', 'pattern'=>'string'],
'RedisCluster::lastSave' => ['int', 'nodeParams'=>'string'],
'RedisCluster::lGet' => ['', 'key'=>'string', 'index'=>'int'],
'RedisCluster::lIndex' => ['string|false', 'key'=>'string', 'index'=>'int'],
'RedisCluster::lInsert' => ['int', 'key'=>'string', 'position'=>'int', 'pivot'=>'string', 'value'=>'string'],
'RedisCluster::lLen' => ['int', 'key'=>'string'],
'RedisCluster::lPop' => ['string|false', 'key'=>'string'],
'RedisCluster::lPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::lPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'RedisCluster::lRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::lRem' => ['int', 'key'=>'string', 'value'=>'string', 'count'=>'int'],
'RedisCluster::lSet' => ['bool', 'key'=>'string', 'index'=>'int', 'value'=>'string'],
'RedisCluster::lTrim' => ['array|false', 'key'=>'string', 'start'=>'int', 'stop'=>'int'],
'RedisCluster::mget' => ['array', 'array'=>'array'],
'RedisCluster::mset' => ['bool', 'array'=>'array'],
'RedisCluster::msetnx' => ['int', 'array'=>'array'],
'RedisCluster::multi' => ['Redis', 'mode='=>'int'],
'RedisCluster::object' => ['string|false', 'string='=>'string', 'key='=>'string'],
'RedisCluster::persist' => ['bool', 'key'=>'string'],
'RedisCluster::pExpire' => ['bool', 'key'=>'string', 'ttl'=>'int'],
'RedisCluster::pExpireAt' => ['bool', 'key'=>'string', 'timestamp'=>'int'],
'RedisCluster::pfAdd' => ['bool', 'key'=>'string', 'elements'=>'array'],
'RedisCluster::pfCount' => ['int', 'key'=>'string'],
'RedisCluster::pfMerge' => ['bool', 'destKey'=>'string', 'sourceKeys'=>'array'],
'RedisCluster::ping' => ['string', 'nodeParams'=>'string'],
'RedisCluster::psetex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::psubscribe' => ['mixed', 'patterns'=>'array', 'callback'=>'string'],
'RedisCluster::pttl' => ['int', 'key'=>'string'],
'RedisCluster::publish' => ['int', 'channel'=>'string', 'message'=>'string'],
'RedisCluster::pubsub' => ['array|int', 'nodeParams'=>'string', 'keyword'=>'string', '...argument='=>'string'],
'RedisCluster::punSubscribe' => ['', 'channels'=>'', 'callback'=>''],
'RedisCluster::randomKey' => ['string', 'nodeParams'=>'string'],
'RedisCluster::rawCommand' => ['mixed', 'nodeParams'=>'string', 'command'=>'string', 'arguments'=>'mixed'],
'RedisCluster::rename' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::renameNx' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::restore' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::role' => ['array', 'nodeParams'=>'string'],
'RedisCluster::rPop' => ['string|false', 'key'=>'string'],
'RedisCluster::rpoplpush' => ['string|false', 'srcKey'=>'string', 'dstKey'=>'string'],
'RedisCluster::rPush' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::rPushx' => ['int|false', 'key'=>'string', 'value'=>'string'],
'RedisCluster::sAdd' => ['int|false', 'key'=>'string', 'value1'=>'string', 'value2='=>'string', 'valueN='=>'string'],
'RedisCluster::sAddArray' => ['int|false', 'key'=>'string', 'valueArray'=>'array'],
'RedisCluster::save' => ['bool', 'nodeParams'=>'string'],
'RedisCluster::scan' => ['array|false', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::sCard' => ['int', 'key'=>'string'],
'RedisCluster::script' => ['mixed', 'nodeParams'=>'string', 'command'=>'string', 'script'=>'string'],
'RedisCluster::sDiff' => ['array', 'key1'=>'string', 'key2'=>'string', '...other_keys='=>'string'],
'RedisCluster::sDiffStore' => ['int|false', 'dstKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::set' => ['bool', 'key'=>'string', 'value'=>'string', 'timeout='=>'array|int'],
'RedisCluster::setBit' => ['int', 'key'=>'string', 'offset'=>'int', 'value'=>'bool|int'],
'RedisCluster::setex' => ['bool', 'key'=>'string', 'ttl'=>'int', 'value'=>'string'],
'RedisCluster::setnx' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::setOption' => ['bool', 'name'=>'string', 'value'=>'string'],
'RedisCluster::setRange' => ['string', 'key'=>'string', 'offset'=>'int', 'value'=>'string'],
'RedisCluster::sInter' => ['array', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sInterStore' => ['int|false', 'dstKey'=>'string', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::sIsMember' => ['bool', 'key'=>'string', 'value'=>'string'],
'RedisCluster::slowLog' => ['', 'nodeParams'=>'string', 'command'=>'string', 'argument'=>'mixed', '...other_arguments='=>'mixed'],
'RedisCluster::sMembers' => ['array', 'key'=>'string'],
'RedisCluster::sMove' => ['bool', 'srcKey'=>'string', 'dstKey'=>'string', 'member'=>'string'],
'RedisCluster::sort' => ['array', 'key'=>'string', 'option='=>'array'],
'RedisCluster::sPop' => ['string', 'key'=>'string'],
'RedisCluster::sRandMember' => ['array|string', 'key'=>'string', 'count='=>'int'],
'RedisCluster::sRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'RedisCluster::sScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'null', 'count='=>'int'],
'RedisCluster::strlen' => ['int', 'key'=>'string'],
'RedisCluster::subscribe' => ['mixed', 'channels'=>'array', 'callback'=>'string'],
'RedisCluster::sUnion' => ['array', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::sUnionStore' => ['int', 'dstKey'=>'string', 'key1'=>'string', '...other_keys='=>'string'],
'RedisCluster::time' => ['array'],
'RedisCluster::ttl' => ['int', 'key'=>'string'],
'RedisCluster::type' => ['int', 'key'=>'string'],
'RedisCluster::unlink' => ['int', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::unSubscribe' => ['', 'channels'=>'', '...other_channels='=>''],
'RedisCluster::unwatch' => [''],
'RedisCluster::watch' => ['void', 'key'=>'string', '...other_keys='=>'string'],
'RedisCluster::xack' => ['', 'str_key'=>'string', 'str_group'=>'string', 'arr_ids'=>'array'],
'RedisCluster::xadd' => ['', 'str_key'=>'string', 'str_id'=>'string', 'arr_fields'=>'array', 'i_maxlen='=>'', 'boo_approximate='=>''],
'RedisCluster::xclaim' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_consumer'=>'string', 'i_min_idle'=>'', 'arr_ids'=>'array', 'arr_opts='=>'array'],
'RedisCluster::xdel' => ['', 'str_key'=>'string', 'arr_ids'=>'array'],
'RedisCluster::xgroup' => ['', 'str_operation'=>'string', 'str_key='=>'string', 'str_arg1='=>'', 'str_arg2='=>'', 'str_arg3='=>''],
'RedisCluster::xinfo' => ['', 'str_cmd'=>'string', 'str_key='=>'string', 'str_group='=>'string'],
'RedisCluster::xlen' => ['', 'key'=>''],
'RedisCluster::xpending' => ['', 'str_key'=>'string', 'str_group'=>'string', 'str_start='=>'', 'str_end='=>'', 'i_count='=>'', 'str_consumer='=>'string'],
'RedisCluster::xrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'RedisCluster::xread' => ['', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'RedisCluster::xreadgroup' => ['', 'str_group'=>'string', 'str_consumer'=>'string', 'arr_streams'=>'array', 'i_count='=>'', 'i_block='=>''],
'RedisCluster::xrevrange' => ['', 'str_key'=>'string', 'str_start'=>'', 'str_end'=>'', 'i_count='=>''],
'RedisCluster::xtrim' => ['', 'str_key'=>'string', 'i_maxlen'=>'', 'boo_approximate='=>''],
'RedisCluster::zAdd' => ['int', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'Redis::zAdd\'1' => ['int', 'options'=>'array', 'key'=>'string', 'score1'=>'float', 'value1'=>'string', 'score2='=>'float', 'value2='=>'string', 'scoreN='=>'float', 'valueN='=>'string'],
'RedisCluster::zCard' => ['int', 'key'=>'string'],
'RedisCluster::zCount' => ['int', 'key'=>'string', 'start'=>'string', 'end'=>'string'],
'RedisCluster::zIncrBy' => ['float', 'key'=>'string', 'value'=>'float', 'member'=>'string'],
'RedisCluster::zInterStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'RedisCluster::zLexCount' => ['int', 'key'=>'string', 'min'=>'int', 'max'=>'int'],
'RedisCluster::zRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscores='=>'bool'],
'RedisCluster::zRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'RedisCluster::zRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'RedisCluster::zRank' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zRem' => ['int', 'key'=>'string', 'member1'=>'string', '...other_members='=>'string'],
'RedisCluster::zRemRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int'],
'RedisCluster::zRemRangeByRank' => ['int', 'key'=>'string', 'start'=>'int', 'end'=>'int'],
'RedisCluster::zRemRangeByScore' => ['int', 'key'=>'string', 'start'=>'float|string', 'end'=>'float|string'],
'RedisCluster::zRevRange' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'withscore='=>'bool'],
'RedisCluster::zRevRangeByLex' => ['array', 'key'=>'string', 'min'=>'int', 'max'=>'int', 'offset='=>'int', 'limit='=>'int'],
'RedisCluster::zRevRangeByScore' => ['array', 'key'=>'string', 'start'=>'int', 'end'=>'int', 'options='=>'array'],
'RedisCluster::zRevRank' => ['int', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zScan' => ['array|false', 'key'=>'string', '&iterator'=>'int', 'pattern='=>'string', 'count='=>'int'],
'RedisCluster::zScore' => ['float', 'key'=>'string', 'member'=>'string'],
'RedisCluster::zUnionStore' => ['int', 'Output'=>'string', 'ZSetKeys'=>'array', 'Weights='=>'?array', 'aggregateFunction='=>'string'],
'Reflection::export' => ['?string', 'r'=>'reflector', 'return='=>'bool'],
'Reflection::getModifierNames' => ['array', 'modifiers'=>'int'],
'ReflectionClass::__clone' => ['void'],
'ReflectionClass::__construct' => ['void', 'argument'=>'object|class-string'],
'ReflectionClass::__toString' => ['string'],
'ReflectionClass::export' => ['?string', 'argument'=>'string|object', 'return='=>'bool'],
'ReflectionClass::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionClass::getConstants' => ['array<string,mixed>'],
'ReflectionClass::getConstructor' => ['?ReflectionMethod'],
'ReflectionClass::getDefaultProperties' => ['array'],
'ReflectionClass::getDocComment' => ['string|false'],
'ReflectionClass::getEndLine' => ['int|false'],
'ReflectionClass::getExtension' => ['?ReflectionExtension'],
'ReflectionClass::getExtensionName' => ['string|false'],
'ReflectionClass::getFileName' => ['string|false'],
'ReflectionClass::getInterfaceNames' => ['class-string[]'],
'ReflectionClass::getInterfaces' => ['array<string, ReflectionClass>'],
'ReflectionClass::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionClass::getMethods' => ['ReflectionMethod[]', 'filter='=>'int'],
'ReflectionClass::getModifiers' => ['int'],
'ReflectionClass::getName' => ['class-string'],
'ReflectionClass::getNamespaceName' => ['string'],
'ReflectionClass::getParentClass' => ['ReflectionClass|false'],
'ReflectionClass::getProperties' => ['ReflectionProperty[]', 'filter='=>'int'],
'ReflectionClass::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionClass::getReflectionConstant' => ['ReflectionClassConstant|false', 'name'=>'string'],
'ReflectionClass::getReflectionConstants' => ['array<int,ReflectionClassConstant>'],
'ReflectionClass::getShortName' => ['string'],
'ReflectionClass::getStartLine' => ['int|false'],
'ReflectionClass::getStaticProperties' => ['ReflectionProperty[]'],
'ReflectionClass::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionClass::getTraitAliases' => ['array<string,string>|null'],
'ReflectionClass::getTraitNames' => ['array<int,string>|null'],
'ReflectionClass::getTraits' => ['array<string,ReflectionClass>'],
'ReflectionClass::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionClass::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionClass::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionClass::implementsInterface' => ['bool', 'interface_name'=>'string|ReflectionClass'],
'ReflectionClass::inNamespace' => ['bool'],
'ReflectionClass::isAbstract' => ['bool'],
'ReflectionClass::isAnonymous' => ['bool'],
'ReflectionClass::isCloneable' => ['bool'],
'ReflectionClass::isFinal' => ['bool'],
'ReflectionClass::isInstance' => ['bool', 'object'=>'object'],
'ReflectionClass::isInstantiable' => ['bool'],
'ReflectionClass::isInterface' => ['bool'],
'ReflectionClass::isInternal' => ['bool'],
'ReflectionClass::isIterable' => ['bool'],
'ReflectionClass::isIterateable' => ['bool'],
'ReflectionClass::isSubclassOf' => ['bool', 'class'=>'string|ReflectionClass'],
'ReflectionClass::isTrait' => ['bool'],
'ReflectionClass::isUserDefined' => ['bool'],
'ReflectionClass::newInstance' => ['object', '...args='=>'mixed'],
'ReflectionClass::newInstanceArgs' => ['object', 'args='=>'array<int,mixed>'],
'ReflectionClass::newInstanceWithoutConstructor' => ['object'],
'ReflectionClass::setStaticPropertyValue' => ['void', 'name'=>'string', 'value'=>'mixed'],
'ReflectionClassConstant::__construct' => ['void', 'class'=>'mixed', 'name'=>'string'],
'ReflectionClassConstant::__toString' => ['string'],
'ReflectionClassConstant::export' => ['string', 'class'=>'mixed', 'name'=>'string', 'return='=>'bool'],
'ReflectionClassConstant::getDeclaringClass' => ['ReflectionClass'],
'ReflectionClassConstant::getDocComment' => ['string|false'],
'ReflectionClassConstant::getModifiers' => ['int'],
'ReflectionClassConstant::getName' => ['string'],
'ReflectionClassConstant::getValue' => ['scalar|array<scalar>|null'],
'ReflectionClassConstant::isPrivate' => ['bool'],
'ReflectionClassConstant::isProtected' => ['bool'],
'ReflectionClassConstant::isPublic' => ['bool'],
'ReflectionExtension::__clone' => ['void'],
'ReflectionExtension::__construct' => ['void', 'name'=>'string'],
'ReflectionExtension::__toString' => ['string'],
'ReflectionExtension::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionExtension::getClasses' => ['array<string,ReflectionClass>'],
'ReflectionExtension::getClassNames' => ['array<int,string>'],
'ReflectionExtension::getConstants' => ['array<string,mixed>'],
'ReflectionExtension::getDependencies' => ['array<string,string>'],
'ReflectionExtension::getFunctions' => ['array<string,ReflectionFunction>'],
'ReflectionExtension::getINIEntries' => ['array<string,mixed>'],
'ReflectionExtension::getName' => ['string'],
'ReflectionExtension::getVersion' => ['string'],
'ReflectionExtension::info' => ['void'],
'ReflectionExtension::isPersistent' => ['bool'],
'ReflectionExtension::isTemporary' => ['bool'],
'ReflectionFunction::__construct' => ['void', 'name'=>'callable-string|Closure'],
'ReflectionFunction::__toString' => ['string'],
'ReflectionFunction::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionFunction::getClosure' => ['?Closure'],
'ReflectionFunction::getClosureScopeClass' => ['ReflectionClass'],
'ReflectionFunction::getClosureThis' => ['bool'],
'ReflectionFunction::getDocComment' => ['string|false'],
'ReflectionFunction::getEndLine' => ['int|false'],
'ReflectionFunction::getExtension' => ['?ReflectionExtension'],
'ReflectionFunction::getExtensionName' => ['string|false'],
'ReflectionFunction::getFileName' => ['string|false'],
'ReflectionFunction::getName' => ['callable-string'],
'ReflectionFunction::getNamespaceName' => ['string'],
'ReflectionFunction::getNumberOfParameters' => ['int'],
'ReflectionFunction::getNumberOfRequiredParameters' => ['int'],
'ReflectionFunction::getParameters' => ['array<int,ReflectionParameter>'],
'ReflectionFunction::getReturnType' => ['?ReflectionType'],
'ReflectionFunction::getShortName' => ['string'],
'ReflectionFunction::getStartLine' => ['int|false'],
'ReflectionFunction::getStaticVariables' => ['array'],
'ReflectionFunction::hasReturnType' => ['bool'],
'ReflectionFunction::inNamespace' => ['bool'],
'ReflectionFunction::invoke' => ['mixed', '...args='=>'mixed'],
'ReflectionFunction::invokeArgs' => ['mixed', 'args'=>'array'],
'ReflectionFunction::isClosure' => ['bool'],
'ReflectionFunction::isDeprecated' => ['bool'],
'ReflectionFunction::isDisabled' => ['bool'],
'ReflectionFunction::isGenerator' => ['bool'],
'ReflectionFunction::isInternal' => ['bool'],
'ReflectionFunction::isUserDefined' => ['bool'],
'ReflectionFunction::isVariadic' => ['bool'],
'ReflectionFunction::returnsReference' => ['bool'],
'ReflectionFunctionAbstract::__clone' => ['void'],
'ReflectionFunctionAbstract::__toString' => ['string'],
'ReflectionFunctionAbstract::export' => ['?string'],
'ReflectionFunctionAbstract::getClosureScopeClass' => ['ReflectionClass|null'],
'ReflectionFunctionAbstract::getClosureThis' => ['object|null'],
'ReflectionFunctionAbstract::getDocComment' => ['string|false'],
'ReflectionFunctionAbstract::getEndLine' => ['int|false'],
'ReflectionFunctionAbstract::getExtension' => ['ReflectionExtension'],
'ReflectionFunctionAbstract::getExtensionName' => ['string'],
'ReflectionFunctionAbstract::getFileName' => ['string|false'],
'ReflectionFunctionAbstract::getName' => ['string'],
'ReflectionFunctionAbstract::getNamespaceName' => ['string'],
'ReflectionFunctionAbstract::getNumberOfParameters' => ['int'],
'ReflectionFunctionAbstract::getNumberOfRequiredParameters' => ['int'],
'ReflectionFunctionAbstract::getParameters' => ['array<int,ReflectionParameter>'],
'ReflectionFunctionAbstract::getReturnType' => ['?ReflectionType'],
'ReflectionFunctionAbstract::getShortName' => ['string'],
'ReflectionFunctionAbstract::getStartLine' => ['int|false'],
'ReflectionFunctionAbstract::getStaticVariables' => ['array'],
'ReflectionFunctionAbstract::hasReturnType' => ['bool'],
'ReflectionFunctionAbstract::inNamespace' => ['bool'],
'ReflectionFunctionAbstract::isClosure' => ['bool'],
'ReflectionFunctionAbstract::isDeprecated' => ['bool'],
'ReflectionFunctionAbstract::isGenerator' => ['bool'],
'ReflectionFunctionAbstract::isInternal' => ['bool'],
'ReflectionFunctionAbstract::isUserDefined' => ['bool'],
'ReflectionFunctionAbstract::isVariadic' => ['bool'],
'ReflectionFunctionAbstract::returnsReference' => ['bool'],
'ReflectionGenerator::__construct' => ['void', 'generator'=>'object'],
'ReflectionGenerator::getExecutingFile' => ['string'],
'ReflectionGenerator::getExecutingGenerator' => ['Generator'],
'ReflectionGenerator::getExecutingLine' => ['int'],
'ReflectionGenerator::getFunction' => ['ReflectionFunctionAbstract'],
'ReflectionGenerator::getThis' => ['?object'],
'ReflectionGenerator::getTrace' => ['array', 'options='=>'int'],
'ReflectionMethod::__construct' => ['void', 'class'=>'string|object', 'name'=>'string'],
'ReflectionMethod::__construct\'1' => ['void', 'class_method'=>'string'],
'ReflectionMethod::__toString' => ['string'],
'ReflectionMethod::export' => ['?string', 'class'=>'string', 'name'=>'string', 'return='=>'bool'],
'ReflectionMethod::getClosure' => ['?Closure', 'object='=>'object'],
'ReflectionMethod::getClosureScopeClass' => ['ReflectionClass'],
'ReflectionMethod::getClosureThis' => ['object'],
'ReflectionMethod::getDeclaringClass' => ['ReflectionClass'],
'ReflectionMethod::getDocComment' => ['false|string'],
'ReflectionMethod::getEndLine' => ['false|int'],
'ReflectionMethod::getExtension' => ['ReflectionExtension'],
'ReflectionMethod::getExtensionName' => ['string'],
'ReflectionMethod::getFileName' => ['false|string'],
'ReflectionMethod::getModifiers' => ['int'],
'ReflectionMethod::getName' => ['string'],
'ReflectionMethod::getNamespaceName' => ['string'],
'ReflectionMethod::getNumberOfParameters' => ['int'],
'ReflectionMethod::getNumberOfRequiredParameters' => ['int'],
'ReflectionMethod::getParameters' => ['array<int,\ReflectionParameter>'],
'ReflectionMethod::getPrototype' => ['ReflectionMethod'],
'ReflectionMethod::getReturnType' => ['?ReflectionType'],
'ReflectionMethod::getShortName' => ['string'],
'ReflectionMethod::getStartLine' => ['false|int'],
'ReflectionMethod::getStaticVariables' => ['array'],
'ReflectionMethod::hasReturnType' => ['bool'],
'ReflectionMethod::inNamespace' => ['bool'],
'ReflectionMethod::invoke' => ['mixed', 'object'=>'?object', '...args='=>'mixed'],
'ReflectionMethod::invokeArgs' => ['mixed', 'object'=>'?object', 'args'=>'array'],
'ReflectionMethod::isAbstract' => ['bool'],
'ReflectionMethod::isClosure' => ['bool'],
'ReflectionMethod::isConstructor' => ['bool'],
'ReflectionMethod::isDeprecated' => ['bool'],
'ReflectionMethod::isDestructor' => ['bool'],
'ReflectionMethod::isFinal' => ['bool'],
'ReflectionMethod::isGenerator' => ['bool'],
'ReflectionMethod::isInternal' => ['bool'],
'ReflectionMethod::isPrivate' => ['bool'],
'ReflectionMethod::isProtected' => ['bool'],
'ReflectionMethod::isPublic' => ['bool'],
'ReflectionMethod::isStatic' => ['bool'],
'ReflectionMethod::isUserDefined' => ['bool'],
'ReflectionMethod::isVariadic' => ['bool'],
'ReflectionMethod::returnsReference' => ['bool'],
'ReflectionMethod::setAccessible' => ['void', 'visible'=>'bool'],
'ReflectionNamedType::__clone' => ['void'],
'ReflectionNamedType::__toString' => ['string'],
'ReflectionNamedType::allowsNull' => [''],
'ReflectionNamedType::getName' => ['string'],
'ReflectionNamedType::isBuiltin' => [''],
'ReflectionObject::__clone' => ['void'],
'ReflectionObject::__construct' => ['void', 'argument'=>'object'],
'ReflectionObject::__toString' => ['string'],
'ReflectionObject::export' => ['?string', 'argument'=>'object', 'return='=>'bool'],
'ReflectionObject::getConstant' => ['mixed', 'name'=>'string'],
'ReflectionObject::getConstants' => ['array<string,mixed>'],
'ReflectionObject::getConstructor' => ['?ReflectionMethod'],
'ReflectionObject::getDefaultProperties' => ['array'],
'ReflectionObject::getDocComment' => ['false|string'],
'ReflectionObject::getEndLine' => ['false|int'],
'ReflectionObject::getExtension' => ['?ReflectionExtension'],
'ReflectionObject::getExtensionName' => ['false|string'],
'ReflectionObject::getFileName' => ['false|string'],
'ReflectionObject::getInterfaceNames' => ['class-string[]'],
'ReflectionObject::getInterfaces' => ['array<string,\ReflectionClass>'],
'ReflectionObject::getMethod' => ['ReflectionMethod', 'name'=>'string'],
'ReflectionObject::getMethods' => ['ReflectionMethod[]', 'filter='=>'int'],
'ReflectionObject::getModifiers' => ['int'],
'ReflectionObject::getName' => ['string'],
'ReflectionObject::getNamespaceName' => ['string'],
'ReflectionObject::getParentClass' => ['ReflectionClass|false'],
'ReflectionObject::getProperties' => ['ReflectionProperty[]', 'filter='=>'int'],
'ReflectionObject::getProperty' => ['ReflectionProperty', 'name'=>'string'],
'ReflectionObject::getReflectionConstant' => ['ReflectionClassConstant', 'name'=>'string'],
'ReflectionObject::getReflectionConstants' => ['array<int,\ReflectionClassConstant>'],
'ReflectionObject::getShortName' => ['string'],
'ReflectionObject::getStartLine' => ['false|int'],
'ReflectionObject::getStaticProperties' => ['ReflectionProperty[]'],
'ReflectionObject::getStaticPropertyValue' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'ReflectionObject::getTraitAliases' => ['array<string,string>'],
'ReflectionObject::getTraitNames' => ['array<int,string>'],
'ReflectionObject::getTraits' => ['array<string,\ReflectionClass>'],
'ReflectionObject::hasConstant' => ['bool', 'name'=>'string'],
'ReflectionObject::hasMethod' => ['bool', 'name'=>'string'],
'ReflectionObject::hasProperty' => ['bool', 'name'=>'string'],
'ReflectionObject::implementsInterface' => ['bool', 'interface_name'=>'ReflectionClass|string'],
'ReflectionObject::inNamespace' => ['bool'],
'ReflectionObject::isAbstract' => ['bool'],
'ReflectionObject::isAnonymous' => ['bool'],
'ReflectionObject::isCloneable' => ['bool'],
'ReflectionObject::isFinal' => ['bool'],
'ReflectionObject::isInstance' => ['bool', 'object'=>'object'],
'ReflectionObject::isInstantiable' => ['bool'],
'ReflectionObject::isInterface' => ['bool'],
'ReflectionObject::isInternal' => ['bool'],
'ReflectionObject::isIterable' => ['bool'],
'ReflectionObject::isIterateable' => ['bool'],
'ReflectionObject::isSubclassOf' => ['bool', 'class'=>'ReflectionClass|string'],
'ReflectionObject::isTrait' => ['bool'],
'ReflectionObject::isUserDefined' => ['bool'],
'ReflectionObject::newInstance' => ['object', 'args='=>'mixed', '...args='=>'array'],
'ReflectionObject::newInstanceArgs' => ['object', 'args='=>'array'],
'ReflectionObject::newInstanceWithoutConstructor' => ['object'],
'ReflectionObject::setStaticPropertyValue' => ['void', 'name'=>'string', 'value'=>'string'],
'ReflectionParameter::__clone' => ['void'],
'ReflectionParameter::__construct' => ['void', 'function'=>'', 'parameter'=>''],
'ReflectionParameter::__toString' => ['string'],
'ReflectionParameter::allowsNull' => ['bool'],
'ReflectionParameter::canBePassedByValue' => ['bool'],
'ReflectionParameter::export' => ['?string', 'function'=>'string', 'parameter'=>'string', 'return='=>'bool'],
'ReflectionParameter::getClass' => ['?ReflectionClass'],
'ReflectionParameter::getDeclaringClass' => ['?ReflectionClass'],
'ReflectionParameter::getDeclaringFunction' => ['ReflectionFunctionAbstract'],
'ReflectionParameter::getDefaultValue' => ['mixed'],
'ReflectionParameter::getDefaultValueConstantName' => ['?string'],
'ReflectionParameter::getName' => ['string'],
'ReflectionParameter::getPosition' => ['int'],
'ReflectionParameter::getType' => ['?ReflectionType'],
'ReflectionParameter::hasType' => ['bool'],
'ReflectionParameter::isArray' => ['bool'],
'ReflectionParameter::isCallable' => ['?bool'],
'ReflectionParameter::isDefaultValueAvailable' => ['bool'],
'ReflectionParameter::isDefaultValueConstant' => ['bool'],
'ReflectionParameter::isOptional' => ['bool'],
'ReflectionParameter::isPassedByReference' => ['bool'],
'ReflectionParameter::isVariadic' => ['bool'],
'ReflectionProperty::__clone' => ['void'],
'ReflectionProperty::__construct' => ['void', 'class'=>'', 'name'=>'string'],
'ReflectionProperty::__toString' => ['string'],
'ReflectionProperty::export' => ['?string', 'class'=>'mixed', 'name'=>'string', 'return='=>'bool'],
'ReflectionProperty::getDeclaringClass' => ['ReflectionClass'],
'ReflectionProperty::getDocComment' => ['string|false'],
'ReflectionProperty::getModifiers' => ['int'],
'ReflectionProperty::getName' => ['string'],
'ReflectionProperty::getValue' => ['mixed', 'object='=>'object'],
'ReflectionProperty::isDefault' => ['bool'],
'ReflectionProperty::isPrivate' => ['bool'],
'ReflectionProperty::isProtected' => ['bool'],
'ReflectionProperty::isPublic' => ['bool'],
'ReflectionProperty::isStatic' => ['bool'],
'ReflectionProperty::setAccessible' => ['void', 'visible'=>'bool'],
'ReflectionProperty::setValue' => ['void', 'object'=>'null|object', 'value'=>''],
'ReflectionProperty::setValue\'1' => ['void', 'value'=>''],
'ReflectionType::__clone' => ['void'],
'ReflectionType::__toString' => ['string'],
'ReflectionType::allowsNull' => ['bool'],
'ReflectionType::getName' => ['string'],
'ReflectionType::isBuiltin' => ['bool'],
'ReflectionZendExtension::__clone' => ['void'],
'ReflectionZendExtension::__construct' => ['void', 'name'=>'string'],
'ReflectionZendExtension::__toString' => ['string'],
'ReflectionZendExtension::export' => ['?string', 'name'=>'string', 'return='=>'bool'],
'ReflectionZendExtension::getAuthor' => ['string'],
'ReflectionZendExtension::getCopyright' => ['string'],
'ReflectionZendExtension::getName' => ['string'],
'ReflectionZendExtension::getURL' => ['string'],
'ReflectionZendExtension::getVersion' => ['string'],
'Reflector::__toString' => ['string'],
'Reflector::export' => ['?string'],
'RegexIterator::__construct' => ['void', 'iterator'=>'Iterator', 'regex'=>'string', 'mode='=>'int', 'flags='=>'int', 'preg_flags='=>'int'],
'RegexIterator::accept' => ['bool'],
'RegexIterator::current' => ['mixed'],
'RegexIterator::getFlags' => ['int'],
'RegexIterator::getInnerIterator' => ['Iterator'],
'RegexIterator::getMode' => ['int'],
'RegexIterator::getPregFlags' => ['int'],
'RegexIterator::getRegex' => ['string'],
'RegexIterator::key' => ['mixed'],
'RegexIterator::next' => ['void'],
'RegexIterator::rewind' => ['void'],
'RegexIterator::setFlags' => ['void', 'new_flags'=>'int'],
'RegexIterator::setMode' => ['void', 'new_mode'=>'int'],
'RegexIterator::setPregFlags' => ['void', 'new_flags'=>'int'],
'RegexIterator::valid' => ['bool'],
'register_event_handler' => ['bool', 'event_handler_func'=>'string', 'handler_register_name'=>'string', 'event_type_mask'=>'int'],
'register_shutdown_function' => ['void', 'function'=>'callable(mixed...):void', '...parameter='=>'mixed'],
'register_tick_function' => ['bool', 'function'=>'callable():void', '...args='=>'mixed'],
'rename' => ['bool', 'old_name'=>'string', 'new_name'=>'string', 'context='=>'resource'],
'rename_function' => ['bool', 'original_name'=>'string', 'new_name'=>'string'],
'reset' => ['mixed|false', '&rw_array_arg'=>'array'],
'ResourceBundle::__construct' => ['void', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'ResourceBundle::count' => ['int'],
'ResourceBundle::create' => ['?ResourceBundle', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'ResourceBundle::get' => ['', 'index'=>'string|int', 'fallback='=>'bool'],
'ResourceBundle::getErrorCode' => ['int'],
'ResourceBundle::getErrorMessage' => ['string'],
'ResourceBundle::getLocales' => ['array', 'bundlename'=>'string'],
'resourcebundle_count' => ['int', 'r'=>'ResourceBundle'],
'resourcebundle_create' => ['?ResourceBundle', 'locale'=>'string', 'bundlename'=>'string', 'fallback='=>'bool'],
'resourcebundle_get' => ['mixed|null', 'r'=>'ResourceBundle', 'index'=>'string|int', 'fallback='=>'bool'],
'resourcebundle_get_error_code' => ['int', 'r'=>'ResourceBundle'],
'resourcebundle_get_error_message' => ['string', 'r'=>'ResourceBundle'],
'resourcebundle_locales' => ['array', 'bundlename'=>'string'],
'restore_error_handler' => ['bool'],
'restore_exception_handler' => ['bool'],
'restore_include_path' => ['void'],
'rewind' => ['bool', 'fp'=>'resource'],
'rewinddir' => ['void', 'dir_handle='=>'resource'],
'rmdir' => ['bool', 'dirname'=>'string', 'context='=>'resource'],
'round' => ['float', 'number'=>'float', 'precision='=>'int', 'mode='=>'int'],
'rpm_close' => ['bool', 'rpmr'=>'resource'],
'rpm_get_tag' => ['mixed', 'rpmr'=>'resource', 'tagnum'=>'int'],
'rpm_is_valid' => ['bool', 'filename'=>'string'],
'rpm_open' => ['resource', 'filename'=>'string'],
'rpm_version' => ['string'],
'rrd_create' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_disconnect' => ['void'],
'rrd_error' => ['string'],
'rrd_fetch' => ['array', 'filename'=>'string', 'options'=>'array'],
'rrd_first' => ['int|false', 'file'=>'string', 'raaindex='=>'int'],
'rrd_graph' => ['array|false', 'filename'=>'string', 'options'=>'array'],
'rrd_info' => ['array|false', 'filename'=>'string'],
'rrd_last' => ['int', 'filename'=>'string'],
'rrd_lastupdate' => ['array|false', 'filename'=>'string'],
'rrd_restore' => ['bool', 'xml_file'=>'string', 'rrd_file'=>'string', 'options='=>'array'],
'rrd_tune' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_update' => ['bool', 'filename'=>'string', 'options'=>'array'],
'rrd_version' => ['string'],
'rrd_xport' => ['array|false', 'options'=>'array'],
'rrdc_disconnect' => ['void'],
'RRDCreator::__construct' => ['void', 'path'=>'string', 'starttime='=>'string', 'step='=>'int'],
'RRDCreator::addArchive' => ['void', 'description'=>'string'],
'RRDCreator::addDataSource' => ['void', 'description'=>'string'],
'RRDCreator::save' => ['bool'],
'RRDGraph::__construct' => ['void', 'path'=>'string'],
'RRDGraph::save' => ['array|false'],
'RRDGraph::saveVerbose' => ['array|false'],
'RRDGraph::setOptions' => ['void', 'options'=>'array'],
'RRDUpdater::__construct' => ['void', 'path'=>'string'],
'RRDUpdater::update' => ['bool', 'values'=>'array', 'time='=>'string'],
'rsort' => ['bool', '&rw_array_arg'=>'array', 'sort_flags='=>'int'],
'rtrim' => ['string', 'str'=>'string', 'character_mask='=>'string'],
'runkit_class_adopt' => ['bool', 'classname'=>'string', 'parentname'=>'string'],
'runkit_class_emancipate' => ['bool', 'classname'=>'string'],
'runkit_constant_add' => ['bool', 'constname'=>'string', 'value'=>'mixed'],
'runkit_constant_redefine' => ['bool', 'constname'=>'string', 'newvalue'=>'mixed'],
'runkit_constant_remove' => ['bool', 'constname'=>'string'],
'runkit_function_add' => ['bool', 'funcname'=>'string', 'arglist'=>'string', 'code'=>'string', 'doccomment='=>'?string'],
'runkit_function_add\'1' => ['bool', 'funcname'=>'string', 'closure'=>'Closure', 'doccomment='=>'?string'],
'runkit_function_copy' => ['bool', 'funcname'=>'string', 'targetname'=>'string'],
'runkit_function_redefine' => ['bool', 'funcname'=>'string', 'arglist'=>'string', 'code'=>'string', 'doccomment='=>'?string'],
'runkit_function_redefine\'1' => ['bool', 'funcname'=>'string', 'closure'=>'Closure', 'doccomment='=>'?string'],
'runkit_function_remove' => ['bool', 'funcname'=>'string'],
'runkit_function_rename' => ['bool', 'funcname'=>'string', 'newname'=>'string'],
'runkit_import' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'runkit_lint' => ['bool', 'code'=>'string'],
'runkit_lint_file' => ['bool', 'filename'=>'string'],
'runkit_method_add' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_add\'1' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'closure'=>'Closure', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_copy' => ['bool', 'dclass'=>'string', 'dmethod'=>'string', 'sclass'=>'string', 'smethod='=>'string'],
'runkit_method_redefine' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'args'=>'string', 'code'=>'string', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_redefine\'1' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'closure'=>'Closure', 'flags='=>'int', 'doccomment='=>'?string'],
'runkit_method_remove' => ['bool', 'classname'=>'string', 'methodname'=>'string'],
'runkit_method_rename' => ['bool', 'classname'=>'string', 'methodname'=>'string', 'newname'=>'string'],
'runkit_return_value_used' => ['bool'],
'Runkit_Sandbox::__construct' => ['void', 'options='=>'array'],
'runkit_sandbox_output_handler' => ['mixed', 'sandbox'=>'object', 'callback='=>'mixed'],
'Runkit_Sandbox_Parent' => [''],
'Runkit_Sandbox_Parent::__construct' => ['void'],
'runkit_superglobals' => ['array'],
'RuntimeException::__clone' => ['void'],
'RuntimeException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?RuntimeException'],
'RuntimeException::__toString' => ['string'],
'RuntimeException::getCode' => ['int'],
'RuntimeException::getFile' => ['string'],
'RuntimeException::getLine' => ['int'],
'RuntimeException::getMessage' => ['string'],
'RuntimeException::getPrevious' => ['Throwable|RuntimeException|null'],
'RuntimeException::getTrace' => ['array'],
'RuntimeException::getTraceAsString' => ['string'],
'SAMConnection::commit' => ['bool'],
'SAMConnection::connect' => ['bool', 'protocol'=>'string', 'properties='=>'array'],
'SAMConnection::disconnect' => ['bool'],
'SAMConnection::errno' => ['int'],
'SAMConnection::error' => ['string'],
'SAMConnection::isConnected' => ['bool'],
'SAMConnection::peek' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::peekAll' => ['array', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::receive' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::remove' => ['SAMMessage', 'target'=>'string', 'properties='=>'array'],
'SAMConnection::rollback' => ['bool'],
'SAMConnection::send' => ['string', 'target'=>'string', 'msg'=>'sammessage', 'properties='=>'array'],
'SAMConnection::setDebug' => ['', 'switch'=>'bool'],
'SAMConnection::subscribe' => ['string', 'targettopic'=>'string'],
'SAMConnection::unsubscribe' => ['bool', 'subscriptionid'=>'string', 'targettopic='=>'string'],
'SAMMessage::body' => ['string'],
'SAMMessage::header' => ['object'],
'sapi_windows_cp_conv' => ['string', 'in_codepage'=>'int|string', 'out_codepage'=>'int|string', 'subject'=>'string'],
'sapi_windows_cp_get' => ['int'],
'sapi_windows_cp_is_utf8' => ['bool'],
'sapi_windows_cp_set' => ['bool', 'code_page'=>'int'],
'sapi_windows_vt100_support' => ['bool', 'stream'=>'resource', 'enable='=>'bool'],
'Saxon\SaxonProcessor::__construct' => ['void', 'license='=>'bool', 'cwd='=>'string'],
'Saxon\SaxonProcessor::createAtomicValue' => ['Saxon\XdmValue', 'primitive_type_val'=>'bool|float|int|string'],
'Saxon\SaxonProcessor::newSchemaValidator' => ['Saxon\SchemaValidator'],
'Saxon\SaxonProcessor::newXPathProcessor' => ['Saxon\XPathProcessor'],
'Saxon\SaxonProcessor::newXQueryProcessor' => ['Saxon\XQueryProcessor'],
'Saxon\SaxonProcessor::newXsltProcessor' => ['Saxon\XsltProcessor'],
'Saxon\SaxonProcessor::parseXmlFromFile' => ['Saxon\XdmNode', 'fileName'=>'string'],
'Saxon\SaxonProcessor::parseXmlFromString' => ['Saxon\XdmNode', 'value'=>'string'],
'Saxon\SaxonProcessor::registerPHPFunctions' => ['void', 'library'=>'string'],
'Saxon\SaxonProcessor::setConfigurationProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\SaxonProcessor::setcwd' => ['void', 'cwd'=>'string'],
'Saxon\SaxonProcessor::setResourceDirectory' => ['void', 'dir'=>'string'],
'Saxon\SaxonProcessor::version' => ['string'],
'Saxon\SchemaValidator::clearParameters' => ['void'],
'Saxon\SchemaValidator::clearProperties' => ['void'],
'Saxon\SchemaValidator::exceptionClear' => ['void'],
'Saxon\SchemaValidator::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\SchemaValidator::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\SchemaValidator::getExceptionCount' => ['int'],
'Saxon\SchemaValidator::getValidationReport' => ['Saxon\XdmNode'],
'Saxon\SchemaValidator::registerSchemaFromFile' => ['void', 'fileName'=>'string'],
'Saxon\SchemaValidator::registerSchemaFromString' => ['void', 'schemaStr'=>'string'],
'Saxon\SchemaValidator::setOutputFile' => ['void', 'fileName'=>'string'],
'Saxon\SchemaValidator::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\SchemaValidator::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\SchemaValidator::setSourceNode' => ['void', 'node'=>'Saxon\XdmNode'],
'Saxon\SchemaValidator::validate' => ['void', 'filename='=>'?string'],
'Saxon\SchemaValidator::validateToNode' => ['Saxon\XdmNode', 'filename='=>'?string'],
'Saxon\XdmAtomicValue::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmAtomicValue::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmAtomicValue::getBooleanValue' => ['bool'],
'Saxon\XdmAtomicValue::getDoubleValue' => ['float'],
'Saxon\XdmAtomicValue::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmAtomicValue::getLongValue' => ['int'],
'Saxon\XdmAtomicValue::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmAtomicValue::getStringValue' => ['string'],
'Saxon\XdmAtomicValue::isAtomic' => ['true'],
'Saxon\XdmAtomicValue::isNode' => ['bool'],
'Saxon\XdmAtomicValue::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmAtomicValue::size' => ['int'],
'Saxon\XdmItem::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmItem::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmItem::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmItem::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmItem::getStringValue' => ['string'],
'Saxon\XdmItem::isAtomic' => ['bool'],
'Saxon\XdmItem::isNode' => ['bool'],
'Saxon\XdmItem::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmItem::size' => ['int'],
'Saxon\XdmNode::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmNode::getAtomicValue' => ['?Saxon\XdmAtomicValue'],
'Saxon\XdmNode::getAttributeCount' => ['int'],
'Saxon\XdmNode::getAttributeNode' => ['?Saxon\XdmNode', 'index'=>'int'],
'Saxon\XdmNode::getAttributeValue' => ['?string', 'index'=>'int'],
'Saxon\XdmNode::getChildCount' => ['int'],
'Saxon\XdmNode::getChildNode' => ['?Saxon\XdmNode', 'index'=>'int'],
'Saxon\XdmNode::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmNode::getNodeKind' => ['int'],
'Saxon\XdmNode::getNodeName' => ['string'],
'Saxon\XdmNode::getNodeValue' => ['?Saxon\XdmNode'],
'Saxon\XdmNode::getParent' => ['?Saxon\XdmNode'],
'Saxon\XdmNode::getStringValue' => ['string'],
'Saxon\XdmNode::isAtomic' => ['false'],
'Saxon\XdmNode::isNode' => ['bool'],
'Saxon\XdmNode::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmNode::size' => ['int'],
'Saxon\XdmValue::addXdmItem' => ['', 'item'=>'Saxon\XdmItem'],
'Saxon\XdmValue::getHead' => ['Saxon\XdmItem'],
'Saxon\XdmValue::itemAt' => ['Saxon\XdmItem', 'index'=>'int'],
'Saxon\XdmValue::size' => ['int'],
'Saxon\XPathProcessor::clearParameters' => ['void'],
'Saxon\XPathProcessor::clearProperties' => ['void'],
'Saxon\XPathProcessor::declareNamespace' => ['void', 'prefix'=>'', 'namespace'=>''],
'Saxon\XPathProcessor::effectiveBooleanValue' => ['bool', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::evaluate' => ['Saxon\XdmValue', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::evaluateSingle' => ['Saxon\XdmItem', 'xpathStr'=>'string'],
'Saxon\XPathProcessor::exceptionClear' => ['void'],
'Saxon\XPathProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XPathProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XPathProcessor::getExceptionCount' => ['int'],
'Saxon\XPathProcessor::setBaseURI' => ['void', 'uri'=>'string'],
'Saxon\XPathProcessor::setContextFile' => ['void', 'fileName'=>'string'],
'Saxon\XPathProcessor::setContextItem' => ['void', 'item'=>'Saxon\XdmItem'],
'Saxon\XPathProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XPathProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XQueryProcessor::clearParameters' => ['void'],
'Saxon\XQueryProcessor::clearProperties' => ['void'],
'Saxon\XQueryProcessor::declareNamespace' => ['void', 'prefix'=>'string', 'namespace'=>'string'],
'Saxon\XQueryProcessor::exceptionClear' => ['void'],
'Saxon\XQueryProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XQueryProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XQueryProcessor::getExceptionCount' => ['int'],
'Saxon\XQueryProcessor::runQueryToFile' => ['void', 'outfilename'=>'string'],
'Saxon\XQueryProcessor::runQueryToString' => ['?string'],
'Saxon\XQueryProcessor::runQueryToValue' => ['?Saxon\XdmValue'],
'Saxon\XQueryProcessor::setContextItem' => ['void', 'obj'=>'Saxon\XdmAtomicValue|Saxon\XdmItem|Saxon\XdmNode|Saxon\XdmValue'],
'Saxon\XQueryProcessor::setContextItemFromFile' => ['void', 'fileName'=>'string'],
'Saxon\XQueryProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XQueryProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XQueryProcessor::setQueryBaseURI' => ['void', 'uri'=>'string'],
'Saxon\XQueryProcessor::setQueryContent' => ['void', 'str'=>'string'],
'Saxon\XQueryProcessor::setQueryFile' => ['void', 'filename'=>'string'],
'Saxon\XQueryProcessor::setQueryItem' => ['void', 'item'=>'Saxon\XdmItem'],
'Saxon\XsltProcessor::clearParameters' => ['void'],
'Saxon\XsltProcessor::clearProperties' => ['void'],
'Saxon\XsltProcessor::compileFromFile' => ['void', 'fileName'=>'string'],
'Saxon\XsltProcessor::compileFromString' => ['void', 'str'=>'string'],
'Saxon\XsltProcessor::compileFromValue' => ['void', 'node'=>'Saxon\XdmNode'],
'Saxon\XsltProcessor::exceptionClear' => ['void'],
'Saxon\XsltProcessor::getErrorCode' => ['string', 'i'=>'int'],
'Saxon\XsltProcessor::getErrorMessage' => ['string', 'i'=>'int'],
'Saxon\XsltProcessor::getExceptionCount' => ['int'],
'Saxon\XsltProcessor::setOutputFile' => ['void', 'fileName'=>'string'],
'Saxon\XsltProcessor::setParameter' => ['void', 'name'=>'string', 'value'=>'Saxon\XdmValue'],
'Saxon\XsltProcessor::setProperty' => ['void', 'name'=>'string', 'value'=>'string'],
'Saxon\XsltProcessor::setSourceFromFile' => ['void', 'filename'=>'string'],
'Saxon\XsltProcessor::setSourceFromXdmValue' => ['void', 'value'=>'Saxon\XdmValue'],
'Saxon\XsltProcessor::transformFileToFile' => ['void', 'sourceFileName'=>'string', 'stylesheetFileName'=>'string', 'outputfileName'=>'string'],
'Saxon\XsltProcessor::transformFileToString' => ['?string', 'sourceFileName'=>'string', 'stylesheetFileName'=>'string'],
'Saxon\XsltProcessor::transformFileToValue' => ['Saxon\XdmValue', 'fileName'=>'string'],
'Saxon\XsltProcessor::transformToFile' => ['void'],
'Saxon\XsltProcessor::transformToString' => ['string'],
'Saxon\XsltProcessor::transformToValue' => ['?Saxon\XdmValue'],
'SCA::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SCA::getService' => ['', 'target'=>'string', 'binding='=>'string', 'config='=>'array'],
'SCA_LocalProxy::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SCA_SoapProxy::createDataObject' => ['SDO_DataObject', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'scalebarObj::convertToString' => ['string'],
'scalebarObj::free' => ['void'],
'scalebarObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'scalebarObj::setImageColor' => ['int', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'scalebarObj::updateFromString' => ['int', 'snippet'=>'string'],
'scandir' => ['array<int,string>|false', 'dir'=>'string', 'sorting_order='=>'int', 'context='=>'resource'],
'SDO_DAS_ChangeSummary::beginLogging' => [''],
'SDO_DAS_ChangeSummary::endLogging' => [''],
'SDO_DAS_ChangeSummary::getChangedDataObjects' => ['SDO_List'],
'SDO_DAS_ChangeSummary::getChangeType' => ['int', 'dataobject'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::getOldContainer' => ['SDO_DataObject', 'data_object'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::getOldValues' => ['SDO_List', 'data_object'=>'sdo_dataobject'],
'SDO_DAS_ChangeSummary::isLogging' => ['bool'],
'SDO_DAS_DataFactory::addPropertyToType' => ['', 'parent_type_namespace_uri'=>'string', 'parent_type_name'=>'string', 'property_name'=>'string', 'type_namespace_uri'=>'string', 'type_name'=>'string', 'options='=>'array'],
'SDO_DAS_DataFactory::addType' => ['', 'type_namespace_uri'=>'string', 'type_name'=>'string', 'options='=>'array'],
'SDO_DAS_DataFactory::getDataFactory' => ['SDO_DAS_DataFactory'],
'SDO_DAS_DataObject::getChangeSummary' => ['SDO_DAS_ChangeSummary'],
'SDO_DAS_Relational::__construct' => ['void', 'database_metadata'=>'array', 'application_root_type='=>'string', 'sdo_containment_references_metadata='=>'array'],
'SDO_DAS_Relational::applyChanges' => ['', 'database_handle'=>'pdo', 'root_data_object'=>'sdodataobject'],
'SDO_DAS_Relational::createRootDataObject' => ['SDODataObject'],
'SDO_DAS_Relational::executePreparedQuery' => ['SDODataObject', 'database_handle'=>'pdo', 'prepared_statement'=>'pdostatement', 'value_list'=>'array', 'column_specifier='=>'array'],
'SDO_DAS_Relational::executeQuery' => ['SDODataObject', 'database_handle'=>'pdo', 'sql_statement'=>'string', 'column_specifier='=>'array'],
'SDO_DAS_Setting::getListIndex' => ['int'],
'SDO_DAS_Setting::getPropertyIndex' => ['int'],
'SDO_DAS_Setting::getPropertyName' => ['string'],
'SDO_DAS_Setting::getValue' => [''],
'SDO_DAS_Setting::isSet' => ['bool'],
'SDO_DAS_XML::addTypes' => ['', 'xsd_file'=>'string'],
'SDO_DAS_XML::create' => ['SDO_DAS_XML', 'xsd_file='=>'mixed', 'key='=>'string'],
'SDO_DAS_XML::createDataObject' => ['SDO_DataObject', 'namespace_uri'=>'string', 'type_name'=>'string'],
'SDO_DAS_XML::createDocument' => ['SDO_DAS_XML_Document', 'document_element_name'=>'string', 'document_element_namespace_uri'=>'string', 'dataobject='=>'sdo_dataobject'],
'SDO_DAS_XML::loadFile' => ['SDO_XMLDocument', 'xml_file'=>'string'],
'SDO_DAS_XML::loadString' => ['SDO_DAS_XML_Document', 'xml_string'=>'string'],
'SDO_DAS_XML::saveFile' => ['', 'xdoc'=>'sdo_xmldocument', 'xml_file'=>'string', 'indent='=>'int'],
'SDO_DAS_XML::saveString' => ['string', 'xdoc'=>'sdo_xmldocument', 'indent='=>'int'],
'SDO_DAS_XML_Document::getRootDataObject' => ['SDO_DataObject'],
'SDO_DAS_XML_Document::getRootElementName' => ['string'],
'SDO_DAS_XML_Document::getRootElementURI' => ['string'],
'SDO_DAS_XML_Document::setEncoding' => ['', 'encoding'=>'string'],
'SDO_DAS_XML_Document::setXMLDeclaration' => ['', 'xmldeclatation'=>'bool'],
'SDO_DAS_XML_Document::setXMLVersion' => ['', 'xmlversion'=>'string'],
'SDO_DataFactory::create' => ['void', 'type_namespace_uri'=>'string', 'type_name'=>'string'],
'SDO_DataObject::clear' => ['void'],
'SDO_DataObject::createDataObject' => ['SDO_DataObject', 'identifier'=>''],
'SDO_DataObject::getContainer' => ['SDO_DataObject'],
'SDO_DataObject::getSequence' => ['SDO_Sequence'],
'SDO_DataObject::getTypeName' => ['string'],
'SDO_DataObject::getTypeNamespaceURI' => ['string'],
'SDO_Exception::getCause' => [''],
'SDO_List::insert' => ['void', 'value'=>'mixed', 'index='=>'int'],
'SDO_Model_Property::getContainingType' => ['SDO_Model_Type'],
'SDO_Model_Property::getDefault' => [''],
'SDO_Model_Property::getName' => ['string'],
'SDO_Model_Property::getType' => ['SDO_Model_Type'],
'SDO_Model_Property::isContainment' => ['bool'],
'SDO_Model_Property::isMany' => ['bool'],
'SDO_Model_ReflectionDataObject::__construct' => ['void', 'data_object'=>'sdo_dataobject'],
'SDO_Model_ReflectionDataObject::export' => ['mixed', 'rdo'=>'sdo_model_reflectiondataobject', 'return='=>'bool'],
'SDO_Model_ReflectionDataObject::getContainmentProperty' => ['SDO_Model_Property'],
'SDO_Model_ReflectionDataObject::getInstanceProperties' => ['array'],
'SDO_Model_ReflectionDataObject::getType' => ['SDO_Model_Type'],
'SDO_Model_Type::getBaseType' => ['SDO_Model_Type'],
'SDO_Model_Type::getName' => ['string'],
'SDO_Model_Type::getNamespaceURI' => ['string'],
'SDO_Model_Type::getProperties' => ['array'],
'SDO_Model_Type::getProperty' => ['SDO_Model_Property', 'identifier'=>''],
'SDO_Model_Type::isAbstractType' => ['bool'],
'SDO_Model_Type::isDataType' => ['bool'],
'SDO_Model_Type::isInstance' => ['bool', 'data_object'=>'sdo_dataobject'],
'SDO_Model_Type::isOpenType' => ['bool'],
'SDO_Model_Type::isSequencedType' => ['bool'],
'SDO_Sequence::getProperty' => ['SDO_Model_Property', 'sequence_index'=>'int'],
'SDO_Sequence::insert' => ['void', 'value'=>'mixed', 'sequenceindex='=>'int', 'propertyidentifier='=>'mixed'],
'SDO_Sequence::move' => ['void', 'toindex'=>'int', 'fromindex'=>'int'],
'SeasLog::__destruct' => ['void'],
'SeasLog::alert' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::analyzerCount' => ['mixed', 'level'=>'string', 'log_path='=>'string', 'key_word='=>'string'],
'SeasLog::analyzerDetail' => ['mixed', 'level'=>'string', 'log_path='=>'string', 'key_word='=>'string', 'start='=>'int', 'limit='=>'int', 'order='=>'int'],
'SeasLog::closeLoggerStream' => ['bool', 'model'=>'int', 'logger'=>'string'],
'SeasLog::critical' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::debug' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::emergency' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::error' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::flushBuffer' => ['bool'],
'SeasLog::getBasePath' => ['string'],
'SeasLog::getBuffer' => ['array'],
'SeasLog::getBufferEnabled' => ['bool'],
'SeasLog::getDatetimeFormat' => ['string'],
'SeasLog::getLastLogger' => ['string'],
'SeasLog::getRequestID' => ['string'],
'SeasLog::getRequestVariable' => ['bool', 'key'=>'int'],
'SeasLog::info' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::log' => ['bool', 'level'=>'string', 'message='=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::notice' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'SeasLog::setBasePath' => ['bool', 'base_path'=>'string'],
'SeasLog::setDatetimeFormat' => ['bool', 'format'=>'string'],
'SeasLog::setLogger' => ['bool', 'logger'=>'string'],
'SeasLog::setRequestID' => ['bool', 'request_id'=>'string'],
'SeasLog::setRequestVariable' => ['bool', 'key'=>'int', 'value'=>'string'],
'SeasLog::warning' => ['bool', 'message'=>'string', 'content='=>'array', 'logger='=>'string'],
'seaslog_get_author' => ['string'],
'seaslog_get_version' => ['string'],
'SeekableIterator::__construct' => ['void'],
'SeekableIterator::current' => ['mixed'],
'SeekableIterator::key' => ['int|string'],
'SeekableIterator::next' => ['void'],
'SeekableIterator::rewind' => ['void'],
'SeekableIterator::seek' => ['void', 'position'=>'int'],
'SeekableIterator::valid' => ['bool'],
'sem_acquire' => ['bool', 'sem_identifier'=>'resource', 'nowait='=>'bool'],
'sem_get' => ['resource|false', 'key'=>'int', 'max_acquire='=>'int', 'perm='=>'int', 'auto_release='=>'int'],
'sem_release' => ['bool', 'sem_identifier'=>'resource'],
'sem_remove' => ['bool', 'sem_identifier'=>'resource'],
'Serializable::__construct' => ['void'],
'Serializable::serialize' => ['?string'],
'Serializable::unserialize' => ['void', 'serialized'=>'string'],
'serialize' => ['string', 'variable'=>'mixed'],
'ServerRequest::withInput' => ['ServerRequest', 'input'=>'mixed'],
'ServerRequest::withoutParams' => ['ServerRequest', 'params'=>'int|string'],
'ServerRequest::withParam' => ['ServerRequest', 'key'=>'int|string', 'val'=>'mixed'],
'ServerRequest::withParams' => ['ServerRequest', 'params'=>'mixed'],
'ServerRequest::withUrl' => ['ServerRequest', 'url'=>'array'],
'ServerResponse::addHeader' => ['void', 'label'=>'string', 'value'=>'string'],
'ServerResponse::date' => ['string', 'date'=>'string|DateTimeInterface'],
'ServerResponse::getHeader' => ['string', 'label'=>'string'],
'ServerResponse::getHeaders' => ['string[]'],
'ServerResponse::getStatus' => ['int'],
'ServerResponse::getVersion' => ['string'],
'ServerResponse::setHeader' => ['void', 'label'=>'string', 'value'=>'string'],
'ServerResponse::setStatus' => ['void', 'status'=>'int'],
'ServerResponse::setVersion' => ['void', 'version'=>'string'],
'session_abort' => ['bool'],
'session_cache_expire' => ['int', 'new_cache_expire='=>'int'],
'session_cache_limiter' => ['string', 'new_cache_limiter='=>'string'],
'session_commit' => ['bool'],
'session_create_id' => ['string', 'prefix='=>'string'],
'session_decode' => ['bool', 'data'=>'string'],
'session_destroy' => ['bool'],
'session_encode' => ['string'],
'session_gc' => ['int|false'],
'session_get_cookie_params' => ['array'],
'session_id' => ['string', 'newid='=>'string'],
'session_is_registered' => ['bool', 'name'=>'string'],
'session_module_name' => ['string', 'newname='=>'string'],
'session_name' => ['string', 'newname='=>'string'],
'session_pgsql_add_error' => ['bool', 'error_level'=>'int', 'error_message='=>'string'],
'session_pgsql_get_error' => ['array', 'with_error_message='=>'bool'],
'session_pgsql_get_field' => ['string'],
'session_pgsql_reset' => ['bool'],
'session_pgsql_set_field' => ['bool', 'value'=>'string'],
'session_pgsql_status' => ['array'],
'session_regenerate_id' => ['bool', 'delete_old_session='=>'bool'],
'session_register' => ['bool', 'name'=>'mixed', '...args='=>'mixed'],
'session_register_shutdown' => ['void'],
'session_reset' => ['bool'],
'session_save_path' => ['string', 'newname='=>'string'],
'session_set_cookie_params' => ['bool', 'lifetime'=>'int', 'path='=>'string', 'domain='=>'?string', 'secure='=>'bool', 'httponly='=>'bool'],
'session_set_cookie_params\'1' => ['bool', 'options'=>'array{lifetime?:int,path?:string,domain?:?string,secure?:bool,httponly?:bool}'],
'session_set_save_handler' => ['bool', 'open'=>'callable(string,string):bool', 'close'=>'callable():bool', 'read'=>'callable(string):string', 'write'=>'callable(string,string):bool', 'destroy'=>'callable(string):bool', 'gc'=>'callable(string):bool', 'create_sid='=>'callable():string', 'validate_sid='=>'callable(string):bool', 'update_timestamp='=>'callable(string):bool'],
'session_set_save_handler\'1' => ['bool', 'sessionhandler'=>'SessionHandlerInterface', 'register_shutdown='=>'bool'],
'session_start' => ['bool', 'options='=>'array'],
'session_status' => ['int'],
'session_unregister' => ['bool', 'name'=>'string'],
'session_unset' => ['bool'],
'session_write_close' => ['bool'],
'SessionHandler::close' => ['bool'],
'SessionHandler::create_sid' => ['char'],
'SessionHandler::destroy' => ['bool', 'id'=>'string'],
'SessionHandler::gc' => ['bool', 'maxlifetime'=>'int'],
'SessionHandler::open' => ['bool', 'save_path'=>'string', 'session_name'=>'string'],
'SessionHandler::read' => ['string', 'id'=>'string'],
'SessionHandler::updateTimestamp' => ['bool', 'session_id'=>'string', 'session_data'=>'string'],
'SessionHandler::validateId' => ['bool', 'session_id'=>'string'],
'SessionHandler::write' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionHandlerInterface::close' => ['bool'],
'SessionHandlerInterface::destroy' => ['bool', 'session_id'=>'string'],
'SessionHandlerInterface::gc' => ['bool', 'maxlifetime'=>'int'],
'SessionHandlerInterface::open' => ['bool', 'save_path'=>'string', 'name'=>'string'],
'SessionHandlerInterface::read' => ['string', 'session_id'=>'string'],
'SessionHandlerInterface::write' => ['bool', 'session_id'=>'string', 'session_data'=>'string'],
'SessionIdInterface::create_sid' => ['string'],
'SessionUpdateTimestampHandler::updateTimestamp' => ['bool', 'id'=>'string', 'data'=>'string'],
'SessionUpdateTimestampHandler::validateId' => ['char', 'id'=>'string'],
'SessionUpdateTimestampHandlerInterface::updateTimestamp' => ['bool', 'key'=>'string', 'val'=>'string'],
'SessionUpdateTimestampHandlerInterface::validateId' => ['bool', 'key'=>'string'],
'set_error_handler' => ['null|callable(int,string,string=,int=,array=):bool', 'error_handler'=>'null|callable(int,string,string=,int=,array=):bool', 'error_types='=>'int'],
'set_exception_handler' => ['null|callable(Throwable):void', 'exception_handler'=>'null|callable(Throwable):void'],
'set_file_buffer' => ['int', 'fp'=>'resource', 'buffer'=>'int'],
'set_include_path' => ['string|false', 'new_include_path'=>'string'],
'set_magic_quotes_runtime' => ['bool', 'new_setting'=>'bool'],
'set_time_limit' => ['bool', 'seconds'=>'int'],
'setcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool'],
'setcookie\'1' => ['bool', 'name'=>'string', 'value='=>'string', 'options='=>'array'],
'setLeftFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setLine' => ['void', 'width'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setlocale' => ['string|false', 'category'=>'int', 'locale'=>'string|0|null', '...args='=>'string'],
'setlocale\'1' => ['string|false', 'category'=>'int', 'locale'=>'?array'],
'setproctitle' => ['void', 'title'=>'string'],
'setrawcookie' => ['bool', 'name'=>'string', 'value='=>'string', 'expires='=>'int', 'path='=>'string', 'domain='=>'string', 'secure='=>'bool', 'httponly='=>'bool'],
'setRightFill' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'setthreadtitle' => ['bool', 'title'=>'string'],
'settype' => ['bool', '&rw_var'=>'mixed', 'type'=>'string'],
'sha1' => ['string', 'str'=>'string', 'raw_output='=>'bool'],
'sha1_file' => ['string|false', 'filename'=>'string', 'raw_output='=>'bool'],
'sha256' => ['string', 'str'=>'string', 'raw_output='=>'bool'],
'sha256_file' => ['string', 'filename'=>'string', 'raw_output='=>'bool'],
'shapefileObj::__construct' => ['void', 'filename'=>'string', 'type'=>'int'],
'shapefileObj::addPoint' => ['int', 'point'=>'pointObj'],
'shapefileObj::addShape' => ['int', 'shape'=>'shapeObj'],
'shapefileObj::free' => ['void'],
'shapefileObj::getExtent' => ['rectObj', 'i'=>'int'],
'shapefileObj::getPoint' => ['shapeObj', 'i'=>'int'],
'shapefileObj::getShape' => ['shapeObj', 'i'=>'int'],
'shapefileObj::getTransformed' => ['shapeObj', 'map'=>'mapObj', 'i'=>'int'],
'shapefileObj::ms_newShapefileObj' => ['shapefileObj', 'filename'=>'string', 'type'=>'int'],
'shapeObj::__construct' => ['void', 'type'=>'int'],
'shapeObj::add' => ['int', 'line'=>'lineObj'],
'shapeObj::boundary' => ['shapeObj'],
'shapeObj::contains' => ['bool', 'point'=>'pointObj'],
'shapeObj::containsShape' => ['int', 'shape2'=>'shapeObj'],
'shapeObj::convexhull' => ['shapeObj'],
'shapeObj::crosses' => ['int', 'shape'=>'shapeObj'],
'shapeObj::difference' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::disjoint' => ['int', 'shape'=>'shapeObj'],
'shapeObj::draw' => ['int', 'map'=>'mapObj', 'layer'=>'layerObj', 'img'=>'imageObj'],
'shapeObj::equals' => ['int', 'shape'=>'shapeObj'],
'shapeObj::free' => ['void'],
'shapeObj::getArea' => ['float'],
'shapeObj::getCentroid' => ['pointObj'],
'shapeObj::getLabelPoint' => ['pointObj'],
'shapeObj::getLength' => ['float'],
'shapeObj::getPointUsingMeasure' => ['pointObj', 'm'=>'float'],
'shapeObj::getValue' => ['string', 'layer'=>'layerObj', 'filedname'=>'string'],
'shapeObj::intersection' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::intersects' => ['bool', 'shape'=>'shapeObj'],
'shapeObj::line' => ['lineObj', 'i'=>'int'],
'shapeObj::ms_shapeObjFromWkt' => ['shapeObj', 'wkt'=>'string'],
'shapeObj::overlaps' => ['int', 'shape'=>'shapeObj'],
'shapeObj::project' => ['int', 'in'=>'projectionObj', 'out'=>'projectionObj'],
'shapeObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'shapeObj::setBounds' => ['int'],
'shapeObj::simplify' => ['shapeObj|null', 'tolerance'=>'float'],
'shapeObj::symdifference' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::topologyPreservingSimplify' => ['shapeObj|null', 'tolerance'=>'float'],
'shapeObj::touches' => ['int', 'shape'=>'shapeObj'],
'shapeObj::toWkt' => ['string'],
'shapeObj::union' => ['shapeObj', 'shape'=>'shapeObj'],
'shapeObj::within' => ['int', 'shape2'=>'shapeObj'],
'shell_exec' => ['?string', 'cmd'=>'string'],
'shm_attach' => ['resource', 'key'=>'int', 'memsize='=>'int', 'perm='=>'int'],
'shm_detach' => ['bool', 'shm_identifier'=>'resource'],
'shm_get_var' => ['mixed', 'id'=>'resource', 'variable_key'=>'int'],
'shm_has_var' => ['bool', 'shm_identifier'=>'resource', 'variable_key'=>'int'],
'shm_put_var' => ['bool', 'shm_identifier'=>'resource', 'variable_key'=>'int', 'variable'=>'mixed'],
'shm_remove' => ['bool', 'shm_identifier'=>'resource'],
'shm_remove_var' => ['bool', 'shm_identifier'=>'resource', 'variable_key'=>'int'],
'shmop_close' => ['void', 'shmid'=>'resource'],
'shmop_delete' => ['bool', 'shmid'=>'resource'],
'shmop_open' => ['resource|false', 'key'=>'int', 'flags'=>'string', 'mode'=>'int', 'size'=>'int'],
'shmop_read' => ['string|false', 'shmid'=>'resource', 'start'=>'int', 'count'=>'int'],
'shmop_size' => ['int', 'shmid'=>'resource'],
'shmop_write' => ['int|false', 'shmid'=>'resource', 'data'=>'string', 'offset'=>'int'],
'show_source' => ['string|bool', 'file_name'=>'string', 'return='=>'bool'],
'shuffle' => ['bool', '&rw_array_arg'=>'array'],
'signeurlpaiement' => ['string', 'clent'=>'string', 'data'=>'string'],
'similar_text' => ['int', 'str1'=>'string', 'str2'=>'string', '&w_percent='=>'float'],
'simplexml_import_dom' => ['SimpleXMLElement|false', 'node'=>'DOMNode', 'class_name='=>'string'],
'simplexml_load_file' => ['SimpleXMLElement|false', 'filename'=>'string', 'class_name='=>'string', 'options='=>'int', 'ns='=>'string', 'is_prefix='=>'bool'],
'simplexml_load_string' => ['SimpleXMLElement|false', 'data'=>'string', 'class_name='=>'string', 'options='=>'int', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::__construct' => ['void', 'data'=>'string', 'options='=>'int', 'data_is_url='=>'bool', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::__get' => ['SimpleXMLElement', 'name'=>'string'],
'SimpleXMLElement::__toString' => ['string'],
'SimpleXMLElement::addAttribute' => ['void', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLElement::addChild' => ['SimpleXMLElement', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLElement::asXML' => ['bool', 'filename'=>'string'],
'SimpleXMLElement::asXML\'1' => ['string|false'],
'SimpleXMLElement::attributes' => ['?SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::children' => ['SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLElement::count' => ['int'],
'SimpleXMLElement::getDocNamespaces' => ['string[]', 'recursive='=>'bool', 'from_root='=>'bool'],
'SimpleXMLElement::getName' => ['string'],
'SimpleXMLElement::getNamespaces' => ['string[]', 'recursive='=>'bool'],
'SimpleXMLElement::offsetExists' => ['bool', 'offset'=>'int|string'],
'SimpleXMLElement::offsetGet' => ['SimpleXMLElement', 'offset'=>'int|string'],
'SimpleXMLElement::offsetSet' => ['void', 'offset'=>'int|string', 'value'=>'mixed'],
'SimpleXMLElement::offsetUnset' => ['void', 'offset'=>'int|string'],
'SimpleXMLElement::registerXPathNamespace' => ['bool', 'prefix'=>'string', 'ns'=>'string'],
'SimpleXMLElement::saveXML' => ['mixed', 'filename='=>'string'],
'SimpleXMLElement::xpath' => ['SimpleXMLElement[]|false', 'path'=>'string'],
'SimpleXMLIterator::__construct' => ['void', 'data'=>'string', 'options='=>'int', 'data_is_url='=>'bool', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLIterator::__toString' => ['string'],
'SimpleXMLIterator::addAttribute' => ['void', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLIterator::addChild' => ['SimpleXMLElement', 'name'=>'string', 'value='=>'string', 'ns='=>'string'],
'SimpleXMLIterator::asXML' => ['bool|string', 'filename='=>'string'],
'SimpleXMLIterator::attributes' => ['?SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLIterator::children' => ['SimpleXMLElement', 'ns='=>'string', 'is_prefix='=>'bool'],
'SimpleXMLIterator::count' => ['int'],
'SimpleXMLIterator::current' => ['?SimpleXMLIterator'],
'SimpleXMLIterator::getChildren' => ['SimpleXMLIterator'],
'SimpleXMLIterator::getDocNamespaces' => ['string[]', 'recursive='=>'bool', 'from_root='=>'bool'],
'SimpleXMLIterator::getName' => ['string'],
'SimpleXMLIterator::getNamespaces' => ['string[]', 'recursive='=>'bool'],
'SimpleXMLIterator::hasChildren' => ['bool'],
'SimpleXMLIterator::key' => ['string|false'],
'SimpleXMLIterator::next' => ['void'],
'SimpleXMLIterator::registerXPathNamespace' => ['bool', 'prefix'=>'string', 'ns'=>'string'],
'SimpleXMLIterator::rewind' => ['void'],
'SimpleXMLIterator::saveXML' => ['mixed', 'filename='=>'string'],
'SimpleXMLIterator::valid' => ['bool'],
'SimpleXMLIterator::xpath' => ['SimpleXMLElement[]|false', 'path'=>'string'],
'sin' => ['float', 'number'=>'float'],
'sinh' => ['float', 'number'=>'float'],
'sizeof' => ['int', 'var'=>'Countable|array', 'mode='=>'int'],
'sleep' => ['int|false', 'seconds'=>'int'],
'snmp2_get' => ['string|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_getnext' => ['string|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_real_walk' => ['array|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_set' => ['bool', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp2_walk' => ['array|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_get' => ['string|false', 'host'=>'string', 'sec_name'=>'string', 'sec_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'priv_protocol'=>'string', 'priv_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_getnext' => ['string|false', 'host'=>'string', 'sec_name'=>'string', 'sec_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'priv_protocol'=>'string', 'priv_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_real_walk' => ['array|false', 'host'=>'string', 'sec_name'=>'string', 'sec_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'priv_protocol'=>'string', 'priv_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_set' => ['bool', 'host'=>'string', 'sec_name'=>'string', 'sec_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'priv_protocol'=>'string', 'priv_passphrase'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmp3_walk' => ['array|false', 'host'=>'string', 'sec_name'=>'string', 'sec_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'priv_protocol'=>'string', 'priv_passphrase'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SNMP::__construct' => ['void', 'version'=>'int', 'hostname'=>'string', 'community'=>'string', 'timeout'=>'int', 'retries'=>'int'],
'SNMP::close' => ['bool'],
'SNMP::get' => ['mixed', 'object_id'=>'mixed', 'preserve_keys'=>'bool'],
'SNMP::getErrno' => ['int'],
'SNMP::getError' => ['string'],
'SNMP::getnext' => ['mixed', 'object_id'=>'mixed'],
'SNMP::set' => ['bool', 'object_id'=>'mixed', 'type'=>'mixed', 'value'=>'mixed'],
'SNMP::setSecurity' => ['bool', 'sec_level'=>'string', 'auth_protocol'=>'string', 'auth_passphrase'=>'string', 'priv_protocol'=>'string', 'priv_passphrase'=>'string', 'contextname'=>'string', 'contextengineid'=>'string'],
'SNMP::walk' => ['array|false', 'object_id'=>'string', 'suffix_as_key'=>'bool', 'max_repetitions'=>'int', 'non_repeaters'=>'int'],
'snmp_get_quick_print' => ['bool'],
'snmp_get_valueretrieval' => ['int'],
'snmp_read_mib' => ['bool', 'filename'=>'string'],
'snmp_set_enum_print' => ['bool', 'enum_print'=>'int'],
'snmp_set_oid_numeric_print' => ['void', 'oid_format'=>'int'],
'snmp_set_oid_output_format' => ['bool', 'oid_format'=>'int'],
'snmp_set_quick_print' => ['bool', 'quick_print'=>'bool'],
'snmp_set_valueretrieval' => ['bool', 'method'=>'int'],
'snmpget' => ['string|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpgetnext' => ['string|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmprealwalk' => ['array|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpset' => ['bool', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'type'=>'string', 'value'=>'mixed', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalk' => ['array|false', 'host'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'snmpwalkoid' => ['array|false', 'hostname'=>'string', 'community'=>'string', 'object_id'=>'string', 'timeout='=>'int', 'retries='=>'int'],
'SoapClient::__call' => ['', 'function_name'=>'string', 'arguments'=>'array'],
'SoapClient::__construct' => ['void', 'wsdl'=>'mixed', 'options='=>'array'],
'SoapClient::__doRequest' => ['string', 'request'=>'string', 'location'=>'string', 'action'=>'string', 'version'=>'int', 'one_way='=>'int'],
'SoapClient::__getCookies' => ['array'],
'SoapClient::__getFunctions' => ['array'],
'SoapClient::__getLastRequest' => ['string'],
'SoapClient::__getLastRequestHeaders' => ['string'],
'SoapClient::__getLastResponse' => ['string'],
'SoapClient::__getLastResponseHeaders' => ['string'],
'SoapClient::__getTypes' => ['array'],
'SoapClient::__setCookie' => ['', 'name'=>'string', 'value='=>'string'],
'SoapClient::__setLocation' => ['string', 'new_location='=>'string'],
'SoapClient::__setSoapHeaders' => ['bool', 'soapheaders='=>''],
'SoapClient::__soapCall' => ['', 'function_name'=>'string', 'arguments'=>'array', 'options='=>'array', 'input_headers='=>'SoapHeader|array', '&w_output_headers='=>'array'],
'SoapClient::SoapClient' => ['object', 'wsdl'=>'mixed', 'options='=>'array'],
'SoapFault::__clone' => ['void'],
'SoapFault::__construct' => ['void', 'faultcode'=>'string', 'faultstring'=>'string', 'faultactor='=>'string', 'detail='=>'string', 'faultname='=>'string', 'headerfault='=>'string'],
'SoapFault::__toString' => ['string'],
'SoapFault::__wakeup' => ['void'],
'SoapFault::getCode' => ['int'],
'SoapFault::getFile' => ['string'],
'SoapFault::getLine' => ['int'],
'SoapFault::getMessage' => ['string'],
'SoapFault::getPrevious' => ['?Exception|?Throwable'],
'SoapFault::getTrace' => ['array'],
'SoapFault::getTraceAsString' => ['string'],
'SoapFault::SoapFault' => ['object', 'faultcode'=>'string', 'faultstring'=>'string', 'faultactor='=>'string', 'detail='=>'string', 'faultname='=>'string', 'headerfault='=>'string'],
'SoapHeader::__construct' => ['void', 'namespace'=>'string', 'name'=>'string', 'data='=>'mixed', 'mustunderstand='=>'bool', 'actor='=>'string'],
'SoapHeader::SoapHeader' => ['object', 'namespace'=>'string', 'name'=>'string', 'data='=>'mixed', 'mustunderstand='=>'bool', 'actor='=>'string'],
'SoapParam::__construct' => ['void', 'data'=>'mixed', 'name'=>'string'],
'SoapParam::SoapParam' => ['object', 'data'=>'mixed', 'name'=>'string'],
'SoapServer::__construct' => ['void', 'wsdl'=>'?string', 'options='=>'array'],
'SoapServer::addFunction' => ['void', 'functions'=>'mixed'],
'SoapServer::addSoapHeader' => ['void', 'object'=>'SoapHeader'],
'SoapServer::fault' => ['void', 'code'=>'string', 'string'=>'string', 'actor='=>'string', 'details='=>'string', 'name='=>'string'],
'SoapServer::getFunctions' => ['array'],
'SoapServer::handle' => ['void', 'soap_request='=>'string'],
'SoapServer::setClass' => ['void', 'class_name'=>'string', '...args='=>'mixed'],
'SoapServer::setObject' => ['void', 'obj'=>'object'],
'SoapServer::setPersistence' => ['void', 'mode'=>'int'],
'SoapServer::SoapServer' => ['object', 'wsdl'=>'?string', 'options='=>'array'],
'SoapVar::__construct' => ['void', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string', 'type_namespace='=>'string', 'node_name='=>'string', 'node_namespace='=>'string'],
'SoapVar::SoapVar' => ['object', 'data'=>'mixed', 'encoding'=>'int', 'type_name='=>'string', 'type_namespace='=>'string', 'node_name='=>'string', 'node_namespace='=>'string'],
'socket_accept' => ['resource|false', 'socket'=>'resource'],
'socket_addrinfo_bind' => ['?resource', 'addrinfo'=>'resource'],
'socket_addrinfo_connect' => ['?resource', 'addrinfo'=>'resource'],
'socket_addrinfo_explain' => ['array', 'addrinfo'=>'resource'],
'socket_addrinfo_lookup' => ['resource[]', 'node'=>'string', 'service='=>'mixed', 'hints='=>'array'],
'socket_bind' => ['bool', 'socket'=>'resource', 'addr'=>'string', 'port='=>'int'],
'socket_clear_error' => ['void', 'socket='=>'resource'],
'socket_close' => ['void', 'socket'=>'resource'],
'socket_cmsg_space' => ['int', 'level'=>'int', 'type'=>'int'],
'socket_connect' => ['bool', 'socket'=>'resource', 'addr'=>'string', 'port='=>'int'],
'socket_create' => ['resource|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'socket_create_listen' => ['resource|false', 'port'=>'int', 'backlog='=>'int'],
'socket_create_pair' => ['bool', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int', '&w_fd'=>'resource[]'],
'socket_export_stream' => ['resource|false', 'socket'=>'resource'],
'socket_get_option' => ['mixed|false', 'socket'=>'resource', 'level'=>'int', 'optname'=>'int'],
'socket_get_status' => ['array', 'stream'=>'resource'],
'socket_getopt' => ['mixed', 'socket'=>'resource', 'level'=>'int', 'optname'=>'int'],
'socket_getpeername' => ['bool', 'socket'=>'resource', '&w_addr'=>'string', '&w_port='=>'int'],
'socket_getsockname' => ['bool', 'socket'=>'resource', '&w_addr'=>'string', '&w_port='=>'int'],
'socket_import_stream' => ['resource|false|null', 'stream'=>'resource'],
'socket_last_error' => ['int', 'socket='=>'resource'],
'socket_listen' => ['bool', 'socket'=>'resource', 'backlog='=>'int'],
'socket_read' => ['string|false', 'socket'=>'resource', 'length'=>'int', 'type='=>'int'],
'socket_recv' => ['int|false', 'socket'=>'resource', '&w_buf'=>'string', 'len'=>'int', 'flags'=>'int'],
'socket_recvfrom' => ['int|false', 'socket'=>'resource', '&w_buf'=>'string', 'len'=>'int', 'flags'=>'int', '&w_name'=>'string', '&w_port='=>'int'],
'socket_recvmsg' => ['int|false', 'socket'=>'resource', '&w_message'=>'string', 'flags='=>'int'],
'socket_select' => ['int|false', '&rw_read_fds'=>'resource[]|null', '&rw_write_fds'=>'resource[]|null', '&rw_except_fds'=>'resource[]|null', 'tv_sec'=>'int', 'tv_usec='=>'int'],
'socket_send' => ['int|false', 'socket'=>'resource', 'buf'=>'string', 'len'=>'int', 'flags'=>'int'],
'socket_sendmsg' => ['int|false', 'socket'=>'resource', 'message'=>'array', 'flags'=>'int'],
'socket_sendto' => ['int|false', 'socket'=>'resource', 'buf'=>'string', 'len'=>'int', 'flags'=>'int', 'addr'=>'string', 'port='=>'int'],
'socket_set_block' => ['bool', 'socket'=>'resource'],
'socket_set_blocking' => ['bool', 'socket'=>'resource', 'mode'=>'int'],
'socket_set_nonblock' => ['bool', 'socket'=>'resource'],
'socket_set_option' => ['bool', 'socket'=>'resource', 'level'=>'int', 'optname'=>'int', 'optval'=>'int|string|array'],
'socket_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'socket_setopt' => ['void', 'socket'=>'resource', 'level'=>'int', 'optname'=>'int', 'optval'=>'int|string|array'],
'socket_shutdown' => ['bool', 'socket'=>'resource', 'how='=>'int'],
'socket_strerror' => ['string', 'errno'=>'int'],
'socket_write' => ['int|false', 'socket'=>'resource', 'buf'=>'string', 'length='=>'int'],
'socket_wsaprotocol_info_export' => ['string|false', 'stream'=>'resource', 'target_pid'=>'int'],
'socket_wsaprotocol_info_import' => ['resource|false', 'id'=>'string'],
'socket_wsaprotocol_info_release' => ['bool', 'id'=>'string'],
'Sodium\add' => ['void', '&left'=>'string', 'right'=>'string'],
'Sodium\bin2hex' => ['string', 'binary'=>'string'],
'Sodium\compare' => ['int', 'left'=>'string', 'right'=>'string'],
'Sodium\crypto_aead_aes256gcm_decrypt' => ['string|false', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_aead_aes256gcm_encrypt' => ['string', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_aead_aes256gcm_is_available' => ['bool'],
'Sodium\crypto_aead_chacha20poly1305_decrypt' => ['string', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_aead_chacha20poly1305_encrypt' => ['string', 'msg'=>'string', 'nonce'=>'string', 'key'=>'string', 'ad='=>'string'],
'Sodium\crypto_auth' => ['string', 'msg'=>'string', 'key'=>'string'],
'Sodium\crypto_auth_verify' => ['bool', 'mac'=>'string', 'msg'=>'string', 'key'=>'string'],
'Sodium\crypto_box' => ['string', 'msg'=>'string', 'nonce'=>'string', 'keypair'=>'string'],
'Sodium\crypto_box_keypair' => ['string'],
'Sodium\crypto_box_keypair_from_secretkey_and_publickey' => ['string', 'secretkey'=>'string', 'publickey'=>'string'],
'Sodium\crypto_box_open' => ['string', 'msg'=>'string', 'nonce'=>'string', 'keypair'=>'string'],
'Sodium\crypto_box_publickey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_box_publickey_from_secretkey' => ['string', 'secretkey'=>'string'],
'Sodium\crypto_box_seal' => ['string', 'message'=>'string', 'publickey'=>'string'],
'Sodium\crypto_box_seal_open' => ['string', 'encrypted'=>'string', 'keypair'=>'string'],
'Sodium\crypto_box_secretkey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_box_seed_keypair' => ['string', 'seed'=>'string'],
'Sodium\crypto_generichash' => ['string', 'input'=>'string', 'key='=>'string', 'length='=>'int'],
'Sodium\crypto_generichash_final' => ['string', 'state'=>'string', 'length='=>'int'],
'Sodium\crypto_generichash_init' => ['string', 'key='=>'string', 'length='=>'int'],
'Sodium\crypto_generichash_update' => ['bool', '&hashState'=>'string', 'append'=>'string'],
'Sodium\crypto_kx' => ['string', 'secretkey'=>'string', 'publickey'=>'string', 'client_publickey'=>'string', 'server_publickey'=>'string'],
'Sodium\crypto_pwhash' => ['string', 'out_len'=>'int', 'passwd'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_scryptsalsa208sha256' => ['string', 'out_len'=>'int', 'passwd'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_scryptsalsa208sha256_str' => ['string', 'passwd'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_scryptsalsa208sha256_str_verify' => ['bool', 'hash'=>'string', 'passwd'=>'string'],
'Sodium\crypto_pwhash_str' => ['string', 'passwd'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'Sodium\crypto_pwhash_str_verify' => ['bool', 'hash'=>'string', 'passwd'=>'string'],
'Sodium\crypto_scalarmult' => ['string', 'ecdhA'=>'string', 'ecdhB'=>'string'],
'Sodium\crypto_scalarmult_base' => ['string', 'sk'=>'string'],
'Sodium\crypto_secretbox' => ['string', 'plaintext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'Sodium\crypto_secretbox_open' => ['string', 'ciphertext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'Sodium\crypto_shorthash' => ['string', 'message'=>'string', 'key'=>'string'],
'Sodium\crypto_sign' => ['string', 'message'=>'string', 'secretkey'=>'string'],
'Sodium\crypto_sign_detached' => ['string', 'message'=>'string', 'secretkey'=>'string'],
'Sodium\crypto_sign_ed25519_pk_to_curve25519' => ['string', 'sign_pk'=>'string'],
'Sodium\crypto_sign_ed25519_sk_to_curve25519' => ['string', 'sign_sk'=>'string'],
'Sodium\crypto_sign_keypair' => ['string'],
'Sodium\crypto_sign_keypair_from_secretkey_and_publickey' => ['string', 'secretkey'=>'string', 'publickey'=>'string'],
'Sodium\crypto_sign_open' => ['string|false', 'signed_message'=>'string', 'publickey'=>'string'],
'Sodium\crypto_sign_publickey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_sign_publickey_from_secretkey' => ['string', 'secretkey'=>'string'],
'Sodium\crypto_sign_secretkey' => ['string', 'keypair'=>'string'],
'Sodium\crypto_sign_seed_keypair' => ['string', 'seed'=>'string'],
'Sodium\crypto_sign_verify_detached' => ['bool', 'signature'=>'string', 'msg'=>'string', 'publickey'=>'string'],
'Sodium\crypto_stream' => ['string', 'length'=>'int', 'nonce'=>'string', 'key'=>'string'],
'Sodium\crypto_stream_xor' => ['string', 'plaintext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'Sodium\hex2bin' => ['string', 'hex'=>'string'],
'Sodium\increment' => ['string', '&nonce'=>'string'],
'Sodium\library_version_major' => ['int'],
'Sodium\library_version_minor' => ['int'],
'Sodium\memcmp' => ['int', 'left'=>'string', 'right'=>'string'],
'Sodium\memzero' => ['void', '&target'=>'string'],
'Sodium\randombytes_buf' => ['string', 'length'=>'int'],
'Sodium\randombytes_random16' => ['int|string'],
'Sodium\randombytes_uniform' => ['int', 'upperBoundNonInclusive'=>'int'],
'Sodium\version_string' => ['string'],
'sodium_add' => ['string', 'string_1'=>'string', 'string_2'=>'string'],
'sodium_base642bin' => ['string', 'base64'=>'string', 'variant'=>'int', 'ignore'=>'string'],
'sodium_bin2base64' => ['string', 'binary'=>'string', 'variant'=>'int'],
'sodium_bin2hex' => ['string', 'binary'=>'string'],
'sodium_compare' => ['int', 'string_1'=>'string', 'string_2'=>'string'],
'sodium_crypto_aead_aes256gcm_decrypt' => ['string|false', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_encrypt' => ['string', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_aes256gcm_is_available' => ['bool'],
'sodium_crypto_aead_aes256gcm_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_decrypt' => ['string', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_encrypt' => ['string', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_decrypt' => ['array<int,string>|false', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_encrypt' => ['string', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_chacha20poly1305_ietf_keygen' => ['string'],
'sodium_crypto_aead_chacha20poly1305_keygen' => ['string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_decrypt' => ['string|false', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' => ['string', 'confidential_message'=>'string', 'public_message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_aead_xchacha20poly1305_ietf_keygen' => ['string'],
'sodium_crypto_auth' => ['string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_auth_keygen' => ['string'],
'sodium_crypto_auth_verify' => ['bool', 'mac'=>'string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_box' => ['string', 'string'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_box_keypair' => ['string'],
'sodium_crypto_box_keypair_from_secretkey_and_publickey' => ['string', 'secret_key'=>'string', 'public_key'=>'string'],
'sodium_crypto_box_open' => ['string|false', 'message'=>'string', 'nonce'=>'string', 'message_keypair'=>'string'],
'sodium_crypto_box_publickey' => ['string', 'keypair'=>'string'],
'sodium_crypto_box_publickey_from_secretkey' => ['string', 'secretkey'=>'string'],
'sodium_crypto_box_seal' => ['string', 'message'=>'string', 'publickey'=>'string'],
'sodium_crypto_box_seal_open' => ['string|false', 'message'=>'string', 'recipient_keypair'=>'string'],
'sodium_crypto_box_secretkey' => ['string', 'keypair'=>'string'],
'sodium_crypto_box_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_generichash' => ['string', 'msg'=>'string', 'key='=>'?string', 'length='=>'?int'],
'sodium_crypto_generichash_final' => ['string', 'state'=>'string', 'length='=>'?int'],
'sodium_crypto_generichash_init' => ['string', 'key='=>'?string', 'length='=>'?int'],
'sodium_crypto_generichash_keygen' => ['string'],
'sodium_crypto_generichash_update' => ['bool', 'state'=>'string', 'string'=>'string'],
'sodium_crypto_kdf_derive_from_key' => ['string', 'subkey_len'=>'int', 'subkey_id'=>'int', 'context'=>'string', 'key'=>'string'],
'sodium_crypto_kdf_keygen' => ['string'],
'sodium_crypto_kx' => ['string', 'secretkey'=>'string', 'publickey'=>'string', 'client_publickey'=>'string', 'server_publickey'=>'string'],
'sodium_crypto_kx_client_session_keys' => ['array<int,string>', 'client_keypair'=>'string', 'server_key'=>'string'],
'sodium_crypto_kx_keypair' => ['string'],
'sodium_crypto_kx_publickey' => ['string', 'keypair'=>'string'],
'sodium_crypto_kx_secretkey' => ['string', 'keypair'=>'string'],
'sodium_crypto_kx_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_kx_server_session_keys' => ['array<int,string>', 'server_keypair'=>'string', 'client_key'=>'string'],
'sodium_crypto_pwhash' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int', 'alg='=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256' => ['string', 'length'=>'int', 'password'=>'string', 'salt'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256_str' => ['string', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_scryptsalsa208sha256_str_verify' => ['bool', 'hash'=>'string', 'password'=>'string'],
'sodium_crypto_pwhash_str' => ['string', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_str_needs_rehash' => ['bool', 'password'=>'string', 'opslimit'=>'int', 'memlimit'=>'int'],
'sodium_crypto_pwhash_str_verify' => ['bool', 'hash'=>'string', 'password'=>'string'],
'sodium_crypto_scalarmult' => ['string', 'string_1'=>'string', 'string_2'=>'string'],
'sodium_crypto_scalarmult_base' => ['string', 'secretkey'=>'string'],
'sodium_crypto_secretbox' => ['string', 'plaintext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_secretbox_keygen' => ['string'],
'sodium_crypto_secretbox_open' => ['string|false', 'ciphertext'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_init_pull' => ['string', 'header'=>'string', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_init_push' => ['array', 'key'=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_keygen' => ['string'],
'sodium_crypto_secretstream_xchacha20poly1305_pull' => ['array', 'state'=>'string', 'c'=>'string', 'ad='=>'string'],
'sodium_crypto_secretstream_xchacha20poly1305_push' => ['string', 'state'=>'string', 'msg'=>'string', 'ad='=>'string', 'tag='=>'int'],
'sodium_crypto_secretstream_xchacha20poly1305_rekey' => ['void', 'state'=>'string'],
'sodium_crypto_shorthash' => ['string', 'message'=>'string', 'key'=>'string'],
'sodium_crypto_shorthash_keygen' => ['string'],
'sodium_crypto_sign' => ['string', 'message'=>'string', 'secretkey'=>'string'],
'sodium_crypto_sign_detached' => ['string', 'message'=>'string', 'secretkey'=>'string'],
'sodium_crypto_sign_ed25519_pk_to_curve25519' => ['string', 'ed25519pk'=>'string'],
'sodium_crypto_sign_ed25519_sk_to_curve25519' => ['string', 'ed25519sk'=>'string'],
'sodium_crypto_sign_keypair' => ['string'],
'sodium_crypto_sign_keypair_from_secretkey_and_publickey' => ['string', 'secret_key'=>'string', 'public_key'=>'string'],
'sodium_crypto_sign_open' => ['string|false', 'message'=>'string', 'publickey'=>'string'],
'sodium_crypto_sign_publickey' => ['string', 'keypair'=>'string'],
'sodium_crypto_sign_publickey_from_secretkey' => ['string', 'secretkey'=>'string'],
'sodium_crypto_sign_secretkey' => ['string', 'keypair'=>'string'],
'sodium_crypto_sign_seed_keypair' => ['string', 'seed'=>'string'],
'sodium_crypto_sign_verify_detached' => ['bool', 'signature'=>'string', 'message'=>'string', 'publickey'=>'string'],
'sodium_crypto_stream' => ['string', 'length'=>'int', 'nonce'=>'string', 'key'=>'string'],
'sodium_crypto_stream_keygen' => ['string'],
'sodium_crypto_stream_xor' => ['string', 'message'=>'string', 'nonce'=>'string', 'key'=>'string'],
'sodium_hex2bin' => ['string', 'hex'=>'string', 'ignore='=>'string'],
'sodium_increment' => ['string', '&binary_string'=>'string'],
'sodium_library_version_major' => ['int'],
'sodium_library_version_minor' => ['int'],
'sodium_memcmp' => ['int', 'string_1'=>'string', 'string_2'=>'string'],
'sodium_memzero' => ['void', '&secret'=>'string'],
'sodium_pad' => ['string', 'unpadded'=>'string', 'length'=>'int'],
'sodium_randombytes_buf' => ['string', 'length'=>'int'],
'sodium_randombytes_random16' => ['int|string'],
'sodium_randombytes_uniform' => ['int', 'upperBoundNonInclusive'=>'int'],
'sodium_unpad' => ['string', 'padded'=>'string', 'length'=>'int'],
'sodium_version_string' => ['string'],
'solid_fetch_prev' => ['bool', 'result_id'=>''],
'solr_get_version' => ['string|false'],
'SolrClient::__construct' => ['void', 'clientOptions'=>'array'],
'SolrClient::__destruct' => ['void'],
'SolrClient::addDocument' => ['SolrUpdateResponse', 'doc'=>'SolrInputDocument', 'allowdups='=>'bool', 'commitwithin='=>'int'],
'SolrClient::addDocuments' => ['SolrUpdateResponse', 'docs'=>'array', 'allowdups='=>'bool', 'commitwithin='=>'int'],
'SolrClient::commit' => ['SolrUpdateResponse', 'maxsegments='=>'int', 'waitflush='=>'bool', 'waitsearcher='=>'bool'],
'SolrClient::deleteById' => ['SolrUpdateResponse', 'id'=>'string'],
'SolrClient::deleteByIds' => ['SolrUpdateResponse', 'ids'=>'array'],
'SolrClient::deleteByQueries' => ['SolrUpdateResponse', 'queries'=>'array'],
'SolrClient::deleteByQuery' => ['SolrUpdateResponse', 'query'=>'string'],
'SolrClient::getById' => ['SolrQueryResponse', 'id'=>'string'],
'SolrClient::getByIds' => ['SolrQueryResponse', 'ids'=>'array'],
'SolrClient::getDebug' => ['string'],
'SolrClient::getOptions' => ['array'],
'SolrClient::optimize' => ['SolrUpdateResponse', 'maxsegments='=>'int', 'waitflush='=>'bool', 'waitsearcher='=>'bool'],
'SolrClient::ping' => ['SolrPingResponse'],
'SolrClient::query' => ['SolrQueryResponse', 'query'=>'SolrParams'],
'SolrClient::request' => ['SolrUpdateResponse', 'raw_request'=>'string'],
'SolrClient::rollback' => ['SolrUpdateResponse'],
'SolrClient::setResponseWriter' => ['void', 'responsewriter'=>'string'],
'SolrClient::setServlet' => ['bool', 'type'=>'int', 'value'=>'string'],
'SolrClient::system' => ['SolrGenericResponse'],
'SolrClient::threads' => ['SolrGenericResponse'],
'SolrClientException::__clone' => ['void'],
'SolrClientException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrClientException::__toString' => ['string'],
'SolrClientException::__wakeup' => ['void'],
'SolrClientException::getCode' => ['int'],
'SolrClientException::getFile' => ['string'],
'SolrClientException::getInternalInfo' => ['array'],
'SolrClientException::getLine' => ['int'],
'SolrClientException::getMessage' => ['string'],
'SolrClientException::getPrevious' => ['?Exception|?Throwable'],
'SolrClientException::getTrace' => ['array'],
'SolrClientException::getTraceAsString' => ['string'],
'SolrCollapseFunction::__construct' => ['void', 'field'=>'string'],
'SolrCollapseFunction::__toString' => ['string'],
'SolrCollapseFunction::getField' => ['string'],
'SolrCollapseFunction::getHint' => ['string'],
'SolrCollapseFunction::getMax' => ['string'],
'SolrCollapseFunction::getMin' => ['string'],
'SolrCollapseFunction::getNullPolicy' => ['string'],
'SolrCollapseFunction::getSize' => ['int'],
'SolrCollapseFunction::setField' => ['SolrCollapseFunction', 'fieldName'=>'string'],
'SolrCollapseFunction::setHint' => ['SolrCollapseFunction', 'hint'=>'string'],
'SolrCollapseFunction::setMax' => ['SolrCollapseFunction', 'max'=>'string'],
'SolrCollapseFunction::setMin' => ['SolrCollapseFunction', 'min'=>'string'],
'SolrCollapseFunction::setNullPolicy' => ['SolrCollapseFunction', 'nullPolicy'=>'string'],
'SolrCollapseFunction::setSize' => ['SolrCollapseFunction', 'size'=>'int'],
'SolrDisMaxQuery::__construct' => ['void', 'q='=>'string'],
'SolrDisMaxQuery::__destruct' => ['void'],
'SolrDisMaxQuery::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrDisMaxQuery::addBigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addBoostQuery' => ['SolrDisMaxQuery', 'field'=>'string', 'value'=>'string', 'boost='=>'string'],
'SolrDisMaxQuery::addExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::addExpandSortField' => ['SolrQuery', 'field'=>'string', 'order'=>'string'],
'SolrDisMaxQuery::addFacetDateField' => ['SolrQuery', 'dateField'=>'string'],
'SolrDisMaxQuery::addFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::addFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addFacetQuery' => ['SolrQuery', 'facetQuery'=>'string'],
'SolrDisMaxQuery::addField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::addGroupField' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupFunction' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupQuery' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::addGroupSortField' => ['SolrQuery', 'field'=>'string', 'order'=>'int'],
'SolrDisMaxQuery::addHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addMltField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addMltQueryField' => ['SolrQuery', 'field'=>'string', 'boost'=>'float'],
'SolrDisMaxQuery::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrDisMaxQuery::addPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addQueryField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost='=>'string'],
'SolrDisMaxQuery::addSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrDisMaxQuery::addStatsFacet' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::addTrigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string', 'boost'=>'string', 'slop='=>'string'],
'SolrDisMaxQuery::addUserField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::collapse' => ['SolrQuery', 'collapseFunction'=>'SolrCollapseFunction'],
'SolrDisMaxQuery::get' => ['mixed', 'param_name'=>'string'],
'SolrDisMaxQuery::getExpand' => ['bool'],
'SolrDisMaxQuery::getExpandFilterQueries' => ['array'],
'SolrDisMaxQuery::getExpandQuery' => ['array'],
'SolrDisMaxQuery::getExpandRows' => ['int'],
'SolrDisMaxQuery::getExpandSortFields' => ['array'],
'SolrDisMaxQuery::getFacet' => ['bool'],
'SolrDisMaxQuery::getFacetDateEnd' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateFields' => ['array'],
'SolrDisMaxQuery::getFacetDateGap' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateHardEnd' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateOther' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetDateStart' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetFields' => ['array'],
'SolrDisMaxQuery::getFacetLimit' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMethod' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMinCount' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetMissing' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetOffset' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetPrefix' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getFacetQueries' => ['string'],
'SolrDisMaxQuery::getFacetSort' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getFields' => ['string'],
'SolrDisMaxQuery::getFilterQueries' => ['string'],
'SolrDisMaxQuery::getGroup' => ['bool'],
'SolrDisMaxQuery::getGroupCachePercent' => ['int'],
'SolrDisMaxQuery::getGroupFacet' => ['bool'],
'SolrDisMaxQuery::getGroupFields' => ['array'],
'SolrDisMaxQuery::getGroupFormat' => ['string'],
'SolrDisMaxQuery::getGroupFunctions' => ['array'],
'SolrDisMaxQuery::getGroupLimit' => ['int'],
'SolrDisMaxQuery::getGroupMain' => ['bool'],
'SolrDisMaxQuery::getGroupNGroups' => ['bool'],
'SolrDisMaxQuery::getGroupOffset' => ['bool'],
'SolrDisMaxQuery::getGroupQueries' => ['array'],
'SolrDisMaxQuery::getGroupSortFields' => ['array'],
'SolrDisMaxQuery::getGroupTruncate' => ['bool'],
'SolrDisMaxQuery::getHighlight' => ['bool'],
'SolrDisMaxQuery::getHighlightAlternateField' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFields' => ['array'],
'SolrDisMaxQuery::getHighlightFormatter' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFragmenter' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightFragsize' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightHighlightMultiTerm' => ['bool'],
'SolrDisMaxQuery::getHighlightMaxAlternateFieldLength' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightMaxAnalyzedChars' => ['int'],
'SolrDisMaxQuery::getHighlightMergeContiguous' => ['bool', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightRegexMaxAnalyzedChars' => ['int'],
'SolrDisMaxQuery::getHighlightRegexPattern' => ['string'],
'SolrDisMaxQuery::getHighlightRegexSlop' => ['float'],
'SolrDisMaxQuery::getHighlightRequireFieldMatch' => ['bool'],
'SolrDisMaxQuery::getHighlightSimplePost' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightSimplePre' => ['string', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightSnippets' => ['int', 'field_override'=>'string'],
'SolrDisMaxQuery::getHighlightUsePhraseHighlighter' => ['bool'],
'SolrDisMaxQuery::getMlt' => ['bool'],
'SolrDisMaxQuery::getMltBoost' => ['bool'],
'SolrDisMaxQuery::getMltCount' => ['int'],
'SolrDisMaxQuery::getMltFields' => ['array'],
'SolrDisMaxQuery::getMltMaxNumQueryTerms' => ['int'],
'SolrDisMaxQuery::getMltMaxNumTokens' => ['int'],
'SolrDisMaxQuery::getMltMaxWordLength' => ['int'],
'SolrDisMaxQuery::getMltMinDocFrequency' => ['int'],
'SolrDisMaxQuery::getMltMinTermFrequency' => ['int'],
'SolrDisMaxQuery::getMltMinWordLength' => ['int'],
'SolrDisMaxQuery::getMltQueryFields' => ['array'],
'SolrDisMaxQuery::getParam' => ['mixed', 'param_name'=>'string'],
'SolrDisMaxQuery::getParams' => ['array'],
'SolrDisMaxQuery::getPreparedParams' => ['array'],
'SolrDisMaxQuery::getQuery' => ['string'],
'SolrDisMaxQuery::getRows' => ['int'],
'SolrDisMaxQuery::getSortFields' => ['array'],
'SolrDisMaxQuery::getStart' => ['int'],
'SolrDisMaxQuery::getStats' => ['bool'],
'SolrDisMaxQuery::getStatsFacets' => ['array'],
'SolrDisMaxQuery::getStatsFields' => ['array'],
'SolrDisMaxQuery::getTerms' => ['bool'],
'SolrDisMaxQuery::getTermsField' => ['string'],
'SolrDisMaxQuery::getTermsIncludeLowerBound' => ['bool'],
'SolrDisMaxQuery::getTermsIncludeUpperBound' => ['bool'],
'SolrDisMaxQuery::getTermsLimit' => ['int'],
'SolrDisMaxQuery::getTermsLowerBound' => ['string'],
'SolrDisMaxQuery::getTermsMaxCount' => ['int'],
'SolrDisMaxQuery::getTermsMinCount' => ['int'],
'SolrDisMaxQuery::getTermsPrefix' => ['string'],
'SolrDisMaxQuery::getTermsReturnRaw' => ['bool'],
'SolrDisMaxQuery::getTermsSort' => ['int'],
'SolrDisMaxQuery::getTermsUpperBound' => ['string'],
'SolrDisMaxQuery::getTimeAllowed' => ['int'],
'SolrDisMaxQuery::removeBigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeBoostQuery' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::removeExpandSortField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetDateField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::removeFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFacetQuery' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::removeField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrDisMaxQuery::removeHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeMltField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeMltQueryField' => ['SolrQuery', 'queryField'=>'string'],
'SolrDisMaxQuery::removePhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeQueryField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeSortField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeStatsFacet' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::removeStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeTrigramPhraseField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::removeUserField' => ['SolrDisMaxQuery', 'field'=>'string'],
'SolrDisMaxQuery::serialize' => ['string'],
'SolrDisMaxQuery::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrDisMaxQuery::setBigramPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setBigramPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setBoostFunction' => ['SolrDisMaxQuery', 'function'=>'string'],
'SolrDisMaxQuery::setBoostQuery' => ['SolrDisMaxQuery', 'q'=>'string'],
'SolrDisMaxQuery::setEchoHandler' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setEchoParams' => ['SolrQuery', 'type'=>'string'],
'SolrDisMaxQuery::setExpand' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setExpandQuery' => ['SolrQuery', 'q'=>'string'],
'SolrDisMaxQuery::setExpandRows' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setExplainOther' => ['SolrQuery', 'query'=>'string'],
'SolrDisMaxQuery::setFacet' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setFacetDateEnd' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateGap' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateHardEnd' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetDateStart' => ['SolrQuery', 'value'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetEnumCacheMinDefaultFrequency' => ['SolrQuery', 'frequency'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetLimit' => ['SolrQuery', 'limit'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMethod' => ['SolrQuery', 'method'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMinCount' => ['SolrQuery', 'mincount'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetMissing' => ['SolrQuery', 'flag'=>'bool', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetOffset' => ['SolrQuery', 'offset'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetPrefix' => ['SolrQuery', 'prefix'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setFacetSort' => ['SolrQuery', 'facetSort'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setGroup' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupCachePercent' => ['SolrQuery', 'percent'=>'int'],
'SolrDisMaxQuery::setGroupFacet' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupFormat' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setGroupLimit' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setGroupMain' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setGroupNGroups' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setGroupOffset' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setGroupTruncate' => ['SolrQuery', 'value'=>'bool'],
'SolrDisMaxQuery::setHighlight' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightAlternateField' => ['SolrQuery', 'field'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFormatter' => ['SolrQuery', 'formatter'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFragmenter' => ['SolrQuery', 'fragmenter'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightFragsize' => ['SolrQuery', 'size'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightHighlightMultiTerm' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightMaxAlternateFieldLength' => ['SolrQuery', 'fieldLength'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightMaxAnalyzedChars' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setHighlightMergeContiguous' => ['SolrQuery', 'flag'=>'bool', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightRegexMaxAnalyzedChars' => ['SolrQuery', 'maxAnalyzedChars'=>'int'],
'SolrDisMaxQuery::setHighlightRegexPattern' => ['SolrQuery', 'value'=>'string'],
'SolrDisMaxQuery::setHighlightRegexSlop' => ['SolrQuery', 'factor'=>'float'],
'SolrDisMaxQuery::setHighlightRequireFieldMatch' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setHighlightSimplePost' => ['SolrQuery', 'simplePost'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightSimplePre' => ['SolrQuery', 'simplePre'=>'string', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightSnippets' => ['SolrQuery', 'value'=>'int', 'field_override'=>'string'],
'SolrDisMaxQuery::setHighlightUsePhraseHighlighter' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMinimumMatch' => ['SolrDisMaxQuery', 'value'=>'string'],
'SolrDisMaxQuery::setMlt' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMltBoost' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setMltCount' => ['SolrQuery', 'count'=>'int'],
'SolrDisMaxQuery::setMltMaxNumQueryTerms' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setMltMaxNumTokens' => ['SolrQuery', 'value'=>'int'],
'SolrDisMaxQuery::setMltMaxWordLength' => ['SolrQuery', 'maxWordLength'=>'int'],
'SolrDisMaxQuery::setMltMinDocFrequency' => ['SolrQuery', 'minDocFrequency'=>'int'],
'SolrDisMaxQuery::setMltMinTermFrequency' => ['SolrQuery', 'minTermFrequency'=>'int'],
'SolrDisMaxQuery::setMltMinWordLength' => ['SolrQuery', 'minWordLength'=>'int'],
'SolrDisMaxQuery::setOmitHeader' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrDisMaxQuery::setPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setQuery' => ['SolrQuery', 'query'=>'string'],
'SolrDisMaxQuery::setQueryAlt' => ['SolrDisMaxQuery', 'q'=>'string'],
'SolrDisMaxQuery::setQueryPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setRows' => ['SolrQuery', 'rows'=>'int'],
'SolrDisMaxQuery::setShowDebugInfo' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setStart' => ['SolrQuery', 'start'=>'int'],
'SolrDisMaxQuery::setStats' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTerms' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsField' => ['SolrQuery', 'fieldname'=>'string'],
'SolrDisMaxQuery::setTermsIncludeLowerBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsIncludeUpperBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsLimit' => ['SolrQuery', 'limit'=>'int'],
'SolrDisMaxQuery::setTermsLowerBound' => ['SolrQuery', 'lowerBound'=>'string'],
'SolrDisMaxQuery::setTermsMaxCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrDisMaxQuery::setTermsMinCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrDisMaxQuery::setTermsPrefix' => ['SolrQuery', 'prefix'=>'string'],
'SolrDisMaxQuery::setTermsReturnRaw' => ['SolrQuery', 'flag'=>'bool'],
'SolrDisMaxQuery::setTermsSort' => ['SolrQuery', 'sortType'=>'int'],
'SolrDisMaxQuery::setTermsUpperBound' => ['SolrQuery', 'upperBound'=>'string'],
'SolrDisMaxQuery::setTieBreaker' => ['SolrDisMaxQuery', 'tieBreaker'=>'string'],
'SolrDisMaxQuery::setTimeAllowed' => ['SolrQuery', 'timeAllowed'=>'int'],
'SolrDisMaxQuery::setTrigramPhraseFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::setTrigramPhraseSlop' => ['SolrDisMaxQuery', 'slop'=>'string'],
'SolrDisMaxQuery::setUserFields' => ['SolrDisMaxQuery', 'fields'=>'string'],
'SolrDisMaxQuery::toString' => ['string', 'url_encode='=>'bool'],
'SolrDisMaxQuery::unserialize' => ['void', 'serialized'=>'string'],
'SolrDisMaxQuery::useDisMaxQueryParser' => ['SolrDisMaxQuery'],
'SolrDisMaxQuery::useEDisMaxQueryParser' => ['SolrDisMaxQuery'],
'SolrDocument::__clone' => ['void'],
'SolrDocument::__construct' => ['void'],
'SolrDocument::__destruct' => ['void'],
'SolrDocument::__get' => ['SolrDocumentField', 'fieldname'=>'string'],
'SolrDocument::__isset' => ['bool', 'fieldname'=>'string'],
'SolrDocument::__set' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::__unset' => ['bool', 'fieldname'=>'string'],
'SolrDocument::addField' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::clear' => ['bool'],
'SolrDocument::current' => ['SolrDocumentField'],
'SolrDocument::deleteField' => ['bool', 'fieldname'=>'string'],
'SolrDocument::fieldExists' => ['bool', 'fieldname'=>'string'],
'SolrDocument::getChildDocuments' => ['SolrInputDocument[]'],
'SolrDocument::getChildDocumentsCount' => ['int'],
'SolrDocument::getField' => ['SolrDocumentField|false', 'fieldname'=>'string'],
'SolrDocument::getFieldCount' => ['int|false'],
'SolrDocument::getFieldNames' => ['array|false'],
'SolrDocument::getInputDocument' => ['SolrInputDocument'],
'SolrDocument::hasChildDocuments' => ['bool'],
'SolrDocument::key' => ['string'],
'SolrDocument::merge' => ['bool', 'sourcedoc'=>'solrdocument', 'overwrite='=>'bool'],
'SolrDocument::next' => ['void'],
'SolrDocument::offsetExists' => ['bool', 'fieldname'=>'string'],
'SolrDocument::offsetGet' => ['SolrDocumentField', 'fieldname'=>'string'],
'SolrDocument::offsetSet' => ['void', 'fieldname'=>'string', 'fieldvalue'=>'string'],
'SolrDocument::offsetUnset' => ['void', 'fieldname'=>'string'],
'SolrDocument::reset' => ['bool'],
'SolrDocument::rewind' => ['void'],
'SolrDocument::serialize' => ['string'],
'SolrDocument::sort' => ['bool', 'sortorderby'=>'int', 'sortdirection='=>'int'],
'SolrDocument::toArray' => ['array'],
'SolrDocument::unserialize' => ['void', 'serialized'=>'string'],
'SolrDocument::valid' => ['bool'],
'SolrDocumentField::__construct' => ['void'],
'SolrDocumentField::__destruct' => ['void'],
'SolrException::__clone' => ['void'],
'SolrException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrException::__toString' => ['string'],
'SolrException::__wakeup' => ['void'],
'SolrException::getCode' => ['int'],
'SolrException::getFile' => ['string'],
'SolrException::getInternalInfo' => ['array'],
'SolrException::getLine' => ['int'],
'SolrException::getMessage' => ['string'],
'SolrException::getPrevious' => ['Exception|Throwable'],
'SolrException::getTrace' => ['array'],
'SolrException::getTraceAsString' => ['string'],
'SolrGenericResponse::__construct' => ['void'],
'SolrGenericResponse::__destruct' => ['void'],
'SolrGenericResponse::getDigestedResponse' => ['string'],
'SolrGenericResponse::getHttpStatus' => ['int'],
'SolrGenericResponse::getHttpStatusMessage' => ['string'],
'SolrGenericResponse::getRawRequest' => ['string'],
'SolrGenericResponse::getRawRequestHeaders' => ['string'],
'SolrGenericResponse::getRawResponse' => ['string'],
'SolrGenericResponse::getRawResponseHeaders' => ['string'],
'SolrGenericResponse::getRequestUrl' => ['string'],
'SolrGenericResponse::getResponse' => ['SolrObject'],
'SolrGenericResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrGenericResponse::success' => ['bool'],
'SolrIllegalArgumentException::__clone' => ['void'],
'SolrIllegalArgumentException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrIllegalArgumentException::__toString' => ['string'],
'SolrIllegalArgumentException::__wakeup' => ['void'],
'SolrIllegalArgumentException::getCode' => ['int'],
'SolrIllegalArgumentException::getFile' => ['string'],
'SolrIllegalArgumentException::getInternalInfo' => ['array'],
'SolrIllegalArgumentException::getLine' => ['int'],
'SolrIllegalArgumentException::getMessage' => ['string'],
'SolrIllegalArgumentException::getPrevious' => ['Exception|Throwable'],
'SolrIllegalArgumentException::getTrace' => ['array'],
'SolrIllegalArgumentException::getTraceAsString' => ['string'],
'SolrIllegalOperationException::__clone' => ['void'],
'SolrIllegalOperationException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrIllegalOperationException::__toString' => ['string'],
'SolrIllegalOperationException::__wakeup' => ['void'],
'SolrIllegalOperationException::getCode' => ['int'],
'SolrIllegalOperationException::getFile' => ['string'],
'SolrIllegalOperationException::getInternalInfo' => ['array'],
'SolrIllegalOperationException::getLine' => ['int'],
'SolrIllegalOperationException::getMessage' => ['string'],
'SolrIllegalOperationException::getPrevious' => ['Exception|Throwable'],
'SolrIllegalOperationException::getTrace' => ['array'],
'SolrIllegalOperationException::getTraceAsString' => ['string'],
'SolrInputDocument::__clone' => ['void'],
'SolrInputDocument::__construct' => ['void'],
'SolrInputDocument::__destruct' => ['void'],
'SolrInputDocument::addChildDocument' => ['void', 'child'=>'SolrInputDocument'],
'SolrInputDocument::addChildDocuments' => ['void', 'docs'=>'array'],
'SolrInputDocument::addField' => ['bool', 'fieldname'=>'string', 'fieldvalue'=>'string', 'fieldboostvalue='=>'float'],
'SolrInputDocument::clear' => ['bool'],
'SolrInputDocument::deleteField' => ['bool', 'fieldname'=>'string'],
'SolrInputDocument::fieldExists' => ['bool', 'fieldname'=>'string'],
'SolrInputDocument::getBoost' => ['float|false'],
'SolrInputDocument::getChildDocuments' => ['SolrInputDocument[]'],
'SolrInputDocument::getChildDocumentsCount' => ['int'],
'SolrInputDocument::getField' => ['SolrDocumentField|false', 'fieldname'=>'string'],
'SolrInputDocument::getFieldBoost' => ['float|false', 'fieldname'=>'string'],
'SolrInputDocument::getFieldCount' => ['int|false'],
'SolrInputDocument::getFieldNames' => ['array|false'],
'SolrInputDocument::hasChildDocuments' => ['bool'],
'SolrInputDocument::merge' => ['bool', 'sourcedoc'=>'SolrInputDocument', 'overwrite='=>'bool'],
'SolrInputDocument::reset' => ['bool'],
'SolrInputDocument::setBoost' => ['bool', 'documentboostvalue'=>'float'],
'SolrInputDocument::setFieldBoost' => ['bool', 'fieldname'=>'string', 'fieldboostvalue'=>'float'],
'SolrInputDocument::sort' => ['bool', 'sortorderby'=>'int', 'sortdirection='=>'int'],
'SolrInputDocument::toArray' => ['array|false'],
'SolrModifiableParams::__construct' => ['void'],
'SolrModifiableParams::__destruct' => ['void'],
'SolrModifiableParams::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrModifiableParams::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrModifiableParams::get' => ['mixed', 'param_name'=>'string'],
'SolrModifiableParams::getParam' => ['mixed', 'param_name'=>'string'],
'SolrModifiableParams::getParams' => ['array'],
'SolrModifiableParams::getPreparedParams' => ['array'],
'SolrModifiableParams::serialize' => ['string'],
'SolrModifiableParams::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrModifiableParams::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrModifiableParams::toString' => ['string', 'url_encode='=>'bool'],
'SolrModifiableParams::unserialize' => ['void', 'serialized'=>'string'],
'SolrObject::__construct' => ['void'],
'SolrObject::__destruct' => ['void'],
'SolrObject::getPropertyNames' => ['array'],
'SolrObject::offsetExists' => ['bool', 'property_name'=>'string'],
'SolrObject::offsetGet' => ['SolrDocumentField', 'property_name'=>'string'],
'SolrObject::offsetSet' => ['void', 'property_name'=>'string', 'property_value'=>'string'],
'SolrObject::offsetUnset' => ['void', 'property_name'=>'string'],
'SolrParams::__construct' => ['void'],
'SolrParams::add' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::addParam' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::get' => ['mixed', 'param_name'=>'string'],
'SolrParams::getParam' => ['mixed', 'param_name='=>'string'],
'SolrParams::getParams' => ['array'],
'SolrParams::getPreparedParams' => ['array'],
'SolrParams::serialize' => ['string'],
'SolrParams::set' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::setParam' => ['SolrParams|false', 'name'=>'string', 'value'=>'string'],
'SolrParams::toString' => ['string|false', 'url_encode='=>'bool'],
'SolrParams::unserialize' => ['void', 'serialized'=>'string'],
'SolrPingResponse::__construct' => ['void'],
'SolrPingResponse::__destruct' => ['void'],
'SolrPingResponse::getDigestedResponse' => ['string'],
'SolrPingResponse::getHttpStatus' => ['int'],
'SolrPingResponse::getHttpStatusMessage' => ['string'],
'SolrPingResponse::getRawRequest' => ['string'],
'SolrPingResponse::getRawRequestHeaders' => ['string'],
'SolrPingResponse::getRawResponse' => ['string'],
'SolrPingResponse::getRawResponseHeaders' => ['string'],
'SolrPingResponse::getRequestUrl' => ['string'],
'SolrPingResponse::getResponse' => ['string'],
'SolrPingResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrPingResponse::success' => ['bool'],
'SolrQuery::__construct' => ['void', 'q='=>'string'],
'SolrQuery::__destruct' => ['void'],
'SolrQuery::add' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrQuery::addExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::addExpandSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'string'],
'SolrQuery::addFacetDateField' => ['SolrQuery', 'datefield'=>'string'],
'SolrQuery::addFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::addFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addFacetQuery' => ['SolrQuery', 'facetquery'=>'string'],
'SolrQuery::addField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::addGroupField' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupFunction' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupQuery' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::addGroupSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrQuery::addHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addMltField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addMltQueryField' => ['SolrQuery', 'field'=>'string', 'boost'=>'float'],
'SolrQuery::addParam' => ['SolrParams', 'name'=>'string', 'value'=>'string'],
'SolrQuery::addSortField' => ['SolrQuery', 'field'=>'string', 'order='=>'int'],
'SolrQuery::addStatsFacet' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::addStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::collapse' => ['SolrQuery', 'collapseFunction'=>'SolrCollapseFunction'],
'SolrQuery::get' => ['mixed', 'param_name'=>'string'],
'SolrQuery::getExpand' => ['bool'],
'SolrQuery::getExpandFilterQueries' => ['array'],
'SolrQuery::getExpandQuery' => ['array'],
'SolrQuery::getExpandRows' => ['int'],
'SolrQuery::getExpandSortFields' => ['array'],
'SolrQuery::getFacet' => ['?bool'],
'SolrQuery::getFacetDateEnd' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateFields' => ['array'],
'SolrQuery::getFacetDateGap' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateHardEnd' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateOther' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetDateStart' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetFields' => ['array'],
'SolrQuery::getFacetLimit' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetMethod' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetMinCount' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetMissing' => ['?bool', 'field_override='=>'string'],
'SolrQuery::getFacetOffset' => ['?int', 'field_override='=>'string'],
'SolrQuery::getFacetPrefix' => ['?string', 'field_override='=>'string'],
'SolrQuery::getFacetQueries' => ['?array'],
'SolrQuery::getFacetSort' => ['int', 'field_override='=>'string'],
'SolrQuery::getFields' => ['?array'],
'SolrQuery::getFilterQueries' => ['?array'],
'SolrQuery::getGroup' => ['bool'],
'SolrQuery::getGroupCachePercent' => ['int'],
'SolrQuery::getGroupFacet' => ['bool'],
'SolrQuery::getGroupFields' => ['array'],
'SolrQuery::getGroupFormat' => ['string'],
'SolrQuery::getGroupFunctions' => ['array'],
'SolrQuery::getGroupLimit' => ['int'],
'SolrQuery::getGroupMain' => ['bool'],
'SolrQuery::getGroupNGroups' => ['bool'],
'SolrQuery::getGroupOffset' => ['int'],
'SolrQuery::getGroupQueries' => ['array'],
'SolrQuery::getGroupSortFields' => ['array'],
'SolrQuery::getGroupTruncate' => ['bool'],
'SolrQuery::getHighlight' => ['bool'],
'SolrQuery::getHighlightAlternateField' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFields' => ['?array'],
'SolrQuery::getHighlightFormatter' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFragmenter' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightFragsize' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightHighlightMultiTerm' => ['?bool'],
'SolrQuery::getHighlightMaxAlternateFieldLength' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightMaxAnalyzedChars' => ['?int'],
'SolrQuery::getHighlightMergeContiguous' => ['?bool', 'field_override='=>'string'],
'SolrQuery::getHighlightRegexMaxAnalyzedChars' => ['?int'],
'SolrQuery::getHighlightRegexPattern' => ['?string'],
'SolrQuery::getHighlightRegexSlop' => ['?float'],
'SolrQuery::getHighlightRequireFieldMatch' => ['?bool'],
'SolrQuery::getHighlightSimplePost' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightSimplePre' => ['?string', 'field_override='=>'string'],
'SolrQuery::getHighlightSnippets' => ['?int', 'field_override='=>'string'],
'SolrQuery::getHighlightUsePhraseHighlighter' => ['?bool'],
'SolrQuery::getMlt' => ['?bool'],
'SolrQuery::getMltBoost' => ['?bool'],
'SolrQuery::getMltCount' => ['?int'],
'SolrQuery::getMltFields' => ['?array'],
'SolrQuery::getMltMaxNumQueryTerms' => ['?int'],
'SolrQuery::getMltMaxNumTokens' => ['?int'],
'SolrQuery::getMltMaxWordLength' => ['?int'],
'SolrQuery::getMltMinDocFrequency' => ['?int'],
'SolrQuery::getMltMinTermFrequency' => ['?int'],
'SolrQuery::getMltMinWordLength' => ['?int'],
'SolrQuery::getMltQueryFields' => ['?array'],
'SolrQuery::getParam' => ['?mixed', 'param_name'=>'string'],
'SolrQuery::getParams' => ['?array'],
'SolrQuery::getPreparedParams' => ['?array'],
'SolrQuery::getQuery' => ['?string'],
'SolrQuery::getRows' => ['?int'],
'SolrQuery::getSortFields' => ['?array'],
'SolrQuery::getStart' => ['?int'],
'SolrQuery::getStats' => ['?bool'],
'SolrQuery::getStatsFacets' => ['?array'],
'SolrQuery::getStatsFields' => ['?array'],
'SolrQuery::getTerms' => ['?bool'],
'SolrQuery::getTermsField' => ['?string'],
'SolrQuery::getTermsIncludeLowerBound' => ['?bool'],
'SolrQuery::getTermsIncludeUpperBound' => ['?bool'],
'SolrQuery::getTermsLimit' => ['?int'],
'SolrQuery::getTermsLowerBound' => ['?string'],
'SolrQuery::getTermsMaxCount' => ['?int'],
'SolrQuery::getTermsMinCount' => ['?int'],
'SolrQuery::getTermsPrefix' => ['?string'],
'SolrQuery::getTermsReturnRaw' => ['?bool'],
'SolrQuery::getTermsSort' => ['?int'],
'SolrQuery::getTermsUpperBound' => ['?string'],
'SolrQuery::getTimeAllowed' => ['?int'],
'SolrQuery::removeExpandFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::removeExpandSortField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetDateField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetDateOther' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::removeFacetField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFacetQuery' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::removeField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeFilterQuery' => ['SolrQuery', 'fq'=>'string'],
'SolrQuery::removeHighlightField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeMltField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeMltQueryField' => ['SolrQuery', 'queryfield'=>'string'],
'SolrQuery::removeSortField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::removeStatsFacet' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::removeStatsField' => ['SolrQuery', 'field'=>'string'],
'SolrQuery::serialize' => ['string'],
'SolrQuery::set' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrQuery::setEchoHandler' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setEchoParams' => ['SolrQuery', 'type'=>'string'],
'SolrQuery::setExpand' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setExpandQuery' => ['SolrQuery', 'q'=>'string'],
'SolrQuery::setExpandRows' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setExplainOther' => ['SolrQuery', 'query'=>'string'],
'SolrQuery::setFacet' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setFacetDateEnd' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetDateGap' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetDateHardEnd' => ['SolrQuery', 'value'=>'bool', 'field_override='=>'string'],
'SolrQuery::setFacetDateStart' => ['SolrQuery', 'value'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetEnumCacheMinDefaultFrequency' => ['SolrQuery', 'frequency'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetLimit' => ['SolrQuery', 'limit'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetMethod' => ['SolrQuery', 'method'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetMinCount' => ['SolrQuery', 'mincount'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetMissing' => ['SolrQuery', 'flag'=>'bool', 'field_override='=>'string'],
'SolrQuery::setFacetOffset' => ['SolrQuery', 'offset'=>'int', 'field_override='=>'string'],
'SolrQuery::setFacetPrefix' => ['SolrQuery', 'prefix'=>'string', 'field_override='=>'string'],
'SolrQuery::setFacetSort' => ['SolrQuery', 'facetsort'=>'int', 'field_override='=>'string'],
'SolrQuery::setGroup' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupCachePercent' => ['SolrQuery', 'percent'=>'int'],
'SolrQuery::setGroupFacet' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupFormat' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setGroupLimit' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setGroupMain' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setGroupNGroups' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setGroupOffset' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setGroupTruncate' => ['SolrQuery', 'value'=>'bool'],
'SolrQuery::setHighlight' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightAlternateField' => ['SolrQuery', 'field'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFormatter' => ['SolrQuery', 'formatter'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFragmenter' => ['SolrQuery', 'fragmenter'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightFragsize' => ['SolrQuery', 'size'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightHighlightMultiTerm' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightMaxAlternateFieldLength' => ['SolrQuery', 'fieldlength'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightMaxAnalyzedChars' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setHighlightMergeContiguous' => ['SolrQuery', 'flag'=>'bool', 'field_override='=>'string'],
'SolrQuery::setHighlightRegexMaxAnalyzedChars' => ['SolrQuery', 'maxanalyzedchars'=>'int'],
'SolrQuery::setHighlightRegexPattern' => ['SolrQuery', 'value'=>'string'],
'SolrQuery::setHighlightRegexSlop' => ['SolrQuery', 'factor'=>'float'],
'SolrQuery::setHighlightRequireFieldMatch' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setHighlightSimplePost' => ['SolrQuery', 'simplepost'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightSimplePre' => ['SolrQuery', 'simplepre'=>'string', 'field_override='=>'string'],
'SolrQuery::setHighlightSnippets' => ['SolrQuery', 'value'=>'int', 'field_override='=>'string'],
'SolrQuery::setHighlightUsePhraseHighlighter' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMlt' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMltBoost' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setMltCount' => ['SolrQuery', 'count'=>'int'],
'SolrQuery::setMltMaxNumQueryTerms' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setMltMaxNumTokens' => ['SolrQuery', 'value'=>'int'],
'SolrQuery::setMltMaxWordLength' => ['SolrQuery', 'maxwordlength'=>'int'],
'SolrQuery::setMltMinDocFrequency' => ['SolrQuery', 'mindocfrequency'=>'int'],
'SolrQuery::setMltMinTermFrequency' => ['SolrQuery', 'mintermfrequency'=>'int'],
'SolrQuery::setMltMinWordLength' => ['SolrQuery', 'minwordlength'=>'int'],
'SolrQuery::setOmitHeader' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setParam' => ['SolrParams', 'name'=>'string', 'value'=>''],
'SolrQuery::setQuery' => ['SolrQuery', 'query'=>'string'],
'SolrQuery::setRows' => ['SolrQuery', 'rows'=>'int'],
'SolrQuery::setShowDebugInfo' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setStart' => ['SolrQuery', 'start'=>'int'],
'SolrQuery::setStats' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTerms' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsField' => ['SolrQuery', 'fieldname'=>'string'],
'SolrQuery::setTermsIncludeLowerBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsIncludeUpperBound' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsLimit' => ['SolrQuery', 'limit'=>'int'],
'SolrQuery::setTermsLowerBound' => ['SolrQuery', 'lowerbound'=>'string'],
'SolrQuery::setTermsMaxCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrQuery::setTermsMinCount' => ['SolrQuery', 'frequency'=>'int'],
'SolrQuery::setTermsPrefix' => ['SolrQuery', 'prefix'=>'string'],
'SolrQuery::setTermsReturnRaw' => ['SolrQuery', 'flag'=>'bool'],
'SolrQuery::setTermsSort' => ['SolrQuery', 'sorttype'=>'int'],
'SolrQuery::setTermsUpperBound' => ['SolrQuery', 'upperbound'=>'string'],
'SolrQuery::setTimeAllowed' => ['SolrQuery', 'timeallowed'=>'int'],
'SolrQuery::toString' => ['string', 'url_encode='=>'bool'],
'SolrQuery::unserialize' => ['void', 'serialized'=>'string'],
'SolrQueryResponse::__construct' => ['void'],
'SolrQueryResponse::__destruct' => ['void'],
'SolrQueryResponse::getDigestedResponse' => ['string'],
'SolrQueryResponse::getHttpStatus' => ['int'],
'SolrQueryResponse::getHttpStatusMessage' => ['string'],
'SolrQueryResponse::getRawRequest' => ['string'],
'SolrQueryResponse::getRawRequestHeaders' => ['string'],
'SolrQueryResponse::getRawResponse' => ['string'],
'SolrQueryResponse::getRawResponseHeaders' => ['string'],
'SolrQueryResponse::getRequestUrl' => ['string'],
'SolrQueryResponse::getResponse' => ['SolrObject'],
'SolrQueryResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrQueryResponse::success' => ['bool'],
'SolrResponse::getDigestedResponse' => ['string'],
'SolrResponse::getHttpStatus' => ['int'],
'SolrResponse::getHttpStatusMessage' => ['string'],
'SolrResponse::getRawRequest' => ['string'],
'SolrResponse::getRawRequestHeaders' => ['string'],
'SolrResponse::getRawResponse' => ['string'],
'SolrResponse::getRawResponseHeaders' => ['string'],
'SolrResponse::getRequestUrl' => ['string'],
'SolrResponse::getResponse' => ['SolrObject'],
'SolrResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrResponse::success' => ['bool'],
'SolrServerException::__clone' => ['void'],
'SolrServerException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'SolrServerException::__toString' => ['string'],
'SolrServerException::__wakeup' => ['void'],
'SolrServerException::getCode' => ['int'],
'SolrServerException::getFile' => ['string'],
'SolrServerException::getInternalInfo' => ['array'],
'SolrServerException::getLine' => ['int'],
'SolrServerException::getMessage' => ['string'],
'SolrServerException::getPrevious' => ['Exception|Throwable'],
'SolrServerException::getTrace' => ['array'],
'SolrServerException::getTraceAsString' => ['string'],
'SolrUpdateResponse::__construct' => ['void'],
'SolrUpdateResponse::__destruct' => ['void'],
'SolrUpdateResponse::getDigestedResponse' => ['string'],
'SolrUpdateResponse::getHttpStatus' => ['int'],
'SolrUpdateResponse::getHttpStatusMessage' => ['string'],
'SolrUpdateResponse::getRawRequest' => ['string'],
'SolrUpdateResponse::getRawRequestHeaders' => ['string'],
'SolrUpdateResponse::getRawResponse' => ['string'],
'SolrUpdateResponse::getRawResponseHeaders' => ['string'],
'SolrUpdateResponse::getRequestUrl' => ['string'],
'SolrUpdateResponse::getResponse' => ['SolrObject'],
'SolrUpdateResponse::setParseMode' => ['bool', 'parser_mode='=>'int'],
'SolrUpdateResponse::success' => ['bool'],
'SolrUtils::digestXmlResponse' => ['SolrObject', 'xmlresponse'=>'string', 'parse_mode='=>'int'],
'SolrUtils::escapeQueryChars' => ['string|false', 'str'=>'string'],
'SolrUtils::getSolrVersion' => ['string'],
'SolrUtils::queryPhrase' => ['string', 'str'=>'string'],
'sort' => ['bool', '&rw_array_arg'=>'array', 'sort_flags='=>'int'],
'soundex' => ['string', 'str'=>'string'],
'SphinxClient::__construct' => ['void'],
'SphinxClient::addQuery' => ['int', 'query'=>'string', 'index='=>'string', 'comment='=>'string'],
'SphinxClient::buildExcerpts' => ['array', 'docs'=>'array', 'index'=>'string', 'words'=>'string', 'opts='=>'array'],
'SphinxClient::buildKeywords' => ['array', 'query'=>'string', 'index'=>'string', 'hits'=>'bool'],
'SphinxClient::close' => ['bool'],
'SphinxClient::escapeString' => ['string', 'string'=>'string'],
'SphinxClient::getLastError' => ['string'],
'SphinxClient::getLastWarning' => ['string'],
'SphinxClient::open' => ['bool'],
'SphinxClient::query' => ['array', 'query'=>'string', 'index='=>'string', 'comment='=>'string'],
'SphinxClient::resetFilters' => ['void'],
'SphinxClient::resetGroupBy' => ['void'],
'SphinxClient::runQueries' => ['array'],
'SphinxClient::setArrayResult' => ['bool', 'array_result'=>'bool'],
'SphinxClient::setConnectTimeout' => ['bool', 'timeout'=>'float'],
'SphinxClient::setFieldWeights' => ['bool', 'weights'=>'array'],
'SphinxClient::setFilter' => ['bool', 'attribute'=>'string', 'values'=>'array', 'exclude='=>'bool'],
'SphinxClient::setFilterFloatRange' => ['bool', 'attribute'=>'string', 'min'=>'float', 'max'=>'float', 'exclude='=>'bool'],
'SphinxClient::setFilterRange' => ['bool', 'attribute'=>'string', 'min'=>'int', 'max'=>'int', 'exclude='=>'bool'],
'SphinxClient::setGeoAnchor' => ['bool', 'attrlat'=>'string', 'attrlong'=>'string', 'latitude'=>'float', 'longitude'=>'float'],
'SphinxClient::setGroupBy' => ['bool', 'attribute'=>'string', 'func'=>'int', 'groupsort='=>'string'],
'SphinxClient::setGroupDistinct' => ['bool', 'attribute'=>'string'],
'SphinxClient::setIDRange' => ['bool', 'min'=>'int', 'max'=>'int'],
'SphinxClient::setIndexWeights' => ['bool', 'weights'=>'array'],
'SphinxClient::setLimits' => ['bool', 'offset'=>'int', 'limit'=>'int', 'max_matches='=>'int', 'cutoff='=>'int'],
'SphinxClient::setMatchMode' => ['bool', 'mode'=>'int'],
'SphinxClient::setMaxQueryTime' => ['bool', 'qtime'=>'int'],
'SphinxClient::setOverride' => ['bool', 'attribute'=>'string', 'type'=>'int', 'values'=>'array'],
'SphinxClient::setRankingMode' => ['bool', 'ranker'=>'int'],
'SphinxClient::setRetries' => ['bool', 'count'=>'int', 'delay='=>'int'],
'SphinxClient::setSelect' => ['bool', 'clause'=>'string'],
'SphinxClient::setServer' => ['bool', 'server'=>'string', 'port'=>'int'],
'SphinxClient::setSortMode' => ['bool', 'mode'=>'int', 'sortby='=>'string'],
'SphinxClient::status' => ['array'],
'SphinxClient::updateAttributes' => ['int', 'index'=>'string', 'attributes'=>'array', 'values'=>'array', 'mva='=>'bool'],
'spl_autoload' => ['void', 'class_name'=>'string', 'file_extensions='=>'string'],
'spl_autoload_call' => ['void', 'class_name'=>'string'],
'spl_autoload_extensions' => ['string', 'file_extensions='=>'string'],
'spl_autoload_functions' => ['false|array'],
'spl_autoload_register' => ['bool', 'autoload_function='=>'callable(string):void', 'throw='=>'bool', 'prepend='=>'bool'],
'spl_autoload_unregister' => ['bool', 'autoload_function'=>'mixed'],
'spl_classes' => ['array'],
'spl_object_hash' => ['string', 'obj'=>'object'],
'spl_object_id' => ['int', 'obj'=>'object'],
'SplDoublyLinkedList::__construct' => ['void'],
'SplDoublyLinkedList::add' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplDoublyLinkedList::bottom' => ['mixed'],
'SplDoublyLinkedList::count' => ['int'],
'SplDoublyLinkedList::current' => ['mixed'],
'SplDoublyLinkedList::getIteratorMode' => ['int'],
'SplDoublyLinkedList::isEmpty' => ['bool'],
'SplDoublyLinkedList::key' => ['mixed'],
'SplDoublyLinkedList::next' => ['void'],
'SplDoublyLinkedList::offsetExists' => ['bool', 'index'=>'mixed'],
'SplDoublyLinkedList::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplDoublyLinkedList::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplDoublyLinkedList::offsetUnset' => ['void', 'index'=>'mixed'],
'SplDoublyLinkedList::pop' => ['mixed'],
'SplDoublyLinkedList::prev' => ['void'],
'SplDoublyLinkedList::push' => ['void', 'value'=>'mixed'],
'SplDoublyLinkedList::rewind' => ['void'],
'SplDoublyLinkedList::serialize' => ['string'],
'SplDoublyLinkedList::setIteratorMode' => ['void', 'flags'=>'int'],
'SplDoublyLinkedList::shift' => ['mixed'],
'SplDoublyLinkedList::top' => ['mixed'],
'SplDoublyLinkedList::unserialize' => ['void', 'serialized'=>'string'],
'SplDoublyLinkedList::unshift' => ['bool', 'value'=>'mixed'],
'SplDoublyLinkedList::valid' => ['bool'],
'SplEnum::__construct' => ['void', 'initial_value='=>'mixed', 'strict='=>'bool'],
'SplEnum::getConstList' => ['array', 'include_default='=>'bool'],
'SplFileInfo::__construct' => ['void', 'file_name'=>'string'],
'SplFileInfo::__toString' => ['string'],
'SplFileInfo::__wakeup' => ['void'],
'SplFileInfo::getATime' => ['int'],
'SplFileInfo::getBasename' => ['string', 'suffix='=>'string'],
'SplFileInfo::getCTime' => ['int'],
'SplFileInfo::getExtension' => ['string'],
'SplFileInfo::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileInfo::getFilename' => ['string'],
'SplFileInfo::getGroup' => ['int'],
'SplFileInfo::getInode' => ['int'],
'SplFileInfo::getLinkTarget' => ['string'],
'SplFileInfo::getMTime' => ['int'],
'SplFileInfo::getOwner' => ['int'],
'SplFileInfo::getPath' => ['string'],
'SplFileInfo::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileInfo::getPathname' => ['string'],
'SplFileInfo::getPerms' => ['int'],
'SplFileInfo::getRealPath' => ['string|false'],
'SplFileInfo::getSize' => ['int'],
'SplFileInfo::getType' => ['string'],
'SplFileInfo::isDir' => ['bool'],
'SplFileInfo::isExecutable' => ['bool'],
'SplFileInfo::isFile' => ['bool'],
'SplFileInfo::isLink' => ['bool'],
'SplFileInfo::isReadable' => ['bool'],
'SplFileInfo::isWritable' => ['bool'],
'SplFileInfo::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplFileInfo::setFileClass' => ['void', 'class_name='=>'string'],
'SplFileInfo::setInfoClass' => ['void', 'class_name='=>'string'],
'SplFileObject::__construct' => ['void', 'filename'=>'string', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>''],
'SplFileObject::__toString' => ['string'],
'SplFileObject::current' => ['string|array|false'],
'SplFileObject::eof' => ['bool'],
'SplFileObject::fflush' => ['bool'],
'SplFileObject::fgetc' => ['string|false'],
'SplFileObject::fgetcsv' => ['?array|false', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fgets' => ['string|false'],
'SplFileObject::fgetss' => ['string|false', 'allowable_tags='=>'string'],
'SplFileObject::flock' => ['bool', 'operation'=>'int', '&w_wouldblock='=>'int'],
'SplFileObject::fpassthru' => ['int|false'],
'SplFileObject::fputcsv' => ['int|false', 'fields'=>'array', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::fread' => ['string|false', 'length'=>'int'],
'SplFileObject::fscanf' => ['array|int', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'SplFileObject::fseek' => ['int', 'pos'=>'int', 'whence='=>'int'],
'SplFileObject::fstat' => ['array|false'],
'SplFileObject::ftell' => ['int|false'],
'SplFileObject::ftruncate' => ['bool', 'size'=>'int'],
'SplFileObject::fwrite' => ['int', 'str'=>'string', 'length='=>'int'],
'SplFileObject::getATime' => ['int'],
'SplFileObject::getBasename' => ['string', 'suffix='=>'string'],
'SplFileObject::getChildren' => ['null'],
'SplFileObject::getCsvControl' => ['array'],
'SplFileObject::getCTime' => ['int'],
'SplFileObject::getCurrentLine' => ['string|false'],
'SplFileObject::getExtension' => ['string'],
'SplFileObject::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileObject::getFilename' => ['string'],
'SplFileObject::getFlags' => ['int'],
'SplFileObject::getGroup' => ['int'],
'SplFileObject::getInode' => ['int'],
'SplFileObject::getLinkTarget' => ['string'],
'SplFileObject::getMaxLineLen' => ['int'],
'SplFileObject::getMTime' => ['int'],
'SplFileObject::getOwner' => ['int'],
'SplFileObject::getPath' => ['string'],
'SplFileObject::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplFileObject::getPathname' => ['string'],
'SplFileObject::getPerms' => ['int'],
'SplFileObject::getRealPath' => ['false|string'],
'SplFileObject::getSize' => ['int'],
'SplFileObject::getType' => ['string'],
'SplFileObject::hasChildren' => ['bool'],
'SplFileObject::isDir' => ['bool'],
'SplFileObject::isExecutable' => ['bool'],
'SplFileObject::isFile' => ['bool'],
'SplFileObject::isLink' => ['bool'],
'SplFileObject::isReadable' => ['bool'],
'SplFileObject::isWritable' => ['bool'],
'SplFileObject::key' => ['int'],
'SplFileObject::next' => ['void'],
'SplFileObject::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplFileObject::rewind' => ['void'],
'SplFileObject::seek' => ['void', 'line_pos'=>'int'],
'SplFileObject::setCsvControl' => ['void', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplFileObject::setFileClass' => ['void', 'class_name='=>'string'],
'SplFileObject::setFlags' => ['void', 'flags'=>'int'],
'SplFileObject::setInfoClass' => ['void', 'class_name='=>'string'],
'SplFileObject::setMaxLineLen' => ['void', 'max_len'=>'int'],
'SplFileObject::valid' => ['bool'],
'SplFixedArray::__construct' => ['void', 'size='=>'int'],
'SplFixedArray::__wakeup' => ['void'],
'SplFixedArray::count' => ['int'],
'SplFixedArray::current' => ['mixed'],
'SplFixedArray::fromArray' => ['SplFixedArray', 'data'=>'array', 'save_indexes='=>'bool'],
'SplFixedArray::getSize' => ['int'],
'SplFixedArray::key' => ['int'],
'SplFixedArray::next' => ['void'],
'SplFixedArray::offsetExists' => ['bool', 'index'=>'int'],
'SplFixedArray::offsetGet' => ['mixed', 'index'=>'int'],
'SplFixedArray::offsetSet' => ['void', 'index'=>'int', 'newval'=>'mixed'],
'SplFixedArray::offsetUnset' => ['void', 'index'=>'int'],
'SplFixedArray::rewind' => ['void'],
'SplFixedArray::setSize' => ['bool', 'size'=>'int'],
'SplFixedArray::toArray' => ['array'],
'SplFixedArray::valid' => ['bool'],
'SplHeap::__construct' => ['void'],
'SplHeap::compare' => ['int', 'value1'=>'mixed', 'value2'=>'mixed'],
'SplHeap::count' => ['int'],
'SplHeap::current' => ['mixed'],
'SplHeap::extract' => ['mixed'],
'SplHeap::insert' => ['bool', 'value'=>'mixed'],
'SplHeap::isCorrupted' => ['bool'],
'SplHeap::isEmpty' => ['bool'],
'SplHeap::key' => ['int'],
'SplHeap::next' => ['void'],
'SplHeap::recoverFromCorruption' => ['int'],
'SplHeap::rewind' => ['void'],
'SplHeap::top' => ['mixed'],
'SplHeap::valid' => ['bool'],
'SplMaxHeap::__construct' => ['void'],
'SplMaxHeap::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplMinHeap::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplMinHeap::count' => ['int'],
'SplMinHeap::current' => ['mixed'],
'SplMinHeap::extract' => ['mixed'],
'SplMinHeap::insert' => ['void', 'value'=>'mixed'],
'SplMinHeap::isCorrupted' => ['int'],
'SplMinHeap::isEmpty' => ['bool'],
'SplMinHeap::key' => ['mixed'],
'SplMinHeap::next' => ['void'],
'SplMinHeap::recoverFromCorruption' => ['void'],
'SplMinHeap::rewind' => ['void'],
'SplMinHeap::top' => ['mixed'],
'SplMinHeap::valid' => ['bool'],
'SplObjectStorage::__construct' => ['void'],
'SplObjectStorage::addAll' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::attach' => ['void', 'obj'=>'object', 'inf='=>'mixed'],
'SplObjectStorage::contains' => ['bool', 'obj'=>'object'],
'SplObjectStorage::count' => ['int'],
'SplObjectStorage::current' => ['object'],
'SplObjectStorage::detach' => ['void', 'obj'=>'object'],
'SplObjectStorage::getHash' => ['string', 'obj'=>'object'],
'SplObjectStorage::getInfo' => ['mixed'],
'SplObjectStorage::key' => ['int'],
'SplObjectStorage::next' => ['void'],
'SplObjectStorage::offsetExists' => ['bool', 'object'=>'object'],
'SplObjectStorage::offsetGet' => ['mixed', 'obj'=>'object'],
'SplObjectStorage::offsetSet' => ['object', 'object'=>'object', 'data='=>'mixed'],
'SplObjectStorage::offsetUnset' => ['object', 'object'=>'object'],
'SplObjectStorage::removeAll' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::removeAllExcept' => ['void', 'os'=>'splobjectstorage'],
'SplObjectStorage::rewind' => ['void'],
'SplObjectStorage::serialize' => ['string'],
'SplObjectStorage::setInfo' => ['void', 'inf'=>'mixed'],
'SplObjectStorage::unserialize' => ['void', 'serialized'=>'string'],
'SplObjectStorage::valid' => ['bool'],
'SplObserver::update' => ['void', 'subject'=>'SplSubject'],
'SplPriorityQueue::__construct' => ['void'],
'SplPriorityQueue::compare' => ['int', 'a'=>'mixed', 'b'=>'mixed'],
'SplPriorityQueue::count' => ['int'],
'SplPriorityQueue::current' => ['mixed'],
'SplPriorityQueue::extract' => ['mixed'],
'SplPriorityQueue::getExtractFlags' => ['int'],
'SplPriorityQueue::insert' => ['bool', 'value'=>'mixed', 'priority'=>'mixed'],
'SplPriorityQueue::isCorrupted' => ['bool'],
'SplPriorityQueue::isEmpty' => ['bool'],
'SplPriorityQueue::key' => ['mixed'],
'SplPriorityQueue::next' => ['void'],
'SplPriorityQueue::recoverFromCorruption' => ['void'],
'SplPriorityQueue::rewind' => ['void'],
'SplPriorityQueue::setExtractFlags' => ['void', 'flags'=>'int'],
'SplPriorityQueue::top' => ['mixed'],
'SplPriorityQueue::valid' => ['bool'],
'SplQueue::dequeue' => ['mixed'],
'SplQueue::enqueue' => ['void', 'value'=>'mixed'],
'SplQueue::getIteratorMode' => ['int'],
'SplQueue::isEmpty' => ['bool'],
'SplQueue::key' => ['mixed'],
'SplQueue::next' => ['void'],
'SplQueue::offsetExists' => ['bool', 'index'=>'mixed'],
'SplQueue::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplQueue::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplQueue::offsetUnset' => ['void', 'index'=>'mixed'],
'SplQueue::pop' => ['mixed'],
'SplQueue::prev' => ['void'],
'SplQueue::push' => ['void', 'value'=>'mixed'],
'SplQueue::rewind' => ['void'],
'SplQueue::serialize' => ['string'],
'SplQueue::setIteratorMode' => ['void', 'mode'=>'int'],
'SplQueue::shift' => ['mixed'],
'SplQueue::top' => ['mixed'],
'SplQueue::unserialize' => ['void', 'serialized'=>'string'],
'SplQueue::unshift' => ['bool', 'value'=>'mixed'],
'SplQueue::valid' => ['bool'],
'SplStack::__construct' => ['void'],
'SplStack::add' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplStack::bottom' => ['mixed'],
'SplStack::count' => ['int'],
'SplStack::current' => ['mixed'],
'SplStack::getIteratorMode' => ['int'],
'SplStack::isEmpty' => ['bool'],
'SplStack::key' => ['mixed'],
'SplStack::next' => ['void'],
'SplStack::offsetExists' => ['bool', 'index'=>'mixed'],
'SplStack::offsetGet' => ['mixed', 'index'=>'mixed'],
'SplStack::offsetSet' => ['void', 'index'=>'mixed', 'newval'=>'mixed'],
'SplStack::offsetUnset' => ['void', 'index'=>'mixed'],
'SplStack::pop' => ['mixed'],
'SplStack::prev' => ['void'],
'SplStack::push' => ['void', 'value'=>'mixed'],
'SplStack::rewind' => ['void'],
'SplStack::serialize' => ['string'],
'SplStack::setIteratorMode' => ['void', 'mode'=>'int'],
'SplStack::shift' => ['mixed'],
'SplStack::top' => ['mixed'],
'SplStack::unserialize' => ['void', 'serialized'=>'string'],
'SplStack::unshift' => ['bool', 'value'=>'mixed'],
'SplStack::valid' => ['bool'],
'SplSubject::attach' => ['void', 'observer'=>'SplObserver'],
'SplSubject::detach' => ['void', 'observer'=>'SplObserver'],
'SplSubject::notify' => ['void'],
'SplTempFileObject::__construct' => ['void', 'max_memory='=>'int'],
'SplTempFileObject::__toString' => ['string'],
'SplTempFileObject::_bad_state_ex' => [''],
'SplTempFileObject::current' => ['array|false|string'],
'SplTempFileObject::eof' => ['bool'],
'SplTempFileObject::fflush' => ['bool'],
'SplTempFileObject::fgetc' => ['false|string'],
'SplTempFileObject::fgetcsv' => ['?array|false', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::fgets' => ['string'],
'SplTempFileObject::fgetss' => ['string', 'allowable_tags='=>'string'],
'SplTempFileObject::flock' => ['bool', 'operation'=>'int', '&wouldblock='=>'int'],
'SplTempFileObject::fpassthru' => ['int|false'],
'SplTempFileObject::fputcsv' => ['false|int', 'fields'=>'array', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::fread' => ['false|string', 'length'=>'int'],
'SplTempFileObject::fscanf' => ['bool', 'format'=>'string', '&...w_vars='=>'array<int,float>|array<int,int>|array<int,string>'],
'SplTempFileObject::fseek' => ['int', 'pos'=>'int', 'whence='=>'int'],
'SplTempFileObject::fstat' => ['array|false'],
'SplTempFileObject::ftell' => ['int'],
'SplTempFileObject::ftruncate' => ['bool', 'size'=>'int'],
'SplTempFileObject::fwrite' => ['int', 'str'=>'string', 'length='=>'int'],
'SplTempFileObject::getATime' => ['int'],
'SplTempFileObject::getBasename' => ['string', 'suffix='=>'string'],
'SplTempFileObject::getChildren' => ['null'],
'SplTempFileObject::getCsvControl' => ['array'],
'SplTempFileObject::getCTime' => ['int'],
'SplTempFileObject::getCurrentLine' => ['string'],
'SplTempFileObject::getExtension' => ['string'],
'SplTempFileObject::getFileInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplTempFileObject::getFilename' => ['string'],
'SplTempFileObject::getFlags' => ['int'],
'SplTempFileObject::getGroup' => ['int'],
'SplTempFileObject::getInode' => ['int'],
'SplTempFileObject::getLinkTarget' => ['string'],
'SplTempFileObject::getMaxLineLen' => ['int'],
'SplTempFileObject::getMTime' => ['int'],
'SplTempFileObject::getOwner' => ['int'],
'SplTempFileObject::getPath' => ['string'],
'SplTempFileObject::getPathInfo' => ['SplFileInfo', 'class_name='=>'string'],
'SplTempFileObject::getPathname' => ['string'],
'SplTempFileObject::getPerms' => ['int'],
'SplTempFileObject::getRealPath' => ['string'],
'SplTempFileObject::getSize' => ['int'],
'SplTempFileObject::getType' => ['string'],
'SplTempFileObject::hasChildren' => ['bool'],
'SplTempFileObject::isDir' => ['bool'],
'SplTempFileObject::isExecutable' => ['bool'],
'SplTempFileObject::isFile' => ['bool'],
'SplTempFileObject::isLink' => ['bool'],
'SplTempFileObject::isReadable' => ['bool'],
'SplTempFileObject::isWritable' => ['bool'],
'SplTempFileObject::key' => ['int'],
'SplTempFileObject::next' => ['void'],
'SplTempFileObject::openFile' => ['SplFileObject', 'mode='=>'string', 'use_include_path='=>'bool', 'context='=>'resource'],
'SplTempFileObject::rewind' => ['void'],
'SplTempFileObject::seek' => ['void', 'line_pos'=>'int'],
'SplTempFileObject::setCsvControl' => ['void', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'SplTempFileObject::setFileClass' => ['void', 'class_name='=>'string'],
'SplTempFileObject::setFlags' => ['void', 'flags'=>'int'],
'SplTempFileObject::setInfoClass' => ['void', 'class_name='=>'string'],
'SplTempFileObject::setMaxLineLen' => ['void', 'max_len'=>'int'],
'SplTempFileObject::valid' => ['bool'],
'SplType::__construct' => ['void', 'initial_value='=>'mixed', 'strict='=>'bool'],
'Spoofchecker::__construct' => ['void'],
'Spoofchecker::areConfusable' => ['bool', 's1'=>'string', 's2'=>'string', '&w_error='=>'string'],
'Spoofchecker::isSuspicious' => ['bool', 'text'=>'string', '&w_error='=>'string'],
'Spoofchecker::setAllowedLocales' => ['void', 'locale_list'=>'string'],
'Spoofchecker::setChecks' => ['void', 'checks'=>'long'],
'Spoofchecker::setRestrictionLevel' => ['void', 'restriction_level'=>'int'],
'sprintf' => ['string', 'format'=>'string', '...vars='=>'string|int|float'],
'SQLite3::__construct' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryption_key='=>'?string'],
'SQLite3::busyTimeout' => ['bool', 'msecs'=>'int'],
'SQLite3::changes' => ['int'],
'SQLite3::close' => ['bool'],
'SQLite3::createAggregate' => ['bool', 'name'=>'string', 'step_callback'=>'callable', 'final_callback'=>'callable', 'argument_count='=>'int'],
'SQLite3::createCollation' => ['bool', 'name'=>'string', 'callback'=>'callable'],
'SQLite3::createFunction' => ['bool', 'name'=>'string', 'callback'=>'callable', 'argument_count='=>'int', 'flags='=>'int'],
'SQLite3::enableExceptions' => ['bool', 'enableexceptions='=>'bool'],
'SQLite3::escapeString' => ['string', 'value'=>'string'],
'SQLite3::exec' => ['bool', 'query'=>'string'],
'SQLite3::lastErrorCode' => ['int'],
'SQLite3::lastErrorMsg' => ['string'],
'SQLite3::lastInsertRowID' => ['int'],
'SQLite3::loadExtension' => ['bool', 'shared_library'=>'string'],
'SQLite3::open' => ['void', 'filename'=>'string', 'flags='=>'int', 'encryption_key='=>'?string'],
'SQLite3::openBlob' => ['resource|false', 'table'=>'string', 'column'=>'string', 'rowid'=>'int', 'dbname='=>'string', 'flags='=>'int'],
'SQLite3::prepare' => ['SQLite3Stmt|false', 'query'=>'string'],
'SQLite3::query' => ['SQLite3Result|false', 'query'=>'string'],
'SQLite3::querySingle' => ['array|int|string|bool|float|null|false', 'query'=>'string', 'entire_row='=>'bool'],
'SQLite3::version' => ['array'],
'SQLite3Result::__construct' => ['void'],
'SQLite3Result::columnName' => ['string', 'column_number'=>'int'],
'SQLite3Result::columnType' => ['int', 'column_number'=>'int'],
'SQLite3Result::fetchArray' => ['array|false', 'mode='=>'int'],
'SQLite3Result::finalize' => ['bool'],
'SQLite3Result::numColumns' => ['int'],
'SQLite3Result::reset' => ['bool'],
'SQLite3Stmt::__construct' => ['void', 'dbobject'=>'sqlite3', 'statement'=>'string'],
'SQLite3Stmt::bindParam' => ['bool', 'parameter_name_or_number'=>'string|int', '&rw_parameter'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::bindValue' => ['bool', 'parameter_name_or_number'=>'string|int', 'parameter'=>'mixed', 'type='=>'int'],
'SQLite3Stmt::clear' => ['bool'],
'SQLite3Stmt::close' => ['bool'],
'SQLite3Stmt::execute' => ['SQLite3Result'],
'SQLite3Stmt::getSQL' => ['string', 'expanded='=>'bool'],
'SQLite3Stmt::paramCount' => ['int'],
'SQLite3Stmt::readOnly' => ['bool'],
'SQLite3Stmt::reset' => ['bool'],
'sqlite_array_query' => ['array|false', 'dbhandle'=>'resource', 'query'=>'string', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_busy_timeout' => ['void', 'dbhandle'=>'resource', 'milliseconds'=>'int'],
'sqlite_changes' => ['int', 'dbhandle'=>'resource'],
'sqlite_close' => ['void', 'dbhandle'=>'resource'],
'sqlite_column' => ['mixed', 'result'=>'resource', 'index_or_name'=>'mixed', 'decode_binary='=>'bool'],
'sqlite_create_aggregate' => ['void', 'dbhandle'=>'resource', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'sqlite_create_function' => ['void', 'dbhandle'=>'resource', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'sqlite_current' => ['array|false', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_error_string' => ['string', 'error_code'=>'int'],
'sqlite_escape_string' => ['string', 'item'=>'string'],
'sqlite_exec' => ['bool', 'dbhandle'=>'resource', 'query'=>'string', 'error_msg='=>'string'],
'sqlite_factory' => ['SQLiteDatabase', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_fetch_all' => ['array', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_fetch_array' => ['array|false', 'result'=>'resource', 'result_type='=>'int', 'decode_binary='=>'bool'],
'sqlite_fetch_column_types' => ['array|false', 'table_name'=>'string', 'dbhandle'=>'resource', 'result_type='=>'int'],
'sqlite_fetch_object' => ['object', 'result'=>'resource', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'sqlite_fetch_single' => ['string', 'result'=>'resource', 'decode_binary='=>'bool'],
'sqlite_fetch_string' => ['string', 'result'=>'resource', 'decode_binary'=>'bool'],
'sqlite_field_name' => ['string', 'result'=>'resource', 'field_index'=>'int'],
'sqlite_has_more' => ['bool', 'result'=>'resource'],
'sqlite_has_prev' => ['bool', 'result'=>'resource'],
'sqlite_key' => ['int', 'result'=>'resource'],
'sqlite_last_error' => ['int', 'dbhandle'=>'resource'],
'sqlite_last_insert_rowid' => ['int', 'dbhandle'=>'resource'],
'sqlite_libencoding' => ['string'],
'sqlite_libversion' => ['string'],
'sqlite_next' => ['bool', 'result'=>'resource'],
'sqlite_num_fields' => ['int', 'result'=>'resource'],
'sqlite_num_rows' => ['int', 'result'=>'resource'],
'sqlite_open' => ['resource|false', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_popen' => ['resource|false', 'filename'=>'string', 'mode='=>'int', 'error_message='=>'string'],
'sqlite_prev' => ['bool', 'result'=>'resource'],
'sqlite_query' => ['resource|false', 'dbhandle'=>'resource', 'query'=>'resource|string', 'result_type='=>'int', 'error_msg='=>'string'],
'sqlite_rewind' => ['bool', 'result'=>'resource'],
'sqlite_seek' => ['bool', 'result'=>'resource', 'rownum'=>'int'],
'sqlite_single_query' => ['array', 'db'=>'resource', 'query'=>'string', 'first_row_only='=>'bool', 'decode_binary='=>'bool'],
'sqlite_udf_decode_binary' => ['string', 'data'=>'string'],
'sqlite_udf_encode_binary' => ['string', 'data'=>'string'],
'sqlite_unbuffered_query' => ['SQLiteUnbuffered|false', 'dbhandle'=>'resource', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'sqlite_valid' => ['bool', 'result'=>'resource'],
'SQLiteDatabase::__construct' => ['void', 'filename'=>'', 'mode='=>'int|mixed', '&error_message'=>''],
'SQLiteDatabase::arrayQuery' => ['array', 'query'=>'string', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteDatabase::busyTimeout' => ['int', 'milliseconds'=>'int'],
'SQLiteDatabase::changes' => ['int'],
'SQLiteDatabase::createAggregate' => ['', 'function_name'=>'string', 'step_func'=>'callable', 'finalize_func'=>'callable', 'num_args='=>'int'],
'SQLiteDatabase::createFunction' => ['', 'function_name'=>'string', 'callback'=>'callable', 'num_args='=>'int'],
'SQLiteDatabase::exec' => ['bool', 'query'=>'string', 'error_msg='=>'string'],
'SQLiteDatabase::fetchColumnTypes' => ['array', 'table_name'=>'string', 'result_type='=>'int'],
'SQLiteDatabase::lastError' => ['int'],
'SQLiteDatabase::lastInsertRowid' => ['int'],
'SQLiteDatabase::query' => ['SQLiteResult|false', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'SQLiteDatabase::queryExec' => ['bool', 'query'=>'string', '&w_error_msg='=>'string'],
'SQLiteDatabase::singleQuery' => ['array', 'query'=>'string', 'first_row_only='=>'bool', 'decode_binary='=>'bool'],
'SQLiteDatabase::unbufferedQuery' => ['SQLiteUnbuffered|false', 'query'=>'string', 'result_type='=>'int', 'error_msg='=>'string'],
'SQLiteException::__clone' => ['void'],
'SQLiteException::__construct' => ['void', 'message'=>'', 'code'=>'', 'previous'=>''],
'SQLiteException::__toString' => ['string'],
'SQLiteException::__wakeup' => ['void'],
'SQLiteException::getCode' => ['int'],
'SQLiteException::getFile' => ['string'],
'SQLiteException::getLine' => ['int'],
'SQLiteException::getMessage' => ['string'],
'SQLiteException::getPrevious' => ['RuntimeException|Throwable|null'],
'SQLiteException::getTrace' => ['array'],
'SQLiteException::getTraceAsString' => ['string'],
'SQLiteResult::__construct' => ['void'],
'SQLiteResult::column' => ['mixed', 'index_or_name'=>'', 'decode_binary='=>'bool'],
'SQLiteResult::count' => ['int'],
'SQLiteResult::current' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetch' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetchAll' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteResult::fetchObject' => ['object', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'SQLiteResult::fetchSingle' => ['string', 'decode_binary='=>'bool'],
'SQLiteResult::fieldName' => ['string', 'field_index'=>'int'],
'SQLiteResult::hasPrev' => ['bool'],
'SQLiteResult::key' => ['mixed|null'],
'SQLiteResult::next' => ['bool'],
'SQLiteResult::numFields' => ['int'],
'SQLiteResult::numRows' => ['int'],
'SQLiteResult::prev' => ['bool'],
'SQLiteResult::rewind' => ['bool'],
'SQLiteResult::seek' => ['bool', 'rownum'=>'int'],
'SQLiteResult::valid' => ['bool'],
'SQLiteUnbuffered::column' => ['void', 'index_or_name'=>'', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::current' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetch' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchAll' => ['array', 'result_type='=>'int', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchObject' => ['object', 'class_name='=>'string', 'ctor_params='=>'array', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fetchSingle' => ['string', 'decode_binary='=>'bool'],
'SQLiteUnbuffered::fieldName' => ['string', 'field_index'=>'int'],
'SQLiteUnbuffered::next' => ['bool'],
'SQLiteUnbuffered::numFields' => ['int'],
'SQLiteUnbuffered::valid' => ['bool'],
'sqlsrv_begin_transaction' => ['bool', 'conn'=>'resource'],
'sqlsrv_cancel' => ['bool', 'stmt'=>'resource'],
'sqlsrv_client_info' => ['array|false', 'conn'=>'resource'],
'sqlsrv_close' => ['bool', 'conn'=>'?resource'],
'sqlsrv_commit' => ['bool', 'conn'=>'resource'],
'sqlsrv_configure' => ['bool', 'setting'=>'string', 'value'=>'mixed'],
'sqlsrv_connect' => ['resource|false', 'serverName'=>'string', 'connectionInfo='=>'array'],
'sqlsrv_errors' => ['?array', 'errorsOrWarnings='=>'int'],
'sqlsrv_execute' => ['bool', 'stmt'=>'resource'],
'sqlsrv_fetch' => ['?bool', 'stmt'=>'resource', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_fetch_array' => ['array|null|false', 'stmt'=>'resource', 'fetchType='=>'int', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_fetch_object' => ['object|null|false', 'stmt'=>'resource', 'className='=>'string', 'ctorParams='=>'array', 'row='=>'int', 'offset='=>'int'],
'sqlsrv_field_metadata' => ['array|false', 'stmt'=>'resource'],
'sqlsrv_free_stmt' => ['bool', 'stmt'=>'resource'],
'sqlsrv_get_config' => ['mixed', 'setting'=>'string'],
'sqlsrv_get_field' => ['mixed', 'stmt'=>'resource', 'fieldIndex'=>'int', 'getAsType='=>'int'],
'sqlsrv_has_rows' => ['bool', 'stmt'=>'resource'],
'sqlsrv_next_result' => ['?bool', 'stmt'=>'resource'],
'sqlsrv_num_fields' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_num_rows' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_prepare' => ['resource|false', 'conn'=>'resource', 'sql'=>'string', 'params='=>'array', 'options='=>'array'],
'sqlsrv_query' => ['resource|false', 'conn'=>'resource', 'sql'=>'string', 'params='=>'array', 'options='=>'array'],
'sqlsrv_rollback' => ['bool', 'conn'=>'resource'],
'sqlsrv_rows_affected' => ['int|false', 'stmt'=>'resource'],
'sqlsrv_send_stream_data' => ['bool', 'stmt'=>'resource'],
'sqlsrv_server_info' => ['array', 'conn'=>'resource'],
'sqrt' => ['float', 'number'=>'float'],
'srand' => ['void', 'seed='=>'int', 'mode='=>'int'],
'sscanf' => ['mixed', 'str'=>'string', 'format'=>'string', '&...w_vars='=>'string|int|float'],
'ssdeep_fuzzy_compare' => ['int', 'signature1'=>'string', 'signature2'=>'string'],
'ssdeep_fuzzy_hash' => ['string', 'to_hash'=>'string'],
'ssdeep_fuzzy_hash_filename' => ['string', 'file_name'=>'string'],
'ssh2_auth_agent' => ['bool', 'session'=>'resource', 'username'=>'string'],
'ssh2_auth_hostbased_file' => ['bool', 'session'=>'resource', 'username'=>'string', 'hostname'=>'string', 'pubkeyfile'=>'string', 'privkeyfile'=>'string', 'passphrase='=>'string', 'local_username='=>'string'],
'ssh2_auth_none' => ['bool|string[]', 'session'=>'resource', 'username'=>'string'],
'ssh2_auth_password' => ['bool', 'session'=>'resource', 'username'=>'string', 'password'=>'string'],
'ssh2_auth_pubkey_file' => ['bool', 'session'=>'resource', 'username'=>'string', 'pubkeyfile'=>'string', 'privkeyfile'=>'string', 'passphrase='=>'string'],
'ssh2_connect' => ['resource|false', 'host'=>'string', 'port='=>'int', 'methods='=>'array', 'callbacks='=>'array'],
'ssh2_disconnect' => ['bool', 'session'=>'resource'],
'ssh2_exec' => ['resource|false', 'session'=>'resource', 'command'=>'string', 'pty='=>'string', 'env='=>'array', 'width='=>'int', 'height='=>'int', 'width_height_type='=>'int'],
'ssh2_fetch_stream' => ['resource|false', 'channel'=>'resource', 'streamid'=>'int'],
'ssh2_fingerprint' => ['string|false', 'session'=>'resource', 'flags='=>'int'],
'ssh2_forward_accept' => ['resource|false', 'session'=>'resource'],
'ssh2_forward_listen' => ['resource|false', 'session'=>'resource', 'port'=>'int', 'host='=>'string', 'max_connections='=>'string'],
'ssh2_methods_negotiated' => ['array|false', 'session'=>'resource'],
'ssh2_poll' => ['int', '&polldes'=>'array', 'timeout='=>'int'],
'ssh2_publickey_add' => ['bool', 'pkey'=>'resource', 'algoname'=>'string', 'blob'=>'string', 'overwrite='=>'bool', 'attributes='=>'array'],
'ssh2_publickey_init' => ['resource|false', 'session'=>'resource'],
'ssh2_publickey_list' => ['array|false', 'pkey'=>'resource'],
'ssh2_publickey_remove' => ['bool', 'pkey'=>'resource', 'algoname'=>'string', 'blob'=>'string'],
'ssh2_scp_recv' => ['bool', 'session'=>'resource', 'remote_file'=>'string', 'local_file'=>'string'],
'ssh2_scp_send' => ['bool', 'session'=>'resource', 'local_file'=>'string', 'remote_file'=>'string', 'create_mode='=>'int'],
'ssh2_sftp' => ['resource|false', 'session'=>'resource'],
'ssh2_sftp_chmod' => ['bool', 'sftp'=>'resource', 'filename'=>'string', 'mode'=>'int'],
'ssh2_sftp_lstat' => ['array|false', 'sftp'=>'resource', 'path'=>'string'],
'ssh2_sftp_mkdir' => ['bool', 'sftp'=>'resource', 'dirname'=>'string', 'mode='=>'int', 'recursive='=>'bool'],
'ssh2_sftp_readlink' => ['string|false', 'sftp'=>'resource', 'link'=>'string'],
'ssh2_sftp_realpath' => ['string|false', 'sftp'=>'resource', 'filename'=>'string'],
'ssh2_sftp_rename' => ['bool', 'sftp'=>'resource', 'from'=>'string', 'to'=>'string'],
'ssh2_sftp_rmdir' => ['bool', 'sftp'=>'resource', 'dirname'=>'string'],
'ssh2_sftp_stat' => ['array|false', 'sftp'=>'resource', 'path'=>'string'],
'ssh2_sftp_symlink' => ['bool', 'sftp'=>'resource', 'target'=>'string', 'link'=>'string'],
'ssh2_sftp_unlink' => ['bool', 'sftp'=>'resource', 'filename'=>'string'],
'ssh2_shell' => ['resource|false', 'session'=>'resource', 'term_type='=>'string', 'env='=>'array', 'width='=>'int', 'height='=>'int', 'width_height_type='=>'int'],
'ssh2_tunnel' => ['resource|false', 'session'=>'resource', 'host'=>'string', 'port'=>'int'],
'stat' => ['array|false', 'filename'=>'string'],
'stats_absolute_deviation' => ['float', 'a'=>'array'],
'stats_cdf_beta' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_binomial' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_cauchy' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_chisquare' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_exponential' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_f' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_gamma' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_laplace' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_logistic' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_negative_binomial' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_chisquare' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_f' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'par4'=>'float', 'which'=>'int'],
'stats_cdf_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_normal' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_poisson' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'which'=>'int'],
'stats_cdf_uniform' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_cdf_weibull' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_covariance' => ['float', 'a'=>'array', 'b'=>'array'],
'stats_den_uniform' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_beta' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_cauchy' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_chisquare' => ['float', 'x'=>'float', 'dfr'=>'float'],
'stats_dens_exponential' => ['float', 'x'=>'float', 'scale'=>'float'],
'stats_dens_f' => ['float', 'x'=>'float', 'dfr1'=>'float', 'dfr2'=>'float'],
'stats_dens_gamma' => ['float', 'x'=>'float', 'shape'=>'float', 'scale'=>'float'],
'stats_dens_laplace' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_logistic' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_negative_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_normal' => ['float', 'x'=>'float', 'ave'=>'float', 'stdev'=>'float'],
'stats_dens_pmf_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_pmf_hypergeometric' => ['float', 'n1'=>'float', 'n2'=>'float', 'N1'=>'float', 'N2'=>'float'],
'stats_dens_pmf_negative_binomial' => ['float', 'x'=>'float', 'n'=>'float', 'pi'=>'float'],
'stats_dens_pmf_poisson' => ['float', 'x'=>'float', 'lb'=>'float'],
'stats_dens_t' => ['float', 'x'=>'float', 'dfr'=>'float'],
'stats_dens_uniform' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_dens_weibull' => ['float', 'x'=>'float', 'a'=>'float', 'b'=>'float'],
'stats_harmonic_mean' => ['float', 'a'=>'array'],
'stats_kurtosis' => ['float', 'a'=>'array'],
'stats_rand_gen_beta' => ['float', 'a'=>'float', 'b'=>'float'],
'stats_rand_gen_chisquare' => ['float', 'df'=>'float'],
'stats_rand_gen_exponential' => ['float', 'av'=>'float'],
'stats_rand_gen_f' => ['float', 'dfn'=>'float', 'dfd'=>'float'],
'stats_rand_gen_funiform' => ['float', 'low'=>'float', 'high'=>'float'],
'stats_rand_gen_gamma' => ['float', 'a'=>'float', 'r'=>'float'],
'stats_rand_gen_ibinomial' => ['int', 'n'=>'int', 'pp'=>'float'],
'stats_rand_gen_ibinomial_negative' => ['int', 'n'=>'int', 'p'=>'float'],
'stats_rand_gen_int' => ['int'],
'stats_rand_gen_ipoisson' => ['int', 'mu'=>'float'],
'stats_rand_gen_iuniform' => ['int', 'low'=>'int', 'high'=>'int'],
'stats_rand_gen_noncenral_chisquare' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_chisquare' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_f' => ['float', 'dfn'=>'float', 'dfd'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_noncentral_t' => ['float', 'df'=>'float', 'xnonc'=>'float'],
'stats_rand_gen_normal' => ['float', 'av'=>'float', 'sd'=>'float'],
'stats_rand_gen_t' => ['float', 'df'=>'float'],
'stats_rand_get_seeds' => ['array'],
'stats_rand_phrase_to_seeds' => ['array', 'phrase'=>'string'],
'stats_rand_ranf' => ['float'],
'stats_rand_setall' => ['void', 'iseed1'=>'int', 'iseed2'=>'int'],
'stats_skew' => ['float', 'a'=>'array'],
'stats_standard_deviation' => ['float', 'a'=>'array', 'sample='=>'bool'],
'stats_stat_binomial_coef' => ['float', 'x'=>'int', 'n'=>'int'],
'stats_stat_correlation' => ['float', 'arr1'=>'array', 'arr2'=>'array'],
'stats_stat_factorial' => ['float', 'n'=>'int'],
'stats_stat_gennch' => ['float', 'n'=>'int'],
'stats_stat_independent_t' => ['float', 'arr1'=>'array', 'arr2'=>'array'],
'stats_stat_innerproduct' => ['float', 'arr1'=>'array', 'arr2'=>'array'],
'stats_stat_noncentral_t' => ['float', 'par1'=>'float', 'par2'=>'float', 'par3'=>'float', 'which'=>'int'],
'stats_stat_paired_t' => ['float', 'arr1'=>'array', 'arr2'=>'array'],
'stats_stat_percentile' => ['float', 'arr'=>'array', 'perc'=>'float'],
'stats_stat_powersum' => ['float', 'arr'=>'array', 'power'=>'float'],
'stats_variance' => ['float', 'a'=>'array', 'sample='=>'bool'],
'Stomp::__construct' => ['void', 'broker='=>'string', 'username='=>'string', 'password='=>'string', 'headers='=>'array'],
'Stomp::__destruct' => ['bool', 'link'=>''],
'Stomp::abort' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::ack' => ['bool', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'Stomp::begin' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::commit' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::error' => ['string', 'link'=>''],
'Stomp::getReadTimeout' => ['array', 'link'=>''],
'Stomp::getSessionId' => ['string', 'link'=>''],
'Stomp::hasFrame' => ['bool', 'link'=>''],
'Stomp::readFrame' => ['array', 'class_name='=>'string', 'link='=>''],
'Stomp::send' => ['bool', 'destination'=>'string', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'Stomp::setReadTimeout' => ['', 'seconds'=>'int', 'microseconds='=>'int', 'link='=>''],
'Stomp::subscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'Stomp::unsubscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_abort' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_ack' => ['bool', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'stomp_begin' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_close' => ['bool', 'link'=>''],
'stomp_commit' => ['bool', 'transaction_id'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_connect' => ['resource', 'broker='=>'string', 'username='=>'string', 'password='=>'string', 'headers='=>'array'],
'stomp_connect_error' => ['string'],
'stomp_error' => ['string', 'link'=>''],
'stomp_get_read_timeout' => ['array', 'link'=>''],
'stomp_get_session_id' => ['string', 'link'=>''],
'stomp_has_frame' => ['bool', 'link'=>''],
'stomp_read_frame' => ['array', 'class_name='=>'string', 'link='=>''],
'stomp_send' => ['bool', 'destination'=>'string', 'msg'=>'', 'headers='=>'array', 'link='=>''],
'stomp_set_read_timeout' => ['', 'seconds'=>'int', 'microseconds='=>'int', 'link='=>''],
'stomp_subscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_unsubscribe' => ['bool', 'destination'=>'string', 'headers='=>'array', 'link='=>''],
'stomp_version' => ['string'],
'StompException::getDetails' => ['string'],
'StompFrame::__construct' => ['void', 'command='=>'string', 'headers='=>'array', 'body='=>'string'],
'str_getcsv' => ['array', 'input'=>'string', 'delimiter='=>'string', 'enclosure='=>'string', 'escape='=>'string'],
'str_ireplace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_replace_count='=>'int'],
'str_pad' => ['string', 'input'=>'string', 'pad_length'=>'int', 'pad_string='=>'string', 'pad_type='=>'int'],
'str_repeat' => ['string', 'input'=>'string', 'multiplier'=>'int'],
'str_replace' => ['string|string[]', 'search'=>'string|array', 'replace'=>'string|array', 'subject'=>'string|array', '&w_replace_count='=>'int'],
'str_rot13' => ['string', 'str'=>'string'],
'str_shuffle' => ['string', 'str'=>'string'],
'str_split' => ['array<int,string>|false', 'str'=>'string', 'split_length='=>'int'],
'str_word_count' => ['array<int, string>|int', 'string'=>'string', 'format='=>'int', 'charlist='=>'string'],
'strcasecmp' => ['int', 'str1'=>'string', 'str2'=>'string'],
'strchr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed', 'before_needle='=>'bool'],
'strcmp' => ['int', 'str1'=>'string', 'str2'=>'string'],
'strcoll' => ['int', 'str1'=>'string', 'str2'=>'string'],
'strcspn' => ['int', 'str'=>'string', 'mask'=>'string', 'start='=>'int', 'length='=>'int'],
'stream_bucket_append' => ['void', 'brigade'=>'resource', 'bucket'=>'object'],
'stream_bucket_make_writeable' => ['object', 'brigade'=>'resource'],
'stream_bucket_new' => ['object|false', 'stream'=>'resource', 'buffer'=>'string'],
'stream_bucket_prepend' => ['void', 'brigade'=>'resource', 'bucket'=>'object'],
'stream_context_create' => ['resource', 'options='=>'array', 'params='=>'array'],
'stream_context_get_default' => ['resource', 'options='=>'array'],
'stream_context_get_options' => ['array', 'context'=>'resource'],
'stream_context_get_params' => ['array', 'context'=>'resource'],
'stream_context_set_default' => ['resource', 'options'=>'array'],
'stream_context_set_option' => ['bool', 'context'=>'', 'wrappername'=>'string', 'optionname'=>'string', 'value'=>''],
'stream_context_set_option\'1' => ['bool', 'context'=>'', 'options'=>'array'],
'stream_context_set_params' => ['bool', 'context'=>'resource', 'options'=>'array'],
'stream_copy_to_stream' => ['int|false', 'source'=>'resource', 'dest'=>'resource', 'maxlen='=>'int', 'pos='=>'int'],
'stream_encoding' => ['bool', 'stream'=>'resource', 'encoding='=>'string'],
'stream_filter_append' => ['resource|false', 'stream'=>'resource', 'filtername'=>'string', 'read_write='=>'int', 'filterparams='=>'array'],
'stream_filter_prepend' => ['resource|false', 'stream'=>'resource', 'filtername'=>'string', 'read_write='=>'int', 'filterparams='=>'array'],
'stream_filter_register' => ['bool', 'filtername'=>'string', 'classname'=>'string'],
'stream_filter_remove' => ['bool', 'stream_filter'=>'resource'],
'stream_get_contents' => ['string|false', 'source'=>'resource', 'maxlen='=>'int', 'offset='=>'int'],
'stream_get_filters' => ['array'],
'stream_get_line' => ['string|false', 'stream'=>'resource', 'maxlen'=>'int', 'ending='=>'string'],
'stream_get_meta_data' => ['array{timed_out:bool,blocked:bool,eof:bool,unread_bytes:int,stream_type:string,wrapper_type:string,wrapper_data:mixed,mode:string,seekable:bool,uri:string,mediatype:string}', 'fp'=>'resource'],
'stream_get_transports' => ['array'],
'stream_get_wrappers' => ['array'],
'stream_is_local' => ['bool', 'stream'=>'resource|string'],
'stream_isatty' => ['bool', 'stream'=>'resource'],
'stream_notification_callback' => ['callback', 'notification_code'=>'int', 'severity'=>'int', 'message'=>'string', 'message_code'=>'int', 'bytes_transferred'=>'int', 'bytes_max'=>'int'],
'stream_register_wrapper' => ['bool', 'protocol'=>'string', 'classname'=>'string', 'flags='=>'int'],
'stream_resolve_include_path' => ['string|false', 'filename'=>'string'],
'stream_select' => ['int|false', '&rw_read_streams'=>'resource[]', '&rw_write_streams'=>'?resource[]', '&rw_except_streams'=>'?resource[]', 'tv_sec'=>'?int', 'tv_usec='=>'?int'],
'stream_set_blocking' => ['bool', 'socket'=>'resource', 'mode'=>'bool'],
'stream_set_chunk_size' => ['int|false', 'fp'=>'resource', 'chunk_size'=>'int'],
'stream_set_read_buffer' => ['int', 'fp'=>'resource', 'buffer'=>'int'],
'stream_set_timeout' => ['bool', 'stream'=>'resource', 'seconds'=>'int', 'microseconds='=>'int'],
'stream_set_write_buffer' => ['int', 'fp'=>'resource', 'buffer'=>'int'],
'stream_socket_accept' => ['resource|false', 'serverstream'=>'resource', 'timeout='=>'float', '&w_peername='=>'string'],
'stream_socket_client' => ['resource|false', 'remoteaddress'=>'string', '&w_errcode='=>'int', '&w_errstring='=>'string', 'timeout='=>'float', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_enable_crypto' => ['bool|int', 'stream'=>'resource', 'enable'=>'bool', 'cryptokind='=>'int', 'sessionstream='=>'resource'],
'stream_socket_get_name' => ['string', 'stream'=>'resource', 'want_peer'=>'bool'],
'stream_socket_pair' => ['resource[]|false', 'domain'=>'int', 'type'=>'int', 'protocol'=>'int'],
'stream_socket_recvfrom' => ['string', 'stream'=>'resource', 'amount'=>'int', 'flags='=>'int', '&w_remote_addr='=>'string'],
'stream_socket_sendto' => ['int', 'stream'=>'resource', 'data'=>'string', 'flags='=>'int', 'target_addr='=>'string'],
'stream_socket_server' => ['resource|false', 'localaddress'=>'string', '&w_errcode='=>'int', '&w_errstring='=>'string', 'flags='=>'int', 'context='=>'resource'],
'stream_socket_shutdown' => ['bool', 'stream'=>'resource', 'how'=>'int'],
'stream_supports_lock' => ['bool', 'stream'=>'resource'],
'stream_wrapper_register' => ['bool', 'protocol'=>'string', 'classname'=>'string', 'flags='=>'int'],
'stream_wrapper_restore' => ['bool', 'protocol'=>'string'],
'stream_wrapper_unregister' => ['bool', 'protocol'=>'string'],
'streamWrapper::__construct' => ['void'],
'streamWrapper::__destruct' => ['void'],
'streamWrapper::dir_closedir' => ['bool'],
'streamWrapper::dir_opendir' => ['bool', 'path'=>'string', 'options'=>'int'],
'streamWrapper::dir_readdir' => ['string'],
'streamWrapper::dir_rewinddir' => ['bool'],
'streamWrapper::mkdir' => ['bool', 'path'=>'string', 'mode'=>'int', 'options'=>'int'],
'streamWrapper::rename' => ['bool', 'path_from'=>'string', 'path_to'=>'string'],
'streamWrapper::rmdir' => ['bool', 'path'=>'string', 'options'=>'int'],
'streamWrapper::stream_cast' => ['resource', 'cast_as'=>'int'],
'streamWrapper::stream_close' => ['void'],
'streamWrapper::stream_eof' => ['bool'],
'streamWrapper::stream_flush' => ['bool'],
'streamWrapper::stream_lock' => ['bool', 'operation'=>'mode'],
'streamWrapper::stream_metadata' => ['bool', 'path'=>'string', 'option'=>'int', 'value'=>'mixed'],
'streamWrapper::stream_open' => ['bool', 'path'=>'string', 'mode'=>'string', 'options'=>'int', 'opened_path'=>'string'],
'streamWrapper::stream_read' => ['string', 'count'=>'int'],
'streamWrapper::stream_seek' => ['bool', 'offset'=>'int', 'whence'=>'int'],
'streamWrapper::stream_set_option' => ['bool', 'option'=>'int', 'arg1'=>'int', 'arg2'=>'int'],
'streamWrapper::stream_stat' => ['array'],
'streamWrapper::stream_tell' => ['int'],
'streamWrapper::stream_truncate' => ['bool', 'new_size'=>'int'],
'streamWrapper::stream_write' => ['int', 'data'=>'string'],
'streamWrapper::unlink' => ['bool', 'path'=>'string'],
'streamWrapper::url_stat' => ['array', 'path'=>'string', 'flags'=>'int'],
'strftime' => ['string', 'format'=>'string', 'timestamp='=>'int'],
'strip_tags' => ['string', 'str'=>'string', 'allowable_tags='=>'string'],
'stripcslashes' => ['string', 'str'=>'string'],
'stripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'stripslashes' => ['string', 'str'=>'string'],
'stristr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed', 'before_needle='=>'bool'],
'strlen' => ['int', 'string'=>'string'],
'strnatcasecmp' => ['int', 's1'=>'string', 's2'=>'string'],
'strnatcmp' => ['int', 's1'=>'string', 's2'=>'string'],
'strncasecmp' => ['int', 'str1'=>'string', 'str2'=>'string', 'len'=>'int'],
'strncmp' => ['int', 'str1'=>'string', 'str2'=>'string', 'len'=>'int'],
'strpbrk' => ['string|false', 'haystack'=>'string', 'char_list'=>'string'],
'strpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'strptime' => ['array|false', 'datestr'=>'string', 'format'=>'string'],
'strrchr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed'],
'strrev' => ['string', 'str'=>'string'],
'strripos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'strrpos' => ['int|false', 'haystack'=>'string', 'needle'=>'string|int', 'offset='=>'int'],
'strspn' => ['int', 'str'=>'string', 'mask'=>'string', 'start='=>'int', 'len='=>'int'],
'strstr' => ['string|false', 'haystack'=>'string', 'needle'=>'mixed', 'before_needle='=>'bool'],
'strtok' => ['string|false', 'str'=>'string', 'token'=>'string'],
'strtok\'1' => ['string|false', 'token'=>'string'],
'strtolower' => ['string', 'str'=>'string'],
'strtotime' => ['int|false', 'time'=>'string', 'now='=>'int'],
'strtoupper' => ['string', 'str'=>'string'],
'strtr' => ['string', 'str'=>'string', 'from'=>'string', 'to'=>'string'],
'strtr\'1' => ['string', 'str'=>'string', 'replace_pairs'=>'array'],
'strval' => ['string', 'var'=>'mixed'],
'styleObj::__construct' => ['void', 'label'=>'labelObj', 'style'=>'styleObj'],
'styleObj::convertToString' => ['string'],
'styleObj::free' => ['void'],
'styleObj::getBinding' => ['string', 'stylebinding'=>'mixed'],
'styleObj::getGeomTransform' => ['string'],
'styleObj::ms_newStyleObj' => ['styleObj', 'class'=>'classObj', 'style'=>'styleObj'],
'styleObj::removeBinding' => ['int', 'stylebinding'=>'mixed'],
'styleObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'styleObj::setBinding' => ['int', 'stylebinding'=>'mixed', 'value'=>'string'],
'styleObj::setGeomTransform' => ['int', 'value'=>'string'],
'styleObj::updateFromString' => ['int', 'snippet'=>'string'],
'substr' => ['string|false', 'str'=>'string', 'start'=>'int', 'length='=>'int'],
'substr_compare' => ['int|false', 'main_str'=>'string', 'str'=>'string', 'offset'=>'int', 'length='=>'int', 'case_sensitivity='=>'bool'],
'substr_count' => ['int', 'haystack'=>'string', 'needle'=>'string', 'offset='=>'int', 'length='=>'int'],
'substr_replace' => ['string|array', 'str'=>'string|array', 'repl'=>'mixed', 'start'=>'mixed', 'length='=>'mixed'],
'suhosin_encrypt_cookie' => ['string|false', 'name'=>'string', 'value'=>'string'],
'suhosin_get_raw_cookies' => ['array'],
'SVM::__construct' => ['void'],
'svm::crossvalidate' => ['float', 'problem'=>'array', 'number_of_folds'=>'int'],
'SVM::getOptions' => ['array'],
'SVM::setOptions' => ['bool', 'params'=>'array'],
'svm::train' => ['SVMModel', 'problem'=>'array', 'weights='=>'array'],
'SVMModel::__construct' => ['void', 'filename='=>'string'],
'SVMModel::checkProbabilityModel' => ['bool'],
'SVMModel::getLabels' => ['array'],
'SVMModel::getNrClass' => ['int'],
'SVMModel::getSvmType' => ['int'],
'SVMModel::getSvrProbability' => ['float'],
'SVMModel::load' => ['bool', 'filename'=>'string'],
'SVMModel::predict' => ['float', 'data'=>'array'],
'SVMModel::predict_probability' => ['float', 'data'=>'array'],
'SVMModel::save' => ['bool', 'filename'=>'string'],
'svn_add' => ['bool', 'path'=>'string', 'recursive='=>'bool', 'force='=>'bool'],
'svn_auth_get_parameter' => ['?string', 'key'=>'string'],
'svn_auth_set_parameter' => ['void', 'key'=>'string', 'value'=>'string'],
'svn_blame' => ['array', 'repository_url'=>'string', 'revision_no='=>'int'],
'svn_cat' => ['string', 'repos_url'=>'string', 'revision_no='=>'int'],
'svn_checkout' => ['bool', 'repos'=>'string', 'targetpath'=>'string', 'revision='=>'int', 'flags='=>'int'],
'svn_cleanup' => ['bool', 'workingdir'=>'string'],
'svn_client_version' => ['string'],
'svn_commit' => ['array', 'log'=>'string', 'targets'=>'array', 'dontrecurse='=>'bool'],
'svn_delete' => ['bool', 'path'=>'string', 'force='=>'bool'],
'svn_diff' => ['array', 'path1'=>'string', 'rev1'=>'int', 'path2'=>'string', 'rev2'=>'int'],
'svn_export' => ['bool', 'frompath'=>'string', 'topath'=>'string', 'working_copy='=>'bool', 'revision_no='=>'int'],
'svn_fs_abort_txn' => ['bool', 'txn'=>'resource'],
'svn_fs_apply_text' => ['resource', 'root'=>'resource', 'path'=>'string'],
'svn_fs_begin_txn2' => ['resource', 'repos'=>'resource', 'rev'=>'int'],
'svn_fs_change_node_prop' => ['bool', 'root'=>'resource', 'path'=>'string', 'name'=>'string', 'value'=>'string'],
'svn_fs_check_path' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_contents_changed' => ['bool', 'root1'=>'resource', 'path1'=>'string', 'root2'=>'resource', 'path2'=>'string'],
'svn_fs_copy' => ['bool', 'from_root'=>'resource', 'from_path'=>'string', 'to_root'=>'resource', 'to_path'=>'string'],
'svn_fs_delete' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_dir_entries' => ['array', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_file_contents' => ['resource', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_file_length' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_is_dir' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_is_file' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_make_dir' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_make_file' => ['bool', 'root'=>'resource', 'path'=>'string'],
'svn_fs_node_created_rev' => ['int', 'fsroot'=>'resource', 'path'=>'string'],
'svn_fs_node_prop' => ['string', 'fsroot'=>'resource', 'path'=>'string', 'propname'=>'string'],
'svn_fs_props_changed' => ['bool', 'root1'=>'resource', 'path1'=>'string', 'root2'=>'resource', 'path2'=>'string'],
'svn_fs_revision_prop' => ['string', 'fs'=>'resource', 'revnum'=>'int', 'propname'=>'string'],
'svn_fs_revision_root' => ['resource', 'fs'=>'resource', 'revnum'=>'int'],
'svn_fs_txn_root' => ['resource', 'txn'=>'resource'],
'svn_fs_youngest_rev' => ['int', 'fs'=>'resource'],
'svn_import' => ['bool', 'path'=>'string', 'url'=>'string', 'nonrecursive'=>'bool'],
'svn_log' => ['array', 'repos_url'=>'string', 'start_revision='=>'int', 'end_revision='=>'int', 'limit='=>'int', 'flags='=>'int'],
'svn_ls' => ['array', 'repos_url'=>'string', 'revision_no='=>'int', 'recurse='=>'bool', 'peg='=>'bool'],
'svn_mkdir' => ['bool', 'path'=>'string', 'log_message='=>'string'],
'svn_move' => ['mixed', 'src_path'=>'string', 'dst_path'=>'string', 'force='=>'bool'],
'svn_propget' => ['mixed', 'path'=>'string', 'property_name'=>'string', 'recurse='=>'bool', 'revision'=>'int'],
'svn_proplist' => ['mixed', 'path'=>'string', 'recurse='=>'bool', 'revision'=>'int'],
'svn_repos_create' => ['resource', 'path'=>'string', 'config='=>'array', 'fsconfig='=>'array'],
'svn_repos_fs' => ['resource', 'repos'=>'resource'],
'svn_repos_fs_begin_txn_for_commit' => ['resource', 'repos'=>'resource', 'rev'=>'int', 'author'=>'string', 'log_msg'=>'string'],
'svn_repos_fs_commit_txn' => ['int', 'txn'=>'resource'],
'svn_repos_hotcopy' => ['bool', 'repospath'=>'string', 'destpath'=>'string', 'cleanlogs'=>'bool'],
'svn_repos_open' => ['resource', 'path'=>'string'],
'svn_repos_recover' => ['bool', 'path'=>'string'],
'svn_revert' => ['bool', 'path'=>'string', 'recursive='=>'bool'],
'svn_status' => ['array', 'path'=>'string', 'flags='=>'int'],
'svn_update' => ['int|false', 'path'=>'string', 'revno='=>'int', 'recurse='=>'bool'],
'swf_actiongeturl' => ['', 'url'=>'string', 'target'=>'string'],
'swf_actiongotoframe' => ['', 'framenumber'=>'int'],
'swf_actiongotolabel' => ['', 'label'=>'string'],
'swf_actionnextframe' => [''],
'swf_actionplay' => [''],
'swf_actionprevframe' => [''],
'swf_actionsettarget' => ['', 'target'=>'string'],
'swf_actionstop' => [''],
'swf_actiontogglequality' => [''],
'swf_actionwaitforframe' => ['', 'framenumber'=>'int', 'skipcount'=>'int'],
'swf_addbuttonrecord' => ['', 'states'=>'int', 'shapeid'=>'int', 'depth'=>'int'],
'swf_addcolor' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_closefile' => ['', 'return_file='=>'int'],
'swf_definebitmap' => ['', 'objid'=>'int', 'image_name'=>'string'],
'swf_definefont' => ['', 'fontid'=>'int', 'fontname'=>'string'],
'swf_defineline' => ['', 'objid'=>'int', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'width'=>'float'],
'swf_definepoly' => ['', 'objid'=>'int', 'coords'=>'array', 'npoints'=>'int', 'width'=>'float'],
'swf_definerect' => ['', 'objid'=>'int', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'width'=>'float'],
'swf_definetext' => ['', 'objid'=>'int', 'str'=>'string', 'docenter'=>'int'],
'swf_endbutton' => [''],
'swf_enddoaction' => [''],
'swf_endshape' => [''],
'swf_endsymbol' => [''],
'swf_fontsize' => ['', 'size'=>'float'],
'swf_fontslant' => ['', 'slant'=>'float'],
'swf_fonttracking' => ['', 'tracking'=>'float'],
'swf_getbitmapinfo' => ['array', 'bitmapid'=>'int'],
'swf_getfontinfo' => ['array'],
'swf_getframe' => ['int'],
'swf_labelframe' => ['', 'name'=>'string'],
'swf_lookat' => ['', 'view_x'=>'float', 'view_y'=>'float', 'view_z'=>'float', 'reference_x'=>'float', 'reference_y'=>'float', 'reference_z'=>'float', 'twist'=>'float'],
'swf_modifyobject' => ['', 'depth'=>'int', 'how'=>'int'],
'swf_mulcolor' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_nextid' => ['int'],
'swf_oncondition' => ['', 'transition'=>'int'],
'swf_openfile' => ['', 'filename'=>'string', 'width'=>'float', 'height'=>'float', 'framerate'=>'float', 'r'=>'float', 'g'=>'float', 'b'=>'float'],
'swf_ortho' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float', 'zmin'=>'float', 'zmax'=>'float'],
'swf_ortho2' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float'],
'swf_perspective' => ['', 'fovy'=>'float', 'aspect'=>'float', 'near'=>'float', 'far'=>'float'],
'swf_placeobject' => ['', 'objid'=>'int', 'depth'=>'int'],
'swf_polarview' => ['', 'dist'=>'float', 'azimuth'=>'float', 'incidence'=>'float', 'twist'=>'float'],
'swf_popmatrix' => [''],
'swf_posround' => ['', 'round'=>'int'],
'swf_pushmatrix' => [''],
'swf_removeobject' => ['', 'depth'=>'int'],
'swf_rotate' => ['', 'angle'=>'float', 'axis'=>'string'],
'swf_scale' => ['', 'x'=>'float', 'y'=>'float', 'z'=>'float'],
'swf_setfont' => ['', 'fontid'=>'int'],
'swf_setframe' => ['', 'framenumber'=>'int'],
'swf_shapearc' => ['', 'x'=>'float', 'y'=>'float', 'r'=>'float', 'ang1'=>'float', 'ang2'=>'float'],
'swf_shapecurveto' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float'],
'swf_shapecurveto3' => ['', 'x1'=>'float', 'y1'=>'float', 'x2'=>'float', 'y2'=>'float', 'x3'=>'float', 'y3'=>'float'],
'swf_shapefillbitmapclip' => ['', 'bitmapid'=>'int'],
'swf_shapefillbitmaptile' => ['', 'bitmapid'=>'int'],
'swf_shapefilloff' => [''],
'swf_shapefillsolid' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float'],
'swf_shapelinesolid' => ['', 'r'=>'float', 'g'=>'float', 'b'=>'float', 'a'=>'float', 'width'=>'float'],
'swf_shapelineto' => ['', 'x'=>'float', 'y'=>'float'],
'swf_shapemoveto' => ['', 'x'=>'float', 'y'=>'float'],
'swf_showframe' => [''],
'swf_startbutton' => ['', 'objid'=>'int', 'type'=>'int'],
'swf_startdoaction' => [''],
'swf_startshape' => ['', 'objid'=>'int'],
'swf_startsymbol' => ['', 'objid'=>'int'],
'swf_textwidth' => ['float', 'str'=>'string'],
'swf_translate' => ['', 'x'=>'float', 'y'=>'float', 'z'=>'float'],
'swf_viewport' => ['', 'xmin'=>'float', 'xmax'=>'float', 'ymin'=>'float', 'ymax'=>'float'],
'SWFAction::__construct' => ['void', 'script'=>'string'],
'SWFBitmap::__construct' => ['void', 'file'=>'', 'alphafile='=>''],
'SWFBitmap::getHeight' => ['float'],
'SWFBitmap::getWidth' => ['float'],
'SWFButton::__construct' => ['void'],
'SWFButton::addAction' => ['void', 'action'=>'swfaction', 'flags'=>'int'],
'SWFButton::addASound' => ['SWFSoundInstance', 'sound'=>'swfsound', 'flags'=>'int'],
'SWFButton::addShape' => ['void', 'shape'=>'swfshape', 'flags'=>'int'],
'SWFButton::setAction' => ['void', 'action'=>'swfaction'],
'SWFButton::setDown' => ['void', 'shape'=>'swfshape'],
'SWFButton::setHit' => ['void', 'shape'=>'swfshape'],
'SWFButton::setMenu' => ['void', 'flag'=>'int'],
'SWFButton::setOver' => ['void', 'shape'=>'swfshape'],
'SWFButton::setUp' => ['void', 'shape'=>'swfshape'],
'SWFDisplayItem::addAction' => ['void', 'action'=>'swfaction', 'flags'=>'int'],
'SWFDisplayItem::addColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFDisplayItem::endMask' => ['void'],
'SWFDisplayItem::getRot' => ['float'],
'SWFDisplayItem::getX' => ['float'],
'SWFDisplayItem::getXScale' => ['float'],
'SWFDisplayItem::getXSkew' => ['float'],
'SWFDisplayItem::getY' => ['float'],
'SWFDisplayItem::getYScale' => ['float'],
'SWFDisplayItem::getYSkew' => ['float'],
'SWFDisplayItem::move' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFDisplayItem::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFDisplayItem::multColor' => ['void', 'red'=>'float', 'green'=>'float', 'blue'=>'float', 'a='=>'float'],
'SWFDisplayItem::remove' => ['void'],
'SWFDisplayItem::rotate' => ['void', 'angle'=>'float'],
'SWFDisplayItem::rotateTo' => ['void', 'angle'=>'float'],
'SWFDisplayItem::scale' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFDisplayItem::scaleTo' => ['void', 'x'=>'float', 'y='=>'float'],
'SWFDisplayItem::setDepth' => ['void', 'depth'=>'int'],
'SWFDisplayItem::setMaskLevel' => ['void', 'level'=>'int'],
'SWFDisplayItem::setMatrix' => ['void', 'a'=>'float', 'b'=>'float', 'c'=>'float', 'd'=>'float', 'x'=>'float', 'y'=>'float'],
'SWFDisplayItem::setName' => ['void', 'name'=>'string'],
'SWFDisplayItem::setRatio' => ['void', 'ratio'=>'float'],
'SWFDisplayItem::skewX' => ['void', 'ddegrees'=>'float'],
'SWFDisplayItem::skewXTo' => ['void', 'degrees'=>'float'],
'SWFDisplayItem::skewY' => ['void', 'ddegrees'=>'float'],
'SWFDisplayItem::skewYTo' => ['void', 'degrees'=>'float'],
'SWFFill::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFFill::rotateTo' => ['void', 'angle'=>'float'],
'SWFFill::scaleTo' => ['void', 'x'=>'float', 'y='=>'float'],
'SWFFill::skewXTo' => ['void', 'x'=>'float'],
'SWFFill::skewYTo' => ['void', 'y'=>'float'],
'SWFFont::__construct' => ['void', 'filename'=>'string'],
'SWFFont::getAscent' => ['float'],
'SWFFont::getDescent' => ['float'],
'SWFFont::getLeading' => ['float'],
'SWFFont::getShape' => ['string', 'code'=>'int'],
'SWFFont::getUTF8Width' => ['float', 'string'=>'string'],
'SWFFont::getWidth' => ['float', 'string'=>'string'],
'SWFFontChar::addChars' => ['void', 'char'=>'string'],
'SWFFontChar::addUTF8Chars' => ['void', 'char'=>'string'],
'SWFGradient::__construct' => ['void'],
'SWFGradient::addEntry' => ['void', 'ratio'=>'float', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int'],
'SWFMorph::__construct' => ['void'],
'SWFMorph::getShape1' => ['SWFShape'],
'SWFMorph::getShape2' => ['SWFShape'],
'SWFMovie::__construct' => ['void', 'version='=>'int'],
'SWFMovie::add' => ['mixed', 'instance'=>'object'],
'SWFMovie::addExport' => ['void', 'char'=>'swfcharacter', 'name'=>'string'],
'SWFMovie::addFont' => ['mixed', 'font'=>'swffont'],
'SWFMovie::importChar' => ['SWFSprite', 'libswf'=>'string', 'name'=>'string'],
'SWFMovie::importFont' => ['SWFFontChar', 'libswf'=>'string', 'name'=>'string'],
'SWFMovie::labelFrame' => ['void', 'label'=>'string'],
'SWFMovie::namedAnchor' => [''],
'SWFMovie::nextFrame' => ['void'],
'SWFMovie::output' => ['int', 'compression='=>'int'],
'SWFMovie::protect' => [''],
'SWFMovie::remove' => ['void', 'instance'=>'object'],
'SWFMovie::save' => ['int', 'filename'=>'string', 'compression='=>'int'],
'SWFMovie::saveToFile' => ['int', 'x'=>'resource', 'compression='=>'int'],
'SWFMovie::setbackground' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int'],
'SWFMovie::setDimension' => ['void', 'width'=>'float', 'height'=>'float'],
'SWFMovie::setFrames' => ['void', 'number'=>'int'],
'SWFMovie::setRate' => ['void', 'rate'=>'float'],
'SWFMovie::startSound' => ['SWFSoundInstance', 'sound'=>'swfsound'],
'SWFMovie::stopSound' => ['void', 'sound'=>'swfsound'],
'SWFMovie::streamMP3' => ['int', 'mp3file'=>'mixed', 'skip='=>'float'],
'SWFMovie::writeExports' => ['void'],
'SWFPrebuiltClip::__construct' => ['void', 'file'=>''],
'SWFShape::__construct' => ['void'],
'SWFShape::addFill' => ['SWFFill', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'alpha='=>'int', 'bitmap='=>'swfbitmap', 'flags='=>'int', 'gradient='=>'swfgradient'],
'SWFShape::addFill\'1' => ['SWFFill', 'bitmap'=>'SWFBitmap', 'flags='=>'int'],
'SWFShape::addFill\'2' => ['SWFFill', 'gradient'=>'SWFGradient', 'flags='=>'int'],
'SWFShape::drawArc' => ['void', 'r'=>'float', 'startangle'=>'float', 'endangle'=>'float'],
'SWFShape::drawCircle' => ['void', 'r'=>'float'],
'SWFShape::drawCubic' => ['int', 'bx'=>'float', 'by'=>'float', 'cx'=>'float', 'cy'=>'float', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawCubicTo' => ['int', 'bx'=>'float', 'by'=>'float', 'cx'=>'float', 'cy'=>'float', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawCurve' => ['int', 'controldx'=>'float', 'controldy'=>'float', 'anchordx'=>'float', 'anchordy'=>'float', 'targetdx='=>'float', 'targetdy='=>'float'],
'SWFShape::drawCurveTo' => ['int', 'controlx'=>'float', 'controly'=>'float', 'anchorx'=>'float', 'anchory'=>'float', 'targetx='=>'float', 'targety='=>'float'],
'SWFShape::drawGlyph' => ['void', 'font'=>'swffont', 'character'=>'string', 'size='=>'int'],
'SWFShape::drawLine' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::drawLineTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFShape::movePen' => ['void', 'dx'=>'float', 'dy'=>'float'],
'SWFShape::movePenTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFShape::setLeftFill' => ['', 'fill'=>'swfgradient', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFShape::setLine' => ['', 'shape'=>'swfshape', 'width'=>'int', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFShape::setRightFill' => ['', 'fill'=>'swfgradient', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFSound' => ['SWFSound', 'filename'=>'string', 'flags='=>'int'],
'SWFSound::__construct' => ['void', 'filename'=>'string', 'flags='=>'int'],
'SWFSoundInstance::loopCount' => ['void', 'point'=>'int'],
'SWFSoundInstance::loopInPoint' => ['void', 'point'=>'int'],
'SWFSoundInstance::loopOutPoint' => ['void', 'point'=>'int'],
'SWFSoundInstance::noMultiple' => ['void'],
'SWFSprite::__construct' => ['void'],
'SWFSprite::add' => ['void', 'object'=>'object'],
'SWFSprite::labelFrame' => ['void', 'label'=>'string'],
'SWFSprite::nextFrame' => ['void'],
'SWFSprite::remove' => ['void', 'object'=>'object'],
'SWFSprite::setFrames' => ['void', 'number'=>'int'],
'SWFSprite::startSound' => ['SWFSoundInstance', 'sount'=>'swfsound'],
'SWFSprite::stopSound' => ['void', 'sount'=>'swfsound'],
'SWFText::__construct' => ['void'],
'SWFText::addString' => ['void', 'string'=>'string'],
'SWFText::addUTF8String' => ['void', 'text'=>'string'],
'SWFText::getAscent' => ['float'],
'SWFText::getDescent' => ['float'],
'SWFText::getLeading' => ['float'],
'SWFText::getUTF8Width' => ['float', 'string'=>'string'],
'SWFText::getWidth' => ['float', 'string'=>'string'],
'SWFText::moveTo' => ['void', 'x'=>'float', 'y'=>'float'],
'SWFText::setColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFText::setFont' => ['void', 'font'=>'swffont'],
'SWFText::setHeight' => ['void', 'height'=>'float'],
'SWFText::setSpacing' => ['void', 'spacing'=>'float'],
'SWFTextField::__construct' => ['void', 'flags='=>'int'],
'SWFTextField::addChars' => ['void', 'chars'=>'string'],
'SWFTextField::addString' => ['void', 'string'=>'string'],
'SWFTextField::align' => ['void', 'alignement'=>'int'],
'SWFTextField::setBounds' => ['void', 'width'=>'float', 'height'=>'float'],
'SWFTextField::setColor' => ['void', 'red'=>'int', 'green'=>'int', 'blue'=>'int', 'a='=>'int'],
'SWFTextField::setFont' => ['void', 'font'=>'swffont'],
'SWFTextField::setHeight' => ['void', 'height'=>'float'],
'SWFTextField::setIndentation' => ['void', 'width'=>'float'],
'SWFTextField::setLeftMargin' => ['void', 'width'=>'float'],
'SWFTextField::setLineSpacing' => ['void', 'height'=>'float'],
'SWFTextField::setMargins' => ['void', 'left'=>'float', 'right'=>'float'],
'SWFTextField::setName' => ['void', 'name'=>'string'],
'SWFTextField::setPadding' => ['void', 'padding'=>'float'],
'SWFTextField::setRightMargin' => ['void', 'width'=>'float'],
'SWFVideoStream::__construct' => ['void', 'file='=>'string'],
'SWFVideoStream::getNumFrames' => ['int'],
'SWFVideoStream::setDimension' => ['void', 'x'=>'int', 'y'=>'int'],
'Swish::__construct' => ['void', 'index_names'=>'string'],
'Swish::getMetaList' => ['array', 'index_name'=>'string'],
'Swish::getPropertyList' => ['array', 'index_name'=>'string'],
'Swish::prepare' => ['object', 'query='=>'string'],
'Swish::query' => ['object', 'query'=>'string'],
'SwishResult::getMetaList' => ['array'],
'SwishResult::stem' => ['array', 'word'=>'string'],
'SwishResults::getParsedWords' => ['array', 'index_name'=>'string'],
'SwishResults::getRemovedStopwords' => ['array', 'index_name'=>'string'],
'SwishResults::nextResult' => ['object'],
'SwishResults::seekResult' => ['int', 'position'=>'int'],
'SwishSearch::execute' => ['object', 'query='=>'string'],
'SwishSearch::resetLimit' => [''],
'SwishSearch::setLimit' => ['', 'property'=>'string', 'low'=>'string', 'high'=>'string'],
'SwishSearch::setPhraseDelimiter' => ['', 'delimiter'=>'string'],
'SwishSearch::setSort' => ['', 'sort'=>'string'],
'SwishSearch::setStructure' => ['', 'structure'=>'int'],
'swoole\async::dnsLookup' => ['void', 'hostname'=>'string', 'callback'=>'callable'],
'swoole\async::read' => ['bool', 'filename'=>'string', 'callback'=>'callable', 'chunk_size='=>'integer', 'offset='=>'integer'],
'swoole\async::readFile' => ['void', 'filename'=>'string', 'callback'=>'callable'],
'swoole\async::set' => ['void', 'settings'=>'array'],
'swoole\async::write' => ['void', 'filename'=>'string', 'content'=>'string', 'offset='=>'integer', 'callback='=>'callable'],
'swoole\async::writeFile' => ['void', 'filename'=>'string', 'content'=>'string', 'callback='=>'callable', 'flags='=>'string'],
'swoole\atomic::add' => ['integer', 'add_value='=>'integer'],
'swoole\atomic::cmpset' => ['integer', 'cmp_value'=>'integer', 'new_value'=>'integer'],
'swoole\atomic::get' => ['integer'],
'swoole\atomic::set' => ['integer', 'value'=>'integer'],
'swoole\atomic::sub' => ['integer', 'sub_value='=>'integer'],
'swoole\buffer::__destruct' => ['void'],
'swoole\buffer::__toString' => ['string'],
'swoole\buffer::append' => ['integer', 'data'=>'string'],
'swoole\buffer::clear' => ['void'],
'swoole\buffer::expand' => ['integer', 'size'=>'integer'],
'swoole\buffer::read' => ['string', 'offset'=>'integer', 'length'=>'integer'],
'swoole\buffer::recycle' => ['void'],
'swoole\buffer::substr' => ['string', 'offset'=>'integer', 'length='=>'integer', 'remove='=>'bool'],
'swoole\buffer::write' => ['void', 'offset'=>'integer', 'data'=>'string'],
'swoole\channel::__destruct' => ['void'],
'swoole\channel::pop' => ['mixed'],
'swoole\channel::push' => ['bool', 'data'=>'string'],
'swoole\channel::stats' => ['array'],
'swoole\client::__destruct' => ['void'],
'swoole\client::close' => ['bool', 'force='=>'bool'],
'swoole\client::connect' => ['bool', 'host'=>'string', 'port='=>'integer', 'timeout='=>'integer', 'flag='=>'integer'],
'swoole\client::getpeername' => ['array'],
'swoole\client::getsockname' => ['array'],
'swoole\client::isConnected' => ['bool'],
'swoole\client::on' => ['void', 'event'=>'string', 'callback'=>'callable'],
'swoole\client::pause' => ['void'],
'swoole\client::pipe' => ['void', 'socket'=>'string'],
'swoole\client::recv' => ['void', 'size='=>'string', 'flag='=>'string'],
'swoole\client::resume' => ['void'],
'swoole\client::send' => ['integer', 'data'=>'string', 'flag='=>'string'],
'swoole\client::sendfile' => ['bool', 'filename'=>'string', 'offset='=>'int'],
'swoole\client::sendto' => ['bool', 'ip'=>'string', 'port'=>'integer', 'data'=>'string'],
'swoole\client::set' => ['void', 'settings'=>'array'],
'swoole\client::sleep' => ['void'],
'swoole\client::wakeup' => ['void'],
'swoole\connection\iterator::count' => ['int'],
'swoole\connection\iterator::current' => ['Connection'],
'swoole\connection\iterator::key' => ['int'],
'swoole\connection\iterator::next' => ['Connection'],
'swoole\connection\iterator::offsetExists' => ['bool', 'index'=>'int'],
'swoole\connection\iterator::offsetGet' => ['Connection', 'index'=>'string'],
'swoole\connection\iterator::offsetSet' => ['void', 'offset'=>'int', 'connection'=>'mixed'],
'swoole\connection\iterator::offsetUnset' => ['void', 'offset'=>'int'],
'swoole\connection\iterator::rewind' => ['void'],
'swoole\connection\iterator::valid' => ['bool'],
'swoole\coroutine::call_user_func' => ['mixed', 'callback'=>'callable', 'parameter='=>'mixed', '...args='=>'mixed'],
'swoole\coroutine::call_user_func_array' => ['mixed', 'callback'=>'callable', 'param_array'=>'array'],
'swoole\coroutine::cli_wait' => ['ReturnType'],
'swoole\coroutine::create' => ['ReturnType'],
'swoole\coroutine::getuid' => ['ReturnType'],
'swoole\coroutine::resume' => ['ReturnType'],
'swoole\coroutine::suspend' => ['ReturnType'],
'swoole\coroutine\client::__destruct' => ['ReturnType'],
'swoole\coroutine\client::close' => ['ReturnType'],
'swoole\coroutine\client::connect' => ['ReturnType'],
'swoole\coroutine\client::getpeername' => ['ReturnType'],
'swoole\coroutine\client::getsockname' => ['ReturnType'],
'swoole\coroutine\client::isConnected' => ['ReturnType'],
'swoole\coroutine\client::recv' => ['ReturnType'],
'swoole\coroutine\client::send' => ['ReturnType'],
'swoole\coroutine\client::sendfile' => ['ReturnType'],
'swoole\coroutine\client::sendto' => ['ReturnType'],
'swoole\coroutine\client::set' => ['ReturnType'],
'swoole\coroutine\http\client::__destruct' => ['ReturnType'],
'swoole\coroutine\http\client::addFile' => ['ReturnType'],
'swoole\coroutine\http\client::close' => ['ReturnType'],
'swoole\coroutine\http\client::execute' => ['ReturnType'],
'swoole\coroutine\http\client::get' => ['ReturnType'],
'swoole\coroutine\http\client::getDefer' => ['ReturnType'],
'swoole\coroutine\http\client::isConnected' => ['ReturnType'],
'swoole\coroutine\http\client::post' => ['ReturnType'],
'swoole\coroutine\http\client::recv' => ['ReturnType'],
'swoole\coroutine\http\client::set' => ['ReturnType'],
'swoole\coroutine\http\client::setCookies' => ['ReturnType'],
'swoole\coroutine\http\client::setData' => ['ReturnType'],
'swoole\coroutine\http\client::setDefer' => ['ReturnType'],
'swoole\coroutine\http\client::setHeaders' => ['ReturnType'],
'swoole\coroutine\http\client::setMethod' => ['ReturnType'],
'swoole\coroutine\mysql::__destruct' => ['ReturnType'],
'swoole\coroutine\mysql::close' => ['ReturnType'],
'swoole\coroutine\mysql::connect' => ['ReturnType'],
'swoole\coroutine\mysql::getDefer' => ['ReturnType'],
'swoole\coroutine\mysql::query' => ['ReturnType'],
'swoole\coroutine\mysql::recv' => ['ReturnType'],
'swoole\coroutine\mysql::setDefer' => ['ReturnType'],
'swoole\event::add' => ['bool', 'fd'=>'int', 'read_callback'=>'callable', 'write_callback='=>'callable', 'events='=>'string'],
'swoole\event::defer' => ['void', 'callback'=>'mixed'],
'swoole\event::del' => ['bool', 'fd'=>'string'],
'swoole\event::exit' => ['void'],
'swoole\event::set' => ['bool', 'fd'=>'int', 'read_callback='=>'string', 'write_callback='=>'string', 'events='=>'string'],
'swoole\event::wait' => ['void'],
'swoole\event::write' => ['void', 'fd'=>'string', 'data'=>'string'],
'swoole\http\client::__destruct' => ['void'],
'swoole\http\client::addFile' => ['void', 'path'=>'string', 'name'=>'string', 'type='=>'string', 'filename='=>'string', 'offset='=>'string'],
'swoole\http\client::close' => ['void'],
'swoole\http\client::download' => ['void', 'path'=>'string', 'file'=>'string', 'callback'=>'callable', 'offset='=>'integer'],
'swoole\http\client::execute' => ['void', 'path'=>'string', 'callback'=>'string'],
'swoole\http\client::get' => ['void', 'path'=>'string', 'callback'=>'callable'],
'swoole\http\client::isConnected' => ['bool'],
'swoole\http\client::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\http\client::post' => ['void', 'path'=>'string', 'data'=>'string', 'callback'=>'callable'],
'swoole\http\client::push' => ['void', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string'],
'swoole\http\client::set' => ['void', 'settings'=>'array'],
'swoole\http\client::setCookies' => ['void', 'cookies'=>'array'],
'swoole\http\client::setData' => ['ReturnType', 'data'=>'string'],
'swoole\http\client::setHeaders' => ['void', 'headers'=>'array'],
'swoole\http\client::setMethod' => ['void', 'method'=>'string'],
'swoole\http\client::upgrade' => ['void', 'path'=>'string', 'callback'=>'string'],
'swoole\http\request::__destruct' => ['void'],
'swoole\http\request::rawcontent' => ['string'],
'swoole\http\response::__destruct' => ['void'],
'swoole\http\response::cookie' => ['string', 'name'=>'string', 'value='=>'string', 'expires='=>'string', 'path='=>'string', 'domain='=>'string', 'secure='=>'string', 'httponly='=>'string'],
'swoole\http\response::end' => ['void', 'content='=>'string'],
'swoole\http\response::gzip' => ['ReturnType', 'compress_level='=>'string'],
'swoole\http\response::header' => ['void', 'key'=>'string', 'value'=>'string', 'ucwords='=>'string'],
'swoole\http\response::initHeader' => ['ReturnType'],
'swoole\http\response::rawcookie' => ['ReturnType', 'name'=>'string', 'value='=>'string', 'expires='=>'string', 'path='=>'string', 'domain='=>'string', 'secure='=>'string', 'httponly='=>'string'],
'swoole\http\response::sendfile' => ['ReturnType', 'filename'=>'string', 'offset='=>'int'],
'swoole\http\response::status' => ['ReturnType', 'http_code'=>'string'],
'swoole\http\response::write' => ['void', 'content'=>'string'],
'swoole\http\server::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\http\server::start' => ['void'],
'swoole\lock::__destruct' => ['void'],
'swoole\lock::lock' => ['void'],
'swoole\lock::lock_read' => ['void'],
'swoole\lock::trylock' => ['void'],
'swoole\lock::trylock_read' => ['void'],
'swoole\lock::unlock' => ['void'],
'swoole\mmap::open' => ['ReturnType', 'filename'=>'string', 'size='=>'string', 'offset='=>'string'],
'swoole\mysql::__destruct' => ['void'],
'swoole\mysql::close' => ['void'],
'swoole\mysql::connect' => ['void', 'server_config'=>'array', 'callback'=>'callable'],
'swoole\mysql::getBuffer' => ['ReturnType'],
'swoole\mysql::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\mysql::query' => ['ReturnType', 'sql'=>'string', 'callback'=>'callable'],
'swoole\process::__destruct' => ['void'],
'swoole\process::alarm' => ['void', 'interval_usec'=>'integer'],
'swoole\process::close' => ['void'],
'swoole\process::daemon' => ['void', 'nochdir='=>'bool', 'noclose='=>'bool'],
'swoole\process::exec' => ['ReturnType', 'exec_file'=>'string', 'args'=>'string'],
'swoole\process::exit' => ['void', 'exit_code='=>'string'],
'swoole\process::freeQueue' => ['void'],
'swoole\process::kill' => ['void', 'pid'=>'integer', 'signal_no='=>'string'],
'swoole\process::name' => ['void', 'process_name'=>'string'],
'swoole\process::pop' => ['mixed', 'maxsize='=>'integer'],
'swoole\process::push' => ['bool', 'data'=>'string'],
'swoole\process::read' => ['string', 'maxsize='=>'integer'],
'swoole\process::signal' => ['void', 'signal_no'=>'string', 'callback'=>'callable'],
'swoole\process::start' => ['void'],
'swoole\process::statQueue' => ['array'],
'swoole\process::useQueue' => ['bool', 'key'=>'integer', 'mode='=>'integer'],
'swoole\process::wait' => ['array', 'blocking='=>'bool'],
'swoole\process::write' => ['integer', 'data'=>'string'],
'swoole\redis\server::format' => ['ReturnType', 'type'=>'string', 'value='=>'string'],
'swoole\redis\server::setHandler' => ['ReturnType', 'command'=>'string', 'callback'=>'string', 'number_of_string_param='=>'string', 'type_of_array_param='=>'string'],
'swoole\redis\server::start' => ['ReturnType'],
'swoole\serialize::pack' => ['ReturnType', 'data'=>'string', 'is_fast='=>'int'],
'swoole\serialize::unpack' => ['ReturnType', 'data'=>'string', 'args='=>'string'],
'swoole\server::addlistener' => ['void', 'host'=>'string', 'port'=>'integer', 'socket_type'=>'string'],
'swoole\server::addProcess' => ['bool', 'process'=>'swoole_process'],
'swoole\server::after' => ['ReturnType', 'after_time_ms'=>'integer', 'callback'=>'callable', 'param='=>'string'],
'swoole\server::bind' => ['bool', 'fd'=>'integer', 'uid'=>'integer'],
'swoole\server::close' => ['bool', 'fd'=>'integer', 'reset='=>'bool'],
'swoole\server::confirm' => ['bool', 'fd'=>'integer'],
'swoole\server::connection_info' => ['array', 'fd'=>'integer', 'reactor_id='=>'integer'],
'swoole\server::connection_list' => ['array', 'start_fd'=>'integer', 'pagesize='=>'integer'],
'swoole\server::defer' => ['void', 'callback'=>'callable'],
'swoole\server::exist' => ['bool', 'fd'=>'integer'],
'swoole\server::finish' => ['void', 'data'=>'string'],
'swoole\server::getClientInfo' => ['ReturnType', 'fd'=>'integer', 'reactor_id='=>'integer'],
'swoole\server::getClientList' => ['array', 'start_fd'=>'integer', 'pagesize='=>'integer'],
'swoole\server::getLastError' => ['integer'],
'swoole\server::heartbeat' => ['mixed', 'if_close_connection'=>'bool'],
'swoole\server::listen' => ['bool', 'host'=>'string', 'port'=>'integer', 'socket_type'=>'string'],
'swoole\server::on' => ['void', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\server::pause' => ['void', 'fd'=>'integer'],
'swoole\server::protect' => ['void', 'fd'=>'integer', 'is_protected='=>'bool'],
'swoole\server::reload' => ['bool'],
'swoole\server::resume' => ['void', 'fd'=>'integer'],
'swoole\server::send' => ['bool', 'fd'=>'integer', 'data'=>'string', 'reactor_id='=>'integer'],
'swoole\server::sendfile' => ['bool', 'fd'=>'integer', 'filename'=>'string', 'offset='=>'integer'],
'swoole\server::sendMessage' => ['bool', 'worker_id'=>'integer', 'data'=>'string'],
'swoole\server::sendto' => ['bool', 'ip'=>'string', 'port'=>'integer', 'data'=>'string', 'server_socket='=>'string'],
'swoole\server::sendwait' => ['bool', 'fd'=>'integer', 'data'=>'string'],
'swoole\server::set' => ['ReturnType', 'settings'=>'array'],
'swoole\server::shutdown' => ['void'],
'swoole\server::start' => ['void'],
'swoole\server::stats' => ['array'],
'swoole\server::stop' => ['bool', 'worker_id='=>'integer'],
'swoole\server::task' => ['mixed', 'data'=>'string', 'dst_worker_id='=>'integer', 'callback='=>'callable'],
'swoole\server::taskwait' => ['void', 'data'=>'string', 'timeout='=>'float', 'worker_id='=>'integer'],
'swoole\server::taskWaitMulti' => ['void', 'tasks'=>'array', 'timeout_ms='=>'double'],
'swoole\server::tick' => ['void', 'interval_ms'=>'integer', 'callback'=>'callable'],
'swoole\server\port::__destruct' => ['void'],
'swoole\server\port::on' => ['ReturnType', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\server\port::set' => ['void', 'settings'=>'array'],
'swoole\table::column' => ['ReturnType', 'name'=>'string', 'type'=>'string', 'size='=>'integer'],
'swoole\table::count' => ['integer'],
'swoole\table::create' => ['void'],
'swoole\table::current' => ['array'],
'swoole\table::decr' => ['ReturnType', 'key'=>'string', 'column'=>'string', 'decrby='=>'integer'],
'swoole\table::del' => ['void', 'key'=>'string'],
'swoole\table::destroy' => ['void'],
'swoole\table::exist' => ['bool', 'key'=>'string'],
'swoole\table::get' => ['integer', 'row_key'=>'string', 'column_key'=>'string'],
'swoole\table::incr' => ['void', 'key'=>'string', 'column'=>'string', 'incrby='=>'integer'],
'swoole\table::key' => ['string'],
'swoole\table::next' => ['ReturnType'],
'swoole\table::rewind' => ['void'],
'swoole\table::set' => ['VOID', 'key'=>'string', 'value'=>'array'],
'swoole\table::valid' => ['bool'],
'swoole\timer::after' => ['void', 'after_time_ms'=>'int', 'callback'=>'callable'],
'swoole\timer::clear' => ['void', 'timer_id'=>'integer'],
'swoole\timer::exists' => ['bool', 'timer_id'=>'integer'],
'swoole\timer::tick' => ['void', 'interval_ms'=>'integer', 'callback'=>'callable', 'param='=>'string'],
'swoole\websocket\server::exist' => ['bool', 'fd'=>'integer'],
'swoole\websocket\server::on' => ['ReturnType', 'event_name'=>'string', 'callback'=>'callable'],
'swoole\websocket\server::pack' => ['binary', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string', 'mask='=>'string'],
'swoole\websocket\server::push' => ['void', 'fd'=>'string', 'data'=>'string', 'opcode='=>'string', 'finish='=>'string'],
'swoole\websocket\server::unpack' => ['string', 'data'=>'binary'],
'swoole_async_dns_lookup' => ['bool', 'hostname'=>'string', 'callback'=>'callable'],
'swoole_async_read' => ['bool', 'filename'=>'string', 'callback'=>'callable', 'chunk_size='=>'int', 'offset='=>'int'],
'swoole_async_readfile' => ['bool', 'filename'=>'string', 'callback'=>'string'],
'swoole_async_set' => ['void', 'settings'=>'array'],
'swoole_async_write' => ['bool', 'filename'=>'string', 'content'=>'string', 'offset='=>'int', 'callback='=>'callable'],
'swoole_async_writefile' => ['bool', 'filename'=>'string', 'content'=>'string', 'callback='=>'callable', 'flags='=>'int'],
'swoole_client_select' => ['int', 'read_array'=>'array', 'write_array'=>'array', 'error_array'=>'array', 'timeout='=>'float'],
'swoole_cpu_num' => ['int'],
'swoole_errno' => ['int'],
'swoole_event_add' => ['int', 'fd'=>'int', 'read_callback='=>'callable', 'write_callback='=>'callable', 'events='=>'int'],
'swoole_event_defer' => ['bool', 'callback'=>'callable'],
'swoole_event_del' => ['bool', 'fd'=>'int'],
'swoole_event_exit' => ['void'],
'swoole_event_set' => ['bool', 'fd'=>'int', 'read_callback='=>'callable', 'write_callback='=>'callable', 'events='=>'int'],
'swoole_event_wait' => ['void'],
'swoole_event_write' => ['bool', 'fd'=>'int', 'data'=>'string'],
'swoole_get_local_ip' => ['array'],
'swoole_last_error' => ['int'],
'swoole_load_module' => ['mixed', 'filename'=>'string'],
'swoole_select' => ['int', 'read_array'=>'array', 'write_array'=>'array', 'error_array'=>'array', 'timeout='=>'float'],
'swoole_set_process_name' => ['void', 'process_name'=>'string', 'size='=>'int'],
'swoole_strerror' => ['string', 'errno'=>'int', 'error_type='=>'int'],
'swoole_timer_after' => ['int', 'ms'=>'int', 'callback'=>'callable', 'param='=>'mixed'],
'swoole_timer_exists' => ['bool', 'timer_id'=>'int'],
'swoole_timer_tick' => ['int', 'ms'=>'int', 'callback'=>'callable', 'param='=>'mixed'],
'swoole_version' => ['string'],
'symbolObj::__construct' => ['void', 'map'=>'mapObj', 'symbolname'=>'string'],
'symbolObj::free' => ['void'],
'symbolObj::getPatternArray' => ['array'],
'symbolObj::getPointsArray' => ['array'],
'symbolObj::ms_newSymbolObj' => ['int', 'map'=>'mapObj', 'symbolname'=>'string'],
'symbolObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'symbolObj::setImagePath' => ['int', 'filename'=>'string'],
'symbolObj::setPattern' => ['int', 'int'=>'array'],
'symbolObj::setPoints' => ['int', 'double'=>'array'],
'symlink' => ['bool', 'target'=>'string', 'link'=>'string'],
'SyncEvent::__construct' => ['void', 'name='=>'string', 'manual='=>'bool'],
'SyncEvent::fire' => ['bool'],
'SyncEvent::reset' => ['bool'],
'SyncEvent::wait' => ['bool', 'wait='=>'int'],
'SyncMutex::__construct' => ['void', 'name='=>'string'],
'SyncMutex::lock' => ['bool', 'wait='=>'int'],
'SyncMutex::unlock' => ['bool', 'all='=>'bool'],
'SyncReaderWriter::__construct' => ['void', 'name='=>'string', 'autounlock='=>'bool'],
'SyncReaderWriter::readlock' => ['bool', 'wait='=>'int'],
'SyncReaderWriter::readunlock' => ['bool'],
'SyncReaderWriter::writelock' => ['bool', 'wait='=>'int'],
'SyncReaderWriter::writeunlock' => ['bool'],
'SyncSemaphore::__construct' => ['void', 'name='=>'string', 'initialval='=>'int', 'autounlock='=>'bool'],
'SyncSemaphore::lock' => ['bool', 'wait='=>'int'],
'SyncSemaphore::unlock' => ['bool', '&w_prevcount='=>'int'],
'SyncSharedMemory::__construct' => ['void', 'name'=>'string', 'size'=>'int'],
'SyncSharedMemory::first' => ['bool'],
'SyncSharedMemory::read' => ['string', 'start='=>'int', 'length='=>'int'],
'SyncSharedMemory::size' => ['int'],
'SyncSharedMemory::write' => ['int', 'string='=>'string', 'start='=>'int'],
'sys_get_temp_dir' => ['string'],
'sys_getloadavg' => ['array'],
'syslog' => ['bool', 'priority'=>'int', 'message'=>'string'],
'system' => ['string|false', 'command'=>'string', '&w_return_value='=>'int'],
'taint' => ['bool', '&rw_string'=>'string', '&...w_other_strings='=>'string'],
'tan' => ['float', 'number'=>'float'],
'tanh' => ['float', 'number'=>'float'],
'tcpwrap_check' => ['bool', 'daemon'=>'string', 'address'=>'string', 'user='=>'string', 'nodns='=>'bool'],
'tempnam' => ['string|false', 'dir'=>'string', 'prefix'=>'string'],
'textdomain' => ['string', 'domain'=>'string'],
'Thread::__construct' => ['void'],
'Thread::addRef' => ['void'],
'Thread::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Thread::count' => ['int'],
'Thread::delRef' => ['void'],
'Thread::detach' => ['void'],
'Thread::extend' => ['bool', 'class'=>'string'],
'Thread::getCreatorId' => ['int'],
'Thread::getCurrentThread' => ['Thread'],
'Thread::getCurrentThreadId' => ['int'],
'Thread::getRefCount' => ['int'],
'Thread::getTerminationInfo' => ['array'],
'Thread::getThreadId' => ['int'],
'Thread::globally' => ['mixed'],
'Thread::isGarbage' => ['bool'],
'Thread::isJoined' => ['bool'],
'Thread::isRunning' => ['bool'],
'Thread::isStarted' => ['bool'],
'Thread::isTerminated' => ['bool'],
'Thread::isWaiting' => ['bool'],
'Thread::join' => ['bool'],
'Thread::kill' => ['void'],
'Thread::lock' => ['bool'],
'Thread::merge' => ['bool', 'from'=>'', 'overwrite='=>'mixed'],
'Thread::notify' => ['bool'],
'Thread::notifyOne' => ['bool'],
'Thread::offsetExists' => ['bool', 'offset'=>'mixed'],
'Thread::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Thread::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Thread::offsetUnset' => ['void', 'offset'=>'mixed'],
'Thread::pop' => ['bool'],
'Thread::run' => ['void'],
'Thread::setGarbage' => ['void'],
'Thread::shift' => ['bool'],
'Thread::start' => ['bool', 'options='=>'int'],
'Thread::synchronized' => ['mixed', 'block'=>'Closure', '_='=>'mixed'],
'Thread::unlock' => ['bool'],
'Thread::wait' => ['bool', 'timeout='=>'int'],
'Threaded::__construct' => ['void'],
'Threaded::addRef' => ['void'],
'Threaded::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Threaded::count' => ['int'],
'Threaded::delRef' => ['void'],
'Threaded::extend' => ['bool', 'class'=>'string'],
'Threaded::from' => ['Threaded', 'run'=>'Closure', 'construct='=>'Closure', 'args='=>'array'],
'Threaded::getRefCount' => ['int'],
'Threaded::getTerminationInfo' => ['array'],
'Threaded::isGarbage' => ['bool'],
'Threaded::isRunning' => ['bool'],
'Threaded::isTerminated' => ['bool'],
'Threaded::isWaiting' => ['bool'],
'Threaded::lock' => ['bool'],
'Threaded::merge' => ['bool', 'from'=>'mixed', 'overwrite='=>'bool'],
'Threaded::notify' => ['bool'],
'Threaded::notifyOne' => ['bool'],
'Threaded::offsetExists' => ['bool', 'offset'=>'mixed'],
'Threaded::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Threaded::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Threaded::offsetUnset' => ['void', 'offset'=>'mixed'],
'Threaded::pop' => ['bool'],
'Threaded::run' => ['void'],
'Threaded::setGarbage' => ['void'],
'Threaded::shift' => ['mixed'],
'Threaded::synchronized' => ['mixed', 'block'=>'Closure', '...args='=>'mixed'],
'Threaded::unlock' => ['bool'],
'Threaded::wait' => ['bool', 'timeout='=>'int'],
'Throwable::__toString' => ['string'],
'Throwable::getCode' => ['int|string'],
'Throwable::getFile' => ['string'],
'Throwable::getLine' => ['int'],
'Throwable::getMessage' => ['string'],
'Throwable::getPrevious' => ['?Throwable'],
'Throwable::getTrace' => ['array'],
'Throwable::getTraceAsString' => ['string'],
'tidy::__construct' => ['void', 'filename='=>'string', 'config='=>'', 'encoding='=>'string', 'use_include_path='=>'bool'],
'tidy::body' => ['tidyNode'],
'tidy::cleanRepair' => ['bool'],
'tidy::diagnose' => ['bool'],
'tidy::getConfig' => ['array'],
'tidy::getHtmlVer' => ['int'],
'tidy::getOpt' => ['mixed', 'option'=>'string'],
'tidy::getOptDoc' => ['string', 'optname'=>'string'],
'tidy::getRelease' => ['string'],
'tidy::getStatus' => ['int'],
'tidy::head' => ['tidyNode'],
'tidy::html' => ['tidyNode'],
'tidy::htmlver' => ['int'],
'tidy::isXhtml' => ['bool'],
'tidy::isXml' => ['bool'],
'tidy::parseFile' => ['bool', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'use_include_path='=>'bool'],
'tidy::parseString' => ['bool', 'input'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::repairFile' => ['string', 'filename'=>'string', 'config='=>'', 'encoding='=>'string', 'use_include_path='=>'bool'],
'tidy::repairString' => ['string', 'data'=>'string', 'config='=>'', 'encoding='=>'string'],
'tidy::root' => ['tidyNode'],
'tidy_access_count' => ['int', 'obj'=>'tidy'],
'tidy_clean_repair' => ['bool', 'obj'=>'tidy'],
'tidy_config_count' => ['int', 'obj'=>'tidy'],
'tidy_diagnose' => ['bool', 'obj'=>'tidy'],
'tidy_error_count' => ['int', 'obj'=>'tidy'],
'tidy_get_body' => ['tidyNode', 'obj'=>'tidy'],
'tidy_get_config' => ['array', 'obj'=>'tidy'],
'tidy_get_error_buffer' => ['string', 'obj'=>'tidy'],
'tidy_get_head' => ['tidyNode', 'obj'=>'tidy'],
'tidy_get_html' => ['tidyNode', 'obj'=>'tidy'],
'tidy_get_html_ver' => ['int', 'obj'=>'tidy'],
'tidy_get_opt_doc' => ['string', 'obj'=>'tidy', 'optname'=>'string'],
'tidy_get_output' => ['string', 'obj'=>'tidy'],
'tidy_get_release' => ['string'],
'tidy_get_root' => ['tidyNode', 'obj'=>'tidy'],
'tidy_get_status' => ['int', 'obj'=>'tidy'],
'tidy_getopt' => ['mixed', 'option'=>'string', 'obj'=>'tidy'],
'tidy_is_xhtml' => ['bool', 'obj'=>'tidy'],
'tidy_is_xml' => ['bool', 'obj'=>'tidy'],
'tidy_load_config' => ['void', 'filename'=>'string', 'encoding'=>'string'],
'tidy_parse_file' => ['tidy', 'file'=>'string', 'config_options='=>'', 'encoding='=>'string', 'use_include_path='=>'bool'],
'tidy_parse_string' => ['tidy', 'input'=>'string', 'config_options='=>'', 'encoding='=>'string'],
'tidy_repair_file' => ['string', 'filename'=>'string', 'config_file='=>'', 'encoding='=>'string', 'use_include_path='=>'bool'],
'tidy_repair_string' => ['string', 'data'=>'string', 'config_file='=>'', 'encoding='=>'string'],
'tidy_reset_config' => ['bool'],
'tidy_save_config' => ['bool', 'filename'=>'string'],
'tidy_set_encoding' => ['bool', 'encoding'=>'string'],
'tidy_setopt' => ['bool', 'option'=>'string', 'value'=>'mixed'],
'tidy_warning_count' => ['int', 'obj'=>'tidy'],
'tidyNode::__construct' => ['void'],
'tidyNode::getParent' => ['tidyNode'],
'tidyNode::hasChildren' => ['bool'],
'tidyNode::hasSiblings' => ['bool'],
'tidyNode::isAsp' => ['bool'],
'tidyNode::isComment' => ['bool'],
'tidyNode::isHtml' => ['bool'],
'tidyNode::isJste' => ['bool'],
'tidyNode::isPhp' => ['bool'],
'tidyNode::isText' => ['bool'],
'time' => ['int'],
'time_nanosleep' => ['array{0:int,1:int}|bool', 'seconds'=>'int', 'nanoseconds'=>'int'],
'time_sleep_until' => ['bool', 'timestamp'=>'float'],
'timezone_abbreviations_list' => ['array|false'],
'timezone_identifiers_list' => ['array|false', 'what='=>'int', 'country='=>'?string'],
'timezone_location_get' => ['array|false', 'object'=>'DateTimeZone'],
'timezone_name_from_abbr' => ['string|false', 'abbr'=>'string', 'gmtoffset='=>'int', 'isdst='=>'int'],
'timezone_name_get' => ['string', 'object'=>'DateTimeZone'],
'timezone_offset_get' => ['int|false', 'object'=>'DateTimeZone', 'datetime'=>'DateTimeInterface'],
'timezone_open' => ['DateTimeZone|false', 'timezone'=>'string'],
'timezone_transitions_get' => ['array|false', 'object'=>'DateTimeZone', 'timestamp_begin='=>'int', 'timestamp_end='=>'int'],
'timezone_version_get' => ['string'],
'tmpfile' => ['resource|false'],
'token_get_all' => ['array<int,string|array{0:int,1:string,2:int}>', 'source'=>'string', 'flags='=>'int'],
'token_name' => ['string', 'type'=>'int'],
'TokyoTyrant::__construct' => ['void', 'host='=>'string', 'port='=>'int', 'options='=>'array'],
'TokyoTyrant::add' => ['int|float', 'key'=>'string', 'increment'=>'float', 'type='=>'int'],
'TokyoTyrant::connect' => ['TokyoTyrant', 'host'=>'string', 'port='=>'int', 'options='=>'array'],
'TokyoTyrant::connectUri' => ['TokyoTyrant', 'uri'=>'string'],
'TokyoTyrant::copy' => ['TokyoTyrant', 'path'=>'string'],
'TokyoTyrant::ext' => ['string', 'name'=>'string', 'options'=>'int', 'key'=>'string', 'value'=>'string'],
'TokyoTyrant::fwmKeys' => ['array', 'prefix'=>'string', 'max_recs'=>'int'],
'TokyoTyrant::get' => ['array', 'keys'=>'mixed'],
'TokyoTyrant::getIterator' => ['TokyoTyrantIterator'],
'TokyoTyrant::num' => ['int'],
'TokyoTyrant::out' => ['string', 'keys'=>'mixed'],
'TokyoTyrant::put' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putCat' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putKeep' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putNr' => ['TokyoTyrant', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrant::putShl' => ['mixed', 'key'=>'string', 'value'=>'string', 'width'=>'int'],
'TokyoTyrant::restore' => ['mixed', 'log_dir'=>'string', 'timestamp'=>'int', 'check_consistency='=>'bool'],
'TokyoTyrant::setMaster' => ['mixed', 'host'=>'string', 'port'=>'int', 'timestamp'=>'int', 'check_consistency='=>'bool'],
'TokyoTyrant::size' => ['int', 'key'=>'string'],
'TokyoTyrant::stat' => ['array'],
'TokyoTyrant::sync' => ['mixed'],
'TokyoTyrant::tune' => ['TokyoTyrant', 'timeout'=>'float', 'options='=>'int'],
'TokyoTyrant::vanish' => ['mixed'],
'TokyoTyrantIterator::__construct' => ['void', 'object'=>'mixed'],
'TokyoTyrantIterator::current' => ['mixed'],
'TokyoTyrantIterator::key' => ['mixed'],
'TokyoTyrantIterator::next' => ['mixed'],
'TokyoTyrantIterator::rewind' => ['void'],
'TokyoTyrantIterator::valid' => ['bool'],
'TokyoTyrantQuery::__construct' => ['void', 'table'=>'TokyoTyrantTable'],
'TokyoTyrantQuery::addCond' => ['mixed', 'name'=>'string', 'op'=>'int', 'expr'=>'string'],
'TokyoTyrantQuery::count' => ['int'],
'TokyoTyrantQuery::current' => ['array'],
'TokyoTyrantQuery::hint' => ['string'],
'TokyoTyrantQuery::key' => ['string'],
'TokyoTyrantQuery::metaSearch' => ['array', 'queries'=>'array', 'type'=>'int'],
'TokyoTyrantQuery::next' => ['array'],
'TokyoTyrantQuery::out' => ['TokyoTyrantQuery'],
'TokyoTyrantQuery::rewind' => ['bool'],
'TokyoTyrantQuery::search' => ['array'],
'TokyoTyrantQuery::setLimit' => ['mixed', 'max='=>'int', 'skip='=>'int'],
'TokyoTyrantQuery::setOrder' => ['mixed', 'name'=>'string', 'type'=>'int'],
'TokyoTyrantQuery::valid' => ['bool'],
'TokyoTyrantTable::add' => ['void', 'key'=>'string', 'increment'=>'mixed', 'type='=>'string'],
'TokyoTyrantTable::genUid' => ['int'],
'TokyoTyrantTable::get' => ['array', 'keys'=>'mixed'],
'TokyoTyrantTable::getIterator' => ['TokyoTyrantIterator'],
'TokyoTyrantTable::getQuery' => ['TokyoTyrantQuery'],
'TokyoTyrantTable::out' => ['void', 'keys'=>'mixed'],
'TokyoTyrantTable::put' => ['int', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putCat' => ['void', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putKeep' => ['void', 'key'=>'string', 'columns'=>'array'],
'TokyoTyrantTable::putNr' => ['void', 'keys'=>'mixed', 'value='=>'string'],
'TokyoTyrantTable::putShl' => ['void', 'key'=>'string', 'value'=>'string', 'width'=>'int'],
'TokyoTyrantTable::setIndex' => ['mixed', 'column'=>'string', 'type'=>'int'],
'touch' => ['bool', 'filename'=>'string', 'time='=>'int', 'atime='=>'int'],
'trader_acos' => ['array', 'real'=>'array'],
'trader_ad' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array'],
'trader_add' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_adosc' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int'],
'trader_adx' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_adxr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_apo' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'mAType='=>'int'],
'trader_aroon' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_aroonosc' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_asin' => ['array', 'real'=>'array'],
'trader_atan' => ['array', 'real'=>'array'],
'trader_atr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_avgprice' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_bbands' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDevUp='=>'float', 'nbDevDn='=>'float', 'mAType='=>'int'],
'trader_beta' => ['array', 'real0'=>'array', 'real1'=>'array', 'timePeriod='=>'int'],
'trader_bop' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cci' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_cdl2crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3blackcrows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3inside' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3linestrike' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3outside' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3starsinsouth' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdl3whitesoldiers' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlabandonedbaby' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdladvanceblock' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlbelthold' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlbreakaway' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlclosingmarubozu' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlconcealbabyswall' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlcounterattack' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldarkcloudcover' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdldoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdldragonflydoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlengulfing' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdleveningdojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdleveningstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlgapsidesidewhite' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlgravestonedoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhammer' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhangingman' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlharami' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlharamicross' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhighwave' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhikkake' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhikkakemod' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlhomingpigeon' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlidentical3crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlinneck' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlinvertedhammer' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlkicking' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlkickingbylength' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlladderbottom' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdllongleggeddoji' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdllongline' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmarubozu' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmatchinglow' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlmathold' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlmorningdojistar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlmorningstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'penetration='=>'float'],
'trader_cdlonneck' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlpiercing' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlrickshawman' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlrisefall3methods' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlseparatinglines' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlshootingstar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlshortline' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlspinningtop' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlstalledpattern' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlsticksandwich' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltakuri' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltasukigap' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlthrusting' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdltristar' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlunique3river' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlupsidegap2crows' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_cdlxsidegap3methods' => ['array', 'open'=>'array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_ceil' => ['array', 'real'=>'array'],
'trader_cmo' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_correl' => ['array', 'real0'=>'array', 'real1'=>'array', 'timePeriod='=>'int'],
'trader_cos' => ['array', 'real'=>'array'],
'trader_cosh' => ['array', 'real'=>'array'],
'trader_dema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_div' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_dx' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_ema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_errno' => ['int'],
'trader_exp' => ['array', 'real'=>'array'],
'trader_floor' => ['array', 'real'=>'array'],
'trader_get_compat' => ['int'],
'trader_get_unstable_period' => ['int', 'functionId'=>'int'],
'trader_ht_dcperiod' => ['array', 'real'=>'array'],
'trader_ht_dcphase' => ['array', 'real'=>'array'],
'trader_ht_phasor' => ['array', 'real'=>'array'],
'trader_ht_sine' => ['array', 'real'=>'array'],
'trader_ht_trendline' => ['array', 'real'=>'array'],
'trader_ht_trendmode' => ['array', 'real'=>'array'],
'trader_kama' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_angle' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_intercept' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_linearreg_slope' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_ln' => ['array', 'real'=>'array'],
'trader_log10' => ['array', 'real'=>'array'],
'trader_ma' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'mAType='=>'int'],
'trader_macd' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'signalPeriod='=>'int'],
'trader_macdext' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'fastMAType='=>'int', 'slowPeriod='=>'int', 'slowMAType='=>'int', 'signalPeriod='=>'int', 'signalMAType='=>'int'],
'trader_macdfix' => ['array', 'real'=>'array', 'signalPeriod='=>'int'],
'trader_mama' => ['array', 'real'=>'array', 'fastLimit='=>'float', 'slowLimit='=>'float'],
'trader_mavp' => ['array', 'real'=>'array', 'periods'=>'array', 'minPeriod='=>'int', 'maxPeriod='=>'int', 'mAType='=>'int'],
'trader_max' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_maxindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_medprice' => ['array', 'high'=>'array', 'low'=>'array'],
'trader_mfi' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'volume'=>'array', 'timePeriod='=>'int'],
'trader_midpoint' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_midprice' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_min' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minmax' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minmaxindex' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_minus_di' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_minus_dm' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_mom' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_mult' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_natr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_obv' => ['array', 'real'=>'array', 'volume'=>'array'],
'trader_plus_di' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_plus_dm' => ['array', 'high'=>'array', 'low'=>'array', 'timePeriod='=>'int'],
'trader_ppo' => ['array', 'real'=>'array', 'fastPeriod='=>'int', 'slowPeriod='=>'int', 'mAType='=>'int'],
'trader_roc' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocp' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocr' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rocr100' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_rsi' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_sar' => ['array', 'high'=>'array', 'low'=>'array', 'acceleration='=>'float', 'maximum='=>'float'],
'trader_sarext' => ['array', 'high'=>'array', 'low'=>'array', 'startValue='=>'float', 'offsetOnReverse='=>'float', 'accelerationInitLong='=>'float', 'accelerationLong='=>'float', 'accelerationMaxLong='=>'float', 'accelerationInitShort='=>'float', 'accelerationShort='=>'float', 'accelerationMaxShort='=>'float'],
'trader_set_compat' => ['void', 'compatId'=>'int'],
'trader_set_unstable_period' => ['void', 'functionId'=>'int', 'timePeriod'=>'int'],
'trader_sin' => ['array', 'real'=>'array'],
'trader_sinh' => ['array', 'real'=>'array'],
'trader_sma' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_sqrt' => ['array', 'real'=>'array'],
'trader_stddev' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDev='=>'float'],
'trader_stoch' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'fastK_Period='=>'int', 'slowK_Period='=>'int', 'slowK_MAType='=>'int', 'slowD_Period='=>'int', 'slowD_MAType='=>'int'],
'trader_stochf' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'fastK_Period='=>'int', 'fastD_Period='=>'int', 'fastD_MAType='=>'int'],
'trader_stochrsi' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'fastK_Period='=>'int', 'fastD_Period='=>'int', 'fastD_MAType='=>'int'],
'trader_sub' => ['array', 'real0'=>'array', 'real1'=>'array'],
'trader_sum' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_t3' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'vFactor='=>'float'],
'trader_tan' => ['array', 'real'=>'array'],
'trader_tanh' => ['array', 'real'=>'array'],
'trader_tema' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_trange' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_trima' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_trix' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_tsf' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trader_typprice' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_ultosc' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod1='=>'int', 'timePeriod2='=>'int', 'timePeriod3='=>'int'],
'trader_var' => ['array', 'real'=>'array', 'timePeriod='=>'int', 'nbDev='=>'float'],
'trader_wclprice' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array'],
'trader_willr' => ['array', 'high'=>'array', 'low'=>'array', 'close'=>'array', 'timePeriod='=>'int'],
'trader_wma' => ['array', 'real'=>'array', 'timePeriod='=>'int'],
'trait_exists' => ['?bool', 'traitname'=>'string', 'autoload='=>'bool'],
'Transliterator::create' => ['?Transliterator', 'id'=>'string', 'direction='=>'int'],
'Transliterator::createFromRules' => ['?Transliterator', 'rules'=>'string', 'direction='=>'int'],
'Transliterator::createInverse' => ['Transliterator'],
'Transliterator::getErrorCode' => ['int'],
'Transliterator::getErrorMessage' => ['string'],
'Transliterator::listIDs' => ['array'],
'Transliterator::transliterate' => ['string|false', 'subject'=>'string', 'start='=>'int', 'end='=>'int'],
'transliterator_create' => ['?Transliterator', 'id'=>'string', 'direction='=>'int'],
'transliterator_create_from_rules' => ['?Transliterator', 'rules'=>'string', 'direction='=>'int'],
'transliterator_create_inverse' => ['Transliterator', 'obj'=>'Transliterator'],
'transliterator_get_error_code' => ['int', 'obj'=>'Transliterator'],
'transliterator_get_error_message' => ['string', 'obj'=>'Transliterator'],
'transliterator_list_ids' => ['array'],
'transliterator_transliterate' => ['string|false', 'obj'=>'Transliterator|string', 'subject'=>'string', 'start='=>'int', 'end='=>'int'],
'trigger_error' => ['bool', 'message'=>'string', 'error_type='=>'int'],
'trim' => ['string', 'str'=>'string', 'character_mask='=>'string'],
'TypeError::__clone' => ['void'],
'TypeError::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?TypeError'],
'TypeError::__toString' => ['string'],
'TypeError::getCode' => ['int'],
'TypeError::getFile' => ['string'],
'TypeError::getLine' => ['int'],
'TypeError::getMessage' => ['string'],
'TypeError::getPrevious' => ['Throwable|TypeError|null'],
'TypeError::getTrace' => ['array'],
'TypeError::getTraceAsString' => ['string'],
'uasort' => ['bool', '&rw_array_arg'=>'array', 'cmp_function'=>'callable(mixed,mixed):int'],
'ucfirst' => ['string', 'str'=>'string'],
'UConverter::__construct' => ['void', 'destination_encoding='=>'string', 'source_encoding='=>'string'],
'UConverter::convert' => ['string', 'str'=>'string', 'reverse='=>'bool'],
'UConverter::fromUCallback' => ['mixed', 'reason'=>'int', 'source'=>'string', 'codePoint'=>'string', '&w_error'=>'int'],
'UConverter::getAliases' => ['array', 'name'=>'string'],
'UConverter::getAvailable' => ['array'],
'UConverter::getDestinationEncoding' => ['string'],
'UConverter::getDestinationType' => ['int'],
'UConverter::getErrorCode' => ['int'],
'UConverter::getErrorMessage' => ['string'],
'UConverter::getSourceEncoding' => ['string'],
'UConverter::getSourceType' => ['int'],
'UConverter::getStandards' => ['array'],
'UConverter::getSubstChars' => ['string'],
'UConverter::reasonText' => ['string', 'reason='=>'int'],
'UConverter::setDestinationEncoding' => ['bool', 'encoding'=>'string'],
'UConverter::setSourceEncoding' => ['bool', 'encoding'=>'string'],
'UConverter::setSubstChars' => ['bool', 'chars'=>'string'],
'UConverter::toUCallback' => ['mixed', 'reason'=>'int', 'source'=>'string', 'codeUnits'=>'string', '&w_error'=>'int'],
'UConverter::transcode' => ['string', 'str'=>'string', 'toEncoding'=>'string', 'fromEncoding'=>'string', 'options='=>'?array'],
'ucwords' => ['string', 'str'=>'string', 'delims='=>'string'],
'udm_add_search_limit' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val'=>'string'],
'udm_alloc_agent' => ['resource', 'dbaddr'=>'string', 'dbmode='=>'string'],
'udm_alloc_agent_array' => ['resource', 'databases'=>'array'],
'udm_api_version' => ['int'],
'udm_cat_list' => ['array', 'agent'=>'resource', 'category'=>'string'],
'udm_cat_path' => ['array', 'agent'=>'resource', 'category'=>'string'],
'udm_check_charset' => ['bool', 'agent'=>'resource', 'charset'=>'string'],
'udm_check_stored' => ['int', 'agent'=>'', 'link'=>'int', 'doc_id'=>'string'],
'udm_clear_search_limits' => ['bool', 'agent'=>'resource'],
'udm_close_stored' => ['int', 'agent'=>'', 'link'=>'int'],
'udm_crc32' => ['int', 'agent'=>'resource', 'str'=>'string'],
'udm_errno' => ['int', 'agent'=>'resource'],
'udm_error' => ['string', 'agent'=>'resource'],
'udm_find' => ['resource', 'agent'=>'resource', 'query'=>'string'],
'udm_free_agent' => ['int', 'agent'=>'resource'],
'udm_free_ispell_data' => ['bool', 'agent'=>'int'],
'udm_free_res' => ['bool', 'res'=>'resource'],
'udm_get_doc_count' => ['int', 'agent'=>'resource'],
'udm_get_res_field' => ['string', 'res'=>'resource', 'row'=>'int', 'field'=>'int'],
'udm_get_res_param' => ['string', 'res'=>'resource', 'param'=>'int'],
'udm_hash32' => ['int', 'agent'=>'resource', 'str'=>'string'],
'udm_load_ispell_data' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val1'=>'string', 'val2'=>'string', 'flag'=>'int'],
'udm_open_stored' => ['int', 'agent'=>'', 'storedaddr'=>'string'],
'udm_set_agent_param' => ['bool', 'agent'=>'resource', 'var'=>'int', 'val'=>'string'],
'ui\area::onDraw' => ['', 'pen'=>'UI\Draw\Pen', 'areaSize'=>'UI\Size', 'clipPoint'=>'UI\Point', 'clipSize'=>'UI\Size'],
'ui\area::onKey' => ['', 'key'=>'string', 'ext'=>'int', 'flags'=>'int'],
'ui\area::onMouse' => ['', 'areaPoint'=>'UI\Point', 'areaSize'=>'UI\Size', 'flags'=>'int'],
'ui\area::redraw' => [''],
'ui\area::scrollTo' => ['', 'point'=>'UI\Point', 'size'=>'UI\Size'],
'ui\area::setSize' => ['', 'size'=>'UI\Size'],
'ui\control::destroy' => [''],
'ui\control::disable' => [''],
'ui\control::enable' => [''],
'ui\control::getParent' => ['UI\Control'],
'ui\control::getTopLevel' => ['int'],
'ui\control::hide' => [''],
'ui\control::isEnabled' => ['bool'],
'ui\control::isVisible' => ['bool'],
'ui\control::setParent' => ['', 'parent'=>'UI\Control'],
'ui\control::show' => [''],
'ui\controls\box::append' => ['int', 'control'=>'Control', 'stretchy='=>'bool'],
'ui\controls\box::delete' => ['bool', 'index'=>'int'],
'ui\controls\box::getOrientation' => ['int'],
'ui\controls\box::isPadded' => ['bool'],
'ui\controls\box::setPadded' => ['', 'padded'=>'bool'],
'ui\controls\button::getText' => ['string'],
'ui\controls\button::onClick' => [''],
'ui\controls\button::setText' => ['', 'text'=>'string'],
'ui\controls\check::getText' => ['string'],
'ui\controls\check::isChecked' => ['bool'],
'ui\controls\check::onToggle' => [''],
'ui\controls\check::setChecked' => ['', 'checked'=>'bool'],
'ui\controls\check::setText' => ['', 'text'=>'string'],
'ui\controls\colorbutton::getColor' => ['UI\Color'],
'ui\controls\colorbutton::onChange' => [''],
'ui\controls\combo::append' => ['', 'text'=>'string'],
'ui\controls\combo::getSelected' => ['int'],
'ui\controls\combo::onSelected' => [''],
'ui\controls\combo::setSelected' => ['', 'index'=>'int'],
'ui\controls\editablecombo::append' => ['', 'text'=>'string'],
'ui\controls\editablecombo::getText' => ['string'],
'ui\controls\editablecombo::onChange' => [''],
'ui\controls\editablecombo::setText' => ['', 'text'=>'string'],
'ui\controls\entry::getText' => ['string'],
'ui\controls\entry::isReadOnly' => ['bool'],
'ui\controls\entry::onChange' => [''],
'ui\controls\entry::setReadOnly' => ['', 'readOnly'=>'bool'],
'ui\controls\entry::setText' => ['', 'text'=>'string'],
'ui\controls\form::append' => ['int', 'label'=>'string', 'control'=>'UI\Control', 'stretchy='=>'bool'],
'ui\controls\form::delete' => ['bool', 'index'=>'int'],
'ui\controls\form::isPadded' => ['bool'],
'ui\controls\form::setPadded' => ['', 'padded'=>'bool'],
'ui\controls\grid::append' => ['', 'control'=>'UI\Control', 'left'=>'int', 'top'=>'int', 'xspan'=>'int', 'yspan'=>'int', 'hexpand'=>'bool', 'halign'=>'int', 'vexpand'=>'bool', 'valign'=>'int'],
'ui\controls\grid::isPadded' => ['bool'],
'ui\controls\grid::setPadded' => ['', 'padding'=>'bool'],
'ui\controls\group::append' => ['', 'control'=>'UI\Control'],
'ui\controls\group::getTitle' => ['string'],
'ui\controls\group::hasMargin' => ['bool'],
'ui\controls\group::setMargin' => ['', 'margin'=>'bool'],
'ui\controls\group::setTitle' => ['', 'title'=>'string'],
'ui\controls\label::getText' => ['string'],
'ui\controls\label::setText' => ['', 'text'=>'string'],
'ui\controls\multilineentry::append' => ['', 'text'=>'string'],
'ui\controls\multilineentry::getText' => ['string'],
'ui\controls\multilineentry::isReadOnly' => ['bool'],
'ui\controls\multilineentry::onChange' => [''],
'ui\controls\multilineentry::setReadOnly' => ['', 'readOnly'=>'bool'],
'ui\controls\multilineentry::setText' => ['', 'text'=>'string'],
'ui\controls\progress::getValue' => ['int'],
'ui\controls\progress::setValue' => ['', 'value'=>'int'],
'ui\controls\radio::append' => ['', 'text'=>'string'],
'ui\controls\radio::getSelected' => ['int'],
'ui\controls\radio::onSelected' => [''],
'ui\controls\radio::setSelected' => ['', 'index'=>'int'],
'ui\controls\slider::getValue' => ['int'],
'ui\controls\slider::onChange' => [''],
'ui\controls\slider::setValue' => ['', 'value'=>'int'],
'ui\controls\spin::getValue' => ['int'],
'ui\controls\spin::onChange' => [''],
'ui\controls\spin::setValue' => ['', 'value'=>'int'],
'ui\controls\tab::append' => ['int', 'name'=>'string', 'control'=>'UI\Control'],
'ui\controls\tab::delete' => ['bool', 'index'=>'int'],
'ui\controls\tab::hasMargin' => ['bool', 'page'=>'int'],
'ui\controls\tab::insertAt' => ['', 'name'=>'string', 'page'=>'int', 'control'=>'UI\Control'],
'ui\controls\tab::pages' => ['int'],
'ui\controls\tab::setMargin' => ['', 'page'=>'int', 'margin'=>'bool'],
'ui\draw\brush::getColor' => ['UI\Draw\Color'],
'ui\draw\brush\gradient::delStop' => ['int', 'index'=>'int'],
'ui\draw\color::getChannel' => ['float', 'channel'=>'int'],
'ui\draw\color::setChannel' => ['void', 'channel'=>'int', 'value'=>'float'],
'ui\draw\matrix::invert' => [''],
'ui\draw\matrix::isInvertible' => ['bool'],
'ui\draw\matrix::multiply' => ['UI\Draw\Matrix', 'matrix'=>'UI\Draw\Matrix'],
'ui\draw\matrix::rotate' => ['', 'point'=>'UI\Point', 'amount'=>'float'],
'ui\draw\matrix::scale' => ['', 'center'=>'UI\Point', 'point'=>'UI\Point'],
'ui\draw\matrix::skew' => ['', 'point'=>'UI\Point', 'amount'=>'UI\Point'],
'ui\draw\matrix::translate' => ['', 'point'=>'UI\Point'],
'ui\draw\path::addRectangle' => ['', 'point'=>'UI\Point', 'size'=>'UI\Size'],
'ui\draw\path::arcTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::bezierTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::closeFigure' => [''],
'ui\draw\path::end' => [''],
'ui\draw\path::lineTo' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\path::newFigure' => ['', 'point'=>'UI\Point'],
'ui\draw\path::newFigureWithArc' => ['', 'point'=>'UI\Point', 'radius'=>'float', 'angle'=>'float', 'sweep'=>'float', 'negative'=>'float'],
'ui\draw\pen::clip' => ['', 'path'=>'UI\Draw\Path'],
'ui\draw\pen::restore' => [''],
'ui\draw\pen::save' => [''],
'ui\draw\pen::transform' => ['', 'matrix'=>'UI\Draw\Matrix'],
'ui\draw\pen::write' => ['', 'point'=>'UI\Point', 'layout'=>'UI\Draw\Text\Layout'],
'ui\draw\stroke::getCap' => ['int'],
'ui\draw\stroke::getJoin' => ['int'],
'ui\draw\stroke::getMiterLimit' => ['float'],
'ui\draw\stroke::getThickness' => ['float'],
'ui\draw\stroke::setCap' => ['', 'cap'=>'int'],
'ui\draw\stroke::setJoin' => ['', 'join'=>'int'],
'ui\draw\stroke::setMiterLimit' => ['', 'limit'=>'float'],
'ui\draw\stroke::setThickness' => ['', 'thickness'=>'float'],
'ui\draw\text\font::getAscent' => ['float'],
'ui\draw\text\font::getDescent' => ['float'],
'ui\draw\text\font::getLeading' => ['float'],
'ui\draw\text\font::getUnderlinePosition' => ['float'],
'ui\draw\text\font::getUnderlineThickness' => ['float'],
'ui\draw\text\font\descriptor::getFamily' => ['string'],
'ui\draw\text\font\descriptor::getItalic' => ['int'],
'ui\draw\text\font\descriptor::getSize' => ['float'],
'ui\draw\text\font\descriptor::getStretch' => ['int'],
'ui\draw\text\font\descriptor::getWeight' => ['int'],
'ui\draw\text\font\fontfamilies' => ['array'],
'ui\draw\text\layout::setWidth' => ['', 'width'=>'float'],
'ui\executor::kill' => ['void'],
'ui\executor::onExecute' => ['void'],
'ui\menu::append' => ['UI\MenuItem', 'name'=>'string', 'type='=>'string'],
'ui\menu::appendAbout' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendCheck' => ['UI\MenuItem', 'name'=>'string', 'type='=>'string'],
'ui\menu::appendPreferences' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendQuit' => ['UI\MenuItem', 'type='=>'string'],
'ui\menu::appendSeparator' => [''],
'ui\menuitem::disable' => [''],
'ui\menuitem::enable' => [''],
'ui\menuitem::isChecked' => ['bool'],
'ui\menuitem::onClick' => [''],
'ui\menuitem::setChecked' => ['', 'checked'=>'bool'],
'ui\point::getX' => ['float'],
'ui\point::getY' => ['float'],
'ui\point::setX' => ['', 'point'=>'float'],
'ui\point::setY' => ['', 'point'=>'float'],
'ui\quit' => ['void'],
'ui\run' => ['void', 'flags='=>'int'],
'ui\size::getHeight' => ['float'],
'ui\size::getWidth' => ['float'],
'ui\size::setHeight' => ['', 'size'=>'float'],
'ui\size::setWidth' => ['', 'size'=>'float'],
'ui\window::add' => ['', 'control'=>'UI\Control'],
'ui\window::error' => ['', 'title'=>'string', 'msg'=>'string'],
'ui\window::getSize' => ['UI\Size'],
'ui\window::getTitle' => ['string'],
'ui\window::hasBorders' => ['bool'],
'ui\window::hasMargin' => ['bool'],
'ui\window::isFullScreen' => ['bool'],
'ui\window::msg' => ['', 'title'=>'string', 'msg'=>'string'],
'ui\window::onClosing' => ['int'],
'ui\window::open' => ['string'],
'ui\window::save' => ['string'],
'ui\window::setBorders' => ['', 'borders'=>'bool'],
'ui\window::setFullScreen' => ['', 'full'=>'bool'],
'ui\window::setMargin' => ['', 'margin'=>'bool'],
'ui\window::setSize' => ['', 'size'=>'UI\Size'],
'ui\window::setTitle' => ['', 'title'=>'string'],
'uksort' => ['bool', '&rw_array_arg'=>'array', 'cmp_function'=>'callable(mixed,mixed):int'],
'umask' => ['int', 'mask='=>'int'],
'UnderflowException::__clone' => ['void'],
'UnderflowException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?UnderflowException'],
'UnderflowException::__toString' => ['string'],
'UnderflowException::getCode' => ['int'],
'UnderflowException::getFile' => ['string'],
'UnderflowException::getLine' => ['int'],
'UnderflowException::getMessage' => ['string'],
'UnderflowException::getPrevious' => ['Throwable|UnderflowException|null'],
'UnderflowException::getTrace' => ['array'],
'UnderflowException::getTraceAsString' => ['string'],
'UnexpectedValueException::__clone' => ['void'],
'UnexpectedValueException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Throwable|?UnexpectedValueException'],
'UnexpectedValueException::__toString' => ['string'],
'UnexpectedValueException::getCode' => ['int'],
'UnexpectedValueException::getFile' => ['string'],
'UnexpectedValueException::getLine' => ['int'],
'UnexpectedValueException::getMessage' => ['string'],
'UnexpectedValueException::getPrevious' => ['Throwable|UnexpectedValueException|null'],
'UnexpectedValueException::getTrace' => ['array'],
'UnexpectedValueException::getTraceAsString' => ['string'],
'uniqid' => ['string', 'prefix='=>'string', 'more_entropy='=>'bool'],
'unixtojd' => ['int', 'timestamp='=>'int'],
'unlink' => ['bool', 'filename'=>'string', 'context='=>'resource'],
'unpack' => ['array|false', 'format'=>'string', 'data'=>'string', 'offset='=>'int'],
'unregister_tick_function' => ['void', 'function_name'=>'callable'],
'unserialize' => ['mixed', 'variable_representation'=>'string', 'allowed_classes='=>'array{allowed_classes?:string[]|bool}'],
'unset' => ['void', 'var='=>'mixed', '...args='=>'mixed'],
'untaint' => ['bool', '&rw_string'=>'string', '&...rw_strings='=>'string'],
'uopz_allow_exit' => ['void', 'allow'=>'bool'],
'uopz_backup' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_backup\'1' => ['void', 'function'=>'string'],
'uopz_compose' => ['void', 'name'=>'string', 'classes'=>'array', 'methods='=>'array', 'properties='=>'array', 'flags='=>'int'],
'uopz_copy' => ['Closure', 'class'=>'string', 'function'=>'string'],
'uopz_copy\'1' => ['Closure', 'function'=>'string'],
'uopz_delete' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_delete\'1' => ['void', 'function'=>'string'],
'uopz_extend' => ['bool', 'class'=>'string', 'parent'=>'string'],
'uopz_flags' => ['int', 'class'=>'string', 'function'=>'string', 'flags'=>'int'],
'uopz_flags\'1' => ['int', 'function'=>'string', 'flags'=>'int'],
'uopz_function' => ['void', 'class'=>'string', 'function'=>'string', 'handler'=>'Closure', 'modifiers='=>'int'],
'uopz_function\'1' => ['void', 'function'=>'string', 'handler'=>'Closure', 'modifiers='=>'int'],
'uopz_get_exit_status' => ['?int'],
'uopz_get_hook' => ['?Closure', 'class'=>'string', 'function'=>'string'],
'uopz_get_hook\'1' => ['?Closure', 'function'=>'string'],
'uopz_get_mock' => ['string|object|null', 'class'=>'string'],
'uopz_get_property' => ['mixed', 'class'=>'object|string', 'property'=>'string'],
'uopz_get_return' => ['mixed', 'class='=>'string', 'function'=>'string'],
'uopz_get_static' => ['?array', 'class'=>'string', 'function'=>'string'],
'uopz_implement' => ['bool', 'class'=>'string', 'interface'=>'string'],
'uopz_overload' => ['void', 'opcode'=>'int', 'callable'=>'Callable'],
'uopz_redefine' => ['bool', 'class'=>'string', 'constant'=>'string', 'value'=>'mixed'],
'uopz_redefine\'1' => ['bool', 'constant'=>'string', 'value'=>'mixed'],
'uopz_rename' => ['void', 'class'=>'string', 'function'=>'string', 'rename'=>'string'],
'uopz_rename\'1' => ['void', 'function'=>'string', 'rename'=>'string'],
'uopz_restore' => ['void', 'class'=>'string', 'function'=>'string'],
'uopz_restore\'1' => ['void', 'function'=>'string'],
'uopz_set_hook' => ['bool', 'class'=>'string', 'function'=>'string', 'hook'=>'Closure'],
'uopz_set_hook\'1' => ['bool', 'function'=>'string', 'hook'=>'Closure'],
'uopz_set_mock' => ['void', 'class'=>'string', 'mock'=>'object|string'],
'uopz_set_property' => ['void', 'class'=>'object|string', 'property'=>'string', 'value'=>'mixed'],
'uopz_set_return' => ['bool', 'class='=>'string', 'function'=>'string', 'value'=>'mixed', 'execute='=>'bool'],
'uopz_set_return\'1' => ['bool', 'function'=>'string', 'value'=>'mixed', 'execute='=>'bool'],
'uopz_set_static' => ['void', 'class'=>'string', 'function'=>'string', 'static'=>'array'],
'uopz_undefine' => ['bool', 'class'=>'string', 'constant'=>'string'],
'uopz_undefine\'1' => ['bool', 'constant'=>'string'],
'uopz_unset_hook' => ['bool', 'class'=>'string', 'function'=>'string'],
'uopz_unset_hook\'1' => ['bool', 'function'=>'string'],
'uopz_unset_mock' => ['void', 'class'=>'string'],
'uopz_unset_return' => ['bool', 'class='=>'string', 'function'=>'string'],
'uopz_unset_return\'1' => ['bool', 'function'=>'string'],
'urldecode' => ['string', 'str'=>'string'],
'urlencode' => ['string', 'str'=>'string'],
'use_soap_error_handler' => ['bool', 'handler='=>'bool'],
'user_error' => ['void', 'message'=>'string', 'error_type='=>'int'],
'usleep' => ['void', 'micro_seconds'=>'int'],
'usort' => ['bool', '&rw_array_arg'=>'array', 'cmp_function'=>'callable(mixed,mixed):int'],
'utf8_decode' => ['string', 'data'=>'string'],
'utf8_encode' => ['string', 'data'=>'string'],
'V8Js::__construct' => ['void', 'object_name='=>'string', 'variables='=>'array', 'extensions='=>'array', 'report_uncaught_exceptions='=>'bool', 'snapshot_blob='=>'string'],
'V8Js::clearPendingException' => [''],
'V8Js::compileString' => ['resource', 'script'=>'', 'identifier='=>'string'],
'V8Js::createSnapshot' => ['false|string', 'embed_source'=>'string'],
'V8Js::executeScript' => ['', 'script'=>'resource', 'flags='=>'int', 'time_limit='=>'int', 'memory_limit='=>'int'],
'V8Js::executeString' => ['mixed', 'script'=>'string', 'identifier='=>'string', 'flags='=>'int'],
'V8Js::getExtensions' => ['string[]'],
'V8Js::getPendingException' => ['?V8JsException'],
'V8Js::registerExtension' => ['bool', 'extension_name'=>'string', 'script'=>'string', 'dependencies='=>'array', 'auto_enable='=>'bool'],
'V8Js::setAverageObjectSize' => ['', 'average_object_size'=>'int'],
'V8Js::setMemoryLimit' => ['', 'limit'=>'int'],
'V8Js::setModuleLoader' => ['', 'loader'=>'callable'],
'V8Js::setModuleNormaliser' => ['', 'normaliser'=>'callable'],
'V8Js::setTimeLimit' => ['', 'limit'=>'int'],
'V8JsException::getJsFileName' => ['string'],
'V8JsException::getJsLineNumber' => ['int'],
'V8JsException::getJsSourceLine' => ['int'],
'V8JsException::getJsTrace' => ['string'],
'V8JsScriptException::__clone' => ['void'],
'V8JsScriptException::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'V8JsScriptException::__toString' => ['string'],
'V8JsScriptException::__wakeup' => ['void'],
'V8JsScriptException::getCode' => ['int'],
'V8JsScriptException::getFile' => ['string'],
'V8JsScriptException::getJsEndColumn' => ['int'],
'V8JsScriptException::getJsFileName' => ['string'],
'V8JsScriptException::getJsLineNumber' => ['int'],
'V8JsScriptException::getJsSourceLine' => ['string'],
'V8JsScriptException::getJsStartColumn' => ['int'],
'V8JsScriptException::getJsTrace' => ['string'],
'V8JsScriptException::getLine' => ['int'],
'V8JsScriptException::getMessage' => ['string'],
'V8JsScriptException::getPrevious' => ['Exception|Throwable'],
'V8JsScriptException::getTrace' => ['array'],
'V8JsScriptException::getTraceAsString' => ['string'],
'var_dump' => ['void', 'var'=>'mixed', '...args='=>'mixed'],
'var_export' => ['?string', 'var'=>'mixed', 'return='=>'bool'],
'VARIANT::__construct' => ['void', 'value='=>'mixed', 'type='=>'int', 'codepage='=>'int'],
'variant_abs' => ['mixed', 'left'=>'mixed'],
'variant_add' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_and' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_cast' => ['VARIANT', 'variant'=>'VARIANT', 'type'=>'int'],
'variant_cat' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_cmp' => ['int', 'left'=>'mixed', 'right'=>'mixed', 'lcid='=>'int', 'flags='=>'int'],
'variant_date_from_timestamp' => ['VARIANT', 'timestamp'=>'int'],
'variant_date_to_timestamp' => ['int', 'variant'=>'VARIANT'],
'variant_div' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_eqv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_fix' => ['mixed', 'left'=>'mixed'],
'variant_get_type' => ['int', 'variant'=>'VARIANT'],
'variant_idiv' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_imp' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_int' => ['mixed', 'left'=>'mixed'],
'variant_mod' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_mul' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_neg' => ['mixed', 'left'=>'mixed'],
'variant_not' => ['mixed', 'left'=>'mixed'],
'variant_or' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_pow' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_round' => ['mixed', 'left'=>'mixed', 'decimals'=>'int'],
'variant_set' => ['void', 'variant'=>'object', 'value'=>'mixed'],
'variant_set_type' => ['void', 'variant'=>'object', 'type'=>'int'],
'variant_sub' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'variant_xor' => ['mixed', 'left'=>'mixed', 'right'=>'mixed'],
'VarnishAdmin::__construct' => ['void', 'args='=>'array'],
'VarnishAdmin::auth' => ['bool'],
'VarnishAdmin::ban' => ['int', 'vcl_regex'=>'string'],
'VarnishAdmin::banUrl' => ['int', 'vcl_regex'=>'string'],
'VarnishAdmin::clearPanic' => ['int'],
'VarnishAdmin::connect' => ['bool'],
'VarnishAdmin::disconnect' => ['bool'],
'VarnishAdmin::getPanic' => ['string'],
'VarnishAdmin::getParams' => ['array'],
'VarnishAdmin::isRunning' => ['bool'],
'VarnishAdmin::setCompat' => ['void', 'compat'=>'int'],
'VarnishAdmin::setHost' => ['void', 'host'=>'string'],
'VarnishAdmin::setIdent' => ['void', 'ident'=>'string'],
'VarnishAdmin::setParam' => ['int', 'name'=>'string', 'value'=>'string|int'],
'VarnishAdmin::setPort' => ['void', 'port'=>'int'],
'VarnishAdmin::setSecret' => ['void', 'secret'=>'string'],
'VarnishAdmin::setTimeout' => ['void', 'timeout'=>'int'],
'VarnishAdmin::start' => ['int'],
'VarnishAdmin::stop' => ['int'],
'VarnishLog::__construct' => ['void', 'args='=>'array'],
'VarnishLog::getLine' => ['array'],
'VarnishLog::getTagName' => ['string', 'index'=>'int'],
'VarnishStat::__construct' => ['void', 'args='=>'array'],
'VarnishStat::getSnapshot' => ['array'],
'version_compare' => ['bool', 'ver1'=>'string', 'ver2'=>'string', 'oper'=>'\'\x3c\'|\'lt\'|\'\x3c=\'|\'le\'|\'\x3e\'|\'gt\'|\'\x3e=\'|\'ge\'|\'==\'|\'=\'|\'eq\'|\'!=\'|\'\x3c\x3e\'|\'ne\''],
'version_compare\'1' => ['int', 'ver1'=>'string', 'ver2'=>'string', 'oper='=>''],
'vfprintf' => ['int', 'stream'=>'resource', 'format'=>'string', 'args'=>'array'],
'virtual' => ['bool', 'uri'=>'string'],
'vpopmail_add_alias_domain' => ['bool', 'domain'=>'string', 'aliasdomain'=>'string'],
'vpopmail_add_alias_domain_ex' => ['bool', 'olddomain'=>'string', 'newdomain'=>'string'],
'vpopmail_add_domain' => ['bool', 'domain'=>'string', 'dir'=>'string', 'uid'=>'int', 'gid'=>'int'],
'vpopmail_add_domain_ex' => ['bool', 'domain'=>'string', 'passwd'=>'string', 'quota='=>'string', 'bounce='=>'string', 'apop='=>'bool'],
'vpopmail_add_user' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'gecos='=>'string', 'apop='=>'bool'],
'vpopmail_alias_add' => ['bool', 'user'=>'string', 'domain'=>'string', 'alias'=>'string'],
'vpopmail_alias_del' => ['bool', 'user'=>'string', 'domain'=>'string'],
'vpopmail_alias_del_domain' => ['bool', 'domain'=>'string'],
'vpopmail_alias_get' => ['array', 'alias'=>'string', 'domain'=>'string'],
'vpopmail_alias_get_all' => ['array', 'domain'=>'string'],
'vpopmail_auth_user' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'apop='=>'string'],
'vpopmail_del_domain' => ['bool', 'domain'=>'string'],
'vpopmail_del_domain_ex' => ['bool', 'domain'=>'string'],
'vpopmail_del_user' => ['bool', 'user'=>'string', 'domain'=>'string'],
'vpopmail_error' => ['string'],
'vpopmail_passwd' => ['bool', 'user'=>'string', 'domain'=>'string', 'password'=>'string', 'apop='=>'bool'],
'vpopmail_set_user_quota' => ['bool', 'user'=>'string', 'domain'=>'string', 'quota'=>'string'],
'vprintf' => ['int', 'format'=>'string', 'args'=>'array'],
'vsprintf' => ['string', 'format'=>'string', 'args'=>'array'],
'Vtiful\Kernel\Excel::__construct' => ['void', 'config'=>'array'],
'Vtiful\Kernel\Excel::addSheet' => ['', 'sheetName'=>'string'],
'Vtiful\Kernel\Excel::autoFilter' => ['', 'scope'=>'string'],
'Vtiful\Kernel\Excel::constMemory' => ['', 'fileName'=>'string', 'sheetName='=>'string'],
'Vtiful\Kernel\Excel::data' => ['', 'data'=>'array'],
'Vtiful\Kernel\Excel::fileName' => ['', 'fileName'=>'string', 'sheetName='=>'string'],
'Vtiful\Kernel\Excel::getHandle' => [''],
'Vtiful\Kernel\Excel::header' => ['', 'headerData'=>'array'],
'Vtiful\Kernel\Excel::insertFormula' => ['', 'row'=>'int', 'column'=>'int', 'formula'=>'string'],
'Vtiful\Kernel\Excel::insertImage' => ['', 'row'=>'int', 'column'=>'int', 'localImagePath'=>'string'],
'Vtiful\Kernel\Excel::insertText' => ['', 'row'=>'int', 'column'=>'int', 'data'=>'string', 'format='=>'string'],
'Vtiful\Kernel\Excel::mergeCells' => ['', 'scope'=>'string', 'data'=>'string'],
'Vtiful\Kernel\Excel::output' => [''],
'Vtiful\Kernel\Excel::setColumn' => ['', 'range'=>'string', 'width'=>'float', 'format='=>'resource'],
'Vtiful\Kernel\Excel::setRow' => ['', 'range'=>'string', 'height'=>'float', 'format='=>'resource'],
'Vtiful\Kernel\Format::align' => ['', 'handle'=>'resource', 'style'=>'int'],
'Vtiful\Kernel\Format::bold' => ['', 'handle'=>'resource'],
'Vtiful\Kernel\Format::italic' => ['', 'handle'=>'resource'],
'Vtiful\Kernel\Format::underline' => ['', 'handle'=>'resource', 'style'=>'int'],
'w32api_deftype' => ['bool', 'typename'=>'string', 'member1_type'=>'string', 'member1_name'=>'string', '...args='=>'string'],
'w32api_init_dtype' => ['resource', 'typename'=>'string', 'value'=>'', '...args='=>''],
'w32api_invoke_function' => ['', 'funcname'=>'string', 'argument'=>'', '...args='=>''],
'w32api_register_function' => ['bool', 'library'=>'string', 'function_name'=>'string', 'return_type'=>'string'],
'w32api_set_call_method' => ['', 'method'=>'int'],
'wddx_add_vars' => ['bool', 'packet_id'=>'resource', 'var_names'=>'mixed', '...vars='=>'mixed'],
'wddx_deserialize' => ['mixed', 'packet'=>'string'],
'wddx_packet_end' => ['string', 'packet_id'=>'resource'],
'wddx_packet_start' => ['resource|false', 'comment='=>'string'],
'wddx_serialize_value' => ['string|false', 'var'=>'mixed', 'comment='=>'string'],
'wddx_serialize_vars' => ['string|false', 'var_name'=>'mixed', '...vars='=>'mixed'],
'WeakMap::__construct' => ['void'],
'WeakMap::count' => ['int'],
'WeakMap::current' => ['mixed'],
'WeakMap::key' => ['object'],
'WeakMap::next' => ['void'],
'WeakMap::offsetExists' => ['bool', 'object'=>'object'],
'WeakMap::offsetGet' => ['mixed', 'object'=>'object'],
'WeakMap::offsetSet' => ['void', 'object'=>'object', 'value'=>'mixed'],
'WeakMap::offsetUnset' => ['void', 'object'=>'object'],
'WeakMap::rewind' => ['void'],
'WeakMap::valid' => ['bool'],
'Weakref::acquire' => ['bool'],
'Weakref::get' => ['object'],
'Weakref::release' => ['bool'],
'Weakref::valid' => ['bool'],
'webObj::convertToString' => ['string'],
'webObj::free' => ['void'],
'webObj::set' => ['int', 'property_name'=>'string', 'new_value'=>''],
'webObj::updateFromString' => ['int', 'snippet'=>'string'],
'win32_continue_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_create_service' => ['int|false', 'details'=>'array', 'machine='=>'string'],
'win32_delete_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_get_last_control_message' => ['int'],
'win32_pause_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_ps_list_procs' => ['array'],
'win32_ps_stat_mem' => ['array'],
'win32_ps_stat_proc' => ['array', 'pid='=>'int'],
'win32_query_service_status' => ['array|false|int', 'servicename'=>'string', 'machine='=>'string'],
'win32_send_custom_control' => ['int', 'servicename'=>'string', 'control'=>'int', 'machine='=>'string'],
'win32_set_service_exit_code' => ['int', 'exitCode='=>'int'],
'win32_set_service_exit_mode' => ['bool', 'gracefulMode='=>'bool'],
'win32_set_service_status' => ['bool|int', 'status'=>'int', 'checkpoint='=>'int'],
'win32_start_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'win32_start_service_ctrl_dispatcher' => ['bool|int', 'name'=>'string'],
'win32_stop_service' => ['int|false', 'servicename'=>'string', 'machine='=>'string'],
'wincache_fcache_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_fcache_meminfo' => ['array|false'],
'wincache_lock' => ['bool', 'key'=>'string', 'isglobal='=>'bool'],
'wincache_ocache_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_ocache_meminfo' => ['array|false'],
'wincache_refresh_if_changed' => ['bool', 'files='=>'array'],
'wincache_rplist_fileinfo' => ['array|false', 'summaryonly='=>'bool'],
'wincache_rplist_meminfo' => ['array|false'],
'wincache_scache_info' => ['array|false', 'summaryonly='=>'bool'],
'wincache_scache_meminfo' => ['array|false'],
'wincache_ucache_add' => ['bool', 'key'=>'string', 'value'=>'mixed', 'ttl='=>'int'],
'wincache_ucache_add\'1' => ['bool', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'wincache_ucache_cas' => ['bool', 'key'=>'string', 'old_value'=>'int', 'new_value'=>'int'],
'wincache_ucache_clear' => ['bool'],
'wincache_ucache_dec' => ['int|false', 'key'=>'string', 'dec_by='=>'int', 'success='=>'bool'],
'wincache_ucache_delete' => ['bool', 'key'=>'mixed'],
'wincache_ucache_exists' => ['bool', 'key'=>'string'],
'wincache_ucache_get' => ['mixed', 'key'=>'mixed', '&w_success='=>'bool'],
'wincache_ucache_inc' => ['int|false', 'key'=>'string', 'inc_by='=>'int', 'success='=>'bool'],
'wincache_ucache_info' => ['array|false', 'summaryonly='=>'bool', 'key='=>'string'],
'wincache_ucache_meminfo' => ['array|false'],
'wincache_ucache_set' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int'],
'wincache_ucache_set\'1' => ['bool', 'values'=>'array', 'unused='=>'', 'ttl='=>'int'],
'wincache_unlock' => ['bool', 'key'=>'string'],
'wkhtmltox\image\converter::convert' => ['?string'],
'wkhtmltox\image\converter::getVersion' => ['string'],
'wkhtmltox\pdf\converter::add' => ['void', 'object'=>'wkhtmltox\PDF\Object'],
'wkhtmltox\pdf\converter::convert' => ['?string'],
'wkhtmltox\pdf\converter::getVersion' => ['string'],
'wordwrap' => ['string', 'str'=>'string', 'width='=>'int', 'break='=>'string', 'cut='=>'bool'],
'Worker::__construct' => ['void'],
'Worker::addRef' => ['void'],
'Worker::chunk' => ['array', 'size'=>'int', 'preserve'=>'bool'],
'Worker::collect' => ['int', 'collector='=>'Callable'],
'Worker::count' => ['int'],
'Worker::delRef' => ['void'],
'Worker::detach' => ['void'],
'Worker::extend' => ['bool', 'class'=>'string'],
'Worker::getCreatorId' => ['int'],
'Worker::getCurrentThread' => ['Thread'],
'Worker::getCurrentThreadId' => ['int'],
'Worker::getRefCount' => ['int'],
'Worker::getStacked' => ['int'],
'Worker::getTerminationInfo' => ['array'],
'Worker::getThreadId' => ['int'],
'Worker::globally' => ['mixed'],
'Worker::isGarbage' => ['bool'],
'Worker::isJoined' => ['bool'],
'Worker::isRunning' => ['bool'],
'Worker::isShutdown' => ['bool'],
'Worker::isStarted' => ['bool'],
'Worker::isTerminated' => ['bool'],
'Worker::isWaiting' => ['bool'],
'Worker::isWorking' => ['bool'],
'Worker::join' => ['bool'],
'Worker::kill' => ['bool'],
'Worker::lock' => ['bool'],
'Worker::merge' => ['bool', 'from'=>'', 'overwrite='=>'mixed'],
'Worker::notify' => ['bool'],
'Worker::notifyOne' => ['bool'],
'Worker::offsetExists' => ['bool', 'offset'=>'mixed'],
'Worker::offsetGet' => ['mixed', 'offset'=>'mixed'],
'Worker::offsetSet' => ['void', 'offset'=>'mixed', 'value'=>'mixed'],
'Worker::offsetUnset' => ['void', 'offset'=>'mixed'],
'Worker::pop' => ['bool'],
'Worker::run' => ['void'],
'Worker::setGarbage' => ['void'],
'Worker::shift' => ['bool'],
'Worker::shutdown' => ['bool'],
'Worker::stack' => ['int', '&rw_work'=>'Threaded'],
'Worker::start' => ['bool', 'options='=>'int'],
'Worker::synchronized' => ['mixed', 'block'=>'Closure', '_='=>'mixed'],
'Worker::unlock' => ['bool'],
'Worker::unstack' => ['int', '&rw_work='=>'Threaded'],
'Worker::wait' => ['bool', 'timeout='=>'int'],
'xattr_get' => ['string', 'filename'=>'string', 'name'=>'string', 'flags='=>'int'],
'xattr_list' => ['array', 'filename'=>'string', 'flags='=>'int'],
'xattr_remove' => ['bool', 'filename'=>'string', 'name'=>'string', 'flags='=>'int'],
'xattr_set' => ['bool', 'filename'=>'string', 'name'=>'string', 'value'=>'string', 'flags='=>'int'],
'xattr_supported' => ['bool', 'filename'=>'string', 'flags='=>'int'],
'xcache_asm' => ['string', 'filename'=>'string'],
'xcache_clear_cache' => ['void', 'type'=>'int', 'id='=>'int'],
'xcache_coredump' => ['string', 'op_type'=>'int'],
'xcache_count' => ['int', 'type'=>'int'],
'xcache_coverager_decode' => ['array', 'data'=>'string'],
'xcache_coverager_get' => ['array', 'clean='=>'bool'],
'xcache_coverager_start' => ['void', 'clean='=>'bool'],
'xcache_coverager_stop' => ['void', 'clean='=>'bool'],
'xcache_dasm_file' => ['string', 'filename'=>'string'],
'xcache_dasm_string' => ['string', 'code'=>'string'],
'xcache_dec' => ['int', 'name'=>'string', 'value='=>'int|mixed', 'ttl='=>'int'],
'xcache_decode' => ['bool', 'filename'=>'string'],
'xcache_encode' => ['string', 'filename'=>'string'],
'xcache_get' => ['mixed', 'name'=>'string'],
'xcache_get_data_type' => ['string', 'type'=>'int'],
'xcache_get_op_spec' => ['string', 'op_type'=>'int'],
'xcache_get_op_type' => ['string', 'op_type'=>'int'],
'xcache_get_opcode' => ['string', 'opcode'=>'int'],
'xcache_get_opcode_spec' => ['string', 'opcode'=>'int'],
'xcache_inc' => ['int', 'name'=>'string', 'value='=>'int|mixed', 'ttl='=>'int'],
'xcache_info' => ['array', 'type'=>'int', 'id'=>'int'],
'xcache_is_autoglobal' => ['string', 'name'=>'string'],
'xcache_isset' => ['bool', 'name'=>'string'],
'xcache_list' => ['array', 'type'=>'int', 'id'=>'int'],
'xcache_set' => ['bool', 'name'=>'string', 'value'=>'mixed', 'ttl='=>'int'],
'xcache_unset' => ['bool', 'name'=>'string'],
'xcache_unset_by_prefix' => ['bool', 'prefix'=>'string'],
'Xcom::__construct' => ['void', 'fabric_url='=>'string', 'fabric_token='=>'string', 'capability_token='=>'string'],
'Xcom::decode' => ['object', 'avro_msg'=>'string', 'json_schema'=>'string'],
'Xcom::encode' => ['string', 'data'=>'stdClass', 'avro_schema'=>'string'],
'Xcom::getDebugOutput' => ['string'],
'Xcom::getLastResponse' => ['string'],
'Xcom::getLastResponseInfo' => ['array'],
'Xcom::getOnboardingURL' => ['string', 'capability_name'=>'string', 'agreement_url'=>'string'],
'Xcom::send' => ['int', 'topic'=>'string', 'data'=>'mixed', 'json_schema='=>'string', 'http_headers='=>'array'],
'Xcom::sendAsync' => ['int', 'topic'=>'string', 'data'=>'mixed', 'json_schema='=>'string', 'http_headers='=>'array'],
'xdebug_break' => ['bool'],
'xdebug_call_class' => ['string', 'depth='=>'int'],
'xdebug_call_file' => ['string', 'depth='=>'int'],
'xdebug_call_function' => ['string', 'depth='=>'int'],
'xdebug_call_line' => ['int', 'depth='=>'int'],
'xdebug_clear_aggr_profiling_data' => ['bool'],
'xdebug_code_coverage_started' => ['bool'],
'xdebug_debug_zval' => ['void', '...varName'=>'string'],
'xdebug_debug_zval_stdout' => ['void', '...varName'=>'string'],
'xdebug_disable' => ['void'],
'xdebug_dump_aggr_profiling_data' => ['bool'],
'xdebug_dump_superglobals' => ['void'],
'xdebug_enable' => ['void'],
'xdebug_get_code_coverage' => ['array'],
'xdebug_get_collected_errors' => ['string', 'clean='=>'bool'],
'xdebug_get_declared_vars' => ['array'],
'xdebug_get_formatted_function_stack' => [''],
'xdebug_get_function_count' => ['int'],
'xdebug_get_function_stack' => ['array', 'message='=>'string', 'options='=>'int'],
'xdebug_get_headers' => ['array'],
'xdebug_get_monitored_functions' => ['array'],
'xdebug_get_profiler_filename' => ['string'],
'xdebug_get_stack_depth' => ['int'],
'xdebug_get_tracefile_name' => ['string'],
'xdebug_is_debugger_active' => ['bool'],
'xdebug_is_enabled' => ['bool'],
'xdebug_memory_usage' => ['int'],
'xdebug_peak_memory_usage' => ['int'],
'xdebug_print_function_stack' => ['array', 'message='=>'string', 'options='=>'int'],
'xdebug_set_filter' => ['void', 'group'=>'int', 'list_type'=>'int', 'configuration'=>'array'],
'xdebug_start_code_coverage' => ['void', 'options='=>'int'],
'xdebug_start_error_collection' => ['void'],
'xdebug_start_function_monitor' => ['void', 'list_of_functions_to_monitor'=>'string[]'],
'xdebug_start_trace' => ['void', 'trace_file'=>'', 'options='=>'int|mixed'],
'xdebug_stop_code_coverage' => ['void', 'cleanup='=>'bool'],
'xdebug_stop_error_collection' => ['void'],
'xdebug_stop_function_monitor' => ['void'],
'xdebug_stop_trace' => ['void'],
'xdebug_time_index' => ['float'],
'xdebug_var_dump' => ['void', '...var'=>''],
'xdiff_file_bdiff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_file_bdiff_size' => ['int', 'file'=>'string'],
'xdiff_file_bpatch' => ['bool', 'file'=>'string', 'patch'=>'string', 'dest'=>'string'],
'xdiff_file_diff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string', 'context='=>'int', 'minimal='=>'bool'],
'xdiff_file_diff_binary' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_file_merge3' => ['mixed', 'old_file'=>'string', 'new_file1'=>'string', 'new_file2'=>'string', 'dest'=>'string'],
'xdiff_file_patch' => ['mixed', 'file'=>'string', 'patch'=>'string', 'dest'=>'string', 'flags='=>'int'],
'xdiff_file_patch_binary' => ['bool', 'file'=>'string', 'patch'=>'string', 'dest'=>'string'],
'xdiff_file_rabdiff' => ['bool', 'old_file'=>'string', 'new_file'=>'string', 'dest'=>'string'],
'xdiff_string_bdiff' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xdiff_string_bdiff_size' => ['int', 'patch'=>'string'],
'xdiff_string_bpatch' => ['string', 'str'=>'string', 'patch'=>'string'],
'xdiff_string_diff' => ['string', 'old_data'=>'string', 'new_data'=>'string', 'context='=>'int', 'minimal='=>'bool'],
'xdiff_string_diff_binary' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xdiff_string_merge3' => ['mixed', 'old_data'=>'string', 'new_data1'=>'string', 'new_data2'=>'string', 'error='=>'string'],
'xdiff_string_patch' => ['string', 'str'=>'string', 'patch'=>'string', 'flags='=>'int', '&w_error='=>'string'],
'xdiff_string_patch_binary' => ['string', 'str'=>'string', 'patch'=>'string'],
'xdiff_string_rabdiff' => ['string', 'old_data'=>'string', 'new_data'=>'string'],
'xhprof_disable' => ['array'],
'xhprof_enable' => ['void', 'flags='=>'int', 'options='=>'array'],
'xhprof_sample_disable' => ['array'],
'xhprof_sample_enable' => ['void'],
'xml_error_string' => ['string', 'code'=>'int'],
'xml_get_current_byte_index' => ['int|false', 'parser'=>'resource'],
'xml_get_current_column_number' => ['int|false', 'parser'=>'resource'],
'xml_get_current_line_number' => ['int|false', 'parser'=>'resource'],
'xml_get_error_code' => ['int|false', 'parser'=>'resource'],
'xml_parse' => ['int', 'parser'=>'resource', 'data'=>'string', 'isfinal='=>'bool'],
'xml_parse_into_struct' => ['int', 'parser'=>'resource', 'data'=>'string', '&w_values'=>'array', '&w_index='=>'array'],
'xml_parser_create' => ['resource', 'encoding='=>'string'],
'xml_parser_create_ns' => ['resource', 'encoding='=>'string', 'sep='=>'string'],
'xml_parser_free' => ['bool', 'parser'=>'resource'],
'xml_parser_get_option' => ['mixed|false', 'parser'=>'resource', 'option'=>'int'],
'xml_parser_set_option' => ['bool', 'parser'=>'resource', 'option'=>'int', 'value'=>'mixed'],
'xml_set_character_data_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_default_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_element_handler' => ['bool', 'parser'=>'resource', 'shdl'=>'callable', 'ehdl'=>'callable'],
'xml_set_end_namespace_decl_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_external_entity_ref_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_notation_decl_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_object' => ['bool', 'parser'=>'resource', 'obj'=>'object'],
'xml_set_processing_instruction_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_start_namespace_decl_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'xml_set_unparsed_entity_decl_handler' => ['bool', 'parser'=>'resource', 'hdl'=>'callable'],
'XMLDiff\Base::__construct' => ['void', 'nsname'=>'string'],
'XMLDiff\Base::diff' => ['mixed', 'from'=>'mixed', 'to'=>'mixed'],
'XMLDiff\Base::merge' => ['mixed', 'src'=>'mixed', 'diff'=>'mixed'],
'XMLDiff\DOM::diff' => ['DOMDocument', 'from'=>'DOMDocument', 'to'=>'DOMDocument'],
'XMLDiff\DOM::merge' => ['DOMDocument', 'src'=>'DOMDocument', 'diff'=>'DOMDocument'],
'XMLDiff\File::diff' => ['string', 'from'=>'string', 'to'=>'string'],
'XMLDiff\File::merge' => ['string', 'src'=>'string', 'diff'=>'string'],
'XMLDiff\Memory::diff' => ['string', 'from'=>'string', 'to'=>'string'],
'XMLDiff\Memory::merge' => ['string', 'src'=>'string', 'diff'=>'string'],
'XMLReader::close' => ['bool'],
'XMLReader::expand' => ['DOMNode|false', 'basenode='=>'DOMNode'],
'XMLReader::getAttribute' => ['?string', 'name'=>'string'],
'XMLReader::getAttributeNo' => ['?string', 'index'=>'int'],
'XMLReader::getAttributeNs' => ['?string', 'name'=>'string', 'namespaceuri'=>'string'],
'XMLReader::getParserProperty' => ['bool', 'property'=>'int'],
'XMLReader::isValid' => ['bool'],
'XMLReader::lookupNamespace' => ['?string', 'prefix'=>'string'],
'XMLReader::moveToAttribute' => ['bool', 'name'=>'string'],
'XMLReader::moveToAttributeNo' => ['bool', 'index'=>'int'],
'XMLReader::moveToAttributeNs' => ['bool', 'localname'=>'string', 'namespaceuri'=>'string'],
'XMLReader::moveToElement' => ['bool'],
'XMLReader::moveToFirstAttribute' => ['bool'],
'XMLReader::moveToNextAttribute' => ['bool'],
'XMLReader::next' => ['bool', 'localname='=>'string'],
'XMLReader::open' => ['bool', 'uri'=>'string', 'encoding='=>'?string', 'options='=>'int'],
'XMLReader::read' => ['bool'],
'XMLReader::readInnerXML' => ['string'],
'XMLReader::readOuterXML' => ['string'],
'XMLReader::readString' => ['string'],
'XMLReader::setParserProperty' => ['bool', 'property'=>'int', 'value'=>'bool'],
'XMLReader::setRelaxNGSchema' => ['bool', 'filename'=>'string'],
'XMLReader::setRelaxNGSchemaSource' => ['bool', 'source'=>'string'],
'XMLReader::setSchema' => ['bool', 'filename'=>'string'],
'XMLReader::XML' => ['bool', 'source'=>'string', 'encoding='=>'?string', 'options='=>'int'],
'xmlrpc_decode' => ['mixed', 'xml'=>'string', 'encoding='=>'string'],
'xmlrpc_decode_request' => ['?array', 'xml'=>'string', '&w_method'=>'string', 'encoding='=>'string'],
'xmlrpc_encode' => ['string', 'value'=>'mixed'],
'xmlrpc_encode_request' => ['string', 'method'=>'string', 'params'=>'mixed', 'output_options='=>'array'],
'xmlrpc_get_type' => ['string', 'value'=>'mixed'],
'xmlrpc_is_fault' => ['bool', 'arg'=>'array'],
'xmlrpc_parse_method_descriptions' => ['array', 'xml'=>'string'],
'xmlrpc_server_add_introspection_data' => ['int', 'server'=>'resource', 'desc'=>'array'],
'xmlrpc_server_call_method' => ['string', 'server'=>'resource', 'xml'=>'string', 'user_data'=>'mixed', 'output_options='=>'array'],
'xmlrpc_server_create' => ['resource'],
'xmlrpc_server_destroy' => ['int', 'server'=>'resource'],
'xmlrpc_server_register_introspection_callback' => ['bool', 'server'=>'resource', 'function'=>'string'],
'xmlrpc_server_register_method' => ['bool', 'server'=>'resource', 'method_name'=>'string', 'function'=>'string'],
'xmlrpc_set_type' => ['bool', '&rw_value'=>'string|DateTime', 'type'=>'string'],
'XMLWriter::endAttribute' => ['bool'],
'XMLWriter::endCData' => ['bool'],
'XMLWriter::endComment' => ['bool'],
'XMLWriter::endDocument' => ['bool'],
'XMLWriter::endDTD' => ['bool', 'xmlwriter='=>''],
'XMLWriter::endDTDAttlist' => ['bool'],
'XMLWriter::endDTDElement' => ['bool'],
'XMLWriter::endDTDEntity' => ['bool'],
'XMLWriter::endElement' => ['bool'],
'XMLWriter::endPI' => ['bool'],
'XMLWriter::flush' => ['', 'empty='=>'bool', 'xmlwriter='=>''],
'XMLWriter::fullEndElement' => ['bool'],
'XMLWriter::openMemory' => ['bool'],
'XMLWriter::openURI' => ['bool', 'uri'=>'string'],
'XMLWriter::outputMemory' => ['string', 'flush='=>'bool', 'xmlwriter='=>''],
'XMLWriter::setIndent' => ['bool', 'indent'=>'bool'],
'XMLWriter::setIndentString' => ['bool', 'indentstring'=>'string'],
'XMLWriter::startAttribute' => ['bool', 'name'=>'string'],
'XMLWriter::startAttributeNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string'],
'XMLWriter::startCData' => ['bool'],
'XMLWriter::startComment' => ['bool'],
'XMLWriter::startDocument' => ['bool', 'version='=>'string', 'encoding='=>'string', 'standalone='=>'string'],
'XMLWriter::startDTD' => ['bool', 'qualifiedname'=>'string', 'publicid='=>'string', 'systemid='=>'string'],
'XMLWriter::startDTDAttlist' => ['bool', 'name'=>'string'],
'XMLWriter::startDTDElement' => ['bool', 'qualifiedname'=>'string'],
'XMLWriter::startDTDEntity' => ['bool', 'name'=>'string', 'isparam'=>'bool'],
'XMLWriter::startElement' => ['bool', 'name'=>'string'],
'XMLWriter::startElementNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string'],
'XMLWriter::startPI' => ['bool', 'target'=>'string'],
'XMLWriter::text' => ['bool', 'content'=>'string'],
'XMLWriter::writeAttribute' => ['bool', 'name'=>'string', 'value'=>'string'],
'XMLWriter::writeAttributeNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string', 'content'=>'string'],
'XMLWriter::writeCData' => ['bool', 'content'=>'string'],
'XMLWriter::writeComment' => ['bool', 'content'=>'string'],
'XMLWriter::writeDTD' => ['bool', 'name'=>'string', 'publicid='=>'string', 'systemid='=>'string', 'subset='=>'string'],
'XMLWriter::writeDTDAttlist' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDTDElement' => ['bool', 'name'=>'string', 'content'=>'string'],
'XMLWriter::writeDTDEntity' => ['bool', 'name'=>'string', 'content'=>'string', 'pe'=>'bool', 'pubid'=>'string', 'sysid'=>'string', 'ndataid'=>'string'],
'XMLWriter::writeElement' => ['bool', 'name'=>'string', 'content='=>'?string'],
'XMLWriter::writeElementNS' => ['bool', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string', 'content='=>'?string'],
'XMLWriter::writePI' => ['bool', 'target'=>'string', 'content'=>'string'],
'XMLWriter::writeRaw' => ['bool', 'content'=>'string'],
'xmlwriter_end_attribute' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_cdata' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_comment' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_document' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_dtd' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_dtd_attlist' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_dtd_element' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_dtd_entity' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_element' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_end_pi' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_flush' => ['mixed', 'xmlwriter'=>'resource', 'empty='=>'bool'],
'xmlwriter_full_end_element' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_open_memory' => ['resource'],
'xmlwriter_open_uri' => ['resource', 'source'=>'string'],
'xmlwriter_output_memory' => ['string', 'xmlwriter'=>'resource', 'flush='=>'bool'],
'xmlwriter_set_indent' => ['bool', 'xmlwriter'=>'resource', 'indent'=>'bool'],
'xmlwriter_set_indent_string' => ['bool', 'xmlwriter'=>'resource', 'indentstring'=>'string'],
'xmlwriter_start_attribute' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string'],
'xmlwriter_start_attribute_ns' => ['bool', 'xmlwriter'=>'resource', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string'],
'xmlwriter_start_cdata' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_start_comment' => ['bool', 'xmlwriter'=>'resource'],
'xmlwriter_start_document' => ['bool', 'xmlwriter'=>'resource', 'version='=>'string', 'encoding='=>'string', 'standalone='=>'string'],
'xmlwriter_start_dtd' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'pubid='=>'string', 'sysid='=>'string'],
'xmlwriter_start_dtd_attlist' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string'],
'xmlwriter_start_dtd_element' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string'],
'xmlwriter_start_dtd_entity' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'isparam'=>'bool'],
'xmlwriter_start_element' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string'],
'xmlwriter_start_element_ns' => ['bool', 'xmlwriter'=>'resource', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string'],
'xmlwriter_start_pi' => ['bool', 'xmlwriter'=>'resource', 'target'=>'string'],
'xmlwriter_text' => ['bool', 'xmlwriter'=>'resource', 'content'=>'string'],
'xmlwriter_write_attribute' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_attribute_ns' => ['bool', 'xmlwriter'=>'resource', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string', 'content'=>'string'],
'xmlwriter_write_cdata' => ['bool', 'xmlwriter'=>'resource', 'content'=>'string'],
'xmlwriter_write_comment' => ['bool', 'xmlwriter'=>'resource', 'content'=>'string'],
'xmlwriter_write_dtd' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'pubid='=>'string', 'sysid='=>'string', 'subset='=>'string'],
'xmlwriter_write_dtd_attlist' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_element' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_dtd_entity' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'content'=>'string', 'pe'=>'bool', 'pubid'=>'string', 'sysid'=>'string', 'ndataid'=>'string'],
'xmlwriter_write_element' => ['bool', 'xmlwriter'=>'resource', 'name'=>'string', 'content'=>'string'],
'xmlwriter_write_element_ns' => ['bool', 'xmlwriter'=>'resource', 'prefix'=>'string', 'name'=>'string', 'uri'=>'string', 'content'=>'string'],
'xmlwriter_write_pi' => ['bool', 'xmlwriter'=>'resource', 'target'=>'string', 'content'=>'string'],
'xmlwriter_write_raw' => ['bool', 'xmlwriter'=>'resource', 'content'=>'string'],
'xpath_new_context' => ['XPathContext', 'dom_document'=>'DOMDocument'],
'xpath_register_ns' => ['bool', 'xpath_context'=>'xpathcontext', 'prefix'=>'string', 'uri'=>'string'],
'xpath_register_ns_auto' => ['bool', 'xpath_context'=>'xpathcontext', 'context_node='=>'object'],
'xptr_new_context' => ['XPathContext'],
'xsl_xsltprocessor_get_parameter' => ['string', 'namespace'=>'string', 'name'=>'string'],
'xsl_xsltprocessor_get_security_prefs' => ['int'],
'xsl_xsltprocessor_has_exslt_support' => ['bool'],
'xsl_xsltprocessor_register_php_functions' => ['', 'restrict'=>''],
'xsl_xsltprocessor_remove_parameter' => ['bool', 'namespace'=>'string', 'name'=>'string'],
'xsl_xsltprocessor_set_parameter' => ['bool', 'namespace'=>'string', 'name'=>'', 'value'=>'string'],
'xsl_xsltprocessor_set_profiling' => ['bool', 'filename'=>'string'],
'xsl_xsltprocessor_set_security_prefs' => ['int', 'securityprefs'=>'int'],
'xsl_xsltprocessor_transform_to_uri' => ['int', 'doc'=>'DOMDocument', 'uri'=>'string'],
'xsl_xsltprocessor_transform_to_xml' => ['string', 'doc'=>'DOMDocument'],
'xslt_backend_info' => ['string'],
'xslt_backend_name' => ['string'],
'xslt_backend_version' => ['string'],
'xslt_create' => ['resource'],
'xslt_errno' => ['int', 'xh'=>''],
'xslt_error' => ['string', 'xh'=>''],
'xslt_free' => ['', 'xh'=>''],
'xslt_getopt' => ['int', 'processor'=>''],
'xslt_process' => ['', 'xh'=>'', 'xmlcontainer'=>'string', 'xslcontainer'=>'string', 'resultcontainer='=>'string', 'arguments='=>'array', 'parameters='=>'array'],
'xslt_set_base' => ['', 'xh'=>'', 'uri'=>'string'],
'xslt_set_encoding' => ['', 'xh'=>'', 'encoding'=>'string'],
'xslt_set_error_handler' => ['', 'xh'=>'', 'handler'=>''],
'xslt_set_log' => ['', 'xh'=>'', 'log='=>''],
'xslt_set_object' => ['bool', 'processor'=>'', 'obj'=>'object'],
'xslt_set_sax_handler' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_set_sax_handlers' => ['', 'processor'=>'', 'handlers'=>'array'],
'xslt_set_scheme_handler' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_set_scheme_handlers' => ['', 'xh'=>'', 'handlers'=>'array'],
'xslt_setopt' => ['', 'processor'=>'', 'newmask'=>'int'],
'XSLTProcessor::getParameter' => ['string|false', 'namespaceuri'=>'string', 'localname'=>'string'],
'XsltProcessor::getSecurityPrefs' => ['int'],
'XSLTProcessor::hasExsltSupport' => ['bool'],
'XSLTProcessor::importStylesheet' => ['bool', 'stylesheet'=>'object'],
'XSLTProcessor::registerPHPFunctions' => ['void', 'restrict='=>'mixed'],
'XSLTProcessor::removeParameter' => ['bool', 'namespaceuri'=>'string', 'localname'=>'string'],
'XSLTProcessor::setParameter' => ['bool', 'namespace'=>'string', 'name'=>'string', 'value'=>'string'],
'XSLTProcessor::setParameter\'1' => ['bool', 'namespace'=>'string', 'options'=>'array'],
'XSLTProcessor::setProfiling' => ['bool', 'filename'=>'string'],
'XsltProcessor::setSecurityPrefs' => ['int', 'securityPrefs'=>'int'],
'XSLTProcessor::transformToDoc' => ['DOMDocument|false', 'doc'=>'DOMNode'],
'XSLTProcessor::transformToURI' => ['int', 'doc'=>'DOMDocument', 'uri'=>'string'],
'XSLTProcessor::transformToXML' => ['string', 'doc'=>'DOMDocument'],
'Yaconf::get' => ['mixed', 'name'=>'string', 'default_value='=>'mixed'],
'Yaconf::has' => ['bool', 'name'=>'string'],
'Yaf\Action_Abstract::__clone' => ['void'],
'Yaf\Action_Abstract::__construct' => ['void', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract', 'view'=>'Yaf\View_Interface', 'invokeArgs='=>'?array'],
'Yaf\Action_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::execute' => ['mixed'],
'Yaf\Action_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::getController' => ['Yaf\Controller_Abstract'],
'Yaf\Action_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf\Action_Abstract::getInvokeArgs' => ['array'],
'Yaf\Action_Abstract::getModuleName' => ['string'],
'Yaf\Action_Abstract::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Action_Abstract::getResponse' => ['Yaf\Response_Abstract'],
'Yaf\Action_Abstract::getView' => ['Yaf\View_Interface'],
'Yaf\Action_Abstract::getViewpath' => ['string'],
'Yaf\Action_Abstract::init' => [''],
'Yaf\Action_Abstract::initView' => ['Yaf\Response_Abstract', 'options='=>'?array'],
'Yaf\Action_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf\Action_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Action_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf\Application::__clone' => ['void'],
'Yaf\Application::__construct' => ['void', 'config'=>'array|string', 'envrion='=>'string'],
'Yaf\Application::__destruct' => ['void'],
'Yaf\Application::__sleep' => ['string[]'],
'Yaf\Application::__wakeup' => ['void'],
'Yaf\Application::app' => ['?Yaf\Application'],
'Yaf\Application::bootstrap' => ['Yaf\Application', 'bootstrap='=>'?Yaf\Bootstrap_Abstract'],
'Yaf\Application::clearLastError' => ['void'],
'Yaf\Application::environ' => ['string'],
'Yaf\Application::execute' => ['void', 'entry'=>'callable', '_='=>'string'],
'Yaf\Application::getAppDirectory' => ['string'],
'Yaf\Application::getConfig' => ['Yaf\Config_Abstract'],
'Yaf\Application::getDispatcher' => ['Yaf\Dispatcher'],
'Yaf\Application::getLastErrorMsg' => ['string'],
'Yaf\Application::getLastErrorNo' => ['int'],
'Yaf\Application::getModules' => ['array'],
'Yaf\Application::run' => ['void'],
'Yaf\Application::setAppDirectory' => ['Yaf\Application', 'directory'=>'string'],
'Yaf\Config\Ini::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf\Config\Ini::__get' => ['', 'name='=>'mixed'],
'Yaf\Config\Ini::__isset' => ['', 'name'=>'string'],
'Yaf\Config\Ini::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Config\Ini::count' => ['int'],
'Yaf\Config\Ini::current' => ['mixed'],
'Yaf\Config\Ini::get' => ['mixed', 'name='=>'mixed'],
'Yaf\Config\Ini::key' => ['int|string'],
'Yaf\Config\Ini::next' => ['void'],
'Yaf\Config\Ini::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Config\Ini::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Config\Ini::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Config\Ini::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Config\Ini::readonly' => ['bool'],
'Yaf\Config\Ini::rewind' => ['void'],
'Yaf\Config\Ini::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config\Ini::toArray' => ['array'],
'Yaf\Config\Ini::valid' => ['bool'],
'Yaf\Config\Simple::__construct' => ['void', 'array'=>'array', 'readonly='=>'string'],
'Yaf\Config\Simple::__get' => ['', 'name='=>'mixed'],
'Yaf\Config\Simple::__isset' => ['', 'name'=>'string'],
'Yaf\Config\Simple::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Config\Simple::count' => ['int'],
'Yaf\Config\Simple::current' => ['mixed'],
'Yaf\Config\Simple::get' => ['mixed', 'name='=>'mixed'],
'Yaf\Config\Simple::key' => ['int|string'],
'Yaf\Config\Simple::next' => ['void'],
'Yaf\Config\Simple::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Config\Simple::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Config\Simple::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Config\Simple::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Config\Simple::readonly' => ['bool'],
'Yaf\Config\Simple::rewind' => ['void'],
'Yaf\Config\Simple::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config\Simple::toArray' => ['array'],
'Yaf\Config\Simple::valid' => ['bool'],
'Yaf\Config_Abstract::__construct' => ['void'],
'Yaf\Config_Abstract::get' => ['mixed', 'name='=>'string'],
'Yaf\Config_Abstract::readonly' => ['bool'],
'Yaf\Config_Abstract::set' => ['Yaf\Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Config_Abstract::toArray' => ['array'],
'Yaf\Controller_Abstract::__clone' => ['void'],
'Yaf\Controller_Abstract::__construct' => ['void', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract', 'view'=>'Yaf\View_Interface', 'invokeArgs='=>'?array'],
'Yaf\Controller_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf\Controller_Abstract::getInvokeArgs' => ['array'],
'Yaf\Controller_Abstract::getModuleName' => ['string'],
'Yaf\Controller_Abstract::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Controller_Abstract::getResponse' => ['Yaf\Response_Abstract'],
'Yaf\Controller_Abstract::getView' => ['Yaf\View_Interface'],
'Yaf\Controller_Abstract::getViewpath' => ['string'],
'Yaf\Controller_Abstract::init' => [''],
'Yaf\Controller_Abstract::initView' => ['Yaf\Response_Abstract', 'options='=>'?array'],
'Yaf\Controller_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf\Controller_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf\Controller_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf\Dispatcher::__clone' => ['void'],
'Yaf\Dispatcher::__construct' => ['void'],
'Yaf\Dispatcher::__sleep' => ['string[]'],
'Yaf\Dispatcher::__wakeup' => ['void'],
'Yaf\Dispatcher::autoRender' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::catchException' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::disableView' => ['bool'],
'Yaf\Dispatcher::dispatch' => ['Yaf\Response_Abstract', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Dispatcher::enableView' => ['Yaf\Dispatcher'],
'Yaf\Dispatcher::flushInstantly' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Dispatcher::getApplication' => ['Yaf\Application'],
'Yaf\Dispatcher::getInstance' => ['Yaf\Dispatcher'],
'Yaf\Dispatcher::getRequest' => ['Yaf\Request_Abstract'],
'Yaf\Dispatcher::getRouter' => ['Yaf\Router'],
'Yaf\Dispatcher::initView' => ['Yaf\View_Interface', 'templates_dir'=>'string', 'options='=>'?array'],
'Yaf\Dispatcher::registerPlugin' => ['Yaf\Dispatcher', 'plugin'=>'Yaf\Plugin_Abstract'],
'Yaf\Dispatcher::returnResponse' => ['Yaf\Dispatcher', 'flag'=>'bool'],
'Yaf\Dispatcher::setDefaultAction' => ['Yaf\Dispatcher', 'action'=>'string'],
'Yaf\Dispatcher::setDefaultController' => ['Yaf\Dispatcher', 'controller'=>'string'],
'Yaf\Dispatcher::setDefaultModule' => ['Yaf\Dispatcher', 'module'=>'string'],
'Yaf\Dispatcher::setErrorHandler' => ['Yaf\Dispatcher', 'callback'=>'callable', 'error_types'=>'int'],
'Yaf\Dispatcher::setRequest' => ['Yaf\Dispatcher', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Dispatcher::setView' => ['Yaf\Dispatcher', 'view'=>'Yaf\View_Interface'],
'Yaf\Dispatcher::throwException' => ['Yaf\Dispatcher', 'flag='=>'bool'],
'Yaf\Loader::__clone' => ['void'],
'Yaf\Loader::__construct' => ['void'],
'Yaf\Loader::__sleep' => ['string[]'],
'Yaf\Loader::__wakeup' => ['void'],
'Yaf\Loader::autoload' => ['bool', 'class_name'=>'string'],
'Yaf\Loader::clearLocalNamespace' => [''],
'Yaf\Loader::getInstance' => ['Yaf\Loader', 'local_library_path='=>'string', 'global_library_path='=>'string'],
'Yaf\Loader::getLibraryPath' => ['string', 'is_global='=>'bool'],
'Yaf\Loader::getLocalNamespace' => ['string'],
'Yaf\Loader::import' => ['bool', 'file'=>'string'],
'Yaf\Loader::isLocalName' => ['bool', 'class_name'=>'string'],
'Yaf\Loader::registerLocalNamespace' => ['bool', 'name_prefix'=>'string|string[]'],
'Yaf\Loader::setLibraryPath' => ['Yaf\Loader', 'directory'=>'string', 'global='=>'bool'],
'Yaf\Plugin_Abstract::dispatchLoopShutdown' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::dispatchLoopStartup' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::postDispatch' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::preDispatch' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::preResponse' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::routerShutdown' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Plugin_Abstract::routerStartup' => ['bool', 'request'=>'Yaf\Request_Abstract', 'response'=>'Yaf\Response_Abstract'],
'Yaf\Registry::__clone' => ['void'],
'Yaf\Registry::__construct' => ['void'],
'Yaf\Registry::del' => ['bool|void', 'name'=>'string'],
'Yaf\Registry::get' => ['mixed', 'name'=>'string'],
'Yaf\Registry::has' => ['bool', 'name'=>'string'],
'Yaf\Registry::set' => ['bool', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Request\Http::__clone' => ['void'],
'Yaf\Request\Http::__construct' => ['void', 'request_uri'=>'string', 'base_uri'=>'string'],
'Yaf\Request\Http::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf\Request\Http::getActionName' => ['string'],
'Yaf\Request\Http::getBaseUri' => ['string'],
'Yaf\Request\Http::getControllerName' => ['string'],
'Yaf\Request\Http::getCookie' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getException' => ['Yaf\Exception'],
'Yaf\Request\Http::getFiles' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getLanguage' => ['string'],
'Yaf\Request\Http::getMethod' => ['string'],
'Yaf\Request\Http::getModuleName' => ['string'],
'Yaf\Request\Http::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getParams' => ['array'],
'Yaf\Request\Http::getPost' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getQuery' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getRequest' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::getRequestUri' => ['string'],
'Yaf\Request\Http::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Http::isCli' => ['bool'],
'Yaf\Request\Http::isDispatched' => ['bool'],
'Yaf\Request\Http::isGet' => ['bool'],
'Yaf\Request\Http::isHead' => ['bool'],
'Yaf\Request\Http::isOptions' => ['bool'],
'Yaf\Request\Http::isPost' => ['bool'],
'Yaf\Request\Http::isPut' => ['bool'],
'Yaf\Request\Http::isRouted' => ['bool'],
'Yaf\Request\Http::isXmlHttpRequest' => ['bool'],
'Yaf\Request\Http::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request\Http::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request\Http::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request\Http::setDispatched' => ['bool'],
'Yaf\Request\Http::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request\Http::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request\Http::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request\Http::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Request\Simple::__clone' => ['void'],
'Yaf\Request\Simple::__construct' => ['void', 'method'=>'string', 'controller'=>'string', 'action'=>'string', 'params='=>'string'],
'Yaf\Request\Simple::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getActionName' => ['string'],
'Yaf\Request\Simple::getBaseUri' => ['string'],
'Yaf\Request\Simple::getControllerName' => ['string'],
'Yaf\Request\Simple::getCookie' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::getException' => ['Yaf\Exception'],
'Yaf\Request\Simple::getFiles' => ['array', 'name='=>'mixed', 'default='=>'null'],
'Yaf\Request\Simple::getLanguage' => ['string'],
'Yaf\Request\Simple::getMethod' => ['string'],
'Yaf\Request\Simple::getModuleName' => ['string'],
'Yaf\Request\Simple::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::getParams' => ['array'],
'Yaf\Request\Simple::getPost' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getQuery' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getRequest' => ['mixed', 'name='=>'string', 'default='=>'string'],
'Yaf\Request\Simple::getRequestUri' => ['string'],
'Yaf\Request\Simple::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request\Simple::isCli' => ['bool'],
'Yaf\Request\Simple::isDispatched' => ['bool'],
'Yaf\Request\Simple::isGet' => ['bool'],
'Yaf\Request\Simple::isHead' => ['bool'],
'Yaf\Request\Simple::isOptions' => ['bool'],
'Yaf\Request\Simple::isPost' => ['bool'],
'Yaf\Request\Simple::isPut' => ['bool'],
'Yaf\Request\Simple::isRouted' => ['bool'],
'Yaf\Request\Simple::isXmlHttpRequest' => ['bool'],
'Yaf\Request\Simple::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request\Simple::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request\Simple::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request\Simple::setDispatched' => ['bool'],
'Yaf\Request\Simple::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request\Simple::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request\Simple::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request\Simple::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Request_Abstract::getActionName' => ['string'],
'Yaf\Request_Abstract::getBaseUri' => ['string'],
'Yaf\Request_Abstract::getControllerName' => ['string'],
'Yaf\Request_Abstract::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::getException' => ['Yaf\Exception'],
'Yaf\Request_Abstract::getLanguage' => ['string'],
'Yaf\Request_Abstract::getMethod' => ['string'],
'Yaf\Request_Abstract::getModuleName' => ['string'],
'Yaf\Request_Abstract::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::getParams' => ['array'],
'Yaf\Request_Abstract::getRequestUri' => ['string'],
'Yaf\Request_Abstract::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf\Request_Abstract::isCli' => ['bool'],
'Yaf\Request_Abstract::isDispatched' => ['bool'],
'Yaf\Request_Abstract::isGet' => ['bool'],
'Yaf\Request_Abstract::isHead' => ['bool'],
'Yaf\Request_Abstract::isOptions' => ['bool'],
'Yaf\Request_Abstract::isPost' => ['bool'],
'Yaf\Request_Abstract::isPut' => ['bool'],
'Yaf\Request_Abstract::isRouted' => ['bool'],
'Yaf\Request_Abstract::isXmlHttpRequest' => ['bool'],
'Yaf\Request_Abstract::setActionName' => ['Yaf\Request_Abstract|bool', 'action'=>'string'],
'Yaf\Request_Abstract::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf\Request_Abstract::setControllerName' => ['Yaf\Request_Abstract|bool', 'controller'=>'string'],
'Yaf\Request_Abstract::setDispatched' => ['bool'],
'Yaf\Request_Abstract::setModuleName' => ['Yaf\Request_Abstract|bool', 'module'=>'string'],
'Yaf\Request_Abstract::setParam' => ['Yaf\Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf\Request_Abstract::setRequestUri' => ['', 'uri'=>'string'],
'Yaf\Request_Abstract::setRouted' => ['Yaf\Request_Abstract|bool'],
'Yaf\Response\Cli::__clone' => ['void'],
'Yaf\Response\Cli::__construct' => ['void'],
'Yaf\Response\Cli::__destruct' => ['void'],
'Yaf\Response\Cli::__toString' => ['string'],
'Yaf\Response\Cli::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Cli::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response\Cli::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response\Cli::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Cli::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::__clone' => ['void'],
'Yaf\Response\Http::__construct' => ['void'],
'Yaf\Response\Http::__destruct' => ['void'],
'Yaf\Response\Http::__toString' => ['string'],
'Yaf\Response\Http::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response\Http::clearHeaders' => ['Yaf\Response_Abstract|false', 'name='=>'string'],
'Yaf\Response\Http::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response\Http::getHeader' => ['mixed', 'name='=>'string'],
'Yaf\Response\Http::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::response' => ['bool'],
'Yaf\Response\Http::setAllHeaders' => ['bool', 'headers'=>'array'],
'Yaf\Response\Http::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response\Http::setHeader' => ['bool', 'name'=>'string', 'value'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'Yaf\Response\Http::setRedirect' => ['bool', 'url'=>'string'],
'Yaf\Response_Abstract::__clone' => ['void'],
'Yaf\Response_Abstract::__construct' => ['void'],
'Yaf\Response_Abstract::__destruct' => ['void'],
'Yaf\Response_Abstract::__toString' => ['void'],
'Yaf\Response_Abstract::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response_Abstract::clearBody' => ['bool', 'key='=>'string'],
'Yaf\Response_Abstract::getBody' => ['mixed', 'key='=>'?string'],
'Yaf\Response_Abstract::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Response_Abstract::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf\Route\Map::__construct' => ['void', 'controller_prefer='=>'bool', 'delimiter='=>'string'],
'Yaf\Route\Map::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Map::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Regex::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'map='=>'?array', 'verify='=>'?array', 'reverse='=>'string'],
'Yaf\Route\Regex::addConfig' => ['Yaf\Router|bool', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Route\Regex::addRoute' => ['Yaf\Router|bool', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Route\Regex::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Regex::getCurrentRoute' => ['string'],
'Yaf\Route\Regex::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Route\Regex::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Route\Regex::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Rewrite::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'verify='=>'?array', 'reverse='=>'string'],
'Yaf\Route\Rewrite::addConfig' => ['Yaf\Router|bool', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Route\Rewrite::addRoute' => ['Yaf\Router|bool', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Route\Rewrite::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Rewrite::getCurrentRoute' => ['string'],
'Yaf\Route\Rewrite::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Route\Rewrite::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Route\Rewrite::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Simple::__construct' => ['void', 'module_name'=>'string', 'controller_name'=>'string', 'action_name'=>'string'],
'Yaf\Route\Simple::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Simple::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route\Supervar::__construct' => ['void', 'supervar_name'=>'string'],
'Yaf\Route\Supervar::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route\Supervar::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route_Interface::__construct' => ['Yaf\Route_Interface'],
'Yaf\Route_Interface::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route_Interface::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Route_Static::assemble' => ['bool', 'info'=>'array', 'query='=>'?array'],
'Yaf\Route_Static::match' => ['bool', 'uri'=>'string'],
'Yaf\Route_Static::route' => ['bool', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Router::__construct' => ['void'],
'Yaf\Router::addConfig' => ['Yaf\Router|false', 'config'=>'Yaf\Config_Abstract'],
'Yaf\Router::addRoute' => ['Yaf\Router|false', 'name'=>'string', 'route'=>'Yaf\Route_Interface'],
'Yaf\Router::getCurrentRoute' => ['string'],
'Yaf\Router::getRoute' => ['Yaf\Route_Interface', 'name'=>'string'],
'Yaf\Router::getRoutes' => ['Yaf\Route_Interface[]'],
'Yaf\Router::route' => ['Yaf\Router|false', 'request'=>'Yaf\Request_Abstract'],
'Yaf\Session::__clone' => ['void'],
'Yaf\Session::__construct' => ['void'],
'Yaf\Session::__get' => ['void', 'name'=>''],
'Yaf\Session::__isset' => ['void', 'name'=>''],
'Yaf\Session::__set' => ['void', 'name'=>'', 'value'=>''],
'Yaf\Session::__sleep' => ['string[]'],
'Yaf\Session::__unset' => ['void', 'name'=>''],
'Yaf\Session::__wakeup' => ['void'],
'Yaf\Session::count' => ['int'],
'Yaf\Session::current' => ['mixed'],
'Yaf\Session::del' => ['Yaf\Session|false', 'name'=>'string'],
'Yaf\Session::get' => ['mixed', 'name'=>'string'],
'Yaf\Session::getInstance' => ['Yaf\Session'],
'Yaf\Session::has' => ['bool', 'name'=>'string'],
'Yaf\Session::key' => ['int|string'],
'Yaf\Session::next' => ['void'],
'Yaf\Session::offsetExists' => ['bool', 'name'=>'mixed'],
'Yaf\Session::offsetGet' => ['mixed', 'name'=>'mixed'],
'Yaf\Session::offsetSet' => ['void', 'name'=>'mixed', 'value'=>'mixed'],
'Yaf\Session::offsetUnset' => ['void', 'name'=>'mixed'],
'Yaf\Session::rewind' => ['void'],
'Yaf\Session::set' => ['Yaf\Session|false', 'name'=>'string', 'value'=>'mixed'],
'Yaf\Session::start' => ['Yaf\Session'],
'Yaf\Session::valid' => ['bool'],
'Yaf\View\Simple::__construct' => ['void', 'template_dir'=>'string', 'options='=>'?array'],
'Yaf\View\Simple::__get' => ['mixed', 'name='=>'null'],
'Yaf\View\Simple::__isset' => ['', 'name'=>'string'],
'Yaf\View\Simple::__set' => ['void', 'name'=>'string', 'value='=>'mixed'],
'Yaf\View\Simple::assign' => ['Yaf\View\Simple', 'name'=>'array|string', 'value='=>'mixed'],
'Yaf\View\Simple::assignRef' => ['Yaf\View\Simple', 'name'=>'string', '&value'=>'mixed'],
'Yaf\View\Simple::clear' => ['Yaf\View\Simple', 'name='=>'string'],
'Yaf\View\Simple::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View\Simple::eval' => ['bool|void', 'tpl_str'=>'string', 'vars='=>'?array'],
'Yaf\View\Simple::getScriptPath' => ['string'],
'Yaf\View\Simple::render' => ['string|void', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View\Simple::setScriptPath' => ['Yaf\View\Simple', 'template_dir'=>'string'],
'Yaf\View_Interface::assign' => ['bool', 'name'=>'array|string', 'value'=>'mixed'],
'Yaf\View_Interface::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View_Interface::getScriptPath' => ['string'],
'Yaf\View_Interface::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'?array'],
'Yaf\View_Interface::setScriptPath' => ['void', 'template_dir'=>'string'],
'Yaf_Action_Abstract::__clone' => ['void'],
'Yaf_Action_Abstract::__construct' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract', 'view'=>'Yaf_View_Interface', 'invokeArgs='=>'?array'],
'Yaf_Action_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::execute' => ['mixed', 'arg='=>'mixed', '...args='=>'mixed'],
'Yaf_Action_Abstract::forward' => ['bool', 'module'=>'string', 'controller='=>'string', 'action='=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::getController' => ['Yaf_Controller_Abstract'],
'Yaf_Action_Abstract::getInvokeArg' => ['mixed|null', 'name'=>'string'],
'Yaf_Action_Abstract::getInvokeArgs' => ['array'],
'Yaf_Action_Abstract::getModuleName' => ['string'],
'Yaf_Action_Abstract::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Action_Abstract::getResponse' => ['Yaf_Response_Abstract'],
'Yaf_Action_Abstract::getView' => ['Yaf_View_Interface'],
'Yaf_Action_Abstract::getViewpath' => ['string'],
'Yaf_Action_Abstract::init' => [''],
'Yaf_Action_Abstract::initView' => ['Yaf_Response_Abstract', 'options='=>'?array'],
'Yaf_Action_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf_Action_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'?array'],
'Yaf_Action_Abstract::setViewpath' => ['bool', 'view_directory'=>'string'],
'Yaf_Application::__clone' => ['void'],
'Yaf_Application::__construct' => ['void', 'config'=>'mixed', 'envrion='=>'string'],
'Yaf_Application::__destruct' => ['void'],
'Yaf_Application::__sleep' => ['string[]'],
'Yaf_Application::__wakeup' => ['void'],
'Yaf_Application::app' => ['?Yaf_Application'],
'Yaf_Application::bootstrap' => ['Yaf_Application', 'bootstrap='=>'Yaf_Bootstrap_Abstract'],
'Yaf_Application::clearLastError' => ['Yaf_Application'],
'Yaf_Application::environ' => ['string'],
'Yaf_Application::execute' => ['void', 'entry'=>'callable', '...args'=>'string'],
'Yaf_Application::getAppDirectory' => ['Yaf_Application'],
'Yaf_Application::getConfig' => ['Yaf_Config_Abstract'],
'Yaf_Application::getDispatcher' => ['Yaf_Dispatcher'],
'Yaf_Application::getLastErrorMsg' => ['string'],
'Yaf_Application::getLastErrorNo' => ['int'],
'Yaf_Application::getModules' => ['array'],
'Yaf_Application::run' => ['void'],
'Yaf_Application::setAppDirectory' => ['Yaf_Application', 'directory'=>'string'],
'Yaf_Config_Abstract::__construct' => ['void'],
'Yaf_Config_Abstract::get' => ['mixed', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Abstract::readonly' => ['bool'],
'Yaf_Config_Abstract::set' => ['Yaf_Config_Abstract'],
'Yaf_Config_Abstract::toArray' => ['array'],
'Yaf_Config_Ini::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf_Config_Ini::__get' => ['void', 'name='=>'string'],
'Yaf_Config_Ini::__isset' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::__set' => ['void', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Ini::count' => ['void'],
'Yaf_Config_Ini::current' => ['void'],
'Yaf_Config_Ini::get' => ['mixed', 'name='=>'mixed'],
'Yaf_Config_Ini::key' => ['void'],
'Yaf_Config_Ini::next' => ['void'],
'Yaf_Config_Ini::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Ini::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Config_Ini::readonly' => ['void'],
'Yaf_Config_Ini::rewind' => ['void'],
'Yaf_Config_Ini::set' => ['Yaf_Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Ini::toArray' => ['array'],
'Yaf_Config_Ini::valid' => ['void'],
'Yaf_Config_Simple::__construct' => ['void', 'config_file'=>'string', 'section='=>'string'],
'Yaf_Config_Simple::__get' => ['void', 'name='=>'string'],
'Yaf_Config_Simple::__isset' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::__set' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Simple::count' => ['void'],
'Yaf_Config_Simple::current' => ['void'],
'Yaf_Config_Simple::get' => ['mixed', 'name='=>'mixed'],
'Yaf_Config_Simple::key' => ['void'],
'Yaf_Config_Simple::next' => ['void'],
'Yaf_Config_Simple::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Config_Simple::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Config_Simple::readonly' => ['void'],
'Yaf_Config_Simple::rewind' => ['void'],
'Yaf_Config_Simple::set' => ['Yaf_Config_Abstract', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Config_Simple::toArray' => ['array'],
'Yaf_Config_Simple::valid' => ['void'],
'Yaf_Controller_Abstract::__clone' => ['void'],
'Yaf_Controller_Abstract::__construct' => ['void'],
'Yaf_Controller_Abstract::display' => ['bool', 'tpl'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward' => ['void', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward\'1' => ['void', 'controller'=>'string', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::forward\'2' => ['void', 'module'=>'string', 'controller'=>'string', 'action'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::getInvokeArg' => ['void', 'name'=>'string'],
'Yaf_Controller_Abstract::getInvokeArgs' => ['void'],
'Yaf_Controller_Abstract::getModuleName' => ['string'],
'Yaf_Controller_Abstract::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Controller_Abstract::getResponse' => ['Yaf_Response_Abstract'],
'Yaf_Controller_Abstract::getView' => ['Yaf_View_Interface'],
'Yaf_Controller_Abstract::getViewpath' => ['void'],
'Yaf_Controller_Abstract::init' => ['void'],
'Yaf_Controller_Abstract::initView' => ['void', 'options='=>'array'],
'Yaf_Controller_Abstract::redirect' => ['bool', 'url'=>'string'],
'Yaf_Controller_Abstract::render' => ['string', 'tpl'=>'string', 'parameters='=>'array'],
'Yaf_Controller_Abstract::setViewpath' => ['void', 'view_directory'=>'string'],
'Yaf_Dispatcher::__clone' => ['void'],
'Yaf_Dispatcher::__construct' => ['void'],
'Yaf_Dispatcher::__sleep' => ['string[]'],
'Yaf_Dispatcher::__wakeup' => ['void'],
'Yaf_Dispatcher::autoRender' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::catchException' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::disableView' => ['bool'],
'Yaf_Dispatcher::dispatch' => ['Yaf_Response_Abstract', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Dispatcher::enableView' => ['Yaf_Dispatcher'],
'Yaf_Dispatcher::flushInstantly' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Dispatcher::getApplication' => ['Yaf_Application'],
'Yaf_Dispatcher::getInstance' => ['Yaf_Dispatcher'],
'Yaf_Dispatcher::getRequest' => ['Yaf_Request_Abstract'],
'Yaf_Dispatcher::getRouter' => ['Yaf_Router'],
'Yaf_Dispatcher::initView' => ['Yaf_View_Interface', 'templates_dir'=>'string', 'options='=>'array'],
'Yaf_Dispatcher::registerPlugin' => ['Yaf_Dispatcher', 'plugin'=>'Yaf_Plugin_Abstract'],
'Yaf_Dispatcher::returnResponse' => ['Yaf_Dispatcher', 'flag'=>'bool'],
'Yaf_Dispatcher::setDefaultAction' => ['Yaf_Dispatcher', 'action'=>'string'],
'Yaf_Dispatcher::setDefaultController' => ['Yaf_Dispatcher', 'controller'=>'string'],
'Yaf_Dispatcher::setDefaultModule' => ['Yaf_Dispatcher', 'module'=>'string'],
'Yaf_Dispatcher::setErrorHandler' => ['Yaf_Dispatcher', 'callback'=>'callable', 'error_types'=>'int'],
'Yaf_Dispatcher::setRequest' => ['Yaf_Dispatcher', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Dispatcher::setView' => ['Yaf_Dispatcher', 'view'=>'Yaf_View_Interface'],
'Yaf_Dispatcher::throwException' => ['Yaf_Dispatcher', 'flag='=>'bool'],
'Yaf_Exception::__construct' => ['void'],
'Yaf_Exception::getPrevious' => ['void'],
'Yaf_Loader::__clone' => ['void'],
'Yaf_Loader::__construct' => ['void'],
'Yaf_Loader::__sleep' => ['string[]'],
'Yaf_Loader::__wakeup' => ['void'],
'Yaf_Loader::autoload' => ['void'],
'Yaf_Loader::clearLocalNamespace' => ['void'],
'Yaf_Loader::getInstance' => ['Yaf_Loader'],
'Yaf_Loader::getLibraryPath' => ['Yaf_Loader', 'is_global='=>'bool'],
'Yaf_Loader::getLocalNamespace' => ['void'],
'Yaf_Loader::import' => ['bool'],
'Yaf_Loader::isLocalName' => ['bool'],
'Yaf_Loader::registerLocalNamespace' => ['void', 'prefix'=>'mixed'],
'Yaf_Loader::setLibraryPath' => ['Yaf_Loader', 'directory'=>'string', 'is_global='=>'bool'],
'Yaf_Plugin_Abstract::dispatchLoopShutdown' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::dispatchLoopStartup' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::postDispatch' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::preDispatch' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::preResponse' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::routerShutdown' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Plugin_Abstract::routerStartup' => ['void', 'request'=>'Yaf_Request_Abstract', 'response'=>'Yaf_Response_Abstract'],
'Yaf_Registry::__clone' => ['void'],
'Yaf_Registry::__construct' => ['void'],
'Yaf_Registry::del' => ['void', 'name'=>'string'],
'Yaf_Registry::get' => ['mixed', 'name'=>'string'],
'Yaf_Registry::has' => ['bool', 'name'=>'string'],
'Yaf_Registry::set' => ['bool', 'name'=>'string', 'value'=>'string'],
'Yaf_Request_Abstract::getActionName' => ['void'],
'Yaf_Request_Abstract::getBaseUri' => ['void'],
'Yaf_Request_Abstract::getControllerName' => ['void'],
'Yaf_Request_Abstract::getEnv' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::getException' => ['void'],
'Yaf_Request_Abstract::getLanguage' => ['void'],
'Yaf_Request_Abstract::getMethod' => ['void'],
'Yaf_Request_Abstract::getModuleName' => ['void'],
'Yaf_Request_Abstract::getParam' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::getParams' => ['void'],
'Yaf_Request_Abstract::getRequestUri' => ['void'],
'Yaf_Request_Abstract::getServer' => ['void', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Abstract::isCli' => ['void'],
'Yaf_Request_Abstract::isDispatched' => ['void'],
'Yaf_Request_Abstract::isGet' => ['void'],
'Yaf_Request_Abstract::isHead' => ['void'],
'Yaf_Request_Abstract::isOptions' => ['void'],
'Yaf_Request_Abstract::isPost' => ['void'],
'Yaf_Request_Abstract::isPut' => ['void'],
'Yaf_Request_Abstract::isRouted' => ['void'],
'Yaf_Request_Abstract::isXmlHttpRequest' => ['void'],
'Yaf_Request_Abstract::setActionName' => ['void', 'action'=>'string'],
'Yaf_Request_Abstract::setBaseUri' => ['bool', 'uir'=>'string'],
'Yaf_Request_Abstract::setControllerName' => ['void', 'controller'=>'string'],
'Yaf_Request_Abstract::setDispatched' => ['void'],
'Yaf_Request_Abstract::setModuleName' => ['void', 'module'=>'string'],
'Yaf_Request_Abstract::setParam' => ['void', 'name'=>'string', 'value='=>'string'],
'Yaf_Request_Abstract::setRequestUri' => ['void', 'uir'=>'string'],
'Yaf_Request_Abstract::setRouted' => ['void', 'flag='=>'string'],
'Yaf_Request_Http::__clone' => ['void'],
'Yaf_Request_Http::__construct' => ['void'],
'Yaf_Request_Http::get' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getActionName' => ['string'],
'Yaf_Request_Http::getBaseUri' => ['string'],
'Yaf_Request_Http::getControllerName' => ['string'],
'Yaf_Request_Http::getCookie' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::getException' => ['Yaf_Exception'],
'Yaf_Request_Http::getFiles' => ['void'],
'Yaf_Request_Http::getLanguage' => ['string'],
'Yaf_Request_Http::getMethod' => ['string'],
'Yaf_Request_Http::getModuleName' => ['string'],
'Yaf_Request_Http::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::getParams' => ['array'],
'Yaf_Request_Http::getPost' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getQuery' => ['mixed', 'name'=>'string', 'default='=>'string'],
'Yaf_Request_Http::getRaw' => ['mixed'],
'Yaf_Request_Http::getRequest' => ['void'],
'Yaf_Request_Http::getRequestUri' => ['string'],
'Yaf_Request_Http::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Http::isCli' => ['bool'],
'Yaf_Request_Http::isDispatched' => ['bool'],
'Yaf_Request_Http::isGet' => ['bool'],
'Yaf_Request_Http::isHead' => ['bool'],
'Yaf_Request_Http::isOptions' => ['bool'],
'Yaf_Request_Http::isPost' => ['bool'],
'Yaf_Request_Http::isPut' => ['bool'],
'Yaf_Request_Http::isRouted' => ['bool'],
'Yaf_Request_Http::isXmlHttpRequest' => ['bool'],
'Yaf_Request_Http::setActionName' => ['Yaf_Request_Abstract|bool', 'action'=>'string'],
'Yaf_Request_Http::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf_Request_Http::setControllerName' => ['Yaf_Request_Abstract|bool', 'controller'=>'string'],
'Yaf_Request_Http::setDispatched' => ['bool'],
'Yaf_Request_Http::setModuleName' => ['Yaf_Request_Abstract|bool', 'module'=>'string'],
'Yaf_Request_Http::setParam' => ['Yaf_Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf_Request_Http::setRequestUri' => ['', 'uri'=>'string'],
'Yaf_Request_Http::setRouted' => ['Yaf_Request_Abstract|bool'],
'Yaf_Request_Simple::__clone' => ['void'],
'Yaf_Request_Simple::__construct' => ['void'],
'Yaf_Request_Simple::get' => ['void'],
'Yaf_Request_Simple::getActionName' => ['string'],
'Yaf_Request_Simple::getBaseUri' => ['string'],
'Yaf_Request_Simple::getControllerName' => ['string'],
'Yaf_Request_Simple::getCookie' => ['void'],
'Yaf_Request_Simple::getEnv' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::getException' => ['Yaf_Exception'],
'Yaf_Request_Simple::getFiles' => ['void'],
'Yaf_Request_Simple::getLanguage' => ['string'],
'Yaf_Request_Simple::getMethod' => ['string'],
'Yaf_Request_Simple::getModuleName' => ['string'],
'Yaf_Request_Simple::getParam' => ['mixed', 'name'=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::getParams' => ['array'],
'Yaf_Request_Simple::getPost' => ['void'],
'Yaf_Request_Simple::getQuery' => ['void'],
'Yaf_Request_Simple::getRequest' => ['void'],
'Yaf_Request_Simple::getRequestUri' => ['string'],
'Yaf_Request_Simple::getServer' => ['mixed', 'name='=>'string', 'default='=>'mixed'],
'Yaf_Request_Simple::isCli' => ['bool'],
'Yaf_Request_Simple::isDispatched' => ['bool'],
'Yaf_Request_Simple::isGet' => ['bool'],
'Yaf_Request_Simple::isHead' => ['bool'],
'Yaf_Request_Simple::isOptions' => ['bool'],
'Yaf_Request_Simple::isPost' => ['bool'],
'Yaf_Request_Simple::isPut' => ['bool'],
'Yaf_Request_Simple::isRouted' => ['bool'],
'Yaf_Request_Simple::isXmlHttpRequest' => ['void'],
'Yaf_Request_Simple::setActionName' => ['Yaf_Request_Abstract|bool', 'action'=>'string'],
'Yaf_Request_Simple::setBaseUri' => ['bool', 'uri'=>'string'],
'Yaf_Request_Simple::setControllerName' => ['Yaf_Request_Abstract|bool', 'controller'=>'string'],
'Yaf_Request_Simple::setDispatched' => ['bool'],
'Yaf_Request_Simple::setModuleName' => ['Yaf_Request_Abstract|bool', 'module'=>'string'],
'Yaf_Request_Simple::setParam' => ['Yaf_Request_Abstract|bool', 'name'=>'array|string', 'value='=>'string'],
'Yaf_Request_Simple::setRequestUri' => ['', 'uri'=>'string'],
'Yaf_Request_Simple::setRouted' => ['Yaf_Request_Abstract|bool'],
'Yaf_Response_Abstract::__clone' => ['void'],
'Yaf_Response_Abstract::__construct' => ['void'],
'Yaf_Response_Abstract::__destruct' => ['void'],
'Yaf_Response_Abstract::__toString' => ['string'],
'Yaf_Response_Abstract::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Abstract::clearHeaders' => ['void'],
'Yaf_Response_Abstract::getBody' => ['mixed', 'key='=>'string'],
'Yaf_Response_Abstract::getHeader' => ['void'],
'Yaf_Response_Abstract::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::response' => ['void'],
'Yaf_Response_Abstract::setAllHeaders' => ['void'],
'Yaf_Response_Abstract::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Abstract::setHeader' => ['void'],
'Yaf_Response_Abstract::setRedirect' => ['void'],
'Yaf_Response_Cli::__clone' => ['void'],
'Yaf_Response_Cli::__construct' => ['void'],
'Yaf_Response_Cli::__destruct' => ['void'],
'Yaf_Response_Cli::__toString' => ['string'],
'Yaf_Response_Cli::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Cli::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Cli::getBody' => ['mixed', 'key='=>'?string'],
'Yaf_Response_Cli::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Cli::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::__clone' => ['void'],
'Yaf_Response_Http::__construct' => ['void'],
'Yaf_Response_Http::__destruct' => ['void'],
'Yaf_Response_Http::__toString' => ['string'],
'Yaf_Response_Http::appendBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::clearBody' => ['bool', 'key='=>'string'],
'Yaf_Response_Http::clearHeaders' => ['Yaf_Response_Abstract|false', 'name='=>'string'],
'Yaf_Response_Http::getBody' => ['mixed', 'key='=>'?string'],
'Yaf_Response_Http::getHeader' => ['mixed', 'name='=>'string'],
'Yaf_Response_Http::prependBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::response' => ['bool'],
'Yaf_Response_Http::setAllHeaders' => ['bool', 'headers'=>'array'],
'Yaf_Response_Http::setBody' => ['bool', 'content'=>'string', 'key='=>'string'],
'Yaf_Response_Http::setHeader' => ['bool', 'name'=>'string', 'value'=>'string', 'replace='=>'bool', 'response_code='=>'int'],
'Yaf_Response_Http::setRedirect' => ['bool', 'url'=>'string'],
'Yaf_Route_Interface::__construct' => ['void'],
'Yaf_Route_Interface::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Interface::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Map::__construct' => ['void', 'controller_prefer='=>'string', 'delimiter='=>'string'],
'Yaf_Route_Map::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Map::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Regex::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'map='=>'array', 'verify='=>'array', 'reverse='=>'string'],
'Yaf_Route_Regex::addConfig' => ['Yaf_Router|bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Route_Regex::addRoute' => ['Yaf_Router|bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Route_Regex::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Regex::getCurrentRoute' => ['string'],
'Yaf_Route_Regex::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Route_Regex::getRoutes' => ['Yaf_Route_Interface[]'],
'Yaf_Route_Regex::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Rewrite::__construct' => ['void', 'match'=>'string', 'route'=>'array', 'verify='=>'array'],
'Yaf_Route_Rewrite::addConfig' => ['Yaf_Router|bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Route_Rewrite::addRoute' => ['Yaf_Router|bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Route_Rewrite::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Rewrite::getCurrentRoute' => ['string'],
'Yaf_Route_Rewrite::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Route_Rewrite::getRoutes' => ['Yaf_Route_Interface[]'],
'Yaf_Route_Rewrite::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Simple::__construct' => ['void', 'module_name'=>'string', 'controller_name'=>'string', 'action_name'=>'string'],
'Yaf_Route_Simple::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Simple::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Static::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Static::match' => ['void', 'uri'=>'string'],
'Yaf_Route_Static::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Route_Supervar::__construct' => ['void', 'supervar_name'=>'string'],
'Yaf_Route_Supervar::assemble' => ['string', 'info'=>'array', 'query='=>'array'],
'Yaf_Route_Supervar::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Router::__construct' => ['void'],
'Yaf_Router::addConfig' => ['bool', 'config'=>'Yaf_Config_Abstract'],
'Yaf_Router::addRoute' => ['bool', 'name'=>'string', 'route'=>'Yaf_Route_Interface'],
'Yaf_Router::getCurrentRoute' => ['string'],
'Yaf_Router::getRoute' => ['Yaf_Route_Interface', 'name'=>'string'],
'Yaf_Router::getRoutes' => ['mixed'],
'Yaf_Router::route' => ['bool', 'request'=>'Yaf_Request_Abstract'],
'Yaf_Session::__clone' => ['void'],
'Yaf_Session::__construct' => ['void'],
'Yaf_Session::__get' => ['void', 'name'=>'string'],
'Yaf_Session::__isset' => ['void', 'name'=>'string'],
'Yaf_Session::__set' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Session::__sleep' => ['string[]'],
'Yaf_Session::__unset' => ['void', 'name'=>'string'],
'Yaf_Session::__wakeup' => ['void'],
'Yaf_Session::count' => ['void'],
'Yaf_Session::current' => ['void'],
'Yaf_Session::del' => ['void', 'name'=>'string'],
'Yaf_Session::get' => ['mixed', 'name'=>'string'],
'Yaf_Session::getInstance' => ['void'],
'Yaf_Session::has' => ['void', 'name'=>'string'],
'Yaf_Session::key' => ['void'],
'Yaf_Session::next' => ['void'],
'Yaf_Session::offsetExists' => ['void', 'name'=>'string'],
'Yaf_Session::offsetGet' => ['void', 'name'=>'string'],
'Yaf_Session::offsetSet' => ['void', 'name'=>'string', 'value'=>'string'],
'Yaf_Session::offsetUnset' => ['void', 'name'=>'string'],
'Yaf_Session::rewind' => ['void'],
'Yaf_Session::set' => ['Yaf_Session|bool', 'name'=>'string', 'value'=>'mixed'],
'Yaf_Session::start' => ['void'],
'Yaf_Session::valid' => ['void'],
'Yaf_View_Interface::assign' => ['bool', 'name'=>'string', 'value='=>'string'],
'Yaf_View_Interface::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Interface::getScriptPath' => ['string'],
'Yaf_View_Interface::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Interface::setScriptPath' => ['void', 'template_dir'=>'string'],
'Yaf_View_Simple::__construct' => ['void', 'tempalte_dir'=>'string', 'options='=>'array'],
'Yaf_View_Simple::__get' => ['void', 'name='=>'string'],
'Yaf_View_Simple::__isset' => ['void', 'name'=>'string'],
'Yaf_View_Simple::__set' => ['void', 'name'=>'string', 'value'=>'mixed'],
'Yaf_View_Simple::assign' => ['bool', 'name'=>'string', 'value='=>'mixed'],
'Yaf_View_Simple::assignRef' => ['bool', 'name'=>'string', '&rw_value'=>'mixed'],
'Yaf_View_Simple::clear' => ['bool', 'name='=>'string'],
'Yaf_View_Simple::display' => ['bool', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::eval' => ['string', 'tpl_content'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::getScriptPath' => ['string'],
'Yaf_View_Simple::render' => ['string', 'tpl'=>'string', 'tpl_vars='=>'array'],
'Yaf_View_Simple::setScriptPath' => ['bool', 'template_dir'=>'string'],
'yaml_emit' => ['string', 'data'=>'mixed', 'encoding='=>'int', 'linebreak='=>'int'],
'yaml_emit_file' => ['bool', 'filename'=>'string', 'data'=>'mixed', 'encoding='=>'int', 'linebreak='=>'int'],
'yaml_parse' => ['mixed|false', 'input'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'yaml_parse_file' => ['mixed|false', 'filename'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'yaml_parse_url' => ['mixed|false', 'url'=>'string', 'pos='=>'int', '&w_ndocs='=>'int', 'callbacks='=>'array'],
'Yar_Client::__call' => ['void', 'method'=>'string', 'parameters'=>'array'],
'Yar_Client::__construct' => ['void', 'url'=>'string'],
'Yar_Client::setOpt' => ['Yar_Client|false', 'name'=>'int', 'value'=>'mixed'],
'Yar_Client_Exception::__clone' => ['void'],
'Yar_Client_Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'Yar_Client_Exception::__toString' => ['string'],
'Yar_Client_Exception::__wakeup' => ['void'],
'Yar_Client_Exception::getCode' => ['int'],
'Yar_Client_Exception::getFile' => ['string'],
'Yar_Client_Exception::getLine' => ['int'],
'Yar_Client_Exception::getMessage' => ['string'],
'Yar_Client_Exception::getPrevious' => ['?Exception|?Throwable'],
'Yar_Client_Exception::getTrace' => ['array'],
'Yar_Client_Exception::getTraceAsString' => ['string'],
'Yar_Client_Exception::getType' => ['string'],
'Yar_Concurrent_Client::call' => ['int', 'uri'=>'string', 'method'=>'string', 'parameters'=>'array', 'callback='=>'callable'],
'Yar_Concurrent_Client::loop' => ['bool', 'callback='=>'callable', 'error_callback='=>'callable'],
'Yar_Concurrent_Client::reset' => ['bool'],
'Yar_Server::__construct' => ['void', 'obj'=>'Object'],
'Yar_Server::handle' => ['bool'],
'Yar_Server_Exception::__clone' => ['void'],
'Yar_Server_Exception::__construct' => ['void', 'message='=>'string', 'code='=>'int', 'previous='=>'?Exception|?Throwable'],
'Yar_Server_Exception::__toString' => ['string'],
'Yar_Server_Exception::__wakeup' => ['void'],
'Yar_Server_Exception::getCode' => ['int'],
'Yar_Server_Exception::getFile' => ['string'],
'Yar_Server_Exception::getLine' => ['int'],
'Yar_Server_Exception::getMessage' => ['string'],
'Yar_Server_Exception::getPrevious' => ['?Exception|?Throwable'],
'Yar_Server_Exception::getTrace' => ['array'],
'Yar_Server_Exception::getTraceAsString' => ['string'],
'Yar_Server_Exception::getType' => ['string'],
'yaz_addinfo' => ['string', 'id'=>'resource'],
'yaz_ccl_conf' => ['void', 'id'=>'resource', 'config'=>'array'],
'yaz_ccl_parse' => ['bool', 'id'=>'resource', 'query'=>'string', '&w_result'=>'array'],
'yaz_close' => ['bool', 'id'=>'resource'],
'yaz_connect' => ['mixed', 'zurl'=>'string', 'options='=>'mixed'],
'yaz_database' => ['bool', 'id'=>'resource', 'databases'=>'string'],
'yaz_element' => ['bool', 'id'=>'resource', 'elementset'=>'string'],
'yaz_errno' => ['int', 'id'=>'resource'],
'yaz_error' => ['string', 'id'=>'resource'],
'yaz_es' => ['void', 'id'=>'resource', 'type'=>'string', 'args'=>'array'],
'yaz_es_result' => ['array', 'id'=>'resource'],
'yaz_get_option' => ['string', 'id'=>'resource', 'name'=>'string'],
'yaz_hits' => ['int', 'id'=>'resource', 'searchresult='=>'array'],
'yaz_itemorder' => ['void', 'id'=>'resource', 'args'=>'array'],
'yaz_present' => ['bool', 'id'=>'resource'],
'yaz_range' => ['void', 'id'=>'resource', 'start'=>'int', 'number'=>'int'],
'yaz_record' => ['string', 'id'=>'resource', 'pos'=>'int', 'type'=>'string'],
'yaz_scan' => ['void', 'id'=>'resource', 'type'=>'string', 'startterm'=>'string', 'flags='=>'array'],
'yaz_scan_result' => ['array', 'id'=>'resource', 'result='=>'array'],
'yaz_schema' => ['void', 'id'=>'resource', 'schema'=>'string'],
'yaz_search' => ['bool', 'id'=>'resource', 'type'=>'string', 'query'=>'string'],
'yaz_set_option' => ['', 'id'=>'', 'name'=>'string', 'value'=>'string', 'options'=>'array'],
'yaz_sort' => ['void', 'id'=>'resource', 'criteria'=>'string'],
'yaz_syntax' => ['void', 'id'=>'resource', 'syntax'=>'string'],
'yaz_wait' => ['mixed', '&rw_options='=>'array'],
'yp_all' => ['void', 'domain'=>'string', 'map'=>'string', 'callback'=>'string'],
'yp_cat' => ['array', 'domain'=>'string', 'map'=>'string'],
'yp_err_string' => ['string', 'errorcode'=>'int'],
'yp_errno' => ['int'],
'yp_first' => ['array', 'domain'=>'string', 'map'=>'string'],
'yp_get_default_domain' => ['string'],
'yp_master' => ['string', 'domain'=>'string', 'map'=>'string'],
'yp_match' => ['string', 'domain'=>'string', 'map'=>'string', 'key'=>'string'],
'yp_next' => ['array', 'domain'=>'string', 'map'=>'string', 'key'=>'string'],
'yp_order' => ['int', 'domain'=>'string', 'map'=>'string'],
'zem_get_extension_info_by_id' => [''],
'zem_get_extension_info_by_name' => [''],
'zem_get_extensions_info' => [''],
'zem_get_license_info' => [''],
'zend_current_obfuscation_level' => ['int'],
'zend_disk_cache_clear' => ['bool', 'namespace='=>'mixed|string'],
'zend_disk_cache_delete' => ['mixed|null', 'key'=>'string'],
'zend_disk_cache_fetch' => ['mixed|null', 'key'=>'string'],
'zend_disk_cache_store' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int|mixed'],
'zend_get_id' => ['array', 'all_ids='=>'all_ids|false'],
'zend_is_configuration_changed' => [''],
'zend_loader_current_file' => ['string'],
'zend_loader_enabled' => ['bool'],
'zend_loader_file_encoded' => ['bool'],
'zend_loader_file_licensed' => ['array'],
'zend_loader_install_license' => ['bool', 'license_file'=>'string', 'override'=>'bool'],
'zend_logo_guid' => ['string'],
'zend_obfuscate_class_name' => ['string', 'class_name'=>'string'],
'zend_obfuscate_function_name' => ['string', 'function_name'=>'string'],
'zend_optimizer_version' => ['string'],
'zend_runtime_obfuscate' => ['void'],
'zend_send_buffer' => ['null|false', 'buffer'=>'string', 'mime_type='=>'string', 'custom_headers='=>'string'],
'zend_send_file' => ['null|false', 'filename'=>'string', 'mime_type='=>'string', 'custom_headers='=>'string'],
'zend_set_configuration_changed' => [''],
'zend_shm_cache_clear' => ['bool', 'namespace='=>'mixed|string'],
'zend_shm_cache_delete' => ['mixed|null', 'key'=>'string'],
'zend_shm_cache_fetch' => ['mixed|null', 'key'=>'string'],
'zend_shm_cache_store' => ['bool', 'key'=>'', 'value'=>'', 'ttl='=>'int|mixed'],
'zend_thread_id' => ['int'],
'zend_version' => ['string'],
'ZendAPI_Job::addJobToQueue' => ['int', 'jobqueue_url'=>'string', 'password'=>'string'],
'ZendAPI_Job::getApplicationID' => [''],
'ZendAPI_Job::getEndTime' => [''],
'ZendAPI_Job::getGlobalVariables' => [''],
'ZendAPI_Job::getHost' => [''],
'ZendAPI_Job::getID' => [''],
'ZendAPI_Job::getInterval' => [''],
'ZendAPI_Job::getJobDependency' => [''],
'ZendAPI_Job::getJobName' => [''],
'ZendAPI_Job::getJobPriority' => [''],
'ZendAPI_Job::getJobStatus' => ['int'],
'ZendAPI_Job::getLastPerformedStatus' => ['int'],
'ZendAPI_Job::getOutput' => ['An'],
'ZendAPI_Job::getPreserved' => [''],
'ZendAPI_Job::getProperties' => ['array'],
'ZendAPI_Job::getScheduledTime' => [''],
'ZendAPI_Job::getScript' => [''],
'ZendAPI_Job::getTimeToNextRepeat' => ['int'],
'ZendAPI_Job::getUserVariables' => [''],
'ZendAPI_Job::setApplicationID' => ['', 'app_id'=>''],
'ZendAPI_Job::setGlobalVariables' => ['', 'vars'=>''],
'ZendAPI_Job::setJobDependency' => ['', 'job_id'=>''],
'ZendAPI_Job::setJobName' => ['', 'name'=>''],
'ZendAPI_Job::setJobPriority' => ['', 'priority'=>'int'],
'ZendAPI_Job::setPreserved' => ['', 'preserved'=>''],
'ZendAPI_Job::setRecurrenceData' => ['', 'interval'=>'', 'end_time='=>'mixed'],
'ZendAPI_Job::setScheduledTime' => ['', 'timestamp'=>''],
'ZendAPI_Job::setScript' => ['', 'script'=>''],
'ZendAPI_Job::setUserVariables' => ['', 'vars'=>''],
'ZendAPI_Job::ZendAPI_Job' => ['Job', 'script'=>'script'],
'ZendAPI_Queue::addJob' => ['int', '&job'=>'Job'],
'ZendAPI_Queue::getAllApplicationIDs' => ['array'],
'ZendAPI_Queue::getAllhosts' => ['array'],
'ZendAPI_Queue::getHistoricJobs' => ['array', 'status'=>'int', 'start_time'=>'', 'end_time'=>'', 'index'=>'int', 'count'=>'int', '&total'=>'int'],
'ZendAPI_Queue::getJob' => ['Job', 'job_id'=>'int'],
'ZendAPI_Queue::getJobsInQueue' => ['array', 'filter_options='=>'array', 'max_jobs='=>'int', 'with_globals_and_output='=>'bool'],
'ZendAPI_Queue::getLastError' => ['string'],
'ZendAPI_Queue::getNumOfJobsInQueue' => ['int', 'filter_options='=>'array'],
'ZendAPI_Queue::getStatistics' => ['array'],
'ZendAPI_Queue::isScriptExists' => ['bool', 'path'=>'string'],
'ZendAPI_Queue::isSuspend' => ['bool'],
'ZendAPI_Queue::login' => ['bool', 'password'=>'string', 'application_id='=>'int'],
'ZendAPI_Queue::removeJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::requeueJob' => ['bool', 'job'=>'Job'],
'ZendAPI_Queue::resumeJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::resumeQueue' => ['bool'],
'ZendAPI_Queue::setMaxHistoryTime' => ['bool'],
'ZendAPI_Queue::suspendJob' => ['bool', 'job_id'=>'array|int'],
'ZendAPI_Queue::suspendQueue' => ['bool'],
'ZendAPI_Queue::updateJob' => ['int', '&job'=>'Job'],
'ZendAPI_Queue::zendapi_queue' => ['ZendAPI_Queue', 'queue_url'=>'string'],
'zip_close' => ['void', 'zip'=>'resource'],
'zip_entry_close' => ['bool', 'zip_ent'=>'resource'],
'zip_entry_compressedsize' => ['int', 'zip_entry'=>'resource'],
'zip_entry_compressionmethod' => ['string', 'zip_entry'=>'resource'],
'zip_entry_filesize' => ['int', 'zip_entry'=>'resource'],
'zip_entry_name' => ['string', 'zip_entry'=>'resource'],
'zip_entry_open' => ['bool', 'zip_dp'=>'resource', 'zip_entry'=>'resource', 'mode='=>'string'],
'zip_entry_read' => ['string|false', 'zip_entry'=>'resource', 'len='=>'int'],
'zip_open' => ['resource', 'filename'=>'string'],
'zip_read' => ['resource', 'zip'=>'resource'],
'ZipArchive::addEmptyDir' => ['bool', 'dirname'=>'string'],
'ZipArchive::addFile' => ['bool', 'filepath'=>'string', 'entryname='=>'string', 'start='=>'int', 'length='=>'int'],
'ZipArchive::addFromString' => ['bool', 'entryname'=>'string', 'content'=>'string'],
'ZipArchive::addGlob' => ['bool', 'pattern'=>'string', 'flags='=>'int', 'options='=>'array'],
'ZipArchive::addPattern' => ['bool', 'pattern'=>'string', 'path='=>'string', 'options='=>'array'],
'ZipArchive::close' => ['bool'],
'ZipArchive::count' => ['int'],
'ZipArchive::createEmptyDir' => ['bool', 'dirname'=>'string'],
'ZipArchive::deleteIndex' => ['bool', 'index'=>'int'],
'ZipArchive::deleteName' => ['bool', 'name'=>'string'],
'ZipArchive::extractTo' => ['bool', 'pathto'=>'string', 'files='=>'string[]|string'],
'ZipArchive::getArchiveComment' => ['string|false', 'flags='=>'int'],
'ZipArchive::getCommentIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getCommentName' => ['string|false', 'name'=>'string', 'flags='=>'int'],
'ZipArchive::getExternalAttributesIndex' => ['bool', 'index'=>'int', '&w_opsys'=>'int', '&w_attr'=>'int', 'flags='=>'int'],
'ZipArchive::getExternalAttributesName' => ['bool', 'name'=>'string', '&w_opsys'=>'int', '&w_attr'=>'int', 'flags='=>'int'],
'ZipArchive::getFromIndex' => ['string|false', 'index'=>'int', 'len='=>'int', 'flags='=>'int'],
'ZipArchive::getFromName' => ['string|false', 'entryname'=>'string', 'len='=>'int', 'flags='=>'int'],
'ZipArchive::getNameIndex' => ['string|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::getStatusString' => ['string|false'],
'ZipArchive::getStream' => ['resource|false', 'entryname'=>'string'],
'ZipArchive::locateName' => ['int|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::open' => ['mixed', 'source'=>'string', 'flags='=>'int'],
'ZipArchive::renameIndex' => ['bool', 'index'=>'int', 'new_name'=>'string'],
'ZipArchive::renameName' => ['bool', 'name'=>'string', 'new_name'=>'string'],
'ZipArchive::setArchiveComment' => ['bool', 'comment'=>'string'],
'ZipArchive::setCommentIndex' => ['bool', 'index'=>'int', 'comment'=>'string'],
'ZipArchive::setCommentName' => ['bool', 'name'=>'string', 'comment'=>'string'],
'ZipArchive::setCompressionIndex' => ['bool', 'index'=>'int', 'comp_method'=>'int', 'comp_flags='=>'int'],
'ZipArchive::setCompressionName' => ['bool', 'name'=>'string', 'comp_method'=>'int', 'comp_flags='=>'int'],
'ZipArchive::setEncryptionIndex' => ['bool', 'index'=>'int', 'method'=>'string', 'password='=>'string'],
'ZipArchive::setEncryptionName' => ['bool', 'name'=>'string', 'method'=>'int', 'password='=>'string'],
'ZipArchive::setExternalAttributesIndex' => ['bool', 'index'=>'int', 'opsys'=>'int', 'attr'=>'int', 'flags='=>'int'],
'ZipArchive::setExternalAttributesName' => ['bool', 'name'=>'string', 'opsys'=>'int', 'attr'=>'int', 'flags='=>'int'],
'ZipArchive::setPassword' => ['bool', 'password'=>'string'],
'ZipArchive::statIndex' => ['array|false', 'index'=>'int', 'flags='=>'int'],
'ZipArchive::statName' => ['array|false', 'filename'=>'string', 'flags='=>'int'],
'ZipArchive::unchangeAll' => ['bool'],
'ZipArchive::unchangeArchive' => ['bool'],
'ZipArchive::unchangeIndex' => ['bool', 'index'=>'int'],
'ZipArchive::unchangeName' => ['bool', 'name'=>'string'],
'zlib_decode' => ['string', 'data'=>'string', 'max_decoded_len='=>'int'],
'zlib_encode' => ['string', 'data'=>'string', 'encoding'=>'int', 'level='=>'string|int'],
'zlib_get_coding_type' => ['string|false'],
'ZMQ::__construct' => ['void'],
'ZMQContext::__construct' => ['void', 'io_threads='=>'int', 'is_persistent='=>'bool'],
'ZMQContext::getOpt' => ['int|string', 'key'=>'string'],
'ZMQContext::getSocket' => ['ZMQSocket', 'type'=>'int', 'persistent_id='=>'string', 'on_new_socket='=>'callable'],
'ZMQContext::isPersistent' => ['bool'],
'ZMQContext::setOpt' => ['ZMQContext', 'key'=>'int', 'value'=>'mixed'],
'ZMQDevice::__construct' => ['void', 'frontend'=>'ZMQSocket', 'backend'=>'ZMQSocket', 'listener='=>'ZMQSocket'],
'ZMQDevice::getIdleTimeout' => ['ZMQDevice'],
'ZMQDevice::getTimerTimeout' => ['ZMQDevice'],
'ZMQDevice::run' => ['void'],
'ZMQDevice::setIdleCallback' => ['ZMQDevice', 'cb_func'=>'callable', 'timeout'=>'int', 'user_data='=>'mixed'],
'ZMQDevice::setIdleTimeout' => ['ZMQDevice', 'timeout'=>'int'],
'ZMQDevice::setTimerCallback' => ['ZMQDevice', 'cb_func'=>'callable', 'timeout'=>'int', 'user_data='=>'mixed'],
'ZMQDevice::setTimerTimeout' => ['ZMQDevice', 'timeout'=>'int'],
'ZMQPoll::add' => ['string', 'entry'=>'mixed', 'type'=>'int'],
'ZMQPoll::clear' => ['ZMQPoll'],
'ZMQPoll::count' => ['int'],
'ZMQPoll::getLastErrors' => ['array'],
'ZMQPoll::poll' => ['int', '&w_readable'=>'array', '&w_writable'=>'array', 'timeout='=>'int'],
'ZMQPoll::remove' => ['bool', 'item'=>'mixed'],
'ZMQSocket::__construct' => ['void', 'context'=>'ZMQContext', 'type'=>'int', 'persistent_id='=>'string', 'on_new_socket='=>'callable'],
'ZMQSocket::bind' => ['ZMQSocket', 'dsn'=>'string', 'force='=>'bool'],
'ZMQSocket::connect' => ['ZMQSocket', 'dsn'=>'string', 'force='=>'bool'],
'ZMQSocket::disconnect' => ['ZMQSocket', 'dsn'=>'string'],
'ZMQSocket::getEndpoints' => ['array'],
'ZMQSocket::getPersistentId' => ['?string'],
'ZMQSocket::getSocketType' => ['int'],
'ZMQSocket::getSockOpt' => ['int|string', 'key'=>'string'],
'ZMQSocket::isPersistent' => ['bool'],
'ZMQSocket::recv' => ['string', 'mode='=>'int'],
'ZMQSocket::recvMulti' => ['string[]', 'mode='=>'int'],
'ZMQSocket::send' => ['ZMQSocket', 'message'=>'array', 'mode='=>'int'],
'ZMQSocket::send\'1' => ['ZMQSocket', 'message'=>'string', 'mode='=>'int'],
'ZMQSocket::sendmulti' => ['ZMQSocket', 'message'=>'array', 'mode='=>'int'],
'ZMQSocket::setSockOpt' => ['ZMQSocket', 'key'=>'int', 'value'=>'mixed'],
'ZMQSocket::unbind' => ['ZMQSocket', 'dsn'=>'string'],
'Zookeeper::addAuth' => ['bool', 'scheme'=>'string', 'cert'=>'string', 'completion_cb='=>'callable'],
'Zookeeper::close' => ['void'],
'Zookeeper::connect' => ['void', 'host'=>'string', 'watcher_cb='=>'callable', 'recv_timeout='=>'int'],
'Zookeeper::create' => ['string', 'path'=>'string', 'value'=>'string', 'acls'=>'array', 'flags='=>'int'],
'Zookeeper::delete' => ['bool', 'path'=>'string', 'version='=>'int'],
'Zookeeper::exists' => ['bool', 'path'=>'string', 'watcher_cb='=>'callable'],
'Zookeeper::get' => ['string', 'path'=>'string', 'watcher_cb='=>'callable', 'stat='=>'array', 'max_size='=>'int'],
'Zookeeper::getAcl' => ['array', 'path'=>'string'],
'Zookeeper::getChildren' => ['array|false', 'path'=>'string', 'watcher_cb='=>'callable'],
'Zookeeper::getClientId' => ['int'],
'Zookeeper::getConfig' => ['ZookeeperConfig'],
'Zookeeper::getRecvTimeout' => ['int'],
'Zookeeper::getState' => ['int'],
'Zookeeper::isRecoverable' => ['bool'],
'Zookeeper::set' => ['bool', 'path'=>'string', 'value'=>'string', 'version='=>'int', 'stat='=>'array'],
'Zookeeper::setAcl' => ['bool', 'path'=>'string', 'version'=>'int', 'acl'=>'array'],
'Zookeeper::setDebugLevel' => ['bool', 'logLevel'=>'int'],
'Zookeeper::setDeterministicConnOrder' => ['bool', 'yesOrNo'=>'bool'],
'Zookeeper::setLogStream' => ['bool', 'stream'=>'resource'],
'Zookeeper::setWatcher' => ['bool', 'watcher_cb'=>'callable'],
'zookeeper_dispatch' => ['void'],
'ZookeeperConfig::add' => ['void', 'members'=>'string', 'version='=>'int', 'stat='=>'array'],
'ZookeeperConfig::get' => ['string', 'watcher_cb='=>'callable', 'stat='=>'array'],
'ZookeeperConfig::remove' => ['void', 'id_list'=>'string', 'version='=>'int', 'stat='=>'array'],
'ZookeeperConfig::set' => ['void', 'members'=>'string', 'version='=>'int', 'stat='=>'array'],
];
| 1 | 8,173 | I missed the $preserve_keys=true case when adding this to Phan. For psalm, two separate signatures may make sense | vimeo-psalm | php |
@@ -18,14 +18,19 @@
package org.apache.servicecomb.foundation.vertx.server;
import java.net.InetSocketAddress;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.servicecomb.foundation.common.event.EventManager;
import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
import org.apache.servicecomb.foundation.ssl.SSLCustom;
import org.apache.servicecomb.foundation.ssl.SSLOption;
import org.apache.servicecomb.foundation.ssl.SSLOptionFactory;
import org.apache.servicecomb.foundation.vertx.AsyncResultCallback;
+import org.apache.servicecomb.foundation.vertx.ClientConnectedEvent;
import org.apache.servicecomb.foundation.vertx.VertxTLSBuilder;
+import com.netflix.config.DynamicPropertyFactory;
+
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions; | 1 | /*
* 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.servicecomb.foundation.vertx.server;
import java.net.InetSocketAddress;
import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
import org.apache.servicecomb.foundation.ssl.SSLCustom;
import org.apache.servicecomb.foundation.ssl.SSLOption;
import org.apache.servicecomb.foundation.ssl.SSLOptionFactory;
import org.apache.servicecomb.foundation.vertx.AsyncResultCallback;
import org.apache.servicecomb.foundation.vertx.VertxTLSBuilder;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
public class TcpServer {
private URIEndpointObject endpointObject;
public TcpServer(URIEndpointObject endpointObject) {
this.endpointObject = endpointObject;
}
public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
NetServer netServer;
if (endpointObject.isSslEnabled()) {
SSLOptionFactory factory =
SSLOptionFactory.createSSLOptionFactory(sslKey, null);
SSLOption sslOption;
if (factory == null) {
sslOption = SSLOption.buildFromYaml(sslKey);
} else {
sslOption = factory.createSSLOption();
}
SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
NetServerOptions serverOptions = new NetServerOptions();
VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
netServer = vertx.createNetServer(serverOptions);
} else {
netServer = vertx.createNetServer();
}
netServer.connectHandler(netSocket -> {
TcpServerConnection connection = createTcpServerConnection();
connection.init(netSocket);
});
InetSocketAddress socketAddress = endpointObject.getSocketAddress();
netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
if (ar.succeeded()) {
callback.success(socketAddress);
return;
}
// 监听失败
String msg = String.format("listen failed, address=%s", socketAddress.toString());
callback.fail(new Exception(msg, ar.cause()));
});
}
protected TcpServerConnection createTcpServerConnection() {
return new TcpServerConnection();
}
}
| 1 | 10,046 | TcpServer will be created for each HighwayServerVerticle instance so the counter number in server is not correct. | apache-servicecomb-java-chassis | java |
@@ -109,10 +109,14 @@ public class WindowsUtils {
* quote (\"?)
*/
// TODO We should be careful, in case Windows has ~1-ified the executable name as well
- pattern.append("\"?.*?\\\\");
- pattern.append(executable.getName());
+ pattern.append("(\"?.*?\\\\)?");
+ String execName = executable.getName();
+ pattern.append(execName);
+ if (!execName.endsWith(".exe")) {
+ pattern.append("(\\.exe)?");
+ }
pattern.append("\"?");
- for (String arg : cmdarray) {
+ for (int i = 1; i < cmdarray.length; i++) {
/*
* There may be a space, but maybe not (\\s?), may be a quote or maybe not (\"?), but then
* turn on block quotation (as if *everything* had a regex backslash in front of it) with \Q. | 1 | /*
* Copyright 2011 Software Freedom Conservancy.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.openqa.selenium.os;
import static org.openqa.selenium.Platform.WINDOWS;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.openqa.selenium.Platform;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilderFactory;
public class WindowsUtils {
public static Boolean regVersion1 = null;
private static Logger LOG = Logger.getLogger(WindowsUtils.class.getName());
private static final boolean THIS_IS_WINDOWS = Platform.getCurrent().is(WINDOWS);
private static String wmic = null;
private static File wbem = null;
private static String taskkill = null;
private static String reg = null;
private static Properties env = null;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Kills Windows processes by matching their command lines");
System.out.println("usage: " + WindowsUtils.class.getName() + " command arg1 arg2 ...");
}
kill(args);
}
public static void traceWith(Logger log) {
WindowsUtils.LOG = log;
}
/**
* Kill processes by name
*/
public static void killByName(String name) {
executeCommand("taskkill", "/f", "/t", "/im", name);
}
/**
* Kill processes by name, log and ignore errors
*/
public static void tryToKillByName(String name) {
if (!thisIsWindows()) {
return;
}
try {
killByName(name);
} catch (WindowsRegistryException e) {
LOG.log(Level.WARNING, "Exception thrown", e);
}
}
/**
* Searches the process list for a process with the specified command line and kills it
*
* @param cmdarray the array of command line arguments
* @throws Exception if something goes wrong while reading the process list or searching for your
* command line
*/
public static void kill(String[] cmdarray) throws Exception {
StringBuilder pattern = new StringBuilder();
File executable = new File(cmdarray[0]);
/*
* For the first argument, the executable, Windows may modify the start path in any number of
* ways. Ignore a starting quote if any (\"?), non-greedily look for anything up until the last
* backslash (.*?\\\\), then look for the executable's filename, then finally ignore a final
* quote (\"?)
*/
// TODO We should be careful, in case Windows has ~1-ified the executable name as well
pattern.append("\"?.*?\\\\");
pattern.append(executable.getName());
pattern.append("\"?");
for (String arg : cmdarray) {
/*
* There may be a space, but maybe not (\\s?), may be a quote or maybe not (\"?), but then
* turn on block quotation (as if *everything* had a regex backslash in front of it) with \Q.
* Then look for the next argument (which may have ?s, \s, "s, who knows), turning off block
* quotation. Now ignore a final quote if any (\"?)
*/
pattern.append("\\s?\"?\\Q");
pattern.append(arg);
pattern.append("\\E\"?");
}
pattern.append("\\s*");
Pattern cmd = Pattern.compile(pattern.toString(), Pattern.CASE_INSENSITIVE);
Map<String, String> procMap = procMap();
boolean killedOne = false;
for (String commandLine : procMap.keySet()) {
if (commandLine == null) {
continue;
}
Matcher m = cmd.matcher(commandLine);
if (m.matches()) {
String processID = procMap.get(commandLine);
StringBuilder logMessage = new StringBuilder("Killing PID ");
logMessage.append(processID);
logMessage.append(": ");
logMessage.append(commandLine);
LOG.info(logMessage.toString());
killPID(processID);
LOG.info("Killed");
killedOne = true;
}
}
if (!killedOne) {
StringBuilder errorMessage = new StringBuilder("Didn't find any matches for");
for (String arg : cmdarray) {
errorMessage.append(" '");
errorMessage.append(arg);
errorMessage.append('\'');
}
LOG.warning(errorMessage.toString());
}
}
/**
* Kills the specified process ID
*/
private static void killPID(String processID) {
executeCommand("taskkill", "/f", "/pid", processID);
}
/**
* Returns a map of process IDs to command lines
*
* @return a map of process IDs to command lines
* @throws Exception - if something goes wrong while reading the process list
*/
public static Map<String, String> procMap() throws Exception {
LOG.info("Reading Windows Process List...");
String output = executeCommand(findWMIC(), "process", "list", "full", "/format:rawxml.xsl");
// exec.setFailonerror(true);
LOG.info("Done, searching for processes to kill...");
// WMIC drops an ugly zero-length batch file; clean that up
File tempWmicBatchFile = new File("TempWmicBatchFile.bat");
if (tempWmicBatchFile.exists()) {
tempWmicBatchFile.delete();
}
// TODO This would be faster if it used SAX instead of DOM
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(output.getBytes()));
NodeList procList = doc.getElementsByTagName("INSTANCE");
Map<String, String> processes = new HashMap<String, String>();
for (int i = 0; i < procList.getLength(); i++) {
Element process = (Element) procList.item(i);
NodeList propList = process.getElementsByTagName("PROPERTY");
Map<String, String> procProps = new HashMap<String, String>();
for (int j = 0; j < propList.getLength(); j++) {
Element property = (Element) propList.item(j);
String propName = property.getAttribute("NAME");
NodeList valList = property.getElementsByTagName("VALUE");
String value = null;
if (valList.getLength() != 0) {
Element valueElement = (Element) valList.item(0);
Text valueNode = (Text) valueElement.getFirstChild();
value = valueNode.getData();
}
procProps.put(propName, value);
}
String processID = procProps.get("ProcessId");
String commandLine = procProps.get("CommandLine");
processes.put(commandLine, processID);
}
return processes;
}
/**
* Returns the current process environment variables
*
* @return the current process environment variables
*/
public static synchronized Properties loadEnvironment() {
if (env != null) {
return env;
}
env = new Properties();
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
env.put(entry.getKey(), entry.getValue());
}
return env;
}
/**
* Returns the path to the Windows Program Files. On non-English versions, this is not necessarily
* "C:\Program Files".
*
* @return the path to the Windows Program Files
*/
public static String getProgramFilesPath() {
return getEnvVarPath("ProgramFiles", "C:\\Program Files");
}
public static String getProgramFiles86Path() {
return getEnvVarPath("ProgramFiles(x86)", "C:\\Program Files (x86)");
}
private static String getEnvVarPath(final String envVar, final String defaultValue) {
String pf = getEnvVarIgnoreCase(envVar);
if (pf != null) {
File programFiles = new File(pf);
if (programFiles.exists()) {
return programFiles.getAbsolutePath();
}
}
return new File(defaultValue).getAbsolutePath();
}
public static ImmutableList<String> getPathsInProgramFiles(final String childPath) {
return new ImmutableList.Builder<String>()
.add(getFullPath(WindowsUtils.getProgramFilesPath(), childPath))
.add(getFullPath(WindowsUtils.getProgramFiles86Path(), childPath))
.build();
}
private static String getFullPath(String parent, String child) {
return new File(parent, child).getAbsolutePath();
}
/**
* Returns the path to Local AppData. For different users, this will be different.
*
* @return the path to Local AppData
*/
public static String getLocalAppDataPath() {
final String keyLocalAppData =
"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\\Local AppData";
String localAppDataPath = readStringRegistryValue(keyLocalAppData);
String userProfile = getEnvVarIgnoreCase("USERPROFILE");
if (userProfile != null) {
return localAppDataPath.replace("%USERPROFILE%", userProfile);
}
return localAppDataPath;
}
public static String getEnvVarIgnoreCase(String var) {
Properties p = loadEnvironment();
for (String key : p.stringPropertyNames()) {
if (key.equalsIgnoreCase(var)) {
return env.getProperty(key);
}
}
return null;
}
/**
* Finds the system root directory, e.g. "c:\windows" or "c:\winnt"
*/
public static File findSystemRoot() {
Properties p = loadEnvironment();
String systemRootPath = p.getProperty("SystemRoot");
if (systemRootPath == null) {
systemRootPath = p.getProperty("SYSTEMROOT");
}
if (systemRootPath == null) {
systemRootPath = p.getProperty("systemroot");
}
if (systemRootPath == null) {
throw new RuntimeException("SystemRoot apparently not set!");
}
File systemRoot = new File(systemRootPath);
if (!systemRoot.exists()) {
throw new RuntimeException("SystemRoot doesn't exist: " + systemRootPath);
}
return systemRoot;
}
/**
* Finds WMIC.exe
*
* @return the exact path to wmic.exe, or just the string "wmic" if it couldn't be found (in which
* case you can pass that to exec to try to run it from the path)
*/
public static String findWMIC() {
if (wmic != null) {
return wmic;
}
findWBEM();
if (null != wbem) {
File wmicExe = new File(findWBEM(), "wmic.exe");
if (wmicExe.exists()) {
wmic = wmicExe.getAbsolutePath();
return wmic;
}
}
LOG.warning("Couldn't find wmic! Hope it's on the path...");
wmic = "wmic";
return wmic;
}
/**
* Finds the WBEM directory in the systemRoot directory
*
* @return the WBEM directory, or <code>null</code> if it couldn't be found
*/
public static File findWBEM() {
if (wbem != null) {
return wbem;
}
File systemRoot = findSystemRoot();
wbem = new File(systemRoot, "system32/wbem");
if (!wbem.exists()) {
LOG.severe("Couldn't find wbem!");
return null;
}
return wbem;
}
/**
* Finds taskkill.exe
*
* @return the exact path to taskkill.exe, or just the string "taskkill" if it couldn't be found
* (in which case you can pass that to exec to try to run it from the path)
*/
public static String findTaskKill() {
if (taskkill != null) {
return taskkill;
}
File systemRoot = findSystemRoot();
File taskkillExe = new File(systemRoot, "system32/taskkill.exe");
if (taskkillExe.exists()) {
taskkill = taskkillExe.getAbsolutePath();
return taskkill;
}
LOG.warning("Couldn't find taskkill! Hope it's on the path...");
taskkill = "taskkill";
return taskkill;
}
/**
* Finds reg.exe
*
* @return the exact path to reg.exe, or just the string "reg" if it couldn't be found (in which
* case you can pass that to exec to try to run it from the path)
*/
public static String findReg() {
if (reg != null) {
return reg;
}
File systemRoot = findSystemRoot();
File regExe = new File(systemRoot, "system32/reg.exe");
if (regExe.exists()) {
reg = regExe.getAbsolutePath();
return reg;
}
regExe = new File("c:\\ntreskit\\reg.exe");
if (regExe.exists()) {
reg = regExe.getAbsolutePath();
return reg;
}
reg = new ExecutableFinder().find("reg.exe");
if (reg != null) {
return reg;
}
LOG.severe("OS Version: " + System.getProperty("os.version"));
throw new WindowsRegistryException("Couldn't find reg.exe!\n" +
"Please download it from Microsoft and install it in a standard location.\n"
+
"See here for details: http://wiki.openqa.org/display/SRC/Windows+Registry+Support");
}
public static boolean isRegExeVersion1() {
if (regVersion1 != null) {
return regVersion1.booleanValue();
}
String output = executeCommand(findReg(), "/?");
boolean version1 = output.indexOf("version 1.0") != -1;
regVersion1 = Boolean.valueOf(version1);
return version1;
}
public static Class<?> discoverRegistryKeyType(String key) {
if (!doesRegistryValueExist(key)) {
return null;
}
RegKeyValue r = new RegKeyValue(key);
String output = runRegQuery(key);
Pattern pat;
if (isRegExeVersion1()) {
pat = Pattern.compile("\\s*(REG_\\S+)");
} else {
pat = Pattern.compile("\\Q" + r.value + "\\E\\s+(REG_\\S+)\\s+(.*)");
}
Matcher m = pat.matcher(output);
if (!m.find()) {
throw new WindowsRegistryException("Output didn't look right: " + output);
}
String type = m.group(1);
if ("REG_SZ".equals(type) || "REG_EXPAND_SZ".equals(type)) {
return String.class;
} else if ("REG_DWORD".equals(type)) {
return int.class;
} else {
throw new WindowsRegistryException("Unknown type: " + type);
}
}
public static String readStringRegistryValue(String key) {
RegKeyValue r = new RegKeyValue(key);
String output = runRegQuery(key);
Pattern pat;
if (isRegExeVersion1()) {
pat = Pattern.compile("\\s*(REG_\\S+)\\s+\\Q" + r.value + "\\E\\s+(.*)");
} else {
pat = Pattern.compile("\\Q" + r.value + "\\E\\s+(REG_\\S+)\\s+(.*)");
}
Matcher m = pat.matcher(output);
if (!m.find()) {
throw new WindowsRegistryException("Output didn't look right: " + output);
}
String type = m.group(1);
if (!"REG_SZ".equals(type) && !"REG_EXPAND_SZ".equals(type)) {
throw new WindowsRegistryException(
r.value + " was not a REG_SZ or a REG_EXPAND_SZ (String): " + type);
}
return m.group(2);
}
public static int readIntRegistryValue(String key) {
RegKeyValue r = new RegKeyValue(key);
String output = runRegQuery(key);
Pattern pat;
if (isRegExeVersion1()) {
pat = Pattern.compile("\\s*(REG_\\S+)\\s+\\Q" + r.value + "\\E\\s+(.*)");
} else {
pat = Pattern.compile("\\Q" + r.value + "\\E\\s+(REG_\\S+)\\s+0x(.*)");
}
Matcher m = pat.matcher(output);
if (!m.find()) {
throw new WindowsRegistryException("Output didn't look right: " + output);
}
String type = m.group(1);
if (!"REG_DWORD".equals(type)) {
throw new WindowsRegistryException(r.value + " was not a REG_DWORD (int): " + type);
}
String strValue = m.group(2);
int value;
if (isRegExeVersion1()) {
value = Integer.parseInt(strValue);
} else {
value = Integer.parseInt(strValue, 16);
}
return value;
}
public static boolean readBooleanRegistryValue(String key) {
RegKeyValue r = new RegKeyValue(key);
int value = readIntRegistryValue(key);
if (0 == value) {
return false;
}
if (1 == value) {
return true;
}
throw new WindowsRegistryException(r.value + " was not either 0 or 1: " + value);
}
public static boolean doesRegistryValueExist(String key) {
List<String> args = Lists.newArrayList();
args.add("query");
if (isRegExeVersion1()) {
args.add(key);
} else {
RegKeyValue r = new RegKeyValue(key);
args.add(r.key);
args.add("/v");
args.add(r.value);
}
try {
executeCommand(findReg(), args.toArray(new String[args.size()]));
return true;
} catch (WindowsRegistryException e) {
return false;
}
}
public static void writeStringRegistryValue(String key, String data)
throws WindowsRegistryException {
List<String> args = new ArrayList<String>();
if (isRegExeVersion1()) {
if (doesRegistryValueExist(key)) {
args.add("update");
} else {
args.add("add");
}
args.add(key + "=" + data);
} else {
args.add("add");
RegKeyValue r = new RegKeyValue(key);
args.add(r.key);
args.add("/v");
args.add(r.value);
args.add("/d");
args.add(data);
args.add("/f");
}
executeCommand(findReg(), args.toArray(new String[args.size()]));
}
private static String executeCommand(String commandName, String... args) {
CommandLine cmd = new CommandLine(commandName, args);
cmd.execute();
String output = cmd.getStdOut();
if (!cmd.isSuccessful()) {
throw new WindowsRegistryException("exec return code " + cmd.getExitCode() + ": " + output);
}
return output;
}
public static void writeIntRegistryValue(String key, int data) {
List<String> args = new ArrayList<String>();
if (isRegExeVersion1()) {
if (doesRegistryValueExist(key)) {
args.add("update");
args.add(key + "=" + Integer.toString(data));
} else {
args.add("add");
args.add(key + "=" + Integer.toString(data));
args.add("REG_DWORD");
}
} else {
args.add("add");
RegKeyValue r = new RegKeyValue(key);
args.add(r.key);
args.add("/v");
args.add(r.value);
args.add("/t");
args.add("REG_DWORD");
args.add("/d");
args.add(Integer.toString(data));
args.add("/f");
}
executeCommand(findReg(), args.toArray(new String[args.size()]));
}
public static void writeBooleanRegistryValue(String key, boolean data) {
writeIntRegistryValue(key, data ? 1 : 0);
}
public static void deleteRegistryValue(String key) {
List<String> args = new ArrayList<String>();
if (isRegExeVersion1()) {
args.add("delete");
args.add(key);
args.add("/FORCE");
} else {
RegKeyValue r = new RegKeyValue(key);
args.add("delete");
args.add(r.key);
args.add("/v");
args.add(r.value);
args.add("/f");
}
executeCommand(findReg(), args.toArray(new String[args.size()]));
}
/**
* Executes reg.exe to query the registry
*/
private static String runRegQuery(String key) {
List<String> args = new ArrayList<String>();
args.add("query");
if (isRegExeVersion1()) {
args.add(key);
} else {
RegKeyValue r = new RegKeyValue(key);
args.add(r.key);
args.add("/v");
args.add(r.value);
}
return executeCommand(findReg(), args.toArray(new String[args.size()]));
}
private static class RegKeyValue {
private String key;
private String value;
public RegKeyValue(String path) {
int i = path.lastIndexOf('\\');
key = path.substring(0, i);
value = path.substring(i + 1);
}
}
/**
* Returns true if the current OS is MS Windows; false otherwise
*
* @return true if the current OS is MS Windows; false otherwise
*/
public static boolean thisIsWindows() {
return THIS_IS_WINDOWS;
}
}
| 1 | 10,241 | Why change this from a foreach? I can't see it gaining anything here and code styles shouldn't change just for the sake of it. | SeleniumHQ-selenium | py |
@@ -116,6 +116,12 @@ func FindCgroupMountpoint(cgroupPath, subsystem string) (string, error) {
return "", errUnified
}
+ // If subsystem is empty it means that we are looking for the
+ // cgroups2 path
+ if len(subsystem) == 0 {
+ return hybridMountpoint, nil
+ }
+
// Avoid parsing mountinfo by trying the default path first, if possible.
if path := tryDefaultPath(cgroupPath, subsystem); path != "" {
return path, nil | 1 | package cgroups
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/moby/sys/mountinfo"
"golang.org/x/sys/unix"
)
// Code in this source file are specific to cgroup v1,
// and must not be used from any cgroup v2 code.
const (
CgroupNamePrefix = "name="
defaultPrefix = "/sys/fs/cgroup"
)
var (
errUnified = errors.New("not implemented for cgroup v2 unified hierarchy")
ErrV1NoUnified = errors.New("invalid configuration: cannot use unified on cgroup v1")
readMountinfoOnce sync.Once
readMountinfoErr error
cgroupMountinfo []*mountinfo.Info
)
type NotFoundError struct {
Subsystem string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("mountpoint for %s not found", e.Subsystem)
}
func NewNotFoundError(sub string) error {
return &NotFoundError{
Subsystem: sub,
}
}
func IsNotFound(err error) bool {
if err == nil {
return false
}
_, ok := err.(*NotFoundError)
return ok
}
func tryDefaultPath(cgroupPath, subsystem string) string {
if !strings.HasPrefix(defaultPrefix, cgroupPath) {
return ""
}
// remove possible prefix
subsystem = strings.TrimPrefix(subsystem, CgroupNamePrefix)
// Make sure we're still under defaultPrefix, and resolve
// a possible symlink (like cpu -> cpu,cpuacct).
path, err := securejoin.SecureJoin(defaultPrefix, subsystem)
if err != nil {
return ""
}
// (1) path should be a directory.
st, err := os.Lstat(path)
if err != nil || !st.IsDir() {
return ""
}
// (2) path should be a mount point.
pst, err := os.Lstat(filepath.Dir(path))
if err != nil {
return ""
}
if st.Sys().(*syscall.Stat_t).Dev == pst.Sys().(*syscall.Stat_t).Dev {
// parent dir has the same dev -- path is not a mount point
return ""
}
// (3) path should have 'cgroup' fs type.
fst := unix.Statfs_t{}
err = unix.Statfs(path, &fst)
if err != nil || fst.Type != unix.CGROUP_SUPER_MAGIC {
return ""
}
return path
}
// readCgroupMountinfo returns a list of cgroup v1 mounts (i.e. the ones
// with fstype of "cgroup") for the current running process.
//
// The results are cached (to avoid re-reading mountinfo which is relatively
// expensive), so it is assumed that cgroup mounts are not being changed.
func readCgroupMountinfo() ([]*mountinfo.Info, error) {
readMountinfoOnce.Do(func() {
cgroupMountinfo, readMountinfoErr = mountinfo.GetMounts(
mountinfo.FSTypeFilter("cgroup"),
)
})
return cgroupMountinfo, readMountinfoErr
}
// https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt
func FindCgroupMountpoint(cgroupPath, subsystem string) (string, error) {
if IsCgroup2UnifiedMode() {
return "", errUnified
}
// Avoid parsing mountinfo by trying the default path first, if possible.
if path := tryDefaultPath(cgroupPath, subsystem); path != "" {
return path, nil
}
mnt, _, err := FindCgroupMountpointAndRoot(cgroupPath, subsystem)
return mnt, err
}
func FindCgroupMountpointAndRoot(cgroupPath, subsystem string) (string, string, error) {
if IsCgroup2UnifiedMode() {
return "", "", errUnified
}
mi, err := readCgroupMountinfo()
if err != nil {
return "", "", err
}
return findCgroupMountpointAndRootFromMI(mi, cgroupPath, subsystem)
}
func findCgroupMountpointAndRootFromMI(mounts []*mountinfo.Info, cgroupPath, subsystem string) (string, string, error) {
for _, mi := range mounts {
if strings.HasPrefix(mi.Mountpoint, cgroupPath) {
for _, opt := range strings.Split(mi.VFSOptions, ",") {
if opt == subsystem {
return mi.Mountpoint, mi.Root, nil
}
}
}
}
return "", "", NewNotFoundError(subsystem)
}
func (m Mount) GetOwnCgroup(cgroups map[string]string) (string, error) {
if len(m.Subsystems) == 0 {
return "", fmt.Errorf("no subsystem for mount")
}
return getControllerPath(m.Subsystems[0], cgroups)
}
func getCgroupMountsHelper(ss map[string]bool, mounts []*mountinfo.Info, all bool) ([]Mount, error) {
res := make([]Mount, 0, len(ss))
numFound := 0
for _, mi := range mounts {
m := Mount{
Mountpoint: mi.Mountpoint,
Root: mi.Root,
}
for _, opt := range strings.Split(mi.VFSOptions, ",") {
seen, known := ss[opt]
if !known || (!all && seen) {
continue
}
ss[opt] = true
opt = strings.TrimPrefix(opt, CgroupNamePrefix)
m.Subsystems = append(m.Subsystems, opt)
numFound++
}
if len(m.Subsystems) > 0 || all {
res = append(res, m)
}
if !all && numFound >= len(ss) {
break
}
}
return res, nil
}
func getCgroupMountsV1(all bool) ([]Mount, error) {
mi, err := readCgroupMountinfo()
if err != nil {
return nil, err
}
allSubsystems, err := ParseCgroupFile("/proc/self/cgroup")
if err != nil {
return nil, err
}
allMap := make(map[string]bool)
for s := range allSubsystems {
allMap[s] = false
}
return getCgroupMountsHelper(allMap, mi, all)
}
// GetOwnCgroup returns the relative path to the cgroup docker is running in.
func GetOwnCgroup(subsystem string) (string, error) {
if IsCgroup2UnifiedMode() {
return "", errUnified
}
cgroups, err := ParseCgroupFile("/proc/self/cgroup")
if err != nil {
return "", err
}
return getControllerPath(subsystem, cgroups)
}
func GetOwnCgroupPath(subsystem string) (string, error) {
cgroup, err := GetOwnCgroup(subsystem)
if err != nil {
return "", err
}
return getCgroupPathHelper(subsystem, cgroup)
}
func GetInitCgroup(subsystem string) (string, error) {
if IsCgroup2UnifiedMode() {
return "", errUnified
}
cgroups, err := ParseCgroupFile("/proc/1/cgroup")
if err != nil {
return "", err
}
return getControllerPath(subsystem, cgroups)
}
func GetInitCgroupPath(subsystem string) (string, error) {
cgroup, err := GetInitCgroup(subsystem)
if err != nil {
return "", err
}
return getCgroupPathHelper(subsystem, cgroup)
}
func getCgroupPathHelper(subsystem, cgroup string) (string, error) {
mnt, root, err := FindCgroupMountpointAndRoot("", subsystem)
if err != nil {
return "", err
}
// This is needed for nested containers, because in /proc/self/cgroup we
// see paths from host, which don't exist in container.
relCgroup, err := filepath.Rel(root, cgroup)
if err != nil {
return "", err
}
return filepath.Join(mnt, relCgroup), nil
}
func getControllerPath(subsystem string, cgroups map[string]string) (string, error) {
if IsCgroup2UnifiedMode() {
return "", errUnified
}
if p, ok := cgroups[subsystem]; ok {
return p, nil
}
if p, ok := cgroups[CgroupNamePrefix+subsystem]; ok {
return p, nil
}
return "", NewNotFoundError(subsystem)
}
| 1 | 17,854 | I'd say "cgroup2 hybrid path" instead. | opencontainers-runc | go |
@@ -84,15 +84,12 @@ module Bolt
{
'name' => name,
'uri' => uri,
- 'alias' => @target_alias,
- 'config' => config.merge(
- 'transport' => transport,
- transport => options
- ),
+ 'alias' => target_alias,
+ 'config' => Bolt::Util.deep_merge(config, 'transport' => transport, transport => options),
'vars' => vars,
'features' => features,
'facts' => facts,
- 'plugin_hooks' => Bolt::Util.deep_clone(plugin_hooks)
+ 'plugin_hooks' => plugin_hooks
}
end
| 1 | # frozen_string_literal: true
require 'bolt/error'
require 'bolt/util'
module Bolt
class Target2
attr_accessor :inventory
# Target.new from a plan initialized with a hash
def self.from_asserted_hash(hash)
inventory = Puppet.lookup(:bolt_inventory)
target = inventory.create_target_from_plan(hash)
new(target.name, inventory)
end
# Target.new from a plan with just a uri. Puppet requires the arguments to
# this method to match (by name) the attributes defined on the datatype.
# rubocop:disable Lint/UnusedMethodArgument
def self.from_asserted_args(uri = nil,
name = nil,
target_alias = nil,
config = nil,
facts = nil,
vars = nil,
features = nil,
plugin_hooks = nil)
from_asserted_hash('uri' => uri)
end
def initialize(name, inventory = nil)
@name = name
@inventory = inventory
end
# rubocop:enable Lint/UnusedMethodArgument
# features returns an array to be compatible with plans
def features
@inventory.features(self).to_a
end
# Use feature_set internally to access set
def feature_set
@inventory.features(self)
end
def vars
@inventory.vars(self)
end
def facts
@inventory.facts(self)
end
def to_s
safe_name
end
def config
inventory_target.config
end
def safe_name
inventory_target.safe_name
end
def target_alias
inventory_target.target_alias
end
def to_h
options.merge(
'name' => name,
'uri' => uri,
'protocol' => protocol,
'user' => user,
'password' => password,
'host' => host,
'port' => port
)
end
def detail
{
'name' => name,
'uri' => uri,
'alias' => @target_alias,
'config' => config.merge(
'transport' => transport,
transport => options
),
'vars' => vars,
'features' => features,
'facts' => facts,
'plugin_hooks' => Bolt::Util.deep_clone(plugin_hooks)
}
end
def inventory_target
@inventory.targets[@name]
end
def host
inventory_target.host
end
attr_reader :name
def uri
inventory_target.uri
end
def remote?
protocol == 'remote'
end
def port
inventory_target.port
end
def transport
inventory_target.protocol
end
def protocol
inventory_target.protocol
end
def user
inventory_target.user
end
def password
inventory_target.password
end
def options
inventory_target.options
end
def plugin_hooks
inventory_target.plugin_hooks
end
def eql?(other)
self.class.equal?(other.class) && @name == other.name
end
alias == eql?
end
class Target
attr_reader :options
# CODEREVIEW: this feels wrong. The altertative is threading inventory through the
# executor to the RemoteTransport
attr_accessor :uri, :inventory
PRINT_OPTS ||= %w[host user port protocol].freeze
# Satisfies the Puppet datatypes API
def self.from_asserted_hash(hash)
new(hash['uri'], hash['options'])
end
# URI can be passes as nil
def initialize(uri, options = nil)
# lazy-load expensive gem code
require 'addressable/uri'
@uri = uri
@uri_obj = parse(uri)
@options = options || {}
@options.freeze
if @options['user']
@user = @options['user']
end
if @options['password']
@password = @options['password']
end
if @options['port']
@port = @options['port']
end
if @options['protocol']
@protocol = @options['protocol']
end
if @options['host']
@host = @options['host']
end
# WARNING: name should never be updated
@name = @options['name'] || @uri
end
def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can easily create copies of a Target.
@options = t_conf.merge(@options)
self
end
def parse(string)
if string.nil?
nil
elsif string =~ %r{^[^:]+://}
Addressable::URI.parse(string)
else
# Initialize with an empty scheme to ensure we parse the hostname correctly
Addressable::URI.parse("//#{string}")
end
rescue Addressable::URI::InvalidURIError => e
raise Bolt::ParseError, "Could not parse target URI: #{e.message}"
end
private :parse
def features
if @inventory
@inventory.features(self)
else
Set.new
end
end
alias feature_set features
def plugin_hooks
if @inventory
@inventory.plugin_hooks(self)
else
{}
end
end
def vars
@inventory.vars(self)
end
def facts
@inventory.facts(self)
end
# TODO: WHAT does equality mean here?
# should we just compare names? is there something else that is meaninful?
def eql?(other)
if self.class.equal?(other.class)
@uri ? @uri == other.uri : @name == other.name
else
false
end
end
alias == eql?
def hash
@uri.hash ^ @options.hash
end
def to_s
opts = @options.select { |k, _| PRINT_OPTS.include? k }
"Target('#{@uri}', #{opts})"
end
def to_h
options.merge(
'name' => name,
'uri' => uri,
'protocol' => protocol,
'user' => user,
'password' => password,
'host' => host,
'port' => port
)
end
def detail
{
'name' => name,
'uri' => uri,
'alias' => @target_alias,
'config' => {
'transport' => transport,
transport => options
},
'vars' => vars,
'facts' => facts,
'features' => features.to_a,
'plugin_hooks' => Bolt::Util.deep_clone(plugin_hooks)
}
end
def host
@uri_obj&.hostname || @host
end
alias safe_name host
def name
@name || @uri
end
def remote?
@uri_obj&.scheme == 'remote' || @protocol == 'remote'
end
def port
@uri_obj&.port || @port
end
# transport is separate from protocol for remote targets.
def transport
remote? ? 'remote' : protocol
end
def protocol
@uri_obj&.scheme || @protocol
end
def user
Addressable::URI.unencode_component(@uri_obj&.user) || @user
end
def password
Addressable::URI.unencode_component(@uri_obj&.password) || @password
end
end
end
| 1 | 13,102 | I dont see a reason to print URI for `Target`. we do not expose that in inventory v1 | puppetlabs-bolt | rb |
@@ -131,9 +131,13 @@ type OpExpression struct {
type ValueExpression struct {
String string
FString *FString
- Int *struct {
- Int int
- } // Should just be *int, but https://github.com/golang/go/issues/23498 :(
+ // These are true if this represents one of the boolean singletons
+ True bool
+ False bool
+ None bool
+ // True if the Int field is set; this helps us distinguish values of 0.
+ IsInt bool
+ Int int
Bool string
List *List
Dict *Dict | 1 | package asp
import "fmt"
// A FileInput is the top-level structure of a BUILD file.
type FileInput struct {
Statements []*Statement
}
// A Position describes a position in a source file.
// All properties in Position are one(1) indexed
type Position struct {
Filename string
Offset int
Line int
Column int
}
// String implements the fmt.Stringer interface.
func (pos Position) String() string {
return fmt.Sprintf("%s:%d:%d", pos.Filename, pos.Line, pos.Column)
}
// A Statement is the type we work with externally the most; it's a single Python statement.
// Note that some mildly excessive fiddling is needed since the parser we're using doesn't
// support backoff (i.e. if an earlier entry matches to its completion but can't consume
// following tokens, it doesn't then make another choice :( )
type Statement struct {
Pos Position
EndPos Position
FuncDef *FuncDef
For *ForStatement
If *IfStatement
Return *ReturnStatement
Raise *Expression // Deprecated
Assert *struct {
Expr *Expression
Message *Expression
}
Ident *IdentStatement
Literal *Expression
Pass bool
Continue bool
}
// A ReturnStatement implements the Python 'return' statement.
type ReturnStatement struct {
Values []*Expression
}
// A FuncDef implements definition of a new function.
type FuncDef struct {
Name string
Arguments []Argument
Docstring string
Statements []*Statement
EoDef Position
// allowed return type of the FuncDef
Return string
// Not part of the grammar. Used to indicate internal targets that can only
// be called using keyword arguments.
KeywordsOnly bool
// Indicates whether the function is private, i.e. name starts with an underscore.
IsPrivate bool
// True if the function is builtin to Please.
IsBuiltin bool
}
// A ForStatement implements the 'for' statement.
// Note that it does not support Python's "for-else" construction.
type ForStatement struct {
Names []string
Expr Expression
Statements []*Statement
}
// An IfStatement implements the if-elif-else statement.
type IfStatement struct {
Condition Expression
Statements []*Statement
Elif []struct {
Condition Expression
Statements []*Statement
}
ElseStatements []*Statement
}
// An Argument represents an argument to a function definition.
type Argument struct {
Name string
Type []string
// Aliases are an experimental non-Python concept where function arguments can be aliased to different names.
// We use this to support compatibility with Bazel & Buck etc in some cases.
Aliases []string
Value *Expression
IsPrivate bool
}
// An Expression is a generalised Python expression, i.e. anything that can appear where an
// expression is allowed (including the extra parts like inline if-then-else, operators, etc).
type Expression struct {
Pos Position
EndPos Position
UnaryOp *UnaryOp
Val *ValueExpression
Op []OpExpression
If *InlineIf
// For internal optimisation - do not use outside this package.
Optimised *OptimisedExpression
}
// An OptimisedExpression contains information to optimise certain aspects of execution of
// an expression. It must be public for serialisation but shouldn't be used outside this package.
type OptimisedExpression struct {
// Used to optimise constant expressions.
Constant pyObject
// Similarly applied to optimise simple lookups of local variables.
Local string
// And similarly applied to optimise lookups into configuration.
Config string
}
// An OpExpression is a operator combined with its following expression.
type OpExpression struct {
Op Operator
Expr *Expression
}
// A ValueExpression is the value part of an expression, i.e. without surrounding operators.
type ValueExpression struct {
String string
FString *FString
Int *struct {
Int int
} // Should just be *int, but https://github.com/golang/go/issues/23498 :(
Bool string
List *List
Dict *Dict
Tuple *List
Lambda *Lambda
Ident *IdentExpr
Slices []*Slice
Property *IdentExpr
Call *Call
}
// An FString represents a minimal version of a Python literal format string.
// Note that we only support a very small subset of what Python allows there; essentially only
// variable substitution, which gives a much simpler AST structure here.
type FString struct {
Vars []FStringVar
Suffix string // Following string bit
}
// An FStringVar represents a single variable in an FString.
type FStringVar struct {
Prefix string // Preceding string bit
Var string // Variable name to interpolate
Config string // Config variable to look up
}
// A UnaryOp represents a unary operation - in our case the only ones we support are negation and not.
type UnaryOp struct {
Op string
Expr ValueExpression
}
// An IdentStatement implements a statement that begins with an identifier (i.e. anything that
// starts off with a variable name). It is a little fiddly due to parser limitations.
type IdentStatement struct {
Name string
Unpack *struct {
Names []string
Expr *Expression
}
Index *struct {
Expr *Expression
Assign *Expression
AugAssign *Expression
}
Action *IdentStatementAction
}
// An IdentStatementAction implements actions on an IdentStatement.
type IdentStatementAction struct {
Property *IdentExpr
Call *Call
Assign *Expression
AugAssign *Expression
}
// An IdentExpr implements parts of an expression that begin with an identifier (i.e. anything
// that might be a variable name).
type IdentExpr struct {
Pos Position
EndPos Position
Name string
Action []struct {
Property *IdentExpr
Call *Call
}
}
// A Call represents a call site of a function.
type Call struct {
Arguments []CallArgument
}
// A CallArgument represents a single argument at a call site of a function.
type CallArgument struct {
Pos Position
Name string
Value Expression
}
// A List represents a list literal, either with or without a comprehension clause.
type List struct {
Values []*Expression
Comprehension *Comprehension
}
// A Dict represents a dict literal, either with or without a comprehension clause.
type Dict struct {
Items []*DictItem
Comprehension *Comprehension
}
// A DictItem represents a single key-value pair in a dict literal.
type DictItem struct {
Key Expression
Value Expression
}
// A Slice represents a slice or index expression (e.g. [1], [1:2], [2:], [:], etc).
type Slice struct {
Start *Expression
Colon string
End *Expression
}
// An InlineIf implements the single-line if-then-else construction
type InlineIf struct {
Condition *Expression
Else *Expression
}
// A Comprehension represents a list or dict comprehension clause.
type Comprehension struct {
Names []string
Expr *Expression
Second *struct {
Names []string
Expr *Expression
}
If *Expression
}
// A Lambda is the inline lambda function.
type Lambda struct {
Arguments []Argument
Expr Expression
}
// An Operator defines a unary or binary operator.
type Operator rune
const (
// Add etc are arithmetic operators - these are implemented on a per-type basis
Add Operator = '+'
// Subtract implements binary - (only works on integers)
Subtract = '-'
// Multiply implements multiplication between two types
Multiply = '×'
// Divide implements division, currently only between integers
Divide = '÷'
// Modulo implements % (including string interpolation)
Modulo = '%'
// LessThan implements <
LessThan = '<'
// GreaterThan implements >
GreaterThan = '>'
// LessThanOrEqual implements <=
LessThanOrEqual = '≤'
// GreaterThanOrEqual implements >=
GreaterThanOrEqual = '≥'
// Equal etc are comparison operators - also on a per-type basis but have slightly different rules.
Equal = '='
// NotEqual implements !=
NotEqual = '≠'
// In implements the in operator
In = '∈'
// NotIn implements "not in" as a single operator.
NotIn = '∉'
// And etc are logical operators - these are implemented type-independently
And Operator = '&'
// Or implements the or operator
Or = '∨'
// Union implements the | or binary or operator, which is only used for dict unions.
Union = '∪'
// Is implements type identity.
Is = '≡'
// IsNot is the inverse of Is.
IsNot = '≢'
// Index is used in the parser, but not when parsing code.
Index = '['
)
// String implements the fmt.Stringer interface. It is not especially efficient and is
// normally only used for errors & debugging.
func (o Operator) String() string {
for k, v := range operators {
if o == v {
return k
}
}
return "unknown"
}
var operators = map[string]Operator{
"+": Add,
"-": Subtract,
"*": Multiply,
"/": Divide,
"%": Modulo,
"<": LessThan,
">": GreaterThan,
"and": And,
"or": Or,
"is": Is,
"is not": IsNot,
"in": In,
"not in": NotIn,
"==": Equal,
"!=": NotEqual,
">=": GreaterThanOrEqual,
"<=": LessThanOrEqual,
"|": Union,
}
| 1 | 9,953 | Do we still need this? | thought-machine-please | go |
@@ -79,9 +79,13 @@ type Application struct {
type Gclient struct {
// constant tracking-id used to send a hit
trackID string
+
// anonymous client-id
clientID string
+ // anonymous campaign source
+ campaignSource string
+
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ds
// (usecase) node-detail
dataSource string | 1 | /*
Copyright 2018 The OpenEBS Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package usage
import (
k8sapi "github.com/openebs/maya/pkg/client/k8s/v1alpha1"
)
// Usage struct represents all information about a usage metric sent to
// Google Analytics with respect to the application
type Usage struct {
// Embedded Event struct as we are currently only sending hits of type
// 'event'
Event
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#an
// use-case: cstor or jiva volume, or m-apiserver application
// Embedded field for application
Application
// Embedded Gclient struct
Gclient
}
// Event is a represents usage of OpenEBS
// Event contains all the query param fields when hits is of type='event'
// Ref: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ec
type Event struct {
// (Required) Event Category, ec
category string
// (Required) Event Action, ea
action string
// (Optional) Event Label, el
label string
// (Optional) Event vallue, ev
// Non negative
value int64
}
// NewEvent returns an Event struct with eventCategory, eventAction,
// eventLabel, eventValue fields
func (u *Usage) NewEvent(c, a, l string, v int64) *Usage {
u.category = c
u.action = a
u.label = l
u.value = v
return u
}
// Application struct holds details about the Application
type Application struct {
// eg. project version
appVersion string
// eg. kubernetes version
appInstallerID string
// Name of the application, usage(OpenEBS/NDM)
appID string
// eg. usage(os-type/architecture) of system or volume's CASType
appName string
}
// Gclient struct represents a Google Analytics hit
type Gclient struct {
// constant tracking-id used to send a hit
trackID string
// anonymous client-id
clientID string
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#ds
// (usecase) node-detail
dataSource string
// Document-title property in Google Analytics
// https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#dt
// use-case: uuid of the volume objects or a uuid to anonymously tell objects apart
documentTitle string
}
// New returns an instance of Usage
func New() *Usage {
return &Usage{}
}
// SetDataSource : usage(os-type, kernel)
func (u *Usage) SetDataSource(dataSource string) *Usage {
u.dataSource = dataSource
return u
}
// SetTrackingID Sets the GA-code for the project
func (u *Usage) SetTrackingID(track string) *Usage {
u.trackID = track
return u
}
// SetDocumentTitle : usecase(anonymous-id)
func (u *Usage) SetDocumentTitle(documentTitle string) *Usage {
u.documentTitle = documentTitle
return u
}
// SetApplicationName : usecase(os-type/arch, volume CASType)
func (u *Usage) SetApplicationName(appName string) *Usage {
u.appName = appName
return u
}
// SetApplicationID : usecase(OpenEBS/NDM)
func (u *Usage) SetApplicationID(appID string) *Usage {
u.appID = appID
return u
}
// SetApplicationVersion : usecase(project-version)
func (u *Usage) SetApplicationVersion(appVersion string) *Usage {
u.appVersion = appVersion
return u
}
// SetApplicationInstallerID : usecase(k8s-version)
func (u *Usage) SetApplicationInstallerID(appInstallerID string) *Usage {
u.appInstallerID = appInstallerID
return u
}
// SetClientID sets the anonymous user id
func (u *Usage) SetClientID(userID string) *Usage {
u.clientID = userID
return u
}
// SetCategory sets the category of an event
func (u *Usage) SetCategory(c string) *Usage {
u.category = c
return u
}
// SetAction sets the action of an event
func (u *Usage) SetAction(a string) *Usage {
u.action = a
return u
}
// SetLabel sets the label for an event
func (u *Usage) SetLabel(l string) *Usage {
u.label = l
return u
}
// SetValue sets the value for an event's label
func (u *Usage) SetValue(v int64) *Usage {
u.value = v
return u
}
// Build is a builder method for Usage struct
func (u *Usage) Build() *Usage {
// Default ApplicationID for openebs project is OpenEBS
v := NewVersion()
v.getVersion(false)
u.SetApplicationID(AppName).
SetTrackingID(GAclientID).
SetClientID(v.id)
// TODO: Add condition for version over-ride
// Case: CAS/Jiva version, etc
return u
}
// Application builder is used for adding k8s&openebs environment detail
// for non install events
func (u *Usage) ApplicationBuilder() *Usage {
v := NewVersion()
v.getVersion(false)
u.SetApplicationVersion(v.openebsVersion).
SetApplicationName(v.k8sArch).
SetApplicationInstallerID(v.k8sVersion).
SetDataSource(v.nodeType)
return u
}
// SetVolumeCapacity sets the storage capacity of the volume for a volume event
func (u *Usage) SetVolumeCapacity(volCapG string) *Usage {
s, _ := toGigaUnits(volCapG)
u.SetValue(s)
return u
}
// Wrapper for setting the default storage-engine for volume-provision event
func (u *Usage) SetVolumeType(volType, method string) *Usage {
if method == VolumeProvision && volType == "" {
// Set the default storage engine, if not specified in the request
u.SetApplicationName(DefaultCASType)
} else {
u.SetApplicationName(volType)
}
return u
}
// Wrapper for setting replica count for volume events
// NOTE: This doesn't get the replica count in a volume de-provision event.
// TODO: Pick the current value of replica-count from the CAS-engine
func (u *Usage) SetReplicaCount(count, method string) *Usage {
if method == VolumeProvision && count == "" {
// Case: When volume-provision the replica count isn't specified
// it is set to three by default by the m-apiserver
u.SetAction(DefaultReplicaCount)
} else {
// Catch all case for volume-deprovision event and
// volume-provision event with an overriden replica-count
u.SetAction(Replica + count)
}
return u
}
// InstallBuilder is a concrete builder for install events
func (u *Usage) InstallBuilder(override bool) *Usage {
v := NewVersion()
clusterSize, _ := k8sapi.NumberOfNodes()
v.getVersion(override)
u.SetApplicationVersion(v.openebsVersion).
SetApplicationName(v.k8sArch).
SetApplicationInstallerID(v.k8sVersion).
SetDataSource(v.nodeType).
SetDocumentTitle(v.id).
SetApplicationID(AppName).
NewEvent(InstallEvent, RunningStatus, EventLabelNode, int64(clusterSize))
return u
}
| 1 | 16,336 | `campaignSource` is unused (from `structcheck`) | openebs-maya | go |
@@ -63,6 +63,7 @@ public final class BaselineErrorProne implements Plugin<Project> {
private static final Logger log = Logging.getLogger(BaselineErrorProne.class);
public static final String EXTENSION_NAME = "baselineErrorProne";
private static final String ERROR_PRONE_JAVAC_VERSION = "9+181-r4173-1";
+ private static final String ASSERTJ_ERROR_PRONE_VERSION = "0.2.1";
private static final String PROP_ERROR_PRONE_APPLY = "errorProneApply";
private static final String PROP_REFASTER_APPLY = "refasterApply";
private static final String DISABLE_PROPERY = "com.palantir.baseline-error-prone.disable"; | 1 | /*
* (c) Copyright 2017 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.baseline.plugins;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.MoreCollectors;
import com.palantir.baseline.extensions.BaselineErrorProneExtension;
import com.palantir.baseline.tasks.CompileRefasterTask;
import java.io.File;
import java.nio.file.Paths;
import java.util.AbstractList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import net.ltgt.gradle.errorprone.CheckSeverity;
import net.ltgt.gradle.errorprone.ErrorProneOptions;
import net.ltgt.gradle.errorprone.ErrorPronePlugin;
import org.gradle.api.JavaVersion;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.RegularFile;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.plugins.ExtensionAware;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.provider.Provider;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.api.tasks.testing.Test;
import org.gradle.process.CommandLineArgumentProvider;
public final class BaselineErrorProne implements Plugin<Project> {
private static final Logger log = Logging.getLogger(BaselineErrorProne.class);
public static final String EXTENSION_NAME = "baselineErrorProne";
private static final String ERROR_PRONE_JAVAC_VERSION = "9+181-r4173-1";
private static final String PROP_ERROR_PRONE_APPLY = "errorProneApply";
private static final String PROP_REFASTER_APPLY = "refasterApply";
private static final String DISABLE_PROPERY = "com.palantir.baseline-error-prone.disable";
@Override
public void apply(Project project) {
project.getPluginManager().withPlugin("java", unused -> {
applyToJavaProject(project);
});
}
private static void applyToJavaProject(Project project) {
BaselineErrorProneExtension errorProneExtension =
project.getExtensions().create(EXTENSION_NAME, BaselineErrorProneExtension.class, project);
project.getPluginManager().apply(ErrorPronePlugin.class);
String version = Optional.ofNullable(
BaselineErrorProne.class.getPackage().getImplementationVersion())
.orElseGet(() -> {
log.warn("Baseline is using 'latest.release' - beware this compromises build reproducibility");
return "latest.release";
});
Configuration refasterConfiguration = project.getConfigurations().create("refaster", conf -> {
conf.defaultDependencies(deps -> {
deps.add(project.getDependencies()
.create("com.palantir.baseline:baseline-refaster-rules:" + version + ":sources"));
});
});
Configuration refasterCompilerConfiguration = project.getConfigurations()
.create("refasterCompiler", configuration -> configuration.extendsFrom(refasterConfiguration));
project.getDependencies()
.add(ErrorPronePlugin.CONFIGURATION_NAME, "com.palantir.baseline:baseline-error-prone:" + version);
project.getDependencies()
.add("refasterCompiler", "com.palantir.baseline:baseline-refaster-javac-plugin:" + version);
Provider<File> refasterRulesFile = project.getLayout()
.getBuildDirectory()
.file("refaster/rules.refaster")
.map(RegularFile::getAsFile);
CompileRefasterTask compileRefaster = project.getTasks()
.create("compileRefaster", CompileRefasterTask.class, task -> {
task.setSource(refasterConfiguration);
task.getRefasterSources().set(refasterConfiguration);
task.setClasspath(refasterCompilerConfiguration);
task.getRefasterRulesFile().set(refasterRulesFile);
});
// In case of java 8 we need to add errorprone javac compiler to bootstrap classpath of tasks that perform
// compilation or code analysis. ErrorProneJavacPluginPlugin handles JavaCompile cases via errorproneJavac
// configuration and we do similar thing for Test and Javadoc type tasks
if (!JavaVersion.current().isJava9Compatible()) {
project.getDependencies()
.add(
ErrorPronePlugin.JAVAC_CONFIGURATION_NAME,
"com.google.errorprone:javac:" + ERROR_PRONE_JAVAC_VERSION);
project.getConfigurations()
.named(ErrorPronePlugin.JAVAC_CONFIGURATION_NAME)
.configure(
conf -> {
List<File> bootstrapClasspath = Splitter.on(File.pathSeparator)
.splitToList(System.getProperty("sun.boot.class.path"))
.stream()
.map(File::new)
.collect(Collectors.toList());
FileCollection errorProneFiles = conf.plus(project.files(bootstrapClasspath));
project.getTasks()
.withType(Test.class)
.configureEach(test -> test.setBootstrapClasspath(errorProneFiles));
project.getTasks().withType(Javadoc.class).configureEach(javadoc -> javadoc.getOptions()
.setBootClasspath(new LazyConfigurationList(errorProneFiles)));
});
}
project.getTasks().withType(JavaCompile.class).configureEach(javaCompile -> {
((ExtensionAware) javaCompile.getOptions())
.getExtensions()
.configure(ErrorProneOptions.class, errorProneOptions -> {
configureErrorProneOptions(
project,
refasterRulesFile,
compileRefaster,
errorProneExtension,
javaCompile,
errorProneOptions);
});
});
// To allow refactoring of deprecated methods, even when -Xlint:deprecation is specified, we need to remove
// these compiler flags after all configuration has happened.
project.afterEvaluate(
unused -> project.getTasks().withType(JavaCompile.class).configureEach(javaCompile -> {
if (javaCompile.equals(compileRefaster)) {
return;
}
if (isRefactoring(project)) {
javaCompile.getOptions().setWarnings(false);
javaCompile.getOptions().setDeprecation(false);
javaCompile
.getOptions()
.setCompilerArgs(javaCompile.getOptions().getCompilerArgs().stream()
.filter(arg -> !arg.equals("-Werror"))
.filter(arg -> !arg.equals("-deprecation"))
.filter(arg -> !arg.equals("-Xlint:deprecation"))
.collect(Collectors.toList()));
}
}));
project.getPluginManager().withPlugin("java-gradle-plugin", appliedPlugin -> {
project.getTasks().withType(JavaCompile.class).configureEach(javaCompile -> ((ExtensionAware)
javaCompile.getOptions())
.getExtensions()
.configure(ErrorProneOptions.class, errorProneOptions -> {
errorProneOptions.check("Slf4jLogsafeArgs", CheckSeverity.OFF);
errorProneOptions.check("PreferSafeLoggableExceptions", CheckSeverity.OFF);
errorProneOptions.check("PreferSafeLoggingPreconditions", CheckSeverity.OFF);
errorProneOptions.check("PreconditionsConstantMessage", CheckSeverity.OFF);
}));
});
}
@SuppressWarnings("UnstableApiUsage")
private static void configureErrorProneOptions(
Project project,
Provider<File> refasterRulesFile,
CompileRefasterTask compileRefaster,
BaselineErrorProneExtension errorProneExtension,
JavaCompile javaCompile,
ErrorProneOptions errorProneOptions) {
if (project.hasProperty(DISABLE_PROPERY)) {
log.info("Disabling baseline-error-prone for {} due to {}", project, DISABLE_PROPERY);
errorProneOptions.getEnabled().set(false);
} else {
errorProneOptions.getEnabled().set(true);
}
errorProneOptions.getDisableWarningsInGeneratedCode().set(true);
String projectPath = project.getProjectDir().getPath();
String separator = Pattern.quote(Paths.get(projectPath).getFileSystem().getSeparator());
errorProneOptions
.getExcludedPaths()
.set(String.format(
"%s%s(build|src%sgenerated.*)%s.*",
Pattern.quote(projectPath), separator, separator, separator));
// FallThrough does not currently work with switch expressions
// See https://github.com/google/error-prone/issues/1649
errorProneOptions.check("FallThrough", project.provider(() -> {
JavaPluginExtension ext = project.getExtensions().getByType(JavaPluginExtension.class);
return ext.getSourceCompatibility().compareTo(JavaVersion.toVersion(14)) < 0
? CheckSeverity.DEFAULT
: CheckSeverity.OFF;
}));
// UnnecessaryParentheses does not currently work with switch expressions
errorProneOptions.check("UnnecessaryParentheses", project.provider(() -> {
JavaPluginExtension ext = project.getExtensions().getByType(JavaPluginExtension.class);
return ext.getSourceCompatibility().compareTo(JavaVersion.toVersion(14)) < 0
? CheckSeverity.DEFAULT
: CheckSeverity.OFF;
}));
errorProneOptions.disable("CatchSpecificity", "UnusedVariable");
errorProneOptions.error(
"EqualsHashCode",
"EqualsIncompatibleType",
"StreamResourceLeak",
"InputStreamSlowMultibyteRead",
"JavaDurationGetSecondsGetNano",
"URLEqualsHashCode");
// Relax some checks for test code
if (errorProneOptions.getCompilingTestOnlyCode().get()) {
errorProneOptions.disable("UnnecessaryLambda");
}
if (javaCompile.equals(compileRefaster)) {
// Don't apply refaster to itself...
return;
}
if (isRefactoring(project)) {
// Don't attempt to cache since it won't capture the source files that might be modified
javaCompile.getOutputs().cacheIf(t -> false);
if (isRefasterRefactoring(project)) {
javaCompile.dependsOn(compileRefaster);
errorProneOptions.getErrorproneArgumentProviders().add(new CommandLineArgumentProvider() {
// intentionally not using a lambda to reduce gradle warnings
@Override
public Iterable<String> asArguments() {
String file = refasterRulesFile.get().getAbsolutePath();
return new File(file).exists()
? ImmutableList.of("-XepPatchChecks:refaster:" + file, "-XepPatchLocation:IN_PLACE")
: Collections.emptyList();
}
});
}
if (isErrorProneRefactoring(project)) {
Optional<SourceSet> maybeSourceSet = project
.getConvention()
.getPlugin(JavaPluginConvention.class)
.getSourceSets()
.matching(ss -> javaCompile.getName().equals(ss.getCompileJavaTaskName()))
.stream()
.collect(MoreCollectors.toOptional());
// TODO(gatesn): Is there a way to discover error-prone checks?
// Maybe service-load from a ClassLoader configured with annotation processor path?
// https://github.com/google/error-prone/pull/947
errorProneOptions.getErrorproneArgumentProviders().add(new CommandLineArgumentProvider() {
// intentionally not using a lambda to reduce gradle warnings
@Override
public Iterable<String> asArguments() {
// Don't apply checks that have been explicitly disabled
Stream<String> errorProneChecks = getSpecificErrorProneChecks(project)
.orElseGet(() -> getNotDisabledErrorproneChecks(
project, errorProneExtension, javaCompile, maybeSourceSet, errorProneOptions));
return ImmutableList.of(
"-XepPatchChecks:" + Joiner.on(',').join(errorProneChecks.iterator()),
"-XepPatchLocation:IN_PLACE");
}
});
}
}
}
private static Optional<Stream<String>> getSpecificErrorProneChecks(Project project) {
return Optional.ofNullable(project.findProperty(PROP_ERROR_PRONE_APPLY))
.map(Objects::toString)
.flatMap(value -> Optional.ofNullable(Strings.emptyToNull(value)))
.map(value -> Splitter.on(',').trimResults().omitEmptyStrings().splitToList(value))
.flatMap(list -> list.isEmpty() ? Optional.empty() : Optional.of(list.stream()));
}
private static Stream<String> getNotDisabledErrorproneChecks(
Project project,
BaselineErrorProneExtension errorProneExtension,
JavaCompile javaCompile,
Optional<SourceSet> maybeSourceSet,
ErrorProneOptions errorProneOptions) {
// If this javaCompile is associated with a source set, use it to figure out if it has preconditions or not.
Predicate<String> filterOutPreconditions = maybeSourceSet
.map(ss -> filterOutPreconditions(
project.getConfigurations().getByName(ss.getCompileClasspathConfigurationName())))
.orElse(check -> true);
return errorProneExtension.getPatchChecks().get().stream().filter(check -> {
if (checkExplicitlyDisabled(errorProneOptions, check)) {
log.info(
"Task {}: not applying errorprone check {} because it has severity OFF in errorProneOptions",
javaCompile.getPath(),
check);
return false;
}
return filterOutPreconditions.test(check);
});
}
private static boolean hasDependenciesMatching(Configuration configuration, Spec<ModuleComponentIdentifier> spec) {
return !Iterables.isEmpty(configuration
.getIncoming()
.artifactView(viewConfiguration -> viewConfiguration.componentFilter(ci ->
ci instanceof ModuleComponentIdentifier && spec.isSatisfiedBy((ModuleComponentIdentifier) ci)))
.getArtifacts());
}
/** Filters out preconditions checks if the required libraries are not on the classpath. */
public static Predicate<String> filterOutPreconditions(Configuration compileClasspath) {
boolean hasPreconditions =
hasDependenciesMatching(compileClasspath, BaselineErrorProne::isSafeLoggingPreconditionsDep);
return check -> {
if (!hasPreconditions) {
if (check.equals("PreferSafeLoggingPreconditions")) {
log.info(
"Disabling check PreferSafeLoggingPreconditions as "
+ "'com.palantir.safe-logging:preconditions' missing from {}",
compileClasspath);
return false;
}
if (check.equals("PreferSafeLoggableExceptions")) {
log.info(
"Disabling check PreferSafeLoggableExceptions as 'com.palantir.safe-logging:preconditions' "
+ "missing from {}",
compileClasspath);
return false;
}
}
return true;
};
}
private static boolean isSafeLoggingPreconditionsDep(ModuleComponentIdentifier mci) {
return mci.getGroup().equals("com.palantir.safe-logging")
&& mci.getModule().equals("preconditions");
}
private static boolean isRefactoring(Project project) {
return isRefasterRefactoring(project) || isErrorProneRefactoring(project);
}
private static boolean isRefasterRefactoring(Project project) {
return project.hasProperty(PROP_REFASTER_APPLY);
}
private static boolean isErrorProneRefactoring(Project project) {
return project.hasProperty(PROP_ERROR_PRONE_APPLY);
}
private static boolean checkExplicitlyDisabled(ErrorProneOptions errorProneOptions, String check) {
Map<String, CheckSeverity> checks = errorProneOptions.getChecks().get();
return checks.get(check) == CheckSeverity.OFF
|| errorProneOptions.getErrorproneArgs().get().contains(String.format("-Xep:%s:OFF", check));
}
private static final class LazyConfigurationList extends AbstractList<File> {
private final FileCollection files;
private List<File> fileList;
private LazyConfigurationList(FileCollection files) {
this.files = files;
}
@Override
public File get(int index) {
if (fileList == null) {
fileList = ImmutableList.copyOf(files.getFiles());
}
return fileList.get(index);
}
@Override
public int size() {
if (fileList == null) {
fileList = ImmutableList.copyOf(files.getFiles());
}
return fileList.size();
}
}
}
| 1 | 8,687 | we should discuss how to not hard-code this version | palantir-gradle-baseline | java |
@@ -5,8 +5,14 @@ const isResumableError = require('./error').isResumableError;
const MongoError = require('./core').MongoError;
const ReadConcern = require('./read_concern');
const MongoDBNamespace = require('./utils').MongoDBNamespace;
+const Cursor = require('./cursor');
+const relayEvents = require('./core/utils').relayEvents;
+const maxWireVersion = require('./core/utils').maxWireVersion;
-var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference'];
+const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument'];
+const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat(
+ CHANGE_STREAM_OPTIONS
+);
const CHANGE_DOMAIN_TYPES = {
COLLECTION: Symbol('Collection'), | 1 | 'use strict';
const EventEmitter = require('events');
const isResumableError = require('./error').isResumableError;
const MongoError = require('./core').MongoError;
const ReadConcern = require('./read_concern');
const MongoDBNamespace = require('./utils').MongoDBNamespace;
var cursorOptionNames = ['maxAwaitTimeMS', 'collation', 'readPreference'];
const CHANGE_DOMAIN_TYPES = {
COLLECTION: Symbol('Collection'),
DATABASE: Symbol('Database'),
CLUSTER: Symbol('Cluster')
};
/**
* Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
* @class ChangeStream
* @since 3.0.0
* @param {(MongoClient|Db|Collection)} changeDomain The domain against which to create the change stream
* @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents
* @param {object} [options] Optional settings
* @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.
* @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query
* @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
* @param {number} [options.batchSize] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
* @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}.
* @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}.
* @fires ChangeStream#close
* @fires ChangeStream#change
* @fires ChangeStream#end
* @fires ChangeStream#error
* @return {ChangeStream} a ChangeStream instance.
*/
class ChangeStream extends EventEmitter {
constructor(changeDomain, pipeline, options) {
super();
const Collection = require('./collection');
const Db = require('./db');
const MongoClient = require('./mongo_client');
this.pipeline = pipeline || [];
this.options = options || {};
this.namespace =
changeDomain instanceof MongoClient
? new MongoDBNamespace('admin')
: changeDomain.s.namespace;
if (changeDomain instanceof Collection) {
this.type = CHANGE_DOMAIN_TYPES.COLLECTION;
this.topology = changeDomain.s.db.serverConfig;
} else if (changeDomain instanceof Db) {
this.type = CHANGE_DOMAIN_TYPES.DATABASE;
this.topology = changeDomain.serverConfig;
} else if (changeDomain instanceof MongoClient) {
this.type = CHANGE_DOMAIN_TYPES.CLUSTER;
this.topology = changeDomain.topology;
} else {
throw new TypeError(
'changeDomain provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient'
);
}
this.promiseLibrary = changeDomain.s.promiseLibrary;
if (!this.options.readPreference && changeDomain.s.readPreference) {
this.options.readPreference = changeDomain.s.readPreference;
}
// We need to get the operationTime as early as possible
const isMaster = this.topology.lastIsMaster();
if (!isMaster) {
throw new MongoError('Topology does not have an ismaster yet.');
}
this.operationTime = isMaster.operationTime;
// Create contained Change Stream cursor
this.cursor = createChangeStreamCursor(this);
// Listen for any `change` listeners being added to ChangeStream
this.on('newListener', eventName => {
if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) {
this.cursor.on('data', change =>
processNewChange({ changeStream: this, change, eventEmitter: true })
);
}
});
// Listen for all `change` listeners being removed from ChangeStream
this.on('removeListener', eventName => {
if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) {
this.cursor.removeAllListeners('data');
}
});
}
/**
* Check if there is any document still available in the Change Stream
* @function ChangeStream.prototype.hasNext
* @param {ChangeStream~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
hasNext(callback) {
return this.cursor.hasNext(callback);
}
/**
* Get the next available document from the Change Stream, returns null if no more documents are available.
* @function ChangeStream.prototype.next
* @param {ChangeStream~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
next(callback) {
var self = this;
if (this.isClosed()) {
if (callback) return callback(new Error('Change Stream is not open.'), null);
return self.promiseLibrary.reject(new Error('Change Stream is not open.'));
}
return this.cursor
.next()
.then(change => processNewChange({ changeStream: self, change, callback }))
.catch(error => processNewChange({ changeStream: self, error, callback }));
}
/**
* Is the cursor closed
* @method ChangeStream.prototype.isClosed
* @return {boolean}
*/
isClosed() {
if (this.cursor) {
return this.cursor.isClosed();
}
return true;
}
/**
* Close the Change Stream
* @method ChangeStream.prototype.close
* @param {ChangeStream~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
close(callback) {
if (!this.cursor) {
if (callback) return callback();
return this.promiseLibrary.resolve();
}
// Tidy up the existing cursor
var cursor = this.cursor;
['data', 'close', 'end', 'error'].forEach(event => this.cursor.removeAllListeners(event));
delete this.cursor;
return cursor.close(callback);
}
/**
* This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
* @method
* @param {Writable} destination The destination for writing data
* @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options}
* @return {null}
*/
pipe(destination, options) {
if (!this.pipeDestinations) {
this.pipeDestinations = [];
}
this.pipeDestinations.push(destination);
return this.cursor.pipe(destination, options);
}
/**
* This method will remove the hooks set up for a previous pipe() call.
* @param {Writable} [destination] The destination for writing data
* @return {null}
*/
unpipe(destination) {
if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) {
this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1);
}
return this.cursor.unpipe(destination);
}
/**
* Return a modified Readable stream including a possible transform method.
* @method
* @param {object} [options] Optional settings.
* @param {function} [options.transform] A transformation method applied to each document emitted by the stream.
* @return {Cursor}
*/
stream(options) {
this.streamOptions = options;
return this.cursor.stream(options);
}
/**
* This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
* @return {null}
*/
pause() {
return this.cursor.pause();
}
/**
* This method will cause the readable stream to resume emitting data events.
* @return {null}
*/
resume() {
return this.cursor.resume();
}
}
// Create a new change stream cursor based on self's configuration
var createChangeStreamCursor = function(self) {
if (self.resumeToken) {
self.options.resumeAfter = self.resumeToken;
}
var changeStreamCursor = buildChangeStreamAggregationCommand(self);
/**
* Fired for each new matching change in the specified namespace. Attaching a `change`
* event listener to a Change Stream will switch the stream into flowing mode. Data will
* then be passed as soon as it is available.
*
* @event ChangeStream#change
* @type {object}
*/
if (self.listenerCount('change') > 0) {
changeStreamCursor.on('data', function(change) {
processNewChange({ changeStream: self, change, eventEmitter: true });
});
}
/**
* Change stream close event
*
* @event ChangeStream#close
* @type {null}
*/
changeStreamCursor.on('close', function() {
self.emit('close');
});
/**
* Change stream end event
*
* @event ChangeStream#end
* @type {null}
*/
changeStreamCursor.on('end', function() {
self.emit('end');
});
/**
* Fired when the stream encounters an error.
*
* @event ChangeStream#error
* @type {Error}
*/
changeStreamCursor.on('error', function(error) {
processNewChange({ changeStream: self, error, eventEmitter: true });
});
if (self.pipeDestinations) {
const cursorStream = changeStreamCursor.stream(self.streamOptions);
for (let pipeDestination in self.pipeDestinations) {
cursorStream.pipe(pipeDestination);
}
}
return changeStreamCursor;
};
function getResumeToken(self) {
return self.resumeToken || self.options.resumeAfter;
}
function getStartAtOperationTime(self) {
const isMaster = self.topology.lastIsMaster() || {};
return (
isMaster.maxWireVersion && isMaster.maxWireVersion >= 7 && self.options.startAtOperationTime
);
}
var buildChangeStreamAggregationCommand = function(self) {
const topology = self.topology;
const namespace = self.namespace;
const pipeline = self.pipeline;
const options = self.options;
var changeStreamStageOptions = {
fullDocument: options.fullDocument || 'default'
};
const resumeToken = getResumeToken(self);
const startAtOperationTime = getStartAtOperationTime(self);
if (resumeToken) {
changeStreamStageOptions.resumeAfter = resumeToken;
}
if (startAtOperationTime) {
changeStreamStageOptions.startAtOperationTime = startAtOperationTime;
}
// Map cursor options
var cursorOptions = {};
cursorOptionNames.forEach(function(optionName) {
if (options[optionName]) {
cursorOptions[optionName] = options[optionName];
}
});
if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) {
changeStreamStageOptions.allChangesForCluster = true;
}
var changeStreamPipeline = [{ $changeStream: changeStreamStageOptions }];
changeStreamPipeline = changeStreamPipeline.concat(pipeline);
var command = {
aggregate: self.type === CHANGE_DOMAIN_TYPES.COLLECTION ? namespace.collection : 1,
pipeline: changeStreamPipeline,
readConcern: new ReadConcern(ReadConcern.MAJORITY),
cursor: {
batchSize: options.batchSize || 1
}
};
// Create and return the cursor
// TODO: switch to passing namespace object later
return topology.cursor(namespace.toString(), command, cursorOptions);
};
// This method performs a basic server selection loop, satisfying the requirements of
// ChangeStream resumability until the new SDAM layer can be used.
const SELECTION_TIMEOUT = 30000;
function waitForTopologyConnected(topology, options, callback) {
setTimeout(() => {
if (options && options.start == null) options.start = process.hrtime();
const start = options.start || process.hrtime();
const timeout = options.timeout || SELECTION_TIMEOUT;
const readPreference = options.readPreference;
if (topology.isConnected({ readPreference })) return callback(null, null);
const hrElapsed = process.hrtime(start);
const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6;
if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection'));
waitForTopologyConnected(topology, options, callback);
}, 3000); // this is an arbitrary wait time to allow SDAM to transition
}
// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream.
function processNewChange(args) {
const changeStream = args.changeStream;
const error = args.error;
const change = args.change;
const callback = args.callback;
const eventEmitter = args.eventEmitter || false;
// If the changeStream is closed, then it should not process a change.
if (changeStream.isClosed()) {
// We do not error in the eventEmitter case.
if (eventEmitter) {
return;
}
const error = new MongoError('ChangeStream is closed');
return typeof callback === 'function'
? callback(error, null)
: changeStream.promiseLibrary.reject(error);
}
const topology = changeStream.topology;
const options = changeStream.cursor.options;
if (error) {
if (isResumableError(error) && !changeStream.attemptingResume) {
changeStream.attemptingResume = true;
if (!(getResumeToken(changeStream) || getStartAtOperationTime(changeStream))) {
const startAtOperationTime = changeStream.cursor.cursorState.operationTime;
changeStream.options = Object.assign({ startAtOperationTime }, changeStream.options);
}
// stop listening to all events from old cursor
['data', 'close', 'end', 'error'].forEach(event =>
changeStream.cursor.removeAllListeners(event)
);
// close internal cursor, ignore errors
changeStream.cursor.close();
// attempt recreating the cursor
if (eventEmitter) {
waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
if (err) return changeStream.emit('error', err);
changeStream.cursor = createChangeStreamCursor(changeStream);
});
return;
}
if (callback) {
waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
if (err) return callback(err, null);
changeStream.cursor = createChangeStreamCursor(changeStream);
changeStream.next(callback);
});
return;
}
return new Promise((resolve, reject) => {
waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => {
if (err) return reject(err);
resolve();
});
})
.then(() => (changeStream.cursor = createChangeStreamCursor(changeStream)))
.then(() => changeStream.next());
}
if (eventEmitter) return changeStream.emit('error', error);
if (typeof callback === 'function') return callback(error, null);
return changeStream.promiseLibrary.reject(error);
}
changeStream.attemptingResume = false;
// Cache the resume token if it is present. If it is not present return an error.
if (!change || !change._id) {
var noResumeTokenError = new Error(
'A change stream document has been received that lacks a resume token (_id).'
);
if (eventEmitter) return changeStream.emit('error', noResumeTokenError);
if (typeof callback === 'function') return callback(noResumeTokenError, null);
return changeStream.promiseLibrary.reject(noResumeTokenError);
}
changeStream.resumeToken = change._id;
// Return the change
if (eventEmitter) return changeStream.emit('change', change);
if (typeof callback === 'function') return callback(error, change);
return changeStream.promiseLibrary.resolve(change);
}
/**
* The callback format for results
* @callback ChangeStream~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {(object|null)} result The result object if the command was executed successfully.
*/
module.exports = ChangeStream;
| 1 | 15,933 | do we have a doclet for this event? | mongodb-node-mongodb-native | js |
@@ -35,10 +35,11 @@ if (isNodeProcess && process.platform === 'win32') {
}
// catching segfaults during testing can help debugging
-if (isNodeProcess) {
- const SegfaultHandler = node_require('segfault-handler');
- SegfaultHandler.registerHandler("crash.log");
-}
+//uncomment to enable segfault handler
+//if (isNodeProcess) {
+ //const SegfaultHandler = node_require('segfault-handler');
+ //SegfaultHandler.registerHandler("crash.log");
+//}
var TESTS = {
ListTests: require('./list-tests'), | 1 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
'use strict';
const Realm = require('realm');
if( typeof Realm.Sync !== 'undefined' && Realm.Sync !== null ) {
global.WARNING = "global is not available in React Native. Use it only in tests";
global.enableSyncTests = true;
}
const isNodeProcess = typeof process === 'object' && process + '' === '[object process]';
const isElectronProcess = isNodeProcess && (process.type === 'renderer' || (process.versions && process.versions.electron));
const require_method = require;
function node_require(module) { return require_method(module); }
if (isNodeProcess && process.platform === 'win32') {
global.enableSyncTests = false;
}
// catching segfaults during testing can help debugging
if (isNodeProcess) {
const SegfaultHandler = node_require('segfault-handler');
SegfaultHandler.registerHandler("crash.log");
}
var TESTS = {
ListTests: require('./list-tests'),
LinkingObjectsTests: require('./linkingobjects-tests'),
ObjectTests: require('./object-tests'),
RealmTests: require('./realm-tests'),
ResultsTests: require('./results-tests'),
QueryTests: require('./query-tests'),
MigrationTests: require('./migration-tests'),
EncryptionTests: require('./encryption-tests'),
ObjectIDTests: require('./object-id-tests'),
AliasTests: require('./alias-tests'),
// Garbagecollectiontests: require('./garbage-collection'),
};
// If sync is enabled, run the sync tests
if (global.enableSyncTests) {
TESTS.OpenBehaviorTests = require('./open-behavior-tests');
TESTS.UserTests = require('./user-tests');
TESTS.SessionTests = require('./session-tests');
TESTS.SubscriptionTests = require('./subscription-tests');
if (isNodeProcess && !isElectronProcess) {
// FIXME: Permission tests currently fail in react native
TESTS.PermissionTests = require('./permission-tests');
node_require('./adapter-tests');
node_require('./notifier-tests');
}
}
// If on node, run the async tests
if (isNodeProcess && process.platform !== 'win32') {
TESTS.AsyncTests = node_require('./async-tests');
}
if (global.enableSyncTests) {
// Ensure that the sync manager is initialized as initializing it
// after calling clearTestState() doesn't work
Realm.Sync.User.all;
}
var SPECIAL_METHODS = {
beforeEach: true,
afterEach: true,
};
exports.getTestNames = function() {
var testNames = {};
for (var suiteName in TESTS) {
var testSuite = TESTS[suiteName];
testNames[suiteName] = Object.keys(testSuite).filter(function(testName) {
return !(testName in SPECIAL_METHODS) && typeof testSuite[testName] == 'function';
});
}
return testNames;
};
exports.registerTests = function(tests) {
for (var suiteName in tests) {
TESTS[suiteName] = tests[suiteName];
}
};
exports.prepare = function(done) {
if (!global.enableSyncTests || !isNodeProcess || global.testAdminUserInfo) {
done();
return;
}
require('./admin-user-helper')
.createAdminUser()
.then(userInfo => {
global.testAdminUserInfo = userInfo;
done();
})
.catch(error => {
console.error("Error running admin-user-helper", error);
done.fail(error);
});
};
exports.runTest = function(suiteName, testName) {
const testSuite = TESTS[suiteName];
const testMethod = testSuite && testSuite[testName];
if (testMethod) {
Realm.clearTestState();
console.warn("Starting test " + testName);
return testMethod.call(testSuite);
}
if (!testSuite || !(testName in SPECIAL_METHODS)) {
throw new Error(`Missing test: ${suiteName}.${testName}`);
}
}
| 1 | 18,001 | Why don't we want to catch segfaults by default? | realm-realm-js | js |
@@ -137,6 +137,7 @@ namespace OpenTelemetry.Exporter.Zipkin
return result;
}
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "The object should not be disposed")]
private Task SendBatchActivityAsync(IEnumerable<Activity> batchActivity, CancellationToken cancellationToken)
{
var requestUri = this.options.Endpoint; | 1 | // <copyright file="ZipkinExporter.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
#if NET452
using Newtonsoft.Json;
#else
using System.Text.Json;
#endif
using System.Threading;
using System.Threading.Tasks;
using OpenTelemetry.Exporter.Zipkin.Implementation;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Exporter.Zipkin
{
/// <summary>
/// Zipkin exporter.
/// </summary>
public class ZipkinExporter : ActivityExporter
{
private readonly ZipkinExporterOptions options;
private readonly HttpClient httpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ZipkinExporter"/> class.
/// </summary>
/// <param name="options">Configuration options.</param>
/// <param name="client">Http client to use to upload telemetry.</param>
public ZipkinExporter(ZipkinExporterOptions options, HttpClient client = null)
{
this.options = options;
this.LocalEndpoint = this.GetLocalZipkinEndpoint();
this.httpClient = client ?? new HttpClient();
}
internal ZipkinEndpoint LocalEndpoint { get; }
/// <inheritdoc/>
public override ExportResult Export(in Batch<Activity> batch)
{
try
{
// take a snapshot of the batch
var activities = new List<Activity>();
foreach (var activity in batch)
{
activities.Add(activity);
}
this.SendBatchActivityAsync(activities, CancellationToken.None).GetAwaiter().GetResult();
return ExportResult.Success;
}
catch (Exception ex)
{
ZipkinExporterEventSource.Log.FailedExport(ex);
// TODO distinguish retryable exceptions
return ExportResult.Failure;
}
}
private static string ResolveHostAddress(string hostName, AddressFamily family)
{
string result = null;
try
{
var results = Dns.GetHostAddresses(hostName);
if (results != null && results.Length > 0)
{
foreach (var addr in results)
{
if (addr.AddressFamily.Equals(family))
{
var sanitizedAddress = new IPAddress(addr.GetAddressBytes()); // Construct address sans ScopeID
result = sanitizedAddress.ToString();
break;
}
}
}
}
catch (Exception)
{
// Ignore
}
return result;
}
private static string ResolveHostName()
{
string result = null;
try
{
result = Dns.GetHostName();
if (!string.IsNullOrEmpty(result))
{
var response = Dns.GetHostEntry(result);
if (response != null)
{
return response.HostName;
}
}
}
catch (Exception)
{
// Ignore
}
return result;
}
private Task SendBatchActivityAsync(IEnumerable<Activity> batchActivity, CancellationToken cancellationToken)
{
var requestUri = this.options.Endpoint;
var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
Content = new JsonContent(this, batchActivity),
};
return this.httpClient.SendAsync(request, cancellationToken);
}
private ZipkinEndpoint GetLocalZipkinEndpoint()
{
var hostName = ResolveHostName();
string ipv4 = null;
string ipv6 = null;
if (!string.IsNullOrEmpty(hostName))
{
ipv4 = ResolveHostAddress(hostName, AddressFamily.InterNetwork);
ipv6 = ResolveHostAddress(hostName, AddressFamily.InterNetworkV6);
}
return new ZipkinEndpoint(
this.options.ServiceName,
ipv4,
ipv6,
null);
}
private class JsonContent : HttpContent
{
private static readonly MediaTypeHeaderValue JsonHeader = new MediaTypeHeaderValue("application/json")
{
CharSet = "utf-8",
};
private readonly ZipkinExporter exporter;
private readonly IEnumerable<Activity> batchActivity;
#if NET452
private JsonWriter writer;
#else
private Utf8JsonWriter writer;
#endif
public JsonContent(ZipkinExporter exporter, IEnumerable<Activity> batchActivity)
{
this.exporter = exporter;
this.batchActivity = batchActivity;
this.Headers.ContentType = JsonHeader;
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
#if NET452
StreamWriter streamWriter = new StreamWriter(stream);
this.writer = new JsonTextWriter(streamWriter);
#else
if (this.writer == null)
{
this.writer = new Utf8JsonWriter(stream);
}
else
{
this.writer.Reset(stream);
}
#endif
this.writer.WriteStartArray();
foreach (var activity in this.batchActivity)
{
var zipkinSpan = activity.ToZipkinSpan(this.exporter.LocalEndpoint, this.exporter.options.UseShortTraceIds);
zipkinSpan.Write(this.writer);
zipkinSpan.Return();
}
this.writer.WriteEndArray();
return this.writer.FlushAsync();
}
protected override bool TryComputeLength(out long length)
{
// We can't know the length of the content being pushed to the output stream.
length = -1;
return false;
}
}
}
}
| 1 | 16,574 | You could probably dispose request & content if you `await` the SendAsync. | open-telemetry-opentelemetry-dotnet | .cs |
@@ -35,6 +35,16 @@ class UtilsTest(ReusedSQLTestCase, SQLTestUtils):
}, index=[0, 1, 3])
validate_arguments_and_invoke_function(pdf, self.to_html, pd.DataFrame.to_html, args)
+ def to_clipboard(self, sep=',', **kwargs):
+ args = locals()
+
+ pdf = pd.DataFrame({
+ 'a': [1, 2, 3],
+ 'b': [4, 5, 6],
+ }, index=[0, 1, 3])
+ validate_arguments_and_invoke_function(pdf, self.to_clipboard,
+ pd.DataFrame.to_clipboard, args)
+
def test_validate_arguments_and_invoke_function(self):
# This should pass and run fine
self.to_html() | 1 | #
# Copyright (C) 2019 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pandas as pd
from databricks.koalas.testing.utils import ReusedSQLTestCase, SQLTestUtils
from databricks.koalas.utils import lazy_property, validate_arguments_and_invoke_function
some_global_variable = 0
class UtilsTest(ReusedSQLTestCase, SQLTestUtils):
# a dummy to_html version with an extra parameter that pandas does not support
# used in test_validate_arguments_and_invoke_function
def to_html(self, max_rows=None, unsupported_param=None):
args = locals()
pdf = pd.DataFrame({
'a': [1, 2, 3],
'b': [4, 5, 6],
}, index=[0, 1, 3])
validate_arguments_and_invoke_function(pdf, self.to_html, pd.DataFrame.to_html, args)
def test_validate_arguments_and_invoke_function(self):
# This should pass and run fine
self.to_html()
self.to_html(unsupported_param=None)
self.to_html(max_rows=5)
# This should fail because we are explicitly setting an unsupported param
# to a non-default value
with self.assertRaises(TypeError):
self.to_html(unsupported_param=1)
def test_lazy_property(self):
obj = TestClassForLazyProp()
# If lazy prop is not working, the second test would fail (because it'd be 2)
self.assert_eq(obj.lazy_prop, 1)
self.assert_eq(obj.lazy_prop, 1)
class TestClassForLazyProp:
def __init__(self):
self.some_variable = 0
@lazy_property
def lazy_prop(self):
self.some_variable += 1
return self.some_variable
| 1 | 8,893 | why is this test case here? this file is for testing functionalities in utils.py | databricks-koalas | py |
@@ -31,6 +31,15 @@ class AuthController < ApplicationController
def do_user_auth(auth)
sign_out
user = User.from_oauth_hash(auth)
+ unless ENV["NO_WELCOME_EMAIL"]
+ send_welcome_mail(user)
+ end
sign_in(user)
end
+
+ def send_welcome_mail(user)
+ if (Time.current - user.created_at) < 2.seconds
+ WelcomeMailer.welcome_notification(user).deliver_later
+ end
+ end
end | 1 | class AuthController < ApplicationController
skip_before_action :authenticate_user!, only: [:oauth_callback, :failure]
skip_before_action :check_disabled_client
def oauth_callback
auth = request.env["omniauth.auth"]
return_to_path = fetch_return_to_path
do_user_auth(auth)
session[:token] = auth.credentials.token
flash[:success] = "You successfully signed in"
redirect_to return_to_path || proposals_path
end
def failure
end
def logout
sign_out
redirect_to root_url
end
protected
def fetch_return_to_path
return_to_struct = return_to
if return_to_struct && return_to_struct.key?("path")
return_to_struct[:path]
end
end
def do_user_auth(auth)
sign_out
user = User.from_oauth_hash(auth)
sign_in(user)
end
end
| 1 | 16,620 | why do we have an env var for this? not sure why we'd want to suppress welcome emails but not any others | 18F-C2 | rb |
@@ -917,7 +917,13 @@ func (p *parser) parseStringExpression() *ast.StringExpression {
}
default:
// TODO bad expression
- return nil
+ loc := p.loc(pos, pos+token.Pos(len(lit)))
+ p.errs = append(p.errs, ast.Error{
+ Msg: fmt.Sprintf("got unexpected token in string expression %s@%d:%d-%d:%d: %s", loc.File, loc.Start.Line, loc.Start.Column, loc.End.Line, loc.End.Column, tok),
+ })
+ return &ast.StringExpression{
+ BaseNode: p.position(beg, pos+token.Pos(len(lit))),
+ }
}
}
} | 1 | package parser
import (
"fmt"
"strconv"
"strings"
"github.com/influxdata/flux/ast"
"github.com/influxdata/flux/internal/scanner"
"github.com/influxdata/flux/internal/token"
)
// Scanner defines the interface for reading a stream of tokens.
type Scanner interface {
// Scan will scan the next token.
Scan() (pos token.Pos, tok token.Token, lit string)
// ScanWithRegex will scan the next token and include any regex literals.
ScanWithRegex() (pos token.Pos, tok token.Token, lit string)
// ScanStringExpr will scan the next token in a string expression context
ScanStringExpr() (pos token.Pos, tok token.Token, lit string)
// File returns the file being processed by the Scanner.
File() *token.File
// Unread will unread back to the previous location within the Scanner.
// This can only be called once so the maximum lookahead is one.
Unread()
}
// ParseFile parses Flux source and produces an ast.File.
func ParseFile(f *token.File, src []byte) *ast.File {
p := &parser{
s: &scannerSkipComments{
Scanner: scanner.New(f, src),
},
src: src,
blocks: make(map[token.Token]int),
}
return p.parseFile(f.Name())
}
// scannerSkipComments is a temporary Scanner used for stripping comments
// from the input stream. We want to attach comments to nodes within the
// AST, but first we want to have feature parity with the old parser so
// the easiest method is just to strip comments at the moment.
type scannerSkipComments struct {
Scanner
}
func (s *scannerSkipComments) Scan() (pos token.Pos, tok token.Token, lit string) {
for {
pos, tok, lit = s.Scanner.Scan()
if tok != token.COMMENT {
return pos, tok, lit
}
}
}
func (s *scannerSkipComments) ScanWithRegex() (pos token.Pos, tok token.Token, lit string) {
for {
pos, tok, lit = s.Scanner.ScanWithRegex()
if tok != token.COMMENT {
return pos, tok, lit
}
}
}
func (s *scannerSkipComments) ScanStringExpr() (pos token.Pos, tok token.Token, lit string) {
for {
pos, tok, lit = s.Scanner.ScanStringExpr()
if tok != token.COMMENT {
return pos, tok, lit
}
}
}
type parser struct {
s Scanner
src []byte
pos token.Pos
tok token.Token
lit string
buffered bool
errs []ast.Error
// blocks maintains a count of the end tokens for nested blocks
// that we have entered.
blocks map[token.Token]int
}
func (p *parser) parseFile(fname string) *ast.File {
pos, _, _ := p.peek()
file := &ast.File{
BaseNode: ast.BaseNode{
Loc: &ast.SourceLocation{
File: p.s.File().Name(),
Start: p.s.File().Position(pos),
},
},
Name: fname,
}
file.Package = p.parsePackageClause()
if file.Package != nil {
file.Loc.End = locEnd(file.Package)
}
file.Imports = p.parseImportList()
if len(file.Imports) > 0 {
file.Loc.End = locEnd(file.Imports[len(file.Imports)-1])
}
file.Body = p.parseStatementList()
if len(file.Body) > 0 {
file.Loc.End = locEnd(file.Body[len(file.Body)-1])
}
file.Loc = p.sourceLocation(file.Loc.Start, file.Loc.End)
return file
}
func (p *parser) parsePackageClause() *ast.PackageClause {
pos, tok, _ := p.peek()
if tok == token.PACKAGE {
p.consume()
ident := p.parseIdentifier()
return &ast.PackageClause{
BaseNode: p.baseNode(p.sourceLocation(
p.s.File().Position(pos),
locEnd(ident),
)),
Name: ident,
}
}
return nil
}
func (p *parser) parseImportList() (imports []*ast.ImportDeclaration) {
for {
if _, tok, _ := p.peek(); tok != token.IMPORT {
return
}
imports = append(imports, p.parseImportDeclaration())
}
}
func (p *parser) parseImportDeclaration() *ast.ImportDeclaration {
start, _ := p.expect(token.IMPORT)
var as *ast.Identifier
if _, tok, _ := p.peek(); tok == token.IDENT {
as = p.parseIdentifier()
}
path := p.parseStringLiteral()
return &ast.ImportDeclaration{
BaseNode: p.baseNode(p.sourceLocation(
p.s.File().Position(start),
locEnd(path),
)),
As: as,
Path: path,
}
}
func (p *parser) parseStatementList() []ast.Statement {
var stmts []ast.Statement
for {
if ok := p.more(); !ok {
return stmts
}
stmts = append(stmts, p.parseStatement())
}
}
func (p *parser) parseStatement() ast.Statement {
switch pos, tok, lit := p.peek(); tok {
case token.IDENT:
return p.parseIdentStatement()
case token.OPTION:
return p.parseOptionAssignment()
case token.BUILTIN:
return p.parseBuiltinStatement()
case token.TEST:
return p.parseTestStatement()
case token.RETURN:
return p.parseReturnStatement()
case token.INT, token.FLOAT, token.STRING, token.DIV,
token.TIME, token.DURATION, token.PIPE_RECEIVE,
token.LPAREN, token.LBRACK, token.LBRACE,
token.ADD, token.SUB, token.NOT, token.IF, token.EXISTS, token.QUOTE:
return p.parseExpressionStatement()
default:
p.consume()
return &ast.BadStatement{
Text: lit,
BaseNode: p.posRange(pos, len(lit)),
}
}
}
func (p *parser) parseOptionAssignment() ast.Statement {
pos, _ := p.expect(token.OPTION)
ident := p.parseIdentifier()
assignment := p.parseOptionAssignmentSuffix(ident)
return &ast.OptionStatement{
Assignment: assignment,
BaseNode: ast.BaseNode{
Loc: p.sourceLocation(
p.s.File().Position(pos),
locEnd(assignment),
),
},
}
}
func (p *parser) parseOptionAssignmentSuffix(id *ast.Identifier) ast.Assignment {
switch _, tok, _ := p.peek(); tok {
case token.DOT:
p.consume()
property := p.parseIdentifier()
expr := p.parseAssignStatement()
return &ast.MemberAssignment{
BaseNode: ast.BaseNode{
Loc: p.sourceLocation(
locStart(id),
locEnd(expr),
),
},
Member: &ast.MemberExpression{
BaseNode: ast.BaseNode{
Loc: p.sourceLocation(
locStart(id),
locEnd(property),
),
},
Object: id,
Property: property,
},
Init: expr,
}
case token.ASSIGN:
expr := p.parseAssignStatement()
return &ast.VariableAssignment{
BaseNode: ast.BaseNode{
Loc: p.sourceLocation(
locStart(id),
locEnd(expr),
),
},
ID: id,
Init: expr,
}
}
return nil
}
func (p *parser) parseBuiltinStatement() *ast.BuiltinStatement {
pos, _ := p.expect(token.BUILTIN)
ident := p.parseIdentifier()
//TODO(nathanielc): Parse type expression
return &ast.BuiltinStatement{
ID: ident,
BaseNode: ast.BaseNode{
Loc: p.sourceLocation(
p.s.File().Position(pos),
locEnd(ident),
),
},
}
}
func (p *parser) parseTestStatement() *ast.TestStatement {
pos, _ := p.expect(token.TEST)
id := p.parseIdentifier()
ex := p.parseAssignStatement()
return &ast.TestStatement{
BaseNode: ast.BaseNode{
Loc: p.sourceLocation(
p.s.File().Position(pos),
locEnd(ex),
),
},
Assignment: &ast.VariableAssignment{
BaseNode: p.baseNode(p.sourceLocation(
locStart(id),
locEnd(ex),
)),
ID: id,
Init: ex,
},
}
}
func (p *parser) parseIdentStatement() ast.Statement {
id := p.parseIdentifier()
switch _, tok, _ := p.peek(); tok {
case token.ASSIGN:
expr := p.parseAssignStatement()
return &ast.VariableAssignment{
BaseNode: p.baseNode(p.sourceLocation(
locStart(id),
locEnd(expr),
)),
ID: id,
Init: expr,
}
default:
expr := p.parseExpressionSuffix(id)
loc := expr.Location()
return &ast.ExpressionStatement{
Expression: expr,
BaseNode: p.baseNode(&loc),
}
}
}
func (p *parser) parseAssignStatement() ast.Expression {
p.expect(token.ASSIGN)
return p.parseExpression()
}
func (p *parser) parseReturnStatement() *ast.ReturnStatement {
pos, _ := p.expect(token.RETURN)
expr := p.parseExpression()
return &ast.ReturnStatement{
Argument: expr,
BaseNode: p.baseNode(p.sourceLocation(
p.s.File().Position(pos),
locEnd(expr),
)),
}
}
func (p *parser) parseExpressionStatement() *ast.ExpressionStatement {
stmt := &ast.ExpressionStatement{
Expression: p.parseExpression(),
}
if stmt.Expression != nil {
loc := stmt.Expression.Location()
stmt.BaseNode = p.baseNode(&loc)
} else {
stmt.BaseNode = p.baseNode(nil)
}
return stmt
}
func (p *parser) parseBlock() *ast.Block {
start, _ := p.open(token.LBRACE, token.RBRACE)
stmts := p.parseStatementList()
end, rbrace := p.close(token.RBRACE)
return &ast.Block{
Body: stmts,
BaseNode: p.position(start, end+token.Pos(len(rbrace))),
}
}
func (p *parser) parseExpression() ast.Expression {
return p.parseConditionalExpression()
}
// parseExpressionWhile will continue to parse expressions until
// the function while the function returns true.
// If there are multiple ast.Expression nodes that are parsed,
// they will be combined into an invalid ast.BinaryExpr node.
// In a well-formed document, this function works identically to
// parseExpression.
func (p *parser) parseExpressionWhile(fn func() bool) ast.Expression {
var expr ast.Expression
for fn() {
e := p.parseExpression()
if e == nil {
// We expected to parse an expression but read nothing.
// We need to skip past this token.
// TODO(jsternberg): We should pretend the token is
// an operator and create a binary expression.
// For now, skip past it.
pos, _, lit := p.scan()
loc := p.loc(pos, pos+token.Pos(len(lit)))
p.errs = append(p.errs, ast.Error{
Msg: fmt.Sprintf("invalid expression %s@%d:%d-%d:%d: %s", loc.File, loc.Start.Line, loc.Start.Column, loc.End.Line, loc.End.Column, lit),
})
continue
}
if expr != nil {
expr = &ast.BinaryExpression{
BaseNode: p.baseNode(p.sourceLocation(
locStart(expr),
locEnd(e),
)),
Left: expr,
Right: e,
}
} else {
expr = e
}
}
return expr
}
func (p *parser) parseExpressionSuffix(expr ast.Expression) ast.Expression {
p.repeat(p.parsePostfixOperatorSuffix(&expr))
p.repeat(p.parsePipeExpressionSuffix(&expr))
p.repeat(p.parseMultiplicativeExpressionSuffix(&expr))
p.repeat(p.parseAdditiveExpressionSuffix(&expr))
p.repeat(p.parseComparisonExpressionSuffix(&expr))
p.repeat(p.parseLogicalAndExpressionSuffix(&expr))
p.repeat(p.parseLogicalOrExpressionSuffix(&expr))
return expr
}
func (p *parser) parseExpressionList() []ast.Expression {
var exprs []ast.Expression
for p.more() {
switch _, tok, _ := p.peek(); tok {
case token.IDENT, token.INT, token.FLOAT, token.STRING, token.DIV,
token.TIME, token.DURATION, token.PIPE_RECEIVE,
token.LPAREN, token.LBRACK, token.LBRACE,
token.ADD, token.SUB, token.NOT, token.EXISTS:
exprs = append(exprs, p.parseExpression())
default:
// TODO(jsternberg): BadExpression.
p.consume()
continue
}
if _, tok, _ := p.peek(); tok == token.COMMA {
p.consume()
}
}
return exprs
}
func (p *parser) parseConditionalExpression() ast.Expression {
if ifPos, tok, _ := p.peek(); tok == token.IF {
p.consume()
test := p.parseExpression()
p.expect(token.THEN)
consequent := p.parseExpression()
p.expect(token.ELSE)
alternate := p.parseExpression()
return &ast.ConditionalExpression{
BaseNode: p.baseNode(p.sourceLocation(
p.s.File().Position(ifPos),
locEnd(alternate))),
Test: test,
Consequent: consequent,
Alternate: alternate,
}
}
return p.parseLogicalOrExpression()
}
func (p *parser) parseLogicalAndExpression() ast.Expression {
expr := p.parseUnaryLogicalExpression()
p.repeat(p.parseLogicalAndExpressionSuffix(&expr))
return expr
}
func (p *parser) parseLogicalOrExpression() ast.Expression {
expr := p.parseLogicalAndExpression()
p.repeat(p.parseLogicalOrExpressionSuffix(&expr))
return expr
}
func (p *parser) parseLogicalAndExpressionSuffix(expr *ast.Expression) func() bool {
return func() bool {
op, ok := p.parseLogicalAndOperator()
if !ok {
return false
}
rhs := p.parseUnaryLogicalExpression()
*expr = &ast.LogicalExpression{
Operator: op,
Left: *expr,
Right: rhs,
BaseNode: p.baseNode(p.sourceLocation(
locStart(*expr),
locEnd(rhs),
)),
}
return true
}
}
func (p *parser) parseLogicalOrExpressionSuffix(expr *ast.Expression) func() bool {
return func() bool {
op, ok := p.parseLogicalOrOperator()
if !ok {
return false
}
rhs := p.parseLogicalAndExpression()
*expr = &ast.LogicalExpression{
Operator: op,
Left: *expr,
Right: rhs,
BaseNode: p.baseNode(p.sourceLocation(
locStart(*expr),
locEnd(rhs),
)),
}
return true
}
}
func (p *parser) parseLogicalAndOperator() (ast.LogicalOperatorKind, bool) {
switch _, tok, _ := p.peek(); tok {
case token.AND:
p.consume()
return ast.AndOperator, true
default:
return 0, false
}
}
func (p *parser) parseLogicalOrOperator() (ast.LogicalOperatorKind, bool) {
switch _, tok, _ := p.peek(); tok {
case token.OR:
p.consume()
return ast.OrOperator, true
default:
return 0, false
}
}
func (p *parser) parseUnaryLogicalExpression() ast.Expression {
pos, op, ok := p.parseUnaryLogicalOperator()
if ok {
expr := p.parseUnaryLogicalExpression()
return &ast.UnaryExpression{
Operator: op,
Argument: expr,
BaseNode: p.baseNode(p.sourceLocation(
p.s.File().Position(pos),
locEnd(expr),
)),
}
}
return p.parseComparisonExpression()
}
func (p *parser) parseUnaryLogicalOperator() (token.Pos, ast.OperatorKind, bool) {
switch pos, tok, _ := p.peek(); tok {
case token.NOT:
p.consume()
return pos, ast.NotOperator, true
case token.EXISTS:
p.consume()
return pos, ast.ExistsOperator, true
default:
return 0, 0, false
}
}
func (p *parser) parseComparisonExpression() ast.Expression {
expr := p.parseAdditiveExpression()
p.repeat(p.parseComparisonExpressionSuffix(&expr))
return expr
}
func (p *parser) parseComparisonExpressionSuffix(expr *ast.Expression) func() bool {
return func() bool {
op, ok := p.parseComparisonOperator()
if !ok {
return false
}
rhs := p.parseAdditiveExpression()
*expr = &ast.BinaryExpression{
Operator: op,
Left: *expr,
Right: rhs,
BaseNode: p.baseNode(p.sourceLocation(
locStart(*expr),
locEnd(rhs),
)),
}
return true
}
}
func (p *parser) parseComparisonOperator() (ast.OperatorKind, bool) {
switch _, tok, _ := p.peek(); tok {
case token.EQ:
p.consume()
return ast.EqualOperator, true
case token.NEQ:
p.consume()
return ast.NotEqualOperator, true
case token.LTE:
p.consume()
return ast.LessThanEqualOperator, true
case token.LT:
p.consume()
return ast.LessThanOperator, true
case token.GTE:
p.consume()
return ast.GreaterThanEqualOperator, true
case token.GT:
p.consume()
return ast.GreaterThanOperator, true
case token.REGEXEQ:
p.consume()
return ast.RegexpMatchOperator, true
case token.REGEXNEQ:
p.consume()
return ast.NotRegexpMatchOperator, true
default:
return 0, false
}
}
func (p *parser) parseAdditiveExpression() ast.Expression {
expr := p.parseMultiplicativeExpression()
p.repeat(p.parseAdditiveExpressionSuffix(&expr))
return expr
}
func (p *parser) parseAdditiveExpressionSuffix(expr *ast.Expression) func() bool {
return func() bool {
op, ok := p.parseAdditiveOperator()
if !ok {
return false
}
rhs := p.parseMultiplicativeExpression()
*expr = &ast.BinaryExpression{
Operator: op,
Left: *expr,
Right: rhs,
BaseNode: p.baseNode(p.sourceLocation(
locStart(*expr),
locEnd(rhs),
)),
}
return true
}
}
func (p *parser) parseAdditiveOperator() (ast.OperatorKind, bool) {
switch _, tok, _ := p.peek(); tok {
case token.ADD:
p.consume()
return ast.AdditionOperator, true
case token.SUB:
p.consume()
return ast.SubtractionOperator, true
default:
return 0, false
}
}
func (p *parser) parseMultiplicativeExpression() ast.Expression {
expr := p.parsePipeExpression()
p.repeat(p.parseMultiplicativeExpressionSuffix(&expr))
return expr
}
func (p *parser) parseMultiplicativeExpressionSuffix(expr *ast.Expression) func() bool {
return func() bool {
op, ok := p.parseMultiplicativeOperator()
if !ok {
return false
}
rhs := p.parsePipeExpression()
*expr = &ast.BinaryExpression{
Operator: op,
Left: *expr,
Right: rhs,
BaseNode: p.baseNode(p.sourceLocation(
locStart(*expr),
locEnd(rhs),
)),
}
return true
}
}
func (p *parser) parseMultiplicativeOperator() (ast.OperatorKind, bool) {
switch _, tok, _ := p.peek(); tok {
case token.MUL:
p.consume()
return ast.MultiplicationOperator, true
case token.DIV:
p.consume()
return ast.DivisionOperator, true
case token.MOD:
p.consume()
return ast.ModuloOperator, true
case token.POW:
p.consume()
return ast.PowerOperator, true
default:
return 0, false
}
}
func (p *parser) parsePipeExpression() ast.Expression {
expr := p.parseUnaryExpression()
p.repeat(p.parsePipeExpressionSuffix(&expr))
return expr
}
func (p *parser) parsePipeExpressionSuffix(expr *ast.Expression) func() bool {
return func() bool {
if ok := p.parsePipeOperator(); !ok {
return false
}
// todo(jsternberg): this is not correct.
rhs := p.parseUnaryExpression()
call, ok := rhs.(*ast.CallExpression)
if !ok && rhs != nil {
// We did not parse a call expression, but we still have something
// that was parsed so we need to pass over any errors from it
// and the location information so those remain present.
// We are losing the expression, so check for errors so that they
// are included in the output.
ast.Check(rhs)
// Copy the information to a blank call expression.
call = &ast.CallExpression{}
if loc := rhs.Location(); loc.IsValid() {
call.Loc = &loc
}
call.Errors = rhs.Errs()
call.Errors = append(call.Errors, ast.Error{
Msg: "pipe destination must be a function call",
})
}
*expr = &ast.PipeExpression{
Argument: *expr,
Call: call,
BaseNode: p.baseNode(p.sourceLocation(
locStart(*expr),
locEnd(rhs),
)),
}
return true
}
}
func (p *parser) parsePipeOperator() bool {
if _, tok, _ := p.peek(); tok == token.PIPE_FORWARD {
p.consume()
return true
}
return false
}
func (p *parser) parseUnaryExpression() ast.Expression {
pos, op, ok := p.parsePrefixOperator()
if ok {
expr := p.parseUnaryExpression()
return &ast.UnaryExpression{
Operator: op,
Argument: expr,
BaseNode: p.baseNode(p.sourceLocation(
p.s.File().Position(pos),
locEnd(expr),
)),
}
}
return p.parsePostfixExpression()
}
func (p *parser) parsePrefixOperator() (token.Pos, ast.OperatorKind, bool) {
switch pos, tok, _ := p.peek(); tok {
case token.ADD:
p.consume()
return pos, ast.AdditionOperator, true
case token.SUB:
p.consume()
return pos, ast.SubtractionOperator, true
default:
return 0, 0, false
}
}
func (p *parser) parsePostfixExpression() ast.Expression {
expr := p.parsePrimaryExpression()
for {
if ok := p.parsePostfixOperator(&expr); !ok {
return expr
}
}
}
func (p *parser) parsePostfixOperatorSuffix(expr *ast.Expression) func() bool {
return func() bool {
return p.parsePostfixOperator(expr)
}
}
func (p *parser) parsePostfixOperator(expr *ast.Expression) bool {
switch _, tok, _ := p.peek(); tok {
case token.DOT:
*expr = p.parseDotExpression(*expr)
return true
case token.LPAREN:
*expr = p.parseCallExpression(*expr)
return true
case token.LBRACK:
*expr = p.parseIndexExpression(*expr)
return true
}
return false
}
func (p *parser) parseDotExpression(expr ast.Expression) ast.Expression {
p.expect(token.DOT)
ident := p.parseIdentifier()
return &ast.MemberExpression{
Object: expr,
Property: ident,
BaseNode: p.baseNode(p.sourceLocation(
locStart(expr),
locEnd(ident),
)),
}
}
func (p *parser) parseCallExpression(callee ast.Expression) ast.Expression {
p.open(token.LPAREN, token.RPAREN)
params := p.parsePropertyList()
end, rparen := p.close(token.RPAREN)
expr := &ast.CallExpression{
Callee: callee,
BaseNode: p.baseNode(p.sourceLocation(
locStart(callee),
p.s.File().Position(end+token.Pos(len(rparen))),
)),
}
if len(params) > 0 {
expr.Arguments = []ast.Expression{
&ast.ObjectExpression{
Properties: params,
BaseNode: p.baseNode(p.sourceLocation(
locStart(params[0]),
locEnd(params[len(params)-1]),
)),
},
}
}
return expr
}
func (p *parser) parseIndexExpression(callee ast.Expression) ast.Expression {
p.open(token.LBRACK, token.RBRACK)
expr := p.parseExpressionWhile(p.more)
end, rbrack := p.close(token.RBRACK)
if lit, ok := expr.(*ast.StringLiteral); ok {
return &ast.MemberExpression{
Object: callee,
Property: lit,
BaseNode: p.baseNode(p.sourceLocation(
locStart(callee),
p.s.File().Position(end+token.Pos(len(rbrack))),
)),
}
}
return &ast.IndexExpression{
Array: callee,
Index: expr,
BaseNode: p.baseNode(p.sourceLocation(
locStart(callee),
p.s.File().Position(end+token.Pos(len(rbrack))),
)),
}
}
func (p *parser) parsePrimaryExpression() ast.Expression {
switch _, tok, _ := p.peekWithRegex(); tok {
case token.IDENT:
return p.parseIdentifier()
case token.INT:
return p.parseIntLiteral()
case token.FLOAT:
return p.parseFloatLiteral()
case token.STRING:
return p.parseStringLiteral()
case token.QUOTE:
return p.parseStringExpression()
case token.REGEX:
return p.parseRegexpLiteral()
case token.TIME:
return p.parseTimeLiteral()
case token.DURATION:
return p.parseDurationLiteral()
case token.PIPE_RECEIVE:
return p.parsePipeLiteral()
case token.LBRACK:
return p.parseArrayLiteral()
case token.LBRACE:
return p.parseObjectLiteral()
case token.LPAREN:
return p.parseParenExpression()
default:
return nil
}
}
func (p *parser) parseStringExpression() *ast.StringExpression {
beg, _ := p.expect(token.QUOTE)
var parts []ast.StringExpressionPart
for {
pos, tok, lit := p.s.ScanStringExpr()
switch tok {
case token.TEXT:
parts = append(parts, &ast.TextPart{
Value: lit,
BaseNode: p.posRange(pos, len(lit)),
})
case token.STRINGEXPR:
expr := p.parseExpression()
end, lit := p.expect(token.RBRACE)
parts = append(parts, &ast.InterpolatedPart{
Expression: expr,
BaseNode: p.position(pos, end+token.Pos(len(lit))),
})
case token.QUOTE:
return &ast.StringExpression{
Parts: parts,
BaseNode: p.position(beg, pos+token.Pos(len(lit))),
}
default:
// TODO bad expression
return nil
}
}
}
func (p *parser) parseIdentifier() *ast.Identifier {
pos, lit := p.expect(token.IDENT)
return &ast.Identifier{
Name: lit,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseIntLiteral() *ast.IntegerLiteral {
pos, lit := p.expect(token.INT)
// todo(jsternberg): handle errors.
value, err := strconv.ParseInt(lit, 10, 64)
if err != nil {
// If the error message comes from strconv.ParseInt, we want
// to remove the first two parts from the error message as they are
// very Go specific and we want a generic error message.
msg := err.Error()
if strings.HasPrefix(msg, "strconv.ParseInt:") {
parts := strings.SplitN(err.Error(), ": ", 3)
msg = parts[len(parts)-1]
}
p.error(fmt.Sprintf("invalid integer literal %q: %s", lit, msg))
// Reset this to zero for consistency with the Rust implementation.
value = 0
}
return &ast.IntegerLiteral{
Value: value,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseFloatLiteral() *ast.FloatLiteral {
pos, lit := p.expect(token.FLOAT)
// todo(jsternberg): handle errors.
value, _ := strconv.ParseFloat(lit, 64)
return &ast.FloatLiteral{
Value: value,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseStringLiteral() *ast.StringLiteral {
pos, lit := p.expect(token.STRING)
value, _ := ParseString(lit)
return &ast.StringLiteral{
Value: value,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseRegexpLiteral() *ast.RegexpLiteral {
pos, lit := p.expect(token.REGEX)
value, err := ParseRegexp(lit)
if err != nil {
p.error(err.Error())
}
return &ast.RegexpLiteral{
Value: value,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseTimeLiteral() *ast.DateTimeLiteral {
pos, lit := p.expect(token.TIME)
value, _ := ParseTime(lit)
return &ast.DateTimeLiteral{
Value: value,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseDurationLiteral() *ast.DurationLiteral {
pos, lit := p.expect(token.DURATION)
// todo(jsternberg): handle errors.
d, _ := ParseDuration(lit)
return &ast.DurationLiteral{
Values: d,
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parsePipeLiteral() *ast.PipeLiteral {
pos, lit := p.expect(token.PIPE_RECEIVE)
return &ast.PipeLiteral{
BaseNode: p.posRange(pos, len(lit)),
}
}
func (p *parser) parseArrayLiteral() ast.Expression {
start, _ := p.open(token.LBRACK, token.RBRACK)
exprs := p.parseExpressionList()
end, rbrack := p.close(token.RBRACK)
return &ast.ArrayExpression{
Elements: exprs,
BaseNode: p.position(start, end+token.Pos(len(rbrack))),
}
}
func (p *parser) parseObjectLiteral() ast.Expression {
start, _ := p.open(token.LBRACE, token.RBRACE)
obj := p.parseObjectBody()
end, rbrace := p.close(token.RBRACE)
obj.BaseNode = p.position(start, end+token.Pos(len(rbrace)))
return obj
}
func (p *parser) parseParenExpression() ast.Expression {
pos, _ := p.open(token.LPAREN, token.RPAREN)
return p.parseParenBodyExpression(pos)
}
func (p *parser) parseParenBodyExpression(lparen token.Pos) ast.Expression {
switch _, tok, _ := p.peek(); tok {
case token.RPAREN:
p.close(token.RPAREN)
return p.parseFunctionExpression(lparen, nil)
case token.IDENT:
ident := p.parseIdentifier()
return p.parseParenIdentExpression(lparen, ident)
default:
expr := p.parseExpressionWhile(p.more)
p.close(token.RPAREN)
return expr
}
}
func (p *parser) parseParenIdentExpression(lparen token.Pos, key *ast.Identifier) ast.Expression {
switch _, tok, _ := p.peek(); tok {
case token.RPAREN:
p.close(token.RPAREN)
if _, tok, _ := p.peek(); tok == token.ARROW {
loc := key.Location()
return p.parseFunctionExpression(lparen, []*ast.Property{{
Key: key,
BaseNode: p.baseNode(&loc),
}})
}
return key
case token.ASSIGN:
p.consume()
value := p.parseExpression()
params := []*ast.Property{{
Key: key,
Value: value,
BaseNode: p.baseNode(p.sourceLocation(
locStart(key),
locEnd(value),
)),
}}
if _, tok, _ := p.peek(); tok == token.COMMA {
p.consume()
params = append(params, p.parseParameterList()...)
}
p.close(token.RPAREN)
return p.parseFunctionExpression(lparen, params)
case token.COMMA:
p.consume()
loc := key.Location()
params := []*ast.Property{{
Key: key,
BaseNode: p.baseNode(&loc),
}}
params = append(params, p.parseParameterList()...)
p.close(token.RPAREN)
return p.parseFunctionExpression(lparen, params)
default:
expr := p.parseExpressionSuffix(key)
for p.more() {
rhs := p.parseExpression()
if rhs == nil {
pos, _, lit := p.scan()
loc := p.loc(pos, pos+token.Pos(len(lit)))
p.errs = append(p.errs, ast.Error{
Msg: fmt.Sprintf("invalid expression %s@%d:%d-%d:%d: %s", loc.File, loc.Start.Line, loc.Start.Column, loc.End.Line, loc.End.Column, lit),
})
continue
}
expr = &ast.BinaryExpression{
BaseNode: p.baseNode(p.sourceLocation(
locStart(expr),
locEnd(rhs),
)),
Left: expr,
Right: rhs,
}
}
p.close(token.RPAREN)
return expr
}
}
func (p *parser) parseObjectBody() *ast.ObjectExpression {
switch _, tok, _ := p.peek(); tok {
case token.IDENT:
ident := p.parseIdentifier()
return p.parseObjectBodySuffix(ident)
case token.STRING:
str := p.parseStringLiteral()
properties := p.parsePropertyListSuffix(str)
return &ast.ObjectExpression{
Properties: properties,
}
default:
return &ast.ObjectExpression{
Properties: p.parsePropertyList(),
}
}
}
func (p *parser) parseObjectBodySuffix(ident *ast.Identifier) *ast.ObjectExpression {
switch _, tok, lit := p.peek(); tok {
case token.IDENT:
if lit != "with" {
// TODO(nathanielc) BadExpression since we had two idents in a row
return nil
}
p.consume()
properties := p.parsePropertyList()
return &ast.ObjectExpression{
With: ident,
Properties: properties,
}
default:
properties := p.parsePropertyListSuffix(ident)
return &ast.ObjectExpression{
Properties: properties,
}
}
}
func (p *parser) parsePropertyListSuffix(key ast.PropertyKey) []*ast.Property {
var properties []*ast.Property
prop := p.parsePropertySuffix(key)
properties = append(properties, prop)
// if there's not more, return
if !p.more() {
return properties
}
switch _, tok, lit := p.peek(); tok {
case token.COMMA:
p.consume()
default:
p.errs = append(p.errs, ast.Error{
Msg: fmt.Sprintf("expected comma in property list, got %s (%q)", tok, lit),
})
}
properties = append(properties, p.parsePropertyList()...)
return properties
}
func (p *parser) parsePropertyList() []*ast.Property {
var params []*ast.Property
perrs := make([]ast.Error, 0)
for p.more() {
var param *ast.Property
switch _, tok, _ := p.peek(); tok {
case token.IDENT:
param = p.parseIdentProperty()
case token.STRING:
param = p.parseStringProperty()
default:
param = p.parseInvalidProperty()
}
params = append(params, param)
if p.more() {
if _, tok, lit := p.peek(); tok != token.COMMA {
perrs = append(perrs, ast.Error{
Msg: fmt.Sprintf("expected comma in property list, got %s (%q)", tok, lit),
})
} else {
p.consume()
}
}
}
p.errs = append(p.errs, perrs...)
return params
}
func (p *parser) parseStringProperty() *ast.Property {
key := p.parseStringLiteral()
return p.parsePropertySuffix(key)
}
func (p *parser) parseIdentProperty() *ast.Property {
key := p.parseIdentifier()
return p.parsePropertySuffix(key)
}
func (p *parser) parsePropertySuffix(key ast.PropertyKey) *ast.Property {
property := &ast.Property{
Key: key,
}
var loc ast.BaseNode
if _, tok, _ := p.peek(); tok == token.COLON {
p.consume()
property.Value = p.parsePropertyValue()
loc = p.baseNode(p.sourceLocation(
locStart(key),
locEnd(property.Value)))
} else {
loc = p.baseNode(p.sourceLocation(locStart(key), locEnd(key)))
}
property.BaseNode = loc
return property
}
func (p *parser) parseInvalidProperty() *ast.Property {
prop := &ast.Property{}
var perrs []ast.Error
startPos, tok, lit := p.peek()
switch tok {
case token.COLON:
perrs = append(perrs, ast.Error{
Msg: "missing property key",
})
p.consume()
prop.Value = p.parsePropertyValue()
case token.COMMA:
perrs = append(perrs, ast.Error{
Msg: "missing property in property list",
})
default:
perrs = append(perrs, ast.Error{
Msg: fmt.Sprintf("unexpected token for property key: %s (%q)", tok, lit),
})
// We are not really parsing an expression, this is just a way to advance to
// to just before the next comma, colon, end of block, or EOF.
p.parseExpressionWhile(func() bool {
if _, tok, _ := p.peek(); tok == token.COMMA || tok == token.COLON {
return false
}
return p.more()
})
// If we stopped at a colon, attempt to parse the value
if _, tok, _ := p.peek(); tok == token.COLON {
p.consume()
prop.Value = p.parsePropertyValue()
}
}
endPos, _, _ := p.peek()
p.errs = append(p.errs, perrs...)
prop.BaseNode = p.position(startPos, endPos)
return prop
}
func (p *parser) parsePropertyValue() ast.Expression {
e := p.parseExpressionWhile(func() bool {
if _, tok, _ := p.peek(); tok == token.COMMA || tok == token.COLON {
return false
}
return p.more()
})
if e == nil {
// TODO: return a BadExpression here. It would help simplify logic.
p.errs = append(p.errs, ast.Error{
Msg: "missing property value",
})
}
return e
}
func (p *parser) parseParameterList() []*ast.Property {
var params []*ast.Property
for {
if !p.more() {
return params
}
param := p.parseParameter()
params = append(params, param)
if _, tok, _ := p.peek(); tok == token.COMMA {
p.consume()
}
}
}
func (p *parser) parseParameter() *ast.Property {
key := p.parseIdentifier()
loc := key.Location()
param := &ast.Property{
Key: key,
BaseNode: p.baseNode(&loc),
}
if _, tok, _ := p.peek(); tok == token.ASSIGN {
p.consume()
param.Value = p.parseExpression()
param.Loc = p.sourceLocation(
locStart(key),
locEnd(param.Value),
)
}
return param
}
func (p *parser) parseFunctionExpression(lparen token.Pos, params []*ast.Property) ast.Expression {
p.expect(token.ARROW)
return p.parseFunctionBodyExpression(lparen, params)
}
func (p *parser) parseFunctionBodyExpression(lparen token.Pos, params []*ast.Property) ast.Expression {
_, tok, _ := p.peek()
fn := &ast.FunctionExpression{
Params: params,
Body: func() ast.Node {
switch tok {
case token.LBRACE:
return p.parseBlock()
default:
return p.parseExpression()
}
}(),
}
fn.BaseNode = p.baseNode(p.sourceLocation(
p.s.File().Position(lparen),
locEnd(fn.Body),
))
return fn
}
// scan will read the next token from the Scanner. If peek has been used,
// this will return the peeked token and consume it.
func (p *parser) scan() (token.Pos, token.Token, string) {
if p.buffered {
p.buffered = false
return p.pos, p.tok, p.lit
}
pos, tok, lit := p.s.Scan()
return pos, tok, lit
}
// peek will read the next token from the Scanner and then buffer it.
// It will return information about the token.
func (p *parser) peek() (token.Pos, token.Token, string) {
if !p.buffered {
p.pos, p.tok, p.lit = p.s.Scan()
p.buffered = true
}
return p.pos, p.tok, p.lit
}
// peekWithRegex is the same as peek, except that the scan step will allow scanning regexp tokens.
func (p *parser) peekWithRegex() (token.Pos, token.Token, string) {
if p.buffered {
if p.tok != token.DIV {
return p.pos, p.tok, p.lit
}
p.s.Unread()
}
p.pos, p.tok, p.lit = p.s.ScanWithRegex()
p.buffered = true
return p.pos, p.tok, p.lit
}
// consume will consume a token that has been retrieve using peek.
// This will panic if a token has not been buffered with peek.
func (p *parser) consume() {
if !p.buffered {
panic("called consume on an unbuffered input")
}
p.buffered = false
}
// expect will continuously scan the input until it reads the requested
// token. If a token has been buffered by peek, then the token will
// be read if it matches or will be discarded if it is the wrong token.
func (p *parser) expect(exp token.Token) (token.Pos, string) {
for {
pos, tok, lit := p.scan()
if tok == token.EOF || tok == exp {
if tok == token.EOF {
p.errs = append(p.errs, ast.Error{
Msg: fmt.Sprintf("expected %s, got EOF", exp),
})
}
return pos, lit
}
p.errs = append(p.errs, ast.Error{
Msg: fmt.Sprintf("expected %s, got %s (%q) at %s",
exp,
tok,
lit,
p.s.File().Position(pos),
),
})
}
}
// repeat will repeatedly call the function until it returns false.
func (p *parser) repeat(fn func() bool) {
for {
if ok := fn(); !ok {
return
}
}
}
// open will open a new block. It will expect that the next token
// is the start token and mark that we expect the end token in the
// future.
func (p *parser) open(start, end token.Token) (pos token.Pos, lit string) {
pos, lit = p.expect(start)
p.blocks[end]++
return pos, lit
}
// more will check if we should continue reading tokens for the
// current block. This is true when the next token is not EOF and
// the next token is also not one that would close a block.
func (p *parser) more() bool {
_, tok, _ := p.peek()
if tok == token.EOF {
return false
}
return p.blocks[tok] == 0
}
// close will close a block that was opened using open.
//
// This function will always decrement the block count for the end
// token.
//
// If the next token is the end token, then this will consume the
// token and return the pos and lit for the token. Otherwise, it will
// return NoPos.
//
// TODO(jsternberg): NoPos doesn't exist yet so this will return the
// values for the next token even if it isn't consumed.
func (p *parser) close(end token.Token) (pos token.Pos, lit string) {
// If the end token is EOF, we have to do this specially
// since we don't track EOF.
if end == token.EOF {
// TODO(jsternberg): Check for EOF and panic if it isn't.
pos, _, lit := p.scan()
return pos, lit
}
// The end token must be in the block map.
count := p.blocks[end]
if count <= 0 {
panic("closing a block that was never opened")
}
p.blocks[end] = count - 1
// Read the next token.
pos, tok, lit := p.peek()
if tok == end {
p.consume()
return pos, lit
}
// TODO(jsternberg): Return NoPos when the positioning code
// is prepared for that.
// Append an error to the current node.
p.errs = append(p.errs, ast.Error{
Msg: fmt.Sprintf("expected %s, got %s", end, tok),
})
return pos, lit
}
func (p *parser) loc(start, end token.Pos) *ast.SourceLocation {
soffset := int(start) - p.s.File().Base()
eoffset := int(end) - p.s.File().Base()
return &ast.SourceLocation{
File: p.s.File().Name(),
Start: p.s.File().Position(start),
End: p.s.File().Position(end),
Source: string(p.src[soffset:eoffset]),
}
}
// position will return a BaseNode with the position information
// filled based on the start and end position.
func (p *parser) position(start, end token.Pos) ast.BaseNode {
return p.baseNode(p.loc(start, end))
}
// posRange will posRange the position cursor to the end of the given
// literal.
func (p *parser) posRange(start token.Pos, sz int) ast.BaseNode {
return p.position(start, start+token.Pos(sz))
}
// sourceLocation constructs an ast.SourceLocation from two
// ast.Position values.
func (p *parser) sourceLocation(start, end ast.Position) *ast.SourceLocation {
soffset := p.s.File().Offset(start)
if soffset == -1 {
return nil
}
eoffset := p.s.File().Offset(end)
if eoffset == -1 {
return nil
}
return &ast.SourceLocation{
File: p.s.File().Name(),
Start: start,
End: end,
Source: string(p.src[soffset:eoffset]),
}
}
func (p *parser) baseNode(loc *ast.SourceLocation) ast.BaseNode {
bnode := ast.BaseNode{
Errors: p.errs,
}
if loc != nil && loc.IsValid() {
bnode.Loc = loc
}
p.errs = nil
return bnode
}
func (p *parser) error(msg string) {
p.errs = append(p.errs, ast.Error{
Msg: msg,
})
}
// locStart is a utility method for retrieving the start position
// from a node. This is needed only because error handling isn't present
// so it is possible for nil nodes to be present.
func locStart(node ast.Node) ast.Position {
if node == nil {
return ast.Position{}
}
return node.Location().Start
}
// locEnd is a utility method for retrieving the end position
// from a node. This is needed only because error handling isn't present
// so it is possible for nil nodes to be present.
func locEnd(node ast.Node) ast.Position {
if node == nil {
return ast.Position{}
}
return node.Location().End
}
| 1 | 11,784 | drop the todo? | influxdata-flux | go |
@@ -383,7 +383,9 @@ void Doors::HandleClick(Client* sender, uint8 trigger) {
if (!IsDoorOpen() || (open_type == 58)) {
if (!disable_timer)
close_timer.Start();
- SetOpenState(true);
+
+ if(strncmp(destination_zone_name, "NONE", strlen("NONE")) == 0)
+ SetOpenState(true);
} else {
close_timer.Disable();
if (!disable_timer) | 1 | /* EQEMu: Everquest Server Emulator
Copyright (C) 2001-2002 EQEMu Development Team (http://eqemu.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; 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
*/
#include "../common/global_define.h"
#include "../common/eqemu_logsys.h"
#include "../common/string_util.h"
#include "client.h"
#include "doors.h"
#include "entity.h"
#include "guild_mgr.h"
#include "mob.h"
#include "string_ids.h"
#include "worldserver.h"
#include "zonedb.h"
#include "zone_store.h"
#include "../common/repositories/criteria/content_filter_criteria.h"
#include <iostream>
#include <string.h>
#define OPEN_DOOR 0x02
#define CLOSE_DOOR 0x03
#define OPEN_INVDOOR 0x03
#define CLOSE_INVDOOR 0x02
extern EntityList entity_list;
extern WorldServer worldserver;
Doors::Doors(const DoorsRepository::Doors& door) :
close_timer(5000),
m_Position(door.pos_x, door.pos_y, door.pos_z, door.heading),
m_Destination(door.dest_x, door.dest_y, door.dest_z, door.dest_heading)
{
strn0cpy(zone_name, door.zone.c_str(), sizeof(zone_name));
strn0cpy(door_name, door.name.c_str(), sizeof(door_name));
strn0cpy(destination_zone_name, door.dest_zone.c_str(), sizeof(destination_zone_name));
database_id = door.id;
door_id = door.doorid;
incline = door.incline;
open_type = door.opentype;
guild_id = door.guild;
lockpick = door.lockpick;
key_item_id = door.keyitem;
no_key_ring = door.nokeyring;
trigger_door = door.triggerdoor;
trigger_type = door.triggertype;
triggered = false;
door_param = door.door_param;
size = door.size;
invert_state = door.invert_state;
destination_instance_id = door.dest_instance;
is_ldon_door = door.is_ldon_door;
client_version_mask = door.client_version_mask;
SetOpenState(false);
close_timer.Disable();
disable_timer = (door.disable_timer == 1 ? true : false);
}
Doors::Doors(const char *model, const glm::vec4 &position, uint8 open_type, uint16 size) :
close_timer(5000),
m_Position(position),
m_Destination(glm::vec4()){
strn0cpy(zone_name, zone->GetShortName(), 32);
strn0cpy(door_name, model, 32);
strn0cpy(destination_zone_name, "NONE", 32);
this->database_id = (uint32) content_db.GetDoorsCountPlusOne(zone->GetShortName(), zone->GetInstanceVersion());
this->door_id = (uint8) content_db.GetDoorsDBCountPlusOne(zone->GetShortName(), zone->GetInstanceVersion());
this->open_type = open_type;
this->size = size;
this->incline = 0;
this->guild_id = 0;
this->lockpick = 0;
this->key_item_id = 0;
this->no_key_ring = 0;
this->trigger_door = 0;
this->trigger_type = 0;
this->triggered = false;
this->door_param = 0;
this->invert_state = 0;
this->is_ldon_door = 0;
this->client_version_mask = 4294967295u;
this->disable_timer = 0;
this->destination_instance_id = 0;
SetOpenState(false);
close_timer.Disable();
}
Doors::~Doors()
{
}
bool Doors::Process()
{
if (close_timer.Enabled() && close_timer.Check() && IsDoorOpen()) {
if (open_type == 40 || GetTriggerType() == 1) {
auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct));
MoveDoor_Struct *md = (MoveDoor_Struct *) outapp->pBuffer;
md->doorid = door_id;
md->action = invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR;
entity_list.QueueClients(0, outapp);
safe_delete(outapp);
}
triggered = false;
close_timer.Disable();
SetOpenState(false);
}
return true;
}
void Doors::HandleClick(Client* sender, uint8 trigger) {
Log(Logs::Detail, Logs::Doors,
"%s clicked door %s (dbid %d, eqid %d) at %s",
sender->GetName(),
this->door_name,
this->database_id,
this->door_id,
to_string(m_Position).c_str()
);
Log(Logs::Detail, Logs::Doors,
"incline %d, open_type %d, lockpick %d, key %d, nokeyring %d, trigger %d type %d, param %d",
this->incline,
this->open_type,
this->lockpick,
this->key_item_id,
this->no_key_ring,
this->trigger_door,
this->trigger_type,
this->door_param
);
Log(Logs::Detail, Logs::Doors,
"disable_timer '%s',size %d, invert %d, dest: %s %s",
(this->disable_timer ? "true" : "false"),
this->size,
this->invert_state,
this->destination_zone_name,
to_string(m_Destination).c_str()
);
auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct));
auto *move_door_packet = (MoveDoor_Struct *) outapp->pBuffer;
move_door_packet->doorid = door_id;
if (this->IsLDoNDoor()) {
if (sender) {
if (RuleI(Adventure, ItemIDToEnablePorts) != 0) {
if (!sender->KeyRingCheck(RuleI(Adventure, ItemIDToEnablePorts))) {
if (sender->GetInv().HasItem(RuleI(Adventure, ItemIDToEnablePorts)) == INVALID_INDEX) {
sender->MessageString(Chat::Red, DUNGEON_SEALED);
safe_delete(outapp);
return;
} else {
sender->KeyRingAdd(RuleI(Adventure, ItemIDToEnablePorts));
}
}
}
if (!sender->GetPendingAdventureDoorClick()) {
sender->PendingAdventureDoorClick();
auto pack = new ServerPacket(
ServerOP_AdventureClickDoor,
sizeof(ServerPlayerClickedAdventureDoor_Struct)
);
/**
* Adventure door
*/
ServerPlayerClickedAdventureDoor_Struct *adventure_door_click;
adventure_door_click = (ServerPlayerClickedAdventureDoor_Struct *) pack->pBuffer;
strcpy(adventure_door_click->player, sender->GetName());
adventure_door_click->zone_id = zone->GetZoneID();
adventure_door_click->id = this->GetDoorDBID();
worldserver.SendPacket(pack);
safe_delete(pack);
}
safe_delete(outapp);
return;
}
}
// todo: if IsDzDoor() call Client::MovePCDynamicZone(target_zone_id) (for systems that use dzs)
uint32 required_key_item = GetKeyItem();
uint8 disable_add_to_key_ring = GetNoKeyring();
uint32 player_has_key = 0;
uint32 player_key = 0;
const EQ::ItemInstance *lock_pick_item = sender->GetInv().GetItem(EQ::invslot::slotCursor);
player_has_key = static_cast<uint32>(sender->GetInv().HasItem(required_key_item, 1));
if (player_has_key != INVALID_INDEX) {
player_key = required_key_item;
}
/**
* Object is not triggered
*/
if (this->GetTriggerType() == 255) {
/**
* Door is only triggered by an object
*/
if (trigger == 1) {
if (!this->IsDoorOpen() || (open_type == 58)) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
} else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
}
} else {
safe_delete(outapp);
return;
}
}
/**
* Guild Doors
*
* Door is not locked
*/
bool is_guild_door = (this->GetGuildID() > 0) && (this->GetGuildID() == sender->GuildID());
bool is_door_not_locked = ((required_key_item == 0) && (this->GetLockpick() == 0) && (this->GetGuildID() == 0));
bool is_door_open_and_open_able = (this->IsDoorOpen() && (open_type == 58));
if (is_door_not_locked || is_door_open_and_open_able || is_guild_door) {
if (!this->IsDoorOpen() || (this->GetOpenType() == 58)) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
} else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
}
} else {
/**
* Guild Doors
*/
if ((this->GetGuildID() > 0) && !sender->GetGM()) {
std::string guild_name;
char door_message[240];
if (guild_mgr.GetGuildNameByID(guild_id, guild_name)) {
sprintf(door_message, "Only members of the <%s> guild may enter here", guild_name.c_str());
} else {
strcpy(door_message, "Door is locked by an unknown guild");
}
sender->Message(Chat::LightBlue, door_message);
safe_delete(outapp);
return;
}
/**
* Key required
*/
sender->Message(Chat::LightBlue, "This is locked...");
/**
* GM can always open locks
*/
if (sender->GetGM()) {
sender->MessageString(Chat::LightBlue, DOORS_GM);
if (!IsDoorOpen() || (open_type == 58)) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
} else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
}
}
/**
* Player has something they are trying to open it with
*/
else if (player_key) {
/**
* Key required and client is using the right key
*/
if (required_key_item &&
(required_key_item == player_key)) {
if (!disable_add_to_key_ring) {
sender->KeyRingAdd(player_key);
}
sender->Message(Chat::LightBlue, "You got it open!");
if (!IsDoorOpen() || (open_type == 58)) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
} else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
}
}
}
/**
* Try Lock pick
*/
else if (lock_pick_item != nullptr) {
if (sender->GetSkill(EQ::skills::SkillPickLock)) {
if (lock_pick_item->GetItem()->ItemType == EQ::item::ItemTypeLockPick) {
float player_pick_lock_skill = sender->GetSkill(EQ::skills::SkillPickLock);
sender->CheckIncreaseSkill(EQ::skills::SkillPickLock, nullptr, 1);
LogSkills("Client has lockpicks: skill=[{}]", player_pick_lock_skill);
if (GetLockpick() <= player_pick_lock_skill) {
if (!IsDoorOpen()) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
} else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
}
sender->MessageString(Chat::LightBlue, DOORS_SUCCESSFUL_PICK);
} else {
sender->MessageString(Chat::LightBlue, DOORS_INSUFFICIENT_SKILL);
safe_delete(outapp);
return;
}
} else {
sender->MessageString(Chat::LightBlue, DOORS_NO_PICK);
safe_delete(outapp);
return;
}
} else {
sender->MessageString(Chat::LightBlue, DOORS_CANT_PICK);
safe_delete(outapp);
return;
}
}
/**
* Locked door and nothing to open it with
*/
else {
/**
* Search for key on keyring
*/
if (sender->KeyRingCheck(required_key_item)) {
player_key = required_key_item;
sender->Message(Chat::LightBlue, "You got it open!"); // more debug spam
if (!IsDoorOpen() || (open_type == 58)) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
} else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
}
} else {
sender->MessageString(Chat::LightBlue, DOORS_LOCKED);
safe_delete(outapp);
return;
}
}
}
entity_list.QueueClients(sender, outapp, false);
if (!IsDoorOpen() || (open_type == 58)) {
if (!disable_timer)
close_timer.Start();
SetOpenState(true);
} else {
close_timer.Disable();
if (!disable_timer)
SetOpenState(false);
}
/*
* Everything past this point assumes we opened the door
* and met all the requirements for opening
* everything to do with closed doors has already been taken care of
* we return because we don't want people using teleports on an unlocked door (exploit!)
*/
if ((move_door_packet->action == CLOSE_DOOR && invert_state == 0) || (move_door_packet->action == CLOSE_INVDOOR && invert_state == 1)) {
safe_delete(outapp);
return;
}
safe_delete(outapp);
if ((GetTriggerDoorID() != 0) && (GetTriggerType() == 1)) {
Doors *trigger_door_entity = entity_list.FindDoor(GetTriggerDoorID());
if (trigger_door_entity && !trigger_door_entity->triggered) {
triggered = true;
trigger_door_entity->HandleClick(sender, 1);
} else {
triggered = false;
}
} else if ((GetTriggerDoorID() != 0) && (GetTriggerType() != 1)) {
Doors *trigger_door_entity = entity_list.FindDoor(GetTriggerDoorID());
if (trigger_door_entity && !trigger_door_entity->triggered) {
triggered = true;
trigger_door_entity->HandleClick(sender, 0);
} else {
triggered = false;
}
}
/**
* Teleport door
*/
if (((open_type == 57) || (open_type == 58)) &&
(strncmp(destination_zone_name, "NONE", strlen("NONE")) != 0)) {
/**
* If click destination is same zone and doesn't require a key
*/
if ((strncmp(destination_zone_name, zone_name, strlen(zone_name)) == 0) && (!required_key_item)) {
if (!disable_add_to_key_ring) {
sender->KeyRingAdd(player_key);
}
sender->MovePC(
zone->GetZoneID(),
zone->GetInstanceID(),
m_Destination.x,
m_Destination.y,
m_Destination.z,
m_Destination.w
);
}
/**
* If requires a key
*/
else if (
(!IsDoorOpen() || open_type == 58) &&
(required_key_item && ((required_key_item == player_key) || sender->GetGM()))
) {
if (!disable_add_to_key_ring) {
sender->KeyRingAdd(player_key);
}
if (ZoneID(destination_zone_name) == zone->GetZoneID()) {
sender->MovePC(
zone->GetZoneID(),
zone->GetInstanceID(),
m_Destination.x,
m_Destination.y,
m_Destination.z,
m_Destination.w
);
} else {
sender->MovePC(
ZoneID(destination_zone_name),
static_cast<uint32>(destination_instance_id),
m_Destination.x,
m_Destination.y,
m_Destination.z,
m_Destination.w
);
}
}
if ((!IsDoorOpen() || open_type == 58) && (!required_key_item)) {
if (ZoneID(destination_zone_name) == zone->GetZoneID()) {
sender->MovePC(
zone->GetZoneID(),
zone->GetInstanceID(),
m_Destination.x,
m_Destination.y,
m_Destination.z,
m_Destination.w
);
} else {
sender->MovePC(
ZoneID(destination_zone_name),
static_cast<uint32>(this->destination_instance_id),
m_Destination.x,
m_Destination.y,
m_Destination.z,
m_Destination.w
);
}
}
}
}
void Doors::Open(Mob* sender, bool alt_mode)
{
if (sender) {
if (GetTriggerType() == 255 || GetTriggerDoorID() > 0 || GetLockpick() != 0 || GetKeyItem() != 0 || open_type == 59 || open_type == 58 || !sender->IsNPC()) { // this object isnt triggered or door is locked - NPCs should not open locked doors!
return;
}
auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct));
MoveDoor_Struct* md = (MoveDoor_Struct*)outapp->pBuffer;
md->doorid = door_id;
md->action = invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR;
entity_list.QueueCloseClients(sender, outapp, false, 200);
safe_delete(outapp);
if (!alt_mode) { // original function
if (!is_open) {
if (!disable_timer)
close_timer.Start();
is_open = true;
}
else {
close_timer.Disable();
if (!disable_timer)
is_open = false;
}
}
else { // alternative function
if (!disable_timer)
close_timer.Start();
is_open = true;
}
}
}
void Doors::ForceOpen(Mob *sender, bool alt_mode)
{
auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct));
MoveDoor_Struct* md = (MoveDoor_Struct*)outapp->pBuffer;
md->doorid = door_id;
md->action = invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR;
entity_list.QueueClients(sender, outapp, false);
safe_delete(outapp);
if (!alt_mode) { // original function
if (!is_open) {
if (!disable_timer)
close_timer.Start();
is_open = true;
}
else {
close_timer.Disable();
if (!disable_timer)
is_open = false;
}
}
else { // alternative function
if (!disable_timer)
close_timer.Start();
is_open = true;
}
}
void Doors::ForceClose(Mob *sender, bool alt_mode) {
auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct));
MoveDoor_Struct *move_door_packet;
move_door_packet = (MoveDoor_Struct *) outapp->pBuffer;
move_door_packet->doorid = door_id;
move_door_packet->action = invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR; // change from original (open to close)
entity_list.QueueClients(sender, outapp, false);
safe_delete(outapp);
if (!alt_mode) { // original function
if (!is_open) {
if (!disable_timer)
close_timer.Start();
is_open = true;
} else {
close_timer.Disable();
is_open = false;
}
} else { // alternative function
if (is_open)
close_timer.Trigger();
}
}
void Doors::ToggleState(Mob *sender)
{
if(GetTriggerDoorID() > 0 || GetLockpick() != 0 || GetKeyItem() != 0 || open_type == 58 || open_type == 40) { // borrowed some NPCOpen criteria
return;
}
auto outapp = new EQApplicationPacket(OP_MoveDoor, sizeof(MoveDoor_Struct));
MoveDoor_Struct* move_door_packet;
move_door_packet = (MoveDoor_Struct*)outapp->pBuffer;
move_door_packet->doorid = door_id;
if(!is_open) {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? OPEN_DOOR : OPEN_INVDOOR);
is_open=true;
}
else {
move_door_packet->action = static_cast<uint8>(invert_state == 0 ? CLOSE_DOOR : CLOSE_INVDOOR);
is_open=false;
}
entity_list.QueueClients(sender,outapp,false);
safe_delete(outapp);
}
int32 ZoneDatabase::GetDoorsCount(uint32* oMaxID, const char *zone_name, int16 version) {
std::string query = StringFormat("SELECT MAX(id), count(*) FROM doors "
"WHERE zone = '%s' AND (version = %u OR version = -1)",
zone_name, version);
auto results = QueryDatabase(query);
if (!results.Success()) {
return -1;
}
if (results.RowCount() != 1)
return -1;
auto row = results.begin();
if (!oMaxID)
return atoi(row[1]);
if (row[0])
*oMaxID = atoi(row[0]);
else
*oMaxID = 0;
return atoi(row[1]);
}
int32 ZoneDatabase::GetDoorsCountPlusOne(const char *zone_name, int16 version) {
std::string query = StringFormat(
"SELECT MAX(id) FROM doors WHERE zone = '%s' AND version = %u",
zone_name,
version
);
auto results = QueryDatabase(query);
if (!results.Success()) {
return -1;
}
if (results.RowCount() != 1)
return -1;
auto row = results.begin();
if (!row[0])
return 0;
return atoi(row[0]) + 1;
}
int32 ZoneDatabase::GetDoorsDBCountPlusOne(const char *zone_name, int16 version) {
uint32 oMaxID = 0;
std::string query = StringFormat("SELECT MAX(doorid) FROM doors "
"WHERE zone = '%s' AND (version = %u OR version = -1)",
zone_name, version);
auto results = QueryDatabase(query);
if (!results.Success()) {
return -1;
}
if (results.RowCount() != 1)
return -1;
auto row = results.begin();
if (!row[0])
return 0;
return atoi(row[0]) + 1;
}
std::vector<DoorsRepository::Doors> ZoneDatabase::LoadDoors(const std::string& zone_name, int16 version)
{
LogInfo("Loading Doors from database");
auto door_entries = DoorsRepository::GetWhere(*this, fmt::format(
"zone = '{}' AND (version = {} OR version = -1) {} ORDER BY doorid ASC",
zone_name, version, ContentFilterCriteria::apply()));
LogDoors("Loaded [{}] doors for [{}] version [{}]", door_entries.size(), zone_name, version);
return door_entries;
}
void Doors::SetLocation(float x, float y, float z)
{
entity_list.DespawnAllDoors();
m_Position = glm::vec4(x, y, z, m_Position.w);
entity_list.RespawnAllDoors();
}
void Doors::SetPosition(const glm::vec4& position) {
entity_list.DespawnAllDoors();
m_Position = position;
entity_list.RespawnAllDoors();
}
void Doors::SetIncline(int in) {
entity_list.DespawnAllDoors();
incline = in;
entity_list.RespawnAllDoors();
}
void Doors::SetInvertState(int in) {
entity_list.DespawnAllDoors();
invert_state = in;
entity_list.RespawnAllDoors();
}
void Doors::SetOpenType(uint8 in) {
entity_list.DespawnAllDoors();
open_type = in;
entity_list.RespawnAllDoors();
}
void Doors::SetDoorName(const char* name) {
entity_list.DespawnAllDoors();
memset(door_name, 0, sizeof(door_name));
strncpy(door_name, name, sizeof(door_name));
entity_list.RespawnAllDoors();
}
void Doors::SetSize(uint16 in) {
entity_list.DespawnAllDoors();
size = in;
entity_list.RespawnAllDoors();
}
void Doors::SetDisableTimer(bool flag) {
disable_timer = flag;
}
void Doors::CreateDatabaseEntry()
{
if (content_db.GetDoorsDBCountPlusOne(zone->GetShortName(), zone->GetInstanceVersion()) - 1 >= 255) {
return;
}
/**
* Persist
*/
content_db.InsertDoor(
GetDoorDBID(),
GetDoorID(),
GetDoorName(),
m_Position,
GetOpenType(),
static_cast<uint16>(GetGuildID()),
GetLockpick(),
GetKeyItem(),
static_cast<uint8>(GetDoorParam()),
static_cast<uint8>(GetInvertState()),
GetIncline(),
GetSize()
);
}
float Doors::GetX()
{
return m_Position.x;
}
float Doors::GetY()
{
return m_Position.y;
}
float Doors::GetZ()
{
return m_Position.z;
}
| 1 | 11,028 | Maybe use { } here like we are most other places now. | EQEmu-Server | cpp |
@@ -96,6 +96,7 @@ class PartitionData
return schema;
}
+ @Override
public Type getType(int pos) {
return partitionType.fields().get(pos).type();
} | 1 | /*
* 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.iceberg;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import org.apache.avro.Schema;
import org.apache.avro.generic.IndexedRecord;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.util.Utf8;
import org.apache.iceberg.avro.AvroSchemaUtil;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.hash.Hasher;
import org.apache.iceberg.relocated.com.google.common.hash.Hashing;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;
class PartitionData
implements IndexedRecord, StructLike, SpecificData.SchemaConstructable, Serializable {
static Schema partitionDataSchema(Types.StructType partitionType) {
return AvroSchemaUtil.convert(partitionType, PartitionData.class.getName());
}
private final Types.StructType partitionType;
private final int size;
private final Object[] data;
private final String stringSchema;
private transient Schema schema = null;
/**
* Used by Avro reflection to instantiate this class when reading manifest files.
*/
PartitionData(Schema schema) {
this.partitionType = AvroSchemaUtil.convert(schema).asNestedType().asStructType();
this.size = partitionType.fields().size();
this.data = new Object[size];
this.stringSchema = schema.toString();
this.schema = schema;
}
PartitionData(Types.StructType partitionType) {
for (Types.NestedField field : partitionType.fields()) {
Preconditions.checkArgument(field.type().isPrimitiveType(),
"Partitions cannot contain nested types: %s", field.type());
}
this.partitionType = partitionType;
this.size = partitionType.fields().size();
this.data = new Object[size];
this.schema = partitionDataSchema(partitionType);
this.stringSchema = schema.toString();
}
/**
* Copy constructor
*/
private PartitionData(PartitionData toCopy) {
this.partitionType = toCopy.partitionType;
this.size = toCopy.size;
this.data = copyData(toCopy.partitionType, toCopy.data);
this.stringSchema = toCopy.stringSchema;
this.schema = toCopy.schema;
}
public Types.StructType getPartitionType() {
return partitionType;
}
@Override
public Schema getSchema() {
if (schema == null) {
this.schema = new Schema.Parser().parse(stringSchema);
}
return schema;
}
public Type getType(int pos) {
return partitionType.fields().get(pos).type();
}
public void clear() {
Arrays.fill(data, null);
}
@Override
public int size() {
return size;
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(int pos, Class<T> javaClass) {
Object value = get(pos);
if (value == null || javaClass.isInstance(value)) {
return javaClass.cast(value);
}
throw new IllegalArgumentException(String.format(
"Wrong class, %s, for object: %s",
javaClass.getName(), String.valueOf(value)));
}
@Override
public Object get(int pos) {
if (pos >= data.length) {
return null;
}
if (data[pos] instanceof byte[]) {
return ByteBuffer.wrap((byte[]) data[pos]);
}
return data[pos];
}
@Override
public <T> void set(int pos, T value) {
if (value instanceof Utf8) {
// Utf8 is not Serializable
data[pos] = value.toString();
} else if (value instanceof ByteBuffer) {
// ByteBuffer is not Serializable
ByteBuffer buffer = (ByteBuffer) value;
byte[] bytes = new byte[buffer.remaining()];
buffer.duplicate().get(bytes);
data[pos] = bytes;
} else {
data[pos] = value;
}
}
@Override
public void put(int i, Object v) {
set(i, v);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PartitionData{");
for (int i = 0; i < data.length; i += 1) {
if (i > 0) {
sb.append(", ");
}
sb.append(partitionType.fields().get(i).name())
.append("=")
.append(data[i]);
}
sb.append("}");
return sb.toString();
}
public PartitionData copy() {
return new PartitionData(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (!(o instanceof PartitionData)) {
return false;
}
PartitionData that = (PartitionData) o;
return partitionType.equals(that.partitionType) && Arrays.equals(data, that.data);
}
@Override
public int hashCode() {
Hasher hasher = Hashing.goodFastHash(32).newHasher();
Stream.of(data).map(Objects::hashCode).forEach(hasher::putInt);
partitionType.fields().stream().map(Objects::hashCode).forEach(hasher::putInt);
return hasher.hash().hashCode();
}
public static Object[] copyData(Types.StructType type, Object[] data) {
List<Types.NestedField> fields = type.fields();
Object[] copy = new Object[data.length];
for (int i = 0; i < data.length; i += 1) {
if (data[i] == null) {
copy[i] = null;
} else {
Types.NestedField field = fields.get(i);
switch (field.type().typeId()) {
case STRUCT:
case LIST:
case MAP:
throw new IllegalArgumentException("Unsupported type in partition data: " + type);
case BINARY:
case FIXED:
byte[] buffer = (byte[]) data[i];
copy[i] = Arrays.copyOf(buffer, buffer.length);
break;
case STRING:
copy[i] = data[i].toString();
break;
default:
// no need to copy the object
copy[i] = data[i];
}
}
}
return copy;
}
}
| 1 | 45,539 | I want to get PartitionData field type, I don't know how to get it in other way. | apache-iceberg | java |
@@ -31,6 +31,9 @@ type Balances interface {
// A non-nil error means the lookup is impossible (e.g., if the database doesn't have necessary state anymore)
Get(addr basics.Address, withPendingRewards bool) (basics.AccountData, error)
+ // GetEx is like Get(addr, false), but also loads specific creatable
+ GetEx(addr basics.Address, cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.AccountData, error)
+
Put(basics.Address, basics.AccountData) error
// PutWithCreatable is like Put, but should be used when creating or deleting an asset or application. | 1 | // Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package apply
import (
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/data/basics"
"github.com/algorand/go-algorand/data/transactions/logic"
)
// Balances allow to move MicroAlgos from one address to another and to update balance records, or to access and modify individual balance records
// After a call to Put (or Move), future calls to Get or Move will reflect the updated balance record(s)
type Balances interface {
// Get looks up the account data for an address, ignoring application state
// If the account is known to be empty, then err should be nil and the returned balance record should have the given address and empty AccountData
// withPendingRewards specifies whether pending rewards should be applied.
// A non-nil error means the lookup is impossible (e.g., if the database doesn't have necessary state anymore)
Get(addr basics.Address, withPendingRewards bool) (basics.AccountData, error)
Put(basics.Address, basics.AccountData) error
// PutWithCreatable is like Put, but should be used when creating or deleting an asset or application.
PutWithCreatable(addr basics.Address, acct basics.AccountData, newCreatable *basics.CreatableLocator, deletedCreatable *basics.CreatableLocator) error
// GetCreator gets the address of the account that created a given creatable
GetCreator(cidx basics.CreatableIndex, ctype basics.CreatableType) (basics.Address, bool, error)
// Allocate or Deallocate either global or address-local app storage.
//
// PutWithCreatable(...) and then {Allocate/Deallocate}(..., ..., global=true)
// creates/destroys an application.
//
// Put(...) and then {Allocate/Deallocate}(..., ..., global=false)
// opts into/closes out of an application.
Allocate(addr basics.Address, aidx basics.AppIndex, global bool, space basics.StateSchema) error
Deallocate(addr basics.Address, aidx basics.AppIndex, global bool) error
// StatefulEval executes a TEAL program in stateful mode on the balances.
// It returns whether the program passed and its error. It alo returns
// an EvalDelta that contains the changes made by the program.
StatefulEval(params logic.EvalParams, aidx basics.AppIndex, program []byte) (passed bool, evalDelta basics.EvalDelta, err error)
// Move MicroAlgos from one account to another, doing all necessary overflow checking (convenience method)
// TODO: Does this need to be part of the balances interface, or can it just be implemented here as a function that calls Put and Get?
Move(src, dst basics.Address, amount basics.MicroAlgos, srcRewards *basics.MicroAlgos, dstRewards *basics.MicroAlgos) error
// Balances correspond to a Round, which mean that they also correspond
// to a ConsensusParams. This returns those parameters.
ConsensusParams() config.ConsensusParams
}
| 1 | 41,954 | I think that a single `Get` method would be preferable, that would have the following parameters: Get(addr basics.Address, withPendingRewards bool, cidx basics.CreatableIndex, ctype basics.CreatableType) where we ignore cidx of -1, and adding support for ctype of "AssetParams" or something like that. (i.e. so that this Get call would be good for asset holding/asset params and applications ) | algorand-go-algorand | go |
@@ -1653,7 +1653,7 @@ char * ExHdfsScanTcb::extractAndTransformAsciiSourceToSqlRow(int &err,
// for non-varchar, length of zero indicates a null value.
// For all datatypes, HIVE_DEFAULT_NULL_STRING('\N') indicates a null value.
if (((len == 0) && (tgtAttr && (NOT DFS2REC::isSQLVarChar(tgtAttr->getDatatype())))) ||
- ((len > 0) && (memcmp(sourceData, HIVE_DEFAULT_NULL_STRING, len) == 0)))
+ ((len > 1) && (memcmp(sourceData, HIVE_DEFAULT_NULL_STRING, len) == 0)))
{
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = -1;
} | 1 | // **********************************************************************
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
// **********************************************************************
#include "Platform.h"
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <poll.h>
#include <iostream>
#include "ex_stdh.h"
#include "ComTdb.h"
#include "ex_tcb.h"
#include "ExHdfsScan.h"
#include "ex_exe_stmt_globals.h"
#include "ExpLOBinterface.h"
#include "SequenceFileReader.h"
#include "Hbase_types.h"
#include "stringBuf.h"
#include "NLSConversion.h"
#include "Context.h"
#include "ExpORCinterface.h"
#include "ComSmallDefs.h"
ex_tcb * ExHdfsScanTdb::build(ex_globals * glob)
{
ExExeStmtGlobals * exe_glob = glob->castToExExeStmtGlobals();
ex_assert(exe_glob,"This operator cannot be in DP2");
ExHdfsScanTcb *tcb = NULL;
if ((isTextFile()) || (isSequenceFile()))
{
tcb = new(exe_glob->getSpace())
ExHdfsScanTcb(
*this,
exe_glob);
}
else if (isOrcFile())
{
tcb = new(exe_glob->getSpace())
ExOrcScanTcb(
*this,
exe_glob);
}
ex_assert(tcb, "Error building ExHdfsScanTcb.");
return (tcb);
}
ex_tcb * ExOrcFastAggrTdb::build(ex_globals * glob)
{
ExHdfsScanTcb *tcb = NULL;
tcb = new(glob->getSpace())
ExOrcFastAggrTcb(
*this,
glob);
ex_assert(tcb, "Error building ExHdfsScanTcb.");
return (tcb);
}
////////////////////////////////////////////////////////////////
// Constructor and initialization.
////////////////////////////////////////////////////////////////
ExHdfsScanTcb::ExHdfsScanTcb(
const ComTdbHdfsScan &hdfsScanTdb,
ex_globals * glob ) :
ex_tcb( hdfsScanTdb, 1, glob)
, workAtp_(NULL)
, bytesLeft_(0)
, hdfsScanBuffer_(NULL)
, hdfsBufNextRow_(NULL)
, hdfsLoggingRow_(NULL)
, hdfsLoggingRowEnd_(NULL)
, debugPrevRow_(NULL)
, hdfsSqlBuffer_(NULL)
, hdfsSqlData_(NULL)
, pool_(NULL)
, step_(NOT_STARTED)
, matches_(0)
, matchBrkPoint_(0)
, endOfRequestedRange_(NULL)
, sequenceFileReader_(NULL)
, seqScanAgain_(false)
, hdfo_(NULL)
, numBytesProcessedInRange_(0)
, exception_(FALSE)
, checkRangeDelimiter_(FALSE)
, dataModCheckDone_(FALSE)
, loggingErrorDiags_(NULL)
, loggingFileName_(NULL)
, hdfsFileInfoListAsArray_(glob->getDefaultHeap(), hdfsScanTdb.getHdfsFileInfoList()->numEntries())
{
Space * space = (glob ? glob->getSpace() : 0);
CollHeap * heap = (glob ? glob->getDefaultHeap() : 0);
lobGlob_ = NULL;
const int readBufSize = (Int32)hdfsScanTdb.hdfsBufSize_;
hdfsScanBuffer_ = new(space) char[ readBufSize + 1 ];
hdfsScanBuffer_[readBufSize] = '\0';
moveExprColsBuffer_ = new(space) ExSimpleSQLBuffer( 1, // one row
(Int32)hdfsScanTdb.moveExprColsRowLength_,
space);
short error = moveExprColsBuffer_->getFreeTuple(moveExprColsTupp_);
ex_assert((error == 0), "get_free_tuple cannot hold a row.");
moveExprColsData_ = moveExprColsTupp_.getDataPointer();
hdfsSqlBuffer_ = new(space) ExSimpleSQLBuffer( 1, // one row
(Int32)hdfsScanTdb.hdfsSqlMaxRecLen_,
space);
error = hdfsSqlBuffer_->getFreeTuple(hdfsSqlTupp_);
ex_assert((error == 0), "get_free_tuple cannot hold a row.");
hdfsSqlData_ = hdfsSqlTupp_.getDataPointer();
hdfsAsciiSourceBuffer_ = new(space) ExSimpleSQLBuffer( 1, // one row
(Int32)hdfsScanTdb.asciiRowLen_ * 2, // just in case
space);
error = hdfsAsciiSourceBuffer_->getFreeTuple(hdfsAsciiSourceTupp_);
ex_assert((error == 0), "get_free_tuple cannot hold a row.");
hdfsAsciiSourceData_ = hdfsAsciiSourceTupp_.getDataPointer();
pool_ = new(space)
sql_buffer_pool(hdfsScanTdb.numBuffers_,
hdfsScanTdb.bufferSize_,
space,
((ExHdfsScanTdb &)hdfsScanTdb).denseBuffers() ?
SqlBufferBase::DENSE_ : SqlBufferBase::NORMAL_);
pool_->setStaticMode(TRUE);
defragTd_ = NULL;
// removing the cast produce a compile error
if (((ExHdfsScanTdb &)hdfsScanTdb).useCifDefrag())
{
defragTd_ = pool_->addDefragTuppDescriptor(hdfsScanTdb.outputRowLength_);
}
// Allocate the queue to communicate with parent
allocateParentQueues(qparent_);
workAtp_ = allocateAtp(hdfsScanTdb.workCriDesc_, space);
// fixup expressions
if (selectPred())
selectPred()->fixup(0, getExpressionMode(), this, space, heap, FALSE, glob);
if (moveExpr())
moveExpr()->fixup(0, getExpressionMode(), this, space, heap, FALSE, glob);
if (convertExpr())
convertExpr()->fixup(0, getExpressionMode(), this, space, heap, FALSE, glob);
if (moveColsConvertExpr())
moveColsConvertExpr()->fixup(0, getExpressionMode(), this, space, heap, FALSE, glob);
// Register subtasks with the scheduler
registerSubtasks();
registerResizeSubtasks();
Lng32 fileNum = getGlobals()->castToExExeStmtGlobals()->getMyInstanceNumber();
ExHbaseAccessTcb::buildLoggingFileName((NAHeap *)getHeap(), ((ExHdfsScanTdb &)hdfsScanTdb).getLoggingLocation(),
((ExHdfsScanTdb &)hdfsScanTdb).tableName(),
"hive_scan_err",
fileNum,
loggingFileName_);
LoggingFileCreated_ = FALSE;
//shoud be move to work method
int jniDebugPort = 0;
int jniDebugTimeout = 0;
ehi_ = ExpHbaseInterface::newInstance(glob->getDefaultHeap(),
(char*)"", //Later replace with server cqd
(char*)"", ////Later replace with port cqd
jniDebugPort,
jniDebugTimeout);
// Populate the hdfsInfo list into an array to gain o(1) lookup access
Queue* hdfsInfoList = hdfsScanTdb.getHdfsFileInfoList();
if ( hdfsInfoList && hdfsInfoList->numEntries() > 0 )
{
hdfsInfoList->position();
int i = 0;
HdfsFileInfo* fInfo = NULL;
while ((fInfo = (HdfsFileInfo*)hdfsInfoList->getNext()) != NULL)
{
hdfsFileInfoListAsArray_.insertAt(i, fInfo);
i++;
}
}
}
ExHdfsScanTcb::~ExHdfsScanTcb()
{
freeResources();
}
void ExHdfsScanTcb::freeResources()
{
if (loggingFileName_ != NULL) {
NADELETEBASIC(loggingFileName_, getHeap());
loggingFileName_ = NULL;
}
if (workAtp_)
{
workAtp_->release();
deallocateAtp(workAtp_, getSpace());
workAtp_ = NULL;
}
if (hdfsScanBuffer_)
{
NADELETEBASIC(hdfsScanBuffer_, getSpace());
hdfsScanBuffer_ = NULL;
}
if (hdfsAsciiSourceBuffer_)
{
NADELETEBASIC(hdfsAsciiSourceBuffer_, getSpace());
hdfsAsciiSourceBuffer_ = NULL;
}
if(sequenceFileReader_)
{
NADELETE(sequenceFileReader_,SequenceFileReader, getHeap());
sequenceFileReader_ = NULL;
}
// hdfsSqlTupp_.release() ; // ???
if (hdfsSqlBuffer_)
{
delete hdfsSqlBuffer_;
hdfsSqlBuffer_ = NULL;
}
if (moveExprColsBuffer_)
{
delete moveExprColsBuffer_;
moveExprColsBuffer_ = NULL;
}
if (pool_)
{
delete pool_;
pool_ = NULL;
}
if (qparent_.up)
{
delete qparent_.up;
qparent_.up = NULL;
}
if (qparent_.down)
{
delete qparent_.down;
qparent_.down = NULL;
}
deallocateRuntimeRanges();
if (lobGlob_) {
ExpLOBinterfaceCleanup(lobGlob_, getGlobals()->getDefaultHeap());
lobGlob_ = NULL;
}
}
NABoolean ExHdfsScanTcb::needStatsEntry()
{
// stats are collected for ALL and OPERATOR options.
if ((getGlobals()->getStatsArea()->getCollectStatsType() ==
ComTdb::ALL_STATS) ||
(getGlobals()->getStatsArea()->getCollectStatsType() ==
ComTdb::OPERATOR_STATS))
return TRUE;
else if ( getGlobals()->getStatsArea()->getCollectStatsType() == ComTdb::PERTABLE_STATS)
return TRUE;
else
return FALSE;
}
ExOperStats * ExHdfsScanTcb::doAllocateStatsEntry(CollHeap *heap,
ComTdb *tdb)
{
ExEspStmtGlobals *espGlobals = getGlobals()->castToExExeStmtGlobals()->castToExEspStmtGlobals();
StmtStats *ss;
if (espGlobals != NULL)
ss = espGlobals->getStmtStats();
else
ss = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals()->getStatement()->getStmtStats();
ExHdfsScanStats *hdfsScanStats = new(heap) ExHdfsScanStats(heap,
this,
tdb);
if (ss != NULL)
hdfsScanStats->setQueryId(ss->getQueryId(), ss->getQueryIdLen());
return hdfsScanStats;
}
void ExHdfsScanTcb::registerSubtasks()
{
ExScheduler *sched = getGlobals()->getScheduler();
sched->registerInsertSubtask(sWork, this, qparent_.down,"PD");
sched->registerUnblockSubtask(sWork, this, qparent_.up, "PU");
sched->registerCancelSubtask(sWork, this, qparent_.down,"CN");
}
ex_tcb_private_state *ExHdfsScanTcb::allocatePstates(
Lng32 &numElems, // inout, desired/actual elements
Lng32 &pstateLength) // out, length of one element
{
PstateAllocator<ex_tcb_private_state> pa;
return pa.allocatePstates(this, numElems, pstateLength);
}
Int32 ExHdfsScanTcb::fixup()
{
lobGlob_ = NULL;
ExpLOBinterfaceInit
(lobGlob_, getGlobals()->getDefaultHeap(),getGlobals()->castToExExeStmtGlobals()->getContext(),TRUE, hdfsScanTdb().hostName_,hdfsScanTdb().port_);
return 0;
}
void brkpoint()
{}
short ExHdfsScanTcb::setupError(Lng32 exeError, Lng32 retcode,
const char * str, const char * str2, const char * str3)
{
// Make sure retcode is positive.
if (retcode < 0)
retcode = -retcode;
ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
Lng32 intParam1 = retcode;
Lng32 intParam2 = 0;
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(exeError), NULL, &intParam1,
&intParam2, NULL,
(str ? (char*)str : (char*)" "),
(str2 ? (char*)str2 : (char*)" "),
(str3 ? (char*)str3 : (char*)" "));
pentry_down->setDiagsArea(diagsArea);
return -1;
}
ExWorkProcRetcode ExHdfsScanTcb::work()
{
Lng32 retcode = 0;
SFR_RetCode sfrRetCode = SFR_OK;
char *errorDesc = NULL;
char cursorId[8];
HdfsFileInfo *hdfo = NULL;
Lng32 openType = 0;
int changedLen = 0;
ContextCli *currContext = getGlobals()->castToExExeStmtGlobals()->getCliGlobals()->currContext();
hdfsFS hdfs = currContext->getHdfsServerConnection(hdfsScanTdb().hostName_,hdfsScanTdb().port_);
hdfsFileInfo *dirInfo = NULL;
Int32 hdfsErrorDetail = 0;//this is errno returned form underlying hdfsOpenFile call.
while (!qparent_.down->isEmpty())
{
ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
switch (step_)
{
case NOT_STARTED:
{
matches_ = 0;
hdfsStats_ = NULL;
if (getStatsEntry())
hdfsStats_ = getStatsEntry()->castToExHdfsScanStats();
ex_assert(hdfsStats_, "hdfs stats cannot be null");
if (hdfsStats_)
hdfsStats_->init();
beginRangeNum_ = -1;
numRanges_ = -1;
hdfsOffset_ = 0;
checkRangeDelimiter_ = FALSE;
dataModCheckDone_ = FALSE;
myInstNum_ = getGlobals()->getMyInstanceNumber();
hdfsScanBufMaxSize_ = hdfsScanTdb().hdfsBufSize_;
if (hdfsScanTdb().getAssignRangesAtRuntime())
{
step_ = ASSIGN_RANGES_AT_RUNTIME;
break;
}
else if (getHdfsFileInfoListAsArray().isEmpty())
{
step_ = CHECK_FOR_DATA_MOD_AND_DONE;
break;
}
beginRangeNum_ =
*(Lng32*)hdfsScanTdb().getHdfsFileRangeBeginList()->get(myInstNum_);
numRanges_ =
*(Lng32*)hdfsScanTdb().getHdfsFileRangeNumList()->get(myInstNum_);
currRangeNum_ = beginRangeNum_;
if (numRanges_ > 0)
step_ = CHECK_FOR_DATA_MOD;
else
step_ = CHECK_FOR_DATA_MOD_AND_DONE;
}
break;
case ASSIGN_RANGES_AT_RUNTIME:
computeRangesAtRuntime();
currRangeNum_ = beginRangeNum_;
if (numRanges_ > 0)
step_ = INIT_HDFS_CURSOR;
else
step_ = DONE;
break;
case CHECK_FOR_DATA_MOD:
case CHECK_FOR_DATA_MOD_AND_DONE:
{
char * dirPath = hdfsScanTdb().hdfsRootDir_;
Int64 modTS = hdfsScanTdb().modTSforDir_;
if ((dirPath == NULL) || (modTS == -1))
dataModCheckDone_ = TRUE;
if (NOT dataModCheckDone_)
{
dataModCheckDone_ = TRUE;
Lng32 numOfPartLevels = hdfsScanTdb().numOfPartCols_;
if (hdfsScanTdb().hdfsDirsToCheck())
{
// TBD
}
Int64 failedModTS = -1;
Lng32 failedLocBufLen = 1000;
char failedLocBuf[failedLocBufLen];
retcode = ExpLOBinterfaceDataModCheck
(lobGlob_,
dirPath,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_,
modTS,
numOfPartLevels,
failedModTS,
failedLocBuf, failedLocBufLen);
if (retcode < 0)
{
Lng32 cliError = 0;
Lng32 intParam1 = -retcode;
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_ERROR_FROM_LOB_INTERFACE),
NULL, &intParam1,
&cliError,
NULL,
"HDFS",
(char*)"ExpLOBInterfaceDataModCheck",
getLobErrStr(intParam1));
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR_AND_DONE;
break;
}
if (retcode == 1) // check failed
{
char errStr[200];
str_sprintf(errStr, "genModTS = %Ld, failedModTS = %Ld",
modTS, failedModTS);
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_HIVE_DATA_MOD_CHECK_ERROR), NULL,
NULL, NULL, NULL,
errStr);
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR_AND_DONE;
break;
}
}
if (step_ == CHECK_FOR_DATA_MOD_AND_DONE)
step_ = DONE;
else
step_ = INIT_HDFS_CURSOR;
}
break;
case INIT_HDFS_CURSOR:
{
hdfo_ = getRange(currRangeNum_);
if ((hdfo_->getBytesToRead() == 0) &&
(beginRangeNum_ == currRangeNum_) && (numRanges_ > 1))
{
// skip the first range if it has 0 bytes to read
// doing this for subsequent ranges is more complex
// since the file may neeed to be closed. The first
// range being 0 is common with sqoop generated files
currRangeNum_++;
hdfo_ = getRange(currRangeNum_);
}
hdfsOffset_ = hdfo_->getStartOffset();
bytesLeft_ = hdfo_->getBytesToRead();
hdfsFileName_ = hdfo_->fileName();
sprintf(cursorId_, "%d", currRangeNum_);
stopOffset_ = hdfsOffset_ + hdfo_->getBytesToRead();
step_ = OPEN_HDFS_CURSOR;
}
break;
case OPEN_HDFS_CURSOR:
{
retcode = 0;
if (isSequenceFile() && !sequenceFileReader_)
{
sequenceFileReader_ = new(getHeap())
SequenceFileReader((NAHeap *)getHeap());
sfrRetCode = sequenceFileReader_->init();
if (sfrRetCode != JNI_OK)
{
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8447), NULL,
NULL, NULL, NULL, sequenceFileReader_->getErrorText(sfrRetCode), NULL);
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR;
break;
}
}
if (isSequenceFile())
{
sfrRetCode = sequenceFileReader_->open(hdfsFileName_);
if (sfrRetCode == JNI_OK)
{
// Seek to start offset
sfrRetCode = sequenceFileReader_->seeknSync(hdfsOffset_);
}
if (sfrRetCode != JNI_OK)
{
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8447), NULL,
NULL, NULL, NULL, sequenceFileReader_->getErrorText(sfrRetCode), NULL);
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR;
break;
}
}
else
{
Int64 rangeTail = hdfo_->fileIsSplitEnd() ?
hdfsScanTdb().rangeTailIOSize_ : 0;
openType = 2; // must open
retcode = ExpLOBInterfaceSelectCursor
(lobGlob_,
hdfsFileName_, //hdfsScanTdb().hdfsFileName_,
NULL, //(char*)"",
(Lng32)Lob_External_HDFS_File,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_,
0, NULL, // handle not valid for non lob access
bytesLeft_ + rangeTail, // max bytes
cursorId_,
requestTag_, Lob_Memory,
0, // not check status
(NOT hdfsScanTdb().hdfsPrefetch()), //1, // waited op
hdfsOffset_,
hdfsScanBufMaxSize_,
bytesRead_,
NULL,
1, // open
openType, //
&hdfsErrorDetail
);
if ((retcode < 0) &&
((hdfsErrorDetail == ENOENT) || (hdfsErrorDetail == EAGAIN)))
{
ComDiagsArea * diagsArea = NULL;
if (hdfsErrorDetail == ENOENT)
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_TABLE_NOT_FOUND), NULL,
NULL, NULL, NULL,
hdfsScanTdb().tableName());
else
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_HIVE_DATA_MOD_CHECK_ERROR));
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR_AND_DONE;
break;
}
// preopen next range.
if ( (currRangeNum_ + 1) < (beginRangeNum_ + numRanges_) )
{
hdfo = getRange(currRangeNum_ + 1);
hdfsFileName_ = hdfo->fileName();
sprintf(cursorId, "%d", currRangeNum_ + 1);
rangeTail = hdfo->fileIsSplitEnd() ?
hdfsScanTdb().rangeTailIOSize_ : 0;
openType = 1; // preOpen
retcode = ExpLOBInterfaceSelectCursor
(lobGlob_,
hdfsFileName_, //hdfsScanTdb().hdfsFileName_,
NULL, //(char*)"",
(Lng32)Lob_External_HDFS_File,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_,
0, NULL,//handle not relevant for non lob access
hdfo->getBytesToRead() + rangeTail, // max bytes
cursorId,
requestTag_, Lob_Memory,
0, // not check status
(NOT hdfsScanTdb().hdfsPrefetch()), //1, // waited op
hdfo->getStartOffset(),
hdfsScanBufMaxSize_,
bytesRead_,
NULL,
1,// open
openType,
&hdfsErrorDetail
);
hdfsFileName_ = hdfo_->fileName();
}
}
if (retcode < 0)
{
Lng32 cliError = 0;
Lng32 intParam1 = -retcode;
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_ERROR_FROM_LOB_INTERFACE), NULL,
&intParam1,
&hdfsErrorDetail,
NULL,
"HDFS",
(char*)"ExpLOBInterfaceSelectCursor/open",
getLobErrStr(intParam1));
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR;
break;
}
trailingPrevRead_ = 0;
firstBufOfFile_ = true;
numBytesProcessedInRange_ = 0;
step_ = GET_HDFS_DATA;
}
break;
case GET_HDFS_DATA:
{
Int64 bytesToRead = hdfsScanBufMaxSize_ - trailingPrevRead_;
ex_assert(bytesToRead >= 0, "bytesToRead less than zero.");
if (hdfo_->fileIsSplitEnd() && !isSequenceFile())
{
if (bytesLeft_ > 0)
bytesToRead = min(bytesToRead,
(bytesLeft_ + hdfsScanTdb().rangeTailIOSize_));
else
bytesToRead = hdfsScanTdb().rangeTailIOSize_;
}
else
{
ex_assert(bytesLeft_ >= 0, "Bad assumption at e-o-f");
if (bytesToRead > bytesLeft_ +
1 // plus one for end-of-range files with no
// record delimiter at eof.
)
bytesToRead = bytesLeft_ + 1;
}
ex_assert(bytesToRead + trailingPrevRead_ <= hdfsScanBufMaxSize_,
"too many bites.");
if (hdfsStats_)
hdfsStats_->getHdfsTimer().start();
retcode = 0;
if (isSequenceFile())
{
sfrRetCode = sequenceFileReader_->fetchRowsIntoBuffer(stopOffset_,
hdfsScanBuffer_,
hdfsScanBufMaxSize_, //bytesToRead,
bytesRead_,
hdfsScanTdb().recordDelimiter_);
if (sfrRetCode != JNI_OK && sfrRetCode != SFR_NOMORE)
{
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8447), NULL,
NULL, NULL, NULL, sequenceFileReader_->getErrorText(sfrRetCode), NULL);
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
else
{
seqScanAgain_ = (sfrRetCode != SFR_NOMORE);
}
}
else
{
Int32 hdfsErrorDetail = 0;///this is the errno returned from the underlying hdfs call.
retcode = ExpLOBInterfaceSelectCursor
(lobGlob_,
hdfsFileName_,
NULL,
(Lng32)Lob_External_HDFS_File,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_,
0, NULL,
0, cursorId_,
requestTag_, Lob_Memory,
0, // not check status
(NOT hdfsScanTdb().hdfsPrefetch()), //1, // waited op
hdfsOffset_,
bytesToRead,
bytesRead_,
hdfsScanBuffer_ + trailingPrevRead_,
2, // read
0 // openType, not applicable for read
&hdfsErrorDetail
);
if (hdfsStats_)
hdfsStats_->incMaxHdfsIOTime(hdfsStats_->getHdfsTimer().stop());
if (retcode < 0)
{
Lng32 cliError = 0;
Lng32 intParam1 = -retcode;
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_ERROR_FROM_LOB_INTERFACE), NULL,
&intParam1,
&hdfsErrorDetail,
NULL,
"HDFS",
(char*)"ExpLOBInterfaceSelectCursor/read",
getLobErrStr(intParam1));
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
}
if (bytesRead_ <= 0)
{
// Finished with this file. Unexpected? Warning/event?
step_ = CLOSE_HDFS_CURSOR;
break;
}
else
{
char * lastByteRead = hdfsScanBuffer_ +
trailingPrevRead_ + bytesRead_ - 1;
if ((bytesRead_ < bytesToRead) &&
(*lastByteRead != hdfsScanTdb().recordDelimiter_))
{
// Some files end without a record delimiter but
// hive treats the end-of-file as a record delimiter.
lastByteRead[1] = hdfsScanTdb().recordDelimiter_;
bytesRead_++;
}
if (bytesRead_ > bytesLeft_)
{
if (isSequenceFile())
endOfRequestedRange_ = hdfsScanBuffer_ + bytesRead_;
else
endOfRequestedRange_ = hdfsScanBuffer_ +
trailingPrevRead_ + bytesLeft_;
}
else
endOfRequestedRange_ = NULL;
if (isSequenceFile())
{
// If the file is compressed, we don't know the real value
// of bytesLeft_, but it doesn't really matter.
if (seqScanAgain_ == false)
bytesLeft_ = 0;
}
else
bytesLeft_ -= bytesRead_;
}
if (hdfsStats_)
hdfsStats_->incBytesRead(bytesRead_);
if (firstBufOfFile_ && hdfo_->fileIsSplitBegin() && !isSequenceFile())
{
// Position in the hdfsScanBuffer_ to the
// first record delimiter.
hdfsBufNextRow_ =
hdfs_strchr(hdfsScanBuffer_,
hdfsScanTdb().recordDelimiter_,
hdfsScanBuffer_+trailingPrevRead_+
min(bytesRead_, hdfo_->bytesToRead_),
checkRangeDelimiter_,
hdfsScanTdb().getHiveScanMode(), &changedLen);
// May be that the record is too long? Or data isn't ascii?
// Or delimiter is incorrect.
if (! hdfsBufNextRow_)
{
if (hdfo_->bytesToRead_ < hdfsScanTdb().rangeTailIOSize_)
{
// for wide rows it is not an error if a whole range
// does not include a record delimiter. RangeTaileIOSize
// is set to max row size in generator by default.
// It is also checked in the compiler that rowsize
// is less than buffer size.
step_ = CLOSE_HDFS_CURSOR;
}
else
{
ComDiagsArea *diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(8446), NULL,
NULL, NULL, NULL,
(char*)"No record delimiter found in buffer from hdfsRead.",
NULL);
// no need to log errors in this case (bulk load) since
// this is a major issue and needs to be corrected
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR_WITH_CLOSE;
}
break;
}
hdfsBufNextRow_ += 1 + changedLen; // point past record delimiter.
//add changedLen since hdfs_strchr will remove the pointer ahead to remove the \r
}
else
hdfsBufNextRow_ = hdfsScanBuffer_;
debugPrevRow_ = hdfsScanBuffer_; // By convention, at
// beginning of scan, the
// prev is set to next.
debugtrailingPrevRead_ = 0;
debugPenultimatePrevRow_ = NULL;
firstBufOfFile_ = false;
hdfsOffset_ += bytesRead_;
step_ = PROCESS_HDFS_ROW;
}
break;
case PROCESS_HDFS_ROW:
{
exception_ = FALSE;
nextStep_ = NOT_STARTED;
debugPenultimatePrevRow_ = debugPrevRow_;
debugPrevRow_ = hdfsBufNextRow_;
int formattedRowLength = 0;
ComDiagsArea *transformDiags = NULL;
int err = 0;
char *startOfNextRow =
extractAndTransformAsciiSourceToSqlRow(err, transformDiags, hdfsScanTdb().getHiveScanMode());
bool rowWillBeSelected = true;
lastErrorCnd_ = NULL;
if(err)
{
if (hdfsScanTdb().continueOnError())
{
Lng32 errorCount = workAtp_->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount>0)
lastErrorCnd_ = workAtp_->getDiagsArea()->getErrorEntry(errorCount);
exception_ = TRUE;
rowWillBeSelected = false;
}
else
{
if (transformDiags)
pentry_down->setDiagsArea(transformDiags);
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
}
if (startOfNextRow == NULL)
{
step_ = REPOS_HDFS_DATA;
if (!exception_)
break;
}
else
{
numBytesProcessedInRange_ +=
startOfNextRow - hdfsBufNextRow_;
hdfsBufNextRow_ = startOfNextRow;
}
if (exception_)
{
nextStep_ = step_;
step_ = HANDLE_EXCEPTION;
break;
}
if (hdfsStats_)
hdfsStats_->incAccessedRows();
workAtp_->getTupp(hdfsScanTdb().workAtpIndex_) =
hdfsSqlTupp_;
if ((rowWillBeSelected) && (selectPred()))
{
ex_expr::exp_return_type evalRetCode =
selectPred()->eval(pentry_down->getAtp(), workAtp_);
if (evalRetCode == ex_expr::EXPR_FALSE)
rowWillBeSelected = false;
else if (evalRetCode == ex_expr::EXPR_ERROR)
{
if (hdfsScanTdb().continueOnError())
{
if (pentry_down->getDiagsArea() || workAtp_->getDiagsArea())
{
Lng32 errorCount = 0;
if (pentry_down->getDiagsArea())
{
errorCount = pentry_down->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = pentry_down->getDiagsArea()->getErrorEntry(errorCount);
}
else
{
errorCount = workAtp_->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = workAtp_->getDiagsArea()->getErrorEntry(errorCount);
}
}
exception_ = TRUE;
nextStep_ = step_;
step_ = HANDLE_EXCEPTION;
rowWillBeSelected = false;
break;
}
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
else
ex_assert(evalRetCode == ex_expr::EXPR_TRUE,
"invalid return code from expr eval");
}
if (rowWillBeSelected)
{
if (moveColsConvertExpr())
{
ex_expr::exp_return_type evalRetCode =
moveColsConvertExpr()->eval(workAtp_, workAtp_);
if (evalRetCode == ex_expr::EXPR_ERROR)
{
if (hdfsScanTdb().continueOnError())
{
if ( workAtp_->getDiagsArea())
{
Lng32 errorCount = 0;
errorCount = workAtp_->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = workAtp_->getDiagsArea()->getErrorEntry(errorCount);
}
exception_ = TRUE;
nextStep_ = step_;
step_ = HANDLE_EXCEPTION;
break;
}
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
}
if (hdfsStats_)
hdfsStats_->incUsedRows();
step_ = RETURN_ROW;
break;
}
break;
}
case RETURN_ROW:
{
if (qparent_.up->isFull())
return WORK_OK;
lastErrorCnd_ = NULL;
ex_queue_entry *up_entry = qparent_.up->getTailEntry();
queue_index saveParentIndex = up_entry->upState.parentIndex;
queue_index saveDownIndex = up_entry->upState.downIndex;
up_entry->copyAtp(pentry_down);
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.downIndex = qparent_.down->getHeadIndex();
up_entry->upState.status = ex_queue::Q_OK_MMORE;
if (moveExpr())
{
UInt32 maxRowLen = hdfsScanTdb().outputRowLength_;
UInt32 rowLen = maxRowLen;
if (hdfsScanTdb().useCifDefrag() &&
!pool_->currentBufferHasEnoughSpace((Lng32)hdfsScanTdb().outputRowLength_))
{
up_entry->getTupp(hdfsScanTdb().tuppIndex_) = defragTd_;
defragTd_->setReferenceCount(1);
ex_expr::exp_return_type evalRetCode =
moveExpr()->eval(up_entry->getAtp(), workAtp_,0,-1,&rowLen);
if (evalRetCode == ex_expr::EXPR_ERROR)
{
if (hdfsScanTdb().continueOnError())
{
if ((pentry_down->downState.request == ex_queue::GET_N) &&
(pentry_down->downState.requestValue == matches_))
step_ = CLOSE_HDFS_CURSOR;
else
step_ = PROCESS_HDFS_ROW;
up_entry->upState.parentIndex =saveParentIndex ;
up_entry->upState.downIndex = saveDownIndex ;
if (up_entry->getDiagsArea() || workAtp_->getDiagsArea())
{
Lng32 errorCount = 0;
if (up_entry->getDiagsArea())
{
errorCount = up_entry->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = up_entry->getDiagsArea()->getErrorEntry(errorCount);
}
else
{
errorCount = workAtp_->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = workAtp_->getDiagsArea()->getErrorEntry(errorCount);
}
}
exception_ = TRUE;
nextStep_ = step_;
step_ = HANDLE_EXCEPTION;
break;
}
else
{
// Get diags from up_entry onto pentry_down, which
// is where the HANDLE_ERROR step expects it.
ComDiagsArea *diagsArea = pentry_down->getDiagsArea();
if (diagsArea == NULL)
{
diagsArea =
ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
pentry_down->setDiagsArea (diagsArea);
}
pentry_down->getDiagsArea()->
mergeAfter(*up_entry->getDiagsArea());
up_entry->setDiagsArea(NULL);
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
if (pool_->get_free_tuple(
up_entry->getTupp(hdfsScanTdb().tuppIndex_),
rowLen))
return WORK_POOL_BLOCKED;
str_cpy_all(up_entry->getTupp(hdfsScanTdb().tuppIndex_).getDataPointer(),
defragTd_->getTupleAddress(),
rowLen);
}
}
else
{
if (pool_->get_free_tuple(
up_entry->getTupp(hdfsScanTdb().tuppIndex_),
(Lng32)hdfsScanTdb().outputRowLength_))
return WORK_POOL_BLOCKED;
ex_expr::exp_return_type evalRetCode =
moveExpr()->eval(up_entry->getAtp(), workAtp_,0,-1,&rowLen);
if (evalRetCode == ex_expr::EXPR_ERROR)
{
if (hdfsScanTdb().continueOnError())
{
if ((pentry_down->downState.request == ex_queue::GET_N) &&
(pentry_down->downState.requestValue == matches_))
step_ = CLOSE_FILE;
else
step_ = PROCESS_HDFS_ROW;
if (up_entry->getDiagsArea() || workAtp_->getDiagsArea())
{
Lng32 errorCount = 0;
if (up_entry->getDiagsArea())
{
errorCount = up_entry->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = up_entry->getDiagsArea()->getErrorEntry(errorCount);
}
else
{
errorCount = workAtp_->getDiagsArea()->getNumber(DgSqlCode::ERROR_);
if (errorCount > 0)
lastErrorCnd_ = workAtp_->getDiagsArea()->getErrorEntry(errorCount);
}
}
up_entry->upState.parentIndex =saveParentIndex ;
up_entry->upState.downIndex = saveDownIndex ;
exception_ = TRUE;
nextStep_ = step_;
step_ = HANDLE_EXCEPTION;
break;
}
else
{
// Get diags from up_entry onto pentry_down, which
// is where the HANDLE_ERROR step expects it.
ComDiagsArea *diagsArea = pentry_down->getDiagsArea();
if (diagsArea == NULL)
{
diagsArea =
ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
pentry_down->setDiagsArea (diagsArea);
}
pentry_down->getDiagsArea()->
mergeAfter(*up_entry->getDiagsArea());
up_entry->setDiagsArea(NULL);
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
}
if (hdfsScanTdb().useCif() && rowLen != maxRowLen)
{
pool_->resizeLastTuple(rowLen,
up_entry->getTupp(hdfsScanTdb().tuppIndex_).getDataPointer());
}
}
}
up_entry->upState.setMatchNo(++matches_);
if (matches_ == matchBrkPoint_)
brkpoint();
qparent_.up->insert();
// use ExOperStats now, to cover OPERATOR stats as well as
// ALL stats.
if (getStatsEntry())
getStatsEntry()->incActualRowsReturned();
workAtp_->setDiagsArea(NULL); // get rid of warnings.
if (((pentry_down->downState.request == ex_queue::GET_N) &&
(pentry_down->downState.requestValue == matches_)) ||
(pentry_down->downState.request == ex_queue::GET_NOMORE))
step_ = CLOSE_HDFS_CURSOR;
else
step_ = PROCESS_HDFS_ROW;
break;
}
case REPOS_HDFS_DATA:
{
bool scanAgain = false;
if (isSequenceFile())
scanAgain = seqScanAgain_;
else
{
if (hdfo_->fileIsSplitEnd())
{
if (numBytesProcessedInRange_ < hdfo_->getBytesToRead())
scanAgain = true;
}
else
if (bytesLeft_ > 0)
scanAgain = true;
}
if (scanAgain)
{
// Get ready for another gulp of hdfs data.
debugtrailingPrevRead_ = trailingPrevRead_;
trailingPrevRead_ = bytesRead_ -
(hdfsBufNextRow_ -
(hdfsScanBuffer_ + trailingPrevRead_));
// Move trailing data from the end of buffer to the front.
// The GET_HDFS_DATA step will use trailingPrevRead_ to
// adjust the read buffer ptr so that the next read happens
// contiguously to the final byte of the prev read. It will
// also use trailingPrevRead_ to to adjust the size of
// the next read so that fixed size buffer is not overrun.
// Finally, trailingPrevRead_ is used in the
// extractSourceFields method to keep from processing
// bytes left in the buffer from the previous read.
if ((trailingPrevRead_ > 0) &&
(hdfsBufNextRow_[0] == RANGE_DELIMITER))
{
checkRangeDelimiter_ = FALSE;
step_ = CLOSE_HDFS_CURSOR;
break;
}
memmove(hdfsScanBuffer_, hdfsBufNextRow_,
(size_t)trailingPrevRead_);
step_ = GET_HDFS_DATA;
}
else
{
trailingPrevRead_ = 0;
step_ = CLOSE_HDFS_CURSOR;
}
break;
}
case CLOSE_HDFS_CURSOR:
{
retcode = 0;
if (isSequenceFile())
{
sfrRetCode = sequenceFileReader_->close();
if (sfrRetCode != JNI_OK)
{
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea, (ExeErrorCode)(8447), NULL,
NULL, NULL, NULL, sequenceFileReader_->getErrorText(sfrRetCode), NULL);
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR;
break;
}
}
else
{
retcode = ExpLOBInterfaceSelectCursor
(lobGlob_,
hdfsFileName_,
NULL,
(Lng32)Lob_External_HDFS_File,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_,
0,NULL, //handle not relevant for non lob access
0, cursorId_,
requestTag_, Lob_Memory,
0, // not check status
(NOT hdfsScanTdb().hdfsPrefetch()), //1, // waited op
0,
hdfsScanBufMaxSize_,
bytesRead_,
hdfsScanBuffer_,
3, // close
0); // openType, not applicable for close
if (retcode < 0)
{
Lng32 cliError = 0;
Lng32 intParam1 = -retcode;
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_ERROR_FROM_LOB_INTERFACE), NULL,
&intParam1,
&errno,
NULL,
"HDFS",
(char*)"ExpLOBInterfaceSelectCursor/close",
getLobErrStr(intParam1));
pentry_down->setDiagsArea(diagsArea);
step_ = HANDLE_ERROR;
break;
}
}
step_ = CLOSE_FILE;
}
break;
case HANDLE_EXCEPTION:
{
step_ = nextStep_;
exception_ = FALSE;
Int64 exceptionCount = 0;
ExHbaseAccessTcb::incrErrorCount( ehi_,exceptionCount,
hdfsScanTdb().getErrCountTable(),hdfsScanTdb().getErrCountRowId());
if (hdfsScanTdb().getMaxErrorRows() > 0)
{
if (exceptionCount > hdfsScanTdb().getMaxErrorRows())
{
if (pentry_down->getDiagsArea())
pentry_down->getDiagsArea()->clear();
if (workAtp_->getDiagsArea())
workAtp_->getDiagsArea()->clear();
ComDiagsArea *da = workAtp_->getDiagsArea();
if(!da)
{
da = ComDiagsArea::allocate(getHeap());
workAtp_->setDiagsArea(da);
}
*da << DgSqlCode(-EXE_MAX_ERROR_ROWS_EXCEEDED);
step_ = HANDLE_ERROR_WITH_CLOSE;
break;
}
}
if (hdfsScanTdb().getLogErrorRows())
{
int loggingRowLen = hdfsLoggingRowEnd_ - hdfsLoggingRow_ +1;
ExHbaseAccessTcb::handleException((NAHeap *)getHeap(), hdfsLoggingRow_,
loggingRowLen, lastErrorCnd_,
ehi_,
LoggingFileCreated_,
loggingFileName_,
&loggingErrorDiags_);
}
if (pentry_down->getDiagsArea())
pentry_down->getDiagsArea()->clear();
if (workAtp_->getDiagsArea())
workAtp_->getDiagsArea()->clear();
}
break;
case HANDLE_ERROR_WITH_CLOSE:
case HANDLE_ERROR:
case HANDLE_ERROR_AND_DONE:
{
if (qparent_.up->isFull())
return WORK_OK;
ex_queue_entry *up_entry = qparent_.up->getTailEntry();
up_entry->copyAtp(pentry_down);
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.downIndex = qparent_.down->getHeadIndex();
if (workAtp_->getDiagsArea())
{
ComDiagsArea *diagsArea = up_entry->getDiagsArea();
if (diagsArea == NULL)
{
diagsArea =
ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
up_entry->setDiagsArea (diagsArea);
}
up_entry->getDiagsArea()->mergeAfter(*workAtp_->getDiagsArea());
workAtp_->setDiagsArea(NULL);
}
up_entry->upState.status = ex_queue::Q_SQLERROR;
qparent_.up->insert();
if (step_ == HANDLE_ERROR_WITH_CLOSE)
step_ = CLOSE_HDFS_CURSOR;
else if (step_ == HANDLE_ERROR_AND_DONE)
step_ = DONE;
else
step_ = ERROR_CLOSE_FILE;
break;
}
case CLOSE_FILE:
case ERROR_CLOSE_FILE:
{
if (getStatsEntry())
{
ExHdfsScanStats * stats =
getStatsEntry()->castToExHdfsScanStats();
if (stats)
{
ExLobStats s;
s.init();
retcode = ExpLOBinterfaceStats
(lobGlob_,
&s,
hdfsFileName_, //hdfsScanTdb().hdfsFileName_,
NULL, //(char*)"",
(Lng32)Lob_External_HDFS_File,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_);
*stats->lobStats() = *stats->lobStats() + s;
}
}
// if next file is not same as current file, then close the current file.
bool closeFile = true;
if ( (step_ == CLOSE_FILE) &&
((currRangeNum_ + 1) < (beginRangeNum_ + numRanges_)))
{
hdfo = getRange(currRangeNum_ + 1);
if (strcmp(hdfsFileName_, hdfo->fileName()) == 0)
closeFile = false;
}
if (closeFile)
{
retcode = ExpLOBinterfaceCloseFile
(lobGlob_,
hdfsFileName_,
NULL,
(Lng32)Lob_External_HDFS_File,
hdfsScanTdb().hostName_,
hdfsScanTdb().port_);
if ((step_ == CLOSE_FILE) &&
(retcode < 0))
{
Lng32 cliError = 0;
Lng32 intParam1 = -retcode;
ComDiagsArea * diagsArea = NULL;
ExRaiseSqlError(getHeap(), &diagsArea,
(ExeErrorCode)(EXE_ERROR_FROM_LOB_INTERFACE), NULL,
&intParam1,
&cliError,
NULL,
"HDFS",
(char*)"ExpLOBinterfaceCloseFile",
getLobErrStr(intParam1));
pentry_down->setDiagsArea(diagsArea);
}
}
if (step_ == CLOSE_FILE)
{
currRangeNum_++;
if (currRangeNum_ < (beginRangeNum_ + numRanges_)) {
if (((pentry_down->downState.request == ex_queue::GET_N) &&
(pentry_down->downState.requestValue == matches_)) ||
(pentry_down->downState.request == ex_queue::GET_NOMORE))
step_ = DONE;
else
// move to the next file.
step_ = INIT_HDFS_CURSOR;
break;
}
}
step_ = DONE;
}
break;
case DONE:
{
if (qparent_.up->isFull())
return WORK_OK;
if (ehi_ != NULL)
retcode = ehi_->hdfsClose();
ex_queue_entry *up_entry = qparent_.up->getTailEntry();
up_entry->copyAtp(pentry_down);
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.downIndex = qparent_.down->getHeadIndex();
up_entry->upState.status = ex_queue::Q_NO_DATA;
up_entry->upState.setMatchNo(matches_);
if (loggingErrorDiags_ != NULL)
{
ComDiagsArea * diagsArea = up_entry->getDiagsArea();
if (!diagsArea)
{
diagsArea =
ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
up_entry->setDiagsArea(diagsArea);
}
diagsArea->mergeAfter(*loggingErrorDiags_);
loggingErrorDiags_->clear();
}
qparent_.up->insert();
qparent_.down->removeHead();
step_ = NOT_STARTED;
dirInfo = hdfsGetPathInfo(hdfs, "/");
break;
}
default:
{
break;
}
} // switch
} // while
return WORK_OK;
}
char * ExHdfsScanTcb::extractAndTransformAsciiSourceToSqlRow(int &err,
ComDiagsArea* &diagsArea, int mode)
{
err = 0;
char *sourceData = hdfsBufNextRow_;
char *sourceRowEnd = NULL;
char *sourceColEnd = NULL;
int changedLen = 0;
NABoolean isTrailingMissingColumn = FALSE;
ExpTupleDesc * asciiSourceTD =
hdfsScanTdb().workCriDesc_->getTupleDescriptor(hdfsScanTdb().asciiTuppIndex_);
ExpTupleDesc * origSourceTD =
hdfsScanTdb().workCriDesc_->getTupleDescriptor(hdfsScanTdb().origTuppIndex_);
const char cd = hdfsScanTdb().columnDelimiter_;
const char rd = hdfsScanTdb().recordDelimiter_;
const char *sourceDataEnd = hdfsScanBuffer_+trailingPrevRead_+ bytesRead_;
hdfsLoggingRow_ = hdfsBufNextRow_;
if (asciiSourceTD->numAttrs() == 0)
{
sourceRowEnd = hdfs_strchr(sourceData, rd, sourceDataEnd, checkRangeDelimiter_, mode, &changedLen);
hdfsLoggingRowEnd_ = sourceRowEnd + changedLen;
if (!sourceRowEnd)
return NULL;
if ((endOfRequestedRange_) &&
(sourceRowEnd >= endOfRequestedRange_)) {
checkRangeDelimiter_ = TRUE;
*(sourceRowEnd +1)= RANGE_DELIMITER;
}
// no columns need to be converted. For e.g. count(*) with no predicate
return sourceRowEnd+1;
}
Lng32 neededColIndex = 0;
Attributes * attr = NULL;
Attributes * tgtAttr = NULL;
NABoolean rdSeen = FALSE;
for (Lng32 i = 0; i < hdfsScanTdb().convertSkipListSize_; i++)
{
// all remainin columns wil be skip columns, don't bother
// finding their column delimiters
if (neededColIndex == asciiSourceTD->numAttrs())
continue;
tgtAttr = NULL;
if (hdfsScanTdb().convertSkipList_[i] > 0)
{
attr = asciiSourceTD->getAttr(neededColIndex);
tgtAttr = origSourceTD->getAttr(neededColIndex);
neededColIndex++;
}
else
attr = NULL;
if (!isTrailingMissingColumn) {
sourceColEnd = hdfs_strchr(sourceData, rd, cd, sourceDataEnd, checkRangeDelimiter_, &rdSeen,mode, &changedLen);
if (sourceColEnd == NULL) {
if (rdSeen || (sourceRowEnd == NULL))
return NULL;
else
return sourceRowEnd+1;
}
Int32 len = 0;
len = (Int64)sourceColEnd - (Int64)sourceData;
if (rdSeen) {
sourceRowEnd = sourceColEnd + changedLen;
hdfsLoggingRowEnd_ = sourceRowEnd;
if ((endOfRequestedRange_) &&
(sourceRowEnd >= endOfRequestedRange_)) {
checkRangeDelimiter_ = TRUE;
*(sourceRowEnd +1)= RANGE_DELIMITER;
}
if (i != hdfsScanTdb().convertSkipListSize_ - 1)
isTrailingMissingColumn = TRUE;
}
if (attr) // this is a needed column. We need to convert
{
if (attr->getVCIndicatorLength() == sizeof(short))
*(short*)&hdfsAsciiSourceData_[attr->getVCLenIndOffset()]
= (short)len;
else
*(Int32*)&hdfsAsciiSourceData_[attr->getVCLenIndOffset()]
= len;
if (attr->getNullFlag())
{
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = 0;
if (hdfsScanTdb().getNullFormat()) // null format specified by user
{
if (((len == 0) && (strlen(hdfsScanTdb().getNullFormat()) == 0)) ||
((len > 0) && (memcmp(sourceData, hdfsScanTdb().getNullFormat(), len) == 0)))
{
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = -1;
}
} // if
else // null format not specified by user
{
// Use default null format.
// for non-varchar, length of zero indicates a null value.
// For all datatypes, HIVE_DEFAULT_NULL_STRING('\N') indicates a null value.
if (((len == 0) && (tgtAttr && (NOT DFS2REC::isSQLVarChar(tgtAttr->getDatatype())))) ||
((len > 0) && (memcmp(sourceData, HIVE_DEFAULT_NULL_STRING, len) == 0)))
{
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = -1;
}
} // else
} // if nullable attr
if (len > 0)
{
// move address of data into the source operand.
// convertExpr will dereference this addr and get to the actual
// data.
*(Int64*)&hdfsAsciiSourceData_[attr->getOffset()] =
(Int64)sourceData;
}
else
{
*(Int64*)&hdfsAsciiSourceData_[attr->getOffset()] =
(Int64)0;
}
} // if(attr)
} // if (!trailingMissingColumn)
else
{
// A delimiter was found, but not enough columns.
// Treat the rest of the columns as NULL.
if (attr && attr->getNullFlag())
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = -1;
}
sourceData = sourceColEnd + 1 ;
}
// It is possible that the above loop came out before
// rowDelimiter is encountered
// So try to find the record delimiter
if (sourceRowEnd == NULL) {
sourceRowEnd = hdfs_strchr(sourceData, rd, sourceDataEnd, checkRangeDelimiter_,mode, &changedLen);
if (sourceRowEnd) {
hdfsLoggingRowEnd_ = sourceRowEnd + changedLen; //changedLen is when hdfs_strchr move the return pointer to remove the extra \r
if ((endOfRequestedRange_) &&
(sourceRowEnd >= endOfRequestedRange_ )) {
checkRangeDelimiter_ = TRUE;
*(sourceRowEnd +1)= RANGE_DELIMITER;
}
}
}
workAtp_->getTupp(hdfsScanTdb().workAtpIndex_) = hdfsSqlTupp_;
workAtp_->getTupp(hdfsScanTdb().asciiTuppIndex_) = hdfsAsciiSourceTupp_;
// for later
workAtp_->getTupp(hdfsScanTdb().moveExprColsTuppIndex_) = moveExprColsTupp_;
if (convertExpr())
{
ex_expr::exp_return_type evalRetCode =
convertExpr()->eval(workAtp_, workAtp_);
if (evalRetCode == ex_expr::EXPR_ERROR)
err = -1;
else
err = 0;
}
if (sourceRowEnd)
return sourceRowEnd+1;
return NULL;
}
void ExHdfsScanTcb::computeRangesAtRuntime()
{
int numFiles = 0;
Int64 totalSize = 0;
Int64 myShare = 0;
Int64 runningSum = 0;
Int64 myStartPositionInBytes = 0;
Int64 myEndPositionInBytes = 0;
Int64 firstFileStartingOffset = 0;
Int64 lastFileBytesToRead = -1;
Int32 numParallelInstances = MAXOF(getGlobals()->getNumOfInstances(),1);
hdfsFS fs = ((GetCliGlobals()->currContext())->getHdfsServerConnection(
hdfsScanTdb().hostName_,
hdfsScanTdb().port_));
hdfsFileInfo *fileInfos = hdfsListDirectory(fs,
hdfsScanTdb().hdfsRootDir_,
&numFiles);
deallocateRuntimeRanges();
// in a first round, count the total number of bytes
for (int f=0; f<numFiles; f++)
{
ex_assert(fileInfos[f].mKind == kObjectKindFile,
"subdirectories not supported with runtime HDFS ranges");
totalSize += (Int64) fileInfos[f].mSize;
}
// compute my share, in bytes
// (the last of the ESPs may read a bit more)
myShare = totalSize / numParallelInstances;
myStartPositionInBytes = myInstNum_ * myShare;
beginRangeNum_ = -1;
numRanges_ = 0;
if (totalSize > 0)
{
if (myInstNum_ < numParallelInstances-1)
// read "myShare" bytes
myEndPositionInBytes = myStartPositionInBytes + myShare;
else
// the last ESP reads whatever is remaining
myEndPositionInBytes = totalSize;
// second round, find out the range of files I need to read
for (int g=0;
g < numFiles && runningSum < myEndPositionInBytes;
g++)
{
Int64 prevSum = runningSum;
runningSum += (Int64) fileInfos[g].mSize;
if (runningSum >= myStartPositionInBytes)
{
if (beginRangeNum_ < 0)
{
// I have reached the first file that I need to read
beginRangeNum_ = g;
firstFileStartingOffset =
myStartPositionInBytes - prevSum;
}
numRanges_++;
if (runningSum > myEndPositionInBytes)
// I don't need to read all the way to the end of this file
lastFileBytesToRead = myEndPositionInBytes - prevSum;
} // file is at or beyond my starting file
} // loop over files, determining ranges
} // total size > 0
else
beginRangeNum_ = 0;
// third round, populate the ranges that this ESP needs to read
for (int h=beginRangeNum_; h<beginRangeNum_+numRanges_; h++)
{
HdfsFileInfo *e = new(getHeap()) HdfsFileInfo;
const char *fileName = fileInfos[h].mName;
Int32 fileNameLen = strlen(fileName) + 1;
e->entryNum_ = h;
e->flags_ = 0;
e->fileName_ = new(getHeap()) char[fileNameLen];
str_cpy_all(e->fileName_, fileName, fileNameLen);
if (h == beginRangeNum_ &&
firstFileStartingOffset > 0)
{
e->startOffset_ = firstFileStartingOffset;
e->setFileIsSplitBegin(TRUE);
}
else
e->startOffset_ = 0;
if (h == beginRangeNum_+numRanges_-1 && lastFileBytesToRead > 0)
{
e->bytesToRead_ = lastFileBytesToRead;
e->setFileIsSplitEnd(TRUE);
}
else
e->bytesToRead_ = (Int64) fileInfos[h].mSize;
hdfsFileInfoListAsArray_.insertAt(h, e);
}
}
void ExHdfsScanTcb::deallocateRuntimeRanges()
{
if (hdfsScanTdb().getAssignRangesAtRuntime() &&
hdfsFileInfoListAsArray_.entries() > 0)
{
for (int i=0; i<hdfsFileInfoListAsArray_.getUsedLength(); i++)
if (hdfsFileInfoListAsArray_.used(i))
{
NADELETEBASIC(hdfsFileInfoListAsArray_[i]->fileName_.getPointer(), getHeap());
NADELETEBASIC(hdfsFileInfoListAsArray_[i], getHeap());
}
hdfsFileInfoListAsArray_.clear();
}
}
short ExHdfsScanTcb::moveRowToUpQueue(const char * row, Lng32 len,
short * rc, NABoolean isVarchar)
{
if (qparent_.up->isFull())
{
if (rc)
*rc = WORK_OK;
return -1;
}
Lng32 length;
if (len <= 0)
length = strlen(row);
else
length = len;
tupp p;
if (pool_->get_free_tuple(p, (Lng32)
((isVarchar ? SQL_VARCHAR_HDR_SIZE : 0)
+ length)))
{
if (rc)
*rc = WORK_POOL_BLOCKED;
return -1;
}
char * dp = p.getDataPointer();
if (isVarchar)
{
*(short*)dp = (short)length;
str_cpy_all(&dp[SQL_VARCHAR_HDR_SIZE], row, length);
}
else
{
str_cpy_all(dp, row, length);
}
ex_queue_entry * pentry_down = qparent_.down->getHeadEntry();
ex_queue_entry * up_entry = qparent_.up->getTailEntry();
up_entry->copyAtp(pentry_down);
up_entry->getAtp()->getTupp((Lng32)hdfsScanTdb().tuppIndex_) = p;
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.setMatchNo(++matches_);
up_entry->upState.status = ex_queue::Q_OK_MMORE;
// insert into parent
qparent_.up->insert();
return 0;
}
short ExHdfsScanTcb::handleError(short &rc)
{
if (qparent_.up->isFull())
{
rc = WORK_OK;
return -1;
}
if (qparent_.up->isFull())
return WORK_OK;
ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
ex_queue_entry *up_entry = qparent_.up->getTailEntry();
up_entry->copyAtp(pentry_down);
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.downIndex = qparent_.down->getHeadIndex();
up_entry->upState.status = ex_queue::Q_SQLERROR;
qparent_.up->insert();
return 0;
}
short ExHdfsScanTcb::handleDone(ExWorkProcRetcode &rc)
{
if (qparent_.up->isFull())
{
rc = WORK_OK;
return -1;
}
ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
ex_queue_entry *up_entry = qparent_.up->getTailEntry();
up_entry->copyAtp(pentry_down);
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.downIndex = qparent_.down->getHeadIndex();
up_entry->upState.status = ex_queue::Q_NO_DATA;
up_entry->upState.setMatchNo(matches_);
qparent_.up->insert();
qparent_.down->removeHead();
return 0;
}
////////////////////////////////////////////////////////////////////////
// ORC files
////////////////////////////////////////////////////////////////////////
ExOrcScanTcb::ExOrcScanTcb(
const ComTdbHdfsScan &orcScanTdb,
ex_globals * glob ) :
ExHdfsScanTcb( orcScanTdb, glob),
step_(NOT_STARTED)
{
orci_ = ExpORCinterface::newInstance(glob->getDefaultHeap(),
(char*)orcScanTdb.hostName_,
orcScanTdb.port_);
}
ExOrcScanTcb::~ExOrcScanTcb()
{
}
Int32 ExOrcScanTcb::fixup()
{
lobGlob_ = NULL;
return 0;
}
short ExOrcScanTcb::extractAndTransformOrcSourceToSqlRow(
char * orcRow,
Int64 orcRowLen,
Lng32 numOrcCols,
ComDiagsArea* &diagsArea)
{
short err = 0;
if ((!orcRow) || (orcRowLen <= 0))
return -1;
char *sourceData = orcRow;
ExpTupleDesc * asciiSourceTD =
hdfsScanTdb().workCriDesc_->getTupleDescriptor(hdfsScanTdb().asciiTuppIndex_);
if (asciiSourceTD->numAttrs() == 0)
{
// no columns need to be converted. For e.g. count(*) with no predicate
return 0;
}
Lng32 neededColIndex = 0;
Attributes * attr = NULL;
Lng32 numCurrCols = 0;
Lng32 currColLen;
for (Lng32 i = 0; i < hdfsScanTdb().convertSkipListSize_; i++)
{
if (hdfsScanTdb().convertSkipList_[i] > 0)
{
attr = asciiSourceTD->getAttr(neededColIndex);
neededColIndex++;
}
else
attr = NULL;
currColLen = *(Lng32*)sourceData;
sourceData += sizeof(currColLen);
if (attr) // this is a needed column. We need to convert
{
*(short*)&hdfsAsciiSourceData_[attr->getVCLenIndOffset()] = currColLen;
if (attr->getNullFlag())
{
if (currColLen == 0)
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = -1;
else if (memcmp(sourceData, HIVE_DEFAULT_NULL_STRING, currColLen) == 0)
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = -1;
else
*(short *)&hdfsAsciiSourceData_[attr->getNullIndOffset()] = 0;
}
if (currColLen > 0)
{
// move address of data into the source operand.
// convertExpr will dereference this addr and get to the actual
// data.
*(Int64*)&hdfsAsciiSourceData_[attr->getOffset()] =
(Int64)sourceData;
}
} // if(attr)
numCurrCols++;
sourceData += currColLen;
}
if (numCurrCols != numOrcCols)
{
return -1;
}
workAtp_->getTupp(hdfsScanTdb().workAtpIndex_) = hdfsSqlTupp_;
workAtp_->getTupp(hdfsScanTdb().asciiTuppIndex_) = hdfsAsciiSourceTupp_;
// for later
workAtp_->getTupp(hdfsScanTdb().moveExprColsTuppIndex_) = moveExprColsTupp_;
err = 0;
if (convertExpr())
{
ex_expr::exp_return_type evalRetCode =
convertExpr()->eval(workAtp_, workAtp_);
if (evalRetCode == ex_expr::EXPR_ERROR)
err = -1;
else
err = 0;
}
return err;
}
ExWorkProcRetcode ExOrcScanTcb::work()
{
Lng32 retcode = 0;
short rc = 0;
while (!qparent_.down->isEmpty())
{
ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
if (pentry_down->downState.request == ex_queue::GET_NOMORE)
step_ = DONE;
switch (step_)
{
case NOT_STARTED:
{
matches_ = 0;
hdfsStats_ = NULL;
if (getStatsEntry())
hdfsStats_ = getStatsEntry()->castToExHdfsScanStats();
ex_assert(hdfsStats_, "hdfs stats cannot be null");
if (hdfsStats_)
hdfsStats_->init();
beginRangeNum_ = -1;
numRanges_ = -1;
if (hdfsScanTdb().getHdfsFileInfoList()->isEmpty())
{
step_ = DONE;
break;
}
myInstNum_ = getGlobals()->getMyInstanceNumber();
beginRangeNum_ =
*(Lng32*)hdfsScanTdb().getHdfsFileRangeBeginList()->get(myInstNum_);
numRanges_ =
*(Lng32*)hdfsScanTdb().getHdfsFileRangeNumList()->get(myInstNum_);
currRangeNum_ = beginRangeNum_;
if (numRanges_ > 0)
step_ = INIT_ORC_CURSOR;
else
step_ = DONE;
}
break;
case INIT_ORC_CURSOR:
{
/* orci_ = ExpORCinterface::newInstance(getHeap(),
(char*)hdfsScanTdb().hostName_,
*/
hdfo_ = (HdfsFileInfo*)
hdfsScanTdb().getHdfsFileInfoList()->get(currRangeNum_);
orcStartRowNum_ = hdfo_->getStartRow();
orcNumRows_ = hdfo_->getNumRows();
hdfsFileName_ = hdfo_->fileName();
sprintf(cursorId_, "%d", currRangeNum_);
if (orcNumRows_ == -1) // select all rows
orcStopRowNum_ = -1;
else
orcStopRowNum_ = orcStartRowNum_ + orcNumRows_ - 1;
step_ = OPEN_ORC_CURSOR;
}
break;
case OPEN_ORC_CURSOR:
{
retcode = orci_->scanOpen(hdfsFileName_,
orcStartRowNum_, orcStopRowNum_);
if (retcode < 0)
{
setupError(EXE_ERROR_FROM_LOB_INTERFACE, retcode, "ORC", "scanOpen",
orci_->getErrorText(-retcode));
step_ = HANDLE_ERROR;
break;
}
step_ = GET_ORC_ROW;
}
break;
case GET_ORC_ROW:
{
orcRow_ = hdfsScanBuffer_;
orcRowLen_ = hdfsScanTdb().hdfsBufSize_;
retcode = orci_->scanFetch(orcRow_, orcRowLen_, orcRowNum_,
numOrcCols_);
if (retcode < 0)
{
setupError(EXE_ERROR_FROM_LOB_INTERFACE, retcode, "ORC", "scanFetch",
orci_->getErrorText(-retcode));
step_ = HANDLE_ERROR;
break;
}
if (retcode == 100)
{
step_ = CLOSE_ORC_CURSOR;
break;
}
step_ = PROCESS_ORC_ROW;
}
break;
case PROCESS_ORC_ROW:
{
int formattedRowLength = 0;
ComDiagsArea *transformDiags = NULL;
short err =
extractAndTransformOrcSourceToSqlRow(orcRow_, orcRowLen_,
numOrcCols_, transformDiags);
if (err)
{
if (transformDiags)
pentry_down->setDiagsArea(transformDiags);
step_ = HANDLE_ERROR;
break;
}
if (hdfsStats_)
hdfsStats_->incAccessedRows();
workAtp_->getTupp(hdfsScanTdb().workAtpIndex_) =
hdfsSqlTupp_;
bool rowWillBeSelected = true;
if (selectPred())
{
ex_expr::exp_return_type evalRetCode =
selectPred()->eval(pentry_down->getAtp(), workAtp_);
if (evalRetCode == ex_expr::EXPR_FALSE)
rowWillBeSelected = false;
else if (evalRetCode == ex_expr::EXPR_ERROR)
{
step_ = HANDLE_ERROR;
break;
}
else
ex_assert(evalRetCode == ex_expr::EXPR_TRUE,
"invalid return code from expr eval");
}
if (rowWillBeSelected)
{
if (moveColsConvertExpr())
{
ex_expr::exp_return_type evalRetCode =
moveColsConvertExpr()->eval(workAtp_, workAtp_);
if (evalRetCode == ex_expr::EXPR_ERROR)
{
step_ = HANDLE_ERROR;
break;
}
}
if (hdfsStats_)
hdfsStats_->incUsedRows();
step_ = RETURN_ROW;
break;
}
step_ = GET_ORC_ROW;
}
break;
case RETURN_ROW:
{
if (qparent_.up->isFull())
return WORK_OK;
ex_queue_entry *up_entry = qparent_.up->getTailEntry();
up_entry->copyAtp(pentry_down);
up_entry->upState.parentIndex =
pentry_down->downState.parentIndex;
up_entry->upState.downIndex = qparent_.down->getHeadIndex();
up_entry->upState.status = ex_queue::Q_OK_MMORE;
if (moveExpr())
{
UInt32 maxRowLen = hdfsScanTdb().outputRowLength_;
UInt32 rowLen = maxRowLen;
if (hdfsScanTdb().useCifDefrag() &&
!pool_->currentBufferHasEnoughSpace((Lng32)hdfsScanTdb().outputRowLength_))
{
up_entry->getTupp(hdfsScanTdb().tuppIndex_) = defragTd_;
defragTd_->setReferenceCount(1);
ex_expr::exp_return_type evalRetCode =
moveExpr()->eval(up_entry->getAtp(), workAtp_,0,-1,&rowLen);
if (evalRetCode == ex_expr::EXPR_ERROR)
{
// Get diags from up_entry onto pentry_down, which
// is where the HANDLE_ERROR step expects it.
ComDiagsArea *diagsArea = pentry_down->getDiagsArea();
if (diagsArea == NULL)
{
diagsArea =
ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
pentry_down->setDiagsArea (diagsArea);
}
pentry_down->getDiagsArea()->
mergeAfter(*up_entry->getDiagsArea());
up_entry->setDiagsArea(NULL);
step_ = HANDLE_ERROR;
break;
}
if (pool_->get_free_tuple(
up_entry->getTupp(hdfsScanTdb().tuppIndex_),
rowLen))
return WORK_POOL_BLOCKED;
str_cpy_all(up_entry->getTupp(hdfsScanTdb().tuppIndex_).getDataPointer(),
defragTd_->getTupleAddress(),
rowLen);
}
else
{
if (pool_->get_free_tuple(
up_entry->getTupp(hdfsScanTdb().tuppIndex_),
(Lng32)hdfsScanTdb().outputRowLength_))
return WORK_POOL_BLOCKED;
ex_expr::exp_return_type evalRetCode =
moveExpr()->eval(up_entry->getAtp(), workAtp_,0,-1,&rowLen);
if (evalRetCode == ex_expr::EXPR_ERROR)
{
// Get diags from up_entry onto pentry_down, which
// is where the HANDLE_ERROR step expects it.
ComDiagsArea *diagsArea = pentry_down->getDiagsArea();
if (diagsArea == NULL)
{
diagsArea =
ComDiagsArea::allocate(getGlobals()->getDefaultHeap());
pentry_down->setDiagsArea (diagsArea);
}
pentry_down->getDiagsArea()->
mergeAfter(*up_entry->getDiagsArea());
up_entry->setDiagsArea(NULL);
step_ = HANDLE_ERROR;
break;
}
if (hdfsScanTdb().useCif() && rowLen != maxRowLen)
{
pool_->resizeLastTuple(rowLen,
up_entry->getTupp(hdfsScanTdb().tuppIndex_).getDataPointer());
}
}
}
up_entry->upState.setMatchNo(++matches_);
if (matches_ == matchBrkPoint_)
brkpoint();
qparent_.up->insert();
// use ExOperStats now, to cover OPERATOR stats as well as
// ALL stats.
if (getStatsEntry())
getStatsEntry()->incActualRowsReturned();
workAtp_->setDiagsArea(NULL); // get rid of warnings.
if ((pentry_down->downState.request == ex_queue::GET_N) &&
(pentry_down->downState.requestValue == matches_))
step_ = CLOSE_ORC_CURSOR;
else
step_ = GET_ORC_ROW;
break;
}
case CLOSE_ORC_CURSOR:
{
retcode = orci_->scanClose();
if (retcode < 0)
{
setupError(EXE_ERROR_FROM_LOB_INTERFACE, retcode, "ORC", "scanClose",
orci_->getErrorText(-retcode));
step_ = HANDLE_ERROR;
break;
}
currRangeNum_++;
if (currRangeNum_ < (beginRangeNum_ + numRanges_))
{
// move to the next file.
step_ = INIT_ORC_CURSOR;
break;
}
step_ = DONE;
}
break;
case HANDLE_ERROR:
{
if (handleError(rc))
return rc;
step_ = DONE;
}
break;
case DONE:
{
if (handleDone(rc))
return rc;
step_ = NOT_STARTED;
}
break;
default:
{
break;
}
} // switch
} // while
return WORK_OK;
}
ExOrcFastAggrTcb::ExOrcFastAggrTcb(
const ComTdbOrcFastAggr &orcAggrTdb,
ex_globals * glob ) :
ExOrcScanTcb(orcAggrTdb, glob),
step_(NOT_STARTED)
{
if (orcAggrTdb.outputRowLength_ > 0)
aggrRow_ = new(glob->getDefaultHeap()) char[orcAggrTdb.outputRowLength_];
}
ExOrcFastAggrTcb::~ExOrcFastAggrTcb()
{
}
ExWorkProcRetcode ExOrcFastAggrTcb::work()
{
Lng32 retcode = 0;
short rc = 0;
while (!qparent_.down->isEmpty())
{
ex_queue_entry *pentry_down = qparent_.down->getHeadEntry();
if (pentry_down->downState.request == ex_queue::GET_NOMORE)
step_ = DONE;
switch (step_)
{
case NOT_STARTED:
{
matches_ = 0;
hdfsStats_ = NULL;
if (getStatsEntry())
hdfsStats_ = getStatsEntry()->castToExHdfsScanStats();
ex_assert(hdfsStats_, "hdfs stats cannot be null");
orcAggrTdb().getHdfsFileInfoList()->position();
rowCount_ = 0;
step_ = ORC_AGGR_INIT;
}
break;
case ORC_AGGR_INIT:
{
if (orcAggrTdb().getHdfsFileInfoList()->atEnd())
{
step_ = ORC_AGGR_PROJECT;
break;
}
hdfo_ = (HdfsFileInfo*)orcAggrTdb().getHdfsFileInfoList()->getNext();
hdfsFileName_ = hdfo_->fileName();
step_ = ORC_AGGR_EVAL;
}
break;
case ORC_AGGR_EVAL:
{
Int64 currRowCount = 0;
retcode = orci_->getRowCount(hdfsFileName_, currRowCount);
if (retcode < 0)
{
setupError(EXE_ERROR_FROM_LOB_INTERFACE, retcode, "ORC", "getRowCount",
orci_->getErrorText(-retcode));
step_ = HANDLE_ERROR;
break;
}
rowCount_ += currRowCount;
step_ = ORC_AGGR_INIT;
}
break;
case ORC_AGGR_PROJECT:
{
ExpTupleDesc * projTuppTD =
orcAggrTdb().workCriDesc_->getTupleDescriptor
(orcAggrTdb().workAtpIndex_);
Attributes * attr = projTuppTD->getAttr(0);
if (! attr)
{
step_ = HANDLE_ERROR;
break;
}
if (attr->getNullFlag())
{
*(short*)&aggrRow_[attr->getNullIndOffset()] = 0;
}
str_cpy_all(&aggrRow_[attr->getOffset()], (char*)&rowCount_, sizeof(rowCount_));
step_ = ORC_AGGR_RETURN;
}
break;
case ORC_AGGR_RETURN:
{
if (qparent_.up->isFull())
return WORK_OK;
short rc = 0;
if (moveRowToUpQueue(aggrRow_, orcAggrTdb().outputRowLength_,
&rc, FALSE))
return rc;
step_ = DONE;
}
break;
case HANDLE_ERROR:
{
if (handleError(rc))
return rc;
step_ = DONE;
}
break;
case DONE:
{
if (handleDone(rc))
return rc;
step_ = NOT_STARTED;
}
break;
} // switch
} // while
return WORK_OK;
}
| 1 | 16,713 | This can handle the '\\' problem, but if (not possible) the user define '\\' as null, this logic will break. So here, it should be to compare the whole HIVE_DEFAULT_NULL_STRING, and make sure length is equal, as I understand. \N is NULL, but \NA is not NULL, what will happen if there is \NAA ? | apache-trafodion | cpp |
@@ -0,0 +1,9 @@
+class ObservationPolicy
+ include ExceptionPolicy
+
+ def can_destroy!
+ role = Role.new(@user, @record.proposal)
+ check(@user.id == @record.user_id || role.client_admin? || @user.admin?,
+ "Only the observer can delete themself")
+ end
+end | 1 | 1 | 13,704 | Hmm, I would think that anyone who can edit the request should be able to delete the observation, in case they accidentally add the wrong person or something. | 18F-C2 | rb |
|
@@ -4,13 +4,9 @@ class PublicPagesController < ApplicationController
# GET template_index
# -----------------------------------------------------
def template_index
- template_ids = Template.where(org_id: Org.funder.pluck(:id), visibility: Template.visibilities[:publicly_visible]).valid.pluck(:dmptemplate_id).uniq << Template.where(is_default: true, published: true).pluck(:dmptemplate_id)
- @templates = []
- template_ids.flatten.each do |tid|
- t = Template.live(tid)
- @templates << t unless t.nil?
- end
- @templates = @templates.sort{|x,y| x.title <=> y.title } if @templates.count > 1
+ template_ids = Template.families(Org.funder.pluck(:id)).publicly_visible.pluck(:dmptemplate_id) <<
+ Template.where(is_default: true).valid.published.pluck(:dmptemplate_id)
+ @templates = Template.includes(:org).where(dmptemplate_id: template_ids.uniq.flatten).valid.published.order(title: :asc).page(1)
end
# GET template_export/:id | 1 | class PublicPagesController < ApplicationController
after_action :verify_authorized, except: [:template_index, :plan_index]
# GET template_index
# -----------------------------------------------------
def template_index
template_ids = Template.where(org_id: Org.funder.pluck(:id), visibility: Template.visibilities[:publicly_visible]).valid.pluck(:dmptemplate_id).uniq << Template.where(is_default: true, published: true).pluck(:dmptemplate_id)
@templates = []
template_ids.flatten.each do |tid|
t = Template.live(tid)
@templates << t unless t.nil?
end
@templates = @templates.sort{|x,y| x.title <=> y.title } if @templates.count > 1
end
# GET template_export/:id
# -----------------------------------------------------
def template_export
# only export live templates, id passed is dmptemplate_id
@template = Template.live(params[:id])
# covers authorization for this action. Pundit dosent support passing objects into scoped policies
raise Pundit::NotAuthorizedError unless PublicPagePolicy.new( @template).template_export?
skip_authorization
# now with prefetching (if guidance is added, prefetch annottaions/guidance)
@template = Template.includes(:org, phases: {sections:{questions:[:question_options, :question_format]}}).find(@template.id)
begin
file_name = @template.title.gsub(/ /, "_")
respond_to do |format|
format.docx { render docx: 'template_export', filename: "#{file_name}.docx" }
format.pdf do
@formatting = Settings::Template::DEFAULT_SETTINGS[:formatting]
render pdf: file_name,
margin: @formatting[:margin],
footer: {
center: _('This document was generated by %{application_name}') % {application_name: Rails.configuration.branding[:application][:name]},
font_size: 8,
spacing: (@formatting[:margin][:bottom] / 2) - 4,
right: '[page] of [topage]'
}
end
end
rescue ActiveRecord::RecordInvalid => e # What scenario is this triggered in? it's common to our export pages
#send back to public_index page
redirect_to template_index_path, alert: _('Unable to download the DMP Template at this time.')
end
end
# GET plan_export/:id
# -------------------------------------------------------------
def plan_export
@plan = Plan.find(params[:id])
# covers authorization for this action. Pundit dosent support passing objects into scoped policies
raise Pundit::NotAuthorizedError unless PublicPagePolicy.new(@plan, current_user).plan_organisationally_exportable? || PublicPagePolicy.new(@plan).plan_export?
skip_authorization
# This creates exported_plans with no user.
# Note for reviewers, The ExportedPlan model actually serves no purpose, except
# to store preferences for PDF export. These preferences could be moved into
# the prefs table for individual users, and a more semsible structure implimented
# to track the exports & formats(html/pdf/ect) of users.
@exported_plan = ExportedPlan.new.tap do |ep|
ep.plan = @plan
ep.phase_id = @plan.phases.first.id
ep.format = :pdf
plan_settings = @plan.settings(:export)
Settings::Template::DEFAULT_SETTINGS.each do |key, value|
ep.settings(:export).send("#{key}=", plan_settings.send(key))
end
end
# need to determine which phases to export
@a_q_ids = Answer.where(plan_id: @plan.id).pluck(:question_id).uniq
@a_s_ids = Question.where(id: @a_q_ids).pluck(:section_id).uniq
a_p_ids = Section.where(id: @a_s_ids).pluck(:phase_id).uniq
@phases = Phase.includes(sections: :questions).where(id: a_p_ids).order(:number)
# name of owner and any co-owners
@creator_text = @plan.owner.name(false)
@plan.roles.administrator.not_creator.each do |role|
@creator_text += ", " + role.user.name(false)
end
# Org name of plan owner
@affiliation = @plan.owner.org.name
# set the funder name
@funder = @plan.template.org.funder? ? @plan.template.org.name : nil
# set the template name and customizer name if applicable
@template = @plan.template.title
@customizer = ""
cust_questions = @plan.questions.where(modifiable: true).pluck(:id)
# if the template is customized, and has custom answered questions
if @plan.template.customization_of.present? && Answer.where(plan_id: @plan.id, question_id: cust_questions).present?
@customizer = _(" Customised By: ") + @plan.template.org.name
end
begin
@exported_plan.save!
file_name = @plan.title.gsub(/ /, "_")
respond_to do |format|
format.pdf do
@formatting = @plan.settings(:export).formatting
render pdf: file_name,
margin: @formatting[:margin],
footer: {
center: _('This document was generated by %{application_name}') % {application_name: Rails.configuration.branding[:application][:name]},
font_size: 8,
spacing: (@formatting[:margin][:bottom] / 2) - 4,
right: '[page] of [topage]'
}
end
end
rescue ActiveRecord::RecordInvalid => e
# send to the public_index page
redirect_to public_index_plan_path, alert: _('Unable to download the DMP at this time.')
end
end
# GET /plans_index
# ------------------------------------------------------------------------------------
def plan_index
@plans = Plan.publicly_visible
@plans = @plans.sort{|x,y| x.title <=> y.title } if @plans.count > 1
end
end
| 1 | 17,326 | I know we are doing this other places already. It would be good to refactor this and the paginable publicly_visible so that we are DRY. Can wait until after MVP though when we do general cleanup | DMPRoadmap-roadmap | rb |
@@ -576,7 +576,12 @@ update_lookuptable_tls(dcontext_t *dcontext, ibl_table_t *table)
* crashing or worse.
*/
state->table_space.table[table->branch_type].lookuptable = table->table;
- state->table_space.table[table->branch_type].hash_mask = table->hash_mask;
+ /* Perform a Store-Release, which when combined with a Load-Acquire of the mask
+ * in the IBL itself, ensures the prior store to lookuptable is never
+ * observed before this store to hash_mask on weakly ordered arches.
+ */
+ ATOMIC_PTRSZ_ALIGNED_WRITE(&state->table_space.table[table->branch_type].hash_mask,
+ table->hash_mask, false);
}
#ifdef DEBUG | 1 | /* **********************************************************
* Copyright (c) 2011-2020 Google, Inc. All rights reserved.
* Copyright (c) 2000-2010 VMware, Inc. All rights reserved.
* **********************************************************/
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2001-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2000-2001 Hewlett-Packard Company */
/*
* fragment.c - fragment related routines
*/
#include "globals.h"
#include "link.h"
#include "fragment.h"
#include "fcache.h"
#include "emit.h"
#include "monitor.h"
#include "instrument.h"
#include <stddef.h> /* for offsetof */
#include <limits.h> /* UINT_MAX */
#include "perscache.h"
#include "synch.h"
#ifdef UNIX
# include "nudge.h"
#endif
/* FIXME: make these runtime parameters */
#define INIT_HTABLE_SIZE_SHARED_BB (DYNAMO_OPTION(coarse_units) ? 5 : 10)
#define INIT_HTABLE_SIZE_SHARED_TRACE 10
/* the only private bbs will be selfmod, so start small */
#define INIT_HTABLE_SIZE_BB (DYNAMO_OPTION(shared_bbs) ? 5 : 10)
/* coarse-grain fragments do not use futures */
#define INIT_HTABLE_SIZE_SHARED_FUTURE (DYNAMO_OPTION(coarse_units) ? 5 : 10)
#ifdef RETURN_AFTER_CALL
/* we have small per-module hashtables */
# define INIT_HTABLE_SIZE_AFTER_CALL 5
#endif
/* private futures are only used when we have private fragments */
#define INIT_HTABLE_SIZE_FUTURE \
((DYNAMO_OPTION(shared_bbs) && DYNAMO_OPTION(shared_traces)) ? 5 : 9)
/* per-module htables */
#define INIT_HTABLE_SIZE_COARSE 5
#define INIT_HTABLE_SIZE_COARSE_TH 4
#ifdef RCT_IND_BRANCH
# include "rct.h"
/* we have small per-module hashtables */
# define INIT_HTABLE_SIZE_RCT_IBT 7
# ifndef RETURN_AFTER_CALL
# error RCT_IND_BRANCH requires RETURN_AFTER_CALL since it reuses data types
# endif
#endif
/* if shared traces, we currently have no private traces so make table tiny
* FIMXE: should start out w/ no table at all
*/
#define INIT_HTABLE_SIZE_TRACE (DYNAMO_OPTION(shared_traces) ? 6 : 9)
/* for small table sizes resize is not an expensive operation and we start smaller */
/* Current flusher, protected by thread_initexit_lock. */
DECLARE_FREQPROT_VAR(static dcontext_t *flusher, NULL);
/* Current allsynch-flusher, protected by thread_initexit_lock. */
DECLARE_FREQPROT_VAR(static dcontext_t *allsynch_flusher, NULL);
/* Current flush base and size, protected by thread_initexit_lock. */
DECLARE_FREQPROT_VAR(static app_pc flush_base, NULL);
DECLARE_FREQPROT_VAR(static size_t flush_size, 0);
/* These global tables are kept on the heap for selfprot (case 7957) */
/* synchronization to these tables is accomplished via read-write locks,
* where the writers are removal and resizing -- addition is atomic to
* readers.
* for now none of these are read from ibl routines so we only have to
* synch with other DR routines
*/
static fragment_table_t *shared_bb;
static fragment_table_t *shared_trace;
/* if we have either shared bbs or shared traces we need this shared: */
static fragment_table_t *shared_future;
/* Thread-shared tables are allocated in a shared per_thread_t.
* The structure is also used if we're dumping shared traces.
* Kept on the heap for selfprot (case 7957)
*/
static per_thread_t *shared_pt;
#define USE_SHARED_PT() \
(SHARED_IBT_TABLES_ENABLED() || (TRACEDUMP_ENABLED() && DYNAMO_OPTION(shared_traces)))
/* We keep track of "old" IBT target tables in a linked list and
* deallocate them in fragment_exit(). */
/* FIXME Deallocate tables more aggressively using a distributed, refcounting
* algo as is used for shared deletion. */
typedef struct _dead_fragment_table_t {
fragment_entry_t *table_unaligned;
uint table_flags;
uint capacity;
uint ref_count;
struct _dead_fragment_table_t *next;
} dead_fragment_table_t;
/* We keep these list pointers on the heap for selfprot (case 8074). */
typedef struct _dead_table_lists_t {
dead_fragment_table_t *dead_tables;
dead_fragment_table_t *dead_tables_tail;
} dead_table_lists_t;
static dead_table_lists_t *dead_lists;
DECLARE_CXTSWPROT_VAR(static mutex_t dead_tables_lock, INIT_LOCK_FREE(dead_tables_lock));
#ifdef RETURN_AFTER_CALL
/* High level lock for an atomic lookup+add operation on the
* after call tables. */
DECLARE_CXTSWPROT_VAR(static mutex_t after_call_lock, INIT_LOCK_FREE(after_call_lock));
/* We use per-module tables and only need this table for non-module code;
* on Linux though this is the only table used, until we have a module list.
*/
static rct_module_table_t rac_non_module_table;
#endif
/* allows independent sequences of flushes and delayed deletions,
* though with -syscalls_synch_flush additions we now hold this
* throughout a flush.
*/
DECLARE_CXTSWPROT_VAR(mutex_t shared_cache_flush_lock,
INIT_LOCK_FREE(shared_cache_flush_lock));
/* Global count of flushes, used as a timestamp for shared deletion.
* Reads may be done w/o a lock, but writes can only be done
* via increment_global_flushtime() while holding shared_cache_flush_lock.
*/
DECLARE_FREQPROT_VAR(uint flushtime_global, 0);
#ifdef CLIENT_INTERFACE
DECLARE_CXTSWPROT_VAR(mutex_t client_flush_request_lock,
INIT_LOCK_FREE(client_flush_request_lock));
DECLARE_CXTSWPROT_VAR(client_flush_req_t *client_flush_requests, NULL);
#endif
#if defined(RCT_IND_BRANCH) && defined(UNIX)
/* On Win32 we use per-module tables; on Linux we use a single global table,
* until we have a module list.
*/
rct_module_table_t rct_global_table;
#endif
#define NULL_TAG ((app_pc)PTR_UINT_0)
/* FAKE_TAG is used as a deletion marker for unlinked entries */
#define FAKE_TAG ((app_pc)PTR_UINT_MINUS_1)
/* instead of an empty hashtable slot containing NULL, we fill it
* with a pointer to this constant fragment, which we give a tag
* of 0.
* PR 305731: rather than having a start_pc of 0, which causes
* an app targeting 0 to crash at 0, we point at a handler that
* sends the app to an ibl miss.
*/
byte *hashlookup_null_target;
#define HASHLOOKUP_NULL_START_PC ((cache_pc)hashlookup_null_handler)
static const fragment_t null_fragment = {
NULL_TAG, 0, 0, 0, 0, HASHLOOKUP_NULL_START_PC,
};
/* to avoid range check on fast path using an end of table sentinel fragment */
static const fragment_t sentinel_fragment = {
NULL_TAG, 0, 0, 0, 0, HASHLOOKUP_SENTINEL_START_PC,
};
/* Shared fragment IBTs: We need to preserve the open addressing traversal
* in the hashtable while marking a table entry as unlinked.
* A null_fragment won't work since it terminates the traversal,
* so we use an unlinked marker. The lookup table entry for
* an unlinked entry *always* has its start_pc_fragment set to
* an IBL target_delete entry.
*/
static const fragment_t unlinked_fragment = {
FAKE_TAG,
};
/* macro used in the code from time of deletion markers */
/* Shared fragment IBTs: unlinked_fragment isn't a real fragment either. So they
* are naturally deleted during a table resize. */
#define REAL_FRAGMENT(fragment) \
((fragment) != &null_fragment && (fragment) != &unlinked_fragment && \
(fragment) != &sentinel_fragment)
#define GET_PT(dc) \
((dc) == GLOBAL_DCONTEXT ? (USE_SHARED_PT() ? shared_pt : NULL) \
: (per_thread_t *)(dc)->fragment_field)
#define TABLE_PROTECTED(ptable) \
(!TABLE_NEEDS_LOCK(ptable) || READWRITE_LOCK_HELD(&(ptable)->rwlock))
/* everything except the invisible table is in here */
#define GET_FTABLE_HELPER(pt, flags, otherwise) \
(TEST(FRAG_IS_TRACE, (flags)) \
? (TEST(FRAG_SHARED, (flags)) ? shared_trace : &pt->trace) \
: (TEST(FRAG_SHARED, (flags)) \
? (TEST(FRAG_IS_FUTURE, (flags)) ? shared_future : shared_bb) \
: (TEST(FRAG_IS_FUTURE, (flags)) ? &pt->future : (otherwise))))
#define GET_FTABLE(pt, flags) GET_FTABLE_HELPER(pt, (flags), &pt->bb)
/* indirect branch table per target type (bb vs trace) and indirect branch type */
#define GET_IBT_TABLE(pt, flags, branch_type) \
(TEST(FRAG_IS_TRACE, (flags)) \
? (DYNAMO_OPTION(shared_trace_ibt_tables) \
? &shared_pt->trace_ibt[(branch_type)] \
: &(pt)->trace_ibt[(branch_type)]) \
: (DYNAMO_OPTION(shared_bb_ibt_tables) ? &shared_pt->bb_ibt[(branch_type)] \
: &(pt)->bb_ibt[(branch_type)]))
/********************************** STATICS ***********************************/
static uint
fragment_heap_size(uint flags, int direct_exits, int indirect_exits);
static void
fragment_free_future(dcontext_t *dcontext, future_fragment_t *fut);
#if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH)
static void
coarse_persisted_fill_ibl(dcontext_t *dcontext, coarse_info_t *info,
ibl_branch_type_t branch_type);
#endif
#ifdef CLIENT_INTERFACE
static void
process_client_flush_requests(dcontext_t *dcontext, dcontext_t *alloc_dcontext,
client_flush_req_t *req, bool flush);
#endif
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
/* trace logging and synch for shared trace file: */
DECLARE_CXTSWPROT_VAR(static mutex_t tracedump_mutex, INIT_LOCK_FREE(tracedump_mutex));
DECLARE_FREQPROT_VAR(static stats_int_t tcount, 0); /* protected by tracedump_mutex */
static void
exit_trace_file(per_thread_t *pt);
static void
output_trace(dcontext_t *dcontext, per_thread_t *pt, fragment_t *f,
stats_int_t deleted_at);
static void
init_trace_file(per_thread_t *pt);
#endif
#define SHOULD_OUTPUT_FRAGMENT(flags) \
(TEST(FRAG_IS_TRACE, (flags)) && !TEST(FRAG_TRACE_OUTPUT, (flags)) && \
TRACEDUMP_ENABLED())
#define FRAGMENT_COARSE_WRAPPER_FLAGS \
FRAG_FAKE | FRAG_SHARED | FRAG_COARSE_GRAIN | FRAG_LINKED_OUTGOING | \
FRAG_LINKED_INCOMING
/* We use temporary fragment_t + linkstub_t structs to more easily
* use existing code when emitting coarse-grain fragments.
* Only 1-ind-exit or 1 or 2 dir exit bbs can be coarse-grain.
* The bb_building_lock protects use of this.
*/
DECLARE_FREQPROT_VAR(
static struct {
fragment_t f;
union {
struct {
direct_linkstub_t dir_exit_1;
direct_linkstub_t dir_exit_2;
} dir_exits;
indirect_linkstub_t ind_exit;
} exits;
} coarse_emit_fragment,
{ { 0 } });
#ifdef SHARING_STUDY
/***************************************************************************
* fragment_t sharing study
* Only used with -fragment_sharing_study
* When the option is off we go ahead and waste the 4 static vars
* below so we don't have to have a define and separate build.
*/
typedef struct _thread_list_t {
uint thread_num;
uint count;
struct _thread_list_t *next;
} thread_list_t;
typedef struct _shared_entry_t {
app_pc tag;
uint num_threads;
thread_list_t *threads;
uint heap_size;
uint cache_size;
struct _shared_entry_t *next;
} shared_entry_t;
# define SHARED_HASH_BITS 16
static shared_entry_t **shared_blocks;
DECLARE_CXTSWPROT_VAR(static mutex_t shared_blocks_lock,
INIT_LOCK_FREE(shared_blocks_lock));
static shared_entry_t **shared_traces;
DECLARE_CXTSWPROT_VAR(static mutex_t shared_traces_lock,
INIT_LOCK_FREE(shared_traces_lock));
/* assumes caller holds table's lock! */
static shared_entry_t *
shared_block_lookup(shared_entry_t **table, fragment_t *f)
{
shared_entry_t *e;
uint hindex;
hindex = HASH_FUNC_BITS((ptr_uint_t)f->tag, SHARED_HASH_BITS);
/* using collision chains */
for (e = table[hindex]; e != NULL; e = e->next) {
if (e->tag == f->tag) {
return e;
}
}
return NULL;
}
static void
reset_shared_block_table(shared_entry_t **table, mutex_t *lock)
{
shared_entry_t *e, *nxte;
uint i;
uint size = HASHTABLE_SIZE(SHARED_HASH_BITS);
d_r_mutex_lock(lock);
for (i = 0; i < size; i++) {
for (e = table[i]; e != NULL; e = nxte) {
thread_list_t *tl = e->threads;
thread_list_t *tlnxt;
nxte = e->next;
while (tl != NULL) {
tlnxt = tl->next;
global_heap_free(tl, sizeof(thread_list_t) HEAPACCT(ACCT_OTHER));
tl = tlnxt;
}
global_heap_free(e, sizeof(shared_entry_t) HEAPACCT(ACCT_OTHER));
}
}
global_heap_free(table, size * sizeof(shared_entry_t *) HEAPACCT(ACCT_OTHER));
d_r_mutex_unlock(lock);
}
static void
add_shared_block(shared_entry_t **table, mutex_t *lock, fragment_t *f)
{
shared_entry_t *e;
uint hindex;
int num_direct = 0, num_indirect = 0;
linkstub_t *l = FRAGMENT_EXIT_STUBS(f);
/* use num to avoid thread_id_t recycling problems */
uint tnum = get_thread_num(d_r_get_thread_id());
d_r_mutex_lock(lock);
e = shared_block_lookup(table, f);
if (e != NULL) {
thread_list_t *tl = e->threads;
for (; tl != NULL; tl = tl->next) {
if (tl->thread_num == tnum) {
tl->count++;
LOG(GLOBAL, LOG_ALL, 2,
"add_shared_block: tag " PFX ", but re-add #%d for thread #%d\n",
e->tag, tl->count, tnum);
d_r_mutex_unlock(lock);
return;
}
}
tl = global_heap_alloc(sizeof(thread_list_t) HEAPACCT(ACCT_OTHER));
tl->thread_num = tnum;
tl->count = 1;
tl->next = e->threads;
e->threads = tl;
e->num_threads++;
LOG(GLOBAL, LOG_ALL, 2,
"add_shared_block: tag " PFX " thread #%d => %d threads\n", e->tag, tnum,
e->num_threads);
d_r_mutex_unlock(lock);
return;
}
/* get num stubs to find heap size */
for (; l != NULL; l = LINKSTUB_NEXT_EXIT(l)) {
if (LINKSTUB_DIRECT(l->flags))
num_direct++;
else {
ASSERT(LINKSTUB_INDIRECT(l->flags));
num_indirect++;
}
}
/* add entry to thread hashtable */
e = (shared_entry_t *)global_heap_alloc(sizeof(shared_entry_t) HEAPACCT(ACCT_OTHER));
e->tag = f->tag;
e->num_threads = 1;
e->heap_size = fragment_heap_size(f->flags, num_direct, num_indirect);
e->cache_size = (f->size + f->fcache_extra);
e->threads = global_heap_alloc(sizeof(thread_list_t) HEAPACCT(ACCT_OTHER));
e->threads->thread_num = tnum;
e->threads->count = 1;
e->threads->next = NULL;
LOG(GLOBAL, LOG_ALL, 2,
"add_shared_block: tag " PFX ", heap %d, cache %d, thread #%d\n", e->tag,
e->heap_size, e->cache_size, e->threads->thread_num);
hindex = HASH_FUNC_BITS((ptr_uint_t)f->tag, SHARED_HASH_BITS);
e->next = table[hindex];
table[hindex] = e;
d_r_mutex_unlock(lock);
}
static void
print_shared_table_stats(shared_entry_t **table, mutex_t *lock, const char *name)
{
uint i;
shared_entry_t *e;
uint size = HASHTABLE_SIZE(SHARED_HASH_BITS);
uint tot = 0, shared_tot = 0, shared = 0, heap = 0, cache = 0, creation_count = 0;
d_r_mutex_lock(lock);
for (i = 0; i < size; i++) {
for (e = table[i]; e != NULL; e = e->next) {
thread_list_t *tl = e->threads;
tot++;
shared_tot += e->num_threads;
for (; tl != NULL; tl = tl->next)
creation_count += tl->count;
if (e->num_threads > 1) {
shared++;
/* assume similar size for each thread -- cache padding
* only real difference
*/
heap += (e->heap_size * e->num_threads);
cache += (e->cache_size * e->num_threads);
}
}
}
d_r_mutex_unlock(lock);
LOG(GLOBAL, LOG_ALL, 1, "Shared %s statistics:\n", name);
LOG(GLOBAL, LOG_ALL, 1, "\ttotal blocks: %10d\n", tot);
LOG(GLOBAL, LOG_ALL, 1, "\tcreation count: %10d\n", creation_count);
LOG(GLOBAL, LOG_ALL, 1, "\tshared count: %10d\n", shared_tot);
LOG(GLOBAL, LOG_ALL, 1, "\tshared blocks: %10d\n", shared);
LOG(GLOBAL, LOG_ALL, 1, "\tshared heap: %10d\n", heap);
LOG(GLOBAL, LOG_ALL, 1, "\tshared cache: %10d\n", cache);
}
void
print_shared_stats()
{
print_shared_table_stats(shared_blocks, &shared_blocks_lock, "basic block");
print_shared_table_stats(shared_traces, &shared_traces_lock, "trace");
}
#endif /* SHARING_STUDY ***************************************************/
#ifdef FRAGMENT_SIZES_STUDY /*****************************************/
# include <math.h>
/* don't bother to synchronize these */
static int bb_sizes[200000];
static int trace_sizes[40000];
static int num_bb = 0;
static int num_traces = 0;
void
record_fragment_size(int size, bool is_trace)
{
if (is_trace) {
trace_sizes[num_traces] = size;
num_traces++;
ASSERT(num_traces < 40000);
} else {
bb_sizes[num_bb] = size;
num_bb++;
ASSERT(num_bb < 200000);
}
}
void
print_size_results()
{
LOG(GLOBAL, LOG_ALL, 1, "Basic block sizes (bytes):\n");
print_statistics(bb_sizes, num_bb);
LOG(GLOBAL, LOG_ALL, 1, "Trace sizes (bytes):\n");
print_statistics(trace_sizes, num_traces);
}
#endif /* FRAGMENT_SIZES_STUDY */ /*****************************************/
#define FRAGTABLE_WHICH_HEAP(flags) \
(TESTALL(FRAG_TABLE_INCLUSIVE_HIERARCHY | FRAG_TABLE_IBL_TARGETED, (flags)) \
? ACCT_IBLTABLE \
: ACCT_FRAG_TABLE)
#ifdef HASHTABLE_STATISTICS
# define UNPROT_STAT(stats) unprot_stats->stats
/* FIXME: either put in nonpersistent heap as appropriate, or
* preserve across resets
*/
# define ALLOC_UNPROT_STATS(dcontext, table) \
do { \
(table)->unprot_stats = HEAP_TYPE_ALLOC( \
(dcontext), unprot_ht_statistics_t, \
FRAGTABLE_WHICH_HEAP((table)->table_flags), UNPROTECTED); \
memset((table)->unprot_stats, 0, sizeof(unprot_ht_statistics_t)); \
} while (0)
# define DEALLOC_UNPROT_STATS(dcontext, table) \
HEAP_TYPE_FREE((dcontext), (table)->unprot_stats, unprot_ht_statistics_t, \
FRAGTABLE_WHICH_HEAP((table)->table_flags), UNPROTECTED)
# define CHECK_UNPROT_STATS(table) ASSERT(table.unprot_stats != NULL)
static void
check_stay_on_trace_stats_overflow(dcontext_t *dcontext, ibl_branch_type_t branch_type)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
hashtable_statistics_t *lookup_stats =
&pt->trace_ibt[branch_type].unprot_stats->trace_ibl_stats[branch_type];
if (lookup_stats->ib_stay_on_trace_stat < lookup_stats->ib_stay_on_trace_stat_last) {
lookup_stats->ib_stay_on_trace_stat_ovfl++;
}
lookup_stats->ib_stay_on_trace_stat_last = lookup_stats->ib_stay_on_trace_stat;
/* FIXME: ib_trace_last_ibl_exit should have an overflow check as well */
}
#endif /* HASHTABLE_STATISTICS */
/* init/update the tls slots storing this table's mask and lookup base
* N.B.: for thread-shared the caller must call for each thread
*/
/* currently we don't support a mixture */
static inline void
update_lookuptable_tls(dcontext_t *dcontext, ibl_table_t *table)
{
/* use dcontext->local_state, rather than get_local_state(), to support
* being called from other threads!
*/
local_state_extended_t *state = (local_state_extended_t *)dcontext->local_state;
ASSERT(state != NULL);
ASSERT(DYNAMO_OPTION(ibl_table_in_tls));
/* We must hold at least the read lock here, else we could grab
* an inconsistent mask/lookuptable pair if another thread is in the middle
* of resizing the table (case 10405).
*/
ASSERT_TABLE_SYNCHRONIZED(table, READWRITE);
/* case 10296: for shared tables we must update the table
* before the mask, as the ibl lookup code accesses the mask first,
* and old mask + new table is ok since it will de-ref within the
* new table (we never shrink tables) and be a miss, whereas
* new mask + old table can de-ref beyond the end of the table,
* crashing or worse.
*/
state->table_space.table[table->branch_type].lookuptable = table->table;
state->table_space.table[table->branch_type].hash_mask = table->hash_mask;
}
#ifdef DEBUG
static const char *ibl_bb_table_type_names[IBL_BRANCH_TYPE_END] = { "ret_bb",
"indcall_bb",
"indjmp_bb" };
static const char *ibl_trace_table_type_names[IBL_BRANCH_TYPE_END] = { "ret_trace",
"indcall_trace",
"indjmp_trace" };
#endif
#ifdef DEBUG
static inline void
dump_lookuptable_tls(dcontext_t *dcontext)
{
/* use dcontext->local_state, rather than get_local_state(), to support
* being called from other threads!
*/
if (DYNAMO_OPTION(ibl_table_in_tls)) {
local_state_extended_t *state = (local_state_extended_t *)dcontext->local_state;
ibl_branch_type_t branch_type;
ASSERT(state != NULL);
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
LOG(THREAD, LOG_FRAGMENT, 1, "\t Table %s, table " PFX ", mask " PFX "\n",
!SHARED_BB_ONLY_IB_TARGETS() ? ibl_trace_table_type_names[branch_type]
: ibl_bb_table_type_names[branch_type],
state->table_space.table[branch_type].lookuptable,
state->table_space.table[branch_type].hash_mask);
}
}
}
#endif
/*******************************************************************************
* IBL HASHTABLE INSTANTIATION
*/
#define FRAGENTRY_FROM_FRAGMENT(f) \
{ \
(f)->tag, PC_AS_JMP_TGT(FRAG_ISA_MODE(f->flags), (f)->start_pc) \
}
/* macros w/ name and types are duplicated in fragment.h -- keep in sync */
#define NAME_KEY ibl
#define ENTRY_TYPE fragment_entry_t
/* not defining HASHTABLE_USE_LOOKUPTABLE */
/* compiler won't let me use null_fragment.tag here */
static const fragment_entry_t fe_empty = { NULL_TAG, HASHLOOKUP_NULL_START_PC };
static const fragment_entry_t fe_sentinel = { NULL_TAG, HASHLOOKUP_SENTINEL_START_PC };
#define ENTRY_TAG(fe) ((ptr_uint_t)(fe).tag_fragment)
#define ENTRY_EMPTY (fe_empty)
#define ENTRY_SENTINEL (fe_sentinel)
#define IBL_ENTRY_IS_EMPTY(fe) \
((fe).tag_fragment == fe_empty.tag_fragment && \
(fe).start_pc_fragment == fe_empty.start_pc_fragment)
#define IBL_ENTRY_IS_INVALID(fe) ((fe).tag_fragment == FAKE_TAG)
#define IBL_ENTRY_IS_SENTINEL(fe) \
((fe).tag_fragment == fe_sentinel.tag_fragment && \
(fe).start_pc_fragment == fe_sentinel.start_pc_fragment)
#define ENTRY_IS_EMPTY(fe) IBL_ENTRY_IS_EMPTY(fe)
#define ENTRY_IS_SENTINEL(fe) IBL_ENTRY_IS_SENTINEL(fe)
#define ENTRY_IS_INVALID(fe) IBL_ENTRY_IS_INVALID(fe)
#define IBL_ENTRIES_ARE_EQUAL(fe1, fe2) ((fe1).tag_fragment == (fe2).tag_fragment)
#define ENTRIES_ARE_EQUAL(table, fe1, fe2) IBL_ENTRIES_ARE_EQUAL(fe1, fe2)
/* We set start_pc_fragment first to avoid races in a shared table where
* another thread matches the tag but then jumps to a bogus address. */
#define ENTRY_SET_TO_ENTRY(e, f) \
(e).start_pc_fragment = (f).start_pc_fragment; \
/* Ensure the start_pc_fragment store completes before the tag_fragment store: */ \
MEMORY_STORE_BARRIER(); \
(e).tag_fragment = (f).tag_fragment
#define HASHTABLE_WHICH_HEAP(flags) FRAGTABLE_WHICH_HEAP(flags)
#define HTLOCK_RANK table_rwlock
#define HASHTABLE_ENTRY_STATS 1
#include "hashtablex.h"
/* all defines are undef-ed at end of hashtablex.h */
/* required routines for hashtable interface that we don't need for this instance */
static void
hashtable_ibl_free_entry(dcontext_t *dcontext, ibl_table_t *table, fragment_entry_t entry)
{
/* nothing to do, data is inlined */
}
/*******************************************************************************
* FRAGMENT HASHTABLE INSTANTIATION
*/
/* macros w/ name and types are duplicated in fragment.h -- keep in sync */
#define NAME_KEY fragment
#define ENTRY_TYPE fragment_t *
/* not defining HASHTABLE_USE_LOOKUPTABLE */
#define ENTRY_TAG(f) ((ptr_uint_t)(f)->tag)
/* instead of setting to 0, point at null_fragment */
#define ENTRY_EMPTY ((fragment_t *)&null_fragment)
#define ENTRY_SENTINEL ((fragment_t *)&sentinel_fragment)
#define ENTRY_IS_EMPTY(f) ((f) == (fragment_t *)&null_fragment)
#define ENTRY_IS_SENTINEL(f) ((f) == (fragment_t *)&sentinel_fragment)
#define ENTRY_IS_INVALID(f) ((f) == (fragment_t *)&unlinked_fragment)
#define ENTRIES_ARE_EQUAL(t, f, g) ((f) == (g))
#define HASHTABLE_WHICH_HEAP(flags) FRAGTABLE_WHICH_HEAP(flags)
#define HTLOCK_RANK table_rwlock
#include "hashtablex.h"
/* all defines are undef-ed at end of hashtablex.h */
static void
hashtable_fragment_resized_custom(dcontext_t *dcontext, fragment_table_t *table,
uint old_capacity, fragment_t **old_table,
fragment_t **old_table_unaligned, uint old_ref_count,
uint old_table_flags)
{
/* nothing */
}
static void
hashtable_fragment_init_internal_custom(dcontext_t *dcontext, fragment_table_t *table)
{
/* nothing */
}
#ifdef DEBUG
static void
hashtable_fragment_study_custom(dcontext_t *dcontext, fragment_table_t *table,
uint entries_inc /*amnt table->entries was pre-inced*/)
{
/* nothing */
}
#endif
/* callers should use either hashtable_ibl_preinit or hashtable_resize instead */
static void
hashtable_ibl_init_internal_custom(dcontext_t *dcontext, ibl_table_t *table)
{
ASSERT(null_fragment.tag == NULL_TAG);
ASSERT(null_fragment.start_pc == HASHLOOKUP_NULL_START_PC);
ASSERT(FAKE_TAG != NULL_TAG);
ASSERT(sentinel_fragment.tag == NULL_TAG);
ASSERT(sentinel_fragment.start_pc == HASHLOOKUP_SENTINEL_START_PC);
ASSERT(HASHLOOKUP_SENTINEL_START_PC != HASHLOOKUP_NULL_START_PC);
ASSERT(TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags));
ASSERT(TEST(FRAG_TABLE_INCLUSIVE_HIERARCHY, table->table_flags));
/* every time we resize a table we reset the flush threshold,
* since it is cleared in place after one flush
*/
table->groom_factor_percent = TEST(FRAG_TABLE_TRACE, table->table_flags)
? DYNAMO_OPTION(trace_ibt_groom)
: DYNAMO_OPTION(bb_ibt_groom);
table->max_capacity_bits = TEST(FRAG_TABLE_TRACE, table->table_flags)
? DYNAMO_OPTION(private_trace_ibl_targets_max)
: DYNAMO_OPTION(private_bb_ibl_targets_max);
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
if (table->unprot_stats == NULL) {
/* first time, not a resize */
ALLOC_UNPROT_STATS(dcontext, table);
} /* else, keep original */
}
#endif /* HASHTABLE_STATISTICS */
if (SHARED_IB_TARGETS() && !TEST(FRAG_TABLE_SHARED, table->table_flags)) {
/* currently we don't support a mixture */
ASSERT(TEST(FRAG_TABLE_TARGET_SHARED, table->table_flags));
ASSERT(TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags));
ASSERT(table->branch_type != IBL_NONE);
/* Only data for one set of tables is stored in TLS -- for the trace
* tables in the default config OR the BB tables in shared BBs
* only mode.
*/
if ((TEST(FRAG_TABLE_TRACE, table->table_flags) || SHARED_BB_ONLY_IB_TARGETS()) &&
DYNAMO_OPTION(ibl_table_in_tls))
update_lookuptable_tls(dcontext, table);
}
}
/* We need our own routines to init/free our added fields */
static void
hashtable_ibl_myinit(dcontext_t *dcontext, ibl_table_t *table, uint bits,
uint load_factor_percent, hash_function_t func, uint hash_offset,
ibl_branch_type_t branch_type, bool use_lookup,
uint table_flags _IF_DEBUG(const char *table_name))
{
uint flags = table_flags;
ASSERT(dcontext != GLOBAL_DCONTEXT || TEST(FRAG_TABLE_SHARED, flags));
/* flags shared by all ibl tables */
flags |= FRAG_TABLE_INCLUSIVE_HIERARCHY;
flags |= FRAG_TABLE_IBL_TARGETED;
flags |= HASHTABLE_ALIGN_TABLE;
/* use entry stats with all our ibl-targeted tables */
flags |= HASHTABLE_USE_ENTRY_STATS;
#ifdef HASHTABLE_STATISTICS
/* indicate this is first time, not a resize */
table->unprot_stats = NULL;
#endif
table->branch_type = branch_type;
hashtable_ibl_init(dcontext, table, bits, load_factor_percent, func, hash_offset,
flags _IF_DEBUG(table_name));
/* PR 305731: rather than having a start_pc of 0, which causes an
* app targeting 0 to crash at 0, we point at a handler that sends
* the app to an ibl miss via target_delete, which restores
* registers saved in the found path.
*/
if (dcontext != GLOBAL_DCONTEXT && hashlookup_null_target == NULL) {
ASSERT(!dynamo_initialized);
hashlookup_null_target = get_target_delete_entry_pc(dcontext, table);
#if !defined(X64) && defined(LINUX)
/* see comments in x86.asm: we patch to avoid text relocations */
byte *pc = (byte *)hashlookup_null_handler;
byte *page_start = (byte *)PAGE_START(pc);
byte *page_end = (byte *)ALIGN_FORWARD(
pc IF_ARM(+ARM_INSTR_SIZE) + JMP_LONG_LENGTH, PAGE_SIZE);
make_writable(page_start, page_end - page_start);
# ifdef X86
insert_relative_target(pc + 1, hashlookup_null_target, NOT_HOT_PATCHABLE);
# elif defined(ARM)
/* We use a pc-rel load w/ the data right after the load */
/* FIXME i#1551: is our gencode going to switch to Thumb?!? */
*(byte **)(pc + ARM_INSTR_SIZE) = hashlookup_null_target;
# endif
make_unwritable(page_start, page_end - page_start);
#endif
}
}
static void
hashtable_ibl_myfree(dcontext_t *dcontext, ibl_table_t *table)
{
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
ASSERT(TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags));
DEALLOC_UNPROT_STATS(dcontext, table);
}
#endif /* HASHTABLE_STATISTICS */
hashtable_ibl_free(dcontext, table);
}
static void
hashtable_fragment_free_entry(dcontext_t *dcontext, fragment_table_t *table,
fragment_t *f)
{
if (TEST(FRAG_TABLE_INCLUSIVE_HIERARCHY, table->table_flags)) {
ASSERT_NOT_REACHED(); /* case 7691 */
} else {
if (TEST(FRAG_IS_FUTURE, f->flags))
fragment_free_future(dcontext, (future_fragment_t *)f);
else
fragment_free(dcontext, f);
}
}
static inline bool
fragment_add_to_hashtable(dcontext_t *dcontext, fragment_t *e, fragment_table_t *table)
{
/* When using shared IBT tables w/trace building and BB2BB IBL, there is a
* race between adding a BB target to a table and having it marked by
* another thread as a trace head. The race exists because the two functions
* do not use a common lock.
* The race does NOT cause a correctness problem since a) the marking thread
* removes the trace head from the table and b) any subsequent add attempt
* is caught in add_ibl_target(). The table lock is used during add and
* remove operations and FRAG_IS_TRACE_HEAD is checked while holding
* the lock. So although a trace head may be present in a table temporarily --
* it's being marked while an add operation that has passed the frag flags
* check is in progress -- it will be subsequently removed by the marking
* thread.
* However, the existence of the race does mean that
* we cannot ASSERT(!(FRAG_IS_TRACE_HEAD,...)) at arbitrary spots along the
* add_ibl_target() path since such an assert could fire due to the race.
* What is likely a safe point to assert is when there is only a single
* thread in the process.
*/
DOCHECK(1, {
if (TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags) &&
d_r_get_num_threads() == 1)
ASSERT(!TEST(FRAG_IS_TRACE_HEAD, e->flags));
});
return hashtable_fragment_add(dcontext, e, table);
}
/* updates all fragments in a given fragment table which may
* have IBL routine heads inlined in the indirect exit stubs
*
* FIXME: [perf] should add a filter of which branch types need updating if
* updating all is a noticeable performance hit.
*
* FIXME: [perf] Also it maybe better to traverse all fragments in an fcache
* unit instead of entries in a half-empty hashtable
*/
static void
update_indirect_exit_stubs_from_table(dcontext_t *dcontext, fragment_table_t *ftable)
{
fragment_t *f;
linkstub_t *l;
uint i;
for (i = 0; i < ftable->capacity; i++) {
f = ftable->table[i];
if (!REAL_FRAGMENT(f))
continue;
for (l = FRAGMENT_EXIT_STUBS(f); l != NULL; l = LINKSTUB_NEXT_EXIT(l)) {
if (LINKSTUB_INDIRECT(l->flags)) {
/* FIXME: should add a filter of which branch types need updating */
update_indirect_exit_stub(dcontext, f, l);
LOG(THREAD, LOG_FRAGMENT, 5,
"\tIBL target table resizing: updating F%d\n", f->id);
STATS_INC(num_ibl_stub_resize_updates);
}
}
}
}
static void
safely_nullify_tables(dcontext_t *dcontext, ibl_table_t *new_table,
fragment_entry_t *table, uint capacity)
{
uint i;
cache_pc target_delete = get_target_delete_entry_pc(dcontext, new_table);
ASSERT(target_delete != NULL);
ASSERT_TABLE_SYNCHRONIZED(new_table, WRITE);
for (i = 0; i < capacity; i++) {
if (IBL_ENTRY_IS_SENTINEL(table[i])) {
ASSERT(i == capacity - 1);
continue;
}
/* We need these writes to be atomic, so check that they're aligned. */
ASSERT(ALIGNED(&table[i].tag_fragment, sizeof(table[i].tag_fragment)));
ASSERT(ALIGNED(&table[i].start_pc_fragment, sizeof(table[i].start_pc_fragment)));
/* We cannot set the tag to fe_empty.tag_fragment to break the hash chain
* as the target_delete path relies on acquiring the tag from the table entry,
* so we leave it alone.
*/
/* We set the payload to target_delete to induce a cache exit.
*
* The target_delete path leads to a loss of information -- we can't
* tell what the src fragment was (the one that transitioned to the
* IBL code) and this in principle could weaken our RCT checks (see case
* 5085). In practical terms, RCT checks are unaffected since they
* are not employed on in-cache transitions such as an IBL hit.
* (All transitions to target_delete are a race along the hit path.)
* If we still want to preserve the src info, we can leave the payload
* as-is, possibly pointing to a cache address. The effect is that
* any thread accessing the old table on the IBL hit path will not exit
* the cache as early. (We should leave the fragment_t* value in the
* table untouched also so that the fragment_table_t is in a consistent
* state.)
*/
table[i].start_pc_fragment = target_delete;
}
STATS_INC(num_shared_ibt_table_flushes);
}
/* Add an item to the dead tables list */
static inline void
add_to_dead_table_list(dcontext_t *alloc_dc, ibl_table_t *ftable, uint old_capacity,
fragment_entry_t *old_table_unaligned, uint old_ref_count,
uint old_table_flags)
{
dead_fragment_table_t *item = (dead_fragment_table_t *)heap_alloc(
GLOBAL_DCONTEXT, sizeof(dead_fragment_table_t) HEAPACCT(ACCT_IBLTABLE));
LOG(GLOBAL, LOG_FRAGMENT, 2, "add_to_dead_table_list %s " PFX " capacity %d\n",
ftable->name, old_table_unaligned, old_capacity);
ASSERT(old_ref_count >= 1); /* someone other the caller must be holding a reference */
/* write lock must be held so that ref_count is copied accurately */
ASSERT_TABLE_SYNCHRONIZED(ftable, WRITE);
item->capacity = old_capacity;
item->table_unaligned = old_table_unaligned;
item->table_flags = old_table_flags;
item->ref_count = old_ref_count;
item->next = NULL;
/* Add to the end of list. We use a FIFO because generally we'll be
* decrementing ref-counts for older tables before we do so for
* younger tables. A FIFO will yield faster searches than, say, a
* stack.
*/
d_r_mutex_lock(&dead_tables_lock);
if (dead_lists->dead_tables == NULL) {
ASSERT(dead_lists->dead_tables_tail == NULL);
dead_lists->dead_tables = item;
} else {
ASSERT(dead_lists->dead_tables_tail != NULL);
ASSERT(dead_lists->dead_tables_tail->next == NULL);
dead_lists->dead_tables_tail->next = item;
}
dead_lists->dead_tables_tail = item;
d_r_mutex_unlock(&dead_tables_lock);
STATS_ADD_PEAK(num_dead_shared_ibt_tables, 1);
STATS_INC(num_total_dead_shared_ibt_tables);
}
/* forward decl */
static inline void
update_private_ptr_to_shared_ibt_table(dcontext_t *dcontext,
ibl_branch_type_t branch_type, bool trace,
bool adjust_old_ref_count, bool lock_table);
static void
hashtable_ibl_resized_custom(dcontext_t *dcontext, ibl_table_t *table, uint old_capacity,
fragment_entry_t *old_table,
fragment_entry_t *old_table_unaligned, uint old_ref_count,
uint old_table_flags)
{
dcontext_t *alloc_dc = FRAGMENT_TABLE_ALLOC_DC(dcontext, table->table_flags);
per_thread_t *pt = GET_PT(dcontext);
bool shared_ibt_table =
TESTALL(FRAG_TABLE_TARGET_SHARED | FRAG_TABLE_SHARED, table->table_flags);
ASSERT(TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags));
/* If we change an ibl-targeted table, must patch up every
* inlined indirect exit stub that targets it.
* For our per-type ibl tables however we don't bother updating
* fragments _targeted_ by the resized table, instead we need to
* update all fragments that may be a source of an inlined IBL.
*/
/* private inlined IBL heads targeting this table need to be updated */
if (DYNAMO_OPTION(inline_trace_ibl) && PRIVATE_TRACES_ENABLED()) {
/* We'll get here on a trace table resize, while we
* need to patch only when the trace_ibt tables are resized.
*/
/* We assume we don't inline IBL lookup targeting tables of basic blocks
* and so shouldn't need to do this for now. */
ASSERT(dcontext != GLOBAL_DCONTEXT && pt != NULL); /* private traces */
if (TESTALL(FRAG_TABLE_INCLUSIVE_HIERARCHY | FRAG_TABLE_TRACE,
table->table_flags)) {
/* need to update all traces that could be targeting the
* currently resized table */
LOG(THREAD, LOG_FRAGMENT, 2,
"\tIBL target table resizing: updating all private trace fragments\n");
update_indirect_exit_stubs_from_table(dcontext, &pt->trace);
}
}
/* if we change the trace table (or an IBL target trace
* table), must patch up every inlined indirect exit stub
* in all bb fragments in case the inlined target is the
* resized table
*/
if (DYNAMO_OPTION(inline_bb_ibl)) {
LOG(THREAD, LOG_FRAGMENT, 3,
"\tIBL target table resizing: updating bb fragments\n");
update_indirect_exit_stubs_from_table(dcontext, &pt->bb);
}
/* don't need to update any inlined lookups in shared fragments */
if (shared_ibt_table) {
if (old_ref_count > 0) {
/* The old table should be nullified ASAP. Since threads update
* their table pointers on-demand only when they exit the cache
* after a failed IBL lookup, they could have IBL targets for
* stale entries. This would likely occur only when there's an
* app race but in the future could occur due to cache
* management.
*/
safely_nullify_tables(dcontext, table, old_table, old_capacity);
add_to_dead_table_list(alloc_dc, table, old_capacity, old_table_unaligned,
old_ref_count, table->table_flags);
}
/* Update the resizing thread's private ptr. */
update_private_ptr_to_shared_ibt_table(dcontext, table->branch_type,
TEST(FRAG_TABLE_TRACE, table->table_flags),
false, /* no adjust
* old ref-count */
false /* already hold lock */);
ASSERT(table->ref_count == 1);
}
/* CHECK: is it safe to update the table without holding the lock? */
/* Using the table flags to drive the update of generated code may
* err on the side of caution, but it's the best way to guarantee
* that all of the necessary code is updated.
* We may perform extra unnecessary updates when a table that's
* accessed off of the dcontext/per_thread_t is grown, but that doesn't
* cause correctness problems and likely doesn't hurt peformance.
*/
STATS_INC(num_ibt_table_resizes);
update_generated_hashtable_access(dcontext);
}
#ifdef DEBUG
static void
hashtable_ibl_study_custom(dcontext_t *dcontext, ibl_table_t *table,
uint entries_inc /*amnt table->entries was pre-inced*/)
{
# ifdef HASHTABLE_STATISTICS
/* For trace table(s) only, use stats from emitted ibl routines */
if (TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags) &&
INTERNAL_OPTION(hashtable_ibl_stats)) {
per_thread_t *pt = GET_PT(dcontext);
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
/* This is convoluted since given a table we have to
* recover its branch type.
* FIXME: should simplify these assumptions one day
*/
/* Current table should be targeted only by one of the IBL routines */
if (!((!DYNAMO_OPTION(disable_traces) &&
table == &pt->trace_ibt[branch_type]) ||
(DYNAMO_OPTION(bb_ibl_targets) && table == &pt->bb_ibt[branch_type])))
continue;
/* stats for lookup routines from bb's & trace's targeting current table */
print_hashtable_stats(dcontext, entries_inc == 0 ? "Total" : "Current",
table->name, "trace ibl ",
get_branch_type_name(branch_type),
&table->UNPROT_STAT(trace_ibl_stats[branch_type]));
print_hashtable_stats(dcontext, entries_inc == 0 ? "Total" : "Current",
table->name, "bb ibl ",
get_branch_type_name(branch_type),
&table->UNPROT_STAT(bb_ibl_stats[branch_type]));
}
}
# endif /* HASHTABLE_STATISTICS */
}
#endif /* DEBUG */
#if defined(DEBUG) || defined(CLIENT_INTERFACE)
/* filter specifies flags for fragments which are OK to be freed */
/* NOTE - if this routine is ever used for non DEBUG purposes be aware that
* because of case 7697 we don't unlink when we free the hashtable elements.
* As such, if we aren't also freeing all fragments that could possibly link
* to fragments in this table at the same time (synchronously) we'll have
* problems (for ex. a trace only reset would need to unlink incoming, or
* allowing private->shared linking would need to ulink outgoing).
*/
static void
hashtable_fragment_reset(dcontext_t *dcontext, fragment_table_t *table)
{
int i;
fragment_t *f;
/* case 7691: we now use separate ibl table types */
ASSERT(!TEST(FRAG_TABLE_INCLUSIVE_HIERARCHY, table->table_flags));
LOG(THREAD, LOG_FRAGMENT, 2, "hashtable_fragment_reset\n");
DOLOG(1, LOG_FRAGMENT | LOG_STATS,
{ hashtable_fragment_load_statistics(dcontext, table); });
if (TEST(FRAG_TABLE_SHARED, table->table_flags) &&
TEST(FRAG_TABLE_IBL_TARGETED, table->table_flags)) {
DOLOG(5, LOG_FRAGMENT, { hashtable_fragment_dump_table(dcontext, table); });
}
DODEBUG({
hashtable_fragment_study(dcontext, table, 0 /*table consistent*/);
/* ensure write lock is held if the table is shared, unless exiting
* or resetting (N.B.: if change reset model to not suspend all in-DR
* threads, will have to change this and handle rank order issues)
*/
if (!dynamo_exited && !dynamo_resetting)
ASSERT_TABLE_SYNCHRONIZED(table, WRITE);
});
# if !defined(DEBUG) && defined(CLIENT_INTERFACE)
if (!dr_fragment_deleted_hook_exists())
return;
/* i#4226: Avoid the slow deletion code and just invoke the event. */
for (i = 0; i < (int)table->capacity; i++) {
f = table->table[i];
if (!REAL_FRAGMENT(f))
continue;
/* This is a full delete (i.e., it is neither FRAGDEL_NO_HEAP nor
* FRAGDEL_NO_FCACHE: see the fragment_delete() call in the debug path
* below) so we call the event for every (real) fragment.
*/
instrument_fragment_deleted(dcontext, f->tag, f->flags);
}
return;
# endif
/* Go in reverse order (for efficiency) since using
* hashtable_fragment_remove_helper to keep all reachable, which is required
* for dynamo_resetting where we unlink fragments here and need to be able to
* perform lookups.
*/
i = table->capacity - 1 - 1 /* sentinel */;
while (i >= 0) {
f = table->table[i];
if (f == &null_fragment) {
i--;
} else { /* i stays put */
/* The shared BB table is reset at process reset or shutdown, so
* trace_abort() has already been called by (or for) every thread.
* If shared traces is true, by this point none of the shared BBs
* should have FRAG_TRACE_BUILDING set since the flag is cleared
* by trace_abort(). Of course, the flag shouldn't be present
* if shared traces is false so we don't need to conditionalize
* the assert.
*/
ASSERT(!TEST(FRAG_TRACE_BUILDING, f->flags));
hashtable_fragment_remove_helper(table, i, &table->table[i]);
if (!REAL_FRAGMENT(f))
continue;
/* make sure no other hashtable has shared fragments in it
* this routine is called on shared table, but only after dynamo_exited
* the per-thread IBL tables contain pointers to shared fragments
* and are OK
*/
ASSERT(dynamo_exited || !TEST(FRAG_SHARED, f->flags) || dynamo_resetting);
if (TEST(FRAG_IS_FUTURE, f->flags)) {
DODEBUG({ ((future_fragment_t *)f)->incoming_stubs = NULL; });
fragment_free_future(dcontext, (future_fragment_t *)f);
} else {
DOSTATS({
if (dynamo_resetting)
STATS_INC(num_fragments_deleted_reset);
else
STATS_INC(num_fragments_deleted_exit);
});
/* Xref 7697 - unlinking the fragments here can screw up the
* future table as we are walking in hash order, so we don't
* unlink. See note at top of routine for issues with not
* unlinking here if this code is ever used in non debug
* builds. */
fragment_delete(dcontext, f,
FRAGDEL_NO_HTABLE | FRAGDEL_NO_UNLINK |
FRAGDEL_NEED_CHLINK_LOCK |
(dynamo_resetting ? 0 : FRAGDEL_NO_OUTPUT));
}
}
}
table->entries = 0;
table->unlinked_entries = 0;
}
#endif /* DEBUG || CLIENT_INTERFACE */
/*
*******************************************************************************/
#if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH)
/*******************************************************************************
* APP_PC HASHTABLE INSTANTIATION
*/
/* FIXME: RCT tables no longer use future_fragment_t and can be moved out of
* fragment.c */
/* The ENTRY_* defines are undef-ed at end of hashtablex.h so we make our own.
* Would be nice to re-use ENTRY_IS_EMPTY, etc., though w/ multiple htables
* in same file can't realistically get away w/o custom defines like these:
*/
# define APP_PC_EMPTY (NULL)
/* assume 1 is always invalid address */
# define APP_PC_SENTINEL ((app_pc)PTR_UINT_1)
# define APP_PC_ENTRY_IS_EMPTY(pc) ((pc) == APP_PC_EMPTY)
# define APP_PC_ENTRY_IS_SENTINEL(pc) ((pc) == APP_PC_SENTINEL)
# define APP_PC_ENTRY_IS_REAL(pc) \
(!APP_PC_ENTRY_IS_EMPTY(pc) && !APP_PC_ENTRY_IS_SENTINEL(pc))
/* 2 macros w/ name and types are duplicated in fragment.h -- keep in sync */
# define NAME_KEY app_pc
# define ENTRY_TYPE app_pc
/* not defining HASHTABLE_USE_LOOKUPTABLE */
# define ENTRY_TAG(f) ((ptr_uint_t)(f))
# define ENTRY_EMPTY APP_PC_EMPTY
# define ENTRY_SENTINEL APP_PC_SENTINEL
# define ENTRY_IS_EMPTY(f) APP_PC_ENTRY_IS_EMPTY(f)
# define ENTRY_IS_SENTINEL(f) APP_PC_ENTRY_IS_SENTINEL(f)
# define ENTRY_IS_INVALID(f) (false) /* no invalid entries */
# define ENTRIES_ARE_EQUAL(t, f, g) ((f) == (g))
# define HASHTABLE_WHICH_HEAP(flags) (ACCT_AFTER_CALL)
# define HTLOCK_RANK app_pc_table_rwlock
# define HASHTABLE_SUPPORT_PERSISTENCE 1
# include "hashtablex.h"
/* all defines are undef-ed at end of hashtablex.h */
/* required routines for hashtable interface that we don't need for this instance */
static void
hashtable_app_pc_init_internal_custom(dcontext_t *dcontext, app_pc_table_t *htable)
{ /* nothing */
}
static void
hashtable_app_pc_resized_custom(dcontext_t *dcontext, app_pc_table_t *htable,
uint old_capacity, app_pc *old_table,
app_pc *old_table_unaligned, uint old_ref_count,
uint old_table_flags)
{ /* nothing */
}
# ifdef DEBUG
static void
hashtable_app_pc_study_custom(dcontext_t *dcontext, app_pc_table_t *htable,
uint entries_inc /*amnt table->entries was pre-inced*/)
{ /* nothing */
}
# endif
static void
hashtable_app_pc_free_entry(dcontext_t *dcontext, app_pc_table_t *htable, app_pc entry)
{
/* nothing to do, data is inlined */
}
#endif /* defined(RETURN_AFTER_CALL) || defined (RCT_IND_BRANCH) */
/*******************************************************************************/
bool
fragment_initialized(dcontext_t *dcontext)
{
return (dcontext != GLOBAL_DCONTEXT && dcontext->fragment_field != NULL);
}
/* thread-shared initialization that should be repeated after a reset */
void
fragment_reset_init(void)
{
/* case 7966: don't initialize at all for hotp_only & thin_client */
if (RUNNING_WITHOUT_CODE_CACHE())
return;
d_r_mutex_lock(&shared_cache_flush_lock);
/* ASSUMPTION: a reset frees all deletions that use flushtimes, so we can
* reset the global flushtime here
*/
flushtime_global = 0;
d_r_mutex_unlock(&shared_cache_flush_lock);
if (SHARED_FRAGMENTS_ENABLED()) {
if (DYNAMO_OPTION(shared_bbs)) {
hashtable_fragment_init(
GLOBAL_DCONTEXT, shared_bb, INIT_HTABLE_SIZE_SHARED_BB,
INTERNAL_OPTION(shared_bb_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
FRAG_TABLE_SHARED | FRAG_TABLE_TARGET_SHARED _IF_DEBUG("shared_bb"));
}
if (DYNAMO_OPTION(shared_traces)) {
hashtable_fragment_init(
GLOBAL_DCONTEXT, shared_trace, INIT_HTABLE_SIZE_SHARED_TRACE,
INTERNAL_OPTION(shared_trace_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
FRAG_TABLE_SHARED | FRAG_TABLE_TARGET_SHARED _IF_DEBUG("shared_trace"));
}
/* init routine will work for future_fragment_t* same as for fragment_t* */
hashtable_fragment_init(
GLOBAL_DCONTEXT, shared_future, INIT_HTABLE_SIZE_SHARED_FUTURE,
INTERNAL_OPTION(shared_future_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
FRAG_TABLE_SHARED | FRAG_TABLE_TARGET_SHARED _IF_DEBUG("shared_future"));
}
if (SHARED_IBT_TABLES_ENABLED()) {
ibl_branch_type_t branch_type;
ASSERT(USE_SHARED_PT());
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (DYNAMO_OPTION(shared_trace_ibt_tables)) {
hashtable_ibl_myinit(GLOBAL_DCONTEXT, &shared_pt->trace_ibt[branch_type],
DYNAMO_OPTION(shared_ibt_table_trace_init),
DYNAMO_OPTION(shared_ibt_table_trace_load),
HASH_FUNCTION_NONE,
HASHTABLE_IBL_OFFSET(branch_type), branch_type,
false, /* no lookup table */
FRAG_TABLE_SHARED | FRAG_TABLE_TARGET_SHARED |
FRAG_TABLE_TRACE _IF_DEBUG(
ibl_trace_table_type_names[branch_type]));
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
CHECK_UNPROT_STATS(&shared_pt->trace_ibt[branch_type]);
/* for compatibility using an entry in the per-branch type stats */
INIT_HASHTABLE_STATS(shared_pt->trace_ibt[branch_type].UNPROT_STAT(
trace_ibl_stats[branch_type]));
} else {
shared_pt->trace_ibt[branch_type].unprot_stats = NULL;
}
#endif /* HASHTABLE_STATISTICS */
}
if (DYNAMO_OPTION(shared_bb_ibt_tables)) {
hashtable_ibl_myinit(GLOBAL_DCONTEXT, &shared_pt->bb_ibt[branch_type],
DYNAMO_OPTION(shared_ibt_table_bb_init),
DYNAMO_OPTION(shared_ibt_table_bb_load),
HASH_FUNCTION_NONE,
HASHTABLE_IBL_OFFSET(branch_type), branch_type,
false, /* no lookup table */
FRAG_TABLE_SHARED |
FRAG_TABLE_TARGET_SHARED _IF_DEBUG(
ibl_bb_table_type_names[branch_type]));
/* mark as inclusive table for bb's - we in fact currently
* keep only frags that are not FRAG_IS_TRACE_HEAD */
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
/* for compatibility using an entry in the per-branch type stats */
CHECK_UNPROT_STATS(&shared_pt->bb_ibt[branch_type]);
/* FIXME: we don't expect trace_ibl_stats yet */
INIT_HASHTABLE_STATS(shared_pt->bb_ibt[branch_type].UNPROT_STAT(
bb_ibl_stats[branch_type]));
} else {
shared_pt->bb_ibt[branch_type].unprot_stats = NULL;
}
#endif /* HASHTABLE_STATISTICS */
}
}
}
#ifdef SHARING_STUDY
if (INTERNAL_OPTION(fragment_sharing_study)) {
uint size = HASHTABLE_SIZE(SHARED_HASH_BITS) * sizeof(shared_entry_t *);
shared_blocks = (shared_entry_t **)global_heap_alloc(size HEAPACCT(ACCT_OTHER));
memset(shared_blocks, 0, size);
shared_traces = (shared_entry_t **)global_heap_alloc(size HEAPACCT(ACCT_OTHER));
memset(shared_traces, 0, size);
}
#endif
}
/* thread-shared initialization */
void
fragment_init()
{
/* case 7966: don't initialize at all for hotp_only & thin_client
* FIXME: could set initial sizes to 0 for all configurations, instead
*/
if (RUNNING_WITHOUT_CODE_CACHE())
return;
/* make sure fields are at same place */
ASSERT(offsetof(fragment_t, flags) == offsetof(future_fragment_t, flags));
ASSERT(offsetof(fragment_t, tag) == offsetof(future_fragment_t, tag));
/* ensure we can read this w/o a lock: no cache line crossing, please */
ASSERT(ALIGNED(&flushtime_global, 4));
if (SHARED_FRAGMENTS_ENABLED()) {
/* tables are persistent across resets, only on heap for selfprot (case 7957) */
if (DYNAMO_OPTION(shared_bbs)) {
shared_bb = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, fragment_table_t,
ACCT_FRAG_TABLE, PROTECTED);
}
if (DYNAMO_OPTION(shared_traces)) {
shared_trace = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, fragment_table_t,
ACCT_FRAG_TABLE, PROTECTED);
}
shared_future = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, fragment_table_t,
ACCT_FRAG_TABLE, PROTECTED);
}
if (USE_SHARED_PT())
shared_pt = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, per_thread_t, ACCT_OTHER, PROTECTED);
if (SHARED_IBT_TABLES_ENABLED()) {
dead_lists =
HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, dead_table_lists_t, ACCT_OTHER, PROTECTED);
memset(dead_lists, 0, sizeof(*dead_lists));
}
fragment_reset_init();
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
if (TRACEDUMP_ENABLED() && DYNAMO_OPTION(shared_traces)) {
ASSERT(USE_SHARED_PT());
shared_pt->tracefile = open_log_file("traces-shared", NULL, 0);
ASSERT(shared_pt->tracefile != INVALID_FILE);
init_trace_file(shared_pt);
}
#endif
}
/* Free all thread-shared state not critical to forward progress;
* fragment_reset_init() will be called before continuing.
*/
void
fragment_reset_free(void)
{
/* case 7966: don't initialize at all for hotp_only & thin_client */
if (RUNNING_WITHOUT_CODE_CACHE())
return;
/* We must study the ibl tables before the trace/bb tables so that we're
* not looking at freed entries
*/
if (SHARED_IBT_TABLES_ENABLED()) {
ibl_branch_type_t branch_type;
dead_fragment_table_t *current, *next;
DEBUG_DECLARE(int table_count = 0;)
DEBUG_DECLARE(stats_int_t dead_tables = GLOBAL_STAT(num_dead_shared_ibt_tables);)
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (DYNAMO_OPTION(shared_trace_ibt_tables)) {
DOLOG(1, LOG_FRAGMENT | LOG_STATS, {
hashtable_ibl_load_statistics(GLOBAL_DCONTEXT,
&shared_pt->trace_ibt[branch_type]);
});
hashtable_ibl_myfree(GLOBAL_DCONTEXT, &shared_pt->trace_ibt[branch_type]);
}
if (DYNAMO_OPTION(shared_bb_ibt_tables)) {
DOLOG(1, LOG_FRAGMENT | LOG_STATS, {
hashtable_ibl_load_statistics(GLOBAL_DCONTEXT,
&shared_pt->bb_ibt[branch_type]);
});
hashtable_ibl_myfree(GLOBAL_DCONTEXT, &shared_pt->bb_ibt[branch_type]);
}
}
/* Delete dead tables. */
/* grab lock for consistency, although we expect a single thread */
d_r_mutex_lock(&dead_tables_lock);
current = dead_lists->dead_tables;
while (current != NULL) {
DODEBUG({ table_count++; });
next = current->next;
LOG(GLOBAL, LOG_FRAGMENT, 2,
"fragment_reset_free: dead table " PFX " cap %d, freeing\n",
current->table_unaligned, current->capacity);
hashtable_ibl_free_table(GLOBAL_DCONTEXT, current->table_unaligned,
current->table_flags, current->capacity);
heap_free(GLOBAL_DCONTEXT, current,
sizeof(dead_fragment_table_t) HEAPACCT(ACCT_IBLTABLE));
STATS_DEC(num_dead_shared_ibt_tables);
STATS_INC(num_dead_shared_ibt_tables_freed);
current = next;
DODEBUG({
if (dynamo_exited)
STATS_INC(num_dead_shared_ibt_tables_freed_at_exit);
});
}
dead_lists->dead_tables = dead_lists->dead_tables_tail = NULL;
ASSERT(table_count == dead_tables);
d_r_mutex_unlock(&dead_tables_lock);
}
/* FIXME: Take in a flag "permanent" that controls whether exiting or
* resetting. If resetting only, do not free unprot stats and entry stats
* (they're already in persistent heap, but we explicitly free them).
* This will be easy w/ unprot but will take work for entry stats
* since they resize themselves.
* Or, move them both to a new unprot and nonpersistent heap so we can
* actually free the memory back to the os, if we don't care to keep
* the stats across the reset.
*/
/* N.B.: to avoid rank order issues w/ shared_vm_areas lock being acquired
* after table_rwlock we do NOT grab the write lock before calling
* reset on the shared tables! We assume that reset involves suspending
* all other threads in DR and there will be no races. If the reset model
* changes, the lock order will have to be addressed.
*/
if (SHARED_FRAGMENTS_ENABLED()) {
/* clean up pending delayed deletion, if any */
vm_area_check_shared_pending(GLOBAL_DCONTEXT /*== safe to free all*/, NULL);
if (DYNAMO_OPTION(coarse_units)) {
/* We need to free coarse units earlier than vm_areas_exit() so we
* call it here. Must call before we free fine fragments so coarse
* can clean up incoming pointers.
*/
vm_area_coarse_units_reset_free();
}
#if defined(DEBUG) || defined(CLIENT_INTERFACE)
/* We need for CLIENT_INTERFACE to get fragment deleted events. */
# if !defined(DEBUG) && defined(CLIENT_INTERFACE)
if (dr_fragment_deleted_hook_exists()) {
# endif
if (DYNAMO_OPTION(shared_bbs))
hashtable_fragment_reset(GLOBAL_DCONTEXT, shared_bb);
if (DYNAMO_OPTION(shared_traces))
hashtable_fragment_reset(GLOBAL_DCONTEXT, shared_trace);
DODEBUG({ hashtable_fragment_reset(GLOBAL_DCONTEXT, shared_future); });
# if !defined(DEBUG) && defined(CLIENT_INTERFACE)
}
# endif
#endif
if (DYNAMO_OPTION(shared_bbs))
hashtable_fragment_free(GLOBAL_DCONTEXT, shared_bb);
if (DYNAMO_OPTION(shared_traces))
hashtable_fragment_free(GLOBAL_DCONTEXT, shared_trace);
hashtable_fragment_free(GLOBAL_DCONTEXT, shared_future);
/* Do NOT free RAC table as its state cannot be rebuilt.
* We also do not free other RCT tables to avoid the time to rebuild them.
*/
}
#ifdef SHARING_STUDY
if (INTERNAL_OPTION(fragment_sharing_study)) {
print_shared_stats();
reset_shared_block_table(shared_blocks, &shared_blocks_lock);
reset_shared_block_table(shared_traces, &shared_traces_lock);
}
#endif
}
/* free all state */
void
fragment_exit()
{
/* case 7966: don't initialize at all for hotp_only & thin_client
* FIXME: could set initial sizes to 0 for all configurations, instead
*/
if (RUNNING_WITHOUT_CODE_CACHE())
goto cleanup;
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
if (TRACEDUMP_ENABLED() && DYNAMO_OPTION(shared_traces)) {
/* write out all traces prior to deleting any, so links print nicely */
uint i;
fragment_t *f;
/* change_linking_lock is required for output_trace(), though there
* won't be any races at this point of exiting.
*/
acquire_recursive_lock(&change_linking_lock);
TABLE_RWLOCK(shared_trace, read, lock);
for (i = 0; i < shared_trace->capacity; i++) {
f = shared_trace->table[i];
if (!REAL_FRAGMENT(f))
continue;
if (SHOULD_OUTPUT_FRAGMENT(f->flags))
output_trace(GLOBAL_DCONTEXT, shared_pt, f, -1);
}
TABLE_RWLOCK(shared_trace, read, unlock);
release_recursive_lock(&change_linking_lock);
exit_trace_file(shared_pt);
}
#endif
#ifdef FRAGMENT_SIZES_STUDY
DOLOG(1, (LOG_FRAGMENT | LOG_STATS), { print_size_results(); });
#endif
fragment_reset_free();
#ifdef RETURN_AFTER_CALL
if (dynamo_options.ret_after_call && rac_non_module_table.live_table != NULL) {
DODEBUG({
DOLOG(1, LOG_FRAGMENT | LOG_STATS, {
hashtable_app_pc_load_statistics(GLOBAL_DCONTEXT,
rac_non_module_table.live_table);
});
hashtable_app_pc_study(GLOBAL_DCONTEXT, rac_non_module_table.live_table,
0 /*table consistent*/);
});
hashtable_app_pc_free(GLOBAL_DCONTEXT, rac_non_module_table.live_table);
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, rac_non_module_table.live_table, app_pc_table_t,
ACCT_AFTER_CALL, PROTECTED);
rac_non_module_table.live_table = NULL;
}
ASSERT(rac_non_module_table.persisted_table == NULL);
DELETE_LOCK(after_call_lock);
#endif
#if defined(RCT_IND_BRANCH) && defined(UNIX)
/* we do not free these tables in fragment_reset_free() b/c we
* would just have to build them all back up again in order to
* continue execution
*/
if ((TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_call)) ||
TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_jump))) &&
rct_global_table.live_table != NULL) {
DODEBUG({
DOLOG(1, LOG_FRAGMENT | LOG_STATS, {
hashtable_app_pc_load_statistics(GLOBAL_DCONTEXT,
rct_global_table.live_table);
});
hashtable_app_pc_study(GLOBAL_DCONTEXT, rct_global_table.live_table,
0 /*table consistent*/);
});
hashtable_app_pc_free(GLOBAL_DCONTEXT, rct_global_table.live_table);
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, rct_global_table.live_table, app_pc_table_t,
ACCT_AFTER_CALL, PROTECTED);
rct_global_table.live_table = NULL;
} else
ASSERT(rct_global_table.live_table == NULL);
ASSERT(rct_global_table.persisted_table == NULL);
#endif /* RCT_IND_BRANCH */
if (SHARED_FRAGMENTS_ENABLED()) {
/* tables are persistent across resets, only on heap for selfprot (case 7957) */
if (DYNAMO_OPTION(shared_bbs)) {
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, shared_bb, fragment_table_t, ACCT_FRAG_TABLE,
PROTECTED);
shared_bb = NULL;
} else
ASSERT(shared_bb == NULL);
if (DYNAMO_OPTION(shared_traces)) {
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, shared_trace, fragment_table_t,
ACCT_FRAG_TABLE, PROTECTED);
shared_trace = NULL;
} else
ASSERT(shared_trace == NULL);
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, shared_future, fragment_table_t, ACCT_FRAG_TABLE,
PROTECTED);
shared_future = NULL;
}
if (SHARED_IBT_TABLES_ENABLED()) {
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, dead_lists, dead_table_lists_t, ACCT_OTHER,
PROTECTED);
dead_lists = NULL;
} else
ASSERT(dead_lists == NULL);
if (USE_SHARED_PT()) {
ASSERT(shared_pt != NULL);
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, shared_pt, per_thread_t, ACCT_OTHER, PROTECTED);
shared_pt = NULL;
} else
ASSERT(shared_pt == NULL);
if (SHARED_IBT_TABLES_ENABLED())
DELETE_LOCK(dead_tables_lock);
#ifdef SHARING_STUDY
if (INTERNAL_OPTION(fragment_sharing_study)) {
DELETE_LOCK(shared_blocks_lock);
DELETE_LOCK(shared_traces_lock);
}
#endif
cleanup:
/* FIXME: we shouldn't need these locks anyway for hotp_only & thin_client */
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
DELETE_LOCK(tracedump_mutex);
#endif
#ifdef CLIENT_INTERFACE
process_client_flush_requests(NULL, GLOBAL_DCONTEXT, client_flush_requests,
false /* no flush */);
DELETE_LOCK(client_flush_request_lock);
#endif
/* avoid compile error "error: label at end of compound statement"
* from vps-release-external build
*/
return;
}
void
fragment_exit_post_sideline(void)
{
DELETE_LOCK(shared_cache_flush_lock);
}
/* Decrement the ref-count for any reference to table that the
* per_thread_t contains. If could_be_live is true, will acquire write
* locks for the currently live tables. */
/* NOTE: Can't inline in release build -- too many call sites? */
static /* inline */ void
dec_table_ref_count(dcontext_t *dcontext, ibl_table_t *table, bool could_be_live)
{
ibl_table_t *live_table = NULL;
ibl_branch_type_t branch_type;
/* Search live tables. A live table's ref-count is decremented
* during a thread exit. */
/* FIXME If the table is more likely to be dead, we can reverse the order
* and search dead tables first. */
if (!DYNAMO_OPTION(ref_count_shared_ibt_tables))
return;
ASSERT(TESTALL(FRAG_TABLE_SHARED | FRAG_TABLE_IBL_TARGETED, table->table_flags));
if (could_be_live) {
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
/* We match based on lookup table addresses. We need to lock the table
* during the compare and hold the lock during the ref-count dec to
* prevent a race with it being moved to the dead list.
*/
ibl_table_t *sh_table_ptr = TEST(FRAG_TABLE_TRACE, table->table_flags)
? &shared_pt->trace_ibt[branch_type]
: &shared_pt->bb_ibt[branch_type];
TABLE_RWLOCK(sh_table_ptr, write, lock);
if (table->table == sh_table_ptr->table) {
live_table = sh_table_ptr;
break;
}
TABLE_RWLOCK(sh_table_ptr, write, unlock);
}
}
if (live_table != NULL) {
/* During shutdown, the ref-count can reach 0. The table is freed
* in the fragment_exit() path. */
ASSERT(live_table->ref_count >= 1);
live_table->ref_count--;
TABLE_RWLOCK(live_table, write, unlock);
} else { /* Search the dead tables list. */
dead_fragment_table_t *current = dead_lists->dead_tables;
dead_fragment_table_t *prev = NULL;
ASSERT(dead_lists->dead_tables != NULL);
ASSERT(dead_lists->dead_tables_tail != NULL);
/* We expect to be removing from the head of the list but due to
* races could be removing from the middle, i.e., if a preceding
* entry is about to be removed by another thread but the
* dead_tables_lock hasn't been acquired yet by that thread.
*/
d_r_mutex_lock(&dead_tables_lock);
for (current = dead_lists->dead_tables; current != NULL;
prev = current, current = current->next) {
if (current->table_unaligned == table->table_unaligned) {
ASSERT_CURIOSITY(current->ref_count >= 1);
current->ref_count--;
if (current->ref_count == 0) {
LOG(GLOBAL, LOG_FRAGMENT, 2,
"dec_table_ref_count: table " PFX " cap %d at ref 0, freeing\n",
current->table_unaligned, current->capacity);
/* Unlink this table from the list. */
if (prev != NULL)
prev->next = current->next;
if (current == dead_lists->dead_tables) {
/* remove from the front */
ASSERT(prev == NULL);
dead_lists->dead_tables = current->next;
}
if (current == dead_lists->dead_tables_tail)
dead_lists->dead_tables_tail = prev;
hashtable_ibl_free_table(GLOBAL_DCONTEXT, current->table_unaligned,
current->table_flags, current->capacity);
heap_free(GLOBAL_DCONTEXT, current,
sizeof(dead_fragment_table_t) HEAPACCT(ACCT_IBLTABLE));
STATS_DEC(num_dead_shared_ibt_tables);
STATS_INC(num_dead_shared_ibt_tables_freed);
}
break;
}
}
d_r_mutex_unlock(&dead_tables_lock);
ASSERT(current != NULL);
}
}
/* Decrement the ref-count for every shared IBT table that the
* per_thread_t has a reference to. */
static void
dec_all_table_ref_counts(dcontext_t *dcontext, per_thread_t *pt)
{
/* We can also decrement ref-count for dead shared tables here. */
if (SHARED_IBT_TABLES_ENABLED()) {
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (DYNAMO_OPTION(shared_trace_ibt_tables)) {
ASSERT(pt->trace_ibt[branch_type].table != NULL);
dec_table_ref_count(dcontext, &pt->trace_ibt[branch_type],
true /*check live*/);
}
if (DYNAMO_OPTION(shared_bb_ibt_tables)) {
ASSERT(pt->bb_ibt[branch_type].table != NULL);
dec_table_ref_count(dcontext, &pt->bb_ibt[branch_type],
true /*check live*/);
}
}
}
}
/* re-initializes non-persistent memory */
void
fragment_thread_reset_init(dcontext_t *dcontext)
{
per_thread_t *pt;
ibl_branch_type_t branch_type;
/* case 7966: don't initialize at all for hotp_only & thin_client */
if (RUNNING_WITHOUT_CODE_CACHE())
return;
pt = (per_thread_t *)dcontext->fragment_field;
/* important to init w/ cur timestamp to avoid this thread dec-ing ref
* count when it wasn't included in ref count init value!
* assumption: don't need lock to read flushtime_global atomically.
* when resetting, though, thread free & re-init is done before global free,
* so we have to explicitly set to 0 for that case.
*/
pt->flushtime_last_update = (dynamo_resetting) ? 0 : flushtime_global;
/* set initial hashtable sizes */
hashtable_fragment_init(
dcontext, &pt->bb, INIT_HTABLE_SIZE_BB, INTERNAL_OPTION(private_bb_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0, 0 _IF_DEBUG("bblock"));
/* init routine will work for future_fragment_t* same as for fragment_t* */
hashtable_fragment_init(dcontext, &pt->future, INIT_HTABLE_SIZE_FUTURE,
INTERNAL_OPTION(private_future_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func),
0 /* hash_mask_offset */, 0 _IF_DEBUG("future"));
/* The trace table now is not used by IBL routines, and
* therefore doesn't need a lookup table, we can also use the
* alternative hash functions and use a higher load.
*/
if (PRIVATE_TRACES_ENABLED()) {
hashtable_fragment_init(dcontext, &pt->trace, INIT_HTABLE_SIZE_TRACE,
INTERNAL_OPTION(private_trace_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func),
0 /* hash_mask_offset */,
FRAG_TABLE_TRACE _IF_DEBUG("trace"));
}
/* We'll now have more control over hashtables based on branch
* type. The most important of all is of course the return
* target table. These tables should be populated only when
* we know that the entry is a valid target, a trace is
* created, and it is indeed targeted by an IBL.
*/
/* These tables are targeted by both bb and trace routines */
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (!DYNAMO_OPTION(disable_traces)
/* If no traces and no bb ibl targets we point ibl at
* an empty trace table */
|| !DYNAMO_OPTION(bb_ibl_targets)) {
if (!DYNAMO_OPTION(shared_trace_ibt_tables)) {
hashtable_ibl_myinit(
dcontext, &pt->trace_ibt[branch_type],
DYNAMO_OPTION(private_trace_ibl_targets_init),
DYNAMO_OPTION(private_ibl_targets_load), HASH_FUNCTION_NONE,
HASHTABLE_IBL_OFFSET(branch_type), branch_type,
false, /* no lookup table */
(DYNAMO_OPTION(shared_traces) ? FRAG_TABLE_TARGET_SHARED : 0) |
FRAG_TABLE_TRACE _IF_DEBUG(
ibl_trace_table_type_names[branch_type]));
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
CHECK_UNPROT_STATS(pt->trace_ibt[branch_type]);
/* for compatibility using an entry in the per-branch type stats */
INIT_HASHTABLE_STATS(pt->trace_ibt[branch_type].UNPROT_STAT(
trace_ibl_stats[branch_type]));
} else {
pt->trace_ibt[branch_type].unprot_stats = NULL;
}
#endif /* HASHTABLE_STATISTICS */
} else {
/* ensure table from last time (if we had a reset) not still there */
memset(&pt->trace_ibt[branch_type], 0,
sizeof(pt->trace_ibt[branch_type]));
update_private_ptr_to_shared_ibt_table(dcontext, branch_type,
true, /* trace = yes */
false, /* no adjust old
* ref-count */
true /* lock */);
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
ALLOC_UNPROT_STATS(dcontext, &pt->trace_ibt[branch_type]);
CHECK_UNPROT_STATS(pt->trace_ibt[branch_type]);
INIT_HASHTABLE_STATS(pt->trace_ibt[branch_type].UNPROT_STAT(
trace_ibl_stats[branch_type]));
} else {
pt->trace_ibt[branch_type].unprot_stats = NULL;
}
#endif
}
}
/* When targetting BBs, currently the source is assumed to be only a
* bb since traces going to a bb for the first time should mark it
* as a trace head. Therefore the tables are currently only
* targeted by bb IBL routines. It will be possible to later
* deal with trace heads and allow a trace to target a BB with
* the intent of modifying its THCI.
*
* (FIXME: having another table for THCI IBLs seems better than
* adding a counter (starting at -1) to all blocks and
* trapping when 0 for marking a trace head and again at 50
* for creating a trace. And that is all of course after proving
* that doing it in DR has significant impact.)
*
* Note that private bb2bb transitions are not captured when
* we run with -shared_bbs.
*/
/* These tables should be populated only when we know that the
* entry is a valid target, and it is indeed targeted by an
* IBL. They have to be per-type so that our security
* policies are properly checked.
*/
if (DYNAMO_OPTION(bb_ibl_targets)) {
if (!DYNAMO_OPTION(shared_bb_ibt_tables)) {
hashtable_ibl_myinit(
dcontext, &pt->bb_ibt[branch_type],
DYNAMO_OPTION(private_bb_ibl_targets_init),
DYNAMO_OPTION(private_bb_ibl_targets_load), HASH_FUNCTION_NONE,
HASHTABLE_IBL_OFFSET(branch_type), branch_type,
false, /* no lookup table */
(DYNAMO_OPTION(shared_bbs) ? FRAG_TABLE_TARGET_SHARED : 0)_IF_DEBUG(
ibl_bb_table_type_names[branch_type]));
/* mark as inclusive table for bb's - we in fact currently
* keep only frags that are not FRAG_IS_TRACE_HEAD */
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
/* for compatibility using an entry in the per-branch type stats */
CHECK_UNPROT_STATS(pt->bb_ibt[branch_type]);
/* FIXME: we don't expect trace_ibl_stats yet */
INIT_HASHTABLE_STATS(
pt->bb_ibt[branch_type].UNPROT_STAT(bb_ibl_stats[branch_type]));
} else {
pt->bb_ibt[branch_type].unprot_stats = NULL;
}
#endif /* HASHTABLE_STATISTICS */
} else {
/* ensure table from last time (if we had a reset) not still there */
memset(&pt->bb_ibt[branch_type], 0, sizeof(pt->bb_ibt[branch_type]));
update_private_ptr_to_shared_ibt_table(dcontext, branch_type,
false, /* trace = no */
false, /* no adjust old
* ref-count */
true /* lock */);
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
ALLOC_UNPROT_STATS(dcontext, &pt->bb_ibt[branch_type]);
CHECK_UNPROT_STATS(pt->bb_ibt[branch_type]);
INIT_HASHTABLE_STATS(pt->bb_ibt[branch_type].UNPROT_STAT(
trace_ibl_stats[branch_type]));
} else {
pt->bb_ibt[branch_type].unprot_stats = NULL;
}
#endif
}
}
}
ASSERT(IBL_BRANCH_TYPE_END == 3);
update_generated_hashtable_access(dcontext);
}
void
fragment_thread_init(dcontext_t *dcontext)
{
/* we allocate per_thread_t in the global heap solely for self-protection,
* even when turned off, since even with a lot of threads this isn't a lot of
* pressure on the global heap
*/
per_thread_t *pt;
/* case 7966: don't initialize un-needed data for hotp_only & thin_client.
* FIXME: could set htable initial sizes to 0 for all configurations, instead.
* per_thread_t is pretty big, so we avoid it, though it costs us checks for
* hotp_only in the islinking-related routines.
*/
if (RUNNING_WITHOUT_CODE_CACHE())
return;
pt = (per_thread_t *)global_heap_alloc(sizeof(per_thread_t) HEAPACCT(ACCT_OTHER));
dcontext->fragment_field = (void *)pt;
fragment_thread_reset_init(dcontext);
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
if (TRACEDUMP_ENABLED() && PRIVATE_TRACES_ENABLED()) {
pt->tracefile = open_log_file("traces", NULL, 0);
ASSERT(pt->tracefile != INVALID_FILE);
init_trace_file(pt);
}
#endif
#if defined(CLIENT_INTERFACE) && defined(CLIENT_SIDELINE)
ASSIGN_INIT_LOCK_FREE(pt->fragment_delete_mutex, fragment_delete_mutex);
#endif
pt->could_be_linking = false;
pt->wait_for_unlink = false;
pt->about_to_exit = false;
pt->flush_queue_nonempty = false;
pt->waiting_for_unlink = create_event();
pt->finished_with_unlink = create_event();
ASSIGN_INIT_LOCK_FREE(pt->linking_lock, linking_lock);
pt->finished_all_unlink = create_event();
pt->soon_to_be_linking = false;
pt->at_syscall_at_flush = false;
}
static bool
check_flush_queue(dcontext_t *dcontext, fragment_t *was_I_flushed);
/* frees all non-persistent memory */
void
fragment_thread_reset_free(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
DEBUG_DECLARE(ibl_branch_type_t branch_type;)
/* case 7966: don't initialize at all for hotp_only & thin_client */
if (RUNNING_WITHOUT_CODE_CACHE())
return;
/* Dec ref count on any shared tables that are pointed to. */
dec_all_table_ref_counts(dcontext, pt);
#ifdef DEBUG
/* for non-debug we do fast exit path and don't free local heap */
SELF_PROTECT_CACHE(dcontext, NULL, WRITABLE);
/* we remove flushed fragments from the htable, and they can be
* flushed after enter_threadexit() due to os_thread_stack_exit(),
* so we need to check the flush queue here
*/
d_r_mutex_lock(&pt->linking_lock);
check_flush_queue(dcontext, NULL);
d_r_mutex_unlock(&pt->linking_lock);
/* For consistency we remove entries from the IBL targets
* tables before we remove them from the trace table. However,
* we cannot free any fragments because for sure all of them will
* be present in the trace table.
*/
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (!DYNAMO_OPTION(disable_traces)
/* If no traces and no bb ibl targets we point ibl at
* an empty trace table */
|| !DYNAMO_OPTION(bb_ibl_targets)) {
if (!DYNAMO_OPTION(shared_trace_ibt_tables)) {
DOLOG(4, LOG_FRAGMENT, {
hashtable_ibl_dump_table(dcontext, &pt->trace_ibt[branch_type]);
});
DOLOG(1, LOG_FRAGMENT | LOG_STATS, {
hashtable_ibl_load_statistics(dcontext, &pt->trace_ibt[branch_type]);
});
hashtable_ibl_myfree(dcontext, &pt->trace_ibt[branch_type]);
} else {
# ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
print_hashtable_stats(dcontext, "Total",
shared_pt->trace_ibt[branch_type].name,
"trace ibl ", get_branch_type_name(branch_type),
&pt->trace_ibt[branch_type].UNPROT_STAT(
trace_ibl_stats[branch_type]));
DEALLOC_UNPROT_STATS(dcontext, &pt->trace_ibt[branch_type]);
}
# endif
memset(&pt->trace_ibt[branch_type], 0,
sizeof(pt->trace_ibt[branch_type]));
}
}
if (DYNAMO_OPTION(bb_ibl_targets)) {
if (!DYNAMO_OPTION(shared_bb_ibt_tables)) {
DOLOG(4, LOG_FRAGMENT,
{ hashtable_ibl_dump_table(dcontext, &pt->bb_ibt[branch_type]); });
DOLOG(1, LOG_FRAGMENT | LOG_STATS, {
hashtable_ibl_load_statistics(dcontext, &pt->bb_ibt[branch_type]);
});
hashtable_ibl_myfree(dcontext, &pt->bb_ibt[branch_type]);
} else {
# ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_stats)) {
print_hashtable_stats(
dcontext, "Total", shared_pt->bb_ibt[branch_type].name, "bb ibl ",
get_branch_type_name(branch_type),
&pt->bb_ibt[branch_type].UNPROT_STAT(bb_ibl_stats[branch_type]));
DEALLOC_UNPROT_STATS(dcontext, &pt->bb_ibt[branch_type]);
}
# endif
memset(&pt->bb_ibt[branch_type], 0, sizeof(pt->bb_ibt[branch_type]));
}
}
}
/* case 7653: we can't free the main tables prior to freeing the contents
* of all of them, as link freeing involves looking up in the other tables.
*/
if (PRIVATE_TRACES_ENABLED()) {
DOLOG(1, LOG_FRAGMENT | LOG_STATS,
{ hashtable_fragment_load_statistics(dcontext, &pt->trace); });
hashtable_fragment_reset(dcontext, &pt->trace);
}
DOLOG(1, LOG_FRAGMENT | LOG_STATS,
{ hashtable_fragment_load_statistics(dcontext, &pt->bb); });
hashtable_fragment_reset(dcontext, &pt->bb);
DOLOG(1, LOG_FRAGMENT | LOG_STATS,
{ hashtable_fragment_load_statistics(dcontext, &pt->future); });
hashtable_fragment_reset(dcontext, &pt->future);
if (PRIVATE_TRACES_ENABLED())
hashtable_fragment_free(dcontext, &pt->trace);
hashtable_fragment_free(dcontext, &pt->bb);
hashtable_fragment_free(dcontext, &pt->future);
SELF_PROTECT_CACHE(dcontext, NULL, READONLY);
#else
/* Case 10807: Clients need to be informed of fragment deletions
* so we'll reset the relevant hash tables for CI release builds.
*/
# ifdef CLIENT_INTERFACE
if (PRIVATE_TRACES_ENABLED())
hashtable_fragment_reset(dcontext, &pt->trace);
hashtable_fragment_reset(dcontext, &pt->bb);
# endif
#endif /* !DEBUG */
}
/* atexit cleanup */
void
fragment_thread_exit(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
/* case 7966: don't initialize at all for hotp_only & thin_client */
if (RUNNING_WITHOUT_CODE_CACHE())
return;
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
if (TRACEDUMP_ENABLED() && PRIVATE_TRACES_ENABLED()) {
/* write out all traces prior to deleting any, so links print nicely */
uint i;
fragment_t *f;
for (i = 0; i < pt->trace.capacity; i++) {
f = pt->trace.table[i];
if (!REAL_FRAGMENT(f))
continue;
if (SHOULD_OUTPUT_FRAGMENT(f->flags))
output_trace(dcontext, pt, f, -1);
}
exit_trace_file(pt);
}
#endif
fragment_thread_reset_free(dcontext);
/* events are global */
destroy_event(pt->waiting_for_unlink);
destroy_event(pt->finished_with_unlink);
destroy_event(pt->finished_all_unlink);
DELETE_LOCK(pt->linking_lock);
#if defined(CLIENT_INTERFACE) && defined(CLIENT_SIDELINE)
DELETE_LOCK(pt->fragment_delete_mutex);
#endif
global_heap_free(pt, sizeof(per_thread_t) HEAPACCT(ACCT_OTHER));
dcontext->fragment_field = NULL;
}
bool
fragment_thread_exited(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
return (pt == NULL || pt->about_to_exit);
}
#ifdef UNIX
void
fragment_fork_init(dcontext_t *dcontext)
{
/* FIXME: what about global file? */
# if defined(INTERNAL) || defined(CLIENT_INTERFACE)
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
if (TRACEDUMP_ENABLED() && PRIVATE_TRACES_ENABLED()) {
/* new log dir has already been created, so just open a new log file */
pt->tracefile = open_log_file("traces", NULL, 0);
ASSERT(pt->tracefile != INVALID_FILE);
init_trace_file(pt);
}
# endif
}
#endif
/* fragment_t heap layout looks like this:
*
* fragment_t/trace_t
* translation_info_t*, if necessary
* array composed of different sizes of linkstub_t subclasses:
* direct_linkstub_t
* cbr_fallthrough_linkstub_t
* indirect_linkstub_t
* post_linkstub_t, if necessary
*/
static uint
fragment_heap_size(uint flags, int direct_exits, int indirect_exits)
{
uint total_sz;
ASSERT((direct_exits + indirect_exits > 0) || TEST(FRAG_COARSE_GRAIN, flags));
total_sz = FRAGMENT_STRUCT_SIZE(flags) +
linkstubs_heap_size(flags, direct_exits, indirect_exits);
/* we rely on a small heap size for our ushort offset at the end */
ASSERT(total_sz <= USHRT_MAX);
return total_sz;
}
/* Allocates memory for a fragment_t and linkstubs and initializes them, but
* does not do any fcache-related initialization.
*/
static fragment_t *
fragment_create_heap(dcontext_t *dcontext, int direct_exits, int indirect_exits,
uint flags)
{
dcontext_t *alloc_dc = FRAGMENT_ALLOC_DC(dcontext, flags);
uint heapsz = fragment_heap_size(flags, direct_exits, indirect_exits);
/* linkstubs are in an array immediately after the fragment_t/trace_t struct */
fragment_t *f = (fragment_t *)nonpersistent_heap_alloc(
alloc_dc,
heapsz HEAPACCT(TEST(FRAG_IS_TRACE, flags) ? ACCT_TRACE : ACCT_FRAGMENT));
LOG(THREAD, LOG_FRAGMENT, 5,
"fragment heap size for flags 0x%08x, exits %d %d, is %d => " PFX "\n", flags,
direct_exits, indirect_exits, heapsz, f);
return f;
}
static void
fragment_init_heap(fragment_t *f, app_pc tag, int direct_exits, int indirect_exits,
uint flags)
{
ASSERT(f != NULL);
f->flags = flags; /* MUST set before calling fcache_add_fragment or
* FRAGMENT_EXIT_STUBS */
f->tag = tag;
/* Let fragment_create() fill in; other users are building fake fragments */
DODEBUG({ f->id = -1; });
f->next_vmarea = NULL; /* must be set by caller */
f->prev_vmarea = NULL; /* must be set by caller */
f->also.also_vmarea = NULL; /* must be set by caller */
linkstubs_init(FRAGMENT_EXIT_STUBS(f), direct_exits, indirect_exits, f);
/* initialize non-ibt entry to top of fragment (caller responsible for
* setting up prefix)
*/
f->prefix_size = 0;
#ifdef FRAGMENT_SIZES_STUDY
record_fragment_size(f->size, (flags & FRAG_IS_TRACE) != 0);
#endif
f->in_xlate.incoming_stubs = NULL;
#ifdef CUSTOM_TRACES_RET_REMOVAL
f->num_calls = 0;
f->num_rets = 0;
#endif
/* trace-only fields */
if (TEST(FRAG_IS_TRACE, flags)) {
trace_only_t *t = TRACE_FIELDS(f);
t->bbs = NULL;
/* real num_bbs won't be set until after the trace is emitted,
* but we need a non-zero value for linkstub_fragment()
*/
t->num_bbs = 1;
#ifdef PROFILE_RDTSC
t->count = 0UL;
t->total_time = (uint64)0;
#endif
}
}
/* Create a new fragment_t with empty prefix and return it.
* The fragment_t is allocated on the global or local heap, depending on the flags,
* unless FRAG_COARSE_GRAIN is set, in which case the fragment_t is a unique
* temporary struct that is NOT heap allocated and is only safe to use
* so long as the bb_building_lock is held!
*/
fragment_t *
fragment_create(dcontext_t *dcontext, app_pc tag, int body_size, int direct_exits,
int indirect_exits, int exits_size, uint flags)
{
fragment_t *f;
DEBUG_DECLARE(stats_int_t next_id;)
DOSTATS({
/* should watch this stat and if it gets too high need to re-do
* who needs the post-linkstub offset
*/
if (linkstub_frag_offs_at_end(flags, direct_exits, indirect_exits))
STATS_INC(num_fragment_post_linkstub);
});
/* ensure no races during a reset */
ASSERT(!dynamo_resetting);
if (TEST(FRAG_COARSE_GRAIN, flags)) {
ASSERT(DYNAMO_OPTION(coarse_units));
ASSERT_OWN_MUTEX(USE_BB_BUILDING_LOCK(), &bb_building_lock);
ASSERT(!TEST(FRAG_IS_TRACE, flags));
ASSERT(TEST(FRAG_SHARED, flags));
ASSERT(fragment_prefix_size(flags) == 0);
ASSERT((direct_exits == 0 && indirect_exits == 1) ||
(indirect_exits == 0 && (direct_exits == 1 || direct_exits == 2)));
/* FIXME: eliminate this temp fragment and linkstubs and
* have custom emit and link code that does not require such data
* structures? It would certainly be faster code.
* But would still want to record each exit's target in a convenient
* data structure, for later linking, unless we try to link in
* the same pass in which we emit indirect stubs.
* We could also use fragment_create() and free the resulting struct
* somewhere and switch to a wrapper at that point.
*/
memset(&coarse_emit_fragment, 0, sizeof(coarse_emit_fragment));
f = (fragment_t *)&coarse_emit_fragment;
/* We do not mark as FRAG_FAKE since this is pretty much a real
* fragment_t, and we do want to walk its linkstub_t structs, which
* are present.
*/
} else {
f = fragment_create_heap(dcontext, direct_exits, indirect_exits, flags);
}
fragment_init_heap(f, tag, direct_exits, indirect_exits, flags);
/* To make debugging easier we assign coarse-grain ids in the same namespace
* as fine-grain fragments, though we won't remember them at all.
*/
STATS_INC_ASSIGN(num_fragments, next_id);
IF_X64(ASSERT_TRUNCATE(f->id, int, next_id));
DOSTATS({ f->id = (int)next_id; });
DO_GLOBAL_STATS({
if (!TEST(FRAG_IS_TRACE, f->flags)) {
RSTATS_INC(num_bbs);
IF_X64(if (FRAG_IS_32(f->flags)) { STATS_INC(num_32bit_bbs); })
}
});
DOSTATS({
/* avoid double-counting for adaptive working set */
if (!fragment_lookup_deleted(dcontext, tag) && !TEST(FRAG_COARSE_GRAIN, flags))
STATS_INC(num_unique_fragments);
});
/* FIXME: make fragment count a release-build stat so we can do this in
* release builds
*/
DOSTATS({
if (d_r_stats != NULL &&
(uint)GLOBAL_STAT(num_fragments) ==
INTERNAL_OPTION(reset_at_fragment_count)) {
ASSERT(INTERNAL_OPTION(reset_at_fragment_count) != 0);
schedule_reset(RESET_ALL);
}
});
DODEBUG({
if ((uint)GLOBAL_STAT(num_fragments) == INTERNAL_OPTION(log_at_fragment_count)) {
/* we started at loglevel 1 and now we raise to the requested level */
options_make_writable();
d_r_stats->loglevel = DYNAMO_OPTION(stats_loglevel);
options_restore_readonly();
SYSLOG_INTERNAL_INFO("hit -log_at_fragment_count %d, raising loglevel to %d",
INTERNAL_OPTION(log_at_fragment_count),
DYNAMO_OPTION(stats_loglevel));
}
});
/* size is a ushort
* our offsets are ushorts as well: they assume body_size is small enough, not size
*/
#ifdef CLIENT_INTERFACE
if (body_size + exits_size + fragment_prefix_size(flags) > MAX_FRAGMENT_SIZE) {
FATAL_USAGE_ERROR(INSTRUMENTATION_TOO_LARGE, 2, get_application_name(),
get_application_pid());
}
#endif
ASSERT(body_size + exits_size + fragment_prefix_size(flags) <= MAX_FRAGMENT_SIZE);
/* currently MAX_FRAGMENT_SIZE is USHRT_MAX, but future proofing */
ASSERT_TRUNCATE(f->size, ushort,
(body_size + exits_size + fragment_prefix_size(flags)));
f->size = (ushort)(body_size + exits_size + fragment_prefix_size(flags));
/* fcache_add will fill in start_pc, next_fcache,
* prev_fcache, and fcache_extra
*/
fcache_add_fragment(dcontext, f);
/* after fcache_add_fragment so we can call get_fragment_coarse_info */
DOSTATS({
if (TEST(FRAG_SHARED, flags)) {
STATS_INC(num_shared_fragments);
if (TEST(FRAG_IS_TRACE, flags))
STATS_INC(num_shared_traces);
else if (TEST(FRAG_COARSE_GRAIN, flags)) {
coarse_info_t *info = get_fragment_coarse_info(f);
if (get_executable_area_coarse_info(f->tag) != info)
STATS_INC(num_coarse_secondary);
STATS_INC(num_coarse_fragments);
} else
STATS_INC(num_shared_bbs);
} else {
STATS_INC(num_private_fragments);
if (TEST(FRAG_IS_TRACE, flags))
STATS_INC(num_private_traces);
else
STATS_INC(num_private_bbs);
}
});
/* wait until initialized fragment completely before dumping any stats */
DOLOG(1, LOG_FRAGMENT | LOG_VMAREAS, {
if (INTERNAL_OPTION(global_stats_interval) &&
(f->id % INTERNAL_OPTION(global_stats_interval) == 0)) {
LOG(GLOBAL, LOG_FRAGMENT, 1, "Created %d fragments\n", f->id);
dump_global_stats(false);
}
if (INTERNAL_OPTION(thread_stats_interval) && INTERNAL_OPTION(thread_stats)) {
/* FIXME: why do we need a new dcontext? */
dcontext_t *cur_dcontext = get_thread_private_dcontext();
if (THREAD_STATS_ON(cur_dcontext) &&
THREAD_STAT(cur_dcontext, num_fragments) %
INTERNAL_OPTION(thread_stats_interval) ==
0) {
dump_thread_stats(cur_dcontext, false);
}
}
});
#ifdef WINDOWS
DOLOG(1, LOG_FRAGMENT | LOG_VMAREAS, {
if (f->id % 50000 == 0) {
LOG(GLOBAL, LOG_VMAREAS, 1,
"50K fragment check point: here are the loaded modules:\n");
print_modules(GLOBAL, DUMP_NOT_XML);
LOG(GLOBAL, LOG_VMAREAS, 1,
"50K fragment check point: here are the executable areas:\n");
print_executable_areas(GLOBAL);
}
});
#endif
return f;
}
/* Creates a new fragment_t+linkstubs from the passed-in fragment and
* fills in linkstub_t and fragment_t fields, copying the fcache-related fields
* from the passed-in fragment (so be careful how the fields are used).
* Meant to be used to create a full fragment from a coarse-grain fragment.
* Caller is responsible for freeing via fragment_free() w/ the same dcontext
* passed in here.
*/
fragment_t *
fragment_recreate_with_linkstubs(dcontext_t *dcontext, fragment_t *f_src)
{
uint num_dir, num_indir;
uint size;
fragment_t *f_tgt;
instrlist_t *ilist;
linkstub_t *l;
cache_pc body_end_pc;
/* Not FAKE since has linkstubs, but still fake in a sense since no fcache
* slot -- need to mark that?
*/
uint flags = (f_src->flags & ~FRAG_FAKE);
ASSERT_CURIOSITY(TEST(FRAG_COARSE_GRAIN, f_src->flags)); /* only use so far */
/* FIXME case 9325: build from tag here? Need to exactly re-mangle + re-instrument.
* We use _exact to get any elided final jmp not counted in size
*/
ilist = decode_fragment_exact(dcontext, f_src, NULL, NULL, f_src->flags, &num_dir,
&num_indir);
f_tgt = fragment_create_heap(dcontext, num_dir, num_indir, flags);
fragment_init_heap(f_tgt, f_src->tag, num_dir, num_indir, flags);
f_tgt->start_pc = f_src->start_pc;
/* Can't call this until we have start_pc set */
body_end_pc = set_linkstub_fields(dcontext, f_tgt, ilist, num_dir, num_indir,
false /*do not emit*/);
/* Calculate total size */
IF_X64(ASSERT_TRUNCATE(size, uint, (body_end_pc - f_tgt->start_pc)));
size = (uint)(body_end_pc - f_tgt->start_pc);
for (l = FRAGMENT_EXIT_STUBS(f_tgt); l != NULL; l = LINKSTUB_NEXT_EXIT(l)) {
if (!EXIT_HAS_LOCAL_STUB(l->flags, f_tgt->flags))
continue; /* it's kept elsewhere */
size += linkstub_size(dcontext, f_tgt, l);
}
ASSERT_TRUNCATE(f_tgt->size, ushort, size);
f_tgt->size = (ushort)size;
ASSERT(TEST(FRAG_FAKE, f_src->flags) || size == f_src->size);
ASSERT_TRUNCATE(f_tgt->prefix_size, byte, fragment_prefix_size(f_src->flags));
f_tgt->prefix_size = (byte)fragment_prefix_size(f_src->flags);
ASSERT(TEST(FRAG_FAKE, f_src->flags) || f_src->prefix_size == f_tgt->prefix_size);
f_tgt->fcache_extra = f_src->fcache_extra;
instrlist_clear_and_destroy(dcontext, ilist);
return f_tgt;
}
/* Frees the storage associated with f.
* Callers should use fragment_delete() instead of this routine, unless they
* obtained their fragment_t from fragment_recreate_with_linkstubs().
*/
void
fragment_free(dcontext_t *dcontext, fragment_t *f)
{
dcontext_t *alloc_dc = FRAGMENT_ALLOC_DC(dcontext, f->flags);
uint heapsz;
int direct_exits = 0;
int indirect_exits = 0;
linkstub_t *l = FRAGMENT_EXIT_STUBS(f);
for (; l != NULL; l = LINKSTUB_NEXT_EXIT(l)) {
if (LINKSTUB_DIRECT(l->flags))
direct_exits++;
else {
ASSERT(LINKSTUB_INDIRECT(l->flags));
indirect_exits++;
}
}
heapsz = fragment_heap_size(f->flags, direct_exits, indirect_exits);
STATS_INC(num_fragments_deleted);
if (HAS_STORED_TRANSLATION_INFO(f)) {
ASSERT(FRAGMENT_TRANSLATION_INFO(f) != NULL);
translation_info_free(dcontext, FRAGMENT_TRANSLATION_INFO(f));
} else
ASSERT(FRAGMENT_TRANSLATION_INFO(f) == NULL);
/* N.B.: monitor_remove_fragment() was called in fragment_delete,
* which is assumed to have been called prior to fragment_free
*/
linkstub_free_exitstubs(dcontext, f);
if ((f->flags & FRAG_IS_TRACE) != 0) {
trace_only_t *t = TRACE_FIELDS(f);
if (t->bbs != NULL) {
nonpersistent_heap_free(alloc_dc, t->bbs,
t->num_bbs *
sizeof(trace_bb_info_t) HEAPACCT(ACCT_TRACE));
}
nonpersistent_heap_free(alloc_dc, f, heapsz HEAPACCT(ACCT_TRACE));
} else {
nonpersistent_heap_free(alloc_dc, f, heapsz HEAPACCT(ACCT_FRAGMENT));
}
}
/* Returns the end of the fragment body + any local stubs (excluding selfmod copy) */
cache_pc
fragment_stubs_end_pc(fragment_t *f)
{
if (TEST(FRAG_SELFMOD_SANDBOXED, f->flags))
return FRAGMENT_SELFMOD_COPY_PC(f);
else
return f->start_pc + f->size;
}
/* Returns the end of the fragment body (excluding exit stubs and selfmod copy) */
cache_pc
fragment_body_end_pc(dcontext_t *dcontext, fragment_t *f)
{
linkstub_t *l;
for (l = FRAGMENT_EXIT_STUBS(f); l; l = LINKSTUB_NEXT_EXIT(l)) {
if (EXIT_HAS_LOCAL_STUB(l->flags, f->flags)) {
return EXIT_STUB_PC(dcontext, f, l);
}
}
/* must be no stubs after fragment body */
return fragment_stubs_end_pc(f);
}
#if defined(CLIENT_INTERFACE) && defined(CLIENT_SIDELINE)
/* synchronization routines needed for sideline threads so they don't get
* fragments they are referencing deleted */
void
fragment_get_fragment_delete_mutex(dcontext_t *dcontext)
{
if (dynamo_exited || dcontext == GLOBAL_DCONTEXT)
return;
d_r_mutex_lock(&(((per_thread_t *)dcontext->fragment_field)->fragment_delete_mutex));
}
void
fragment_release_fragment_delete_mutex(dcontext_t *dcontext)
{
if (dynamo_exited || dcontext == GLOBAL_DCONTEXT)
return;
d_r_mutex_unlock(
&(((per_thread_t *)dcontext->fragment_field)->fragment_delete_mutex));
}
#endif
/* cleaner to have own flags since there are no negative versions
* of FRAG_SHARED and FRAG_IS_TRACE for distinguishing from "don't care"
*/
enum {
LOOKUP_TRACE = 0x001,
LOOKUP_BB = 0x002,
LOOKUP_PRIVATE = 0x004,
LOOKUP_SHARED = 0x008,
};
/* A lookup constrained by bb/trace and/or shared/private */
static inline fragment_t *
fragment_lookup_type(dcontext_t *dcontext, app_pc tag, uint lookup_flags)
{
fragment_t *f;
LOG(THREAD, LOG_MONITOR, 6, "fragment_lookup_type " PFX " 0x%x\n", tag, lookup_flags);
if (dcontext != GLOBAL_DCONTEXT && TEST(LOOKUP_PRIVATE, lookup_flags)) {
/* FIXME: add a hashtablex.h wrapper that checks #entries and
* grabs lock for us for all lookups?
*/
/* look at private tables */
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
/* case 147: traces take precedence over bbs */
if (PRIVATE_TRACES_ENABLED() && TEST(LOOKUP_TRACE, lookup_flags)) {
/* now try trace table */
f = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag, &pt->trace);
if (f->tag != NULL) {
ASSERT(f->tag == tag);
DOLOG(2, LOG_FRAGMENT, {
if (DYNAMO_OPTION(shared_traces)) {
/* ensure private trace never shadows shared trace */
fragment_t *sf;
d_r_read_lock(&shared_trace->rwlock);
sf = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag,
shared_trace);
d_r_read_unlock(&shared_trace->rwlock);
ASSERT(sf->tag == NULL);
}
});
ASSERT(!TESTANY(FRAG_FAKE | FRAG_COARSE_GRAIN, f->flags));
return f;
}
}
if (TEST(LOOKUP_BB, lookup_flags) && pt->bb.entries > 0) {
/* basic block table last */
f = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag, &pt->bb);
if (f->tag != NULL) {
ASSERT(f->tag == tag);
DOLOG(2, LOG_FRAGMENT, {
if (DYNAMO_OPTION(shared_bbs)) {
/* ensure private bb never shadows shared bb, except for
* temp privates for trace building
*/
fragment_t *sf;
d_r_read_lock(&shared_bb->rwlock);
sf = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag,
shared_bb);
d_r_read_unlock(&shared_bb->rwlock);
ASSERT(sf->tag == NULL || TEST(FRAG_TEMP_PRIVATE, f->flags));
}
});
ASSERT(!TESTANY(FRAG_FAKE | FRAG_COARSE_GRAIN, f->flags));
return f;
}
}
}
if (TEST(LOOKUP_SHARED, lookup_flags)) {
if (DYNAMO_OPTION(shared_traces) && TEST(LOOKUP_TRACE, lookup_flags)) {
/* MUST look at shared trace table before shared bb table,
* since a shared trace can shadow a shared trace head
*/
d_r_read_lock(&shared_trace->rwlock);
f = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag, shared_trace);
d_r_read_unlock(&shared_trace->rwlock);
if (f->tag != NULL) {
ASSERT(f->tag == tag);
ASSERT(!TESTANY(FRAG_FAKE | FRAG_COARSE_GRAIN, f->flags));
return f;
}
}
if (DYNAMO_OPTION(shared_bbs) && TEST(LOOKUP_BB, lookup_flags)) {
/* MUST look at private trace table before shared bb table,
* since a private trace can shadow a shared trace head
*/
d_r_read_lock(&shared_bb->rwlock);
f = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag, shared_bb);
d_r_read_unlock(&shared_bb->rwlock);
if (f->tag != NULL) {
ASSERT(f->tag == tag);
ASSERT(!TESTANY(FRAG_FAKE | FRAG_COARSE_GRAIN, f->flags));
return f;
}
}
}
return NULL;
}
/* lookup a fragment tag */
fragment_t *
fragment_lookup(dcontext_t *dcontext, app_pc tag)
{
return fragment_lookup_type(
dcontext, tag, LOOKUP_TRACE | LOOKUP_BB | LOOKUP_PRIVATE | LOOKUP_SHARED);
}
/* lookup a fragment tag, but only look in trace tables
* N.B.: because of shadowing this may not return what fragment_lookup() returns!
*/
fragment_t *
fragment_lookup_trace(dcontext_t *dcontext, app_pc tag)
{
return fragment_lookup_type(dcontext, tag,
LOOKUP_TRACE | LOOKUP_PRIVATE | LOOKUP_SHARED);
}
/* lookup a fragment tag, but only look in bb tables
* N.B.: because of shadowing this may not return what fragment_lookup() returns!
*/
fragment_t *
fragment_lookup_bb(dcontext_t *dcontext, app_pc tag)
{
return fragment_lookup_type(dcontext, tag,
LOOKUP_BB | LOOKUP_PRIVATE | LOOKUP_SHARED);
}
/* lookup a fragment tag, but only look in shared bb table
* N.B.: because of shadowing this may not return what fragment_lookup() returns!
*/
fragment_t *
fragment_lookup_shared_bb(dcontext_t *dcontext, app_pc tag)
{
return fragment_lookup_type(dcontext, tag, LOOKUP_BB | LOOKUP_SHARED);
}
/* lookup a fragment tag, but only look in tables that are the same shared-ness
* as flags.
* N.B.: because of shadowing this may not return what fragment_lookup() returns!
*/
fragment_t *
fragment_lookup_same_sharing(dcontext_t *dcontext, app_pc tag, uint flags)
{
return fragment_lookup_type(
dcontext, tag,
LOOKUP_TRACE | LOOKUP_BB |
(TEST(FRAG_SHARED, flags) ? LOOKUP_SHARED : LOOKUP_PRIVATE));
}
#ifdef DEBUG /*currently only used for debugging */
static fragment_t *
hashtable_pclookup(dcontext_t *dcontext, fragment_table_t *table, cache_pc pc)
{
uint i;
fragment_t *f;
ASSERT_TABLE_SYNCHRONIZED(table, READWRITE); /* lookup requires read or write lock */
for (i = 0; i < table->capacity; i++) {
f = table->table[i];
if (!REAL_FRAGMENT(f))
continue;
if (pc >= f->start_pc && pc < (f->start_pc + f->size)) {
return f;
}
}
return NULL;
}
/* lookup a fragment pc in the fcache by walking all hashtables.
* we have more efficient methods (fcache_fragment_pclookup) so this is only
* used for debugging.
*/
fragment_t *
fragment_pclookup_by_htable(dcontext_t *dcontext, cache_pc pc, fragment_t *wrapper)
{
/* if every fragment is guaranteed to end in 1+ stubs (which
* is not true for DYNAMO_OPTION(separate_private_stubs) we can
* simply decode forward until we hit the stub and recover
* the linkstub_t* from there -- much more efficient than walking
* all the hashtables, plus nicely handles invisible & removed frags!
* FIXME: measure perf hit of pclookup, implement this decode strategy.
* also we can miss invisible or removed fragments (case 122) so we
* may want this regardless of performance -- see also FIXME below.
*/
fragment_t *f;
per_thread_t *pt = NULL;
if (dcontext != GLOBAL_DCONTEXT) {
pt = (per_thread_t *)dcontext->fragment_field;
/* look at private traces first */
if (PRIVATE_TRACES_ENABLED()) {
f = hashtable_pclookup(dcontext, &pt->trace, pc);
if (f != NULL)
return f;
}
}
if (DYNAMO_OPTION(shared_traces)) {
/* then shared traces */
d_r_read_lock(&shared_trace->rwlock);
f = hashtable_pclookup(dcontext, shared_trace, pc);
d_r_read_unlock(&shared_trace->rwlock);
if (f != NULL)
return f;
}
if (DYNAMO_OPTION(shared_bbs)) {
/* then shared basic blocks */
d_r_read_lock(&shared_bb->rwlock);
f = hashtable_pclookup(dcontext, shared_bb, pc);
d_r_read_unlock(&shared_bb->rwlock);
if (f != NULL)
return f;
}
if (dcontext != GLOBAL_DCONTEXT) {
/* now private basic blocks */
f = hashtable_pclookup(dcontext, &pt->bb, pc);
if (f != NULL)
return f;
}
if (DYNAMO_OPTION(coarse_units)) {
coarse_info_t *info = get_executable_area_coarse_info(pc);
while (info != NULL) { /* loop over primary and secondary unit */
cache_pc body;
app_pc tag = fragment_coarse_pclookup(dcontext, info, pc, &body);
if (tag != NULL) {
ASSERT(wrapper != NULL);
fragment_coarse_wrapper(wrapper, tag, body);
return wrapper;
}
ASSERT(info->frozen || info->non_frozen == NULL);
info = info->non_frozen;
ASSERT(info == NULL || !info->frozen);
}
}
/* FIXME: shared fragment may have been removed from hashtable but
* still be in cache, and e.g. handle_modified_code still needs to know about it --
* should walk deletion vector
*/
return NULL;
}
#endif /* DEBUG */
/* lookup a fragment pc in the fcache */
fragment_t *
fragment_pclookup(dcontext_t *dcontext, cache_pc pc, fragment_t *wrapper)
{
/* Rather than walk every single hashtable, including the invisible table,
* and the pending-deletion list (case 3567), we find the fcache unit
* and walk it.
* An even more efficient alternative would be to decode backward, but
* that's not doable in general.
*
* If every fragment is guaranteed to end in 1+ stubs (which
* is not true for DYNAMO_OPTION(separate_{private,shared}_stubs) we can
* simply decode forward until we hit the stub and recover
* the linkstub_t* from there.
* Or we can decode until we hit a jmp and if it's to a linked fragment_t,
* search its incoming list.
* Stub decoding is complicated by CLIENT_INTERFACE custom stubs.
*/
return fcache_fragment_pclookup(dcontext, pc, wrapper);
}
/* Performs a pclookup and if the result is a coarse-grain fragment, allocates
* a new fragment_t+linkstubs.
* Returns in alloc whether the returned fragment_t was allocated and needs to be
* freed by the caller via fragment_free().
* If no result is found, alloc is set to false.
* FIXME: use FRAG_RECREATED flag to indicate allocated instead?
*/
fragment_t *
fragment_pclookup_with_linkstubs(dcontext_t *dcontext, cache_pc pc,
/*OUT*/ bool *alloc)
{
fragment_t wrapper;
fragment_t *f = fragment_pclookup(dcontext, pc, &wrapper);
ASSERT(alloc != NULL);
if (f != NULL && TEST(FRAG_COARSE_GRAIN, f->flags)) {
ASSERT(f == &wrapper);
f = fragment_recreate_with_linkstubs(dcontext, f);
*alloc = true;
} else
*alloc = false;
return f;
}
/* add f to the ftable */
void
fragment_add(dcontext_t *dcontext, fragment_t *f)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
fragment_table_t *table = GET_FTABLE(pt, f->flags);
bool resized;
/* no future frags! */
ASSERT(!TEST(FRAG_IS_FUTURE, f->flags));
DOCHECK(1, {
fragment_t *existing = fragment_lookup(dcontext, f->tag);
ASSERT(existing == NULL ||
IF_CUSTOM_TRACES(/* we create and persist shadowed trace heads */
(TEST(FRAG_IS_TRACE_HEAD, f->flags) ||
TEST(FRAG_IS_TRACE_HEAD, existing->flags)) ||)
/* private trace or temp can shadow shared bb */
(TESTANY(FRAG_IS_TRACE | FRAG_TEMP_PRIVATE, f->flags) &&
TEST(FRAG_SHARED, f->flags) != TEST(FRAG_SHARED, existing->flags)) ||
/* shared trace can shadow shared trace head, even with
* -remove_shared_trace_heads */
(TESTALL(FRAG_IS_TRACE | FRAG_SHARED, f->flags) &&
!TEST(FRAG_IS_TRACE, existing->flags) &&
TESTALL(FRAG_SHARED | FRAG_IS_TRACE_HEAD, existing->flags)));
});
/* We'd like the shared fragment table synch to be independent of the
* bb building synch (which may become more fine-grained in the future),
* so an add needs to hold the write lock to prevent conflicts with
* other adds.
* We may be able to have a scheme where study() and remove() are writers
* but add() is a reader -- but that's confusing and prone to errors in
* the future.
* We assume that synchronizing addition of the same tag is done through
* other means -- we cannot grab this while performing the lookup
* w/o making our read locks check to see if we're the writer,
* which is a perf hit. Only the actual hashtable add is a "write".
*/
TABLE_RWLOCK(table, write, lock);
resized = fragment_add_to_hashtable(dcontext, f, table);
TABLE_RWLOCK(table, write, unlock);
/* After resizing a table that is targeted by inlined IBL heads
* the current fragment will need to be repatched; but, we don't have
* to update the stubs when using per-type trace tables since the
* trace table itself is not targeted therefore resizing it doesn't matter.
*/
#ifdef SHARING_STUDY
if (INTERNAL_OPTION(fragment_sharing_study)) {
if (TEST(FRAG_IS_TRACE, f->flags))
add_shared_block(shared_traces, &shared_traces_lock, f);
else
add_shared_block(shared_blocks, &shared_blocks_lock, f);
}
#endif
}
/* Many options, use macros in fragment.h for readability
* If output:
* dumps f to trace file
* If remove:
* removes f from ftable
* If unlink:
* if f is linked, unlinks f
* removes f from incoming link tables
* If fcache:
* deletes f from fcache unit
*/
void
fragment_delete(dcontext_t *dcontext, fragment_t *f, uint actions)
{
#if defined(CLIENT_INTERFACE) && defined(CLIENT_SIDELINE)
bool acquired_shared_vm_lock = false;
bool acquired_fragdel_lock = false;
#endif
LOG(THREAD, LOG_FRAGMENT, 3,
"fragment_delete: *" PFX " F%d(" PFX ")." PFX " %s 0x%x\n", f, f->id, f->tag,
f->start_pc, TEST(FRAG_IS_TRACE, f->flags) ? "trace" : "bb", actions);
DOLOG(1, LOG_FRAGMENT, {
if ((f->flags & FRAG_CANNOT_DELETE) != 0) {
LOG(THREAD, LOG_FRAGMENT, 2,
"ERROR: trying to delete undeletable F%d(" PFX ") 0x%x\n", f->id, f->tag,
actions);
}
});
ASSERT((f->flags & FRAG_CANNOT_DELETE) == 0);
ASSERT((f->flags & FRAG_IS_FUTURE) == 0);
/* ensure the actual free of a shared fragment is done only
* after a multi-stage flush or a reset
*/
ASSERT(!TEST(FRAG_SHARED, f->flags) || TEST(FRAG_WAS_DELETED, f->flags) ||
dynamo_exited || dynamo_resetting || is_self_allsynch_flushing());
#if defined(CLIENT_INTERFACE) && defined(CLIENT_SIDELINE)
/* need to protect ability to reference frag fields and fcache space */
/* all other options are mostly notification */
if (monitor_delete_would_abort_trace(dcontext, f) && DYNAMO_OPTION(shared_traces)) {
/* must acquire shared_vm_areas lock before fragment_delete_mutex (PR 596371) */
acquired_shared_vm_lock = true;
acquire_recursive_lock(&change_linking_lock);
acquire_vm_areas_lock(dcontext, FRAG_SHARED);
}
/* XXX: I added the test for FRAG_WAS_DELETED for i#759: does sideline
* look at fragments after that is set? If so need to resolve rank order
* w/ shared_cache_lock.
*/
if (!TEST(FRAG_WAS_DELETED, f->flags) &&
(!TEST(FRAGDEL_NO_HEAP, actions) || !TEST(FRAGDEL_NO_FCACHE, actions))) {
acquired_fragdel_lock = true;
fragment_get_fragment_delete_mutex(dcontext);
}
#endif
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
if (!TEST(FRAGDEL_NO_OUTPUT, actions)) {
if (TEST(FRAGDEL_NEED_CHLINK_LOCK, actions) && TEST(FRAG_SHARED, f->flags))
acquire_recursive_lock(&change_linking_lock);
else {
ASSERT(!TEST(FRAG_SHARED, f->flags) ||
self_owns_recursive_lock(&change_linking_lock));
}
fragment_output(dcontext, f);
if (TEST(FRAGDEL_NEED_CHLINK_LOCK, actions) && TEST(FRAG_SHARED, f->flags))
release_recursive_lock(&change_linking_lock);
}
#endif
if (!TEST(FRAGDEL_NO_MONITOR, actions))
monitor_remove_fragment(dcontext, f);
if (!TEST(FRAGDEL_NO_UNLINK, actions)) {
if (TEST(FRAGDEL_NEED_CHLINK_LOCK, actions) && TEST(FRAG_SHARED, f->flags))
acquire_recursive_lock(&change_linking_lock);
else {
ASSERT(!TEST(FRAG_SHARED, f->flags) ||
self_owns_recursive_lock(&change_linking_lock));
}
if ((f->flags & FRAG_LINKED_INCOMING) != 0)
unlink_fragment_incoming(dcontext, f);
if ((f->flags & FRAG_LINKED_OUTGOING) != 0)
unlink_fragment_outgoing(dcontext, f);
incoming_remove_fragment(dcontext, f);
if (TEST(FRAGDEL_NEED_CHLINK_LOCK, actions) && TEST(FRAG_SHARED, f->flags))
release_recursive_lock(&change_linking_lock);
}
#ifdef LINUX
if (TEST(FRAG_HAS_RSEQ_ENDPOINT, f->flags))
rseq_remove_fragment(dcontext, f);
#endif
if (!TEST(FRAGDEL_NO_HTABLE, actions))
fragment_remove(dcontext, f);
if (!TEST(FRAGDEL_NO_VMAREA, actions))
vm_area_remove_fragment(dcontext, f);
if (!TEST(FRAGDEL_NO_FCACHE, actions)) {
fcache_remove_fragment(dcontext, f);
}
#ifdef SIDELINE
if (dynamo_options.sideline)
sideline_fragment_delete(f);
#endif
#ifdef CLIENT_INTERFACE
/* For exit-time deletion we invoke instrument_fragment_deleted() directly from
* hashtable_fragment_reset(). If we add any further conditions on when it should
* be invoked we should keep the two calls in synch.
*/
if (dr_fragment_deleted_hook_exists() &&
(!TEST(FRAGDEL_NO_HEAP, actions) || !TEST(FRAGDEL_NO_FCACHE, actions)))
instrument_fragment_deleted(dcontext, f->tag, f->flags);
#endif
#ifdef UNIX
if (INTERNAL_OPTION(profile_pcs))
pcprofile_fragment_deleted(dcontext, f);
#endif
if (!TEST(FRAGDEL_NO_HEAP, actions)) {
fragment_free(dcontext, f);
}
#if defined(CLIENT_INTERFACE) && defined(CLIENT_SIDELINE)
if (acquired_fragdel_lock)
fragment_release_fragment_delete_mutex(dcontext);
if (acquired_shared_vm_lock) {
release_vm_areas_lock(dcontext, FRAG_SHARED);
release_recursive_lock(&change_linking_lock);
}
#endif
}
/* Record translation info. Typically used for pending-delete fragments
* whose original app code cannot be trusted as it has been modified (case
* 3559).
* Caller is required to take care of synch (typically this is called
* during a flush or during fragment emit)
*/
void
fragment_record_translation_info(dcontext_t *dcontext, fragment_t *f, instrlist_t *ilist)
{
ASSERT(!NEED_SHARED_LOCK(f->flags) || !USE_BB_BUILDING_LOCK() ||
OWN_MUTEX(&bb_building_lock) || OWN_MUTEX(&trace_building_lock) ||
is_self_flushing());
/* We require that either the FRAG_WAS_DELETED flag is set, to
* indicate there is allocated memory in the live field that needs
* to be freed, or that the FRAG_HAS_TRANSLATION_INFO field is
* set, indicating that there is a special appended field pointing
* to the translation info.
*/
if (TEST(FRAG_HAS_TRANSLATION_INFO, f->flags)) {
ASSERT(!TEST(FRAG_WAS_DELETED, f->flags));
*(FRAGMENT_TRANSLATION_INFO_ADDR(f)) =
record_translation_info(dcontext, f, ilist);
ASSERT(FRAGMENT_TRANSLATION_INFO(f) != NULL);
STATS_INC(num_fragment_translation_stored);
} else if (TEST(FRAG_WAS_DELETED, f->flags)) {
ASSERT(f->in_xlate.incoming_stubs == NULL);
if (INTERNAL_OPTION(safe_translate_flushed)) {
f->in_xlate.translation_info = record_translation_info(dcontext, f, ilist);
ASSERT(f->in_xlate.translation_info != NULL);
ASSERT(FRAGMENT_TRANSLATION_INFO(f) == f->in_xlate.translation_info);
STATS_INC(num_fragment_translation_stored);
#ifdef INTERNAL
DODEBUG({
if (INTERNAL_OPTION(stress_recreate_pc)) {
/* verify recreation */
stress_test_recreate(dcontext, f, NULL);
}
});
#endif
} else
f->in_xlate.translation_info = NULL;
} else
ASSERT_NOT_REACHED();
}
/* Removes the shared fragment f from all lookup tables in a safe
* manner that does not require a full flush synch.
* This routine can be called without synchronizing with other threads.
*/
void
fragment_remove_shared_no_flush(dcontext_t *dcontext, fragment_t *f)
{
DEBUG_DECLARE(bool shared_ibt_table_used = !TEST(FRAG_IS_TRACE, f->flags)
? DYNAMO_OPTION(shared_bb_ibt_tables)
: DYNAMO_OPTION(shared_trace_ibt_tables);)
ASSERT_NOT_IMPLEMENTED(!TEST(FRAG_COARSE_GRAIN, f->flags));
LOG(GLOBAL, LOG_FRAGMENT, 4, "Remove shared %s " PFX " (@" PFX ")\n",
fragment_type_name(f), f->tag, f->start_pc);
/* Strategy: ensure no races in updating table or links by grabbing the high-level
* locks that are used to synchronize additions to the table itself.
* Then, simply remove directly from DR-only tables, and safely from ib tables.
* FIXME: There are still risks that the fragment's link state may change
*/
LOG(THREAD, LOG_FRAGMENT, 3, "fragment_remove_shared_no_flush: F%d\n", f->id);
ASSERT(TEST(FRAG_SHARED, f->flags));
if (TEST(FRAG_IS_TRACE, f->flags)) {
d_r_mutex_lock(&trace_building_lock);
}
/* grab bb building lock even for traces to further prevent link changes */
d_r_mutex_lock(&bb_building_lock);
if (TEST(FRAG_WAS_DELETED, f->flags)) {
/* since caller can't grab locks, we can have a race where someone
* else deletes first -- in that case nothing to do
*/
STATS_INC(shared_delete_noflush_race);
d_r_mutex_unlock(&bb_building_lock);
if (TEST(FRAG_IS_TRACE, f->flags))
d_r_mutex_unlock(&trace_building_lock);
return;
}
/* FIXME: try to share code w/ fragment_unlink_for_deletion() */
/* Make link changes atomic. We also want vm_area_remove_fragment and
* marking as deleted to be atomic so we grab vm_areas lock up front.
*/
acquire_recursive_lock(&change_linking_lock);
acquire_vm_areas_lock(dcontext, f->flags);
/* FIXME: share all this code w/ vm_area_unlink_fragments()
* The work there is just different enough to make that hard, though.
*/
if (TEST(FRAG_LINKED_OUTGOING, f->flags))
unlink_fragment_outgoing(GLOBAL_DCONTEXT, f);
if (TEST(FRAG_LINKED_INCOMING, f->flags))
unlink_fragment_incoming(GLOBAL_DCONTEXT, f);
incoming_remove_fragment(GLOBAL_DCONTEXT, f);
/* remove from ib lookup tables in a safe manner. this removes the
* frag only from this thread's tables OR from shared tables.
*/
fragment_prepare_for_removal(GLOBAL_DCONTEXT, f);
/* fragment_remove ignores the ibl tables for shared fragments */
fragment_remove(GLOBAL_DCONTEXT, f);
/* FIXME: we don't currently remove from thread-private ibl tables as that
* requires walking all of the threads. */
ASSERT_NOT_IMPLEMENTED(DYNAMO_OPTION(opt_jit) || !IS_IBL_TARGET(f->flags) ||
shared_ibt_table_used);
vm_area_remove_fragment(dcontext, f);
/* case 8419: make marking as deleted atomic w/ fragment_t.also_vmarea field
* invalidation, so that users of vm_area_add_to_list() can rely on this
* flag to determine validity
*/
f->flags |= FRAG_WAS_DELETED;
release_vm_areas_lock(dcontext, f->flags);
release_recursive_lock(&change_linking_lock);
/* if a flush occurs, this fragment will be ignored -- so we must store
* translation info now, just in case
*/
if (!TEST(FRAG_HAS_TRANSLATION_INFO, f->flags))
fragment_record_translation_info(dcontext, f, NULL);
/* try to catch any potential races */
ASSERT(!TEST(FRAG_LINKED_OUTGOING, f->flags));
ASSERT(!TEST(FRAG_LINKED_INCOMING, f->flags));
d_r_mutex_unlock(&bb_building_lock);
if (TEST(FRAG_IS_TRACE, f->flags)) {
d_r_mutex_unlock(&trace_building_lock);
}
/* no locks can be held when calling this, but f is already unreachable,
* so can do this outside of locks
*/
add_to_lazy_deletion_list(dcontext, f);
}
/* Prepares a fragment for delayed deletion by unlinking it.
* Caller is responsible for calling vm_area_remove_fragment().
* Caller must hold the change_linking_lock if f is shared.
*/
void
fragment_unlink_for_deletion(dcontext_t *dcontext, fragment_t *f)
{
ASSERT(!TEST(FRAG_SHARED, f->flags) ||
self_owns_recursive_lock(&change_linking_lock));
/* this is not an error since fcache unit flushing puts lazily-deleted
* fragments onto its list to ensure they are in the same pending
* delete entry as the normal fragments -- so this routine becomes
* a nop for them
*/
if (TEST(FRAG_WAS_DELETED, f->flags)) {
LOG(THREAD, LOG_FRAGMENT | LOG_VMAREAS, 5,
"NOT unlinking F%d(" PFX ") for deletion\n", f->id, f->start_pc);
STATS_INC(deleted_frags_re_deleted);
return;
}
LOG(THREAD, LOG_FRAGMENT | LOG_VMAREAS, 5, "unlinking F%d(" PFX ") for deletion\n",
f->id, f->start_pc);
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
/* we output now to avoid problems reading component blocks
* of traces after source modules are unloaded
*/
fragment_output(dcontext, f);
#endif
if (TEST(FRAG_LINKED_OUTGOING, f->flags))
unlink_fragment_outgoing(dcontext, f);
if (TEST(FRAG_LINKED_INCOMING, f->flags))
unlink_fragment_incoming(dcontext, f);
/* need to remove outgoings from others' incoming and
* redirect others' outgoing to a future. former must be
* done before we remove from hashtable, and latter must be
* done now to avoid other fragments jumping into stale code,
* so we do it here and not when we do the real fragment_delete().
* we don't need to do this for private fragments, but we do anyway
* so that we can use the fragment_t.incoming_stubs field as a union.
*/
incoming_remove_fragment(dcontext, f);
if (TEST(FRAG_SHARED, f->flags)) {
/* we shouldn't need to worry about someone else changing the
* link status, since nobody else is allowed to be in DR now,
* and afterward they all must invalidate any ptrs they hold
* to flushed fragments, and flushed fragments are not
* reachable via hashtable or incoming lists!
*/
/* ASSUMPTION: monitor_remove_fragment does NOT need to
* be called for all threads, since private trace head
* ctrs are cleared lazily (only relevant here for
* -shared_traces) and invalidating last_{exit,fragment}
* is done by the trace overlap and abort in the main
* flush loop.
*/
}
/* need to remove from htable
* we used to only do fragment_prepare_for_removal() (xref case 1808)
* for private fragments, but for case 3559 we want to free up the
* incoming field at unlink time, and we must do all 3 of unlink,
* vmarea, and htable freeing at once.
*/
fragment_remove(dcontext, f);
/* let recreate_fragment_ilist() know that this fragment is
* pending deletion and might no longer match the app's state.
* for shared fragments, also lets people know f is not in a normal
* vmarea anymore (though actually moving f is up to the caller).
* additionally the flag indicates that translation info was allocated
* for this fragment.
*/
f->flags |= FRAG_WAS_DELETED;
/* the original app code cannot be used to recreate state, so we must
* store translation info now
*/
if (!TEST(FRAG_HAS_TRANSLATION_INFO, f->flags))
fragment_record_translation_info(dcontext, f, NULL);
STATS_INC(fragments_unlinked_for_deletion);
}
/* When shared IBT tables are used, update thread-private state
* to reflect the current parameter values -- hash mask, table address --
* for the shared ftable.
*/
static bool
update_private_ibt_table_ptrs(
dcontext_t *dcontext, ibl_table_t *ftable _IF_DEBUG(fragment_entry_t **orig_table))
{
bool table_change = false;
if (TEST(FRAG_TABLE_SHARED, ftable->table_flags)) {
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
if (TEST(FRAG_TABLE_TRACE, ftable->table_flags) &&
ftable->table != pt->trace_ibt[ftable->branch_type].table) {
DODEBUG({
if (orig_table != NULL) {
*orig_table = pt->trace_ibt[ftable->branch_type].table;
}
});
table_change = true;
} else if (DYNAMO_OPTION(bb_ibl_targets) &&
!TEST(FRAG_TABLE_TRACE, ftable->table_flags) &&
ftable->table != pt->bb_ibt[ftable->branch_type].table) {
DODEBUG({
if (orig_table != NULL) {
*orig_table = pt->bb_ibt[ftable->branch_type].table;
}
});
table_change = true;
}
if (table_change) {
update_private_ptr_to_shared_ibt_table(
dcontext, ftable->branch_type,
TEST(FRAG_TABLE_TRACE, ftable->table_flags), true, /* adjust old
* ref-count */
true /* lock */);
DODEBUG({
if (orig_table != NULL)
ASSERT(ftable->table != *orig_table);
});
}
#ifdef DEBUG
else if (orig_table != NULL)
*orig_table = NULL;
#endif
}
return table_change;
}
/* Update the thread-private ptrs for the dcontext to point to the
* currently "live" shared IBT table for branch_type.
* When adjust_ref_count==true, adjust the ref-count for the old table
* that the dcontext currently points to.
* When lock_table==true, lock the shared table prior to manipulating
* it. If this is false, the caller must have locked the table already.
* NOTE: If adjust_ref_count=true, lock_table should be true also and
* the caller should NOT hold the table lock, since the underlying
* routines that manipulate the ref count lock the table.
*/
static inline void
update_private_ptr_to_shared_ibt_table(dcontext_t *dcontext,
ibl_branch_type_t branch_type, bool trace,
bool adjust_old_ref_count, bool lock_table)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
ibl_table_t *sh_table_ptr =
trace ? &shared_pt->trace_ibt[branch_type] : &shared_pt->bb_ibt[branch_type];
ibl_table_t *pvt_table_ptr =
trace ? &pt->trace_ibt[branch_type] : &pt->bb_ibt[branch_type];
/* Point to the new table. The shared table must be locked prior to
* accessing any of its fields. */
if (lock_table)
TABLE_RWLOCK(sh_table_ptr, write, lock);
ASSERT_OWN_WRITE_LOCK(true, &sh_table_ptr->rwlock);
/* We can get here multiple times due to callers being racy */
if (pvt_table_ptr->table == sh_table_ptr->table) {
SYSLOG_INTERNAL_WARNING_ONCE("racy private ptr to shared table update");
if (lock_table)
TABLE_RWLOCK(sh_table_ptr, write, unlock);
return;
}
/* Decrement the ref-count for any old table that is pointed to. */
if (adjust_old_ref_count) {
dec_table_ref_count(dcontext, pvt_table_ptr, false /*can't be live*/);
}
/* We must hold at least the read lock when writing, else we could grab
* an inconsistent mask/lookuptable pair if another thread is in the middle
* of resizing the table (case 10405).
*/
/* Only data for one set of tables is stored in TLS -- for the trace
* tables in the default config OR the BB tables in shared BBs
* only mode.
*/
if ((trace || SHARED_BB_ONLY_IB_TARGETS()) && DYNAMO_OPTION(ibl_table_in_tls))
update_lookuptable_tls(dcontext, sh_table_ptr);
ASSERT(pvt_table_ptr->table != sh_table_ptr->table);
pvt_table_ptr->table = sh_table_ptr->table;
pvt_table_ptr->hash_mask = sh_table_ptr->hash_mask;
/* We copy the unaligned value over also because it's used for matching
* in the dead table list. */
pvt_table_ptr->table_unaligned = sh_table_ptr->table_unaligned;
pvt_table_ptr->table_flags = sh_table_ptr->table_flags;
sh_table_ptr->ref_count++;
ASSERT(sh_table_ptr->ref_count > 0);
DODEBUG({
LOG(THREAD, LOG_FRAGMENT | LOG_STATS, 2,
"update_table_ptrs %s-%s table: addr " PFX ", mask " PIFX "\n",
trace ? "trace" : "BB", sh_table_ptr->name, sh_table_ptr->table,
sh_table_ptr->hash_mask);
if ((trace || SHARED_BB_ONLY_IB_TARGETS()) && DYNAMO_OPTION(ibl_table_in_tls)) {
local_state_extended_t *state =
(local_state_extended_t *)dcontext->local_state;
LOG(THREAD, LOG_FRAGMENT | LOG_STATS, 2,
"TLS state %s-%s table: addr " PFX ", mask " PIFX "\n",
trace ? "trace" : "BB", sh_table_ptr->name,
state->table_space.table[branch_type].lookuptable,
state->table_space.table[branch_type].hash_mask);
}
});
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(hashtable_ibl_entry_stats)) {
pvt_table_ptr->entry_stats_to_lookup_table =
sh_table_ptr->entry_stats_to_lookup_table;
} else
pvt_table_ptr->entry_stats_to_lookup_table = 0;
#endif
if (lock_table)
TABLE_RWLOCK(sh_table_ptr, write, unlock);
/* We don't need the lock for this, and holding it will have rank order
* issues with disassembling in debug builds */
if (PRIVATE_TRACES_ENABLED() || DYNAMO_OPTION(bb_ibl_targets))
update_generated_hashtable_access(dcontext);
STATS_INC(num_shared_ibt_table_ptr_resets);
}
/* When shared IBT tables are used, update thread-private state
* to reflect the current parameter values -- hash mask, table address --
* for all tables.
*/
static bool
update_all_private_ibt_table_ptrs(dcontext_t *dcontext, per_thread_t *pt)
{
bool rc = false;
if (SHARED_IBT_TABLES_ENABLED()) {
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (DYNAMO_OPTION(shared_trace_ibt_tables)) {
if (update_private_ibt_table_ptrs(
dcontext, &shared_pt->trace_ibt[branch_type] _IF_DEBUG(NULL)))
rc = true;
}
if (DYNAMO_OPTION(shared_bb_ibt_tables)) {
if (update_private_ibt_table_ptrs(
dcontext, &shared_pt->bb_ibt[branch_type] _IF_DEBUG(NULL)))
rc = true;
}
}
}
return rc;
}
/* Prepares for removal of f from ftable (does not delete f) by pointing the
* fragment's lookup table entry to an entry point that leads to a cache exit.
* This routine is needed for safe removal of a fragment by a thread while
* another thread may be about to jump to it via an IBL. The lookuptable is
* left in a slightly inconsistent state but one that is accepted by the
* consistency check. See the note on hashtable_fragment_check_consistency
* in the routine.
*
* Returns true if the fragment was found & removed.
*/
static bool
fragment_prepare_for_removal_from_table(dcontext_t *dcontext, fragment_t *f,
ibl_table_t *ftable)
{
uint hindex;
fragment_entry_t fe = FRAGENTRY_FROM_FRAGMENT(f);
fragment_entry_t *pg;
/* We need the write lock since the start_pc is modified (though we
* technically may be ok in all scenarios there) and to avoid problems
* with parallel prepares (shouldn't count on the bb building lock).
* Grab the lock after all private ptrs are updated since that
* operation might grab the same lock, if this remove is from a
* shared IBT table.
*/
/* FIXME: why do we need to update here? */
update_private_ibt_table_ptrs(dcontext, ftable _IF_DEBUG(NULL));
TABLE_RWLOCK(ftable, write, lock);
pg = hashtable_ibl_lookup_for_removal(fe, ftable, &hindex);
if (pg != NULL) {
/* Note all IBL routines that could be looking up an entry
* in this table have to exit with equivalent register
* state. It is possible to enter a private bb IBL
* lookup, shared bb IBL lookup or trace bb IBL lookup and
* if a delete race is hit then they would all go to the
* pending_delete_pc that we'll now supply. They HAVE to
* be all equivalent independent of the source fragment for this to work.
*
* On the other hand we can provide different start_pc
* values if we have different tables. We currently don't
* take advantage of this but we'll leave the power in place.
*/
/* FIXME: [perf] we could memoize this value in the table itself */
cache_pc pending_delete_pc = get_target_delete_entry_pc(dcontext, ftable);
ASSERT(IBL_ENTRIES_ARE_EQUAL(*pg, fe));
ASSERT(pending_delete_pc != NULL);
LOG(THREAD, LOG_FRAGMENT, 3,
"fragment_prepare: remove F%d(" PFX ") from %s[%u] (table addr " PFX "), "
"set to " PFX "\n",
f->id, f->tag, ftable->name, hindex, ftable->table, pending_delete_pc);
/* start_pc_fragment will not match start_pc for the table
* consistency checks. However, the hashtable_fragment_check_consistency
* routine verifies that either start_pc/start_pc_fragment match OR that
* the start_pc_fragment is set to the correct target_delete
* entry point.
*
* We change the tag to FAKE_TAG, which preserves linear probing.
* In a thread-shared table, this ensures that the same tag will never
* be present in more than one entry in a table (1 real entry &
* 1+ target_delete entries).
* This isn't needed in a thread-private table but doesn't hurt.
*/
ftable->table[hindex].start_pc_fragment = pending_delete_pc;
ftable->table[hindex].tag_fragment = FAKE_TAG;
/* FIXME In a shared table, this means that the entry cannot
* be overwritten for a fragment with the same tag. */
ftable->unlinked_entries++;
ftable->entries--;
TABLE_RWLOCK(ftable, write, unlock);
ASSERT(!TEST(FRAG_CANNOT_DELETE, f->flags));
return true;
}
TABLE_RWLOCK(ftable, write, unlock);
return false;
}
/* Prepares fragment f for removal from all IBL routine targeted tables.
* Does not actually remove the entry from the table
* as that can only be done through proper cross-thread synchronization.
*
* Returns true if the fragment was found & removed.
*/
bool
fragment_prepare_for_removal(dcontext_t *dcontext, fragment_t *f)
{
per_thread_t *pt;
bool prepared = false;
ibl_branch_type_t branch_type;
if (!IS_IBL_TARGET(f->flags)) {
/* nothing to do */
return false;
}
ASSERT(TEST(FRAG_SHARED, f->flags) || dcontext != GLOBAL_DCONTEXT);
/* We need a real per_thread_t & context below so make sure we have one. */
if (dcontext == GLOBAL_DCONTEXT) {
dcontext = get_thread_private_dcontext();
ASSERT(dcontext != NULL);
}
pt = GET_PT(dcontext);
/* FIXME: as an optimization we could test if IS_IBL_TARGET() is
* set before looking it up
*/
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
per_thread_t *local_pt = pt;
/* We put traces into the trace tables and BBs into the BB tables
* and sometimes put traces into BB tables also. We never put
* BBs into a trace table.
*/
if (TEST(FRAG_IS_TRACE, f->flags)) {
if (DYNAMO_OPTION(shared_trace_ibt_tables))
local_pt = shared_pt;
if (fragment_prepare_for_removal_from_table(
dcontext, f, &local_pt->trace_ibt[branch_type]))
prepared = true;
}
if (DYNAMO_OPTION(bb_ibl_targets) &&
(!TEST(FRAG_IS_TRACE, f->flags) ||
DYNAMO_OPTION(bb_ibt_table_includes_traces))) {
if (DYNAMO_OPTION(shared_bb_ibt_tables))
local_pt = shared_pt;
if (fragment_prepare_for_removal_from_table(dcontext, f,
&local_pt->bb_ibt[branch_type])) {
#ifdef DEBUG
ibl_table_t *ibl_table = GET_IBT_TABLE(pt, f->flags, branch_type);
fragment_entry_t current;
TABLE_RWLOCK(ibl_table, read, lock);
current = hashtable_ibl_lookup(dcontext, (ptr_uint_t)f->tag, ibl_table);
ASSERT(IBL_ENTRY_IS_EMPTY(current));
TABLE_RWLOCK(ibl_table, read, unlock);
#endif
prepared = true;
}
}
}
return prepared;
}
#ifdef DEBUG
/* FIXME: hashtable_fragment_reset() needs to walk the tables to get these
* stats, but then we'd need to subtract 1 from all smaller counts -
* e.g. if an entry is found in 3 tables we can add (1,-1,0) then
* we'll find it again and we should add (0,1,-1) and one more time
* when we should add (0,0,1). In total all will be accounted for to
* (1,0,0) without messing much else.
*/
static inline void
fragment_ibl_stat_account(uint flags, uint ibls_targeted)
{
if (TEST(FRAG_IS_TRACE, flags)) {
switch (ibls_targeted) {
case 0: break; /* doesn't have to be a target of any IBL routine */
case 1: STATS_INC(num_traces_in_1_ibl_tables); break;
case 2: STATS_INC(num_traces_in_2_ibl_tables); break;
case 3: STATS_INC(num_traces_in_3_ibl_tables); break;
default: ASSERT_NOT_REACHED();
}
} else {
switch (ibls_targeted) {
case 0: break; /* doesn't have to be a target of any IBL routine */
case 1: STATS_INC(num_bbs_in_1_ibl_tables); break;
case 2: STATS_INC(num_bbs_in_2_ibl_tables); break;
case 3: STATS_INC(num_bbs_in_3_ibl_tables); break;
default: ASSERT_NOT_REACHED();
}
}
}
#endif
/* Removes f from any IBT tables it is in.
* If f is in a shared table, only removes if from_shared is true, in
* which case dcontext must be GLOBAL_DCONTEXT and we must have
* dynamo_all_threads_synched (case 10137).
*/
void
fragment_remove_from_ibt_tables(dcontext_t *dcontext, fragment_t *f, bool from_shared)
{
bool shared_ibt_table =
(!TEST(FRAG_IS_TRACE, f->flags) && DYNAMO_OPTION(shared_bb_ibt_tables)) ||
(TEST(FRAG_IS_TRACE, f->flags) && DYNAMO_OPTION(shared_trace_ibt_tables));
fragment_entry_t fe = FRAGENTRY_FROM_FRAGMENT(f);
ASSERT(!from_shared || !shared_ibt_table || !IS_IBL_TARGET(f->flags) ||
(dcontext == GLOBAL_DCONTEXT && dynamo_all_threads_synched));
if (((!shared_ibt_table && dcontext != GLOBAL_DCONTEXT) ||
(from_shared && dcontext == GLOBAL_DCONTEXT && dynamo_all_threads_synched)) &&
IS_IBL_TARGET(f->flags)) {
/* trace_t tables should be all private and any deletions should follow strict
* two step deletion process, we don't need to be holding nested locks when
* removing any cached entries from the per-type IBL target tables.
*/
/* FIXME: the stats on ibls_targeted are not quite correct - we need to
* gather these independently */
DEBUG_DECLARE(uint ibls_targeted = 0;)
ibl_branch_type_t branch_type;
per_thread_t *pt = GET_PT(dcontext);
ASSERT(TEST(FRAG_IS_TRACE, f->flags) || DYNAMO_OPTION(bb_ibl_targets));
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
/* assuming a single tag can't be both a trace and bb */
ibl_table_t *ibtable = GET_IBT_TABLE(pt, f->flags, branch_type);
ASSERT(!TEST(FRAG_TABLE_SHARED, ibtable->table_flags) ||
dynamo_all_threads_synched);
TABLE_RWLOCK(ibtable, write, lock); /* satisfy asserts, even if allsynch */
if (hashtable_ibl_remove(fe, ibtable)) {
LOG(THREAD, LOG_FRAGMENT, 2, " removed F%d(" PFX ") from IBT table %s\n",
f->id, f->tag,
TEST(FRAG_TABLE_TRACE, ibtable->table_flags)
? ibl_trace_table_type_names[branch_type]
: ibl_bb_table_type_names[branch_type]);
DOSTATS({ ibls_targeted++; });
}
TABLE_RWLOCK(ibtable, write, unlock);
}
DOSTATS({ fragment_ibl_stat_account(f->flags, ibls_targeted); });
}
}
/* Removes ibl entries whose tags are in [start,end) */
static uint
fragment_remove_ibl_entries_in_region(dcontext_t *dcontext, app_pc start, app_pc end,
uint frag_flags)
{
uint total_removed = 0;
per_thread_t *pt = GET_PT(dcontext);
ibl_branch_type_t branch_type;
ASSERT(pt != NULL);
ASSERT(TEST(FRAG_IS_TRACE, frag_flags) || DYNAMO_OPTION(bb_ibl_targets));
ASSERT(dcontext == get_thread_private_dcontext() || dynamo_all_threads_synched);
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
ibl_table_t *ibtable = GET_IBT_TABLE(pt, frag_flags, branch_type);
uint removed = 0;
TABLE_RWLOCK(ibtable, write, lock);
if (ibtable->entries > 0) {
removed = hashtable_ibl_range_remove(dcontext, ibtable, (ptr_uint_t)start,
(ptr_uint_t)end, NULL);
/* Ensure a full remove gets everything */
ASSERT(start != UNIVERSAL_REGION_BASE || end != UNIVERSAL_REGION_END ||
(ibtable->entries == 0 &&
is_region_memset_to_char(
(app_pc)ibtable->table,
(ibtable->capacity - 1) * sizeof(fragment_entry_t), 0)));
}
LOG(THREAD, LOG_FRAGMENT, 2,
" removed %d entries (%d left) in " PFX "-" PFX " from IBT table %s\n",
removed, ibtable->entries, start, end,
TEST(FRAG_TABLE_TRACE, ibtable->table_flags)
? ibl_trace_table_type_names[branch_type]
: ibl_bb_table_type_names[branch_type]);
TABLE_RWLOCK(ibtable, write, unlock);
total_removed += removed;
}
return total_removed;
}
/* Removes shared (and incidentally private, but if no shared targets
* can exist, may remove nothing) ibl entries whose tags are in
* [start,end) from all tables associated w/ dcontext. If
* dcontext==GLOBAL_DCONTEXT, uses the shared tables, if they exist;
* else, uses the private tables, if any.
*/
uint
fragment_remove_all_ibl_in_region(dcontext_t *dcontext, app_pc start, app_pc end)
{
uint removed = 0;
if (DYNAMO_OPTION(bb_ibl_targets) &&
((dcontext == GLOBAL_DCONTEXT && DYNAMO_OPTION(shared_bb_ibt_tables)) ||
(dcontext != GLOBAL_DCONTEXT && !DYNAMO_OPTION(shared_bb_ibt_tables)))) {
removed +=
fragment_remove_ibl_entries_in_region(dcontext, start, end, 0 /*bb table*/);
}
if (DYNAMO_OPTION(shared_traces) &&
((dcontext == GLOBAL_DCONTEXT && DYNAMO_OPTION(shared_trace_ibt_tables)) ||
(dcontext != GLOBAL_DCONTEXT && !DYNAMO_OPTION(shared_trace_ibt_tables)))) {
removed +=
fragment_remove_ibl_entries_in_region(dcontext, start, end, FRAG_IS_TRACE);
}
return removed;
}
/* Removes f from any hashtables -- BB, trace, or future -- and IBT tables
* it is in, except for shared IBT tables. */
void
fragment_remove(dcontext_t *dcontext, fragment_t *f)
{
per_thread_t *pt = GET_PT(dcontext);
fragment_table_t *table = GET_FTABLE(pt, f->flags);
ASSERT(TEST(FRAG_SHARED, f->flags) || dcontext != GLOBAL_DCONTEXT);
/* For consistency we remove entries from the IBT
* tables before we remove them from the trace table.
*/
fragment_remove_from_ibt_tables(dcontext, f, false /*leave in shared*/);
/* We need the write lock since deleting shifts elements around (though we
* technically may be ok in all scenarios there) and to avoid problems with
* multiple removes at once (shouldn't count on the bb building lock)
*/
TABLE_RWLOCK(table, write, lock);
if (hashtable_fragment_remove(f, table)) {
LOG(THREAD, LOG_FRAGMENT, 4,
"fragment_remove: removed F%d(" PFX ") from fcache lookup table\n", f->id,
f->tag);
TABLE_RWLOCK(table, write, unlock);
return;
}
TABLE_RWLOCK(table, write, unlock);
/* ok to not find a trace head used to start a trace -- fine to have deleted
* the trace head
*/
ASSERT(cur_trace_tag(dcontext) ==
f->tag
/* PR 299808: we have invisible temp trace bbs */
IF_CLIENT_INTERFACE(|| TEST(FRAG_TEMP_PRIVATE, f->flags)));
}
/* Remove f from ftable, replacing it in the hashtable with new_f,
* which has an identical tag.
* f's next field is left intact so this can be done while owner is in fcache
* f is NOT deleted in any other way!
* To delete later, caller must call fragment_delete w/ remove=false
*/
void
fragment_replace(dcontext_t *dcontext, fragment_t *f, fragment_t *new_f)
{
per_thread_t *pt = GET_PT(dcontext);
fragment_table_t *table = GET_FTABLE(pt, f->flags);
TABLE_RWLOCK(table, write, lock);
if (hashtable_fragment_replace(f, new_f, table)) {
fragment_entry_t fe = FRAGENTRY_FROM_FRAGMENT(f);
fragment_entry_t new_fe = FRAGENTRY_FROM_FRAGMENT(new_f);
LOG(THREAD, LOG_FRAGMENT, 4,
"removed F%d from fcache lookup table (replaced with F%d) " PFX "->~" PFX
"," PFX "\n",
f->id, new_f->id, f->tag, f->start_pc, new_f->start_pc);
/* Need to replace all entries from the IBL tables that may have this entry */
if (IS_IBL_TARGET(f->flags)) {
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
ibl_table_t *ibtable = GET_IBT_TABLE(pt, f->flags, branch_type);
/* currently we don't have shared ib target tables,
* otherwise a write lock would come in the picture here
*/
ASSERT(!TEST(FRAG_TABLE_SHARED, ibtable->table_flags));
hashtable_ibl_replace(fe, new_fe, ibtable);
}
}
} else
ASSERT_NOT_REACHED();
TABLE_RWLOCK(table, write, unlock);
/* tell monitor f has disappeared, but do not delete from incoming table
* or from fcache, also do not dump to trace file
*/
monitor_remove_fragment(dcontext, f);
}
void
fragment_shift_fcache_pointers(dcontext_t *dcontext, fragment_t *f, ssize_t shift,
cache_pc start, cache_pc end, size_t old_size)
{
per_thread_t *pt = GET_PT(dcontext);
IF_X64(ASSERT_NOT_IMPLEMENTED(false)); /* must re-relativize when copying! */
/* need to shift all stored cache_pcs.
* do not need to shift relative pcs pointing to other fragments -- they're
* all getting shifted too!
* just need to re-pc-relativize jmps to fixed locations, namely
* cti's in exit stubs, and call instructions inside fragments.
*/
LOG(THREAD, LOG_FRAGMENT, 2, "fragment_shift_fcache_pointers: F%d + " SSZFMT "\n",
f->id, shift);
ASSERT(!TEST(FRAG_IS_FUTURE, f->flags)); /* only in-cache frags */
f->start_pc += shift;
/* Should shift cached lookup entries in all IBL target tables,
* order doesn't matter here: either way we'll be inconsistent, can't do this
* within the cache.
*/
if (IS_IBL_TARGET(f->flags)) {
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
/* Of course, we need to shift only pointers into the
* cache that is getting shifted!
*/
ibl_table_t *ibtable = GET_IBT_TABLE(pt, f->flags, branch_type);
fragment_entry_t fe = FRAGENTRY_FROM_FRAGMENT(f);
fragment_entry_t *pg;
uint hindex;
TABLE_RWLOCK(ibtable, read, lock);
pg = hashtable_ibl_lookup_for_removal(fe, ibtable, &hindex);
if (pg != NULL)
pg->start_pc_fragment += shift;
TABLE_RWLOCK(ibtable, read, unlock);
LOG(THREAD, LOG_FRAGMENT, 2,
"fragment_table_shift_fcache_pointers: %s ibt %s shifted by %d\n",
TEST(FRAG_IS_TRACE, f->flags) ? "trace" : "BB", ibtable->name, shift);
}
}
linkstubs_shift(dcontext, f, shift);
DOLOG(6, LOG_FRAGMENT, { /* print after start_pc updated so get actual code */
LOG(THREAD, LOG_FRAGMENT, 6,
"before shifting F%d (" PFX ")\n", f->id, f->tag);
disassemble_fragment(dcontext, f, d_r_stats->loglevel < 3);
});
#ifdef X86
if (TEST(FRAG_SELFMOD_SANDBOXED, f->flags)) {
/* just re-finalize to update */
finalize_selfmod_sandbox(dcontext, f);
}
#endif
/* inter-cache links must be redone, but all fragment entry pcs must be
* fixed up first, so that's done separately
*/
/* re-do pc-relative targets outside of cache */
shift_ctis_in_fragment(dcontext, f, shift, start, end, old_size);
#ifdef CHECK_RETURNS_SSE2
finalize_return_check(dcontext, f);
#endif
DOLOG(6, LOG_FRAGMENT, {
LOG(THREAD, LOG_FRAGMENT, 6, "after shifting F%d (" PFX ")\n", f->id, f->tag);
disassemble_fragment(dcontext, f, d_r_stats->loglevel < 3);
});
}
/* this routine only copies data structures like bbs and statistics
*/
void
fragment_copy_data_fields(dcontext_t *dcontext, fragment_t *f_src, fragment_t *f_dst)
{
if ((f_src->flags & FRAG_IS_TRACE) != 0) {
trace_only_t *t_src = TRACE_FIELDS(f_src);
trace_only_t *t_dst = TRACE_FIELDS(f_dst);
ASSERT((f_dst->flags & FRAG_IS_TRACE) != 0);
if (t_src->bbs != NULL) {
t_dst->bbs = nonpersistent_heap_alloc(
dcontext, t_src->num_bbs * sizeof(trace_bb_info_t) HEAPACCT(ACCT_TRACE));
memcpy(t_dst->bbs, t_src->bbs, t_src->num_bbs * sizeof(trace_bb_info_t));
t_dst->num_bbs = t_src->num_bbs;
}
#ifdef PROFILE_RDTSC
t_dst->count = t_src->count;
t_dst->total_time = t_src->total_time;
#endif
}
}
#if defined(DEBUG) && defined(INTERNAL)
static void
dump_lookup_table(dcontext_t *dcontext, ibl_table_t *ftable)
{
uint i;
cache_pc target_delete = get_target_delete_entry_pc(dcontext, ftable);
ASSERT(target_delete != NULL);
ASSERT(ftable->table != NULL);
LOG(THREAD, LOG_FRAGMENT, 1, "%6s %10s %10s -- %s\n", "i", "tag", "target",
ftable->name);
/* need read lock to traverse the table */
TABLE_RWLOCK(ftable, read, lock);
for (i = 0; i < ftable->capacity; i++) {
if (ftable->table[i].tag_fragment != 0) {
if (ftable->table[i].start_pc_fragment == target_delete) {
LOG(THREAD, LOG_FRAGMENT, 1, "%6x " PFX " target_delete\n", i,
ftable->table[i].tag_fragment);
ASSERT(ftable->table[i].tag_fragment == FAKE_TAG);
} else {
LOG(THREAD, LOG_FRAGMENT, 1, "%6x " PFX " " PFX "\n", i,
ftable->table[i].tag_fragment, ftable->table[i].start_pc_fragment);
}
}
DOCHECK(1, { hashtable_ibl_check_consistency(dcontext, ftable, i); });
}
TABLE_RWLOCK(ftable, read, unlock);
}
#endif
#ifdef DEBUG
/* used only for debugging purposes, check if IBL routine leaks due to wraparound */
/* interesting only when not using INTERNAL_OPTION(ibl_sentinel_check) */
static bool
is_fragment_index_wraparound(dcontext_t *dcontext, ibl_table_t *ftable, fragment_t *f)
{
uint hindex = HASH_FUNC((ptr_uint_t)f->tag, ftable);
uint found_at_hindex;
fragment_entry_t fe = FRAGENTRY_FROM_FRAGMENT(f);
fragment_entry_t *pg = hashtable_ibl_lookup_for_removal(fe, ftable, &found_at_hindex);
ASSERT(pg != NULL);
ASSERT(IBL_ENTRIES_ARE_EQUAL(*pg, fe));
LOG(THREAD, LOG_FRAGMENT, 3,
"is_fragment_index_wraparound F%d, tag " PFX ", found_at_hindex 0x%x, "
"preferred 0x%x\n",
f->id, f->tag, found_at_hindex, hindex);
return (found_at_hindex < hindex); /* wraparound */
}
#endif /* DEBUG */
static void
fragment_add_ibl_target_helper(dcontext_t *dcontext, fragment_t *f,
ibl_table_t *ibl_table)
{
fragment_entry_t current;
fragment_entry_t fe = FRAGENTRY_FROM_FRAGMENT(f);
/* Never add a BB to a trace table. */
ASSERT(!(!TEST(FRAG_IS_TRACE, f->flags) &&
TEST(FRAG_TABLE_TRACE, ibl_table->table_flags)));
/* adding is a write operation */
TABLE_RWLOCK(ibl_table, write, lock);
/* This is the last time the table lock is grabbed before adding the frag so
* check here to account for the race in the time between the
* FRAG_IS_TRACE_HEAD check in add_ibl_target() and now. We never add trace
* heads to an IBT target table.
*/
if (TEST(FRAG_IS_TRACE_HEAD, f->flags)) {
TABLE_RWLOCK(ibl_table, write, unlock);
STATS_INC(num_th_bb_ibt_add_race);
return;
}
/* For shared tables, check again in case another thread snuck in
* before the preceding lock and added the target. */
if (TEST(FRAG_TABLE_SHARED, ibl_table->table_flags)) {
current = hashtable_ibl_lookup(dcontext, (ptr_uint_t)f->tag, ibl_table);
if (IBL_ENTRY_IS_EMPTY(current))
hashtable_ibl_add(dcontext, fe, ibl_table);
/* We don't ever expect to find a like-tagged fragment. A BB
* can be unlinked due to eviction or when it's marked as a trace
* head. Eviction (for example, due to cache consistency)
* sets start_pc_fragment to FAKE_TAG, so there can't be
* a tag match; &unlinked_fragment is returned, and this
* applies to traces also. For trace head marking, FAKE_TAG
* is also set so &unlinked_fragment is returned.
*
* If we didn't set FAKE_TAG for an unlinked entry, then it
* could be clobbered with a new fragment w/the same tag.
* In a shared table, unlinked entries cannot be clobbered
* except by fragments w/the same tags, so this could help
* limit the length of collision chains.
*/
} else {
hashtable_ibl_add(dcontext, fe, ibl_table);
}
TABLE_RWLOCK(ibl_table, write, unlock);
DOSTATS({
if (!TEST(FRAG_IS_TRACE, f->flags))
STATS_INC(num_bbs_ibl_targets);
/* We assume that traces can be added to trace and BB IBT tables but
* not just to BB tables. We count only traces added to trace tables
* so that we don't double increment.
*/
else if (TEST(FRAG_IS_TRACE, f->flags) &&
TEST(FRAG_TABLE_TRACE, ibl_table->table_flags))
STATS_INC(num_traces_ibl_targets);
});
/* Adding current exit to help calculate an estimated
* indirect branch fan-out, that is function fan-in for
* returns. Note that other IBL hits to the same place
* will not have exits associated.
*/
LOG(THREAD, LOG_FRAGMENT, 2,
"fragment_add_ibl_target added F%d(" PFX "), branch %d, to %s, on exit from " PFX
"\n",
f->id, f->tag, ibl_table->branch_type, ibl_table->name,
LINKSTUB_FAKE(dcontext->last_exit)
? 0
: EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit));
DOLOG(5, LOG_FRAGMENT, {
dump_lookuptable_tls(dcontext);
hashtable_ibl_dump_table(dcontext, ibl_table);
dump_lookup_table(dcontext, ibl_table);
});
DODEBUG({
if (TEST(FRAG_SHARED, f->flags) && !TEST(FRAG_IS_TRACE, f->flags)) {
LOG(THREAD, LOG_FRAGMENT, 2, "add_ibl_target: shared BB F%d(" PFX ") added\n",
f->id, f->tag);
}
});
}
/* IBL targeted fragments per branch type */
fragment_t *
fragment_add_ibl_target(dcontext_t *dcontext, app_pc tag, ibl_branch_type_t branch_type)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
fragment_t *f = NULL;
fragment_t wrapper;
if (SHARED_BB_ONLY_IB_TARGETS()) {
f = fragment_lookup_bb(dcontext, tag);
if (f == NULL) {
f = fragment_coarse_lookup_wrapper(dcontext, tag, &wrapper);
if (f != NULL) {
#if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH)
if (TEST(COARSE_FILL_IBL_MASK(branch_type),
DYNAMO_OPTION(coarse_fill_ibl))) {
/* On-demand per-type ibl filling from the persisted RAC/RCT
* table. We limit to the first thread to ask for it by
* clearing the coarse_info_t pending_table fields.
*/
/* FIXME: combine w/ the coarse lookup to do this once only */
coarse_info_t *coarse = get_fragment_coarse_info(f);
ASSERT(coarse != NULL);
if (coarse->persisted &&
exists_coarse_ibl_pending_table(dcontext, coarse, branch_type)) {
bool in_persisted_ibl = false;
d_r_mutex_lock(&coarse->lock);
if (exists_coarse_ibl_pending_table(dcontext, coarse,
branch_type)) {
ibl_table_t *ibl_table =
GET_IBT_TABLE(pt, f->flags, branch_type);
coarse_persisted_fill_ibl(dcontext, coarse, branch_type);
TABLE_RWLOCK(ibl_table, read, lock);
if (!IBL_ENTRY_IS_EMPTY(hashtable_ibl_lookup(
dcontext, (ptr_uint_t)tag, ibl_table)))
in_persisted_ibl = true;
TABLE_RWLOCK(ibl_table, read, unlock);
if (in_persisted_ibl) {
d_r_mutex_unlock(&coarse->lock);
return f;
}
}
d_r_mutex_unlock(&coarse->lock);
}
}
#endif /* defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH) */
}
}
} else {
f = fragment_lookup_trace(dcontext, tag);
if (f == NULL && DYNAMO_OPTION(bb_ibl_targets)) {
/* Populate with bb's that are not trace heads */
f = fragment_lookup_bb(dcontext, tag);
/* We don't add trace heads OR when a trace is targetting a BB. In the
* latter case, the BB will shortly be marked as a trace head and
* removed from the IBT table so we don't needlessly add it.
*/
if (f != NULL &&
(TEST(FRAG_IS_TRACE_HEAD, f->flags) ||
TEST(FRAG_IS_TRACE, dcontext->last_fragment->flags))) {
/* XXX: change the logic if trace headness becomes a private property */
f = NULL; /* ignore fragment */
STATS_INC(num_ib_th_target); /* counted in num_ibt_cold_misses */
}
}
}
LOG(THREAD, LOG_FRAGMENT, 3,
"fragment_add_ibl_target tag " PFX ", branch %d, F%d %s\n", tag, branch_type,
f != NULL ? f->id : 0,
(f != NULL && TEST(FRAG_IS_TRACE, f->flags)) ? "existing trace" : "");
/* a valid IBT fragment exists */
if (f != NULL) {
ibl_table_t *ibl_table = GET_IBT_TABLE(pt, f->flags, branch_type);
DEBUG_DECLARE(fragment_entry_t *orig_lookuptable = NULL;)
fragment_entry_t current;
/* Make sure this thread's local ptrs & state is current in case a
* shared table resize occurred while it was in the cache. We update
* only during an IBL miss, since that's the first time that
* accessing the old table inflicted a cost (a context switch).
*/
/* NOTE We could be more aggressive and update the private ptrs for
* all tables, not just the one being added to, by calling
* update_all_private_ibt_table_ptrs(). We could be even more
* aggressive by updating all ptrs on every cache exit in
* enter_couldbelinking() but that could also prove to be more
* expensive by invoking the update logic when an IBL miss didn't
* occur. However, more frequent updates could lead to old tables
* being freed earlier. We can revisit this if we see old tables
* piling up and not being freed in a timely manner.
*/
update_private_ibt_table_ptrs(dcontext, ibl_table _IF_DEBUG(&orig_lookuptable));
/* We can't place a private fragment into a thread-shared table.
* Nothing prevents a sandboxed or ignore syscalls frag from being
* the target of an IB. This is covered by case 5836.
*
* We don't need to re-check in the add_ibl_target_helper because
* the shared/private property applies to all IBT tables -- either
* all are shared or none are.
*/
if (TEST(FRAG_TABLE_SHARED, ibl_table->table_flags) &&
!TEST(FRAG_SHARED, f->flags)) {
STATS_INC(num_ibt_shared_private_conflict);
return f;
}
ASSERT(TEST(FRAG_IS_TRACE, f->flags) ==
TEST(FRAG_TABLE_TRACE, ibl_table->table_flags));
/* We can't assert that an IBL target isn't a trace head due to a race
* between trace head marking and adding to a table. See the comments
* in fragment_add_to_hashtable().
*/
TABLE_RWLOCK(ibl_table, read, lock);
current = hashtable_ibl_lookup(dcontext, (ptr_uint_t)tag, ibl_table);
TABLE_RWLOCK(ibl_table, read, unlock);
/* Now that we set the fragment_t* for any unlinked entry to
* &unlinked_fragment -- regardless of why it was unlinked -- and also
* set the lookup table tag to FAKE_TAG, we should never find a fragment
* with the same tag and should never have an unlinked marker returned
* here.
*/
ASSERT(!IBL_ENTRY_IS_INVALID(current));
if (IBL_ENTRY_IS_EMPTY(current)) {
DOLOG(5, LOG_FRAGMENT, {
dump_lookuptable_tls(dcontext);
hashtable_ibl_dump_table(dcontext, ibl_table);
dump_lookup_table(dcontext, ibl_table);
});
fragment_add_ibl_target_helper(dcontext, f, ibl_table);
/* When using BB2BB IBL w/trace building, we add trace targets
* to the BB table. (We always add a trace target to the trace
* table.) We fool the helper routine into using the BB
* table by passing in a non-trace value for the flags argument.
*/
if (TEST(FRAG_IS_TRACE, f->flags) && DYNAMO_OPTION(bb_ibl_targets) &&
DYNAMO_OPTION(bb_ibt_table_includes_traces)) {
ibl_table_t *ibl_table_too =
GET_IBT_TABLE(pt, f->flags & ~FRAG_IS_TRACE, branch_type);
ASSERT(ibl_table_too != NULL);
ASSERT(!TEST(FRAG_TABLE_TRACE, ibl_table_too->table_flags));
/* Make sure this thread's local ptrs & state is up to
* date in case a resize occurred while it was in the cache. */
update_private_ibt_table_ptrs(dcontext, ibl_table_too _IF_DEBUG(NULL));
fragment_add_ibl_target_helper(dcontext, f, ibl_table_too);
}
} else {
DEBUG_DECLARE(const char *reason;)
#ifdef DEBUG
if (is_building_trace(dcontext)) {
reason = "trace building";
STATS_INC(num_ibt_exit_trace_building);
} else if (TEST(FRAG_WAS_DELETED, dcontext->last_fragment->flags)) {
reason = "src unlinked (frag deleted)";
STATS_INC(num_ibt_exit_src_unlinked_frag_deleted);
} else if (!TEST(LINK_LINKED, dcontext->last_exit->flags) &&
TESTALL(FRAG_SHARED | FRAG_IS_TRACE_HEAD,
dcontext->last_fragment->flags) &&
fragment_lookup_type(dcontext, dcontext->last_fragment->tag,
LOOKUP_TRACE | LOOKUP_SHARED) != NULL) {
/* Another thread unlinked src as part of replacing it with
* a new trace while this thread was in there (see case 5634
* for details) */
reason = "src unlinked (shadowed)";
STATS_INC(num_ibt_exit_src_unlinked_shadowed);
} else if (!INTERNAL_OPTION(ibl_sentinel_check) &&
is_fragment_index_wraparound(dcontext, ibl_table, f)) {
reason = "sentinel";
STATS_INC(num_ibt_leaks_likely_sentinel);
} else if (TEST(FRAG_SELFMOD_SANDBOXED, dcontext->last_fragment->flags)) {
reason = "src sandboxed";
STATS_INC(num_ibt_exit_src_sandboxed);
} else if (TEST(FRAG_TABLE_SHARED, ibl_table->table_flags) &&
orig_lookuptable != ibl_table->table) {
/* A table resize could cause a miss when the target is
* in the new table. */
reason = "shared IBT table resize";
STATS_INC(num_ibt_exit_shared_table_resize);
} else if (DYNAMO_OPTION(bb_ibl_targets) &&
IS_SHARED_SYSCALLS_LINKSTUB(dcontext->last_exit) &&
!DYNAMO_OPTION(disable_traces) && !TEST(FRAG_IS_TRACE, f->flags)) {
reason = "shared syscall exit cannot target BBs";
STATS_INC(num_ibt_exit_src_trace_shared_syscall);
} else if (DYNAMO_OPTION(bb_ibl_targets) && TEST(FRAG_IS_TRACE, f->flags) &&
!DYNAMO_OPTION(bb_ibt_table_includes_traces)) {
reason = "BBs do not target traces";
STATS_INC(num_ibt_exit_src_trace_shared_syscall);
} else if (!INTERNAL_OPTION(link_ibl)) {
reason = "-no_link_ibl prevents ibl";
STATS_INC(num_ibt_exit_nolink);
} else if (DYNAMO_OPTION(disable_traces) &&
!TEST(FRAG_LINKED_OUTGOING, dcontext->last_fragment->flags)) {
reason = "IBL fragment unlinked in signal handler";
STATS_INC(num_ibt_exit_src_unlinked_signal);
} else {
reason = "BAD leak?";
DOLOG(3, LOG_FRAGMENT, {
hashtable_ibl_dump_table(dcontext, ibl_table);
hashtable_ibl_study(dcontext, ibl_table, 0 /*table consistent*/);
});
STATS_INC(num_ibt_exit_unknown);
ASSERT_CURIOSITY_ONCE(false && "fragment_add_ibl_target unknown reason");
}
/* nothing to do, just sanity checking */
LOG(THREAD, LOG_FRAGMENT, 2,
"fragment_add_ibl_target tag " PFX ", F%d already added - %s\n", tag,
f->id, reason);
#endif
}
} else {
STATS_INC(num_ibt_cold_misses);
}
#ifdef HASHTABLE_STATISTICS
if (INTERNAL_OPTION(stay_on_trace_stats)) {
/* best effort: adjust for 32bit counter overflow occasionally
* we'll get a hashtable leak only when not INTERNAL_OPTION(ibl_sentinel_check)
*/
check_stay_on_trace_stats_overflow(dcontext, branch_type);
}
#endif /* HASHTABLE_STATISTICS */
DOLOG(4, LOG_FRAGMENT, { dump_lookuptable_tls(dcontext); });
return f;
}
/**********************************************************************/
/* FUTURE FRAGMENTS */
/* create a new fragment with empty prefix and return it
*/
static future_fragment_t *
fragment_create_future(dcontext_t *dcontext, app_pc tag, uint flags)
{
dcontext_t *alloc_dc = FRAGMENT_ALLOC_DC(dcontext, flags);
future_fragment_t *fut = (future_fragment_t *)nonpersistent_heap_alloc(
alloc_dc, sizeof(future_fragment_t) HEAPACCT(ACCT_FRAG_FUTURE));
ASSERT(!NEED_SHARED_LOCK(flags) || self_owns_recursive_lock(&change_linking_lock));
LOG(THREAD, LOG_FRAGMENT, 4, "Created future fragment " PFX " w/ flags 0x%08x\n", tag,
flags | FRAG_FAKE | FRAG_IS_FUTURE);
STATS_INC(num_future_fragments);
DOSTATS({
if (TEST(FRAG_SHARED, flags))
STATS_INC(num_shared_future_fragments);
});
fut->tag = tag;
fut->flags = flags | FRAG_FAKE | FRAG_IS_FUTURE;
fut->incoming_stubs = NULL;
return fut;
}
static void
fragment_free_future(dcontext_t *dcontext, future_fragment_t *fut)
{
dcontext_t *alloc_dc = FRAGMENT_ALLOC_DC(dcontext, fut->flags);
LOG(THREAD, LOG_FRAGMENT, 4, "Freeing future fragment " PFX "\n", fut->tag);
ASSERT(fut->incoming_stubs == NULL);
nonpersistent_heap_free(alloc_dc, fut,
sizeof(future_fragment_t) HEAPACCT(ACCT_FRAG_FUTURE));
}
future_fragment_t *
fragment_create_and_add_future(dcontext_t *dcontext, app_pc tag, uint flags)
{
per_thread_t *pt = GET_PT(dcontext);
future_fragment_t *fut = fragment_create_future(dcontext, tag, flags);
fragment_table_t *futtable = GET_FTABLE(pt, fut->flags);
ASSERT(!NEED_SHARED_LOCK(flags) || self_owns_recursive_lock(&change_linking_lock));
/* adding to the table is a write operation */
TABLE_RWLOCK(futtable, write, lock);
fragment_add_to_hashtable(dcontext, (fragment_t *)fut, futtable);
TABLE_RWLOCK(futtable, write, unlock);
return fut;
}
void
fragment_delete_future(dcontext_t *dcontext, future_fragment_t *fut)
{
per_thread_t *pt = GET_PT(dcontext);
fragment_table_t *futtable = GET_FTABLE(pt, fut->flags);
ASSERT(!NEED_SHARED_LOCK(fut->flags) ||
self_owns_recursive_lock(&change_linking_lock));
/* removing from the table is a write operation */
TABLE_RWLOCK(futtable, write, lock);
hashtable_fragment_remove((fragment_t *)fut, futtable);
TABLE_RWLOCK(futtable, write, unlock);
fragment_free_future(dcontext, fut);
}
/* We do not want to remove futures from a flushed region if they have
* incoming links (i#609).
*/
static bool
fragment_delete_future_filter(fragment_t *f)
{
future_fragment_t *fut = (future_fragment_t *)f;
ASSERT(TEST(FRAG_IS_FUTURE, f->flags));
return (fut->incoming_stubs == NULL);
}
static uint
fragment_delete_futures_in_region(dcontext_t *dcontext, app_pc start, app_pc end)
{
per_thread_t *pt = GET_PT(dcontext);
uint flags = FRAG_IS_FUTURE | (dcontext == GLOBAL_DCONTEXT ? FRAG_SHARED : 0);
fragment_table_t *futtable = GET_FTABLE(pt, flags);
uint removed;
/* Higher-level lock needed since we do lookup+add w/o holding table lock between */
ASSERT(!NEED_SHARED_LOCK(flags) || self_owns_recursive_lock(&change_linking_lock));
TABLE_RWLOCK(futtable, write, lock);
removed =
hashtable_fragment_range_remove(dcontext, futtable, (ptr_uint_t)start,
(ptr_uint_t)end, fragment_delete_future_filter);
TABLE_RWLOCK(futtable, write, unlock);
return removed;
}
future_fragment_t *
fragment_lookup_future(dcontext_t *dcontext, app_pc tag)
{
/* default is to lookup shared, since private only sometimes exists,
* and often only care about trace head, for which always use shared
*/
uint flags = SHARED_FRAGMENTS_ENABLED() ? FRAG_SHARED : 0;
per_thread_t *pt = GET_PT(dcontext);
fragment_table_t *futtable = GET_FTABLE(pt, FRAG_IS_FUTURE | flags);
fragment_t *f;
TABLE_RWLOCK(futtable, read, lock);
f = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag, futtable);
TABLE_RWLOCK(futtable, read, unlock);
if (f != &null_fragment)
return (future_fragment_t *)f;
return NULL;
}
future_fragment_t *
fragment_lookup_private_future(dcontext_t *dcontext, app_pc tag)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
fragment_table_t *futtable = GET_FTABLE(pt, FRAG_IS_FUTURE);
fragment_t *f = hashtable_fragment_lookup(dcontext, (ptr_uint_t)tag, futtable);
if (f != &null_fragment)
return (future_fragment_t *)f;
return NULL;
}
/* END FUTURE FRAGMENTS
**********************************************************************/
#if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH)
/* FIXME: move to rct.c when we move the whole app_pc table there */
# define STATS_RCT_ADD(which, stat, val) \
DOSTATS({ \
if ((which) == RCT_RAC) \
STATS_ADD(rac_##stat, val); \
else \
STATS_ADD(rct_##stat, val); \
})
static inline bool
rct_is_global_table(rct_module_table_t *permod)
{
return (permod == &rac_non_module_table ||
IF_UNIX_ELSE(permod == &rct_global_table, false));
}
static inline rct_module_table_t *
rct_get_table(app_pc tag, rct_type_t which)
{
rct_module_table_t *permod = os_module_get_rct_htable(tag, which);
if (permod == NULL) { /* not a module */
if (which == RCT_RAC)
permod = &rac_non_module_table;
}
return permod;
}
/* returns NULL if not found */
static app_pc
rct_table_lookup_internal(dcontext_t *dcontext, app_pc tag, rct_module_table_t *permod)
{
app_pc actag = NULL;
ASSERT(os_get_module_info_locked());
if (permod != NULL) {
/* Check persisted table first as it's likely to be larger and
* it needs no read lock
*/
if (permod->persisted_table != NULL) {
actag = hashtable_app_pc_rlookup(dcontext, (ptr_uint_t)tag,
permod->persisted_table);
}
if (actag == NULL && permod->live_table != NULL) {
actag =
hashtable_app_pc_rlookup(dcontext, (ptr_uint_t)tag, permod->live_table);
}
}
return actag;
}
/* returns NULL if not found */
static app_pc
rct_table_lookup(dcontext_t *dcontext, app_pc tag, rct_type_t which)
{
app_pc actag = NULL;
rct_module_table_t *permod;
ASSERT(which >= 0 && which < RCT_NUM_TYPES);
os_get_module_info_lock();
permod = rct_get_table(tag, which);
actag = rct_table_lookup_internal(dcontext, tag, permod);
os_get_module_info_unlock();
return actag;
}
/* Caller must hold the higher-level lock.
* Returns whether added a new entry or not.
*/
static bool
rct_table_add(dcontext_t *dcontext, app_pc tag, rct_type_t which)
{
rct_module_table_t *permod;
/* we use a higher-level lock to synchronize the lookup + add
* combination with other simultaneous adds as well as with removals
*/
/* FIXME We could use just the table lock for the lookup+add. This is cleaner
* than using another lock during the entire routine and acquiring & releasing
* the table lock in read mode for the lookup and then acquiring & releasing
* it again in write mode for the add. Also, any writes to the table outside
* of this routine would be blocked (as is desired). The down side is that
* reads would be blocked during the entire operation.
* The #ifdef DEBUG lookup would need to be moved to after the table lock
* is released to avoid a rank order violation (all table locks have the
* same rank). That's not problematic since it's only stat code.
*/
/* If we no longer hold this high-level lock for adds+removes we need
* to hold the new add/remove lock across persist_size->persist
*/
ASSERT_OWN_MUTEX(true, (which == RCT_RAC ? &after_call_lock : &rct_module_lock));
os_get_module_info_lock();
permod = rct_get_table(tag, which);
/* Xref case 9717, on a partial image mapping we may try to add locations
* (specifically the entry point) that our outside of any module. Technically this
* is also possible on a full mapping since we've seen entry points redirected
* (and there's nothing requiring that they be re-directed to another dll or, if
* at dr init, that we've already processed that target module, xref case 10693. */
ASSERT_CURIOSITY(permod != NULL || EXEMPT_TEST("win32.partial_map.exe"));
if (permod == NULL || rct_table_lookup_internal(dcontext, tag, permod) != NULL) {
os_get_module_info_unlock();
return false;
}
if (permod->live_table == NULL) {
/* lazily initialized */
if (rct_is_global_table(permod))
SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT);
permod->live_table =
HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, app_pc_table_t, ACCT_AFTER_CALL, PROTECTED);
if (rct_is_global_table(permod)) {
/* For global tables we would have to move to heap, or
* else unprot every time, to maintain min and max: but
* the min-max optimization isn't going to help global
* tables so we just don't bother.
*/
permod->live_min = NULL;
permod->live_max = (app_pc)POINTER_MAX;
SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT);
}
hashtable_app_pc_init(
GLOBAL_DCONTEXT, permod->live_table,
which == RCT_RAC ? INIT_HTABLE_SIZE_AFTER_CALL : INIT_HTABLE_SIZE_RCT_IBT,
which == RCT_RAC ? DYNAMO_OPTION(shared_after_call_load)
: DYNAMO_OPTION(global_rct_ind_br_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
(SHARED_FRAGMENTS_ENABLED() ? HASHTABLE_ENTRY_SHARED : 0) | HASHTABLE_SHARED |
HASHTABLE_PERSISTENT
/* I'm seeing a number of high-ave-collision
* cases on both rac and rct; there's no easy
* way to estimate final size, so going to
* relax a little as not perf-critical */
| HASHTABLE_RELAX_CLUSTER_CHECKS _IF_DEBUG(
which == RCT_RAC ? "after_call_targets" : "rct_ind_targets"));
STATS_RCT_ADD(which, live_tables, 1);
}
ASSERT(permod->live_table != NULL);
/* adding is a write operation */
TABLE_RWLOCK(permod->live_table, write, lock);
hashtable_app_pc_add(dcontext, tag, permod->live_table);
TABLE_RWLOCK(permod->live_table, write, unlock);
/* case 7628: used for persistence optimization: but watch overhead */
if (!rct_is_global_table(permod)) {
/* See comments above */
if (permod->live_min == NULL || tag < permod->live_min)
permod->live_min = tag;
if (tag > permod->live_max)
permod->live_max = tag;
}
os_get_module_info_unlock();
STATS_RCT_ADD(which, live_entries, 1);
DOSTATS({
if (permod == &rac_non_module_table)
STATS_INC(rac_non_module_entries);
});
return true;
}
static void
rct_table_flush_entry(dcontext_t *dcontext, app_pc tag, rct_type_t which)
{
rct_module_table_t *permod;
/* need higher level lock to properly synchronize with lookup+add */
ASSERT_OWN_MUTEX(true, (which == RCT_RAC ? &after_call_lock : &rct_module_lock));
os_get_module_info_lock();
permod = rct_get_table(tag, which);
ASSERT(permod != NULL);
/* We should have removed any persist info before calling this routine */
ASSERT(permod->persisted_table == NULL);
ASSERT(permod->live_table != NULL);
if (permod->live_table != NULL) {
/* removing is a write operation */
TABLE_RWLOCK(permod->live_table, write, lock);
hashtable_app_pc_remove(tag, permod->live_table);
TABLE_RWLOCK(permod->live_table, write, unlock);
}
os_get_module_info_unlock();
}
/* Invalidates all after call or indirect branch targets from given
* range [text_start,text_end) which must be either completely
* contained in a single module or not touch any modules.
* Assuming any existing fragments that were added to IBL tables will
* be flushed independently: this routine only flushes the policy
* information.
* Note this needs to be called on app_memory_deallocation() for RAC
* (potentially from DGC), and rct_process_module_mmap() for other RCT
* entries which should be only in modules.
*
* Returns entries flushed.
*/
static uint
rct_table_invalidate_range(dcontext_t *dcontext, rct_type_t which, app_pc text_start,
app_pc text_end)
{
uint entries_removed = 0;
rct_module_table_t *permod;
/* need higher level lock to properly synchronize with lookup+add */
ASSERT_OWN_MUTEX(true, (which == RCT_RAC ? &after_call_lock : &rct_module_lock));
ASSERT(text_start < text_end);
if (DYNAMO_OPTION(rct_sticky)) {
/* case 5329 - leaving for bug-compatibility with previous releases */
/* trade-off is spurious RCT violations vs memory leak */
return 0;
}
/* We only support removing from within a single module or not touching
* any modules */
ASSERT(get_module_base(text_start) == get_module_base(text_end));
os_get_module_info_lock();
permod = rct_get_table(text_start, which);
ASSERT(permod != NULL);
/* We should have removed any persist info before calling this routine */
ASSERT(permod->persisted_table == NULL);
ASSERT(permod->live_table != NULL);
if (permod != NULL && permod->live_table != NULL) {
TABLE_RWLOCK(permod->live_table, write, lock);
entries_removed = hashtable_app_pc_range_remove(dcontext, permod->live_table,
(ptr_uint_t)text_start,
(ptr_uint_t)text_end, NULL);
DOCHECK(1, {
uint second_pass = hashtable_app_pc_range_remove(dcontext, permod->live_table,
(ptr_uint_t)text_start,
(ptr_uint_t)text_end, NULL);
ASSERT(second_pass == 0 && "nothing should be missed");
/* simplest sanity check that hashtable_app_pc_range_remove() works */
});
TABLE_RWLOCK(permod->live_table, write, unlock);
}
os_get_module_info_unlock();
return entries_removed;
}
static void
rct_table_free_internal(dcontext_t *dcontext, app_pc_table_t *table)
{
hashtable_app_pc_free(dcontext, table);
ASSERT(TEST(HASHTABLE_PERSISTENT, table->table_flags));
HEAP_TYPE_FREE(dcontext, table, app_pc_table_t, ACCT_AFTER_CALL, PROTECTED);
}
void
rct_table_free(dcontext_t *dcontext, app_pc_table_t *table, bool free_data)
{
DODEBUG({
DOLOG(1, LOG_FRAGMENT | LOG_STATS,
{ hashtable_app_pc_load_statistics(dcontext, table); });
hashtable_app_pc_study(dcontext, table, 0 /*table consistent*/);
});
if (!free_data) {
/* We don't need the free_data param anymore */
ASSERT(table->table_unaligned == NULL); /* don't try to free, part of mmap */
}
rct_table_free_internal(GLOBAL_DCONTEXT, table);
}
app_pc_table_t *
rct_table_copy(dcontext_t *dcontext, app_pc_table_t *src)
{
if (src == NULL)
return NULL;
else
return hashtable_app_pc_copy(GLOBAL_DCONTEXT, src);
}
app_pc_table_t *
rct_table_merge(dcontext_t *dcontext, app_pc_table_t *src1, app_pc_table_t *src2)
{
if (src1 == NULL) {
if (src2 == NULL)
return NULL;
return hashtable_app_pc_copy(GLOBAL_DCONTEXT, src2);
} else if (src2 == NULL)
return hashtable_app_pc_copy(GLOBAL_DCONTEXT, src1);
else
return hashtable_app_pc_merge(GLOBAL_DCONTEXT, src1, src2);
}
/* Up to caller to synchronize access to table. */
uint
rct_table_persist_size(dcontext_t *dcontext, app_pc_table_t *table)
{
/* Don't persist zero-entry tables */
if (table == NULL || table->entries == 0)
return 0;
else
return hashtable_app_pc_persist_size(dcontext, table);
}
/* Up to caller to synchronize access to table.
* Returns true iff all writes succeeded.
*/
bool
rct_table_persist(dcontext_t *dcontext, app_pc_table_t *table, file_t fd)
{
bool success = true;
ASSERT(fd != INVALID_FILE);
ASSERT(table != NULL); /* caller shouldn't call us o/w */
if (table != NULL)
success = hashtable_app_pc_persist(dcontext, table, fd);
return success;
}
app_pc_table_t *
rct_table_resurrect(dcontext_t *dcontext, byte *mapped_table, rct_type_t which)
{
return hashtable_app_pc_resurrect(GLOBAL_DCONTEXT,
mapped_table _IF_DEBUG(which == RCT_RAC
? "after_call_targets"
: "rct_ind_targets"));
}
void
rct_module_table_free(dcontext_t *dcontext, rct_module_table_t *permod, app_pc modpc)
{
ASSERT(os_get_module_info_locked());
if (permod->live_table != NULL) {
rct_table_free(GLOBAL_DCONTEXT, permod->live_table, true);
permod->live_table = NULL;
}
if (permod->persisted_table != NULL) {
/* persisted table: table data is from disk, but header is on heap */
rct_table_free(GLOBAL_DCONTEXT, permod->persisted_table, false);
permod->persisted_table = NULL;
/* coarse_info_t has a duplicated pointer to the persisted table,
* but it should always be flushed before we get here
*/
ASSERT(get_executable_area_coarse_info(modpc) == NULL);
}
}
void
rct_module_table_persisted_invalidate(dcontext_t *dcontext, app_pc modpc)
{
rct_module_table_t *permod;
uint i;
os_get_module_info_lock();
for (i = 0; i < RCT_NUM_TYPES; i++) {
permod = rct_get_table(modpc, i);
ASSERT(permod != NULL);
if (permod != NULL && permod->persisted_table != NULL) {
/* If the persisted table contains entries beyond what we will discover
* when we re-build its cache we must transfer those to the live table
* now. At first I was only keeping entire-module RCT entries, but we
* must keep all RAC and RCT entries since we may not see the triggering
* code before we hit the check point (may reset at a ret so we won't see
* the call before the ret check; same for Borland SEH). We can only not
* keep them on a module unload.
*/
/* Optimization: don't transfer if about to unload. This assumes
* there will be no persistence of a later coarse unit in a different
* region of the same module, which case 9651 primary_for_module
* currently ensures! (We already have read lock; ok to grab again.)
*/
if (!os_module_get_flag(modpc, MODULE_BEING_UNLOADED) && !dynamo_exited) {
/* FIXME case 10362: we could leave the file mapped in and
* use the persisted RCT table independently of the cache
*/
/* Merging will remove any dups, though today we never re-load
* pcaches so there shouldn't be any
*/
app_pc_table_t *merged =
/* all modinfo RCT tables are on global heap */
rct_table_merge(GLOBAL_DCONTEXT, permod->live_table,
permod->persisted_table);
if (permod->live_table != NULL)
rct_table_free(GLOBAL_DCONTEXT, permod->live_table, true);
permod->live_table = merged;
LOG(THREAD, LOG_FRAGMENT, 2,
"rct_module_table_persisted_invalidate " PFX ": not unload, so "
"moving persisted %d entries to live table\n",
modpc, permod->persisted_table->entries);
# ifdef WINDOWS
/* We leave the MODULE_RCT_LOADED flag */
# endif
STATS_INC(rct_persisted_outlast_cache);
}
/* we rely on coarse_unit_reset_free() freeing the persisted table struct */
permod->persisted_table = NULL;
}
}
os_get_module_info_unlock();
}
/* Produces a new hashtable that contains all entries in the live and persisted
* tables for the module containing modpc that are within [limit_start, limit_end)
*/
app_pc_table_t *
rct_module_table_copy(dcontext_t *dcontext, app_pc modpc, rct_type_t which,
app_pc limit_start, app_pc limit_end)
{
app_pc_table_t *merged = NULL;
rct_module_table_t *permod;
mutex_t *lock = (which == RCT_RAC) ? &after_call_lock : &rct_module_lock;
d_r_mutex_lock(lock);
if (which == RCT_RAC) {
ASSERT(DYNAMO_OPTION(ret_after_call));
if (!DYNAMO_OPTION(ret_after_call))
return NULL;
} else {
ASSERT(TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_call)) ||
TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_jump)));
if (!TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_call)) &&
!TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_jump)))
return NULL;
}
os_get_module_info_lock();
permod = rct_get_table(modpc, which);
ASSERT(permod != NULL);
if (permod != NULL) {
/* FIXME: we could pass the limit range down to hashtable_app_pc_{copy,merge}
* for more efficiency and to avoid over-sizing the table, but this
* should be rare w/ -persist_rct_entire and single-+x-section modules
*/
merged = rct_table_merge(dcontext, permod->live_table, permod->persisted_table);
if (merged != NULL) {
DEBUG_DECLARE(uint removed = 0;)
TABLE_RWLOCK(merged, write, lock);
if (limit_start > permod->live_min) {
DEBUG_DECLARE(removed +=)
hashtable_app_pc_range_remove(dcontext, merged,
(ptr_uint_t)permod->live_min,
(ptr_uint_t)limit_start, NULL);
}
if (limit_end <= permod->live_max) {
DEBUG_DECLARE(removed +=)
hashtable_app_pc_range_remove(dcontext, merged, (ptr_uint_t)limit_end,
(ptr_uint_t)permod->live_max + 1, NULL);
}
TABLE_RWLOCK(merged, write, unlock);
STATS_RCT_ADD(which, module_persist_out_of_range, removed);
}
}
os_get_module_info_unlock();
d_r_mutex_unlock(lock);
return merged;
}
/* We return the persisted table so we can keep a pointer to it in the
* loaded coarse_info_t, but we must be careful to do a coordinated
* free of the duplicated pointer.
*/
bool
rct_module_table_set(dcontext_t *dcontext, app_pc modpc, app_pc_table_t *table,
rct_type_t which)
{
rct_module_table_t *permod;
bool used = false;
mutex_t *lock = (which == RCT_RAC) ? &after_call_lock : &rct_module_lock;
d_r_mutex_lock(lock);
os_get_module_info_lock();
permod = rct_get_table(modpc, which);
ASSERT(permod != NULL);
ASSERT(permod->persisted_table == NULL); /* can't resurrect twice */
ASSERT(table != NULL);
/* Case 9834: avoid double-add from earlier entire-module resurrect */
ASSERT(which == RCT_RAC || !os_module_get_flag(modpc, MODULE_RCT_LOADED));
/* FIXME case 8648: we're loosening security by allowing ret to target any
* after-call executed in any prior run of this app or whatever
* app is producing, instead of just this run.
*/
if (permod != NULL && permod->persisted_table == NULL) {
used = true;
/* There could be dups in persisted table that are already in
* live table (particularly from unloading and re-loading a pcache,
* though that never happens today). Everything should work fine,
* and if we do unload the pcache prior to module unload the merge
* into the live entries will remove the dups.
*/
permod->persisted_table = table;
ASSERT(permod->persisted_table->entries > 0);
/* FIXME: for case 9639 if we had the ibl table set up (say, for shared
* ibl tables) and stored the cache pc (though I guess coarse htable is
* set up) we could fill the ibl table here as well (but then we'd
* have to abort for hotp conflicts earlier in coarse_unit_load()).
* Instead we delay and do it in rac_persisted_fill_ibl().
*/
LOG(THREAD, LOG_FRAGMENT, 2, "rct_module_table_resurrect: added %d %s entries\n",
permod->persisted_table->entries, which == RCT_RAC ? "RAC" : "RCT");
STATS_RCT_ADD(which, persisted_tables, 1);
STATS_RCT_ADD(which, persisted_entries, permod->persisted_table->entries);
}
os_get_module_info_unlock();
d_r_mutex_unlock(lock);
return used;
}
bool
rct_module_persisted_table_exists(dcontext_t *dcontext, app_pc modpc, rct_type_t which)
{
bool exists = false;
rct_module_table_t *permod;
os_get_module_info_lock();
permod = rct_get_table(modpc, which);
exists = (permod != NULL && permod->persisted_table != NULL);
os_get_module_info_unlock();
return exists;
}
uint
rct_module_live_entries(dcontext_t *dcontext, app_pc modpc, rct_type_t which)
{
uint entries = 0;
rct_module_table_t *permod;
os_get_module_info_lock();
permod = rct_get_table(modpc, which);
if (permod != NULL && permod->live_table != NULL)
entries = permod->live_table->entries;
os_get_module_info_unlock();
return entries;
}
static void
coarse_persisted_fill_ibl_helper(dcontext_t *dcontext, ibl_table_t *ibl_table,
coarse_info_t *info, app_pc_table_t *ptable,
ibl_branch_type_t branch_type)
{
uint i;
fragment_t wrapper;
app_pc tag;
cache_pc body_pc;
DEBUG_DECLARE(uint added = 0;)
ASSERT(ptable != NULL);
if (ptable == NULL)
return;
ASSERT(os_get_module_info_locked());
/* Make sure this thread's local ptrs & state are up to
* date in case a resize occurred while it was in the cache. */
update_private_ibt_table_ptrs(dcontext, ibl_table _IF_DEBUG(NULL));
/* Avoid hash collision asserts while adding by sizing up front;
* FIXME: we may over-size for INDJMP table
*/
TABLE_RWLOCK(ibl_table, write, lock);
hashtable_ibl_check_size(dcontext, ibl_table, 0, ptable->entries);
TABLE_RWLOCK(ibl_table, write, unlock);
/* FIXME: we should hold ptable's read lock but it's lower ranked
* than the fragment table's lock, so we rely on os module lock
*/
for (i = 0; i < ptable->capacity; i++) {
tag = ptable->table[i];
if (APP_PC_ENTRY_IS_REAL(tag)) {
/* FIXME: should we persist the cache pcs to save time here? That won't
* be ideal if we ever use the mmapped table directly (for per-module
* tables: case 9672). We could support both tag-only and tag-cache
* pairs by having the 1st entry be a flags word.
*/
fragment_coarse_lookup_in_unit(dcontext, info, tag, NULL, &body_pc);
/* may not be present, given no checks in rct_entries_in_region() */
if (body_pc != NULL &&
/* We can have same entry in both RAC and RCT table, and we use
* both tables to fill the INDJMP table
*/
(branch_type != IBL_INDJMP ||
!IBL_ENTRY_IS_EMPTY(
hashtable_ibl_lookup(dcontext, (ptr_uint_t)tag, ibl_table)))) {
fragment_coarse_wrapper(&wrapper, tag, body_pc);
fragment_add_ibl_target_helper(dcontext, &wrapper, ibl_table);
DOSTATS({ added++; });
}
}
}
LOG(THREAD, LOG_FRAGMENT, 2, "coarse_persisted_fill_ibl %s: added %d of %d entries\n",
get_branch_type_name(branch_type), added, ptable->entries);
STATS_ADD(perscache_ibl_prefill, added);
}
/* Case 9639: fill ibl table from persisted RAC/RCT table entries */
static void
coarse_persisted_fill_ibl(dcontext_t *dcontext, coarse_info_t *info,
ibl_branch_type_t branch_type)
{
per_thread_t *pt = GET_PT(dcontext);
ibl_table_t *ibl_table;
rct_module_table_t *permod;
/* Caller must hold info lock */
ASSERT_OWN_MUTEX(true, &info->lock);
ASSERT(exists_coarse_ibl_pending_table(dcontext, info, branch_type));
ASSERT(TEST(COARSE_FILL_IBL_MASK(branch_type), DYNAMO_OPTION(coarse_fill_ibl)));
if (!exists_coarse_ibl_pending_table(dcontext, info, branch_type))
return;
os_get_module_info_lock();
ibl_table = GET_IBT_TABLE(pt, FRAG_SHARED | FRAG_COARSE_GRAIN, branch_type);
if (branch_type == IBL_RETURN || branch_type == IBL_INDJMP) {
permod = rct_get_table(info->base_pc, RCT_RAC);
ASSERT(permod != NULL && permod->persisted_table != NULL);
if (permod != NULL && permod->persisted_table != NULL) {
LOG(THREAD, LOG_FRAGMENT, 2,
"coarse_persisted_fill_ibl %s: adding RAC %d entries\n",
get_branch_type_name(branch_type), permod->persisted_table->entries);
coarse_persisted_fill_ibl_helper(dcontext, ibl_table, info,
permod->persisted_table, branch_type);
}
}
if (branch_type == IBL_INDCALL || branch_type == IBL_INDJMP) {
permod = rct_get_table(info->base_pc, RCT_RCT);
ASSERT(permod != NULL && permod->persisted_table != NULL);
if (permod != NULL && permod->persisted_table != NULL) {
LOG(THREAD, LOG_FRAGMENT, 2,
"coarse_persisted_fill_ibl %s: adding RCT %d entries\n",
get_branch_type_name(branch_type), permod->persisted_table->entries);
coarse_persisted_fill_ibl_helper(dcontext, ibl_table, info,
permod->persisted_table, branch_type);
}
}
os_get_module_info_unlock();
/* We only fill for the 1st thread (if using per-thread ibl
* tables). We'd need per-thread flags to do otherwise, and the
* goal is only to help startup performance.
* FIXME case 9639: later threads may do startup work in various apps,
* and we may want a better solution here.
*/
info->ibl_pending_used |= COARSE_FILL_IBL_MASK(branch_type);
}
#endif /* defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH) */
#ifdef RETURN_AFTER_CALL
/* returns NULL if not found */
app_pc
fragment_after_call_lookup(dcontext_t *dcontext, app_pc tag)
{
return rct_table_lookup(dcontext, tag, RCT_RAC);
}
void
fragment_add_after_call(dcontext_t *dcontext, app_pc tag)
{
d_r_mutex_lock(&after_call_lock);
if (!rct_table_add(dcontext, tag, RCT_RAC))
STATS_INC(num_existing_after_call);
else
STATS_INC(num_future_after_call);
d_r_mutex_unlock(&after_call_lock);
}
/* flushing a fragment invalidates the after call entry */
void
fragment_flush_after_call(dcontext_t *dcontext, app_pc tag)
{
d_r_mutex_lock(&after_call_lock);
rct_table_flush_entry(dcontext, tag, RCT_RAC);
d_r_mutex_unlock(&after_call_lock);
STATS_INC(num_future_after_call_removed);
STATS_DEC(num_future_after_call);
}
/* see comments in rct_table_invalidate_range() */
uint
invalidate_after_call_target_range(dcontext_t *dcontext, app_pc text_start,
app_pc text_end)
{
uint entries_removed;
d_r_mutex_lock(&after_call_lock);
entries_removed = rct_table_invalidate_range(dcontext, RCT_RAC, text_start, text_end);
d_r_mutex_unlock(&after_call_lock);
STATS_ADD(num_future_after_call_removed, entries_removed);
STATS_SUB(num_future_after_call, entries_removed);
LOG(THREAD, LOG_FRAGMENT, 2,
"invalidate_rct_target_range " PFX "-" PFX ": removed %d entries\n", text_start,
text_end, entries_removed);
return entries_removed;
}
#endif /* RETURN_AFTER_CALL */
/***********************************************************************/
#ifdef RCT_IND_BRANCH
/*
* RCT indirect branch policy bookkeeping. Mostly a set of wrappers
* around the basic hashtable functionality.
*
* FIXME: all of these routines should be moved to rct.c after we move
* the hashtable primitives to fragment.h as static inline's
*/
/* returns NULL if not found */
app_pc
rct_ind_branch_target_lookup(dcontext_t *dcontext, app_pc tag)
{
return rct_table_lookup(dcontext, tag, RCT_RCT);
}
/* returns true if a new entry for target was added,
* or false if target was already known
*/
/* Note - entries are expected to be within MEM_IMAGE */
bool
rct_add_valid_ind_branch_target(dcontext_t *dcontext, app_pc tag)
{
ASSERT_OWN_MUTEX(true, &rct_module_lock);
DOLOG(2, LOG_FRAGMENT,
{
/* FIXME: would be nice to add a heavy weight check that we're
* really only a PE IMAGE via is_in_code_section()
*/
});
if (!rct_table_add(dcontext, tag, RCT_RCT))
return false;
else {
STATS_INC(rct_ind_branch_entries);
return true; /* new entry */
}
}
/* invalidate an indirect branch target and free any associated memory */
/* FIXME: note that this is currently not used and
* invalidate_ind_branch_target_range() will be the likely method to
* use for most cases when a whole module range is invalidated.
*/
void
rct_flush_ind_branch_target_entry(dcontext_t *dcontext, app_pc tag)
{
ASSERT_OWN_MUTEX(true, &rct_module_lock); /* synch with adding */
rct_table_flush_entry(dcontext, tag, RCT_RCT);
STATS_DEC(rct_ind_branch_entries);
STATS_INC(rct_ind_branch_entries_removed);
}
/* see comments in rct_table_invalidate_range() */
uint
invalidate_ind_branch_target_range(dcontext_t *dcontext, app_pc text_start,
app_pc text_end)
{
uint entries_removed;
ASSERT_OWN_MUTEX(true, &rct_module_lock); /* synch with adding */
entries_removed = rct_table_invalidate_range(dcontext, RCT_RCT, text_start, text_end);
STATS_ADD(rct_ind_branch_entries_removed, entries_removed);
STATS_SUB(rct_ind_branch_entries, entries_removed);
return entries_removed;
}
#endif /* RCT_IND_BRANCH */
/****************************************************************************/
/* CACHE CONSISTENCY */
/* Handle exits from the cache from our self-modifying code sandboxing
* instrumentation.
*/
void
fragment_self_write(dcontext_t *dcontext)
{
ASSERT(!is_self_couldbelinking());
/* need to delete just this fragment, then start interpreting
* at the instr after the self-write instruction
*/
dcontext->next_tag =
EXIT_TARGET_TAG(dcontext, dcontext->last_fragment, dcontext->last_exit);
LOG(THREAD, LOG_ALL, 2, "Sandboxing exit from fragment " PFX " @" PFX "\n",
dcontext->last_fragment->tag,
EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit));
LOG(THREAD, LOG_ALL, 2, "\tset next_tag to " PFX "\n", dcontext->next_tag);
/* We come in here both for actual selfmod and for exec count thresholds,
* to avoid needing separate LINK_ flags.
*/
if (DYNAMO_OPTION(sandbox2ro_threshold) > 0) {
if (vm_area_selfmod_check_clear_exec_count(dcontext, dcontext->last_fragment)) {
/* vm_area_* deleted this fragment by flushing so nothing more to do */
return;
}
}
LOG(THREAD, LOG_ALL, 1, "WARNING: fragment " PFX " @" PFX " overwrote its own code\n",
dcontext->last_fragment->tag,
EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit));
STATS_INC(num_self_writes);
if (TEST(FRAG_WAS_DELETED, dcontext->last_fragment->flags)) {
/* Case 8177: case 3559 unionized fragment_t.in_xlate, so we cannot delete a
* fragment that has already been unlinked in the first stage of a flush.
* The flush queue check, which comes after this (b/c we want to be
* nolinking), will delete.
*/
ASSERT(((per_thread_t *)dcontext->fragment_field)->flush_queue_nonempty);
STATS_INC(num_self_writes_after_flushes);
} else {
#ifdef PROGRAM_SHEPHERDING
/* we can't call fragment_delete if vm_area_t deletes it by flushing */
if (!vm_area_fragment_self_write(dcontext, dcontext->last_fragment->tag)) {
#endif
fragment_delete(dcontext, dcontext->last_fragment, FRAGDEL_ALL);
STATS_INC(num_fragments_deleted_selfmod);
#ifdef PROGRAM_SHEPHERDING
}
#endif
}
}
/* coarse_grain says to use just the min_pc and max_pc of f.
* otherwise a full walk of the original code is done to see if
* any piece of the fragment really does overlap.
* returns the tag of the bb that actually overlaps (i.e., finds the
* component bb of a trace that does the overlapping).
*/
bool
fragment_overlaps(dcontext_t *dcontext, fragment_t *f, byte *region_start,
byte *region_end, bool coarse_grain, overlap_info_t *info_res,
app_pc *bb_tag)
{
overlap_info_t info;
info.overlap = false;
if ((f->flags & FRAG_IS_TRACE) != 0) {
uint i;
trace_only_t *t = TRACE_FIELDS(f);
/* look through all blocks making up the trace */
ASSERT(t->bbs != NULL);
/* trace should have at least one bb */
ASSERT(t->num_bbs > 0);
for (i = 0; i < t->num_bbs; i++) {
if (app_bb_overlaps(dcontext, t->bbs[i].tag, f->flags, region_start,
region_end, &info)) {
if (bb_tag != NULL)
*bb_tag = t->bbs[i].tag;
break;
}
}
} else {
app_bb_overlaps(dcontext, f->tag, f->flags, region_start, region_end, &info);
if (info.overlap && bb_tag != NULL)
*bb_tag = f->tag;
}
if (info_res != NULL)
*info_res = info;
return info.overlap;
}
#ifdef DEBUG
void
study_all_hashtables(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
if (!DYNAMO_OPTION(disable_traces)) {
per_thread_t *ibl_pt = pt;
if (DYNAMO_OPTION(shared_trace_ibt_tables))
ibl_pt = shared_pt;
hashtable_ibl_study(dcontext, &ibl_pt->trace_ibt[branch_type],
0 /*table consistent*/);
}
if (DYNAMO_OPTION(bb_ibl_targets)) {
per_thread_t *ibl_pt = pt;
if (DYNAMO_OPTION(shared_bb_ibt_tables))
ibl_pt = shared_pt;
hashtable_ibl_study(dcontext, &ibl_pt->bb_ibt[branch_type],
0 /*table consistent*/);
}
}
if (PRIVATE_TRACES_ENABLED())
hashtable_fragment_study(dcontext, &pt->trace, 0 /*table consistent*/);
hashtable_fragment_study(dcontext, &pt->bb, 0 /*table consistent*/);
hashtable_fragment_study(dcontext, &pt->future, 0 /*table consistent*/);
if (DYNAMO_OPTION(shared_bbs))
hashtable_fragment_study(dcontext, shared_bb, 0 /*table consistent*/);
if (DYNAMO_OPTION(shared_traces))
hashtable_fragment_study(dcontext, shared_trace, 0 /*table consistent*/);
if (SHARED_FRAGMENTS_ENABLED())
hashtable_fragment_study(dcontext, shared_future, 0 /*table consistent*/);
# ifdef RETURN_AFTER_CALL
if (dynamo_options.ret_after_call && rac_non_module_table.live_table != NULL) {
hashtable_app_pc_study(dcontext, rac_non_module_table.live_table,
0 /*table consistent*/);
}
# endif
# if defined(RCT_IND_BRANCH) && defined(UNIX)
if ((TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_call)) ||
TEST(OPTION_ENABLED, DYNAMO_OPTION(rct_ind_jump))) &&
rct_global_table.live_table != NULL) {
hashtable_app_pc_study(dcontext, rct_global_table.live_table,
0 /*table consistent*/);
}
# endif /* RCT_IND_BRANCH */
# if defined(WIN32) && (defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH))
{
module_iterator_t *mi = module_iterator_start();
uint i;
rct_module_table_t *permod;
while (module_iterator_hasnext(mi)) {
module_area_t *data = module_iterator_next(mi);
for (i = 0; i < RCT_NUM_TYPES; i++) {
permod = os_module_get_rct_htable(data->start, i);
ASSERT(permod != NULL);
if (permod->persisted_table != NULL) {
LOG(THREAD, LOG_FRAGMENT, 2,
"%s persisted hashtable for %s " PFX "-" PFX "\n",
i == RCT_RAC ? "RAC" : "RCT", GET_MODULE_NAME(&data->names),
data->start, data->end);
hashtable_app_pc_study(dcontext, permod->persisted_table,
0 /*table consistent*/);
}
if (permod->live_table != NULL) {
LOG(THREAD, LOG_FRAGMENT, 2,
"%s live hashtable for %s " PFX "-" PFX "\n",
i == RCT_RAC ? "RAC" : "RCT", GET_MODULE_NAME(&data->names),
data->start, data->end);
hashtable_app_pc_study(dcontext, permod->live_table,
0 /*table consistent*/);
}
}
}
module_iterator_stop(mi);
}
# endif /* defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH) */
}
#endif /* DEBUG */
/****************************************************************************
* FLUSHING
*
* Two-stage freeing of fragments via immediate unlinking followed by lazy
* deletion.
*/
uint
get_flushtime_last_update(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
return pt->flushtime_last_update;
}
void
set_flushtime_last_update(dcontext_t *dcontext, uint val)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
pt->flushtime_last_update = val;
}
void
set_at_syscall(dcontext_t *dcontext, bool val)
{
ASSERT(dcontext != GLOBAL_DCONTEXT);
dcontext->upcontext_ptr->at_syscall = val;
}
bool
get_at_syscall(dcontext_t *dcontext)
{
ASSERT(dcontext != GLOBAL_DCONTEXT);
return dcontext->upcontext_ptr->at_syscall;
}
/* Assumes caller takes care of synchronization.
* Returns false iff was_I_flushed ends up being deleted right now from
* a private cache OR was_I_flushed has been flushed from a shared cache
* and is pending final deletion.
*/
static bool
check_flush_queue(dcontext_t *dcontext, fragment_t *was_I_flushed)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
bool not_flushed = true;
ASSERT_OWN_MUTEX(true, &pt->linking_lock);
/* first check private queue and act on pending deletions */
if (pt->flush_queue_nonempty) {
bool local_prot = local_heap_protected(dcontext);
if (local_prot)
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
/* remove local vm areas on t->Q queue and all frags in their lists */
not_flushed = not_flushed && vm_area_flush_fragments(dcontext, was_I_flushed);
pt->flush_queue_nonempty = false;
LOG(THREAD, LOG_FRAGMENT, 2, "Hashtable state after flushing the queue:\n");
DOLOG(2, LOG_FRAGMENT, { study_all_hashtables(dcontext); });
if (local_prot)
SELF_PROTECT_LOCAL(dcontext, READONLY);
}
/* now check shared queue to dec ref counts */
if (DYNAMO_OPTION(shared_deletion) &&
/* No lock needed: any racy incs to global are in safe direction, and our inc
* is atomic so we shouldn't see any partial-word-updated values here. This
* check is our shared deletion algorithm's only perf hit when there's no
* actual shared flushing.
*/
pt->flushtime_last_update < flushtime_global) {
#ifdef LINUX
rseq_shared_fragment_flushtime_update(dcontext);
#endif
/* dec ref count on any pending shared areas */
not_flushed =
not_flushed && vm_area_check_shared_pending(dcontext, was_I_flushed);
/* Remove unlinked markers if called for.
* FIXME If a thread's flushtime is updated due to shared syscall sync,
* its tables won't be rehashed here -- the thread's flushtime will be
* equal to the global flushtime so the 'if' isn't entered. We have
* multiple options as to other points for rehashing -- a table add, a
* table delete, any entry into DR. For now, we've chosen a table add
* (see check_table_size()).
*/
if (SHARED_IB_TARGETS() &&
(INTERNAL_OPTION(rehash_unlinked_threshold) < 100 ||
INTERNAL_OPTION(rehash_unlinked_always))) {
ibl_branch_type_t branch_type;
for (branch_type = IBL_BRANCH_TYPE_START; branch_type < IBL_BRANCH_TYPE_END;
branch_type++) {
ibl_table_t *table = &pt->bb_ibt[branch_type];
if (table->unlinked_entries > 0 &&
(INTERNAL_OPTION(rehash_unlinked_threshold) <
(100 * table->unlinked_entries /
(table->unlinked_entries + table->entries)) ||
INTERNAL_OPTION(rehash_unlinked_always))) {
STATS_INC(num_ibt_table_rehashes);
LOG(THREAD, LOG_FRAGMENT, 1,
"Rehash table %s: linked %u, unlinked %u\n", table->name,
table->entries, table->unlinked_entries);
hashtable_ibl_unlinked_remove(dcontext, table);
}
}
}
}
/* FIXME This is the ideal location for inserting refcounting logic
* for freeing a resized shared IBT table, as is done for shared
* deletion above.
*/
return not_flushed;
}
/* Note that an all-threads-synch flush does NOT set the self-flushing flag,
* so use is_self_allsynch_flushing() instead.
*/
bool
is_self_flushing()
{
/* race condition w/ flusher being updated -- but since only testing vs self,
* if flusher update is atomic, should be safe
*/
return (get_thread_private_dcontext() == flusher);
}
bool
is_self_allsynch_flushing()
{
/* race condition w/ allsynch_flusher being updated -- but since only testing
* vs self, if flusher update is atomic, should be safe
*/
return (allsynch_flusher != NULL &&
get_thread_private_dcontext() == allsynch_flusher);
}
/* N.B.: only accurate if called on self (else a race condition) */
bool
is_self_couldbelinking()
{
dcontext_t *dcontext = get_thread_private_dcontext();
/* if no dcontext yet then can't be couldbelinking */
return (dcontext != NULL && !RUNNING_WITHOUT_CODE_CACHE() /*case 7966: has no pt*/ &&
is_couldbelinking(dcontext));
}
/* N.B.: can only call if target thread is self, suspended, or waiting for flush */
bool
is_couldbelinking(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
/* the lock is only needed for self writing or another thread reading
* but if different thread we require thread is suspended or waiting for
* flush so is ok */
/* FIXME : add an assert that the thread that owns the dcontext is either
* the caller, at the flush sync wait, or is suspended by thread_synch
* routines */
return (!RUNNING_WITHOUT_CODE_CACHE() /*case 7966: has no pt*/ &&
pt != NULL /*PR 536058: no pt*/ && pt->could_be_linking);
}
static void
wait_for_flusher_nolinking(dcontext_t *dcontext)
{
/* FIXME: can have livelock w/ these types of synch loops,
* any way to work into deadlock-avoidance?
*/
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
ASSERT(!pt->could_be_linking);
while (pt->wait_for_unlink) {
LOG(THREAD, LOG_DISPATCH | LOG_THREADS, 2,
"Thread " TIDFMT " waiting for flush (flusher is %d @flushtime %d)\n",
/* safe to deref flusher since flusher is waiting for our signal */
dcontext->owning_thread, flusher->owning_thread, flushtime_global);
d_r_mutex_unlock(&pt->linking_lock);
STATS_INC(num_wait_flush);
wait_for_event(pt->finished_all_unlink, 0);
LOG(THREAD, LOG_DISPATCH | LOG_THREADS, 2,
"Thread " TIDFMT " resuming after flush\n", dcontext->owning_thread);
d_r_mutex_lock(&pt->linking_lock);
}
}
static void
wait_for_flusher_linking(dcontext_t *dcontext)
{
/* FIXME: can have livelock w/ these types of synch loops,
* any way to work into deadlock-avoidance?
*/
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
ASSERT(pt->could_be_linking);
while (pt->wait_for_unlink) {
LOG(THREAD, LOG_DISPATCH | LOG_THREADS, 2,
"Thread " TIDFMT " waiting for flush (flusher is %d @flushtime %d)\n",
/* safe to deref flusher since flusher is waiting for our signal */
dcontext->owning_thread, flusher->owning_thread, flushtime_global);
d_r_mutex_unlock(&pt->linking_lock);
signal_event(pt->waiting_for_unlink);
STATS_INC(num_wait_flush);
wait_for_event(pt->finished_with_unlink, 0);
LOG(THREAD, LOG_DISPATCH | LOG_THREADS, 2,
"Thread " TIDFMT " resuming after flush\n", dcontext->owning_thread);
d_r_mutex_lock(&pt->linking_lock);
}
}
#ifdef DEBUG
static void
check_safe_for_flush_synch(dcontext_t *dcontext)
{
/* We cannot hold any locks at synch points that wait for flushers, as we
* could prevent forward progress of a couldbelinking thread that the
* flusher will wait for.
*/
/* FIXME: will fail w/ -single_thread_in_DR, along w/ the other similar
* asserts for flushing and cache entering
*/
# ifdef DEADLOCK_AVOIDANCE
ASSERT(
thread_owns_no_locks(dcontext) ||
/* if thread exits while a trace is in progress (case 8055) we're
* holding thread_initexit_lock, which prevents any flusher from
* proceeding and hitting a deadlock point, so we should be safe
*/
thread_owns_one_lock(dcontext, &thread_initexit_lock) ||
/* it is safe to be the all-thread-syncher and hit a flush synch
* point, as no flusher can be active (all threads should be suspended
* except this thread)
*/
thread_owns_two_locks(dcontext, &thread_initexit_lock, &all_threads_synch_lock));
# endif /* DEADLOCK_AVOIDANCE */
}
#endif /* DEBUG */
#ifdef CLIENT_INTERFACE
static void
process_client_flush_requests(dcontext_t *dcontext, dcontext_t *alloc_dcontext,
client_flush_req_t *req, bool flush)
{
client_flush_req_t *iter = req;
while (iter != NULL) {
client_flush_req_t *next = iter->next;
if (flush) {
/* Note that we don't free futures from potentially linked-to region b/c we
* don't have lazy linking (xref case 2236) */
/* FIXME - if there's more then one of these would be nice to batch them
* especially for the synch all ones. */
if (iter->flush_callback != NULL) {
/* FIXME - for implementation simplicity we do a synch-all flush so
* that we can inform the client right away, it might be nice to use
* the more performant regular flush when possible. */
flush_fragments_from_region(dcontext, iter->start, iter->size,
true /*force synchall*/);
(*iter->flush_callback)(iter->flush_id);
} else {
/* do a regular flush */
flush_fragments_from_region(dcontext, iter->start, iter->size,
false /*don't force synchall*/);
}
}
HEAP_TYPE_FREE(alloc_dcontext, iter, client_flush_req_t, ACCT_CLIENT,
UNPROTECTED);
iter = next;
}
}
#endif
/* Returns false iff was_I_flushed ends up being deleted
* if cache_transition is true, assumes entering the cache now.
*/
bool
enter_nolinking(dcontext_t *dcontext, fragment_t *was_I_flushed, bool cache_transition)
{
#ifdef CLIENT_INTERFACE
/* Handle any pending low on memory events */
vmm_heap_handle_pending_low_on_memory_event_trigger();
#endif
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
bool not_flushed = true;
/*case 7966: has no pt, no flushing either */
if (RUNNING_WITHOUT_CODE_CACHE())
return true;
DOCHECK(1, { check_safe_for_flush_synch(dcontext); });
/* FIXME: once we have this working correctly, come up with scheme
* that avoids synch in common case
*/
d_r_mutex_lock(&pt->linking_lock);
ASSERT(pt->could_be_linking);
wait_for_flusher_linking(dcontext);
not_flushed = not_flushed && check_flush_queue(dcontext, was_I_flushed);
pt->could_be_linking = false;
d_r_mutex_unlock(&pt->linking_lock);
if (!cache_transition)
return not_flushed;
/* now we act on pending actions that can only be done while nolinking
* FIXME: optimization if add more triggers here: use a single
* master trigger as a first test to avoid testing all
* conditionals every time
*/
if (reset_pending != 0) {
d_r_mutex_lock(&reset_pending_lock);
if (reset_pending != 0) {
uint target = reset_pending;
reset_pending = 0;
/* fcache_reset_all_caches_proactively() will unlock */
fcache_reset_all_caches_proactively(target);
LOG(THREAD, LOG_DISPATCH, 2, "Just reset all caches, next_tag is " PFX "\n",
dcontext->next_tag);
/* fragment is gone for sure, so return false */
return false;
}
d_r_mutex_unlock(&reset_pending_lock);
}
/* FIXME: perf opt: make global flag can check w/ making a call,
* or at least inline the call
*/
if (fcache_is_flush_pending(dcontext)) {
not_flushed = not_flushed && fcache_flush_pending_units(dcontext, was_I_flushed);
}
#ifdef UNIX
/* i#61/PR 211530: nudges on Linux do not use separate threads */
while (dcontext->nudge_pending != NULL) {
/* handle_nudge may not return, so we can't call it w/ inconsistent state */
pending_nudge_t local = *dcontext->nudge_pending;
heap_free(dcontext, dcontext->nudge_pending, sizeof(local) HEAPACCT(ACCT_OTHER));
dcontext->nudge_pending = local.next;
if (dcontext->interrupted_for_nudge != NULL) {
fragment_t *f = dcontext->interrupted_for_nudge;
LOG(THREAD, LOG_ASYNCH, 3, "\tre-linking outgoing for interrupted F%d\n",
f->id);
SHARED_FLAGS_RECURSIVE_LOCK(f->flags, acquire, change_linking_lock);
link_fragment_outgoing(dcontext, f, false);
SHARED_FLAGS_RECURSIVE_LOCK(f->flags, release, change_linking_lock);
if (TEST(FRAG_HAS_SYSCALL, f->flags)) {
mangle_syscall_code(dcontext, f, EXIT_CTI_PC(f, dcontext->last_exit),
true /*skip exit cti*/);
}
dcontext->interrupted_for_nudge = NULL;
}
handle_nudge(dcontext, &local.arg);
/* we may have done a reset, so do not enter cache now */
return false;
}
#endif
#ifdef CLIENT_INTERFACE
/* Handle flush requests queued via dr_flush_fragments()/dr_delay_flush_region() */
/* thread private list */
process_client_flush_requests(dcontext, dcontext, dcontext->client_data->flush_list,
true /*flush*/);
dcontext->client_data->flush_list = NULL;
/* global list */
if (client_flush_requests != NULL) { /* avoid acquiring lock every cxt switch */
client_flush_req_t *req;
d_r_mutex_lock(&client_flush_request_lock);
req = client_flush_requests;
client_flush_requests = NULL;
d_r_mutex_unlock(&client_flush_request_lock);
/* NOTE - we must release the lock before doing the flush. */
process_client_flush_requests(dcontext, GLOBAL_DCONTEXT, req, true /*flush*/);
/* FIXME - this is an ugly, yet effective, hack. The problem is there is no
* good way to tell currently if we flushed was_I_flushed. Since it could be
* gone by now we pretend that it was flushed if we did any flushing at all.
* Dispatch should refind the fragment if it wasn't flushed. */
if (req != NULL)
not_flushed = false;
}
#endif
return not_flushed;
}
/* Returns false iff was_I_flushed ends up being deleted */
bool
enter_couldbelinking(dcontext_t *dcontext, fragment_t *was_I_flushed,
bool cache_transition)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
bool not_flushed;
/*case 7966: has no pt, no flushing either */
if (RUNNING_WITHOUT_CODE_CACHE())
return true;
ASSERT(pt != NULL); /* i#1989: API callers should check fragment_thread_exited() */
DOCHECK(1, { check_safe_for_flush_synch(dcontext); });
d_r_mutex_lock(&pt->linking_lock);
ASSERT(!pt->could_be_linking);
/* ensure not still marked at_syscall */
ASSERT(!DYNAMO_OPTION(syscalls_synch_flush) || !get_at_syscall(dcontext) ||
/* i#2026: this can happen during detach but there it's innocuous */
doing_detach);
/* for thread-shared flush and thread-private flush+execareas atomicity,
* to avoid non-properly-nested locks (could have flusher hold
* pt->linking_lock for the entire flush) we need an additional
* synch point here for shared flushing to synch w/ all threads.
* I suppose switching from non-nested locks to this loop isn't
* nec. helping deadlock avoidance -- can still hang -- but this
* should be better performance-wise (only a few writes and a
* conditional in the common case here, no extra locks)
*/
pt->soon_to_be_linking = true;
wait_for_flusher_nolinking(dcontext);
pt->soon_to_be_linking = false;
pt->could_be_linking = true;
not_flushed = check_flush_queue(dcontext, was_I_flushed);
d_r_mutex_unlock(&pt->linking_lock);
return not_flushed;
}
/* NOTE - this routine may be called more then one time for the same exiting thread,
* xref case 8047. Any once only reference counting, cleanup, etc. should be done in
* fragment_thread_exit(). This routine is just a stripped down version of
* enter_nolinking() to keep an exiting thread from deadlocking with flushing. */
void
enter_threadexit(dcontext_t *dcontext)
{
per_thread_t *pt = (per_thread_t *)dcontext->fragment_field;
/*case 7966: has no pt, no flushing either */
if (RUNNING_WITHOUT_CODE_CACHE() || pt == NULL /*PR 536058: no pt*/)
return;
d_r_mutex_lock(&pt->linking_lock);
/* must dec ref count on shared regions before we die */
check_flush_queue(dcontext, NULL);
pt->could_be_linking = false;
if (pt->wait_for_unlink) {
/* make sure don't get into deadlock w/ flusher */
pt->about_to_exit = true; /* let flusher know can ignore us */
signal_event(pt->waiting_for_unlink); /* wake flusher up */
}
d_r_mutex_unlock(&pt->linking_lock);
}
/* caller must hold shared_cache_flush_lock */
void
increment_global_flushtime()
{
ASSERT_OWN_MUTEX(true, &shared_cache_flush_lock);
/* reset will turn flushtime_global back to 0, so we schedule one
* when we're approaching overflow
*/
if (flushtime_global == UINT_MAX / 2) {
ASSERT_NOT_TESTED(); /* FIXME: add -stress_flushtime_global_max */
SYSLOG_INTERNAL_WARNING("flushtime_global approaching UINT_MAX, resetting");
schedule_reset(RESET_ALL);
}
ASSERT(flushtime_global < UINT_MAX);
/* compiler should 4-byte-align so no cache line crossing
* (asserted in fragment_init()
*/
flushtime_global++;
LOG(GLOBAL, LOG_VMAREAS, 2, "new flush timestamp: %u\n", flushtime_global);
}
/* The master flusher routines are split into 3:
* stage1) flush_fragments_synch_unlink_priv
* stage2) flush_fragments_unlink_shared
* stage3) flush_fragments_end_synch
* which MUST be used together. They are split to allow the caller to
* perform custom operations at certain synchronization points in the
* middle of flushing without using callback routines. The stages and
* points are:
*
* stage1: head synch, priv flushee unlink
* here caller can produce a custom list of fragments to flush while
* all threads are fully synched
* stage2: shared flushee unlink
*
* between stage2 and stage3, a region flush performs additional actions:
* region flush: exec area lock
* here caller can do custom exec area manipulations
* region flush: exec area unlock
*
* stage3: tail synch
*
* When doing a region flush with no custom region removals (the default is
* removing [base,base+size)), use the routine flush_fragments_and_remove_region().
* When doing a region flush with custom removals, use
* flush_fragments_in_region_start() and flush_fragments_in_region_finish().
* When doing a flush with no region removals at all use flush_fragments_from_region().
*
* The thread requesting a flush must be !couldbelinking and must not
* be holding any locks that are ever grabbed while a thread is
* couldbelinking (pretty much all locks), as it must wait for other
* threads who are couldbelinking. The thread_initexit_lock is held
* from stage 1 to stage 3 (if there are fragments to flush), and
* region flushing also holds the executable_areas lock between stage
* 2 and stage 3. After stage 1 no thread is couldbelinking() until
* the synchronization release in stage 3.
*
* The general delayed-deletion flushing strategy involves first
* freezing the threads via the thread_initexit_lock.
* It then walks the thread list and marks all vm areas that overlap
* base...base+size as to-be-deleted, along with unlinking all fragments in those
* vm areas and unlinking shared_syscall for that thread.
* Fragments in the target area are not actually deleted until their owning thread
* checks its pending deletion queue, which it does prior to entering the fcache.
* Also flushes shared fragments, in a similar manner, with deletion delayed
* until all threads are out of the shared cache.
*/
/* Variables shared between the 3 flush stage routines
* flush_fragments_synch_unlink_priv(),
* flush_fragments_unlink_shared(), and flush_fragments_end_synch.
* As there can only be one flush at a time, we only need one copy,
* protected by the thread_initexit_lock.
*/
/* Not persistent across code cache execution, so unprotected */
DECLARE_NEVERPROT_VAR(static thread_record_t **flush_threads, NULL);
DECLARE_NEVERPROT_VAR(static int flush_num_threads, 0);
DECLARE_NEVERPROT_VAR(static int pending_delete_threads, 0);
DECLARE_NEVERPROT_VAR(static int shared_flushed, 0);
DECLARE_NEVERPROT_VAR(static bool flush_synchall, false);
#ifdef DEBUG
DECLARE_NEVERPROT_VAR(static int num_flushed, 0);
DECLARE_NEVERPROT_VAR(static int flush_last_stage, 0);
#endif
static void
flush_fragments_free_futures(app_pc base, size_t size)
{
int i;
dcontext_t *tgt_dcontext;
ASSERT_OWN_MUTEX(true, &thread_initexit_lock);
ASSERT((allsynch_flusher == NULL && flusher == get_thread_private_dcontext()) ||
(flusher == NULL && allsynch_flusher == get_thread_private_dcontext()));
ASSERT(flush_num_threads > 0);
ASSERT(flush_threads != NULL);
if (DYNAMO_OPTION(free_unmapped_futures) && !RUNNING_WITHOUT_CODE_CACHE()) {
/* We need to free the futures after all fragments have been unlinked,
* as unlinking will create new futures
*/
acquire_recursive_lock(&change_linking_lock);
for (i = 0; i < flush_num_threads; i++) {
tgt_dcontext = flush_threads[i]->dcontext;
if (tgt_dcontext != NULL) {
fragment_delete_futures_in_region(tgt_dcontext, base, base + size);
thcounter_range_remove(tgt_dcontext, base, base + size);
}
}
if (SHARED_FRAGMENTS_ENABLED())
fragment_delete_futures_in_region(GLOBAL_DCONTEXT, base, base + size);
release_recursive_lock(&change_linking_lock);
} /* else we leak them */
}
/* This routine begins a flush that requires full thread synch: currently,
* it is used for flushing coarse-grain units and for dr_flush_region()
*/
static void
flush_fragments_synchall_start(dcontext_t *ignored, app_pc base, size_t size,
bool exec_invalid)
{
dcontext_t *my_dcontext = get_thread_private_dcontext();
app_pc exec_start = NULL, exec_end = NULL;
bool all_synched = true;
int i;
const thread_synch_state_t desired_state =
THREAD_SYNCH_SUSPENDED_VALID_MCONTEXT_OR_NO_XFER;
DEBUG_DECLARE(bool ok;)
KSTART(synchall_flush);
LOG(GLOBAL, LOG_FRAGMENT, 2,
"\nflush_fragments_synchall_start: thread " TIDFMT " suspending all threads\n",
d_r_get_thread_id());
STATS_INC(flush_synchall);
/* suspend all DR-controlled threads at safe locations */
DEBUG_DECLARE(ok =)
synch_with_all_threads(desired_state, &flush_threads, &flush_num_threads,
THREAD_SYNCH_NO_LOCKS_NO_XFER,
/* if we fail to suspend a thread (e.g., for
* privilege reasons), ignore it since presumably
* the failed thread is some injected thread not
* running to-be-flushed code, so we continue
* with the flush!
*/
THREAD_SYNCH_SUSPEND_FAILURE_IGNORE);
ASSERT(ok);
/* now we own the thread_initexit_lock */
ASSERT(OWN_MUTEX(&all_threads_synch_lock) && OWN_MUTEX(&thread_initexit_lock));
/* We do NOT set flusher as is_self_flushing() is all about
* couldbelinking, while our synch is of a different nature. The
* trace_abort() is_self_flushing() check is the only worrisome
* one: FIXME.
*/
ASSERT(flusher == NULL);
ASSERT(allsynch_flusher == NULL);
allsynch_flusher = my_dcontext;
flush_synchall = true;
ASSERT(flush_last_stage == 0);
DODEBUG({ flush_last_stage = 1; });
LOG(GLOBAL, LOG_FRAGMENT, 2, "flush_fragments_synchall_start: walking the threads\n");
/* We rely on coarse fragments not touching more than one vmarea region
* for our ibl invalidation. It's
* ok to invalidate more than we need to so we don't care if there are
* multiple coarse units within this range. We just need the exec areas
* bounds that overlap the flush region.
*/
if (!executable_area_overlap_bounds(base, base + size, &exec_start, &exec_end, 0,
true /*doesn't matter w/ 0*/)) {
/* caller checks for overlap but lock let go so can get here; go ahead
* and do synch per flushing contract.
*/
exec_start = base;
exec_end = base + size;
}
LOG(GLOBAL, LOG_FRAGMENT, 2,
"flush_fragments_synchall_start: from " PFX "-" PFX " => coarse " PFX "-" PFX
"\n",
base, base + size, exec_start, exec_end);
/* FIXME: share some of this code that I duplicated from reset */
for (i = 0; i < flush_num_threads; i++) {
dcontext_t *dcontext = flush_threads[i]->dcontext;
if (dcontext != NULL) { /* include my_dcontext here */
DEBUG_DECLARE(uint removed;)
LOG(GLOBAL, LOG_FRAGMENT, 2, "\tconsidering thread #%d " TIDFMT "\n", i,
flush_threads[i]->id);
if (dcontext != my_dcontext) {
/* must translate BEFORE freeing any memory! */
if (!thread_synch_successful(flush_threads[i])) {
/* FIXME case 9480: if we do get here for low-privilege handles
* or exceeding our synch try count, best to not move the thread
* as we won't get a clean translation. Chances are it is
* not in the region being flushed.
*/
SYSLOG_INTERNAL_ERROR_ONCE("failed to synch with thread during "
"synchall flush");
LOG(THREAD, LOG_FRAGMENT | LOG_SYNCH, 2,
"failed to synch with thread #%d\n", i);
STATS_INC(flush_synchall_fail);
all_synched = false;
} else if (is_thread_currently_native(flush_threads[i])) {
/* native_exec's regain-control point is in our DLL,
* and lost-control threads are truly native, so no
* state to worry about except for hooks -- and we're
* not freeing the interception buffer.
*/
LOG(GLOBAL, LOG_FRAGMENT, 2,
"\tcurrently native so no translation needed\n");
} else if (thread_synch_state_no_xfer(dcontext)) {
/* Case 6821: do not translate other synch-all-thread users.
* They have no fragment state, so leave alone.
* All flush call points are in syscalls or from nudges.
* Xref case 8901 on ensuring nudges don't try to return
* to the code cache.
*/
LOG(GLOBAL, LOG_FRAGMENT, 2,
"\tat THREAD_SYNCH_NO_LOCKS_NO_XFER so no translation needed\n");
STATS_INC(flush_synchall_races);
} else {
translate_from_synchall_to_dispatch(flush_threads[i], desired_state);
}
}
if (dcontext == my_dcontext || thread_synch_successful(flush_threads[i])) {
last_exit_deleted(dcontext);
/* case 7394: need to abort other threads' trace building
* since the reset xfer to d_r_dispatch will disrupt it.
* also, with PR 299808, we now have thread-shared
* "undeletable" trace-temp fragments, so we need to abort
* all traces.
*/
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_FRAGMENT, 2, "\tsquashing trace of thread #%d\n", i);
trace_abort(dcontext);
}
}
/* Since coarse fragments never cross coarse/non-coarse executable region
* bounds, we can bound their bodies by taking
* executable_area_distinct_bounds(). This lets us remove by walking the
* ibl tables and looking only at tags, rather than walking the htable of
* each coarse unit. FIXME: not clear this is a perf win: I arbitrarily
* picked it under assumption that ibl tables are relatively small. It
* would be a clearer win if we could do the fine fragments this way
* also, but fine fragments are not constrained and could be missed using
* only a tag-based range remove.
*/
DEBUG_DECLARE(removed =)
fragment_remove_all_ibl_in_region(dcontext, exec_start, exec_end);
LOG(THREAD, LOG_FRAGMENT, 2, "\tremoved %d ibl entries in " PFX "-" PFX "\n",
removed, exec_start, exec_end);
/* Free any fine private fragments in the region */
vm_area_allsynch_flush_fragments(dcontext, dcontext, base, base + size,
exec_invalid, all_synched /*ignored*/);
if (!SHARED_IBT_TABLES_ENABLED() && SHARED_FRAGMENTS_ENABLED()) {
/* Remove shared fine fragments from private ibl tables */
vm_area_allsynch_flush_fragments(dcontext, GLOBAL_DCONTEXT, base,
base + size, exec_invalid,
all_synched /*ignored*/);
}
}
}
/* Removed shared coarse fragments from ibl tables, before freeing any */
if (SHARED_IBT_TABLES_ENABLED() && SHARED_FRAGMENTS_ENABLED())
fragment_remove_all_ibl_in_region(GLOBAL_DCONTEXT, exec_start, exec_end);
/* Free coarse units and shared fine fragments, as well as removing shared fine
* entries in any shared ibl tables
*/
if (SHARED_FRAGMENTS_ENABLED()) {
vm_area_allsynch_flush_fragments(GLOBAL_DCONTEXT, GLOBAL_DCONTEXT, base,
base + size, exec_invalid, all_synched);
}
}
static void
flush_fragments_synchall_end(dcontext_t *ignored)
{
thread_record_t **temp_threads = flush_threads;
DEBUG_DECLARE(dcontext_t *my_dcontext = get_thread_private_dcontext();)
LOG(GLOBAL, LOG_FRAGMENT, 2, "flush_fragments_synchall_end: resuming all threads\n");
/* We need to clear this before we release the locks. We use a temp var
* so we can use end_synch_with_all_threads.
*/
flush_threads = NULL;
ASSERT(flusher == NULL);
flush_synchall = false;
ASSERT(dynamo_all_threads_synched);
ASSERT(allsynch_flusher == my_dcontext);
allsynch_flusher = NULL;
end_synch_with_all_threads(temp_threads, flush_num_threads, true /*resume*/);
KSTOP(synchall_flush);
}
/* Relink shared sycalls and/or special IBL transfer for thread-private scenario. */
static void
flush_fragments_relink_thread_syscalls(dcontext_t *dcontext, dcontext_t *tgt_dcontext,
per_thread_t *tgt_pt)
{
#ifdef WINDOWS
if (DYNAMO_OPTION(shared_syscalls)) {
if (SHARED_FRAGMENTS_ENABLED()) {
/* we cannot re-link shared_syscall here as that would allow
* the target thread to enter to-be-flushed fragments prior
* to their being unlinked and removed from ibl tables -- so
* we force this thread to re-link in check_flush_queue.
* we could re-link after unlink/removal of fragments,
* if it's worth optimizing == case 6194/PR 210655.
*/
tgt_pt->flush_queue_nonempty = true;
STATS_INC(num_flushq_relink_syscall);
} else if (!IS_SHARED_SYSCALL_THREAD_SHARED) {
/* no shared fragments, and no private ones being flushed,
* so this thread is all set
*/
link_shared_syscall(tgt_dcontext);
}
}
#endif
if (special_ibl_xfer_is_thread_private()) {
if (SHARED_FRAGMENTS_ENABLED()) {
/* see shared_syscall relink comment: we have to delay the relink */
tgt_pt->flush_queue_nonempty = true;
STATS_INC(num_flushq_relink_special_ibl_xfer);
} else
link_special_ibl_xfer(dcontext);
}
}
static bool
flush_fragments_thread_unlink(dcontext_t *dcontext, int thread_index,
dcontext_t *tgt_dcontext)
{
per_thread_t *tgt_pt = (per_thread_t *)tgt_dcontext->fragment_field;
/* if a trace-in-progress crosses this region, must squash the trace
* (all traces are essentially frozen now since threads stop in d_r_dispatch)
*/
if (flush_size > 0 /* else, no region to cross */ &&
is_building_trace(tgt_dcontext)) {
void *trace_vmlist = cur_trace_vmlist(tgt_dcontext);
if (trace_vmlist != NULL &&
vm_list_overlaps(tgt_dcontext, trace_vmlist, flush_base,
flush_base + flush_size)) {
LOG(THREAD, LOG_FRAGMENT, 2, "\tsquashing trace of thread " TIDFMT "\n",
tgt_dcontext->owning_thread);
trace_abort(tgt_dcontext);
}
}
/* Optimization for shared deletion strategy: perform flush work
* for a thread waiting at a system call on behalf of that thread
* (which we do before the flush tail synch, as if we did it now we
* would need to inc flushtime_global up front, and then we'd have synch
* issues trying to prevent thread we hadn't synched with from checking
* the pending list before we put flushed fragments on it).
* We do count these threads in the ref count as we check the pending
* queue on their behalf after adding the newly flushed fragments to
* the queue, so the ref count gets decremented right away.
*
* We must do this AFTER unlinking shared_syscall's post-syscall ibl, to
* avoid races -- the thread will hit a real synch point before accessing
* any fragments or link info.
* Do this BEFORE checking whether fragments in region to catch all threads.
*/
ASSERT(!tgt_pt->at_syscall_at_flush);
if (DYNAMO_OPTION(syscalls_synch_flush) && get_at_syscall(tgt_dcontext)) {
/* we have to know exactly which threads were at_syscall here when
* we get to post-flush, so we cache in this special bool
*/
DEBUG_DECLARE(bool tables_updated;)
tgt_pt->at_syscall_at_flush = true;
#ifdef DEBUG
tables_updated =
#endif
update_all_private_ibt_table_ptrs(tgt_dcontext, tgt_pt);
STATS_INC(num_shared_flush_atsyscall);
DODEBUG({
if (tables_updated)
STATS_INC(num_shared_tables_updated_atsyscall);
});
}
/* don't need to go any further if thread has no frags in region */
if (flush_size == 0 ||
!thread_vm_area_overlap(tgt_dcontext, flush_base, flush_base + flush_size)) {
LOG(THREAD, LOG_FRAGMENT, 2,
"\tthread " TIDFMT " has no fragments in region to flush\n",
tgt_dcontext->owning_thread);
return true; /* true: relink syscalls now b/c skipping vm_area_flush_fragments */
}
LOG(THREAD, LOG_FRAGMENT, 2, "\tflushing fragments for thread " TIDFMT "\n",
flush_threads[thread_index]->id);
DOLOG(2, LOG_FRAGMENT, {
if (tgt_dcontext != dcontext) {
LOG(tgt_dcontext->logfile, LOG_FRAGMENT, 2,
"thread " TIDFMT " is flushing our fragments\n", dcontext->owning_thread);
}
});
if (flush_size > 0) {
/* unlink all frags in overlapping regions, and mark regions for deletion */
tgt_pt->flush_queue_nonempty = true;
#ifdef DEBUG
num_flushed +=
#endif
vm_area_unlink_fragments(tgt_dcontext, flush_base, flush_base + flush_size,
0 _IF_DGCDIAG(written_pc));
}
return false; /* false: syscalls remain unlinked until vm_area_flush_fragments */
}
/* This routine begins a flush of the group of fragments in the memory
* region [base, base+size) by synchronizing with each thread and
* invoking thread_synch_callback().
*
* If shared syscalls and/or special IBL transfer are thread-private, they will
* be unlinked for each thread prior to invocation of the callback. The return
* value of the callback indicates whether to relink these routines (true), or
* wait for a later operation (such as vm_area_flush_fragments()) to relink
* them later (false).
*/
void
flush_fragments_synch_priv(dcontext_t *dcontext, app_pc base, size_t size,
bool own_initexit_lock,
bool (*thread_synch_callback)(dcontext_t *dcontext,
int thread_index,
dcontext_t *thread_dcontext)
_IF_DGCDIAG(app_pc written_pc))
{
dcontext_t *tgt_dcontext;
per_thread_t *tgt_pt;
int i;
/* our flushing design requires that flushers are NOT couldbelinking
* and are not holding any locks
*/
ASSERT(!is_self_couldbelinking());
#if defined(DEADLOCK_AVOIDANCE) && defined(DEBUG)
if (own_initexit_lock) {
/* We can get here while holding the all_threads_synch_lock
* for detach (& prob. TerminateProcess(0) with other threads
* still active) on XP and 2003 via os_thread_stack_exit()
* (for other thread exit) if we have executed off that stack.
* Can be seen with Araktest detach on violation using the stack
* attack button. */
ASSERT(thread_owns_first_or_both_locks_only(dcontext, &thread_initexit_lock,
&all_threads_synch_lock));
} else {
ASSERT_OWN_NO_LOCKS();
}
#endif
/* Take a snapshot of the threads in the system.
* Grab the thread lock to prevent threads from being created or
* exited for the duration of this routine
* FIXME -- is that wise? could be a relatively long time!
* It's unlikely a new thread will run code in a region being
* unmapped...but we would like to prevent threads from exiting
* while we're messing with their data.
* FIXME: need to special-case every instance where thread_initexit_lock
* is grabbed, to avoid deadlocks! we already do for a thread exiting.
*/
if (!own_initexit_lock)
d_r_mutex_lock(&thread_initexit_lock);
ASSERT_OWN_MUTEX(true, &thread_initexit_lock);
flusher = dcontext;
get_list_of_threads(&flush_threads, &flush_num_threads);
ASSERT(flush_last_stage == 0);
DODEBUG({ flush_last_stage = 1; });
/* FIXME: we can optimize this even more to not grab thread_initexit_lock */
if (RUNNING_WITHOUT_CODE_CACHE()) /* case 7966: nothing to flush, ever */
return;
flush_base = base;
flush_size = size;
/* Set the ref count of threads who may be using a deleted fragment. We
* include ourselves in the ref count as we could be invoked with a cache
* return point before any synch (as done w/ hotpatches) and should NOT
* consider ourselves done w/ all cache fragments right now. We assume we
* will soon hit a real synch point to dec the count for us, and don't try
* to specially handle the single-threaded case here.
*/
pending_delete_threads = flush_num_threads;
DODEBUG({ num_flushed = 0; });
#ifdef WINDOWS
/* Make sure exit fcache if currently inside syscall. For thread-shared
* shared_syscall, we re-link after the shared fragments have all been
* unlinked and removed from the ibl tables. All we lose is the bounded time
* on a thread checking its private flush queue, which in a thread-shared
* configuration doesn't seem so bad. For thread-private this will work as
* well, with the same time bound lost, but we're not as worried about memory
* usage of thread-private configurations.
*/
if (DYNAMO_OPTION(shared_syscalls) && IS_SHARED_SYSCALL_THREAD_SHARED)
unlink_shared_syscall(GLOBAL_DCONTEXT);
#endif
/* i#849: unlink while we clear out ibt */
if (!special_ibl_xfer_is_thread_private())
unlink_special_ibl_xfer(GLOBAL_DCONTEXT);
for (i = 0; i < flush_num_threads; i++) {
tgt_dcontext = flush_threads[i]->dcontext;
tgt_pt = (per_thread_t *)tgt_dcontext->fragment_field;
LOG(THREAD, LOG_FRAGMENT, 2, " considering thread #%d/%d = " TIDFMT "\n", i + 1,
flush_num_threads, flush_threads[i]->id);
ASSERT(is_thread_known(tgt_dcontext->owning_thread));
/* can't do anything, even check if thread has any vm areas overlapping flush
* region, until sure thread is in fcache or somewhere that won't change
* vm areas or linking state
*/
d_r_mutex_lock(&tgt_pt->linking_lock);
/* Must explicitly check for self and avoid synch then, o/w will lock up
* if ever called from a could_be_linking location (currently only
* happens w/ app syscalls)
*/
if (tgt_dcontext != dcontext && tgt_pt->could_be_linking) {
/* remember we have a global lock, thread_initexit_lock, so two threads
* cannot be here at the same time!
*/
LOG(THREAD, LOG_FRAGMENT, 2, "\twaiting for thread " TIDFMT "\n",
tgt_dcontext->owning_thread);
tgt_pt->wait_for_unlink = true;
d_r_mutex_unlock(&tgt_pt->linking_lock);
wait_for_event(tgt_pt->waiting_for_unlink, 0);
d_r_mutex_lock(&tgt_pt->linking_lock);
tgt_pt->wait_for_unlink = false;
LOG(THREAD, LOG_FRAGMENT, 2, "\tdone waiting for thread " TIDFMT "\n",
tgt_dcontext->owning_thread);
} else {
LOG(THREAD, LOG_FRAGMENT, 2, "\tthread " TIDFMT " synch not required\n",
tgt_dcontext->owning_thread);
}
/* it is now safe to access link, vm, and trace info in tgt_dcontext
* => FIXME: rename, since not just accessing linking info?
* FIXME: if includes vm access, are syscalls now bad?
* what about handle_modified_code, considered nolinking since straight
* from cache via fault handler? reading should be ok, but exec area splits
* and whatnot?
*/
if (tgt_pt->about_to_exit) {
/* thread is about to exit, it's waiting for us to give up
* thread_initexit_lock -- we don't need to flush it
*/
} else {
#ifdef WINDOWS
/* Make sure exit fcache if currently inside syscall. If thread has no
* vm area overlap, will be re-linked down below before going to the
* next thread, unless we have shared fragments, in which case we force
* the thread to check_flush_queue() on its next synch point. It will
* re-link in vm_area_flush_fragments().
*/
if (DYNAMO_OPTION(shared_syscalls) && !IS_SHARED_SYSCALL_THREAD_SHARED)
unlink_shared_syscall(tgt_dcontext);
#endif
/* i#849: unlink while we clear out ibt */
if (special_ibl_xfer_is_thread_private())
unlink_special_ibl_xfer(tgt_dcontext);
if (thread_synch_callback(dcontext, i, tgt_dcontext))
flush_fragments_relink_thread_syscalls(dcontext, tgt_dcontext, tgt_pt);
}
/* for thread-shared, we CANNOT let any thread become could_be_linking, for normal
* flushing synch -- for thread-private, we can, but we CANNOT let any thread
* that we've already synched with for flushing go and change the exec areas
* vector! the simplest solution is to have thread-private, like thread-shared,
* stop all threads at a cache exit point.
* FIXME: optimize thread-private by allowing already-synched threads to
* continue but not grab executable_areas lock, while letting
* to-be-synched threads grab the lock (otherwise could wait forever)
*/
/* Since we must let go of lock for proper nesting, we use a new
* synch to stop threads at cache exit, since we need them all
* out of DR for duration of shared flush.
*/
if (tgt_dcontext != dcontext && !tgt_pt->could_be_linking)
tgt_pt->wait_for_unlink = true; /* stop at cache exit */
d_r_mutex_unlock(&tgt_pt->linking_lock);
}
}
/* This routine begins a flush of the group of fragments in the memory
* region [base, base+size) by synchronizing with each thread and unlinking
* all private fragments in the region.
*
* The exec_invalid parameter must be set to indicate whether the
* executable area is being invalidated as well or this is just a capacity
* flush (or a flush to change instrumentation).
*
* If size==0 then no unlinking occurs; however, the full synch is
* performed (so the caller should check size if no action is desired on
* zero size).
*
* If size>0 and there is no executable area overlap, then no synch is
* performed and false is returned. The caller must acquire the executable
* areas lock and re-check the overlap if exec area manipulation is to be
* performed. Returns true otherwise.
*/
bool
flush_fragments_synch_unlink_priv(dcontext_t *dcontext, app_pc base, size_t size,
/* WARNING: case 8572: the caller owning this lock
* is incompatible w/ suspend-the-world flushing!
*/
bool own_initexit_lock, bool exec_invalid,
bool force_synchall _IF_DGCDIAG(app_pc written_pc))
{
LOG(THREAD, LOG_FRAGMENT, 2,
"FLUSH STAGE 1: synch_unlink_priv(thread " TIDFMT " flushtime %d): " PFX "-" PFX
"\n",
dcontext->owning_thread, flushtime_global, base, base + size);
/* Case 9750: to specify a region of size 0, do not pass in NULL as the base!
* Use EMPTY_REGION_{BASE,SIZE} instead.
*/
ASSERT(base != NULL || size != 0);
ASSERT(dcontext == get_thread_private_dcontext());
/* quick check for overlap first by using read lock and avoiding
* thread_initexit_lock:
* if no overlap, must hold lock through removal of region
* if overlap, ok to release for a bit
*/
if (size > 0 && !executable_vm_area_executed_from(base, base + size)) {
/* Only a curiosity since we can have a race (not holding exec areas lock) */
ASSERT_CURIOSITY((!SHARED_FRAGMENTS_ENABLED() ||
!thread_vm_area_overlap(GLOBAL_DCONTEXT, base, base + size)) &&
!thread_vm_area_overlap(dcontext, base, base + size));
return false;
}
/* Only a curiosity since we can have a race (not holding exec areas lock) */
ASSERT_CURIOSITY(size == 0 ||
executable_vm_area_overlap(base, base + size, false /*no lock*/));
STATS_INC(num_flushes);
if (force_synchall ||
(size > 0 && executable_vm_area_coarse_overlap(base, base + size))) {
/* Coarse units do not support individual unlinking (though prior to
* freezing they do, we ignore that) and instead require all-thread-synch
* in order to flush. For that we cannot be already holding
* thread_initexit_lock! FIXME case 8572: the only caller who does hold it
* now is os_thread_stack_exit(). For now relying on that stack not
* overlapping w/ any coarse regions.
*/
ASSERT(!own_initexit_lock);
/* The synchall will flush fine as well as coarse so we'll be done */
flush_fragments_synchall_start(dcontext, base, size, exec_invalid);
return true;
}
flush_fragments_synch_priv(dcontext, base, size, own_initexit_lock,
flush_fragments_thread_unlink _IF_DGCDIAG(written_pc));
return true;
}
/* This routine continues a flush of one of two groups of fragments:
* 1) if list!=NULL, the list of shared fragments beginning at list and
* chained by next_vmarea (we assume that private fragments are
* easily deleted by the owning thread and do not require a flush).
* Caller should call vm_area_remove_fragment() for each target fragment,
* building a custom list chained by next_vmarea, and pass that list to this
* routine.
* 2) otherwise, all fragments in the memory region [base, base+size).
*
* This routine MUST be called after flush_fragments_synch_unlink_priv(), and
* must be followed with flush_fragments_end_synch().
*/
void
flush_fragments_unlink_shared(dcontext_t *dcontext, app_pc base, size_t size,
fragment_t *list _IF_DGCDIAG(app_pc written_pc))
{
/* we would assert that size > 0 || list != NULL but we have to pass
* in 0 and NULL for unit flushing when no live fragments are in the unit
*/
LOG(THREAD, LOG_FRAGMENT, 2,
"FLUSH STAGE 2: unlink_shared(thread " TIDFMT "): flusher is " TIDFMT "\n",
dcontext->owning_thread, (flusher == NULL) ? -1 : flusher->owning_thread);
ASSERT_OWN_MUTEX(true, &thread_initexit_lock);
ASSERT(flush_threads != NULL);
ASSERT(flush_num_threads > 0);
ASSERT(flush_last_stage == 1);
DODEBUG({ flush_last_stage = 2; });
if (RUNNING_WITHOUT_CODE_CACHE()) /* case 7966: nothing to flush, ever */
return;
if (flush_synchall) /* no more flush work to do */
return;
if (SHARED_FRAGMENTS_ENABLED()) {
/* Flushing shared fragments: the strategy is again immediate
* unlinking (plus hashtable removal and vm area list removal)
* with delayed deletion. Unlinking is atomic, and hashtable
* removal is for now since there are no shared bbs in ibls from
* the cache. But deletion needs to ensure that every thread who may
* hold a pointer to a shared fragment or may be inside a shared
* fragment is ok with the fragment being deleted. We use a reference count
* for each flushed region to ensure that every thread has reached a synch
* point before we actually free the fragments in the region.
*
* We do have pathological cases where a single thread at a wait syscall or
* an infinite loop in the cache will prevent all freeing. One solution
* to the syscall problem is to store a flag saying that a thread is at
* the shared_syscall routine. That routine is private and unlinked so
* we know the thread will hit a synch routine if it exits, so no race.
* We then wouldn't bother to inc the ref count for that thread.
*
* Our fallback proactive deletion is to do a full reset when the size
* of the pending deletion list gets too long, though we could be more
* efficient by only resetting the pending list, and by only suspending
* those threads that haven't dec-ed a ref count in a particular region.
*/
LOG(THREAD, LOG_FRAGMENT, 2, " flushing shared fragments\n");
if (DYNAMO_OPTION(shared_deletion)) {
/* We use shared_cache_flush_lock to make atomic the increment of
* flushtime_global and the adding of pending deletion fragments with
* that flushtime, wrt other threads checking the pending list.
*/
d_r_mutex_lock(&shared_cache_flush_lock);
}
/* Increment flush count for shared deletion algorithm and for list-based
* flushing (such as for shared cache units). We could wait
* and only do this if we actually flush shared fragments, but it's
* simpler when done in this routine, and nearly every flush does flush
* shared fragments.
*/
increment_global_flushtime();
/* Both vm_area_unlink_fragments and unlink_fragments_for_deletion call
* back to flush_invalidate_ibl_shared_target to remove shared
* fragments from private/shared ibl tables
*/
if (list == NULL) {
shared_flushed =
vm_area_unlink_fragments(GLOBAL_DCONTEXT, base, base + size,
pending_delete_threads _IF_DGCDIAG(written_pc));
} else {
shared_flushed = unlink_fragments_for_deletion(GLOBAL_DCONTEXT, list,
pending_delete_threads);
}
if (DYNAMO_OPTION(shared_deletion))
d_r_mutex_unlock(&shared_cache_flush_lock);
DODEBUG({
num_flushed += shared_flushed;
if (shared_flushed > 0)
STATS_INC(num_shared_flushes);
});
}
#ifdef WINDOWS
/* Re-link thread-shared shared_syscall */
if (DYNAMO_OPTION(shared_syscalls) && IS_SHARED_SYSCALL_THREAD_SHARED)
link_shared_syscall(GLOBAL_DCONTEXT);
#endif
if (!special_ibl_xfer_is_thread_private())
link_special_ibl_xfer(GLOBAL_DCONTEXT);
STATS_ADD(num_flushed_fragments, num_flushed);
DODEBUG({
if (num_flushed > 0) {
LOG(THREAD, LOG_FRAGMENT, 1, "Flushed %5d fragments from " PFX "-" PFX "\n",
num_flushed, base, ((char *)base) + size);
} else {
STATS_INC(num_empty_flushes);
LOG(THREAD, LOG_FRAGMENT, 2, "Flushed 0 fragments from " PFX "-" PFX "\n",
base, ((char *)base) + size);
}
});
}
/* Invalidates (does not remove) shared fragment f from the private/shared
* ibl tables. Can only be called in flush stage 2.
*/
void
flush_invalidate_ibl_shared_target(dcontext_t *dcontext, fragment_t *f)
{
ASSERT(is_self_flushing());
ASSERT(!flush_synchall);
ASSERT_OWN_MUTEX(true, &thread_initexit_lock);
ASSERT(flush_threads != NULL);
ASSERT(flush_num_threads > 0);
ASSERT(flush_last_stage == 2);
ASSERT(TEST(FRAG_SHARED, f->flags));
/*case 7966: has no pt, no flushing either */
if (RUNNING_WITHOUT_CODE_CACHE()) {
ASSERT_NOT_REACHED(); /* shouldn't get here */
return;
}
if (!SHARED_IB_TARGETS())
return;
if (SHARED_IBT_TABLES_ENABLED()) {
/* Remove from shared ibl tables.
* dcontext need not be GLOBAL_DCONTEXT.
*/
fragment_prepare_for_removal(dcontext, f);
} else {
/* We can't tell afterward which entries to remove from the private
* ibl tables, as we no longer keep fragment_t* pointers (we used to
* look for FRAG_WAS_DELETED) and we can't do a range remove (tags
* don't map regularly to regions). So we must invalidate each
* fragment as we process it. It's ok to walk the thread list
* here since we're post-synch for all threads.
*/
int i;
for (i = 0; i < flush_num_threads; i++) {
fragment_prepare_for_removal(flush_threads[i]->dcontext, f);
}
}
}
/* Must ONLY be called as the third part of flushing (after
* flush_fragments_synch_unlink_priv() and flush_fragments_unlink_shared()).
* Uses the static shared variables flush_threads and flush_num_threads.
*/
void
flush_fragments_end_synch(dcontext_t *dcontext, bool keep_initexit_lock)
{
dcontext_t *tgt_dcontext;
per_thread_t *tgt_pt;
int i;
LOG(THREAD, LOG_FRAGMENT, 2,
"FLUSH STAGE 3: end_synch(thread " TIDFMT "): flusher is " TIDFMT "\n",
dcontext->owning_thread, (flusher == NULL) ? -1 : flusher->owning_thread);
if (!is_self_flushing() && !flush_synchall /* doesn't set flusher */) {
LOG(THREAD, LOG_FRAGMENT, 2, "\tnothing was flushed\n");
ASSERT_DO_NOT_OWN_MUTEX(!keep_initexit_lock, &thread_initexit_lock);
ASSERT_OWN_MUTEX(keep_initexit_lock, &thread_initexit_lock);
return;
}
ASSERT_OWN_MUTEX(true, &thread_initexit_lock);
ASSERT(flush_threads != NULL);
ASSERT(flush_num_threads > 0);
ASSERT(flush_last_stage == 2);
DODEBUG({ flush_last_stage = 0; });
if (flush_synchall) {
flush_fragments_synchall_end(dcontext);
return;
}
/* now can let all threads at DR synch point go
* FIXME: if implement thread-private optimization above, this would turn into
* re-setting exec areas lock to treat all threads uniformly
*/
for (i = flush_num_threads - 1; i >= 0; i--) {
/*case 7966: has no pt, no flushing either */
if (RUNNING_WITHOUT_CODE_CACHE())
continue;
tgt_dcontext = flush_threads[i]->dcontext;
tgt_pt = (per_thread_t *)tgt_dcontext->fragment_field;
/* re-acquire lock */
d_r_mutex_lock(&tgt_pt->linking_lock);
/* Optimization for shared deletion strategy: perform flush work
* for a thread waiting at a system call, as we didn't add it to the
* ref count in the pre-flush synch.
* We assume that shared_syscall is still unlinked at this point and
* will not be relinked until we let the thread go.
*/
if (DYNAMO_OPTION(syscalls_synch_flush) && tgt_pt->at_syscall_at_flush) {
/* Act on behalf of the thread as though it's at a synch point, but
* only wrt shared fragments (we don't free private fragments here,
* though we could -- should we? may make flush time while holding
* lock take too long? FIXME)
* Currently this works w/ syscalls from d_r_dispatch, and w/
* -shared_syscalls by using unprotected storage (thus a slight hole
* but very hard to exploit for security purposes: can get stale code
* executed, but we already have that window, or crash us).
* FIXME: Does not work w/ -ignore_syscalls, but those are private
* for now.
*/
DEBUG_DECLARE(uint pre_flushtime = flushtime_global;)
vm_area_check_shared_pending(tgt_dcontext, NULL);
/* lazy deletion may inc flushtime_global, so may have a higher
* value than our cached one, but should never be lower
*/
ASSERT(tgt_pt->flushtime_last_update >= pre_flushtime);
tgt_pt->at_syscall_at_flush = false;
}
if (tgt_dcontext != dcontext) {
if (tgt_pt->could_be_linking) {
signal_event(tgt_pt->finished_with_unlink);
} else {
/* we don't need to wait on a !could_be_linking thread
* so we use this bool to tell whether we should signal
* the event.
* FIXME: really we want a pulse that wakes ALL waiting
* threads and then resets the event!
*/
tgt_pt->wait_for_unlink = false;
if (tgt_pt->soon_to_be_linking)
signal_event(tgt_pt->finished_all_unlink);
}
}
d_r_mutex_unlock(&tgt_pt->linking_lock);
}
/* thread init/exit can proceed now */
flusher = NULL;
global_heap_free(flush_threads,
flush_num_threads *
sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT));
flush_threads = NULL;
if (!keep_initexit_lock)
d_r_mutex_unlock(&thread_initexit_lock);
}
/* This routine performs flush stages 1 and 2 (synch_unlink_priv()
* and unlink_shared()) and then returns after grabbing the
* executable_areas lock so that removal of this area from the global list
* is atomic w/ the flush and local removals, before letting the threads go
* -- we return while holding both the thread_initexit_lock and the exec
* areas lock
*
* FIXME: this only helps thread-shared: for thread-private, should let
* already-synched threads continue but not grab executable_areas lock, while
* letting to-be-synched threads grab the lock.
*
* returning while holding locks isn't ideal -- but other choices are worse:
* 1) grab exec areas lock and then let go of initexit lock -- bad nesting
* 2) do all work here, which has to include:
* A) remove region (nearly all uses) == flush_fragments_and_remove_region
* B) change region from rw to r (splitting if nec) (vmareas.c app rw->r)
* C) restore writability and change to selfmod (splitting if nec)
* (vmareas.c handle_modified_code)
* D) remove region and then look up a certain pc and return whether
* flushing overlapped w/ it (vmareas.c handle_modified_code)
*/
void
flush_fragments_in_region_start(dcontext_t *dcontext, app_pc base, size_t size,
bool own_initexit_lock, bool free_futures,
bool exec_invalid,
bool force_synchall _IF_DGCDIAG(app_pc written_pc))
{
KSTART(flush_region);
while (true) {
if (flush_fragments_synch_unlink_priv(dcontext, base, size, own_initexit_lock,
exec_invalid,
force_synchall _IF_DGCDIAG(written_pc))) {
break;
} else {
/* grab lock and then re-check overlap */
executable_areas_lock();
if (!executable_vm_area_executed_from(base, base + size)) {
LOG(THREAD, LOG_FRAGMENT, 2,
"\tregion not executable, so no fragments to flush\n");
/* caller will release lock! */
STATS_INC(num_noncode_flushes);
return;
}
/* unlock and try again */
executable_areas_unlock();
}
}
flush_fragments_unlink_shared(dcontext, base, size, NULL _IF_DGCDIAG(written_pc));
/* We need to free the futures after all fragments have been unlinked */
if (free_futures) {
flush_fragments_free_futures(base, size);
}
executable_areas_lock();
}
/* must ONLY be called as the second half of flush_fragments_in_region_start().
* uses the shared variables flush_threads and flush_num_threads
*/
void
flush_fragments_in_region_finish(dcontext_t *dcontext, bool keep_initexit_lock)
{
/* done w/ exec areas lock; also free any non-executed coarse units */
free_nonexec_coarse_and_unlock();
flush_fragments_end_synch(dcontext, keep_initexit_lock);
KSTOP(flush_region);
}
/* flush and remove region from exec list, atomically */
void
flush_fragments_and_remove_region(dcontext_t *dcontext, app_pc base, size_t size,
bool own_initexit_lock, bool free_futures)
{
flush_fragments_in_region_start(dcontext, base, size, own_initexit_lock, free_futures,
true /*exec invalid*/,
false /*don't force synchall*/ _IF_DGCDIAG(NULL));
/* ok to call on non-exec region, so don't need to test return value
* both flush routines will return quickly if nothing to flush/was flushed
*/
remove_executable_region(base, size, true /*have lock*/);
flush_fragments_in_region_finish(dcontext, own_initexit_lock);
/* verify initexit lock is in the right state */
ASSERT_OWN_MUTEX(own_initexit_lock, &thread_initexit_lock);
ASSERT_DO_NOT_OWN_MUTEX(!own_initexit_lock, &thread_initexit_lock);
}
/* Flushes fragments from the region without any changes to the exec list.
* Does not free futures and caller can't be holding the initexit lock.
* FIXME - add argument parameters (free futures etc.) as needed. */
void
flush_fragments_from_region(dcontext_t *dcontext, app_pc base, size_t size,
bool force_synchall)
{
/* we pass false to flush_fragments_in_region_start() below for owning the initexit
* lock */
ASSERT_DO_NOT_OWN_MUTEX(true, &thread_initexit_lock);
/* ok to call on non-exec region, so don't need to test return value
* both flush routines will return quickly if nothing to flush/was flushed */
flush_fragments_in_region_start(dcontext, base, size, false /*don't own initexit*/,
false /*don't free futures*/, false /*exec valid*/,
force_synchall _IF_DGCDIAG(NULL));
flush_fragments_in_region_finish(dcontext, false);
}
/* Invalidate all fragments in all caches. Currently executed
* fragments may be alive until they reach an exit.
*
* Note not necessarily immediately freeing memory like
* fcache_reset_all_caches_proactively().
*/
void
invalidate_code_cache()
{
dcontext_t *dcontext = get_thread_private_dcontext();
LOG(GLOBAL, LOG_FRAGMENT, 2, "invalidate_code_cache()\n");
flush_fragments_in_region_start(dcontext, UNIVERSAL_REGION_BASE,
UNIVERSAL_REGION_SIZE, false,
true /* remove futures */, false /*exec valid*/,
false /*don't force synchall*/
_IF_DGCDIAG(NULL));
flush_fragments_in_region_finish(dcontext, false);
}
/* Flushes all areas stored in the vector toflush.
* Synchronization of toflush is up to caller, but as locks cannot be
* held when flushing, toflush must be thread-private.
* Currently only used for pcache hotp interop (case 9970).
*/
void
flush_vmvector_regions(dcontext_t *dcontext, vm_area_vector_t *toflush, bool free_futures,
bool exec_invalid)
{
vmvector_iterator_t vmvi;
app_pc start, end;
ASSERT(toflush != NULL && !TEST(VECTOR_SHARED, toflush->flags));
ASSERT(!RUNNING_WITHOUT_CODE_CACHE());
ASSERT(DYNAMO_OPTION(coarse_units) &&
DYNAMO_OPTION(use_persisted) IF_HOTP(&&DYNAMO_OPTION(hot_patching)));
if (vmvector_empty(toflush))
return;
vmvector_iterator_start(toflush, &vmvi);
while (vmvector_iterator_hasnext(&vmvi)) {
vmvector_iterator_next(&vmvi, &start, &end);
/* FIXME case 10086: optimization: batch the flushes together so we only
* synch once. Currently this is rarely used, and with few areas in the
* vector, so we don't bother. To batch them we'd need to assume the
* worst and do a synchall up front, which could be more costly than 2
* or 3 separate flushes that do not involve coarse code.
*/
ASSERT_OWN_NO_LOCKS();
flush_fragments_in_region_start(dcontext, start, end - start, false /*no lock*/,
free_futures, exec_invalid,
false /*don't force synchall*/ _IF_DGCDIAG(NULL));
flush_fragments_in_region_finish(dcontext, false /*no lock*/);
STATS_INC(num_flush_vmvector);
}
vmvector_iterator_stop(&vmvi);
}
/****************************************************************************/
#if defined(INTERNAL) || defined(CLIENT_INTERFACE)
void
fragment_output(dcontext_t *dcontext, fragment_t *f)
{
ASSERT(!TEST(FRAG_SHARED, f->flags) ||
self_owns_recursive_lock(&change_linking_lock));
if (SHOULD_OUTPUT_FRAGMENT(f->flags)) {
per_thread_t *pt = (dcontext == GLOBAL_DCONTEXT)
? shared_pt
: (per_thread_t *)dcontext->fragment_field;
output_trace(dcontext, pt, f,
IF_DEBUG_ELSE(GLOBAL_STAT(num_fragments),
GLOBAL_STAT(num_traces) + GLOBAL_STAT(num_bbs)) +
1);
}
}
void
init_trace_file(per_thread_t *pt)
{
if (INTERNAL_OPTION(tracedump_binary)) {
/* First 4 bytes in binary file gives size of linkcounts, which are
* no longer supported: we always set to 0 to indicate no linkcounts.
*/
tracedump_file_header_t hdr = { CURRENT_API_VERSION, IF_X64_ELSE(true, false),
0 };
os_write(pt->tracefile, &hdr, sizeof(hdr));
}
}
void
exit_trace_file(per_thread_t *pt)
{
close_log_file(pt->tracefile);
}
/* Binary trace dump is used to save time and space.
* The format is in fragment.h.
* FIXME: add general symbol table support to disassembly?
* We'd dump num_targets, then fcache_enter, ibl, trace_cache_incr addrs?
* Reader would then add exit stubs & other traces to table?
* But links will target cache pcs...
*/
# define TRACEBUF_SIZE 2048
# define TRACEBUF_MAKE_ROOM(p, buf, sz) \
do { \
if (p + sz >= &buf[TRACEBUF_SIZE]) { \
os_write(pt->tracefile, buf, (p - buf)); \
p = buf; \
} \
} while (0)
static void
output_trace_binary(dcontext_t *dcontext, per_thread_t *pt, fragment_t *f,
stats_int_t trace_num)
{
/* FIXME:
* We do not support PROFILE_RDTSC or various small fields
*/
/* FIXME: should allocate buffer elsewhere */
byte buf[TRACEBUF_SIZE];
byte *p = buf;
trace_only_t *t = TRACE_FIELDS(f);
linkstub_t *l;
tracedump_trace_header_t hdr = {
(int)trace_num,
f->tag,
f->start_pc,
f->prefix_size,
0,
f->size,
(INTERNAL_OPTION(tracedump_origins) ? t->num_bbs : 0),
IF_X86_64_ELSE(!TEST(FRAG_32_BIT, f->flags), false),
};
tracedump_stub_data_t stub;
/* Should we widen the identifier? */
IF_X64(ASSERT(CHECK_TRUNCATE_TYPE_int(trace_num)));
for (l = FRAGMENT_EXIT_STUBS(f); l != NULL; l = LINKSTUB_NEXT_EXIT(l))
hdr.num_exits++;
TRACEBUF_MAKE_ROOM(p, buf, sizeof(hdr));
*((tracedump_trace_header_t *)p) = hdr;
p += sizeof(hdr);
if (INTERNAL_OPTION(tracedump_origins)) {
uint i;
for (i = 0; i < t->num_bbs; i++) {
instr_t *inst;
instrlist_t *ilist;
int size = 0;
TRACEBUF_MAKE_ROOM(p, buf, sizeof(app_pc));
*((app_pc *)p) = t->bbs[i].tag;
p += sizeof(app_pc);
/* we assume that the target is readable, since we dump prior
* to unloading of modules on flush events
*/
ilist = build_app_bb_ilist(dcontext, t->bbs[i].tag, INVALID_FILE);
for (inst = instrlist_first(ilist); inst; inst = instr_get_next(inst)) {
size += instr_length(dcontext, inst);
}
TRACEBUF_MAKE_ROOM(p, buf, sizeof(int));
*((int *)p) = size;
p += sizeof(int);
for (inst = instrlist_first(ilist); inst; inst = instr_get_next(inst)) {
TRACEBUF_MAKE_ROOM(p, buf, instr_length(dcontext, inst));
/* PR 302353: we can't use instr_encode() as it will
* try to re-relativize rip-rel instrs, which may fail
*/
ASSERT(instr_get_raw_bits(inst) != NULL);
memcpy(p, instr_get_raw_bits(inst), instr_length(dcontext, inst));
p += instr_length(dcontext, inst);
}
/* free the instrlist_t elements */
instrlist_clear_and_destroy(dcontext, ilist);
}
}
ASSERT(SEPARATE_STUB_MAX_SIZE == DIRECT_EXIT_STUB_SIZE(0));
for (l = FRAGMENT_EXIT_STUBS(f); l != NULL; l = LINKSTUB_NEXT_EXIT(l)) {
cache_pc stub_pc = EXIT_STUB_PC(dcontext, f, l);
stub.cti_offs = l->cti_offset;
stub.stub_pc = stub_pc;
stub.target = EXIT_TARGET_TAG(dcontext, f, l);
stub.linked = TEST(LINK_LINKED, l->flags);
stub.stub_size = EXIT_HAS_STUB(l->flags, f->flags)
? DIRECT_EXIT_STUB_SIZE(f->flags)
: 0 /* no stub neededd: -no_indirect_stubs */;
ASSERT(DIRECT_EXIT_STUB_SIZE(f->flags) <= SEPARATE_STUB_MAX_SIZE);
TRACEBUF_MAKE_ROOM(p, buf, STUB_DATA_FIXED_SIZE);
memcpy(p, &stub, STUB_DATA_FIXED_SIZE);
p += STUB_DATA_FIXED_SIZE;
if (TEST(LINK_SEPARATE_STUB, l->flags) && stub_pc != NULL) {
TRACEBUF_MAKE_ROOM(p, buf, DIRECT_EXIT_STUB_SIZE(f->flags));
ASSERT(stub_pc < f->start_pc || stub_pc >= f->start_pc + f->size);
memcpy(p, stub_pc, DIRECT_EXIT_STUB_SIZE(f->flags));
p += DIRECT_EXIT_STUB_SIZE(f->flags);
} else { /* ensure client's method of identifying separate stubs works */
ASSERT(stub_pc == NULL /* no stub at all */ ||
(stub_pc >= f->start_pc && stub_pc < f->start_pc + f->size));
}
}
if (f->size >= TRACEBUF_SIZE) {
os_write(pt->tracefile, buf, (p - buf));
p = buf;
os_write(pt->tracefile, f->start_pc, f->size);
} else {
/* single syscall for all but largest traces */
TRACEBUF_MAKE_ROOM(p, buf, f->size);
memcpy(p, f->start_pc, f->size);
p += f->size;
os_write(pt->tracefile, buf, (p - buf));
p = buf;
}
}
/* Output the contents of the specified trace.
* Does full disassembly of every instruction.
* If deleted_at != -1, it is taken to be the fragment id that
* caused the flushing of this fragment from the cache
* If f is shared, pt argument must be shared_pt, and caller must hold
* the change_linking_lock.
*/
static void
output_trace(dcontext_t *dcontext, per_thread_t *pt, fragment_t *f,
stats_int_t deleted_at)
{
trace_only_t *t = TRACE_FIELDS(f);
# ifdef WINDOWS
char buf[MAXIMUM_PATH];
# endif
stats_int_t trace_num;
bool locked_vmareas = false, ok;
dr_isa_mode_t old_mode;
ASSERT(SHOULD_OUTPUT_FRAGMENT(f->flags));
ASSERT(TEST(FRAG_IS_TRACE, f->flags));
ASSERT(!TEST(FRAG_SELFMOD_SANDBOXED, f->flags)); /* no support for selfmod */
/* already been output? caller should check this flag, just like trace flag */
ASSERT(!TEST(FRAG_TRACE_OUTPUT, f->flags));
ASSERT(!TEST(FRAG_SHARED, f->flags) ||
self_owns_recursive_lock(&change_linking_lock));
f->flags |= FRAG_TRACE_OUTPUT;
LOG(THREAD, LOG_FRAGMENT, 4, "output_trace: F%d(" PFX ")\n", f->id, f->tag);
/* Recreate in same mode as original fragment */
ok = dr_set_isa_mode(dcontext, FRAG_ISA_MODE(f->flags), &old_mode);
ASSERT(ok);
/* xref 8131/8202 if dynamo_resetting we don't need to grab the tracedump
* mutex to ensure we're the only writer and grabbing here on reset path
* can lead to a rank-order violation. */
if (!dynamo_resetting) {
/* We must grab shared_vm_areas lock first to avoid rank order (i#1157) */
if (SHARED_FRAGMENTS_ENABLED())
locked_vmareas = acquire_vm_areas_lock_if_not_already(dcontext, FRAG_SHARED);
d_r_mutex_lock(&tracedump_mutex);
}
trace_num = tcount;
tcount++;
if (!TEST(FRAG_SHARED, f->flags)) {
/* No lock is needed because we use thread-private files.
* If dumping traces for a different thread (dynamo_other_thread_exit
* for ex.) caller is responsible for the necessary synchronization. */
ASSERT(pt != shared_pt);
if (!dynamo_resetting) {
d_r_mutex_unlock(&tracedump_mutex);
if (locked_vmareas) {
locked_vmareas = false;
release_vm_areas_lock(dcontext, FRAG_SHARED);
}
}
} else {
ASSERT(pt == shared_pt);
}
/* binary dump requested? */
if (INTERNAL_OPTION(tracedump_binary)) {
output_trace_binary(dcontext, pt, f, trace_num);
goto output_trace_done;
}
/* just origins => just bb tags in text */
if (INTERNAL_OPTION(tracedump_origins) && !INTERNAL_OPTION(tracedump_text)) {
uint i;
print_file(pt->tracefile, "Trace %d\n", tcount);
# ifdef DEBUG
print_file(pt->tracefile, "Fragment %d\n", f->id);
# endif
for (i = 0; i < t->num_bbs; i++) {
print_file(pt->tracefile, "\tbb %d = " PFX "\n", i, t->bbs[i].tag);
}
print_file(pt->tracefile, "\n");
goto output_trace_done;
}
/* full text dump */
print_file(pt->tracefile,
"=============================================="
"=============================\n\n");
print_file(pt->tracefile, "TRACE # %d\n", tcount);
# ifdef DEBUG
print_file(pt->tracefile, "Fragment # %d\n", f->id);
# endif
print_file(pt->tracefile, "Tag = " PFX "\n", f->tag);
print_file(pt->tracefile, "Thread = %d\n", d_r_get_thread_id());
if (deleted_at > -1) {
print_file(pt->tracefile, "*** Flushed from cache when top fragment id was %d\n",
deleted_at);
}
# ifdef WINDOWS
/* FIXME: for fragments flushed by unloaded modules, naturally we
* won't be able to get the module name b/c by now it is unloaded,
* the only fix is to keep a listing of mapped modules and only
* unmap in our listing at this point
*/
get_module_name(f->tag, buf, sizeof(buf));
if (buf[0] != '\0')
print_file(pt->tracefile, "Module of basic block 0 = %s\n", buf);
else
print_file(pt->tracefile, "Module of basic block 0 = <unknown>\n");
# endif
# if defined(INTERNAL) || defined(CLIENT_INTERFACE)
if (INTERNAL_OPTION(tracedump_origins)) {
uint i;
print_file(pt->tracefile, "\nORIGINAL CODE:\n");
for (i = 0; i < t->num_bbs; i++) {
/* we only care about the printing that the build routine does */
print_file(pt->tracefile, "basic block # %d: ", i);
/* we assume that the target is readable, since we dump prior
* to unloading of modules on flush events
*/
ASSERT(is_readable_without_exception(t->bbs[i].tag, sizeof(t->bbs[i])));
disassemble_app_bb(dcontext, t->bbs[i].tag, pt->tracefile);
}
print_file(pt->tracefile, "END ORIGINAL CODE\n\n");
}
# endif
# ifdef PROFILE_RDTSC
if (dynamo_options.profile_times) {
/* Cycle counts are too high due to extra instructions needed
* to save regs and store time, so we subtract a constant for
* each fragment entry.
* Experiments using large-iter loops show that:
* empty loop overhead = 2 cycles
* 2 pushes, 2 moves, 2 pops = 7 cycles - 2 cycles = 5 cycles
* add in 1 rdtsc = 38 cycles - 2 cycles = 36 cycles
* add in 2 rdtsc = 69 cycles - 2 cycles = 67 cycles
* If we assume the time transfer happens in the middle of the rdtsc, we
* should use 36 cycles.
*/
trace_only_t *tr = TRACE_FIELDS(f);
const int adjustment = 37;
uint64 real_time = tr->total_time;
uint64 temp;
uint time_top, time_bottom;
print_file(pt->tracefile, "Size = %d (+ %d for profiling)\n",
f->size - profile_call_size(), profile_call_size());
print_file(pt->tracefile, "Profiling:\n");
print_file(pt->tracefile, "\tcount = " UINT64_FORMAT_STRING "\n", tr->count);
print_file(pt->tracefile, "\tmeasured cycles = " PFX "\n", real_time);
temp = tr->count * (uint64)adjustment;
if (real_time < temp) {
print_file(
pt->tracefile,
"\t ERROR: adjustment too large, cutting off at 0, should use < %d\n",
(int)(real_time / tr->count));
real_time = 0;
} else {
real_time -= temp;
}
print_file(pt->tracefile, "\tadjusted cycles = " PFX "\n", real_time);
divide_uint64_print(real_time, kilo_hertz, false, 6, &time_top, &time_bottom);
print_file(pt->tracefile, "\ttime = %u.%.6u ms\n", time_top, time_bottom);
} else {
print_file(pt->tracefile, "Size = %d\n", f->size);
}
# else
print_file(pt->tracefile, "Size = %d\n", f->size);
# endif /* PROFILE_RDTSC */
# if defined(INTERNAL) || defined(CLIENT_INTERFACE)
print_file(pt->tracefile, "Body:\n");
disassemble_fragment_body(dcontext, f, pt->tracefile);
print_file(pt->tracefile, "END TRACE %d\n\n", tcount);
# endif
output_trace_done:
dr_set_isa_mode(dcontext, old_mode, NULL);
if (TEST(FRAG_SHARED, f->flags) && !dynamo_resetting) {
ASSERT_OWN_MUTEX(true, &tracedump_mutex);
d_r_mutex_unlock(&tracedump_mutex);
if (locked_vmareas)
release_vm_areas_lock(dcontext, FRAG_SHARED);
} else {
ASSERT_DO_NOT_OWN_MUTEX(true, &tracedump_mutex);
}
}
#endif /* defined(INTERNAL) || defined(CLIENT_INTERFACE) */
/****************************************************************************/
#ifdef PROFILE_RDTSC
/* This routine is called at the start of every trace
* it assumes the caller has saved the caller-saved registers
* (eax, ecx, edx)
*
* See insert_profile_call() for the assembly code prefix that calls
* this routine. The end time is computed in the assembly code and passed
* in to have as accurate times as possible (don't want the profiling overhead
* added into the times). Also, the assembly code computes the new start
* time after this routine returns.
*
* We could generate a custom copy of this routine
* for every thread, but we don't do that now -- don't need to.
*/
void
profile_fragment_enter(fragment_t *f, uint64 end_time)
{
dcontext_t *dcontext;
# ifdef WINDOWS
/* must get last error prior to getting dcontext */
int error_code = get_last_error();
# endif
trace_only_t *t = TRACE_FIELDS(f);
/* this is done in assembly: uint64 end_time = get_time() */
dcontext = get_thread_private_dcontext();
/* increment this fragment's execution count */
t->count++;
/***********************************************************************/
/* all-in-cache sequence profiling */
/* top ten cache times */
dcontext->cache_frag_count++;
/***********************************************************************/
/* we rely on d_r_dispatch being the only way to enter the fcache.
* d_r_dispatch sets prev_fragment to null prior to entry */
if (dcontext->prev_fragment != NULL) {
trace_only_t *last_t = TRACE_FIELDS(dcontext->prev_fragment);
ASSERT((dcontext->prev_fragment->flags & FRAG_IS_TRACE) != 0);
/* charge time to last fragment */
last_t->total_time += (end_time - dcontext->start_time);
}
/* set up for next fragment */
dcontext->prev_fragment = f;
/* this is done in assembly: dcontext->start_time = get_time() */
# ifdef WINDOWS
/* retore app's error code */
set_last_error(error_code);
# endif
}
/* this routine is called from d_r_dispatch after exiting the fcache
* it finishes up the final fragment's time slot
*/
void
profile_fragment_dispatch(dcontext_t *dcontext)
{
/* end time slot ASAP, should we try to move this to assembly routines exiting
* the cache? probably not worth it, in a long-running program shouldn't
* be exiting the cache that often */
uint64 end_time = get_time();
bool tagtable = LINKSTUB_INDIRECT(dcontext->last_exit->flags);
if (dcontext->prev_fragment != NULL &&
(dcontext->prev_fragment->flags & FRAG_IS_TRACE) != 0) {
/* end time slot, charge time to last fragment
* there's more overhead here than other time endings, so subtract
* some time off. these numbers are pretty arbitrary:
*/
trace_only_t *last_t = TRACE_FIELDS(dcontext->prev_fragment);
const uint64 adjust = (tagtable) ? 72 : 36;
uint64 add = end_time - dcontext->start_time;
if (add < adjust) {
SYSLOG_INTERNAL_ERROR("ERROR: profile_fragment_dispatch: add was %d, "
"tagtable %d",
(int)add, tagtable);
add = 0;
} else
add -= adjust;
ASSERT((dcontext->prev_fragment->flags & FRAG_IS_TRACE) != 0);
last_t->total_time += add;
}
}
#endif /* PROFILE_RDTSC */
/*******************************************************************************
* COARSE-GRAIN FRAGMENT HASHTABLE INSTANTIATION
*/
/* Synch model: the htable lock should be held during all
* app_to_cache_t manipulations, to be consistent (not strictly
* necessary as there are no removals from the htable except in
* all-thread-synch flushes). Copies of a looked-up cache_pc are safe
* to use w/o the htable lock, or any lock -- they're pointers into
* cache units, and there are no deletions of cache units, except in
* all-thread-synch flushes.
*/
/* 2 macros w/ name and types are duplicated in fragment.h -- keep in sync */
#define NAME_KEY coarse
#define ENTRY_TYPE app_to_cache_t
static app_to_cache_t a2c_empty = { NULL, NULL };
static app_to_cache_t a2c_sentinel = { /*assume invalid*/ (app_pc)PTR_UINT_MINUS_1,
NULL };
/* FIXME: want to inline the app_to_cache_t struct just like lookuptable
* does and use it for main table -- no support for that right now
*/
/* not defining HASHTABLE_USE_LOOKUPTABLE */
#define ENTRY_TAG(f) ((ptr_uint_t)(f).app)
#define ENTRY_EMPTY (a2c_empty)
#define ENTRY_SENTINEL (a2c_sentinel)
#define ENTRY_IS_EMPTY(f) ((f).app == a2c_empty.app)
#define ENTRY_IS_SENTINEL(f) ((f).app == a2c_sentinel.app)
#define ENTRY_IS_INVALID(f) (false) /* no invalid entries */
#define ENTRIES_ARE_EQUAL(t, f, g) ((f).app == (g).app)
#define HASHTABLE_WHICH_HEAP(flags) (ACCT_FRAG_TABLE)
/* note that we give the th table a lower-ranked coarse_th_htable_rwlock */
#define COARSE_HTLOCK_RANK coarse_table_rwlock /* for use after hashtablex.h */
#define HTLOCK_RANK COARSE_HTLOCK_RANK
#define HASHTABLE_SUPPORT_PERSISTENCE 1
#include "hashtablex.h"
/* All defines are undef-ed at end of hashtablex.h
* Would be nice to re-use ENTRY_IS_EMPTY, etc., though w/ multiple htables
* in same file can't realistically get away w/o custom defines like these:
*/
#define A2C_ENTRY_IS_EMPTY(a2c) ((a2c).app == NULL)
#define A2C_ENTRY_IS_SENTINEL(a2c) ((a2c).app == a2c_sentinel.app)
#define A2C_ENTRY_IS_REAL(a2c) (!A2C_ENTRY_IS_EMPTY(a2c) && !A2C_ENTRY_IS_SENTINEL(a2c))
/* required routines for hashtable interface that we don't need for this instance */
static void
hashtable_coarse_init_internal_custom(dcontext_t *dcontext, coarse_table_t *htable)
{ /* nothing */
}
static void
hashtable_coarse_resized_custom(dcontext_t *dcontext, coarse_table_t *htable,
uint old_capacity, app_to_cache_t *old_table,
app_to_cache_t *old_table_unaligned, uint old_ref_count,
uint old_table_flags)
{ /* nothing */
}
#ifdef DEBUG
static void
hashtable_coarse_study_custom(dcontext_t *dcontext, coarse_table_t *htable,
uint entries_inc /*amnt table->entries was pre-inced*/)
{ /* nothing */
}
#endif
static void
hashtable_coarse_free_entry(dcontext_t *dcontext, coarse_table_t *htable,
app_to_cache_t entry)
{
/* nothing to do, data is inlined */
}
/* i#670: To handle differing app addresses from different module
* bases across different executions, we store the persist-time abs
* addrs in our tables and always shift on lookup. For frozen exit
* stubs, we have the frozen fcache return convert to a cur-base abs
* addr so this shift will then restore to persist-time.
*
* XXX: this is needed for -persist_trust_textrel, but for Windows
* bases will only be different when we need to apply relocations, and
* there we could just add an extra relocation per exit stub, which
* would end up being lower overhead for long-running apps, but may be
* higher than the overhead of shifting for short-running. For now,
* I'm enabling this as cross-platform, and we can do perf
* measurements later if desired.
*
* Storing persist-time abs addr versus storing module offsets: note
* that whatever we do we want a frozen-unit-only solution so we don't
* want to, say, always store module offsets for non-frozen units.
* This is because we support mixing coarse and fine and we have to
* use abs addrs in fine tables b/c they're not per-module. We could
* store offsets in frozen only, but then we'd have to do extra work
* when freezing. Plus, by storing absolute, when the module base
* lines up we can avoid the shift on the exit stubs (although today
* we only avoid exit stub overhead for trace heads when the base
* matches).
*/
static inline app_to_cache_t
coarse_lookup_internal(dcontext_t *dcontext, app_pc tag, coarse_table_t *table)
{
/* note that for mod_shift we don't need to compare to bounds b/c
* this is a table for this module only
*/
app_to_cache_t a2c =
hashtable_coarse_lookup(dcontext, (ptr_uint_t)(tag + table->mod_shift), table);
if (table->mod_shift != 0 && A2C_ENTRY_IS_REAL(a2c))
a2c.app -= table->mod_shift;
return a2c;
}
/* I would #define hashtable_coarse_lookup as DO_NOT_USE but we have to use for
* pclookup
*/
/* Pass 0 for the initial capacity to use the default.
* Initial capacities are number of entires and NOT bits in mask or anything.
*/
void
fragment_coarse_htable_create(coarse_info_t *info, uint init_capacity,
uint init_th_capacity)
{
coarse_table_t *th_htable;
coarse_table_t *htable;
uint init_size;
ASSERT(SHARED_FRAGMENTS_ENABLED());
/* Case 9537: If we start the new table small and grow it we have large
* collision chains as we map the lower address space of a large table into
* the same lower fraction of a smaller table, so we create our table fully
* sized up front.
*/
if (init_capacity != 0) {
init_size = hashtable_bits_given_entries(init_capacity,
DYNAMO_OPTION(coarse_htable_load));
} else
init_size = INIT_HTABLE_SIZE_COARSE;
LOG(GLOBAL, LOG_FRAGMENT, 2, "Coarse %s htable %d capacity => %d bits\n",
info->module, init_capacity, init_size);
htable =
NONPERSISTENT_HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, coarse_table_t, ACCT_FRAG_TABLE);
hashtable_coarse_init(
GLOBAL_DCONTEXT, htable, init_size, DYNAMO_OPTION(coarse_htable_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
HASHTABLE_ENTRY_SHARED | HASHTABLE_SHARED |
HASHTABLE_RELAX_CLUSTER_CHECKS _IF_DEBUG("coarse htable"));
htable->mod_shift = 0;
info->htable = (void *)htable;
/* We could create th_htable lazily independently of htable but not worth it */
if (init_th_capacity != 0) {
init_size = hashtable_bits_given_entries(init_th_capacity,
DYNAMO_OPTION(coarse_th_htable_load));
} else
init_size = INIT_HTABLE_SIZE_COARSE_TH;
LOG(GLOBAL, LOG_FRAGMENT, 2, "Coarse %s th htable %d capacity => %d bits\n",
info->module, init_th_capacity, init_size);
th_htable =
NONPERSISTENT_HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, coarse_table_t, ACCT_FRAG_TABLE);
hashtable_coarse_init(
GLOBAL_DCONTEXT, th_htable, init_size, DYNAMO_OPTION(coarse_th_htable_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
HASHTABLE_ENTRY_SHARED | HASHTABLE_SHARED |
HASHTABLE_RELAX_CLUSTER_CHECKS _IF_DEBUG("coarse th htable"));
th_htable->mod_shift = 0;
/* We give th table a lower lock rank for coarse_body_from_htable_entry().
* FIXME: add param to init() that takes in lock rank?
*/
ASSIGN_INIT_READWRITE_LOCK_FREE(th_htable->rwlock, coarse_th_table_rwlock);
info->th_htable = (void *)th_htable;
}
/* Adds all entries from stable into dtable, offsetting by dst_cache_offset,
* which is the offset from dst->cache_start_pc at which
* the src cache has been placed.
*/
static void
fragment_coarse_htable_merge_helper(dcontext_t *dcontext, coarse_info_t *dst,
coarse_table_t *dtable, coarse_info_t *src,
coarse_table_t *stable, ssize_t dst_cache_offset)
{
app_to_cache_t a2c, look_a2c;
uint i;
/* assumption: dtable is private to this thread and so does not need synch */
DODEBUG({ dtable->is_local = true; });
TABLE_RWLOCK(stable, read, lock);
for (i = 0; i < stable->capacity; i++) {
a2c = stable->table[i];
if (A2C_ENTRY_IS_REAL(a2c)) {
look_a2c = coarse_lookup_internal(dcontext, a2c.app, dtable);
if (A2C_ENTRY_IS_EMPTY(look_a2c)) {
a2c.cache += dst_cache_offset;
if (!dst->frozen) { /* adjust absolute value */
ASSERT_NOT_TESTED();
a2c.cache += (dst->cache_start_pc - src->cache_start_pc);
}
hashtable_coarse_add(dcontext, a2c, dtable);
} else {
/* Our merging-with-dups strategy requires that we not
* merge them in this early
*/
ASSERT_NOT_REACHED();
}
}
}
TABLE_RWLOCK(stable, read, unlock);
DODEBUG({ dtable->is_local = false; });
}
/* Merges the main and th htables from info1 and info2 into new htables for dst.
* If !add_info2, makes room for but does not add entries from info2.
* If !add_th_htable, creates but does not add entries to dst->th_htable.
* FIXME: we can't use hashtable_coarse_merge() b/c we don't want to add
* entries from the 2nd table, and we do custom mangling of entries when adding.
* Is it worth parametrizing hashtable_coarse_merge() to share anything?
*/
void
fragment_coarse_htable_merge(dcontext_t *dcontext, coarse_info_t *dst,
coarse_info_t *info1, coarse_info_t *info2, bool add_info2,
bool add_th_htable)
{
coarse_table_t *thht_dst, *thht1, *thht2;
coarse_table_t *ht_dst, *ht1, *ht2;
uint merged_entries = 0;
ASSERT(SHARED_FRAGMENTS_ENABLED());
ASSERT(info1 != NULL && info2 != NULL);
ht1 = (coarse_table_t *)info1->htable;
ht2 = (coarse_table_t *)info2->htable;
thht1 = (coarse_table_t *)info1->th_htable;
thht2 = (coarse_table_t *)info2->th_htable;
ASSERT(dst != NULL && dst->htable == NULL && dst->th_htable == NULL);
/* We go to the trouble of determining non-dup total entries to
* avoid repeatedly increasing htable size on merges and hitting
* collision asserts. FIXME: should we shrink afterward instead?
* Or just ignore collision asserts until at full size?
*/
merged_entries = hashtable_coarse_num_unique_entries(dcontext, ht1, ht2);
STATS_ADD(coarse_merge_dups, ht1->entries + ht2->entries - merged_entries);
LOG(THREAD, LOG_FRAGMENT, 2, "Merging %s: %d + %d => %d (%d unique) entries\n",
info1->module, ht1->entries, ht2->entries, ht1->entries + ht2->entries,
merged_entries);
/* We could instead copy ht1 and then add ht2; for simplicity we re-use
* our create-empty routine and add both
*/
fragment_coarse_htable_create(dst, merged_entries,
/* Heuristic to never over-size, yet try to avoid
* collision asserts while resizing the table;
* FIXME: if we shrink the main htable afterward
* could do the same here and start at sum of
* entries */
MAX(thht1->entries, thht2->entries));
ht_dst = (coarse_table_t *)dst->htable;
thht_dst = (coarse_table_t *)dst->th_htable;
ASSERT(ht_dst != NULL && thht_dst != NULL);
/* For now we only support frozen tables; else will have to change
* the offsets to be stubs for main table and cache for th table
*/
ASSERT(info1->frozen && info2->frozen);
fragment_coarse_htable_merge_helper(dcontext, dst, ht_dst, info1, ht1, 0);
if (add_info2) {
fragment_coarse_htable_merge_helper(dcontext, dst, ht_dst, info2, ht2,
info1->cache_end_pc - info1->cache_start_pc);
}
if (add_th_htable) {
ASSERT_NOT_TESTED();
fragment_coarse_htable_merge_helper(dcontext, dst, thht_dst, info1, thht1, 0);
fragment_coarse_htable_merge_helper(dcontext, dst, thht_dst, info2, thht2,
/* stubs_end_pc is not allocated end */
info1->mmap_pc + info1->mmap_size -
info1->stubs_start_pc);
}
}
#ifndef DEBUG
/* not in header file unless debug, in which case it's static */
static void
coarse_body_from_htable_entry(dcontext_t *dcontext, coarse_info_t *info, app_pc tag,
cache_pc res, cache_pc *stub_pc_out /*OUT*/,
cache_pc *body_pc_out /*OUT*/);
#endif
static void
study_and_free_coarse_htable(coarse_info_t *info, coarse_table_t *htable,
bool never_persisted _IF_DEBUG(const char *name))
{
LOG(GLOBAL, LOG_FRAGMENT, 1, "Coarse %s %s hashtable stats:\n", info->module, name);
DOLOG(1, LOG_FRAGMENT | LOG_STATS,
{ hashtable_coarse_load_statistics(GLOBAL_DCONTEXT, htable); });
DODEBUG({ hashtable_coarse_study(GLOBAL_DCONTEXT, htable, 0 /*table consistent*/); });
DOLOG(3, LOG_FRAGMENT, { hashtable_coarse_dump_table(GLOBAL_DCONTEXT, htable); });
#ifdef CLIENT_INTERFACE
/* Only raise deletion events if client saw creation events: so no persisted
* units
*/
if (!info->persisted && htable == info->htable && dr_fragment_deleted_hook_exists()) {
app_to_cache_t a2c;
uint i;
dcontext_t *dcontext = get_thread_private_dcontext();
cache_pc body = NULL;
TABLE_RWLOCK(htable, read, lock);
for (i = 0; i < htable->capacity; i++) {
a2c = htable->table[i];
if (A2C_ENTRY_IS_REAL(a2c)) {
if (info->frozen)
body = a2c.cache;
else { /* make sure not an entrance stub w/ no body */
coarse_body_from_htable_entry(dcontext, info, a2c.app, a2c.cache,
NULL, &body);
}
if (body != NULL) {
instrument_fragment_deleted(get_thread_private_dcontext(), a2c.app,
FRAGMENT_COARSE_WRAPPER_FLAGS);
}
}
}
TABLE_RWLOCK(htable, read, unlock);
}
#endif
/* entries are inlined so nothing external to free */
if (info->persisted && !never_persisted) {
/* ensure won't try to free (part of mmap) */
ASSERT(htable->table_unaligned == NULL);
}
hashtable_coarse_free(GLOBAL_DCONTEXT, htable);
NONPERSISTENT_HEAP_TYPE_FREE(GLOBAL_DCONTEXT, htable, coarse_table_t,
ACCT_FRAG_TABLE);
}
void
fragment_coarse_free_entry_pclookup_table(dcontext_t *dcontext, coarse_info_t *info)
{
if (info->pclookup_htable != NULL) {
ASSERT(DYNAMO_OPTION(coarse_pclookup_table));
study_and_free_coarse_htable(info, (coarse_table_t *)info->pclookup_htable,
true /*never persisted*/ _IF_DEBUG("pclookup"));
info->pclookup_htable = NULL;
}
}
void
fragment_coarse_htable_free(coarse_info_t *info)
{
ASSERT_OWN_MUTEX(!info->is_local, &info->lock);
if (info->htable == NULL) {
/* lazily initialized, so common to have empty units */
ASSERT(info->th_htable == NULL);
ASSERT(info->pclookup_htable == NULL);
return;
}
study_and_free_coarse_htable(info, (coarse_table_t *)info->htable,
false _IF_DEBUG("main"));
info->htable = NULL;
study_and_free_coarse_htable(info, (coarse_table_t *)info->th_htable,
false _IF_DEBUG("tracehead"));
info->th_htable = NULL;
if (info->pclookup_last_htable != NULL) {
generic_hash_destroy(GLOBAL_DCONTEXT, info->pclookup_last_htable);
info->pclookup_last_htable = NULL;
}
fragment_coarse_free_entry_pclookup_table(GLOBAL_DCONTEXT, info);
}
uint
fragment_coarse_num_entries(coarse_info_t *info)
{
coarse_table_t *htable;
ASSERT(info != NULL);
htable = (coarse_table_t *)info->htable;
if (htable == NULL)
return 0;
return htable->entries;
}
/* Add coarse fragment represented by wrapper f to the hashtable
* for unit info.
*/
void
fragment_coarse_add(dcontext_t *dcontext, coarse_info_t *info, app_pc tag, cache_pc cache)
{
coarse_table_t *htable;
app_to_cache_t a2c = { tag, cache };
ASSERT(info != NULL && info->htable != NULL);
htable = (coarse_table_t *)info->htable;
DOCHECK(1, {
/* We have lock rank order problems b/c this lookup may acquire
* the th table read lock, and we can't split its rank from
* the main table's. So we live w/ a racy assert that could
* have false positives or negatives.
*/
cache_pc stub;
cache_pc body;
/* OK to have dup entries for entrance stubs in other units,
* or a stub already present for a trace head */
fragment_coarse_lookup_in_unit(dcontext, info, tag, &stub, &body);
ASSERT(body == NULL);
ASSERT(stub == NULL ||
coarse_is_trace_head_in_own_unit(dcontext, tag, stub,
/* case 10876: pass what we're adding */
(ptr_uint_t)cache + info->cache_start_pc,
true, info));
/* There can only be one body. But similarly to above,
* fragment_coarse_lookup may look in the secondary unit, so
* we can't do this lookup holding the write lock.
*/
if (!coarse_is_entrance_stub(cache)) {
coarse_info_t *xinfo = get_executable_area_coarse_info(tag);
fragment_t *f;
ASSERT(xinfo != NULL);
/* If an official unit, tag should not exist in any other official unit */
ASSERT((info != xinfo && info != xinfo->non_frozen) ||
fragment_coarse_lookup(dcontext, tag) == NULL);
f = fragment_lookup(dcontext, tag);
/* ok for trace to shadow coarse trace head */
ASSERT(f == NULL || TEST(FRAG_IS_TRACE, f->flags));
}
});
TABLE_RWLOCK(htable, write, lock);
/* Table is not an ibl table so we ignore resize return value */
hashtable_coarse_add(dcontext, a2c, htable);
TABLE_RWLOCK(htable, write, unlock);
#ifdef SHARING_STUDY
if (INTERNAL_OPTION(fragment_sharing_study)) {
ASSERT_NOT_IMPLEMENTED(false && "need to pass f in to add_shared_block");
}
#endif
}
/* Returns the body pc of the coarse trace head fragment corresponding to tag, or
* NULL if not found. Caller must hold the th table's read or write lock!
*/
static cache_pc
fragment_coarse_th_lookup(dcontext_t *dcontext, coarse_info_t *info, app_pc tag)
{
cache_pc res = NULL;
app_to_cache_t a2c;
coarse_table_t *htable;
ASSERT(info != NULL);
ASSERT(info->htable != NULL);
htable = (coarse_table_t *)info->th_htable;
ASSERT(TABLE_PROTECTED(htable));
a2c = coarse_lookup_internal(dcontext, tag, htable);
if (!A2C_ENTRY_IS_EMPTY(a2c)) {
ASSERT(BOOLS_MATCH(info->frozen, info->stubs_start_pc != NULL));
/* for frozen, th_htable only holds stubs */
res = ((ptr_uint_t)a2c.cache) + info->stubs_start_pc;
}
return res;
}
/* Performs two actions while holding the trace head table's write lock,
* making them atomic (solving the race in case 8795):
* 1) unlinks the coarse fragment's entrance pc and points it at the
* trace head exit routine;
* 2) adds the coarse fragment's body pc to the trace head hashtable.
*
* Case 8628: if we split the main htable into stubs and bodies then
* we can eliminate the th htable as it will be part of the body table.
*
* We could merge this info in to the thcounter table, and assume that
* most trace heads are coarse so we're not wasting much memory with
* the extra field. But then we have to walk entire stub table on
* cache flush and individually clear body pcs from monitor table, so
* better to have own th table?
*/
void
fragment_coarse_th_unlink_and_add(dcontext_t *dcontext, app_pc tag, cache_pc stub_pc,
cache_pc body_pc)
{
ASSERT(stub_pc != NULL);
if (body_pc != NULL) {
/* trace head is in this unit, so we have to add it to our th htable */
coarse_info_t *info = get_fcache_coarse_info(body_pc);
coarse_table_t *th_htable;
app_to_cache_t a2c = { tag, body_pc };
ASSERT(info != NULL && info->th_htable != NULL);
ASSERT(!info->frozen);
th_htable = (coarse_table_t *)info->th_htable;
TABLE_RWLOCK(th_htable, write, lock);
ASSERT(fragment_coarse_th_lookup(dcontext, info, tag) == NULL);
unlink_entrance_stub(dcontext, stub_pc, FRAG_IS_TRACE_HEAD, info);
/* Table is not an ibl table so we ignore resize return value */
hashtable_coarse_add(dcontext, a2c, th_htable);
TABLE_RWLOCK(th_htable, write, unlock);
LOG(THREAD, LOG_FRAGMENT, 4,
"adding to coarse th table for %s: " PFX "->" PFX "\n", info->module, tag,
body_pc);
} else {
/* ensure lives in another unit */
ASSERT(fragment_coarse_lookup(dcontext, tag) != stub_pc);
unlink_entrance_stub(dcontext, stub_pc, FRAG_IS_TRACE_HEAD, NULL);
}
}
/* Only use when building up a brand-new table. Otherwise use
* fragment_coarse_th_unlink_and_add().
*/
void
fragment_coarse_th_add(dcontext_t *dcontext, coarse_info_t *info, app_pc tag,
cache_pc cache)
{
coarse_table_t *th_htable;
app_to_cache_t a2c = { tag, cache };
ASSERT(info != NULL && info->th_htable != NULL);
ASSERT(info->frozen); /* only used when merging units */
th_htable = (coarse_table_t *)info->th_htable;
TABLE_RWLOCK(th_htable, write, lock);
ASSERT(fragment_coarse_th_lookup(dcontext, info, tag) == NULL);
/* Table is not an ibl table so we ignore resize return value */
hashtable_coarse_add(dcontext, a2c, th_htable);
TABLE_RWLOCK(th_htable, write, unlock);
}
/* The input here is the result of a lookup in the main htable.
* For a frozen unit, this actually looks up the stub pc since res is
* always the body pc.
* For a non-frozen unit this determines where to obtain the body pc.
* FIXME: case 8628 will simplify this whole thing
*/
/* exported only for assert in push_pending_freeze() */
IF_DEBUG_ELSE(, static)
void
coarse_body_from_htable_entry(dcontext_t *dcontext, coarse_info_t *info, app_pc tag,
cache_pc res, cache_pc *stub_pc_out /*OUT*/,
cache_pc *body_pc_out /*OUT*/)
{
cache_pc stub_pc = NULL, body_pc = NULL;
/* Should be passing absolute pc, not offset */
ASSERT(!info->frozen || res == NULL || res >= info->cache_start_pc);
if (info->frozen) {
/* We still need the stub table for lazy linking and for
shifting links from a trace head to a trace.
*/
body_pc = res;
if (stub_pc_out != NULL) {
TABLE_RWLOCK((coarse_table_t *)info->th_htable, read, lock);
stub_pc = fragment_coarse_th_lookup(dcontext, info, tag);
TABLE_RWLOCK((coarse_table_t *)info->th_htable, read, unlock);
}
} else {
/* In a non-frozen unit, htable entries are always stubs */
DOCHECK(CHKLVL_DEFAULT + 1, { ASSERT(coarse_is_entrance_stub(res)); });
stub_pc = res;
if (body_pc_out != NULL) {
/* keep the th table entry and stub link status linked atomically */
TABLE_RWLOCK((coarse_table_t *)info->th_htable, read, lock);
body_pc = fragment_coarse_th_lookup(dcontext, info, tag);
if (body_pc != NULL) {
/* We can't just check coarse_is_trace_head(res) because a
* shadowed trace head is directly linked to its trace. The
* trace has lookup order precedence, but the head must show up
* if asked about here!
*/
/* FIXME: we could have a flags OUT param and set FRAG_IS_TRACE_HEAD
* to help out fragment_lookup_fine_and_coarse*().
*/
} else {
if (entrance_stub_linked(res, info)) {
/* We only want to set body_pc if it is present in this unit */
cache_pc tgt = entrance_stub_jmp_target(res);
if (get_fcache_coarse_info(tgt) == info)
body_pc = tgt;
else
body_pc = NULL;
} else
body_pc = NULL;
DOCHECK(CHKLVL_DEFAULT + 1, {
ASSERT(!coarse_is_trace_head(res) ||
/* allow targeting trace head in another unit */
body_pc == NULL);
});
}
TABLE_RWLOCK((coarse_table_t *)info->th_htable, read, unlock);
}
}
if (stub_pc_out != NULL)
*stub_pc_out = stub_pc;
if (body_pc_out != NULL)
*body_pc_out = body_pc;
}
/* Coarse fragments have two entrance points: the actual fragment
* body, and the entrance stub that is used for indirection and
* convenient incremental building for intra-unit non-frozen linking
* as well as always used at the source end for inter-unit linking.
* This routine returns both. If the stub_pc returned is non-NULL, it
* only indicates that there is an outgoing link from a fragment
* present in this unit that targets the queried tag (and for
* intra-unit links in a frozen unit, such a link may exist but
* stub_pc will be NULL as the entrance stub indirection will have
* been replaced with a direct link). The fragment corresponding to
* the tag is only present in this unit if the body_pc returned is
* non-NULL.
*/
void
fragment_coarse_lookup_in_unit(dcontext_t *dcontext, coarse_info_t *info, app_pc tag,
/* FIXME: have separate type for stub pc vs body pc? */
cache_pc *stub_pc_out /*OUT*/,
cache_pc *body_pc_out /*OUT*/)
{
cache_pc res = NULL;
cache_pc stub_pc = NULL, body_pc = NULL;
app_to_cache_t a2c;
coarse_table_t *htable;
ASSERT(info != NULL);
if (info->htable == NULL) /* not initialized yet, so no code there */
goto coarse_lookup_return;
htable = (coarse_table_t *)info->htable;
TABLE_RWLOCK(htable, read, lock);
a2c = coarse_lookup_internal(dcontext, tag, htable);
if (!A2C_ENTRY_IS_EMPTY(a2c)) {
LOG(THREAD, LOG_FRAGMENT, 5,
"%s: %s %s tag=" PFX " => app=" PFX " cache=" PFX "\n", __FUNCTION__,
info->module, info->frozen ? "frozen" : "", tag, a2c.app, a2c.cache);
ASSERT(BOOLS_MATCH(info->frozen, info->cache_start_pc != NULL));
/* for frozen, htable only holds body pc */
res = ((ptr_uint_t)a2c.cache) + info->cache_start_pc;
}
if (res != NULL)
coarse_body_from_htable_entry(dcontext, info, tag, res, &stub_pc, &body_pc);
else if (info->frozen) /* need a separate lookup for stub */
coarse_body_from_htable_entry(dcontext, info, tag, res, &stub_pc, &body_pc);
TABLE_RWLOCK(htable, read, unlock);
/* cannot have both a shared coarse and shared fine bb for same tag
* (can have shared trace shadowing shared coarse trace head bb, or
* private bb shadowing shared coarse bb)
*/
ASSERT(body_pc == NULL || fragment_lookup_shared_bb(dcontext, tag) == NULL);
coarse_lookup_return:
if (stub_pc_out != NULL)
*stub_pc_out = stub_pc;
if (body_pc_out != NULL)
*body_pc_out = body_pc;
}
/* Returns the body pc of the coarse fragment corresponding to tag, or
* NULL if not found
*/
cache_pc
fragment_coarse_lookup(dcontext_t *dcontext, app_pc tag)
{
cache_pc res = NULL;
coarse_info_t *info = get_executable_area_coarse_info(tag);
/* We must check each unit in turn */
while (info != NULL) { /* loop over primary and secondary unit */
fragment_coarse_lookup_in_unit(dcontext, info, tag, NULL, &res);
if (res != NULL)
return res;
ASSERT(info->frozen || info->non_frozen == NULL);
info = info->non_frozen;
ASSERT(info == NULL || !info->frozen);
}
return NULL;
}
/* It's up to the caller to hold locks preventing simultaneous writes to wrapper */
void
fragment_coarse_wrapper(fragment_t *wrapper, app_pc tag, cache_pc body_pc)
{
ASSERT(wrapper != NULL);
if (wrapper == NULL)
return;
ASSERT(tag != NULL);
ASSERT(body_pc != NULL);
/* FIXME: fragile to rely on other routines not inspecting other
* fields of fragment_t -- but setting to 0 perhaps no better than garbage
* in that case. We do need to set prefix_size, incoming_stubs, and
* {next,prev}_vmarea to NULL, for sure.
*/
memset(wrapper, 0, sizeof(*wrapper));
wrapper->tag = tag;
wrapper->start_pc = body_pc;
wrapper->flags = FRAGMENT_COARSE_WRAPPER_FLAGS;
/* We don't have stub pc so can't fill in FRAG_IS_TRACE_HEAD -- so we rely
* on callers passing src info to fragment_lookup_fine_and_coarse()
*/
}
/* If finds a coarse fragment for tag, returns wrapper; else returns NULL */
fragment_t *
fragment_coarse_lookup_wrapper(dcontext_t *dcontext, app_pc tag, fragment_t *wrapper)
{
cache_pc coarse;
ASSERT(wrapper != NULL);
coarse = fragment_coarse_lookup(dcontext, tag);
if (coarse != NULL) {
fragment_coarse_wrapper(wrapper, tag, coarse);
return wrapper;
}
return NULL;
}
/* Takes in last_exit in order to mark trace headness.
* FIXME case 8600: should we replace all other lookups with this one?
* Fragile to only have select callers use this and everyone else
* ignore coarse fragments...
*/
fragment_t *
fragment_lookup_fine_and_coarse(dcontext_t *dcontext, app_pc tag, fragment_t *wrapper,
linkstub_t *last_exit)
{
fragment_t *res = fragment_lookup(dcontext, tag);
if (DYNAMO_OPTION(coarse_units)) {
ASSERT(wrapper != NULL);
if (res == NULL) {
res = fragment_coarse_lookup_wrapper(dcontext, tag, wrapper);
/* FIXME: no way to know if source is a fine fragment! */
if (res != NULL && last_exit == get_coarse_trace_head_exit_linkstub())
res->flags |= FRAG_IS_TRACE_HEAD;
} else {
/* cannot have both coarse and fine shared bb for same tag
* (can have shared trace shadowing shared coarse trace head bb,
* or private bb with same tag)
*/
ASSERT(TEST(FRAG_IS_TRACE, res->flags) || !TEST(FRAG_SHARED, res->flags) ||
fragment_coarse_lookup(dcontext, tag) == NULL);
}
}
return res;
}
/* Takes in last_exit in order to mark trace headness.
* FIXME: should we replace all other same_sharing lookups with this one?
* Fragile to only have select callers use this and everyone else
* ignore coarse fragments...
*/
fragment_t *
fragment_lookup_fine_and_coarse_sharing(dcontext_t *dcontext, app_pc tag,
fragment_t *wrapper, linkstub_t *last_exit,
uint share_flags)
{
fragment_t *res = fragment_lookup_same_sharing(dcontext, tag, share_flags);
if (DYNAMO_OPTION(coarse_units) && TEST(FRAG_SHARED, share_flags)) {
ASSERT(wrapper != NULL);
if (res == NULL) {
res = fragment_coarse_lookup_wrapper(dcontext, tag, wrapper);
if (res != NULL && last_exit == get_coarse_trace_head_exit_linkstub())
res->flags |= FRAG_IS_TRACE_HEAD;
}
}
return res;
}
/* Returns the owning unit of f (versus get_executable_area_coarse_info(f->tag)
* which may return a frozen unit that must be checked for f along with its
* secondary unfrozen unit).
*/
coarse_info_t *
get_fragment_coarse_info(fragment_t *f)
{
/* We have multiple potential units per vmarea region, so we use the fcache
* pc to get the unambiguous owning unit
*/
if (!TEST(FRAG_COARSE_GRAIN, f->flags))
return NULL;
ASSERT(FCACHE_ENTRY_PC(f) != NULL);
return get_fcache_coarse_info(FCACHE_ENTRY_PC(f));
}
/* Pass in info if you know it; else this routine will look it up.
* Checks for stub targeting a trace head, or targeting a trace thus
* indicating that this is a shadowed trace head.
* If body_in or info_in is NULL, this routine will look them up.
*/
bool
coarse_is_trace_head_in_own_unit(dcontext_t *dcontext, app_pc tag, cache_pc stub,
cache_pc body_in, bool body_valid,
coarse_info_t *info_in)
{
coarse_info_t *info = info_in;
ASSERT(stub != NULL);
if (coarse_is_trace_head(stub))
return true;
if (info == NULL)
info = get_stub_coarse_info(stub);
if (info == NULL)
return false;
/* If a coarse stub is linked to a fine fragment and there exists
* a body for that target tag in the same unit as the stub, we assume that
* we have a shadowed coarse trace head.
*/
if (entrance_stub_linked(stub, info) &&
/* Target is fine if no info for it */
get_fcache_coarse_info(entrance_stub_jmp_target(stub)) == NULL) {
cache_pc body = body_in;
if (!body_valid) {
ASSERT(body == NULL);
fragment_coarse_lookup_in_unit(dcontext, info, tag, NULL, &body);
}
if (body != NULL)
return true;
}
return false;
}
/* Returns whether an entry exists. */
bool
fragment_coarse_replace(dcontext_t *dcontext, coarse_info_t *info, app_pc tag,
cache_pc new_value)
{
app_to_cache_t old_entry = { tag, NULL /*doesn't matter*/ };
app_to_cache_t new_entry = { tag, new_value };
coarse_table_t *htable;
bool res = false;
ASSERT(info != NULL && info->htable != NULL);
htable = (coarse_table_t *)info->htable;
TABLE_RWLOCK(htable, read, lock);
res = hashtable_coarse_replace(old_entry, new_entry, info->htable);
TABLE_RWLOCK(htable, read, unlock);
return res;
}
/**************************************************
* PC LOOKUP
*/
/* Table for storing results of prior coarse pclookups (i#658) */
#define PCLOOKUP_LAST_HTABLE_INIT_SIZE 6 /*should remain small*/
/* Alarm signals can result in many pclookups from a variety of places
* (unlike usual DGC patterns) so we bound the size of the table.
* We want to err on the side of using more memory, since failing to
* cache all the instrs that are writing DGC can result in 2x slowdowns.
* It's not worth fancy replacement: we just clear the table if it gets
* really large and start over. Remember that this is per-coarse-unit.
*/
#define PCLOOKUP_LAST_HTABLE_MAX_ENTRIES 8192
typedef struct _pclookup_last_t {
app_pc tag;
cache_pc entry;
} pclookup_last_t;
static void
pclookup_last_free(dcontext_t *dcontext, void *last)
{
HEAP_TYPE_FREE(GLOBAL_DCONTEXT, last, pclookup_last_t, ACCT_FRAG_TABLE, PROTECTED);
}
/* Returns the tag for the coarse fragment whose body contains pc.
* If that returned tag != NULL, also returns the body pc in the optional OUT param.
* FIXME: verify not called too often: watch the kstat.
*/
app_pc
fragment_coarse_pclookup(dcontext_t *dcontext, coarse_info_t *info, cache_pc pc,
/*OUT*/ cache_pc *body_out)
{
app_to_cache_t a2c;
coarse_table_t *htable;
generic_table_t *pc_htable;
pclookup_last_t *last;
cache_pc body_pc;
ssize_t closest_distance = SSIZE_T_MAX;
app_pc closest = NULL;
uint i;
ASSERT(info != NULL);
if (info->htable == NULL)
return NULL;
KSTART(coarse_pclookup);
htable = (coarse_table_t *)info->htable;
if (info->pclookup_last_htable == NULL) {
/* lazily allocate table of all pclookups to avoid htable walk
* on frequent codemod instrs (i#658).
* I tried using a small array instead but chrome v8 needs at least
* 12 entries, and rather than LFU or LRU to avoid worst-case,
* it seems reasonable to simply store all lookups.
* Then the worst case is some extra memory, not 4x slowdowns.
*/
d_r_mutex_lock(&info->lock);
if (info->pclookup_last_htable == NULL) {
/* coarse_table_t isn't quite enough b/c we need the body pc,
* which would require an extra lookup w/ coarse_table_t
*/
pc_htable =
generic_hash_create(GLOBAL_DCONTEXT, PCLOOKUP_LAST_HTABLE_INIT_SIZE,
80 /* load factor: not perf-critical */,
HASHTABLE_ENTRY_SHARED | HASHTABLE_SHARED |
HASHTABLE_RELAX_CLUSTER_CHECKS,
pclookup_last_free _IF_DEBUG("pclookup last table"));
/* Only when fully initialized can we set it, as we hold no lock for it */
info->pclookup_last_htable = (void *)pc_htable;
}
d_r_mutex_unlock(&info->lock);
}
pc_htable = (generic_table_t *)info->pclookup_last_htable;
ASSERT(pc_htable != NULL);
TABLE_RWLOCK(pc_htable, read, lock);
last = (pclookup_last_t *)generic_hash_lookup(GLOBAL_DCONTEXT, pc_htable,
(ptr_uint_t)pc);
if (last != NULL) {
closest = last->tag;
ASSERT(pc >= last->entry);
closest_distance = pc - last->entry;
}
TABLE_RWLOCK(pc_htable, read, unlock);
if (closest == NULL) {
/* do the htable walk */
TABLE_RWLOCK(htable, read, lock);
for (i = 0; i < htable->capacity; i++) {
a2c = htable->table[i];
/* must check for sentinel */
if (A2C_ENTRY_IS_REAL(a2c)) {
a2c.app -= htable->mod_shift;
ASSERT(BOOLS_MATCH(info->frozen, info->cache_start_pc != NULL));
/* for frozen, htable only holds body pc */
a2c.cache += (ptr_uint_t)info->cache_start_pc;
/* We have no body length so we must walk entire table */
coarse_body_from_htable_entry(dcontext, info, a2c.app, a2c.cache, NULL,
&body_pc);
if (body_pc != NULL && body_pc <= pc &&
(pc - body_pc) < closest_distance) {
closest_distance = pc - body_pc;
closest = a2c.app;
}
}
}
if (closest != NULL) {
/* Update the cache of results. Note that since this is coarse we
* don't have to do anything special to invalidate on codemod as the
* whole coarse unit will be thrown out.
*/
TABLE_RWLOCK(pc_htable, write, lock);
/* Check for race (i#1191) */
last = (pclookup_last_t *)generic_hash_lookup(GLOBAL_DCONTEXT, pc_htable,
(ptr_uint_t)pc);
if (last != NULL) {
closest = last->tag;
ASSERT(pc >= last->entry);
closest_distance = pc - last->entry;
} else {
last = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, pclookup_last_t, ACCT_FRAG_TABLE,
PROTECTED);
last->tag = closest;
last->entry = pc - closest_distance;
if (pc_htable->entries >= PCLOOKUP_LAST_HTABLE_MAX_ENTRIES) {
/* See notes above: we don't want an enormous table.
* We just clear rather than a fancy replacement policy.
*/
generic_hash_clear(GLOBAL_DCONTEXT, pc_htable);
}
generic_hash_add(GLOBAL_DCONTEXT, pc_htable, (ptr_uint_t)pc,
(void *)last);
STATS_INC(coarse_pclookup_cached);
}
TABLE_RWLOCK(pc_htable, write, unlock);
}
TABLE_RWLOCK(htable, read, unlock);
}
if (body_out != NULL)
*body_out = pc - closest_distance;
KSTOP(coarse_pclookup);
LOG(THREAD, LOG_FRAGMENT, 4, "%s: " PFX " => " PFX "\n", __FUNCTION__, pc, closest);
return closest;
}
/* Creates a reverse lookup table. For a non-frozen unit, the caller should only
* do this while all threads are suspended, and should free the table before
* resuming other threads.
*/
void
fragment_coarse_create_entry_pclookup_table(dcontext_t *dcontext, coarse_info_t *info)
{
app_to_cache_t main_a2c;
app_to_cache_t pc_a2c;
coarse_table_t *main_htable;
coarse_table_t *pc_htable;
cache_pc body_pc;
uint i;
ASSERT(info != NULL);
if (info->htable == NULL)
return;
if (info->pclookup_htable == NULL) {
d_r_mutex_lock(&info->lock);
if (info->pclookup_htable == NULL) {
/* set up reverse lookup table */
main_htable = (coarse_table_t *)info->htable;
pc_htable = NONPERSISTENT_HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, coarse_table_t,
ACCT_FRAG_TABLE);
hashtable_coarse_init(
GLOBAL_DCONTEXT, pc_htable, main_htable->hash_bits,
DYNAMO_OPTION(coarse_pclookup_htable_load),
(hash_function_t)INTERNAL_OPTION(alt_hash_func), 0 /* hash_mask_offset */,
HASHTABLE_ENTRY_SHARED | HASHTABLE_SHARED |
HASHTABLE_RELAX_CLUSTER_CHECKS _IF_DEBUG("coarse pclookup htable"));
pc_htable->mod_shift = 0;
/* We give pc table a lower lock rank so we can add below
* while holding the lock, though the table is still local
* while we hold info->lock and do not write it out to its
* info-> field, so we could update the add() and
* deadlock-avoidance routines instead (xref case 9522).
* FIXME: add param to init() that takes in lock rank?
*/
ASSIGN_INIT_READWRITE_LOCK_FREE(pc_htable->rwlock,
coarse_pclookup_table_rwlock);
TABLE_RWLOCK(main_htable, read, lock);
TABLE_RWLOCK(pc_htable, write, lock);
for (i = 0; i < main_htable->capacity; i++) {
main_a2c = main_htable->table[i];
/* must check for sentinel */
if (A2C_ENTRY_IS_REAL(main_a2c)) {
main_a2c.app -= main_htable->mod_shift;
ASSERT(BOOLS_MATCH(info->frozen, info->cache_start_pc != NULL));
coarse_body_from_htable_entry(
dcontext, info, main_a2c.app,
main_a2c.cache
/* frozen htable only holds body pc */
+ (ptr_uint_t)info->cache_start_pc,
NULL, &body_pc);
if (body_pc != NULL) {
/* We can have two tags with the same cache pc, if
* one is a single jmp that was elided (but we only
* do that if -unsafe_freeze_elide_sole_ubr).
* It's unsafe b/c of case 9677: when translating back
* to app pc we will just take 1st one in linear walk of
* htable, which may be the wrong one!
*/
pc_a2c = hashtable_coarse_lookup(dcontext, (ptr_uint_t)body_pc,
pc_htable);
if (A2C_ENTRY_IS_EMPTY(pc_a2c)) {
pc_a2c.app = body_pc;
pc_a2c.cache = main_a2c.app;
hashtable_coarse_add(dcontext, pc_a2c, pc_htable);
} else {
ASSERT(DYNAMO_OPTION(unsafe_freeze_elide_sole_ubr));
}
}
}
}
TABLE_RWLOCK(pc_htable, write, unlock);
TABLE_RWLOCK(main_htable, read, unlock);
/* Only when fully initialized can we set it, as we hold no lock for it */
info->pclookup_htable = (void *)pc_htable;
}
d_r_mutex_unlock(&info->lock);
}
}
/* Returns the tag for the coarse fragment whose body _begins at_ pc */
app_pc
fragment_coarse_entry_pclookup(dcontext_t *dcontext, coarse_info_t *info, cache_pc pc)
{
app_to_cache_t pc_a2c;
coarse_table_t *pc_htable;
cache_pc body_pc;
app_pc res = NULL;
ASSERT(info != NULL);
if (info->htable == NULL)
return NULL;
/* FIXME: we could use this table for non-frozen if we updated it
* when we add to main htable; for now we only support frozen use
*/
if (!DYNAMO_OPTION(coarse_pclookup_table) ||
/* we do create a table for non-frozen while we're freezing (i#735) */
(!info->frozen && info->pclookup_htable == NULL)) {
res = fragment_coarse_pclookup(dcontext, info, pc, &body_pc);
if (body_pc == pc) {
LOG(THREAD, LOG_FRAGMENT, 4, "%s: " PFX " => " PFX "\n", __FUNCTION__, pc,
res);
return res;
} else
return NULL;
}
KSTART(coarse_pclookup);
if (info->pclookup_htable == NULL) {
fragment_coarse_create_entry_pclookup_table(dcontext, info);
}
pc_htable = (coarse_table_t *)info->pclookup_htable;
ASSERT(pc_htable != NULL);
TABLE_RWLOCK(pc_htable, read, lock);
pc_a2c = hashtable_coarse_lookup(dcontext, (ptr_uint_t)pc, pc_htable);
if (!A2C_ENTRY_IS_EMPTY(pc_a2c))
res = pc_a2c.cache;
TABLE_RWLOCK(pc_htable, read, unlock);
KSTOP(coarse_pclookup);
LOG(THREAD, LOG_FRAGMENT, 4, "%s: " PFX " => " PFX "\n", __FUNCTION__, pc, res);
return res;
}
/* case 9900: must have dynamo_all_threads_synched since we haven't resolved
* lock rank ordering issues with the hashtable locks
*/
static void
fragment_coarse_entry_freeze(dcontext_t *dcontext, coarse_freeze_info_t *freeze_info,
pending_freeze_t *pending)
{
app_to_cache_t frozen_a2c;
app_to_cache_t looka2c = { 0, 0 };
coarse_table_t *frozen_htable;
cache_pc tgt;
if (pending->entrance_stub) {
frozen_htable = (coarse_table_t *)freeze_info->dst_info->th_htable;
/* case 9900: rank order conflict with coarse_info_incoming_lock:
* do not grab frozen_htable write lock (only need read but we were
* grabbing write to match assert): mark is_local instead and rely
* on dynamo_all_threads_synched
*/
DODEBUG({ frozen_htable->is_local = true; });
ASSERT_NOT_IMPLEMENTED(dynamo_all_threads_synched && "case 9900");
} else {
frozen_htable = (coarse_table_t *)freeze_info->dst_info->htable;
}
ASSERT_OWN_WRITE_LOCK(!frozen_htable->is_local, &frozen_htable->rwlock);
looka2c = coarse_lookup_internal(dcontext, pending->tag, frozen_htable);
if (A2C_ENTRY_IS_EMPTY(looka2c)) {
frozen_a2c.app = pending->tag;
if (pending->entrance_stub) {
/* add inter-unit/trace-head stub to htable */
LOG(THREAD, LOG_FRAGMENT, 4,
" adding pending stub " PFX "." PFX " => " PFX "\n", pending->tag,
pending->cur_pc, freeze_info->stubs_cur_pc);
frozen_a2c.cache =
(cache_pc)(freeze_info->stubs_cur_pc - freeze_info->stubs_start_pc);
hashtable_coarse_add(dcontext, frozen_a2c, frozen_htable);
/* copy to new stubs area */
transfer_coarse_stub(dcontext, freeze_info, pending->cur_pc,
pending->trace_head, true /*replace*/);
} else {
/* fall-through optimization */
if (DYNAMO_OPTION(coarse_freeze_elide_ubr) &&
pending->link_cti_opnd != NULL &&
pending->link_cti_opnd + 4 == freeze_info->cache_cur_pc &&
pending->elide_ubr) {
ASSERT(!pending->trace_head);
LOG(THREAD, LOG_FRAGMENT, 4, " fall-through opt from prev fragment\n");
freeze_info->cache_cur_pc -= JMP_LONG_LENGTH;
pending->link_cti_opnd = NULL;
STATS_INC(coarse_freeze_fallthrough);
DODEBUG({ freeze_info->num_elisions++; });
}
LOG(THREAD, LOG_FRAGMENT, 4,
" adding pending %sfragment " PFX "." PFX " => " PFX "\n",
pending->trace_head ? "trace head " : "", pending->tag, pending->cur_pc,
freeze_info->cache_cur_pc);
/* add to htable the offset from start of cache */
frozen_a2c.cache =
(cache_pc)(freeze_info->cache_cur_pc - freeze_info->cache_start_pc);
hashtable_coarse_add(dcontext, frozen_a2c, frozen_htable);
/* copy to new cache */
transfer_coarse_fragment(dcontext, freeze_info, pending->cur_pc);
}
tgt = frozen_a2c.cache;
} else {
tgt = looka2c.cache;
/* Should not hit any links to TH, so should hit once, from htable walk */
ASSERT(!pending->trace_head || pending->entrance_stub);
/* May have added entrance stub for intra-unit TH as non-TH if it was
* linked to a trace, since didn't have body pc at the time, so we
* fix up here on the proactive add when adding its body
*/
if (pending->entrance_stub && pending->trace_head && freeze_info->unlink) {
cache_pc abs_tgt = tgt + (ptr_uint_t)freeze_info->stubs_start_pc;
transfer_coarse_stub_fix_trace_head(dcontext, freeze_info, abs_tgt);
}
}
if (pending->link_cti_opnd != NULL) {
/* fix up incoming link */
cache_pc patch_tgt = (cache_pc)(
((ptr_uint_t)(pending->entrance_stub ? freeze_info->stubs_start_pc
: freeze_info->cache_start_pc)) +
tgt);
ASSERT(!pending->trace_head || pending->entrance_stub);
LOG(THREAD, LOG_FRAGMENT, 4, " patch link " PFX " => " PFX "." PFX "%s\n",
pending->link_cti_opnd, pending->tag, patch_tgt,
pending->entrance_stub ? " stub" : "");
insert_relative_target(pending->link_cti_opnd, patch_tgt, NOT_HOT_PATCHABLE);
}
if (pending->entrance_stub) {
DODEBUG({ frozen_htable->is_local = false; });
}
}
/* There are several strategies for copying each fragment and non-inter-unit stub
* to new, compact storage. Here we use a cache-driven approach, necessarily
* augmented with the htable as we cannot find tags for arbitrary fragments in
* the cache. We use a pending-add stack to avoid a second pass.
* By adding ubr targets last, we can elide fall-through jmps.
* FIXME case 9428:
* - Sorting entrance stubs for faster lazy linking lookup
* - Use 8-bit-relative jmps when possible for compaction, though this
* requires pc translation support and probably an extra pass when freezing.
*
* Tasks:
* Copy each new fragment and non-inter-unit stub to the new region
* Unlink all inter-unit entrance stubs, unless freezing and not
* writing to disk.
* Re-target intra-unit jmps from old entrance stub to new fragment location
* Re-target jmp to stub
* Re-target indirect stubs to new prefix
* Re-target inter-unit and trace head stubs to new prefix
*
* case 9900: must have dynamo_all_threads_synched since we haven't resolved
* lock rank ordering issues with the hashtable locks
*/
void
fragment_coarse_unit_freeze(dcontext_t *dcontext, coarse_freeze_info_t *freeze_info)
{
pending_freeze_t pending_local;
pending_freeze_t *pending;
app_to_cache_t a2c;
coarse_table_t *frozen_htable;
coarse_table_t *htable;
cache_pc body_pc;
uint i;
ASSERT(freeze_info != NULL && freeze_info->src_info != NULL);
if (freeze_info->src_info->htable == NULL)
return;
LOG(THREAD, LOG_FRAGMENT, 2, "freezing fragments in %s\n",
freeze_info->src_info->module);
/* we walk just the main htable and find trace heads by asking for the body pc */
htable = (coarse_table_t *)freeze_info->src_info->htable;
DOSTATS({
LOG(THREAD, LOG_ALL, 1, "htable pre-freezing %s\n",
freeze_info->src_info->module);
hashtable_coarse_study(dcontext, htable, 0 /*clean state*/);
});
frozen_htable = (coarse_table_t *)freeze_info->dst_info->htable;
/* case 9900: rank order conflict with coarse_info_incoming_lock:
* do not grab frozen_htable write lock: mark is_local instead and rely
* on dynamo_all_threads_synched
*/
DODEBUG({ frozen_htable->is_local = true; });
ASSERT_NOT_IMPLEMENTED(dynamo_all_threads_synched && "case 9900");
/* FIXME case 9522: not grabbing TABLE_RWLOCK(htable, read, lock) due to
* rank order violation with frozen_htable write lock! We go w/ the write
* lock since lookup routines check for it. To solve we'll need a way to
* tell deadlock checking that frozen_htable is private to this thread and
* that no other thread can hold its lock. For now we only support
* all-synch, but if later we want !in_place that needs no synch we'll need
* a solution.
*/
ASSERT_NOT_IMPLEMENTED(dynamo_all_threads_synched && "case 9522");
/* FIXME: we're doing htable order, better to use either tag (original app)
* or cache (execution) order?
*/
for (i = 0; i < htable->capacity || freeze_info->pending != NULL; i++) {
/* Process pending entries first; then continue through htable */
while (freeze_info->pending != NULL) {
pending = freeze_info->pending;
freeze_info->pending = pending->next;
fragment_coarse_entry_freeze(dcontext, freeze_info, pending);
HEAP_TYPE_FREE(dcontext, pending, pending_freeze_t,
ACCT_MEM_MGT /*appropriate?*/, UNPROTECTED);
}
if (i < htable->capacity) {
a2c = htable->table[i];
/* must check for sentinel */
if (!A2C_ENTRY_IS_REAL(a2c))
continue;
} else
continue;
LOG(THREAD, LOG_FRAGMENT, 4, " %d app=" PFX ", cache=" PFX "\n", i, a2c.app,
a2c.cache);
coarse_body_from_htable_entry(dcontext, freeze_info->src_info, a2c.app, a2c.cache,
NULL, &body_pc);
if (body_pc == NULL) {
/* We add only when targeted by fragments, so we don't have to
* figure out multiple times whether intra-unit or not
*/
LOG(THREAD, LOG_FRAGMENT, 4, " ignoring entrance stub " PFX "\n", a2c.cache);
} else {
pending_local.tag = a2c.app;
pending_local.cur_pc = body_pc;
pending_local.entrance_stub = false;
pending_local.link_cti_opnd = NULL;
pending_local.elide_ubr = true; /* doesn't matter since no link */
pending_local.trace_head = coarse_is_trace_head_in_own_unit(
dcontext, a2c.app, a2c.cache, body_pc, true, freeze_info->src_info);
pending_local.next = NULL;
fragment_coarse_entry_freeze(dcontext, freeze_info, &pending_local);
if (pending_local.trace_head) {
/* we do need to proactively add the entrance stub, in
* case it is only targeted by an indirect branch
*/
LOG(THREAD, LOG_FRAGMENT, 4,
" adding trace head entrance stub " PFX "\n", a2c.cache);
pending_local.tag = a2c.app;
pending_local.cur_pc = a2c.cache;
pending_local.entrance_stub = true;
pending_local.link_cti_opnd = NULL;
pending_local.elide_ubr = true; /* doesn't matter since no link */
pending_local.trace_head = true;
fragment_coarse_entry_freeze(dcontext, freeze_info, &pending_local);
}
}
}
DODEBUG({ frozen_htable->is_local = false; });
DOSTATS({
/* The act of freezing tends to improve hashtable layout */
LOG(THREAD, LOG_ALL, 1, "htable post-freezing %s\n",
freeze_info->src_info->module);
hashtable_coarse_study(dcontext, frozen_htable, 0 /*clean state*/);
});
}
uint
fragment_coarse_htable_persist_size(dcontext_t *dcontext, coarse_info_t *info,
bool cache_table)
{
coarse_table_t *htable =
(coarse_table_t *)(cache_table ? info->htable : info->th_htable);
return hashtable_coarse_persist_size(dcontext, htable);
}
/* Returns true iff all writes succeeded. */
bool
fragment_coarse_htable_persist(dcontext_t *dcontext, coarse_info_t *info,
bool cache_table, file_t fd)
{
coarse_table_t *htable =
(coarse_table_t *)(cache_table ? info->htable : info->th_htable);
ASSERT(fd != INVALID_FILE);
return hashtable_coarse_persist(dcontext, htable, fd);
}
void
fragment_coarse_htable_resurrect(dcontext_t *dcontext, coarse_info_t *info,
bool cache_table, byte *mapped_table)
{
coarse_table_t **htable =
(coarse_table_t **)(cache_table ? &info->htable : &info->th_htable);
ASSERT(info->frozen);
ASSERT(mapped_table != NULL);
ASSERT(*htable == NULL);
*htable = hashtable_coarse_resurrect(
dcontext,
mapped_table _IF_DEBUG(cache_table ? "persisted cache htable"
: "persisted stub htable"));
(*htable)->mod_shift = info->mod_shift;
/* generally want to keep basic alignment */
ASSERT_CURIOSITY(ALIGNED((*htable)->table, sizeof(app_pc)));
}
/*******************************************************************************/
| 1 | 20,520 | I think this should read "is always observed before" or "is never observed after". | DynamoRIO-dynamorio | c |
@@ -1,5 +1,5 @@
/*
- * Copyright 2002-2020 the original author or authors.
+ * Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | 1 | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.saml2.provider.service.registration;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.saml2.Saml2Exception;
/**
* A utility class for constructing instances of {@link RelyingPartyRegistration}
*
* @author Josh Cummings
* @author Ryan Cassar
* @since 5.4
*/
public final class RelyingPartyRegistrations {
private static final OpenSamlAssertingPartyMetadataConverter assertingPartyMetadataConverter = new OpenSamlAssertingPartyMetadataConverter();
private static final ResourceLoader resourceLoader = new DefaultResourceLoader();
private RelyingPartyRegistrations() {
}
/**
* Return a {@link RelyingPartyRegistration.Builder} based off of the given SAML 2.0
* Asserting Party (IDP) metadata location.
*
* Valid locations can be classpath- or file-based or they can be HTTP endpoints. Some
* valid endpoints might include:
*
* <pre>
* metadataLocation = "classpath:asserting-party-metadata.xml";
* metadataLocation = "file:asserting-party-metadata.xml";
* metadataLocation = "https://ap.example.org/metadata";
* </pre>
*
* Note that by default the registrationId is set to be the given metadata location,
* but this will most often not be sufficient. To complete the configuration, most
* applications will also need to provide a registrationId, like so:
*
* <pre>
* RelyingPartyRegistration registration = RelyingPartyRegistrations
* .fromMetadataLocation(metadataLocation)
* .registrationId("registration-id")
* .build();
* </pre>
*
* Also note that an {@code IDPSSODescriptor} typically only contains information
* about the asserting party. Thus, you will need to remember to still populate
* anything about the relying party, like any private keys the relying party will use
* for signing AuthnRequests.
* @param metadataLocation The classpath- or file-based locations or HTTP endpoints of
* the asserting party metadata file
* @return the {@link RelyingPartyRegistration.Builder} for further configuration
*/
public static RelyingPartyRegistration.Builder fromMetadataLocation(String metadataLocation) {
try (InputStream source = resourceLoader.getResource(metadataLocation).getInputStream()) {
return assertingPartyMetadataConverter.convert(source);
}
catch (IOException ex) {
if (ex.getCause() instanceof Saml2Exception) {
throw (Saml2Exception) ex.getCause();
}
throw new Saml2Exception(ex);
}
}
}
| 1 | 17,462 | You might consider adding yourself as an author of the class. | spring-projects-spring-security | java |
@@ -1065,7 +1065,8 @@ int ACTIVE_TASK::start(bool test) {
// hook up stderr to a specially-named file
//
- (void) freopen(STDERR_FILE, "a", stderr);
+ if (freopen(STDERR_FILE, "a", stderr) == NULL) {
+ }
// lower our priority if needed
// | 1 | // This file is part of BOINC.
// http://boinc.berkeley.edu
// Copyright (C) 2020 University of California
//
// BOINC is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// BOINC is distributed in the hope that 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
// initialization and starting of applications
#include "cpp.h"
#ifdef _WIN32
#include "boinc_win.h"
#include "win_util.h"
#else
#include "config.h"
#if HAVE_SCHED_SETSCHEDULER && defined (__linux__)
#include <sched.h>
#endif
#if HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#if HAVE_SYS_IPC_H
#include <sys/ipc.h>
#endif
#if HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <unistd.h>
#include <cerrno>
#include <sys/stat.h>
#include <string>
#endif
#ifdef __EMX__
#include <process.h>
#endif
#if(!defined (_WIN32) && !defined (__EMX__))
#include <fcntl.h>
#endif
#include <vector>
using std::vector;
using std::string;
#include "base64.h"
#include "error_numbers.h"
#include "filesys.h"
#include "shmem.h"
#include "str_replace.h"
#include "str_util.h"
#include "util.h"
#include "async_file.h"
#include "client_msgs.h"
#include "client_state.h"
#include "file_names.h"
#include "result.h"
#include "sandbox.h"
#ifdef _WIN32
#include "run_app_windows.h"
#endif
#include "cs_proxy.h"
#include "app.h"
#ifdef _WIN32
// Dynamically link to these functions at runtime;
// otherwise BOINC cannot run on Win98
// CreateEnvironmentBlock
typedef BOOL (WINAPI *tCEB)(LPVOID *lpEnvironment, HANDLE hToken, BOOL bInherit);
// DestroyEnvironmentBlock
typedef BOOL (WINAPI *tDEB)(LPVOID lpEnvironment);
#endif
// print each string in an array
//
#ifndef _WIN32
static void debug_print_argv(char** argv) {
msg_printf(0, MSG_INFO, "[task] Arguments:");
for (int i=0; argv[i]; i++) {
msg_printf(0, MSG_INFO, "[task] argv[%d]: %s\n", i, argv[i]);
}
}
#endif
// For apps that use coprocessors, append "--device x" to the command line.
// NOTE: this is deprecated. Use app_init_data instead.
//
static void coproc_cmdline(
int rsc_type, RESULT* rp, double ninstances, char* cmdline, int cmdline_len
) {
char buf[256];
COPROC* coproc = &coprocs.coprocs[rsc_type];
for (int j=0; j<ninstances; j++) {
int k = rp->coproc_indices[j];
// sanity check
//
if (k < 0 || k >= coproc->count) {
msg_printf(0, MSG_INTERNAL_ERROR,
"coproc_cmdline: coproc index %d out of range", k
);
k = 0;
}
sprintf(buf, " --device %d", coproc->device_nums[k]);
strlcat(cmdline, buf, cmdline_len);
}
}
// Make a unique key for client/app shared memory segment.
// Windows: also create and attach to the segment.
//
int ACTIVE_TASK::get_shmem_seg_name() {
#ifdef _WIN32
int i;
char seg_name[256];
bool try_global = (sandbox_account_service_token != NULL);
for (i=0; i<1024; i++) {
sprintf(seg_name, "%sboinc_%d", SHM_PREFIX, i);
shm_handle = create_shmem(
seg_name, sizeof(SHARED_MEM), (void**)&app_client_shm.shm,
try_global
);
if (shm_handle) break;
}
if (!shm_handle) return ERR_SHMGET;
sprintf(shmem_seg_name, "boinc_%d", i);
#else
char init_data_path[MAXPATHLEN];
#ifndef __EMX__
// shmem_seg_name is not used with mmap() shared memory
if (app_version->api_version_at_least(6, 0)) {
shmem_seg_name = -1;
return 0;
}
#endif
sprintf(init_data_path, "%s/%s", slot_dir, INIT_DATA_FILE);
// ftok() only works if there's a file at the given location
//
if (!boinc_file_exists(init_data_path)) {
FILE* f = boinc_fopen(init_data_path, "w");
if (f) {
fclose(f);
} else {
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"error: can't open file for shmem seg name"
);
}
}
shmem_seg_name = ftok(init_data_path, 1);
if (shmem_seg_name == -1) {
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"error: can't open file for shmem seg name: %d", errno
);
perror("ftok");
return ERR_SHMEM_NAME;
}
#endif
return 0;
}
void ACTIVE_TASK::init_app_init_data(APP_INIT_DATA& aid) {
PROJECT* project = wup->project;
aid.major_version = BOINC_MAJOR_VERSION;
aid.minor_version = BOINC_MINOR_VERSION;
aid.release = BOINC_RELEASE;
aid.app_version = app_version->version_num;
safe_strcpy(aid.app_name, wup->app->name);
safe_strcpy(aid.symstore, project->symstore);
safe_strcpy(aid.acct_mgr_url, gstate.acct_mgr_info.master_url);
if (project->project_specific_prefs.length()) {
aid.project_preferences = strdup(
project->project_specific_prefs.c_str()
);
}
aid.userid = project->userid;
aid.teamid = project->teamid;
aid.hostid = project->hostid;
safe_strcpy(aid.user_name, project->user_name);
safe_strcpy(aid.team_name, project->team_name);
safe_strcpy(aid.project_dir, project->project_dir_absolute());
relative_to_absolute("", aid.boinc_dir);
safe_strcpy(aid.authenticator, project->authenticator);
aid.slot = slot;
#ifdef _WIN32
aid.client_pid = GetCurrentProcessId();
#else
aid.client_pid = getpid();
#endif
safe_strcpy(aid.wu_name, wup->name);
safe_strcpy(aid.result_name, result->name);
aid.user_total_credit = project->user_total_credit;
aid.user_expavg_credit = project->user_expavg_credit;
aid.host_total_credit = project->host_total_credit;
aid.host_expavg_credit = project->host_expavg_credit;
double rrs = gstate.runnable_resource_share(RSC_TYPE_CPU);
if (rrs) {
aid.resource_share_fraction = project->resource_share/rrs;
} else {
aid.resource_share_fraction = 1;
}
aid.host_info = gstate.host_info;
aid.proxy_info = working_proxy_info;
aid.global_prefs = gstate.global_prefs;
aid.starting_elapsed_time = checkpoint_elapsed_time;
aid.using_sandbox = g_use_sandbox;
aid.vm_extensions_disabled = gstate.host_info.p_vm_extensions_disabled;
aid.rsc_fpops_est = wup->rsc_fpops_est;
aid.rsc_fpops_bound = wup->rsc_fpops_bound;
aid.rsc_memory_bound = wup->rsc_memory_bound;
aid.rsc_disk_bound = wup->rsc_disk_bound;
aid.computation_deadline = result->computation_deadline();
int rt = app_version->gpu_usage.rsc_type;
if (rt) {
COPROC& cp = coprocs.coprocs[rt];
if (coproc_type_name_to_num(cp.type) >= 0) {
// Standardized vendor name ("NVIDIA", "ATI" or "intel_gpu")
safe_strcpy(aid.gpu_type, cp.type);
} else {
// For other vendors, use vendor name as returned by OpenCL
safe_strcpy(aid.gpu_type, cp.opencl_prop.vendor);
}
int k = result->coproc_indices[0];
if (k<0 || k>=cp.count) {
msg_printf(0, MSG_INTERNAL_ERROR,
"init_app_init_data(): coproc index %d out of range", k
);
k = 0;
}
aid.gpu_device_num = cp.device_nums[k];
aid.gpu_opencl_dev_index = cp.opencl_device_indexes[k];
aid.gpu_usage = app_version->gpu_usage.usage;
} else {
safe_strcpy(aid.gpu_type, "");
aid.gpu_device_num = -1;
aid.gpu_opencl_dev_index = -1;
aid.gpu_usage = 0;
}
aid.ncpus = app_version->avg_ncpus;
aid.vbox_window = cc_config.vbox_window;
aid.checkpoint_period = gstate.global_prefs.disk_interval;
aid.fraction_done_start = 0;
aid.fraction_done_end = 1;
#ifdef _WIN32
safe_strcpy(aid.shmem_seg_name, shmem_seg_name);
#else
aid.shmem_seg_name = shmem_seg_name;
#endif
aid.wu_cpu_time = checkpoint_cpu_time;
APP_VERSION* avp = app_version;
for (unsigned int i=0; i<avp->app_files.size(); i++) {
FILE_REF& fref = avp->app_files[i];
aid.app_files.push_back(string(fref.file_name));
}
aid.no_priority_change = cc_config.no_priority_change;
aid.process_priority = cc_config.process_priority;
aid.process_priority_special = cc_config.process_priority_special;
}
// write the app init file.
// This is done before starting or restarting the app,
// and when project prefs have changed during app execution
//
int ACTIVE_TASK::write_app_init_file(APP_INIT_DATA& aid) {
FILE *f;
char init_data_path[MAXPATHLEN];
#if 0
msg_printf(wup->project, MSG_INFO,
"writing app_init.xml for %s; slot %d rt %s gpu_device_num %d", result->name, slot, aid.gpu_type, aid.gpu_device_num
);
#endif
sprintf(init_data_path, "%s/%s", slot_dir, INIT_DATA_FILE);
// delete the file using the switcher (Unix)
// in case it's owned by another user and we don't have write access
//
delete_project_owned_file(init_data_path, false);
f = boinc_fopen(init_data_path, "w");
if (!f) {
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"Failed to open init file %s",
init_data_path
);
return ERR_FOPEN;
}
int retval = write_init_data_file(f, aid);
fclose(f);
return retval;
}
// Given a logical name of the form D1/D2/.../Dn/F,
// create the directories D1 ... Dn in the slot dir
//
static int create_dirs_for_logical_name(
const char* name, const char* slot_dir
) {
char buf[1024];
char dir_path[MAXPATHLEN];
int retval;
safe_strcpy(buf, name);
safe_strcpy(dir_path, slot_dir);
char* p = buf;
while (1) {
char* q = strchr(p, '/');
if (!q) break;
*q = 0;
safe_strcat(dir_path, "/");
safe_strcat(dir_path, p);
retval = boinc_mkdir(dir_path);
if (retval) return retval;
p = q+1;
}
return 0;
}
static void prepend_prefix(APP_VERSION* avp, char* in, char* out, int len) {
if (strlen(avp->file_prefix)) {
snprintf(out, len, "%.16s/%.200s", avp->file_prefix, in);
} else {
strlcpy(out, in, len);
}
}
// an input/output file must be copied if either
// - the FILE_REFERENCE says so or
// - the APP_VERSION has a non-empty file_prefix
//
bool ACTIVE_TASK::must_copy_file(FILE_REF& fref, bool is_io_file) {
if (fref.copy_file) return true;
if (is_io_file && strlen(app_version->file_prefix)) return true;
return false;
}
// set up a file reference, given a slot dir and project dir.
// This means:
// 1) copy the file to slot dir, if reference is by copy
// 2) else make a soft link
//
int ACTIVE_TASK::setup_file(
FILE_INFO* fip, FILE_REF& fref, char* file_path, bool input, bool is_io_file
) {
char link_path[MAXPATHLEN], rel_file_path[MAXPATHLEN], open_name[256];
int retval;
PROJECT* project = result->project;
if (log_flags.slot_debug) {
msg_printf(wup->project, MSG_INFO,
"setup_file: %s (%s)", file_path, input?"input":"output"
);
}
if (strlen(fref.open_name)) {
if (is_io_file) {
prepend_prefix(
app_version, fref.open_name, open_name, sizeof(open_name)
);
} else {
safe_strcpy(open_name, fref.open_name);
}
retval = create_dirs_for_logical_name(open_name, slot_dir);
if (retval) return retval;
snprintf(link_path, sizeof(link_path), "%s/%s", slot_dir, open_name);
} else {
snprintf(link_path, sizeof(link_path), "%s/%s", slot_dir, fip->name);
}
snprintf(rel_file_path, sizeof(rel_file_path), "../../%s", file_path );
if (boinc_file_exists(link_path)) {
return 0;
}
if (must_copy_file(fref, is_io_file)) {
if (input) {
// the file may be there already (async copy case)
//
if (boinc_file_exists(link_path)) {
return 0;
}
if (fip->nbytes > ASYNC_FILE_THRESHOLD) {
ASYNC_COPY* ac = new ASYNC_COPY;
retval = ac->init(this, fip, file_path, link_path);
if (retval) return retval;
return ERR_IN_PROGRESS;
} else {
retval = boinc_copy(file_path, link_path);
if (retval) {
msg_printf(project, MSG_INTERNAL_ERROR,
"Can't copy %s to %s: %s", file_path, link_path,
boincerror(retval)
);
return retval;
}
retval = fip->set_permissions(link_path);
if (retval) return retval;
}
}
return 0;
}
#ifdef _WIN32
retval = make_soft_link(project, link_path, rel_file_path);
if (retval) return retval;
#else
if (project->use_symlinks) {
retval = symlink(rel_file_path, link_path);
} else {
retval = make_soft_link(project, link_path, rel_file_path);
}
if (retval) return retval;
#endif
if (g_use_sandbox) set_to_project_group(link_path);
return 0;
}
int ACTIVE_TASK::link_user_files() {
PROJECT* project = wup->project;
unsigned int i;
FILE_REF fref;
FILE_INFO* fip;
char file_path[MAXPATHLEN];
for (i=0; i<project->user_files.size(); i++) {
fref = project->user_files[i];
fip = fref.file_info;
if (fip->status != FILE_PRESENT) continue;
get_pathname(fip, file_path, sizeof(file_path));
setup_file(fip, fref, file_path, true, false);
}
return 0;
}
int ACTIVE_TASK::copy_output_files() {
char slotfile[MAXPATHLEN], projfile[256], open_name[256];
unsigned int i;
for (i=0; i<result->output_files.size(); i++) {
FILE_REF& fref = result->output_files[i];
if (!must_copy_file(fref, true)) continue;
FILE_INFO* fip = fref.file_info;
prepend_prefix(
app_version, fref.open_name, open_name, sizeof(open_name)
);
snprintf(slotfile, sizeof(slotfile), "%.*s/%.*s", DIR_LEN, slot_dir, FILE_LEN, open_name);
get_pathname(fip, projfile, sizeof(projfile));
int retval = boinc_rename(slotfile, projfile);
// the rename fails if the output file isn't there.
//
if (retval) {
if (retval == ERR_FILE_MISSING) {
if (log_flags.slot_debug) {
msg_printf(wup->project, MSG_INFO,
"[slot] output file %s missing, not copying", slotfile
);
}
} else {
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"Can't rename output file %s to %s: %s",
slotfile, projfile, boincerror(retval)
);
}
} else {
if (log_flags.slot_debug) {
msg_printf(wup->project, MSG_INFO,
"[slot] renamed %s to %s", slotfile, projfile
);
}
}
}
return 0;
}
static int get_priority(bool is_high_priority) {
int p = is_high_priority?cc_config.process_priority_special:cc_config.process_priority;
#ifdef _WIN32
switch (p) {
case CONFIG_PRIORITY_LOWEST: return IDLE_PRIORITY_CLASS;
case CONFIG_PRIORITY_LOW: return BELOW_NORMAL_PRIORITY_CLASS;
case CONFIG_PRIORITY_NORMAL: return NORMAL_PRIORITY_CLASS;
case CONFIG_PRIORITY_HIGH: return ABOVE_NORMAL_PRIORITY_CLASS;
case CONFIG_PRIORITY_HIGHEST: return HIGH_PRIORITY_CLASS;
case CONFIG_PRIORITY_REALTIME: return REALTIME_PRIORITY_CLASS;
}
return is_high_priority ? BELOW_NORMAL_PRIORITY_CLASS : IDLE_PRIORITY_CLASS;
#else
switch (p) {
case CONFIG_PRIORITY_LOWEST: return PROCESS_IDLE_PRIORITY;
case CONFIG_PRIORITY_LOW: return PROCESS_MEDIUM_PRIORITY;
case CONFIG_PRIORITY_NORMAL: return PROCESS_NORMAL_PRIORITY;
case CONFIG_PRIORITY_HIGH: return PROCESS_ABOVE_NORMAL_PRIORITY;
case CONFIG_PRIORITY_HIGHEST: return PROCESS_HIGH_PRIORITY;
case CONFIG_PRIORITY_REALTIME: return PROCESS_REALTIME_PRIORITY;
}
return is_high_priority ? PROCESS_MEDIUM_PRIORITY : PROCESS_IDLE_PRIORITY;
#endif
}
// Start a task in a slot directory.
// This includes setting up soft links,
// passing preferences, and starting the process
//
// Current dir is top-level BOINC dir
//
// postcondition:
// If any error occurs
// ACTIVE_TASK::task_state is PROCESS_COULDNT_START
// report_result_error() is called
// else
// ACTIVE_TASK::task_state is PROCESS_EXECUTING
//
// If "test" is set, we're doing the API test; just run "test_app".
//
int ACTIVE_TASK::start(bool test) {
char exec_name[256], file_path[MAXPATHLEN], buf[MAXPATHLEN], exec_path[MAXPATHLEN];
char cmdline[80000]; // 64KB plus some extra
unsigned int i;
FILE_REF fref;
FILE_INFO* fip;
int retval;
APP_INIT_DATA aid;
#ifdef _WIN32
bool success = false;
LPVOID environment_block=NULL;
#endif
if (async_copy) {
if (log_flags.task_debug) {
msg_printf(wup->project, MSG_INFO,
"[task_debug] ACTIVE_TASK::start(): async file copy already in progress"
);
}
return 0;
}
// run it at above idle priority if it
// - uses coprocs
// - uses less than one CPU
// - is a wrapper
//
bool high_priority = false;
if (app_version->rsc_type()) high_priority = true;
if (app_version->avg_ncpus < 1) high_priority = true;
if (app_version->is_wrapper) high_priority = true;
if (wup->project->verify_files_on_app_start) {
fip=0;
retval = gstate.input_files_available(result, true, &fip);
if (retval) {
if (fip) {
snprintf(
buf, sizeof(buf),
"Input file %s missing or invalid: %s",
fip->name, boincerror(retval)
);
} else {
safe_strcpy(buf, "Input file missing or invalid");
}
goto error;
}
}
current_cpu_time = checkpoint_cpu_time;
elapsed_time = checkpoint_elapsed_time;
graphics_request_queue.init(result->name); // reset message queues
process_control_queue.init(result->name);
bytes_sent_episode = 0;
bytes_received_episode = 0;
if (!app_client_shm.shm) {
retval = get_shmem_seg_name();
if (retval) {
snprintf(buf, sizeof(buf),
"Can't get shared memory segment name: %s",
boincerror(retval)
);
goto error;
}
}
// this must go AFTER creating shmem name,
// since the shmem name is part of the file
//
init_app_init_data(aid);
retval = write_app_init_file(aid);
if (retval) {
snprintf(buf, sizeof(buf), "Can't write init file: %s", boincerror(retval));
goto error;
}
// set up applications files
//
if (test) {
safe_strcpy(exec_name, "test_app");
safe_strcpy(exec_path, "test_app");
} else {
safe_strcpy(exec_name, "");
}
for (i=0; i<app_version->app_files.size(); i++) {
fref = app_version->app_files[i];
fip = fref.file_info;
get_pathname(fip, file_path, sizeof(file_path));
if (fref.main_program) {
if (is_image_file(fip->name)) {
snprintf(buf, sizeof(buf), "Main program %s is an image file", fip->name);
retval = ERR_NO_SIGNATURE;
goto error;
}
if (!fip->executable && !wup->project->anonymous_platform) {
snprintf(buf, sizeof(buf), "Main program %s is not executable", fip->name);
retval = ERR_NO_SIGNATURE;
goto error;
}
safe_strcpy(exec_name, fip->name);
safe_strcpy(exec_path, file_path);
}
retval = setup_file(fip, fref, file_path, true, false);
if (retval == ERR_IN_PROGRESS) {
set_task_state(PROCESS_COPY_PENDING, "start");
return 0;
} else if (retval) {
safe_strcpy(buf, "Can't link app version file");
goto error;
}
}
if (!strlen(exec_name)) {
safe_strcpy(buf, "No main program specified");
retval = ERR_NOT_FOUND;
goto error;
}
// set up input, output files
//
for (i=0; i<wup->input_files.size(); i++) {
fref = wup->input_files[i];
fip = fref.file_info;
get_pathname(fref.file_info, file_path, sizeof(file_path));
retval = setup_file(fip, fref, file_path, true, true);
if (retval == ERR_IN_PROGRESS) {
set_task_state(PROCESS_COPY_PENDING, "start");
return 0;
} else if (retval) {
safe_strcpy(buf, "Can't link input file");
goto error;
}
}
for (i=0; i<result->output_files.size(); i++) {
fref = result->output_files[i];
if (must_copy_file(fref, true)) continue;
fip = fref.file_info;
get_pathname(fref.file_info, file_path, sizeof(file_path));
retval = setup_file(fip, fref, file_path, false, true);
if (retval) {
safe_strcpy(buf, "Can't link output file");
goto error;
}
}
link_user_files();
// don't check retval here
// remove temporary exit file from last run
//
snprintf(file_path, sizeof(file_path), "%s/%s", slot_dir, TEMPORARY_EXIT_FILE);
delete_project_owned_file(file_path, true);
if (cc_config.exit_before_start) {
msg_printf(0, MSG_INFO, "about to start a job; exiting");
exit(0);
}
#ifdef _WIN32
PROCESS_INFORMATION process_info;
STARTUPINFO startup_info;
char slotdirpath[MAXPATHLEN];
char error_msg[1024];
char error_msg2[1024];
DWORD last_error = 0;
memset(&process_info, 0, sizeof(process_info));
memset(&startup_info, 0, sizeof(startup_info));
startup_info.cb = sizeof(startup_info);
// suppress 2-sec rotating hourglass cursor on startup
//
startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK;
app_client_shm.reset_msgs();
if (cc_config.run_apps_manually) {
// fill in client's PID so we won't think app has exited
//
pid = GetCurrentProcessId();
process_handle = GetCurrentProcess();
set_task_state(PROCESS_EXECUTING, "start");
return 0;
}
snprintf(cmdline, sizeof(cmdline),
"%s %s %s",
exec_path, wup->command_line.c_str(), app_version->cmdline
);
if (!app_version->api_version_at_least(7, 5)) {
int rt = app_version->gpu_usage.rsc_type;
if (rt) {
coproc_cmdline(rt, result, app_version->gpu_usage.usage, cmdline, sizeof(cmdline));
}
}
relative_to_absolute(slot_dir, slotdirpath);
int prio_mask;
if (cc_config.no_priority_change) {
prio_mask = 0;
} else {
prio_mask = get_priority(high_priority);
}
for (i=0; i<5; i++) {
last_error = 0;
if (sandbox_account_service_token != NULL) {
if (!CreateEnvironmentBlock(&environment_block, sandbox_account_service_token, FALSE)) {
if (log_flags.task) {
windows_format_error_string(GetLastError(), error_msg, sizeof(error_msg));
msg_printf(wup->project, MSG_INFO,
"Process environment block creation failed: %s", error_msg
);
}
}
if (CreateProcessAsUser(
sandbox_account_service_token,
exec_path,
cmdline,
NULL,
NULL,
FALSE,
CREATE_NEW_PROCESS_GROUP|CREATE_NO_WINDOW|prio_mask|CREATE_UNICODE_ENVIRONMENT,
environment_block,
slotdirpath,
&startup_info,
&process_info
)) {
success = true;
break;
} else {
last_error = GetLastError();
windows_format_error_string(last_error, error_msg, sizeof(error_msg));
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"Process creation failed: %s - error code %d (0x%x)",
error_msg, last_error, last_error
);
}
if (!DestroyEnvironmentBlock(environment_block)) {
if (log_flags.task) {
windows_format_error_string(GetLastError(), error_msg, sizeof(error_msg2));
msg_printf(wup->project, MSG_INFO,
"Process environment block cleanup failed: %s",
error_msg2
);
}
}
} else {
if (CreateProcess(
exec_path,
cmdline,
NULL,
NULL,
FALSE,
CREATE_NEW_PROCESS_GROUP|CREATE_NO_WINDOW|prio_mask,
NULL,
slotdirpath,
&startup_info,
&process_info
)) {
success = true;
break;
} else {
last_error = GetLastError();
windows_format_error_string(last_error, error_msg, sizeof(error_msg));
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"Process creation failed: %s - error code %d (0x%x)",
error_msg, last_error, last_error
);
}
}
boinc_sleep(drand());
}
if (!success) {
snprintf(buf, sizeof(buf), "CreateProcess() failed - %s", error_msg);
if (last_error == ERROR_NOT_ENOUGH_MEMORY) {
// if CreateProcess() failed because system is low on memory,
// treat this like a temporary exit;
// retry in 10 min, and give up after 100 times
//
bool will_restart;
handle_temporary_exit(will_restart, 600, "not enough memory", false);
if (will_restart) return 0;
}
retval = ERR_EXEC;
goto error;
}
pid = process_info.dwProcessId;
process_handle = process_info.hProcess;
CloseHandle(process_info.hThread); // thread handle is not used
#ifdef _WIN64
// if host has multiple processor groups (i.e. > 64 processors)
// see which one was used for this job, and show it
//
if (log_flags.task_debug && gstate.host_info.n_processor_groups > 0) {
msg_printf(wup->project, MSG_INFO,
"[task_debug] task is running in processor group %d",
get_processor_group(process_handle)
);
}
#endif
#elif defined(__EMX__)
char* argv[100];
char current_dir[_MAX_PATH];
// Set up client/app shared memory seg if needed
//
if (!app_client_shm.shm) {
retval = create_shmem(
shmem_seg_name, sizeof(SHARED_MEM), (void**)&app_client_shm.shm
);
if (retval) {
return retval;
}
}
app_client_shm.reset_msgs();
// save current dir
getcwd(current_dir, sizeof(current_dir));
// chdir() into the slot directory
//
retval = chdir(slot_dir);
if (retval) {
sprintf(buf, "Can't change directory to %s: %s", slot_dir, boincerror(retval));
goto error;
}
// hook up stderr to a specially-named file
//
//freopen(STDERR_FILE, "a", stderr);
argv[0] = exec_name;
safe_strcpy(cmdline, wup->command_line.c_str());
if (strlen(result->cmdline)) {
safe_strcat(cmdline, " ");
safe_strcat(cmdline, result->cmdline);
}
parse_command_line(cmdline, argv+1);
if (log_flags.task_debug) {
debug_print_argv(argv);
}
snprintf(buf, sizeof(buf), "../../%s", exec_path );
pid = spawnv(P_NOWAIT, buf, argv);
if (pid == -1) {
snprintf(buf, sizeof(buf), "Process creation failed: %s\n", boincerror(retval));
chdir(current_dir);
retval = ERR_EXEC;
goto error;
}
// restore current dir
chdir(current_dir);
if (log_flags.task_debug) {
msg_printf(wup->project, MSG_INFO,
"[task] ACTIVE_TASK::start(): forked process: pid %d\n", pid
);
}
if (!cc_config.no_priority_change) {
int priority = get_priority(high_priority);
if (setpriority(PRIO_PROCESS, pid, priority)) {
perror("setpriority");
}
}
#else
// Unix/Linux/Mac case
char* argv[100];
char current_dir[1024];
if (getcwd(current_dir, sizeof(current_dir)) == NULL) {
snprintf(buf, sizeof(buf), "Can't get cwd");
goto error;
}
snprintf(cmdline, sizeof(cmdline),
"%s %s",
wup->command_line.c_str(), app_version->cmdline
);
if (!app_version->api_version_at_least(7, 5)) {
int rt = app_version->gpu_usage.rsc_type;
if (rt) {
coproc_cmdline(rt, result, app_version->gpu_usage.usage, cmdline, sizeof(cmdline));
}
}
// Set up client/app shared memory seg if needed
//
if (!app_client_shm.shm) {
#ifdef ANDROID
if (true) {
#else
if (app_version->api_version_at_least(6, 0)) {
#endif
// Use mmap() shared memory
snprintf(buf, sizeof(buf), "%s/%s", slot_dir, MMAPPED_FILE_NAME);
if (g_use_sandbox) {
if (!boinc_file_exists(buf)) {
int fd = open(buf, O_RDWR | O_CREAT, 0660);
if (fd >= 0) {
close (fd);
if (g_use_sandbox) set_to_project_group(buf);
}
}
}
retval = create_shmem_mmap(
buf, sizeof(SHARED_MEM), (void**)&app_client_shm.shm
);
if (retval) {
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"ACTIVE_TASK::start(): can't create memory-mapped file: %s",
boincerror(retval)
);
return retval;
}
} else {
// Use shmget() shared memory
retval = create_shmem(
shmem_seg_name, sizeof(SHARED_MEM), gstate.boinc_project_gid,
(void**)&app_client_shm.shm
);
if (retval) {
needs_shmem = true;
destroy_shmem(shmem_seg_name);
return retval;
}
}
needs_shmem = false;
}
app_client_shm.reset_msgs();
if (cc_config.run_apps_manually) {
pid = getpid(); // use the client's PID
set_task_state(PROCESS_EXECUTING, "start");
return 0;
}
pid = fork();
if (pid == -1) {
snprintf(buf, sizeof(buf), "fork() failed: %s", strerror(errno));
retval = ERR_FORK;
goto error;
}
if (pid == 0) {
// from here on we're running in a new process.
// If an error happens,
// exit nonzero so that the client knows there was a problem.
// don't pass stdout to the app
//
int fd = open("/dev/null", O_RDWR);
dup2(fd, STDOUT_FILENO);
close(fd);
// prepend to library path:
// - the project dir (../../projects/X)
// - the slot dir (.)
// - the BOINC dir (../..)
// (Mac) /usr/local/cuda/lib/
// We use relative paths in case higher-level dirs
// are not readable to the account under which app runs
//
char libpath[8192];
char newlibs[256];
snprintf(newlibs, sizeof(newlibs), "../../%s:.:../..", wup->project->project_dir());
#ifdef __APPLE__
safe_strcat(newlibs, ":/usr/local/cuda/lib/");
#endif
char* p = getenv("LD_LIBRARY_PATH");
if (p) {
snprintf(libpath, sizeof(libpath), "%s:%s", newlibs, p);
} else {
safe_strcpy(libpath, newlibs);
}
setenv("LD_LIBRARY_PATH", libpath, 1);
// On the Mac, do the same for DYLD_LIBRARY_PATH
//
#ifdef __APPLE__
p = getenv("DYLD_LIBRARY_PATH");
if (p) {
snprintf(libpath, sizeof(libpath), "%s:%s", newlibs, p);
} else {
safe_strcpy(libpath, newlibs);
}
setenv("DYLD_LIBRARY_PATH", libpath, 1);
#endif
retval = chdir(slot_dir);
if (retval) {
perror("chdir");
fflush(NULL);
_exit(errno);
}
#if 0
// set stack size limit to the max.
// Some BOINC apps have reported problems with exceeding
// small stack limits (e.g. 8 MB)
// and it seems like the best thing to raise it as high as possible
//
struct rlimit rlim;
#define MIN_STACK_LIMIT 64000000
getrlimit(RLIMIT_STACK, &rlim);
if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur <= MIN_STACK_LIMIT) {
if (rlim.rlim_max == RLIM_INFINITY || rlim.rlim_max > MIN_STACK_LIMIT) {
rlim.rlim_cur = MIN_STACK_LIMIT;
} else {
rlim.rlim_cur = rlim.rlim_max;
}
setrlimit(RLIMIT_STACK, &rlim);
}
#endif
// hook up stderr to a specially-named file
//
(void) freopen(STDERR_FILE, "a", stderr);
// lower our priority if needed
//
if (!cc_config.no_priority_change) {
#if HAVE_SETPRIORITY
int priority = get_priority(high_priority);
if (setpriority(PRIO_PROCESS, 0, priority)) {
perror("setpriority");
}
#endif
#ifdef ANDROID
// Android has its own notion of background scheduling
if (!high_priority) {
FILE* f = fopen("/dev/cpuctl/apps/bg_non_interactive/tasks", "w");
if (!f) {
msg_printf(NULL, MSG_INFO, "Can't open /dev/cpuctl/apps/bg_non_interactive/tasks");
} else {
fprintf(f, "%d", getpid());
fclose(f);
}
}
#endif
#if HAVE_SCHED_SETSCHEDULER && defined(SCHED_IDLE) && defined (__linux__)
if (!high_priority) {
struct sched_param sp;
sp.sched_priority = 0;
if (sched_setscheduler(0, SCHED_IDLE, &sp)) {
perror("app_start sched_setscheduler(SCHED_IDLE)");
}
}
#endif
}
// Run the application program.
// If using account-based sandboxing, use a helper app
// to do this, to set the right user ID
//
if (test) {
strcpy(buf, exec_path);
} else {
snprintf(buf, sizeof(buf), "../../%.1024s", exec_path);
}
if (g_use_sandbox) {
char switcher_path[MAXPATHLEN];
snprintf(switcher_path, sizeof(switcher_path),
"../../%s/%s",
SWITCHER_DIR, SWITCHER_FILE_NAME
);
argv[0] = const_cast<char*>(SWITCHER_FILE_NAME);
argv[1] = buf;
argv[2] = exec_name;
parse_command_line(cmdline, argv+3);
if (log_flags.task_debug) {
debug_print_argv(argv);
}
// Files written by projects have user boinc_project
// and group boinc_project,
// so they must be world-readable so BOINC CLient can read them
//
umask(2);
retval = execv(switcher_path, argv);
} else {
argv[0] = buf;
parse_command_line(cmdline, argv+1);
retval = execv(buf, argv);
}
fprintf(stderr,
"Process creation (%s) failed: %s, errno=%d\n",
buf, boincerror(retval), errno
);
perror("execv");
fflush(NULL);
_exit(errno);
}
// parent process (client) continues here
//
if (log_flags.task_debug) {
msg_printf(wup->project, MSG_INFO,
"[task] ACTIVE_TASK::start(): forked process: pid %d\n", pid
);
}
#endif
set_task_state(PROCESS_EXECUTING, "start");
return 0;
// go here on error; "buf" contains error message, "retval" is nonzero
//
error:
if (test) {
return retval;
}
// if something failed, it's possible that the executable was munged.
// Verify it to trigger another download.
//
gstate.input_files_available(result, true);
char err_msg[4096];
snprintf(err_msg, sizeof(err_msg), "couldn't start app: %.256s", buf);
gstate.report_result_error(*result, err_msg);
if (log_flags.task_debug) {
msg_printf(wup->project, MSG_INFO,
"[task] couldn't start app: %s", buf
);
}
set_task_state(PROCESS_COULDNT_START, "start");
return retval;
}
// Resume the task if it was previously running; otherwise start it
// Postcondition: "state" is set correctly
//
int ACTIVE_TASK::resume_or_start(bool first_time) {
const char* str = "??";
int retval;
switch (task_state()) {
case PROCESS_UNINITIALIZED:
str = (first_time)?"Starting":"Restarting";
retval = start();
if ((retval == ERR_SHMGET) || (retval == ERR_SHMAT)) {
return retval;
}
if (retval) {
set_task_state(PROCESS_COULDNT_START, "resume_or_start1");
return retval;
}
break;
case PROCESS_SUSPENDED:
retval = unsuspend();
if (retval) {
msg_printf(wup->project, MSG_INTERNAL_ERROR,
"Couldn't resume task %s", result->name
);
set_task_state(PROCESS_COULDNT_START, "resume_or_start2");
return retval;
}
str = "Resuming";
break;
default:
msg_printf(result->project, MSG_INTERNAL_ERROR,
"Unexpected state %d for task %s", task_state(), result->name
);
return 0;
}
if (log_flags.task && first_time) {
msg_printf(result->project, MSG_INFO,
"Starting task %s", result->name
);
}
if (log_flags.cpu_sched) {
char buf[256];
safe_strcpy(buf, "");
if (strlen(app_version->plan_class)) {
snprintf(buf, sizeof(buf), " (%s)", app_version->plan_class);
}
msg_printf(result->project, MSG_INFO,
"[cpu_sched] %s task %s using %s version %d%s in slot %d",
str,
result->name,
app_version->app->name,
app_version->version_num,
buf,
slot
);
}
return 0;
}
// The following runs "test_app" and sends it various messages.
// Used for testing the runtime system.
//
void run_test_app() {
WORKUNIT wu;
PROJECT project;
APP app;
APP_VERSION av;
ACTIVE_TASK at;
ACTIVE_TASK_SET ats;
RESULT result;
int retval;
char buf[256];
getcwd(buf, sizeof(buf)); // so we can see where we're running
gstate.run_test_app = true;
wu.project = &project;
wu.app = &app;
wu.command_line = string("--critical_section");
safe_strcpy(app.name, "test app");
av.init();
av.avg_ncpus = 1;
safe_strcpy(result.name, "test result");
result.avp = &av;
result.wup = &wu;
result.project = &project;
result.app = &app;
at.result = &result;
at.wup = &wu;
at.app_version = &av;
at.max_elapsed_time = 1e6;
at.max_disk_usage = 1e14;
at.max_mem_usage = 1e14;
safe_strcpy(at.slot_dir, ".");
#if 0
// test file copy
//
ASYNC_COPY* ac = new ASYNC_COPY;
FILE_INFO fi;
retval = ac->init(&at, &fi, "big_file", "./big_file_copy");
if (retval) {
exit(1);
}
while (1) {
do_async_file_op();
if (at.async_copy == NULL) {
break;
}
}
fprintf(stderr, "done\n");
exit(0);
#endif
ats.active_tasks.push_back(&at);
unlink("boinc_finish_called");
unlink("boinc_lockfile");
unlink("boinc_temporary_exit");
unlink("stderr.txt");
retval = at.start(true);
if (retval) {
fprintf(stderr, "start() failed: %s\n", boincerror(retval));
}
while (1) {
gstate.now = dtime();
at.preempt(REMOVE_NEVER);
ats.poll();
boinc_sleep(.1);
at.unsuspend();
ats.poll();
boinc_sleep(.2);
//at.request_reread_prefs();
}
}
| 1 | 15,499 | If this fails, then 'stderr' is not a valid file handler anymore, and then any further 'write' operations will fail. Maybe some handling of such situation should be added here? | BOINC-boinc | php |
@@ -58,9 +58,12 @@ public class TracerTest {
public void shouldBeAbleToCreateATracer() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
+ long timeStamp = 1593493828L;
try (Span span = tracer.getCurrentContext().createSpan("parent")) {
span.setAttribute("cheese", "gouda");
+ span.addEvent("Grating cheese");
+ span.addEvent("Melting cheese", timeStamp);
span.setStatus(Status.NOT_FOUND);
}
| 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.remote.tracing.opentelemetry;
import io.opentelemetry.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.TracerSdkProvider;
import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.sdk.trace.export.SimpleSpansProcessor;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import org.junit.Test;
import org.openqa.selenium.grid.web.CombinedHandler;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.http.Routable;
import org.openqa.selenium.remote.http.Route;
import org.openqa.selenium.remote.tracing.HttpTracing;
import org.openqa.selenium.remote.tracing.Span;
import org.openqa.selenium.remote.tracing.Status;
import org.openqa.selenium.remote.tracing.Tracer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.openqa.selenium.remote.http.HttpMethod.GET;
import static org.openqa.selenium.remote.tracing.HttpTracing.newSpanAsChildOf;
public class TracerTest {
@Test
public void shouldBeAbleToCreateATracer() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span span = tracer.getCurrentContext().createSpan("parent")) {
span.setAttribute("cheese", "gouda");
span.setStatus(Status.NOT_FOUND);
}
Set<SpanData> values = allSpans.stream()
.filter(data -> data.getAttributes().containsKey("cheese"))
.collect(Collectors.toSet());
assertThat(values).hasSize(1);
assertThat(values).element(0)
.extracting(SpanData::getStatus).isEqualTo(io.opentelemetry.trace.Status.NOT_FOUND);
assertThat(values).element(0)
.extracting(el -> el.getAttributes().get("cheese").getStringValue()).isEqualTo("gouda");
}
@Test
public void nestingSpansInTheSameThreadShouldWork() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
try (Span child = parent.createSpan("child")) {
child.setAttribute("cheese", "camembert");
}
}
SpanData parent = allSpans.stream().filter(data -> data.getName().equals("parent"))
.findFirst().orElseThrow(NoSuchElementException::new);
SpanData child = allSpans.stream().filter(data -> data.getName().equals("child"))
.findFirst().orElseThrow(NoSuchElementException::new);
assertThat(child.getParentSpanId()).isEqualTo(parent.getSpanId());
}
@Test
public void nestingSpansFromDifferentThreadsIsFineToo() throws ExecutionException, InterruptedException {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> {
try (Span child = parent.createSpan("child")) {
child.setAttribute("cheese", "gruyere");
}
});
future.get();
}
SpanData parent = allSpans.stream().filter(data -> data.getName().equals("parent"))
.findFirst().orElseThrow(NoSuchElementException::new);
SpanData child = allSpans.stream().filter(data -> data.getName().equals("child"))
.findFirst().orElseThrow(NoSuchElementException::new);
assertThat(child.getParentSpanId()).isEqualTo(parent.getSpanId());
}
@Test
public void currentSpanIsKeptOnTracerCorrectlyWithinSameThread() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
try (Span child = parent.createSpan("child")) {
assertThat(child.getId()).isEqualTo(tracer.getCurrentContext().getId());
}
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
}
}
@Test
public void currentSpanIsKeptOnTracerCorrectlyBetweenThreads() throws ExecutionException, InterruptedException {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
try (Span parent = tracer.getCurrentContext().createSpan("parent")) {
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
Future<?> future = Executors.newSingleThreadExecutor().submit(() -> {
Span child = null;
try {
child = parent.createSpan("child");
assertThat(child.getId()).isEqualTo(tracer.getCurrentContext().getId());
} finally {
assert child != null;
child.close();
}
// At this point, the parent span is undefind, but shouldn't be null
assertThat(parent.getId()).isNotEqualTo(tracer.getCurrentContext().getId());
assertThat(child.getId()).isNotEqualTo(tracer.getCurrentContext().getId());
assertThat(tracer.getCurrentContext().getId()).isNotNull();
});
future.get();
assertThat(parent.getId()).isEqualTo(tracer.getCurrentContext().getId());
}
}
@Test
public void cleverShenanigansRepresentingWhatWeSeeInTheRouter() {
List<SpanData> allSpans = new ArrayList<>();
Tracer tracer = createTracer(allSpans);
CombinedHandler handler = new CombinedHandler();
ExecutorService executors = Executors.newCachedThreadPool();
handler.addHandler(Route.get("/status").to(() -> req -> {
try (Span span = HttpTracing.newSpanAsChildOf(tracer, req, "status")) {
executors.submit(span.wrap(() -> new HashSet<>(Arrays.asList("cheese", "peas")))).get();
CompletableFuture<String> toReturn = new CompletableFuture<>();
executors.submit(() -> {
try {
HttpRequest cheeseReq = new HttpRequest(GET, "/cheeses");
HttpTracing.inject(tracer, span, cheeseReq);
handler.execute(cheeseReq);
toReturn.complete("nom, nom, nom");
} catch (RuntimeException e) {
toReturn.completeExceptionally(e);
}
});
toReturn.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
return new HttpResponse();
}));
handler.addHandler(Route.get("/cheeses").to(() -> req -> new HttpResponse()));
Routable routable = handler.with(delegate -> req -> {
try (Span span = newSpanAsChildOf(tracer, req, "httpclient.execute")) {
return delegate.execute(req);
}
});
routable.execute(new HttpRequest(GET, "/"));
}
private Tracer createTracer(List<SpanData> exportTo) {
TracerSdkProvider provider = OpenTelemetrySdk.getTracerProvider();
provider.addSpanProcessor(SimpleSpansProcessor.create(new SpanExporter() {
@Override
public ResultCode export(Collection<SpanData> spans) {
exportTo.addAll(spans);
return ResultCode.SUCCESS;
}
@Override public ResultCode flush() {
return ResultCode.SUCCESS;
}
@Override
public void shutdown() {
}
}));
io.opentelemetry.trace.Tracer otTracer = provider.get("get");
return new OpenTelemetryTracer(
otTracer,
OpenTelemetry.getPropagators().getHttpTextFormat());
}
}
| 1 | 17,762 | Break out tests for events into their own tests rather than placing them in other ones. That makes it easier for us to figure out where problems lie and to do a TDD-driven implementation over new APIs. | SeleniumHQ-selenium | rb |
@@ -262,8 +262,8 @@ class DHCPOptionsField(StrField):
s += chr(len(oval))
s += oval
- elif (type(o) is str and DHCPRevOptions.has_key(o) and
- DHCPRevOptions[o][1] == None):
+ elif (type(o) is str and DHCPRevOptions.has_key(o) and
+ DHCPRevOptions[o][1] is None):
s += chr(DHCPRevOptions[o][0])
elif type(o) is int:
s += chr(o)+"\0" | 1 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <phil@secdev.org>
## This program is published under a GPLv2 license
"""
DHCP (Dynamic Host Configuration Protocol) d BOOTP
"""
import struct
from scapy.packet import *
from scapy.fields import *
from scapy.ansmachine import *
from scapy.layers.inet import UDP,IP
from scapy.layers.l2 import Ether
from scapy.base_classes import Net
from scapy.volatile import RandField
from scapy.arch import get_if_raw_hwaddr
from scapy.sendrecv import srp1
dhcpmagic="c\x82Sc"
class BOOTP(Packet):
name = "BOOTP"
fields_desc = [ ByteEnumField("op",1, {1:"BOOTREQUEST", 2:"BOOTREPLY"}),
ByteField("htype",1),
ByteField("hlen",6),
ByteField("hops",0),
IntField("xid",0),
ShortField("secs",0),
FlagsField("flags", 0, 16, "???????????????B"),
IPField("ciaddr","0.0.0.0"),
IPField("yiaddr","0.0.0.0"),
IPField("siaddr","0.0.0.0"),
IPField("giaddr","0.0.0.0"),
Field("chaddr","", "16s"),
Field("sname","","64s"),
Field("file","","128s"),
StrField("options","") ]
def guess_payload_class(self, payload):
if self.options[:len(dhcpmagic)] == dhcpmagic:
return DHCP
else:
return Packet.guess_payload_class(self, payload)
def extract_padding(self,s):
if self.options[:len(dhcpmagic)] == dhcpmagic:
# set BOOTP options to DHCP magic cookie and make rest a payload of DHCP options
payload = self.options[len(dhcpmagic):]
self.options = self.options[:len(dhcpmagic)]
return payload, None
else:
return "", None
def hashret(self):
return struct.pack("L", self.xid)
def answers(self, other):
if not isinstance(other, BOOTP):
return 0
return self.xid == other.xid
#DHCP_UNKNOWN, DHCP_IP, DHCP_IPLIST, DHCP_TYPE \
#= range(4)
#
DHCPTypes = {
1: "discover",
2: "offer",
3: "request",
4: "decline",
5: "ack",
6: "nak",
7: "release",
8: "inform",
9: "force_renew",
10:"lease_query",
11:"lease_unassigned",
12:"lease_unknown",
13:"lease_active",
}
DHCPOptions = {
0: "pad",
1: IPField("subnet_mask", "0.0.0.0"),
2: "time_zone",
3: IPField("router","0.0.0.0"),
4: IPField("time_server","0.0.0.0"),
5: IPField("IEN_name_server","0.0.0.0"),
6: IPField("name_server","0.0.0.0"),
7: IPField("log_server","0.0.0.0"),
8: IPField("cookie_server","0.0.0.0"),
9: IPField("lpr_server","0.0.0.0"),
12: "hostname",
14: "dump_path",
15: "domain",
17: "root_disk_path",
22: "max_dgram_reass_size",
23: "default_ttl",
24: "pmtu_timeout",
28: IPField("broadcast_address","0.0.0.0"),
35: "arp_cache_timeout",
36: "ether_or_dot3",
37: "tcp_ttl",
38: "tcp_keepalive_interval",
39: "tcp_keepalive_garbage",
40: "NIS_domain",
41: IPField("NIS_server","0.0.0.0"),
42: IPField("NTP_server","0.0.0.0"),
43: "vendor_specific",
44: IPField("NetBIOS_server","0.0.0.0"),
45: IPField("NetBIOS_dist_server","0.0.0.0"),
50: IPField("requested_addr","0.0.0.0"),
51: IntField("lease_time", 43200),
54: IPField("server_id","0.0.0.0"),
55: "param_req_list",
56: "error_message",
57: ShortField("max_dhcp_size", 1500),
58: IntField("renewal_time", 21600),
59: IntField("rebinding_time", 37800),
60: "vendor_class_id",
61: "client_id",
64: "NISplus_domain",
65: IPField("NISplus_server","0.0.0.0"),
69: IPField("SMTP_server","0.0.0.0"),
70: IPField("POP3_server","0.0.0.0"),
71: IPField("NNTP_server","0.0.0.0"),
72: IPField("WWW_server","0.0.0.0"),
73: IPField("Finger_server","0.0.0.0"),
74: IPField("IRC_server","0.0.0.0"),
75: IPField("StreetTalk_server","0.0.0.0"),
76: "StreetTalk_Dir_Assistance",
82: "relay_agent_Information",
53: ByteEnumField("message-type", 1, DHCPTypes),
# 55: DHCPRequestListField("request-list"),
255: "end"
}
DHCPRevOptions = {}
for k,v in DHCPOptions.iteritems():
if type(v) is str:
n = v
v = None
else:
n = v.name
DHCPRevOptions[n] = (k,v)
del(n)
del(v)
del(k)
class RandDHCPOptions(RandField):
def __init__(self, size=None, rndstr=None):
if size is None:
size = RandNumExpo(0.05)
self.size = size
if rndstr is None:
rndstr = RandBin(RandNum(0,255))
self.rndstr=rndstr
self._opts = DHCPOptions.values()
self._opts.remove("pad")
self._opts.remove("end")
def _fix(self):
op = []
for k in xrange(self.size):
o = random.choice(self._opts)
if type(o) is str:
op.append((o,self.rndstr*1))
else:
op.append((o.name, o.randval()._fix()))
return op
class DHCPOptionsField(StrField):
islist=1
def i2repr(self,pkt,x):
s = []
for v in x:
if type(v) is tuple and len(v) >= 2:
if DHCPRevOptions.has_key(v[0]) and isinstance(DHCPRevOptions[v[0]][1],Field):
f = DHCPRevOptions[v[0]][1]
vv = ",".join(f.i2repr(pkt,val) for val in v[1:])
else:
vv = ",".join(repr(val) for val in v[1:])
r = "%s=%s" % (v[0],vv)
s.append(r)
else:
s.append(sane(v))
return "[%s]" % (" ".join(s))
def getfield(self, pkt, s):
return "", self.m2i(pkt, s)
def m2i(self, pkt, x):
opt = []
while x:
o = ord(x[0])
if o == 255:
opt.append("end")
x = x[1:]
continue
if o == 0:
opt.append("pad")
x = x[1:]
continue
if len(x) < 2 or len(x) < ord(x[1])+2:
opt.append(x)
break
elif DHCPOptions.has_key(o):
f = DHCPOptions[o]
if isinstance(f, str):
olen = ord(x[1])
opt.append( (f,x[2:olen+2]) )
x = x[olen+2:]
else:
olen = ord(x[1])
lval = [f.name]
try:
left = x[2:olen+2]
while left:
left, val = f.getfield(pkt,left)
lval.append(val)
except:
opt.append(x)
break
else:
otuple = tuple(lval)
opt.append(otuple)
x = x[olen+2:]
else:
olen = ord(x[1])
opt.append((o, x[2:olen+2]))
x = x[olen+2:]
return opt
def i2m(self, pkt, x):
if type(x) is str:
return x
s = ""
for o in x:
if type(o) is tuple and len(o) >= 2:
name = o[0]
lval = o[1:]
if isinstance(name, int):
onum, oval = name, "".join(lval)
elif DHCPRevOptions.has_key(name):
onum, f = DHCPRevOptions[name]
if f is not None:
lval = [f.addfield(pkt,"",f.any2i(pkt,val)) for val in lval]
oval = "".join(lval)
else:
warning("Unknown field option %s" % name)
continue
s += chr(onum)
s += chr(len(oval))
s += oval
elif (type(o) is str and DHCPRevOptions.has_key(o) and
DHCPRevOptions[o][1] == None):
s += chr(DHCPRevOptions[o][0])
elif type(o) is int:
s += chr(o)+"\0"
elif type(o) is str:
s += o
else:
warning("Malformed option %s" % o)
return s
class DHCP(Packet):
name = "DHCP options"
fields_desc = [ DHCPOptionsField("options","") ]
bind_layers( UDP, BOOTP, dport=67, sport=68)
bind_layers( UDP, BOOTP, dport=68, sport=67)
bind_bottom_up( UDP, BOOTP, dport=67, sport=67)
bind_layers( BOOTP, DHCP, options='c\x82Sc')
def dhcp_request(iface=None,**kargs):
if conf.checkIPaddr != 0:
warning("conf.checkIPaddr is not 0, I may not be able to match the answer")
if iface is None:
iface = conf.iface
fam,hw = get_if_raw_hwaddr(iface)
return srp1(Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67)
/BOOTP(chaddr=hw)/DHCP(options=[("message-type","discover"),"end"]),iface=iface,**kargs)
class BOOTP_am(AnsweringMachine):
function_name = "bootpd"
filter = "udp and port 68 and port 67"
send_function = staticmethod(sendp)
def parse_options(self, pool=Net("192.168.1.128/25"), network="192.168.1.0/24",gw="192.168.1.1",
domain="localnet", renewal_time=60, lease_time=1800):
if type(pool) is str:
poom = Net(pool)
self.domain = domain
netw,msk = (network.split("/")+["32"])[:2]
msk = itom(int(msk))
self.netmask = ltoa(msk)
self.network = ltoa(atol(netw)&msk)
self.broadcast = ltoa( atol(self.network) | (0xffffffff&~msk) )
self.gw = gw
if isinstance(pool,Gen):
pool = [k for k in pool if k not in [gw, self.network, self.broadcast]]
pool.reverse()
if len(pool) == 1:
pool, = pool
self.pool = pool
self.lease_time = lease_time
self.renewal_time = renewal_time
self.leases = {}
def is_request(self, req):
if not req.haslayer(BOOTP):
return 0
reqb = req.getlayer(BOOTP)
if reqb.op != 1:
return 0
return 1
def print_reply(self, req, reply):
print "Reply %s to %s" % (reply.getlayer(IP).dst,reply.dst)
def make_reply(self, req):
mac = req.src
if type(self.pool) is list:
if not self.leases.has_key(mac):
self.leases[mac] = self.pool.pop()
ip = self.leases[mac]
else:
ip = self.pool
repb = req.getlayer(BOOTP).copy()
repb.op="BOOTREPLY"
repb.yiaddr = ip
repb.siaddr = self.gw
repb.ciaddr = self.gw
repb.giaddr = self.gw
del(repb.payload)
rep=Ether(dst=mac)/IP(dst=ip)/UDP(sport=req.dport,dport=req.sport)/repb
return rep
class DHCP_am(BOOTP_am):
function_name="dhcpd"
def make_reply(self, req):
resp = BOOTP_am.make_reply(self, req)
if DHCP in req:
dhcp_options = [(op[0],{1:2,3:5}.get(op[1],op[1]))
for op in req[DHCP].options
if type(op) is tuple and op[0] == "message-type"]
dhcp_options += [("server_id",self.gw),
("domain", self.domain),
("router", self.gw),
("name_server", self.gw),
("broadcast_address", self.broadcast),
("subnet_mask", self.netmask),
("renewal_time", self.renewal_time),
("lease_time", self.lease_time),
"end"
]
resp /= DHCP(options=dhcp_options)
return resp
| 1 | 8,504 | I think your indentation is wrong here. | secdev-scapy | py |
@@ -63,7 +63,9 @@ type L3RouteResolver struct {
blockToRoutes map[string]set.Set
allPools map[string]model.IPPool
workloadIDToCIDRs map[model.WorkloadEndpointKey][]cnet.IPNet
+ nodeToCIDRs map[string]set.Set
useNodeResourceUpdates bool
+ routeSource string
}
type l3rrNodeInfo struct { | 1 | // Copyright (c) 2019-2020 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package calc
import (
"fmt"
"reflect"
"sort"
"github.com/sirupsen/logrus"
apiv3 "github.com/projectcalico/libcalico-go/lib/apis/v3"
"github.com/projectcalico/libcalico-go/lib/backend/api"
"github.com/projectcalico/libcalico-go/lib/backend/encap"
"github.com/projectcalico/libcalico-go/lib/backend/model"
cnet "github.com/projectcalico/libcalico-go/lib/net"
"github.com/projectcalico/libcalico-go/lib/set"
"github.com/projectcalico/felix/dispatcher"
"github.com/projectcalico/felix/ip"
"github.com/projectcalico/felix/proto"
)
// L3RouteResolver is responsible for indexing (currently only IPv4 versions of):
//
// - IPAM blocks
// - IP pools
// - Node metadata (either from the Node resource, if available, or from HostIP)
//
// and emitting a set of longest prefix match routes that include:
//
// - The relevant destination CIDR.
// - The IP pool type that contains the CIDR (or none).
// - Other metadata about the containing IP pool.
// - Whether this (/32) CIDR is a host or not.
// - For workload CIDRs, the IP and name of the host that contains the workload.
//
// The BPF dataplane use the above to form a map of IP space so it can look up whether a particular
// IP belongs to a workload/host/IP pool etc. and where to forward that IP to if it needs to.
// The VXLAN dataplane combines routes for remote workloads with VTEPs from the VXLANResolver to
// form VXLAN routes.
type L3RouteResolver struct {
myNodeName string
callbacks routeCallbacks
trie *RouteTrie
// Store node metadata indexed by node name, and routes by the
// block that contributed them.
nodeNameToNodeInfo map[string]l3rrNodeInfo
blockToRoutes map[string]set.Set
allPools map[string]model.IPPool
workloadIDToCIDRs map[model.WorkloadEndpointKey][]cnet.IPNet
useNodeResourceUpdates bool
}
type l3rrNodeInfo struct {
Addr ip.V4Addr
CIDR ip.V4CIDR
}
func (i l3rrNodeInfo) AddrAsCIDR() ip.V4CIDR {
return i.Addr.AsCIDR().(ip.V4CIDR)
}
func NewL3RouteResolver(hostname string, callbacks PipelineCallbacks, useNodeResourceUpdates bool) *L3RouteResolver {
logrus.Info("Creating L3 route resolver")
return &L3RouteResolver{
myNodeName: hostname,
callbacks: callbacks,
trie: NewRouteTrie(),
nodeNameToNodeInfo: map[string]l3rrNodeInfo{},
blockToRoutes: map[string]set.Set{},
allPools: map[string]model.IPPool{},
workloadIDToCIDRs: map[model.WorkloadEndpointKey][]cnet.IPNet{},
useNodeResourceUpdates: useNodeResourceUpdates,
}
}
func (c *L3RouteResolver) RegisterWith(allUpdDispatcher, localDispatcher *dispatcher.Dispatcher) {
if c.useNodeResourceUpdates {
logrus.Info("Registering L3 route resolver (node resources on)")
allUpdDispatcher.Register(model.ResourceKey{}, c.OnResourceUpdate)
} else {
logrus.Info("Registering L3 route resolver (node resources off)")
allUpdDispatcher.Register(model.HostIPKey{}, c.OnHostIPUpdate)
}
allUpdDispatcher.Register(model.BlockKey{}, c.OnBlockUpdate)
allUpdDispatcher.Register(model.IPPoolKey{}, c.OnPoolUpdate)
localDispatcher.Register(model.WorkloadEndpointKey{}, c.OnLocalWorkloadUpdate)
}
func (c *L3RouteResolver) OnLocalWorkloadUpdate(update api.Update) (_ bool) {
defer c.flush()
key := update.Key.(model.WorkloadEndpointKey)
// Look up the (possibly nil) old CIDRs.
oldCIDRs := c.workloadIDToCIDRs[key]
// Get the new CIDRs (again, may be nil if this is a deletion).
var newCIDRs []cnet.IPNet
if update.Value != nil {
newWorkload := update.Value.(*model.WorkloadEndpoint)
newCIDRs = newWorkload.IPv4Nets
logrus.WithField("workload", key).WithField("newCIDRs", newCIDRs).Debug("Workload update")
}
if reflect.DeepEqual(oldCIDRs, newCIDRs) {
// No change, ignore.
logrus.Debug("No change to CIDRs, ignore.")
return
}
// Incref the new CIDRs.
for _, newCIDR := range newCIDRs {
c.trie.AddLocalWEP(ip.CIDRFromCalicoNet(newCIDR).(ip.V4CIDR))
}
// Decref the old.
for _, oldCIDR := range oldCIDRs {
c.trie.RemoveLocalWEP(ip.CIDRFromCalicoNet(oldCIDR).(ip.V4CIDR))
}
if len(newCIDRs) > 0 {
// Only store an entry if there are some CIDRs.
c.workloadIDToCIDRs[key] = newCIDRs
} else {
delete(c.workloadIDToCIDRs, key)
}
return
}
func (c *L3RouteResolver) OnBlockUpdate(update api.Update) (_ bool) {
// Queue up a flush.
defer c.flush()
// Update the routes map based on the provided block update.
key := update.Key.String()
deletes := set.New()
adds := set.New()
if update.Value != nil {
// Block has been created or updated.
// We don't allow multiple blocks with the same CIDR, so no need to check
// for duplicates here. Look at the routes contributed by this block and determine if we
// need to send any updates.
newRoutes := c.v4RoutesFromBlock(update.Value.(*model.AllocationBlock))
logrus.WithField("numRoutes", len(newRoutes)).Debug("IPAM block update")
cachedRoutes, ok := c.blockToRoutes[key]
if !ok {
cachedRoutes = set.New()
c.blockToRoutes[key] = cachedRoutes
}
// Now scan the old routes, looking for any that are no-longer associated with the block.
// Remove no longer active routes from the cache and queue up deletions.
cachedRoutes.Iter(func(item interface{}) error {
r := item.(nodenameRoute)
// For each existing route which is no longer present, we need to delete it.
// Note: since r.Key() only contains the destination, we need to check equality too in case
// the gateway has changed.
if newRoute, ok := newRoutes[r.Key()]; ok && newRoute == r {
// Exists, and we want it to - nothing to do.
return nil
}
// Current route is not in new set - we need to withdraw the route, and also
// remove it from internal state.
deletes.Add(r)
logrus.WithField("route", r).Debug("Found stale route")
return set.RemoveItem
})
// Now scan the new routes, looking for additions. Cache them and queue up adds.
for _, r := range newRoutes {
logCxt := logrus.WithField("newRoute", r)
if cachedRoutes.Contains(r) {
logCxt.Debug("Desired route already exists, skip")
continue
}
logrus.WithField("route", r).Debug("Found new route")
cachedRoutes.Add(r)
adds.Add(r)
}
// At this point we've determined the correct diff to perform based on the block update. Queue up
// updates.
deletes.Iter(func(item interface{}) error {
nr := item.(nodenameRoute)
c.trie.RemoveBlockRoute(nr.dst)
return nil
})
adds.Iter(func(item interface{}) error {
nr := item.(nodenameRoute)
c.trie.UpdateBlockRoute(nr.dst, nr.nodeName)
return nil
})
} else {
// Block has been deleted. Clean up routes that were contributed by this block.
logrus.WithField("update", update).Debug("IPAM block deleted")
routes := c.blockToRoutes[key]
if routes != nil {
routes.Iter(func(item interface{}) error {
nr := item.(nodenameRoute)
c.trie.RemoveBlockRoute(nr.dst)
return nil
})
}
delete(c.blockToRoutes, key)
}
return
}
func (c *L3RouteResolver) OnResourceUpdate(update api.Update) (_ bool) {
// We only care about nodes, not other resources.
resourceKey := update.Key.(model.ResourceKey)
if resourceKey.Kind != apiv3.KindNode {
return
}
// Queue up a flush.
defer c.flush()
// Extract the nodename and check whether the node was known already.
nodeName := update.Key.(model.ResourceKey).Name
logCxt := logrus.WithField("node", nodeName).WithField("update", update)
logCxt.Debug("OnResourceUpdate triggered")
// Update our tracking data structures.
var nodeInfo *l3rrNodeInfo
if update.Value != nil {
node := update.Value.(*apiv3.Node)
if node.Spec.BGP != nil && node.Spec.BGP.IPv4Address != "" {
bgp := node.Spec.BGP
// Use cnet.ParseCIDROrIP so we get the IP and the CIDR. The parse functions in the ip package
// throw away one or the other.
ipv4, caliNodeCIDR, err := cnet.ParseCIDROrIP(bgp.IPv4Address)
if err != nil {
logrus.WithError(err).Panic("Failed to parse already-validated IP address")
}
nodeInfo = &l3rrNodeInfo{
Addr: ip.FromCalicoIP(*ipv4).(ip.V4Addr),
CIDR: ip.CIDRFromCalicoNet(*caliNodeCIDR).(ip.V4CIDR),
}
}
}
c.onNodeUpdate(nodeName, nodeInfo)
return
}
// OnHostIPUpdate gets called whenever a node IP address changes.
func (c *L3RouteResolver) OnHostIPUpdate(update api.Update) (_ bool) {
// Queue up a flush.
defer c.flush()
nodeName := update.Key.(model.HostIPKey).Hostname
logrus.WithField("node", nodeName).Debug("OnHostIPUpdate triggered")
var newNodeInfo *l3rrNodeInfo
if update.Value != nil {
newCaliIP := update.Value.(*cnet.IP)
v4Addr, ok := ip.FromCalicoIP(*newCaliIP).(ip.V4Addr)
if ok { // Defensive; we only expect an IPv4.
newNodeInfo = &l3rrNodeInfo{
Addr: v4Addr,
CIDR: v4Addr.AsCIDR().(ip.V4CIDR), // Don't know the CIDR so use the /32.
}
}
}
c.onNodeUpdate(nodeName, newNodeInfo)
return
}
// onNodeUpdate updates our cache of node information as well add adding/removing the node's CIDR from the trie.
// Passing newCIDR==nil cleans up the entry in the trie.
func (c *L3RouteResolver) onNodeUpdate(nodeName string, newNodeInfo *l3rrNodeInfo) {
oldNodeInfo, nodeExisted := c.nodeNameToNodeInfo[nodeName]
if (newNodeInfo == nil && !nodeExisted) || (newNodeInfo != nil && nodeExisted && oldNodeInfo == *newNodeInfo) {
// No change.
return
}
if nodeName == c.myNodeName {
// Check if our CIDR has changed and if so recalculate the "same subnet" tracking.
var myNewCIDR ip.V4CIDR
var myNewCIDRKnown bool
if newNodeInfo != nil {
myNewCIDR = newNodeInfo.CIDR
myNewCIDRKnown = true
}
if oldNodeInfo.CIDR != myNewCIDR {
// This node's CIDR has changed; some routes may now have an incorrect value for same-subnet.
c.visitAllRoutes(func(r nodenameRoute) {
if r.nodeName == c.myNodeName {
return // Ignore self.
}
otherNodeInfo, known := c.nodeNameToNodeInfo[r.nodeName]
if !known {
return // Don't know other node's CIDR so ignore for now.
}
otherNodesIPv4 := otherNodeInfo.Addr
wasSameSubnet := nodeExisted && oldNodeInfo.CIDR.ContainsV4(otherNodesIPv4)
nowSameSubnet := myNewCIDRKnown && myNewCIDR.ContainsV4(otherNodesIPv4)
if wasSameSubnet != nowSameSubnet {
logrus.WithField("route", r).Debug("Update to our subnet invalidated route")
c.trie.MarkCIDRDirty(r.dst)
}
})
}
}
if nodeExisted {
delete(c.nodeNameToNodeInfo, nodeName)
c.trie.RemoveHost(oldNodeInfo.AddrAsCIDR(), nodeName)
}
if newNodeInfo != nil {
c.nodeNameToNodeInfo[nodeName] = *newNodeInfo
c.trie.AddHost(newNodeInfo.AddrAsCIDR(), nodeName)
}
c.markAllNodeRoutesDirty(nodeName)
}
func (c *L3RouteResolver) markAllNodeRoutesDirty(nodeName string) {
c.visitAllRoutes(func(route nodenameRoute) {
if route.nodeName != nodeName {
return
}
c.trie.MarkCIDRDirty(route.dst)
})
}
func (c *L3RouteResolver) visitAllRoutes(v func(route nodenameRoute)) {
for _, routes := range c.blockToRoutes {
routes.Iter(func(item interface{}) error {
v(item.(nodenameRoute))
return nil
})
}
}
// OnPoolUpdate gets called whenever an IP pool changes.
func (c *L3RouteResolver) OnPoolUpdate(update api.Update) (_ bool) {
// Queue up a flush.
defer c.flush()
k := update.Key.(model.IPPoolKey)
poolKey := k.String()
oldPool, oldPoolExists := c.allPools[poolKey]
oldPoolType := proto.IPPoolType_NONE
var poolCIDR ip.V4CIDR
if oldPoolExists {
// Need explicit oldPoolExists check so that we don't pass a zero-struct to poolTypeForPool.
oldPoolType = c.poolTypeForPool(&oldPool)
poolCIDR = ip.CIDRFromCalicoNet(oldPool.CIDR).(ip.V4CIDR)
}
var newPool *model.IPPool
if update.Value != nil {
newPool = update.Value.(*model.IPPool)
if len(newPool.CIDR.IP.To4()) == 0 {
logrus.Debug("Ignoring IPv6 pool")
newPool = nil
}
}
newPoolType := c.poolTypeForPool(newPool)
logCxt := logrus.WithFields(logrus.Fields{"oldType": oldPoolType, "newType": newPoolType})
if newPool != nil && newPoolType != proto.IPPoolType_NONE {
logCxt.Info("Pool is active")
c.allPools[poolKey] = *newPool
poolCIDR = ip.CIDRFromCalicoNet(newPool.CIDR).(ip.V4CIDR)
crossSubnet := newPool.IPIPMode == encap.CrossSubnet || newPool.VXLANMode == encap.CrossSubnet
c.trie.UpdatePool(poolCIDR, newPoolType, newPool.Masquerade, crossSubnet)
} else {
delete(c.allPools, poolKey)
c.trie.RemovePool(poolCIDR)
}
return
}
func (c *L3RouteResolver) poolTypeForPool(pool *model.IPPool) proto.IPPoolType {
if pool == nil {
return proto.IPPoolType_NONE
}
if pool.VXLANMode != encap.Undefined {
return proto.IPPoolType_VXLAN
}
if pool.IPIPMode != encap.Undefined {
return proto.IPPoolType_IPIP
}
return proto.IPPoolType_NO_ENCAP
}
// v4RoutesFromBlock returns a list of routes which should exist based on the provided
// allocation block.
func (c *L3RouteResolver) v4RoutesFromBlock(b *model.AllocationBlock) map[string]nodenameRoute {
if len(b.CIDR.IP.To4()) == 0 {
logrus.Debug("Ignoring IPv6 block")
return nil
}
routes := make(map[string]nodenameRoute)
for _, alloc := range b.NonAffineAllocations() {
if alloc.Host == "" {
logrus.WithField("IP", alloc.Addr).Warn(
"Unable to create route for IP; the node it belongs to was not recorded in IPAM")
continue
}
r := nodenameRoute{
dst: ip.CIDRFromNetIP(alloc.Addr.IP).(ip.V4CIDR),
nodeName: alloc.Host,
}
routes[r.Key()] = r
}
host := b.Host()
if host != "" {
logrus.WithField("host", host).Debug("Block has a host, including block-via-host route")
r := nodenameRoute{
dst: ip.CIDRFromCalicoNet(b.CIDR).(ip.V4CIDR),
nodeName: host,
}
routes[r.Key()] = r
}
return routes
}
// flush() iterates over the CIDRs that are marked dirty in the trie and sends any route updates
// that it finds.
func (c *L3RouteResolver) flush() {
var buf []ip.V4TrieEntry
c.trie.dirtyCIDRs.Iter(func(item interface{}) error {
logCxt := logrus.WithField("cidr", item)
logCxt.Debug("Flushing dirty route")
cidr := item.(ip.V4CIDR)
// We know the CIDR may be dirty, look up the path through the trie to the CIDR. This will
// give us the information about the enclosing CIDRs. For example, if we have:
// - IP pool 10.0.0.0/16 VXLAN
// - IPAM block 10.0.1.0/26 node x
// - IP 10.0.0.1/32 node y
// Then, we'll see the pool, block and IP in turn on the lookup path allowing us to collect the
// relevant information from each.
buf = c.trie.t.LookupPath(buf, cidr)
if len(buf) == 0 {
// CIDR is not in the trie. Nothing to do. Route removed before it had even been sent?
logCxt.Debug("CIDR not in trie, ignoring.")
return set.RemoveItem
}
// Otherwise, check if the route is removed.
ri := buf[len(buf)-1].Data.(RouteInfo)
if ri.WasSent && !ri.IsValidRoute() {
logCxt.Debug("CIDR was sent before but now needs to be removed.")
c.callbacks.OnRouteRemove(cidr.String())
c.trie.SetRouteSent(cidr, false)
return set.RemoveItem
}
rt := &proto.RouteUpdate{
Type: proto.RouteType_CIDR_INFO,
IpPoolType: proto.IPPoolType_NONE,
Dst: cidr.String(),
}
poolAllowsCrossSubnet := false
for _, entry := range buf {
ri := entry.Data.(RouteInfo)
if ri.Pool.Type != proto.IPPoolType_NONE {
logCxt.WithField("type", ri.Pool.Type).Debug("Found containing IP pool.")
rt.IpPoolType = ri.Pool.Type
}
if ri.Pool.NATOutgoing {
logCxt.Debug("NAT outgoing enabled on this CIDR.")
rt.NatOutgoing = true
}
if ri.Pool.CrossSubnet {
logCxt.Debug("Cross-subnet enabled on this CIDR.")
poolAllowsCrossSubnet = true
}
if ri.Block.NodeName != "" {
rt.DstNodeName = ri.Block.NodeName
if rt.DstNodeName == c.myNodeName {
logCxt.Debug("Local workload route.")
rt.Type = proto.RouteType_LOCAL_WORKLOAD
} else {
logCxt.Debug("Remote workload route.")
rt.Type = proto.RouteType_REMOTE_WORKLOAD
}
}
if len(ri.Host.NodeNames) > 0 {
rt.DstNodeName = ri.Host.NodeNames[0]
if rt.DstNodeName == c.myNodeName {
logCxt.Debug("Local host route.")
rt.Type = proto.RouteType_LOCAL_HOST
} else {
logCxt.Debug("Remote host route.")
rt.Type = proto.RouteType_REMOTE_HOST
}
}
if ri.LocalWEP.RefCount > 0 {
// We have a local WEP with this IP.
rt.DstNodeName = c.myNodeName
rt.Type = proto.RouteType_LOCAL_WORKLOAD
rt.LocalWorkload = true
}
}
if rt.DstNodeName != "" {
dstNodeInfo, exists := c.nodeNameToNodeInfo[rt.DstNodeName]
if exists {
rt.DstNodeIp = dstNodeInfo.Addr.String()
}
}
rt.SameSubnet = poolAllowsCrossSubnet && c.nodeInOurSubnet(rt.DstNodeName)
logrus.WithField("route", rt).Debug("Sending route")
c.callbacks.OnRouteUpdate(rt)
c.trie.SetRouteSent(cidr, true)
return set.RemoveItem
})
}
// nodeInOurSubnet returns true if the IP of the given node is known and it's in our subnet.
// Return false if either the remote IP or our subnet is not known.
func (c *L3RouteResolver) nodeInOurSubnet(name string) bool {
localNodeInfo, exists := c.nodeNameToNodeInfo[c.myNodeName]
if !exists {
return false
}
nodeInfo, exists := c.nodeNameToNodeInfo[name]
if !exists {
return false
}
return localNodeInfo.CIDR.ContainsV4(nodeInfo.Addr)
}
// nodenameRoute is the L3RouteResolver's internal representation of a route.
type nodenameRoute struct {
nodeName string
dst ip.V4CIDR
}
func (r nodenameRoute) Key() string {
return r.dst.String()
}
func (r nodenameRoute) String() string {
return fmt.Sprintf("hostnameRoute(dst: %s, node: %s)", r.dst.String(), r.nodeName)
}
// RouteTrie stores the information that we've gleaned from various resources in a way that allows us to
//
// - Look up a CIDR and find all the information that we know about the containing CIDRs.
// Example: if we look up a workload /32 CIDR then we'll also find the IP pool that contains it.
// - Deal with collisions where resources from different sources share the same CIDR.
// Example: an IP pool and an IPAM block can share the same CIDR. When we do a lookup, we want to know
// about both the pool and the block.
//
// More examples of nesting and collisions to be aware of:
//
// - Disabled IPAM pools that contain no blocks, which are used for tagging "external" IPs as safe destinations that
// don't require SNAT and for adding IP ranges for BIRD to export.
// - IPAM blocks that are /32s so they overlap with the pod IP inside them (and potentially with a
// misconfigured host IP).
// - Transient misconfigurations during a resync where we may see things out of order (for example, two hosts
// sharing an IP).
// - In future, /32s that we've learned from workload endpoints that are not contained within IP pools.
//
// Approach: for each CIDR in the trie, we store a RouteInfo struct, which has a disjoint nested struct for
// tracking data from each source. All updates are done via the updateCIDR method, which handles cleaning up
// RouteInfo structs that are empty.
//
// The RouteTrie maintains a set of dirty CIDRs. When an IPAM pool is updated, all the CIDRs under it are
// marked dirty.
type RouteTrie struct {
t *ip.V4Trie
dirtyCIDRs set.Set
}
func NewRouteTrie() *RouteTrie {
return &RouteTrie{
t: &ip.V4Trie{},
dirtyCIDRs: set.New(),
}
}
func (r *RouteTrie) UpdatePool(cidr ip.V4CIDR, poolType proto.IPPoolType, natOutgoing bool, crossSubnet bool) {
logrus.WithFields(logrus.Fields{
"cidr": cidr,
"poolType": poolType,
"nat": natOutgoing,
"crossSubnet": crossSubnet,
}).Debug("IP pool update")
changed := r.updateCIDR(cidr, func(ri *RouteInfo) {
ri.Pool.Type = poolType
ri.Pool.NATOutgoing = natOutgoing
ri.Pool.CrossSubnet = crossSubnet
})
if !changed {
return
}
r.markChildrenDirty(cidr)
}
func (r *RouteTrie) markChildrenDirty(cidr ip.V4CIDR) {
// TODO: avoid full scan to mark children dirty
r.t.Visit(func(c ip.V4CIDR, data interface{}) bool {
if cidr.ContainsV4(c.Addr().(ip.V4Addr)) {
r.MarkCIDRDirty(c)
}
return true
})
}
func (r *RouteTrie) MarkCIDRDirty(cidr ip.V4CIDR) {
r.dirtyCIDRs.Add(cidr)
}
func (r *RouteTrie) RemovePool(cidr ip.V4CIDR) {
r.UpdatePool(cidr, proto.IPPoolType_NONE, false, false)
}
func (r *RouteTrie) UpdateBlockRoute(cidr ip.V4CIDR, nodeName string) {
r.updateCIDR(cidr, func(ri *RouteInfo) {
ri.Block.NodeName = nodeName
})
}
func (r *RouteTrie) RemoveBlockRoute(cidr ip.V4CIDR) {
r.UpdateBlockRoute(cidr, "")
}
func (r *RouteTrie) AddHost(cidr ip.V4CIDR, nodeName string) {
r.updateCIDR(cidr, func(ri *RouteInfo) {
ri.Host.NodeNames = append(ri.Host.NodeNames, nodeName)
if len(ri.Host.NodeNames) > 1 {
logrus.WithFields(logrus.Fields{
"cidr": cidr,
"nodes": ri.Host.NodeNames,
}).Warn("Some nodes share IP address, route calculation may choose wrong node.")
// For determinism in case we have two hosts sharing an IP, sort the entries.
sort.Strings(ri.Host.NodeNames)
}
})
}
func (r *RouteTrie) RemoveHost(cidr ip.V4CIDR, nodeName string) {
r.updateCIDR(cidr, func(ri *RouteInfo) {
var ns []string
for _, n := range ri.Host.NodeNames {
if n == nodeName {
continue
}
ns = append(ns, n)
}
ri.Host.NodeNames = ns
})
}
func (r *RouteTrie) AddLocalWEP(cidr ip.V4CIDR) {
r.updateCIDR(cidr, func(ri *RouteInfo) {
ri.LocalWEP.RefCount++
})
}
func (r *RouteTrie) RemoveLocalWEP(cidr ip.V4CIDR) {
r.updateCIDR(cidr, func(ri *RouteInfo) {
ri.LocalWEP.RefCount--
if ri.LocalWEP.RefCount < 0 {
logrus.WithField("cidr", cidr).Panic("BUG: Asked to decref a local workload past 0.")
}
})
}
func (r *RouteTrie) SetRouteSent(cidr ip.V4CIDR, sent bool) {
r.updateCIDR(cidr, func(ri *RouteInfo) {
ri.WasSent = sent
})
}
func (r RouteTrie) updateCIDR(cidr ip.V4CIDR, updateFn func(info *RouteInfo)) bool {
// Get the RouteInfo for the given CIDR and take a copy so we can compare.
ri := r.Get(cidr)
riCopy := ri
// Apply the update, whatever that is.
updateFn(&ri)
// Check if the update was a no-op.
if riCopy.Equals(ri) {
// Change was a no-op, ignore.
logrus.WithField("cidr", cidr).Debug("Ignoring no-op change")
return false
}
// Not a no-op; mark CIDR as dirty.
logrus.WithFields(logrus.Fields{"old": riCopy, "new": ri}).Debug("Route updated, marking dirty.")
r.MarkCIDRDirty(cidr)
if ri.IsZero() {
// No longer have *anything* to track about this CIDR, clean it up.
logrus.WithField("cidr", cidr).Debug("RouteInfo is zero, cleaning up.")
r.t.Delete(cidr)
return true
}
r.t.Update(cidr, ri)
return true
}
func (r RouteTrie) Get(cidr ip.V4CIDR) RouteInfo {
ri := r.t.Get(cidr)
if ri == nil {
return RouteInfo{}
}
return ri.(RouteInfo)
}
type RouteInfo struct {
// Pool contains information extracted from the IP pool that has this CIDR.
Pool struct {
Type proto.IPPoolType // Only set if this CIDR represents an IP pool
NATOutgoing bool
CrossSubnet bool
}
// Block contains route information extracted from IPAM blocks.
Block struct {
NodeName string // Set for each route that comes from an IPAM block.
}
// Host contains information extracted from the node/host config updates.
Host struct {
NodeNames []string // set if this CIDR _is_ a node's own IP.
}
// LocalWEP contains information extracted from the local workload endpoints.
LocalWEP struct {
// Count of local WEPs that have this CIDR. Normally, this will be 0 or 1 but Felix has to be tolerant
// to bad data (two local WEPs with the same CIDR) so we do ref counting.
RefCount int
}
// WasSent is set to true when the route is sent downstream.
WasSent bool
}
// IsValidRoute returns true if the RouteInfo contains some information about a CIDR, i.e. if this route
// should be sent downstream. This _excludes_ the WasSent flag, which we use to track whether a route with
// this CIDR was previously sent. If IsValidRoute() returns false but WasSent is true then we need to withdraw
// the route.
func (r RouteInfo) IsValidRoute() bool {
return r.Pool.Type != proto.IPPoolType_NONE ||
r.Block.NodeName != "" ||
len(r.Host.NodeNames) > 0 ||
r.Pool.NATOutgoing ||
r.LocalWEP.RefCount > 0
}
// IsZero() returns true if this node in the trie now contains no tracking information at all and is
// ready for deletion.
func (r RouteInfo) IsZero() bool {
return !r.WasSent && !r.IsValidRoute()
}
func (r RouteInfo) Equals(other RouteInfo) bool {
return reflect.DeepEqual(r, other)
}
| 1 | 17,613 | UT spotted that we weren't marking routes dirty when they targeted at Node and that node's IP changed. e.g., the case where a WEP appears in the syncer before the corresponding node does, so we don't know the node's IP. I added a new map to track the CIDRs for each node so that when the node IP changes we can mark those CIDRs dirty. Right now it's only used for the "WorkloadIPs" scenario. Need to decide if the same issue applies in the "CalicoIPAM' case. I suspect it might. It looks like we have some logic present to detect when our own node IP changes, but we don't seem to handle when a remote node's IP changes. | projectcalico-felix | go |
@@ -390,6 +390,14 @@ HELP
def execute(options)
if options[:mode] == 'plan' || options[:mode] == 'task'
begin
+ if Gem.win_platform?
+ # Windows 'fix' for openssl behaving strangely. Prevents very slow operation
+ # of random_bytes later when establishing winrm connections from a Windows host.
+ # See https://github.com/rails/rails/issues/25805 for background.
+ require 'openssl'
+ OpenSSL::Random.random_bytes(1)
+ end
+
require_relative '../../vendored/require_vendored'
rescue LoadError
raise Bolt::CLIError, "Puppet must be installed to execute tasks" | 1 | require 'uri'
require 'optparse'
require 'benchmark'
require 'json'
require 'logging'
require 'bolt/logger'
require 'bolt/node'
require 'bolt/version'
require 'bolt/error'
require 'bolt/executor'
require 'bolt/outputter'
require 'bolt/config'
require 'io/console'
module Bolt
class CLIError < Bolt::Error
attr_reader :error_code
def initialize(msg, error_code: 1)
super(msg, "bolt/cli-error")
@error_code = error_code
end
end
class CLIExit < StandardError; end
class CLI
BANNER = <<-HELP.freeze
Usage: bolt <subcommand> <action> [options]
Available subcommands:
bolt command run <command> Run a command remotely
bolt script run <script> Upload a local script and run it remotely
bolt task show Show list of available tasks
bolt task show <task> Show documentation for task
bolt task run <task> [params] Run a Puppet task
bolt plan show Show list of available plans
bolt plan run <plan> [params] Run a Puppet task plan
bolt file upload <src> <dest> Upload a local file
where [options] are:
HELP
TASK_HELP = <<-HELP.freeze
Usage: bolt task <action> <task> [options] [parameters]
Available actions are:
show Show list of available tasks
run Run a Puppet task
Parameters are of the form <parameter>=<value>.
Available options are:
HELP
COMMAND_HELP = <<-HELP.freeze
Usage: bolt command <action> <command> [options]
Available actions are:
run Run a command remotely
Available options are:
HELP
SCRIPT_HELP = <<-HELP.freeze
Usage: bolt script <action> <script> [[arg1] ... [argN]] [options]
Available actions are:
run Upload a local script and run it remotely
Available options are:
HELP
PLAN_HELP = <<-HELP.freeze
Usage: bolt plan <action> <plan> [options] [parameters]
Available actions are:
show Show list of available plans
run Run a Puppet task plan
Parameters are of the form <parameter>=<value>.
Available options are:
HELP
FILE_HELP = <<-HELP.freeze
Usage: bolt file <action> [options]
Available actions are:
upload <src> <dest> Upload local file <src> to <dest> on each node
Available options are:
HELP
COMMANDS = { 'command' => %w[run],
'script' => %w[run],
'task' => %w[show run],
'plan' => %w[show run],
'file' => %w[upload] }.freeze
TRANSPORTS = %w[ssh winrm pcp].freeze
BOLTLIB_PATH = File.join(__FILE__, '../../../modules')
attr_reader :parser, :config
attr_accessor :options
def initialize(argv)
Bolt::Logger.initialize_logging
@argv = argv
@options = {
nodes: []
}
@config = Bolt::Config.new
@parser = create_option_parser(@options)
@logger = Logging.logger[self]
end
def create_option_parser(results)
OptionParser.new('') do |opts|
opts.on(
'-n', '--nodes NODES',
'Node(s) to connect to in URI format [protocol://]host[:port]',
'Eg. --nodes bolt.puppet.com',
'Eg. --nodes localhost,ssh://nix.com:2222,winrm://windows.puppet.com',
"\n",
'* NODES can either be comma-separated, \'@<file>\' to read',
'* nodes from a file, or \'-\' to read from stdin',
'* Windows nodes must specify protocol with winrm://',
'* protocol is `ssh` by default, may be `ssh` or `winrm`',
'* port is `22` by default for SSH, `5985` for winrm (Optional)'
) do |nodes|
results[:nodes] += parse_nodes(nodes)
results[:nodes].uniq!
end
opts.on('-u', '--user USER',
"User to authenticate as (Optional)") do |user|
results[:user] = user
end
opts.on('-p', '--password [PASSWORD]',
'Password to authenticate with (Optional).',
'Omit the value to prompt for the password.') do |password|
if password.nil?
STDOUT.print "Please enter your password: "
results[:password] = STDIN.noecho(&:gets).chomp
STDOUT.puts
else
results[:password] = password
end
end
opts.on('--private-key KEY',
"Private ssh key to authenticate with (Optional)") do |key|
results[:key] = key
end
opts.on('--tmpdir DIR',
"The directory to upload and execute temporary files on the target(Optional)") do |tmpdir|
results[:tmpdir] = tmpdir
end
opts.on('-c', '--concurrency CONCURRENCY', Integer,
"Maximum number of simultaneous connections " \
"(Optional, defaults to 100)") do |concurrency|
results[:concurrency] = concurrency
end
opts.on('--connect-timeout TIMEOUT', Integer,
"Connection timeout (Optional)") do |timeout|
results[:connect_timeout] = timeout
end
opts.on('--modulepath MODULES',
"List of directories containing modules, " \
"separated by #{File::PATH_SEPARATOR}") do |modulepath|
results[:modulepath] = modulepath.split(File::PATH_SEPARATOR)
end
opts.on('--params PARAMETERS',
"Parameters to a task or plan") do |params|
results[:task_options] = parse_params(params)
end
opts.on('--format FORMAT',
"Output format to use: human or json") do |format|
results[:format] = format
end
opts.on('-k', '--insecure',
"Whether to connect insecurely ") do |insecure|
results[:insecure] = insecure
end
opts.on('--transport TRANSPORT', TRANSPORTS,
"Specify a default transport: #{TRANSPORTS.join(', ')}") do |t|
results[:transport] = t
end
opts.on('--run-as USER',
"User to run as using privilege escalation") do |user|
results[:run_as] = user
end
opts.on('--sudo-password [PASSWORD]',
'Password for privilege escalation') do |password|
if password.nil?
STDOUT.print "Please enter your privilege escalation password: "
results[:sudo_password] = STDIN.noecho(&:gets).chomp
STDOUT.puts
else
results[:sudo_password] = password
end
end
opts.on('--configfile CONFIG_PATH',
'Specify where to load the config file from') do |path|
results[:configfile] = path
end
opts.on_tail('--[no-]tty',
"Request a pseudo TTY on nodes that support it") do |tty|
results[:tty] = tty
end
opts.on_tail('--noop',
"Execute a task that supports it in noop mode") do |_|
results[:noop] = true
end
opts.on_tail('-h', '--help', 'Display help') do |_|
results[:help] = true
end
opts.on_tail('--verbose', 'Display verbose logging') do |_|
results[:verbose] = true
end
opts.on_tail('--debug', 'Display debug logging') do |_|
results[:debug] = true
end
opts.on_tail('--version', 'Display the version') do |_|
puts Bolt::VERSION
raise Bolt::CLIExit
end
end
end
def parse
if @argv.empty?
options[:help] = true
end
remaining = handle_parser_errors do
parser.permute(@argv)
end
# Shortcut to handle help before other errors may be generated
options[:mode] = remaining.shift
if options[:mode] == 'help'
options[:help] = true
options[:mode] = remaining.shift
end
if options[:help]
print_help(options[:mode])
raise Bolt::CLIExit
end
@config.load_file(options[:configfile])
@config.update_from_cli(options)
@config.validate
Logging.logger[:root].level = @config[:log_level] || :notice
# This section handles parsing non-flag options which are
# mode specific rather then part of the config
options[:action] = remaining.shift
options[:object] = remaining.shift
task_options, remaining = remaining.partition { |s| s =~ /.+=/ }
if options[:task_options]
unless task_options.empty?
raise Bolt::CLIError,
"Parameters must be specified through either the --params " \
"option or param=value pairs, not both"
end
else
options[:task_options] = Hash[task_options.map { |a| a.split('=', 2) }]
end
options[:leftovers] = remaining
validate(options)
options
rescue Bolt::CLIError => e
warn e.message
raise e
end
def print_help(mode)
parser.banner = case mode
when 'task'
TASK_HELP
when 'command'
COMMAND_HELP
when 'script'
SCRIPT_HELP
when 'file'
FILE_HELP
when 'plan'
PLAN_HELP
else
BANNER
end
puts parser.help
end
def parse_nodes(nodes)
list = get_arg_input(nodes)
list.split(/[[:space:],]+/).reject(&:empty?).uniq
end
def parse_params(params)
json = get_arg_input(params)
JSON.parse(json)
rescue JSON::ParserError => err
raise Bolt::CLIError, "Unable to parse --params value as JSON: #{err}"
end
def get_arg_input(value)
if value.start_with?('@')
file = value.sub(/^@/, '')
read_arg_file(file)
elsif value == '-'
STDIN.read
else
value
end
end
def read_arg_file(file)
File.read(file)
rescue StandardError => err
raise Bolt::CLIError, "Error attempting to read #{file}: #{err}"
end
def validate(options)
unless COMMANDS.include?(options[:mode])
raise Bolt::CLIError,
"Expected subcommand '#{options[:mode]}' to be one of " \
"#{COMMANDS.keys.join(', ')}"
end
if options[:action].nil?
raise Bolt::CLIError,
"Expected an action of the form 'bolt #{options[:mode]} <action>'"
end
actions = COMMANDS[options[:mode]]
unless actions.include?(options[:action])
raise Bolt::CLIError,
"Expected action '#{options[:action]}' to be one of " \
"#{actions.join(', ')}"
end
if options[:mode] != 'file' && options[:mode] != 'script' &&
!options[:leftovers].empty?
raise Bolt::CLIError,
"Unknown argument(s) #{options[:leftovers].join(', ')}"
end
if %w[task plan].include?(options[:mode]) && options[:action] == 'run'
if options[:object].nil?
raise Bolt::CLIError, "Must specify a #{options[:mode]} to run"
end
# This may mean that we parsed a parameter as the object
unless options[:object] =~ /\A([a-z][a-z0-9_]*)?(::[a-z][a-z0-9_]*)*\Z/
raise Bolt::CLIError,
"Invalid #{options[:mode]} '#{options[:object]}'"
end
end
if options[:nodes].empty? && options[:mode] != 'plan' && options[:action] != 'show'
raise Bolt::CLIError, "Option '--nodes' must be specified"
end
if %w[task plan].include?(options[:mode]) && @config[:modulepath].nil?
raise Bolt::CLIError,
"Option '--modulepath' must be specified when using" \
" a task or plan"
end
if options[:noop] && (options[:mode] != 'task' || options[:action] != 'run')
raise Bolt::CLIError,
"Option '--noop' may only be specified when running a task"
end
end
def handle_parser_errors
yield
rescue OptionParser::MissingArgument => e
raise Bolt::CLIError, "Option '#{e.args.first}' needs a parameter"
rescue OptionParser::InvalidOption => e
raise Bolt::CLIError, "Unknown argument '#{e.args.first}'"
end
def execute(options)
if options[:mode] == 'plan' || options[:mode] == 'task'
begin
require_relative '../../vendored/require_vendored'
rescue LoadError
raise Bolt::CLIError, "Puppet must be installed to execute tasks"
end
Puppet::Util::Log.newdestination(:console)
Puppet[:log_level] = if @config[:log_level] == :debug
'debug'
else
'notice'
end
end
# ExecutionResult loaded here so that it can get puppet features if
# puppet is present
require 'bolt/execution_result'
if options[:action] == 'show'
if options[:mode] == 'task'
if options[:object]
outputter.print_task_info(get_task_info(options[:object]))
else
outputter.print_table(list_tasks)
outputter.print_message("\nUse `bolt task show <task-name>` to view "\
"details and parameters for a specific "\
"task.")
end
elsif options[:mode] == 'plan'
outputter.print_table(list_plans)
end
return
end
if options[:mode] == 'plan'
executor = Bolt::Executor.new(@config, options[:noop], true)
execute_plan(executor, options)
else
executor = Bolt::Executor.new(@config, options[:noop])
nodes = executor.from_uris(options[:nodes])
results = nil
outputter.print_head
elapsed_time = Benchmark.realtime do
results =
case options[:mode]
when 'command'
executor.run_command(nodes, options[:object]) do |node, event|
outputter.print_event(node, event)
end
when 'script'
script = options[:object]
validate_file('script', script)
executor.run_script(
nodes, script, options[:leftovers]
) do |node, event|
outputter.print_event(node, event)
end
when 'task'
execute_task(executor, options) do |node, event|
outputter.print_event(node, event)
end
when 'file'
src = options[:object]
dest = options[:leftovers].first
if dest.nil?
raise Bolt::CLIError, "A destination path must be specified"
end
validate_file('source file', src)
executor.file_upload(nodes, src, dest) do |node, event|
outputter.print_event(node, event)
end
end
end
outputter.print_summary(results, elapsed_time)
end
rescue Bolt::CLIError => e
outputter.fatal_error(e)
raise e
end
def with_bolt_executor(executor, &block)
Puppet.override(bolt_executor: executor, &block)
end
def execute_task(executor, options, &block)
with_bolt_executor(executor) do
run_task(options[:object],
options[:nodes],
options[:task_options],
&block)
end
end
def execute_plan(executor, options)
# Plans return null here?
result = with_bolt_executor(executor) do
run_plan(options[:object],
options[:task_options])
end
outputter.print_plan(result)
end
def validate_file(type, path)
if path.nil?
raise Bolt::CLIError, "A #{type} must be specified"
end
stat = file_stat(path)
if !stat.readable?
raise Bolt::CLIError, "The #{type} '#{path}' is unreadable"
elsif !stat.file?
raise Bolt::CLIError, "The #{type} '#{path}' is not a file"
end
rescue Errno::ENOENT
raise Bolt::CLIError, "The #{type} '#{path}' does not exist"
end
def file_stat(path)
File.stat(path)
end
def outputter
@outputter ||= Bolt::Outputter.for_format(@config[:format])
end
# Runs a block in a PAL script compiler configured for Bolt.
# Catches exceptions thrown by the block and re-raises them as Bolt::CLIError.
def in_bolt_compiler(opts = [])
Puppet.initialize_settings(opts)
r = Puppet::Pal.in_tmp_environment('bolt', modulepath: [BOLTLIB_PATH] + @config[:modulepath], facts: {}) do |pal|
pal.with_script_compiler do |compiler|
begin
yield compiler
rescue Puppet::PreformattedError => err
err.cause
rescue StandardError => err
err
end
end
end
raise Bolt::CLIError, r.message if r.is_a? StandardError
r
end
def list_tasks
in_bolt_compiler do |compiler|
tasks = compiler.list_tasks
tasks.map(&:name).sort.map do |task_name|
task_sig = compiler.task_signature(task_name)
[task_name, task_sig.task.description]
end
end
end
def list_plans
in_bolt_compiler do |compiler|
compiler.list_plans.map { |plan| [plan.name] }.sort
end
end
def get_task_info(task_name)
task = in_bolt_compiler do |compiler|
compiler.task_signature(task_name)
end
raise Bolt::CLIError, "Could not find task #{task_name} in your modulepath" if task.nil?
task.task_hash
end
def run_task(name, nodes, args, &block)
in_bolt_compiler do |compiler|
compiler.call_function('run_task', name, nodes, args, &block)
end
end
# Expects to be called with a configured Puppet compiler or error.instance? will fail
def unwrap_execution_result(result)
if result.instance_of? Bolt::ExecutionResult
result.iterator.map do |node, output|
if output.is_a?(Puppet::DataTypes::Error)
# Get the original error hash used to initialize the Error type object.
result = output.partial_result || {}
result[:_error] = { msg: output.message,
kind: output.kind,
details: output.details,
issue_code: output.issue_code }
{ node: node, status: 'failed', result: result }
else
{ node: node, status: 'finished', result: output }
end
end
else
result
end
end
def run_plan(plan, args)
Dir.mktmpdir('bolt') do |dir|
cli = []
Puppet::Settings::REQUIRED_APP_SETTINGS.each do |setting|
cli << "--#{setting}" << dir
end
in_bolt_compiler(cli) do |compiler|
result = compiler.call_function('run_plan', plan, args)
# Querying ExecutionResult for failures currently requires a script compiler.
# Convert from an ExecutionResult to structured output that we can print.
unwrap_execution_result(result)
end
end
end
end
end
| 1 | 7,519 | Given this will 'pause' bolt for a few seconds on older rubies, perhaps emit a debug message saying "Warming up OpenSSL" or something to that effect | puppetlabs-bolt | rb |
@@ -85,6 +85,11 @@ class Package(object):
self._package = package
self._pkg_dir = pkg_dir
self._path = path
+ self._format = None
+
+ def set_format(self, pkgformat):
+ """Set the format. Only used when building a new package."""
+ self._format = pkgformat
def file(self, hash_list):
""" | 1 | from enum import Enum
import json
import os
from shutil import copyfile
import tempfile
import zlib
import pandas as pd
import requests
from six import iteritems
try:
import fastparquet
except ImportError:
fastparquet = None
try:
import pyarrow as pa
from pyarrow import parquet
except ImportError:
pa = None
try:
from pyspark.sql import SparkSession
except ImportError:
SparkSession = None
from .const import TargetType
from .core import (decode_node, encode_node, hash_contents,
FileNode, RootNode, GroupNode, TableNode,
PackageFormat)
from .hashing import digest_file
ZLIB_LEVEL = 2
ZLIB_METHOD = zlib.DEFLATED # The only supported one.
ZLIB_WBITS = zlib.MAX_WBITS | 16 # Add a gzip header and checksum.
CHUNK_SIZE = 4096
class ParquetLib(Enum):
ARROW = 'pyarrow'
FASTPARQUET = 'fastparquet'
SPARK = 'pyspark'
class PackageException(Exception):
"""
Exception class for Package handling
"""
pass
class Package(object):
BUILD_DIR = 'build'
OBJ_DIR = 'objs'
TMP_OBJ_DIR = 'objs/tmp'
DF_NAME = 'df'
__parquet_lib = None
@classmethod
def get_parquet_lib(cls):
if not cls.__parquet_lib:
parq_env = os.environ.get('QUILT_PARQUET_LIBRARY')
if parq_env:
cls.__parquet_lib = ParquetLib(parq_env)
else:
if SparkSession is not None:
cls.__parquet_lib = ParquetLib.SPARK
elif pa is not None:
cls.__parquet_lib = ParquetLib.ARROW
elif fastparquet is not None:
cls.__parquet_lib = ParquetLib.FASTPARQUET
else:
msg = "One of the following libraries is requried to read"
msg += " Parquet packages: %s" % [l.value for l in ParquetLib]
raise PackageException(msg)
return cls.__parquet_lib
@classmethod
def reset_parquet_lib(cls):
cls.__parquet_lib = None
def __init__(self, user, package, path, pkg_dir):
self._user = user
self._package = package
self._pkg_dir = pkg_dir
self._path = path
def file(self, hash_list):
"""
Returns the path to an object file that matches the given hash.
"""
assert isinstance(hash_list, list)
assert len(hash_list) == 1, "File objects must be contained in one file."
filehash = hash_list[0]
return self._object_path(filehash)
def _read_hdf5(self, hash_list):
assert len(hash_list) == 1, "Multi-file DFs not supported in HDF5."
filehash = hash_list[0]
with pd.HDFStore(self._object_path(filehash), 'r') as store:
return store.get(self.DF_NAME)
def _read_parquet_arrow(self, hash_list):
if pa is None:
raise PackageException("Module pyarrow is required for ArrowPackage.")
assert len(hash_list) == 1, "Multi-file DFs not supported for Arrow Packages (yet)."
filehash = hash_list[0]
nt = 8
fpath = self._object_path(filehash)
table = parquet.read_table(fpath, nthreads=nt)
df = table.to_pandas()
return df
def _read_parquet_fastparquet(self, hash_list):
assert len(hash_list) == 1, "Multi-file DFs not supported yet."
filehash = hash_list[0]
pfile = fastparquet.ParquetFile(self._object_path(filehash))
return pfile.to_pandas()
def _read_parquet_spark(self, hash_list):
if SparkSession is None:
raise PackageException("Module SparkSession from pyspark.sql is required for " +
"SparkPackage.")
spark = SparkSession.builder.getOrCreate()
assert len(hash_list) == 1, "Multi-file DFs not supported yet."
filehash = hash_list[0]
df = spark.read.parquet(self._object_path(filehash))
return df
def _dataframe(self, hash_list, pkgformat):
"""
Creates a DataFrame from a set of objects (identified by hashes).
"""
enumformat = PackageFormat(pkgformat)
if enumformat is PackageFormat.HDF5:
return self._read_hdf5(hash_list)
elif enumformat is PackageFormat.PARQUET:
parqlib = self.get_parquet_lib()
if parqlib is ParquetLib.SPARK:
return self._read_parquet_spark(hash_list)
elif parqlib is ParquetLib.ARROW:
return self._read_parquet_arrow(hash_list)
elif parqlib is ParquetLib.FASTPARQUET:
return self._read_parquet_fastparquet(hash_list)
else:
assert False, "Unimplemented Parquet Library %s" % parqlib
else:
assert False, "Unimplemented package format: %s" % enumformat
def save_df(self, df, name, path, ext, target):
"""
Save a DataFrame to the store.
"""
enumformat = PackageFormat(self.get_contents().format)
buildfile = name.lstrip('/').replace('/', '.')
storepath = self._temporary_object_path(buildfile)
# Serialize DataFrame to chosen format
if enumformat is PackageFormat.HDF5:
with pd.HDFStore(storepath, mode='w') as store:
store[self.DF_NAME] = df
elif enumformat is PackageFormat.PARQUET:
# switch parquet lib
parqlib = self.get_parquet_lib()
if parqlib is ParquetLib.FASTPARQUET:
fastparquet.write(storepath, df)
elif parqlib is ParquetLib.ARROW:
table = pa.Table.from_pandas(df)
parquet.write_table(table, storepath)
else:
assert False, "Unimplemented ParquetLib %s" % parqlib
else:
assert False, "Unimplemented PackageFormat %s" % enumformat
# Move serialized DataFrame to object store
filehash = digest_file(storepath)
self._add_to_contents(buildfile, filehash, ext, path, target)
os.rename(storepath, self._object_path(filehash))
def save_file(self, srcfile, name, path):
"""
Save a (raw) file to the store.
"""
filehash = digest_file(srcfile)
fullname = name.lstrip('/').replace('/', '.')
self._add_to_contents(fullname, filehash, '', path, 'file')
objpath = self._object_path(filehash)
if not os.path.exists(objpath):
copyfile(srcfile, objpath)
def get_contents(self):
"""
Returns a dictionary with the contents of the package.
"""
try:
with open(self._path, 'r') as contents_file:
contents = json.load(contents_file, object_hook=decode_node)
if not isinstance(contents, RootNode):
contents = RootNode(contents.children, PackageFormat.default.value)
except IOError:
contents = RootNode(dict(), PackageFormat.default)
return contents
def clear_contents(self):
"""
Removes the package's contents file.
"""
os.remove(self._path)
def save_contents(self, contents):
"""
Saves an updated version of the package's contents.
"""
with open(self._path, 'w') as contents_file:
json.dump(contents, contents_file, default=encode_node, indent=2, sort_keys=True)
def init_contents(self, pkgformat):
# Verify the format is recognized
enumformat = PackageFormat(pkgformat)
contents = RootNode(dict(), enumformat.value)
self.save_contents(contents)
def get(self, path):
"""
Read a group or object from the store.
"""
key = path.lstrip('/')
ipath = key.split('/') if key else []
ptr = self.get_contents()
pkgformat = ptr.format
path_so_far = []
for node_name in ipath:
path_so_far += [node_name]
ptr = ptr.children.get(node_name)
if ptr is None:
raise PackageException("Key {path} Not Found in Package {owner}/{pkg}".format(
path="/".join(path_so_far),
owner=self._user,
pkg=self._package))
node = ptr
if isinstance(node, GroupNode):
return node
elif isinstance(node, TableNode):
return self._dataframe(node.hashes, pkgformat)
elif isinstance(node, FileNode):
return self.file(node.hashes)
else:
assert False, "Unhandled Node {node}".format(node=node)
def get_hash(self):
"""
Returns the hash digest of the package data.
"""
return hash_contents(self.get_contents())
def get_path(self):
"""
Returns the path to the package's contents file.
"""
return self._path
def install(self, contents, urls):
"""
Download and install a package locally.
"""
# Download individual object files and store
# in object dir. Verify individual file hashes.
# Verify global hash?
for download_hash, url in iteritems(urls):
# download and install
response = requests.get(url, stream=True)
if not response.ok:
msg = "Download {hash} failed: error {code}"
raise PackageException(msg.format(hash=download_hash, code=response.status_code))
local_filename = self._object_path(download_hash)
with open(local_filename, 'wb') as output_file:
# `requests` will automatically un-gzip the content, as long as
# the 'Content-Encoding: gzip' header is set.
for chunk in response.iter_content(chunk_size=CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
output_file.write(chunk)
file_hash = digest_file(local_filename)
if file_hash != download_hash:
os.remove(local_filename)
raise PackageException("Mismatched hash! Expected %s, got %s." %
(download_hash, file_hash))
self.save_contents(contents)
class UploadFile(object):
"""
Helper class to manage temporary package files uploaded by push.
"""
def __init__(self, store, objhash):
self._store = store
self._hash = objhash
self._temp_file = None
def __enter__(self):
self._temp_file = tempfile.TemporaryFile()
with open(self._store._object_path(self._hash), 'rb') as input_file:
zlib_obj = zlib.compressobj(ZLIB_LEVEL, ZLIB_METHOD, ZLIB_WBITS)
for chunk in iter(lambda: input_file.read(CHUNK_SIZE), b''):
self._temp_file.write(zlib_obj.compress(chunk))
self._temp_file.write(zlib_obj.flush())
self._temp_file.seek(0)
return self._temp_file
def __exit__(self, type, value, traceback):
self._temp_file.close()
def tempfile(self, hash):
"""
Create and return a temporary file for uploading to a registry.
"""
return self.UploadFile(self, hash)
def _object_path(self, objhash):
"""
Returns the path to an object file based on its hash.
"""
return os.path.join(self._pkg_dir, self.OBJ_DIR, objhash)
def _temporary_object_path(self, name):
"""
Returns the path to a temporary object, before we know its hash.
"""
return os.path.join(self._pkg_dir, self.TMP_OBJ_DIR, name)
def _add_to_contents(self, fullname, objhash, ext, path, target):
"""
Adds an object (name-hash mapping) to the package's contents.
"""
contents = self.get_contents()
ipath = fullname.split('.')
leaf = ipath.pop()
ptr = contents
for node in ipath:
ptr = ptr.children.setdefault(node, GroupNode(dict()))
try:
target_type = TargetType(target)
if target_type is TargetType.PANDAS:
node_cls = TableNode
elif target_type is TargetType.FILE:
node_cls = FileNode
else:
assert False, "Unhandled TargetType {tt}".format(tt=target_type)
except ValueError:
raise PackageException("Unrecognized target {tgt}".format(tgt=target))
ptr.children[leaf] = node_cls(
hashes=[objhash],
metadata=dict(
q_ext=ext,
q_path=path,
q_target=target
)
)
self.save_contents(contents)
| 1 | 14,925 | Initializing _format to None, but asserting that it's not None later, seems unnecessarily fragile. We shouldn't architect the package class to rely on classes or methods that use it (e.g., build). Let's at least set the format to the default in case we don't create all packages through build.py. | quiltdata-quilt | py |
@@ -105,7 +105,7 @@ public interface WebDriver extends SearchContext {
* @see org.openqa.selenium.WebDriver.Timeouts
*/
@Override
- List<WebElement> findElements(By by);
+ <T extends WebElement> List<T> findElements(By by);
/** | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.logging.Logs;
import java.net.URL;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* WebDriver is a remote control interface that enables introspection and control of user agents
* (browsers). The methods in this interface fall into three categories:
* <ul>
* <li>Control of the browser itself</li>
* <li>Selection of {@link WebElement}s</li>
* <li>Debugging aids</li>
* </ul>
* <p>
* Key methods are {@link WebDriver#get(String)}, which is used to load a new web page, and the
* various methods similar to {@link WebDriver#findElement(By)}, which is used to find
* {@link WebElement}s.
* <p>
* Currently, you will need to instantiate implementations of this interface directly. It is hoped
* that you write your tests against this interface so that you may "swap in" a more fully featured
* browser when there is a requirement for one.
* <p>
* Most implementations of this interface follow
* <a href="https://w3c.github.io/webdriver/">W3C WebDriver specification</a>
*/
public interface WebDriver extends SearchContext {
// Navigation
/**
* Load a new web page in the current browser window. This is done using an HTTP POST operation,
* and the method will block until the load is complete (with the default 'page load strategy'.
* This will follow redirects issued either by the server or as a meta-redirect from within the
* returned HTML. Should a meta-redirect "rest" for any duration of time, it is best to wait until
* this timeout is over, since should the underlying page change whilst your test is executing the
* results of future calls against this interface will be against the freshly loaded page. Synonym
* for {@link org.openqa.selenium.WebDriver.Navigation#to(String)}.
* <p>
* See <a href="https://w3c.github.io/webdriver/#navigate-to">W3C WebDriver specification</a>
* for more details.
*
* @param url The URL to load. Must be a fully qualified URL
* @see org.openqa.selenium.PageLoadStrategy
*/
void get(String url);
/**
* Get a string representing the current URL that the browser is looking at.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-current-url">W3C WebDriver specification</a>
* for more details.
*
* @return The URL of the page currently loaded in the browser
*/
String getCurrentUrl();
// General properties
/**
* Get the title of the current page.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-title">W3C WebDriver specification</a>
* for more details.
*
* @return The title of the current page, with leading and trailing whitespace stripped, or null
* if one is not already set
*/
String getTitle();
/**
* Find all elements within the current page using the given mechanism.
* This method is affected by the 'implicit wait' times in force at the time of execution. When
* implicitly waiting, this method will return as soon as there are more than 0 items in the
* found collection, or will return an empty list if the timeout is reached.
* <p>
* See <a href="https://w3c.github.io/webdriver/#find-elements">W3C WebDriver specification</a>
* for more details.
*
* @param by The locating mechanism to use
* @return A list of all matching {@link WebElement}s, or an empty list if nothing matches
* @see org.openqa.selenium.By
* @see org.openqa.selenium.WebDriver.Timeouts
*/
@Override
List<WebElement> findElements(By by);
/**
* Find the first {@link WebElement} using the given method.
* This method is affected by the 'implicit wait' times in force at the time of execution.
* The findElement(..) invocation will return a matching row, or try again repeatedly until
* the configured timeout is reached.
* <p>
* findElement should not be used to look for non-present elements, use {@link #findElements(By)}
* and assert zero length response instead.
* <p>
* See <a href="https://w3c.github.io/webdriver/#find-element">W3C WebDriver specification</a>
* for more details.
*
* @param by The locating mechanism to use
* @return The first matching element on the current page
* @throws NoSuchElementException If no matching elements are found
* @see org.openqa.selenium.By
* @see org.openqa.selenium.WebDriver.Timeouts
*/
@Override
WebElement findElement(By by);
// Misc
/**
* Get the source of the last loaded page. If the page has been modified after loading (for
* example, by Javascript) there is no guarantee that the returned text is that of the modified
* page. Please consult the documentation of the particular driver being used to determine whether
* the returned text reflects the current state of the page or the text last sent by the web
* server. The page source returned is a representation of the underlying DOM: do not expect it to
* be formatted or escaped in the same way as the response sent from the web server. Think of it
* as an artist's impression.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-page-source">W3C WebDriver specification</a>
* for more details.
*
* @return The source of the current page
*/
String getPageSource();
/**
* Close the current window, quitting the browser if it's the last window currently open.
* <p>
* See <a href="https://w3c.github.io/webdriver/#close-window">W3C WebDriver specification</a>
* for more details.
*/
void close();
/**
* Quits this driver, closing every associated window.
*/
void quit();
/**
* Return a set of window handles which can be used to iterate over all open windows of this
* WebDriver instance by passing them to {@link #switchTo()}.{@link Options#window()}
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-window-handles">W3C WebDriver specification</a>
* for more details.
*
* @return A set of window handles which can be used to iterate over all open windows.
*/
Set<String> getWindowHandles();
/**
* Return an opaque handle to this window that uniquely identifies it within this driver instance.
* This can be used to switch to this window at a later date
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-window-handle">W3C WebDriver specification</a>
* for more details.
*
* @return the current window handle
*/
String getWindowHandle();
/**
* Send future commands to a different frame or window.
*
* @return A TargetLocator which can be used to select a frame or window
* @see org.openqa.selenium.WebDriver.TargetLocator
*/
TargetLocator switchTo();
/**
* An abstraction allowing the driver to access the browser's history and to navigate to a given
* URL.
*
* @return A {@link org.openqa.selenium.WebDriver.Navigation} that allows the selection of what to
* do next
*/
Navigation navigate();
/**
* Gets the Option interface
*
* @return An option interface
* @see org.openqa.selenium.WebDriver.Options
*/
Options manage();
/**
* An interface for managing stuff you would do in a browser menu
*/
interface Options {
/**
* Add a specific cookie. If the cookie's domain name is left blank, it is assumed that the
* cookie is meant for the domain of the current document.
* <p>
* See <a href="https://w3c.github.io/webdriver/#add-cookie">W3C WebDriver specification</a>
* for more details.
*
* @param cookie The cookie to add.
*/
void addCookie(Cookie cookie);
/**
* Delete the named cookie from the current domain. This is equivalent to setting the named
* cookie's expiry date to some time in the past.
* <p>
* See <a href="https://w3c.github.io/webdriver/#delete-cookie">W3C WebDriver specification</a>
* for more details.
*
* @param name The name of the cookie to delete
*/
void deleteCookieNamed(String name);
/**
* Delete a cookie from the browser's "cookie jar". The domain of the cookie will be ignored.
*
* @param cookie nom nom nom
*/
void deleteCookie(Cookie cookie);
/**
* Delete all the cookies for the current domain.
* <p>
* See <a href="https://w3c.github.io/webdriver/#delete-all-cookies">W3C WebDriver specification</a>
* for more details.
*/
void deleteAllCookies();
/**
* Get all the cookies for the current domain.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-all-cookies">W3C WebDriver specification</a>
* for more details.
*
* @return A Set of cookies for the current domain.
*/
Set<Cookie> getCookies();
/**
* Get a cookie with a given name.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-named-cookie">W3C WebDriver specification</a>
* for more details.
*
* @param name the name of the cookie
* @return the cookie, or null if no cookie with the given name is present
*/
Cookie getCookieNamed(String name);
/**
* @return the interface for managing driver timeouts.
*/
Timeouts timeouts();
/**
* @return the interface for controlling IME engines to generate complex-script input.
*/
ImeHandler ime();
/**
* @return the interface for managing the current window.
*/
Window window();
/**
* Gets the {@link Logs} interface used to fetch different types of logs.
* <p>
* To set the logging preferences {@link LoggingPreferences}.
*
* @return A Logs interface.
*/
@Beta
Logs logs();
}
/**
* An interface for managing timeout behavior for WebDriver instances.
* <p>
* See <a href="https://w3c.github.io/webdriver/#set-timeouts">W3C WebDriver specification</a>
* for more details.
*/
interface Timeouts {
/**
* @deprecated Use {@link #implicitlyWait(Duration)}
*
* Specifies the amount of time the driver should wait when searching for an element if it is
* not immediately present.
* <p>
* When searching for a single element, the driver should poll the page until the element has
* been found, or this timeout expires before throwing a {@link NoSuchElementException}. When
* searching for multiple elements, the driver should poll the page until at least one element
* has been found or this timeout has expired.
* <p>
* Increasing the implicit wait timeout should be used judiciously as it will have an adverse
* effect on test run time, especially when used with slower location strategies like XPath.
* <p>
* If the timeout is negative, not null, or greater than 2e16 - 1, an error code with invalid
* argument will be returned.
*
* @param time The amount of time to wait.
* @param unit The unit of measure for {@code time}.
* @return A self reference.
*/
@Deprecated
Timeouts implicitlyWait(long time, TimeUnit unit);
/**
* Specifies the amount of time the driver should wait when searching for an element if it is
* not immediately present.
* <p>
* When searching for a single element, the driver should poll the page until the element has
* been found, or this timeout expires before throwing a {@link NoSuchElementException}. When
* searching for multiple elements, the driver should poll the page until at least one element
* has been found or this timeout has expired.
* <p>
* Increasing the implicit wait timeout should be used judiciously as it will have an adverse
* effect on test run time, especially when used with slower location strategies like XPath.
* <p>
* If the timeout is negative, not null, or greater than 2e16 - 1, an error code with invalid
* argument will be returned.
*
* @param duration The duration to wait.
* @return A self reference.
*/
default Timeouts implicitlyWait(Duration duration) {
return implicitlyWait(duration.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Gets the amount of time the driver should wait when searching for an element if it is
* not immediately present.
*
* @return The amount of time the driver should wait when searching for an element.
* @see <a href="https://www.w3.org/TR/webdriver/#get-timeouts">W3C WebDriver</a>
*/
default Duration getImplicitWaitTimeout() {
throw new UnsupportedCommandException();
}
/**
* @deprecated Use {@link #setScriptTimeout(Duration)}
*
* Sets the amount of time to wait for an asynchronous script to finish execution before
* throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an
* error code with invalid argument will be returned.
*
* @param time The timeout value.
* @param unit The unit of time.
* @return A self reference.
* @see JavascriptExecutor#executeAsyncScript(String, Object...)
* @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
*/
@Deprecated
Timeouts setScriptTimeout(long time, TimeUnit unit);
/**
* Sets the amount of time to wait for an asynchronous script to finish execution before
* throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an
* error code with invalid argument will be returned.
*
* @param duration The timeout value.
* @deprecated Use {@link #scriptTimeout(Duration)}
* @return A self reference.
* @see JavascriptExecutor#executeAsyncScript(String, Object...)
* @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
*/
@Deprecated
default Timeouts setScriptTimeout(Duration duration) {
return setScriptTimeout(duration.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Sets the amount of time to wait for an asynchronous script to finish execution before
* throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an
* error code with invalid argument will be returned.
*
* @param duration The timeout value.
* @return A self reference.
* @see JavascriptExecutor#executeAsyncScript(String, Object...)
* @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
*/
default Timeouts scriptTimeout(Duration duration) {
return setScriptTimeout(duration);
}
/**
* Gets the amount of time to wait for an asynchronous script to finish execution before
* throwing an error. If the timeout is negative, not null, or greater than 2e16 - 1, an
* error code with invalid argument will be returned.
*
* @return The amount of time to wait for an asynchronous script to finish execution.
* @see <a href="https://www.w3.org/TR/webdriver/#get-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
*/
default Duration getScriptTimeout() {
throw new UnsupportedCommandException();
}
/**
* @param time The timeout value.
* @param unit The unit of time.
* @return A Timeouts interface.
* @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
* @deprecated Use {@link #pageLoadTimeout(Duration)}
*
* Sets the amount of time to wait for a page load to complete before throwing an error.
* If the timeout is negative, not null, or greater than 2e16 - 1, an error code with
* invalid argument will be returned.
*/
@Deprecated
Timeouts pageLoadTimeout(long time, TimeUnit unit);
/**
* Sets the amount of time to wait for a page load to complete before throwing an error.
* If the timeout is negative, not null, or greater than 2e16 - 1, an error code with
* invalid argument will be returned.
*
* @param duration The timeout value.
* @return A Timeouts interface.
* @see <a href="https://www.w3.org/TR/webdriver/#set-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
*/
default Timeouts pageLoadTimeout(Duration duration) {
return pageLoadTimeout(duration.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Gets the amount of time to wait for a page load to complete before throwing an error.
* If the timeout is negative, not null, or greater than 2e16 - 1, an error code with
* invalid argument will be returned.
*
* @return The amount of time to wait for a page load to complete.
* @see <a href="https://www.w3.org/TR/webdriver/#get-timeouts">W3C WebDriver</a>
* @see <a href="https://www.w3.org/TR/webdriver/#dfn-timeouts-configuration">W3C WebDriver</a>
*/
default Duration getPageLoadTimeout() {
throw new UnsupportedCommandException();
}
}
/**
* Used to locate a given frame or window.
*/
interface TargetLocator {
/**
* Select a frame by its (zero-based) index. Selecting a frame by index is equivalent to the
* JS expression window.frames[index] where "window" is the DOM window represented by the
* current context. Once the frame has been selected, all subsequent calls on the WebDriver
* interface are made to that frame.
* <p>
* See <a href="https://w3c.github.io/webdriver/#switch-to-frame">W3C WebDriver specification</a>
* for more details.
*
* @param index (zero-based) index
* @return This driver focused on the given frame
* @throws NoSuchFrameException If the frame cannot be found
*/
WebDriver frame(int index);
/**
* Select a frame by its name or ID. Frames located by matching name attributes are always given
* precedence over those matched by ID.
*
* @param nameOrId the name of the frame window, the id of the <frame> or <iframe>
* element, or the (zero-based) index
* @return This driver focused on the given frame
* @throws NoSuchFrameException If the frame cannot be found
*/
WebDriver frame(String nameOrId);
/**
* Select a frame using its previously located {@link WebElement}.
* <p>
* See <a href="https://w3c.github.io/webdriver/#switch-to-frame">W3C WebDriver specification</a>
* for more details.
*
* @param frameElement The frame element to switch to.
* @return This driver focused on the given frame.
* @throws NoSuchFrameException If the given element is neither an IFRAME nor a FRAME element.
* @throws StaleElementReferenceException If the WebElement has gone stale.
* @see WebDriver#findElement(By)
*/
WebDriver frame(WebElement frameElement);
/**
* Change focus to the parent context. If the current context is the top level browsing context,
* the context remains unchanged.
* <p>
* See <a href="https://w3c.github.io/webdriver/#switch-to-parent-frame">W3C WebDriver specification</a>
* for more details.
*
* @return This driver focused on the parent frame
*/
WebDriver parentFrame();
/**
* Switch the focus of future commands for this driver to the window with the given name/handle.
* <p>
* See <a href="https://w3c.github.io/webdriver/#switch-to-window">W3C WebDriver specification</a>
* for more details.
*
* @param nameOrHandle The name of the window or the handle as returned by
* {@link WebDriver#getWindowHandle()}
* @return This driver focused on the given window
* @throws NoSuchWindowException If the window cannot be found
*/
WebDriver window(String nameOrHandle);
/**
* Creates a new browser window and switches the focus for future commands of this driver
* to the new window.
* <p>
* See <a href="https://w3c.github.io/webdriver/#new-window">W3C WebDriver specification</a>
* for more details.
*
* @param typeHint The type of new browser window to be created. The created window is not
* guaranteed to be of the requested type; if the driver does not support
* the requested type, a new browser window will be created of whatever type
* the driver does support.
* @return This driver focused on the given window
*/
WebDriver newWindow(WindowType typeHint);
/**
* Selects either the first frame on the page, or the main document when a page contains
* iframes.
* <p>
* See <a href="https://w3c.github.io/webdriver/#switch-to-frame">W3C WebDriver specification</a>
* for more details.
*
* @return This driver focused on the top window/first frame.
*/
WebDriver defaultContent();
/**
* Switches to the element that currently has focus within the document currently "switched to",
* or the body element if this cannot be detected. This matches the semantics of calling
* "document.activeElement" in Javascript.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-active-element">W3C WebDriver specification</a>
* for more details.
*
* @return The WebElement with focus, or the body element if no element with focus can be
* detected.
*/
WebElement activeElement();
/**
* Switches to the currently active modal dialog for this particular driver instance.
*
* @return A handle to the dialog.
* @throws NoAlertPresentException If the dialog cannot be found
*/
Alert alert();
}
interface Navigation {
/**
* Move back a single "item" in the browser's history.
* <p>
* See <a href="https://w3c.github.io/webdriver/#back">W3C WebDriver specification</a>
* for more details.
*/
void back();
/**
* Move a single "item" forward in the browser's history. Does nothing if we are on the latest
* page viewed.
* <p>
* See <a href="https://w3c.github.io/webdriver/#forward">W3C WebDriver specification</a>
* for more details.
*/
void forward();
/**
* Load a new web page in the current browser window. This is done using an HTTP POST operation,
* and the method will block until the load is complete. This will follow redirects issued
* either by the server or as a meta-redirect from within the returned HTML. Should a
* meta-redirect "rest" for any duration of time, it is best to wait until this timeout is over,
* since should the underlying page change whilst your test is executing the results of future
* calls against this interface will be against the freshly loaded page.
* <p>
* See <a href="https://w3c.github.io/webdriver/#navigate-to">W3C WebDriver specification</a>
* for more details.
*
* @param url The URL to load. Must be a fully qualified URL
*/
void to(String url);
/**
* Overloaded version of {@link #to(String)} that makes it easy to pass in a URL.
*
* @param url URL
*/
void to(URL url);
/**
* Refresh the current page
* <p>
* See <a href="https://w3c.github.io/webdriver/#refresh">W3C WebDriver specification</a>
* for more details.
*/
void refresh();
}
/**
* An interface for managing input methods.
*/
interface ImeHandler {
/**
* All available engines on the machine. To use an engine, it has to be activated.
*
* @return list of available IME engines.
* @throws ImeNotAvailableException if the host does not support IME.
*/
List<String> getAvailableEngines();
/**
* Get the name of the active IME engine. The name string is platform-specific.
*
* @return name of the active IME engine.
* @throws ImeNotAvailableException if the host does not support IME.
*/
String getActiveEngine();
/**
* Indicates whether IME input active at the moment (not if it's available).
*
* @return true if IME input is available and currently active, false otherwise.
* @throws ImeNotAvailableException if the host does not support IME.
*/
boolean isActivated();
/**
* De-activate IME input (turns off the currently activated engine). Note that getActiveEngine
* may still return the name of the engine but isActivated will return false.
*
* @throws ImeNotAvailableException if the host does not support IME.
*/
void deactivate();
/**
* Make an engines that is available (appears on the list returned by getAvailableEngines)
* active. After this call, the only loaded engine on the IME daemon will be this one and the
* input sent using sendKeys will be converted by the engine. Note that this is a
* platform-independent method of activating IME (the platform-specific way being using keyboard
* shortcuts).
*
*
* @param engine name of engine to activate.
* @throws ImeNotAvailableException if the host does not support IME.
* @throws ImeActivationFailedException if the engine is not available or if activation failed
* for other reasons.
*/
void activateEngine(String engine);
}
@Beta
interface Window {
/**
* Get the size of the current window. This will return the outer window dimension, not just
* the view port.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-window-rect">W3C WebDriver specification</a>
* for more details.
*
* @return The current window size.
*/
Dimension getSize();
/**
* Set the size of the current window. This will change the outer window dimension,
* not just the view port, synonymous to window.resizeTo() in JS.
* <p>
* See <a href="https://w3c.github.io/webdriver/#set-window-rect">W3C WebDriver specification</a>
* for more details.
*
* @param targetSize The target size.
*/
void setSize(Dimension targetSize);
/**
* Get the position of the current window, relative to the upper left corner of the screen.
* <p>
* See <a href="https://w3c.github.io/webdriver/#get-window-rect">W3C WebDriver specification</a>
* for more details.
*
* @return The current window position.
*/
Point getPosition();
/**
* Set the position of the current window. This is relative to the upper left corner of the
* screen, synonymous to window.moveTo() in JS.
* <p>
* See <a href="https://w3c.github.io/webdriver/#set-window-rect">W3C WebDriver specification</a>
* for more details.
*
* @param targetPosition The target position of the window.
*/
void setPosition(Point targetPosition);
/**
* Maximizes the current window if it is not already maximized
* <p>
* See <a href="https://w3c.github.io/webdriver/#maximize-window">W3C WebDriver specification</a>
* for more details.
*/
void maximize();
/**
* Minimizes the current window if it is not already minimized
* <p>
* See <a href="https://w3c.github.io/webdriver/#minimize-window">W3C WebDriver specification</a>
* for more details.
*/
void minimize();
/**
* Fullscreen the current window if it is not already fullscreen
* <p>
* See <a href="https://w3c.github.io/webdriver/#fullscreen-window">W3C WebDriver specification</a>
* for more details.
*/
void fullscreen();
}
}
| 1 | 19,274 | This change should also probably go into the corresponding method of the abstract By class? | SeleniumHQ-selenium | py |
@@ -0,0 +1,8 @@
+<?php
+namespace Psalm\Issue;
+
+class UnresolvableConstant extends CodeIssue
+{
+ public const ERROR_LEVEL = -1;
+ public const SHORTCODE = 303;
+} | 1 | 1 | 12,109 | Should this be set to something else? | vimeo-psalm | php |
|
@@ -0,0 +1 @@
+Hi | 1 | 1 | 6,896 | Whats up with this? It looks like this is rendered on purchases/new for subscribers, so it would result in a dead end? | thoughtbot-upcase | rb |
|
@@ -1326,13 +1326,13 @@ class StoreOptions(object):
return specs
@classmethod
- def propagate_ids(cls, obj, match_id, new_id, applied_keys):
+ def propagate_ids(cls, obj, match_id, new_id, applied_keys, backend=None):
"""
Recursively propagate an id through an object for components
matching the applied_keys. This method can only be called if
there is a tree with a matching id in Store.custom_options
"""
- if not new_id in Store.custom_options():
+ if not new_id in Store.custom_options(backend=backend):
raise AssertionError("The set_ids method requires "
"Store.custom_options to contain"
" a tree with id %d" % new_id) | 1 | """
Options and OptionTrees allow different classes of options
(e.g. matplotlib-specific styles and plot specific parameters) to be
defined separately from the core data structures and away from
visualization specific code.
There are three classes that form the options system:
Cycle:
Used to define infinite cycles over a finite set of elements, using
either an explicit list or some pre-defined collection (e.g from
matplotlib rcParams). For instance, a Cycle object can be used loop
a set of display colors for multiple curves on a single axis.
Options:
Containers of arbitrary keyword values, including optional keyword
validation, support for Cycle objects and inheritance.
OptionTree:
A subclass of AttrTree that is used to define the inheritance
relationships between a collection of Options objects. Each node
of the tree supports a group of Options objects and the leaf nodes
inherit their keyword values from parent nodes up to the root.
Store:
A singleton class that stores all global and custom options and
links HoloViews objects, the chosen plotting backend and the IPython
extension together.
"""
import pickle
import traceback
import difflib
from contextlib import contextmanager
from collections import OrderedDict, defaultdict
import numpy as np
import param
from .tree import AttrTree
from .util import sanitize_identifier, group_sanitizer,label_sanitizer, basestring
from .pprint import InfoPrinter
class SkipRendering(Exception):
"""
A SkipRendering exception in the plotting code will make the display
hooks fall back to a text repr. Used to skip rendering of
DynamicMaps with exhausted element generators.
"""
def __init__(self, message="", warn=True):
self.warn = warn
super(SkipRendering, self).__init__(message)
class OptionError(Exception):
"""
Custom exception raised when there is an attempt to apply invalid
options. Stores the necessary information to construct a more
readable message for the user if caught and processed
appropriately.
"""
def __init__(self, invalid_keyword, allowed_keywords,
group_name=None, path=None):
super(OptionError, self).__init__(self.message(invalid_keyword,
allowed_keywords,
group_name, path))
self.invalid_keyword = invalid_keyword
self.allowed_keywords = allowed_keywords
self.group_name =group_name
self.path = path
def message(self, invalid_keyword, allowed_keywords, group_name, path):
msg = ("Invalid option %s, valid options are: %s"
% (repr(invalid_keyword), str(allowed_keywords)))
if path and group_name:
msg = ("Invalid key for group %r on path %r;\n"
% (group_name, path)) + msg
return msg
def format_options_error(self):
"""
Return a fuzzy match message based on the OptionError
"""
allowed_keywords = self.allowed_keywords
target = allowed_keywords.target
matches = allowed_keywords.fuzzy_match(self.invalid_keyword)
if not matches:
matches = allowed_keywords.values
similarity = 'Possible'
else:
similarity = 'Similar'
loaded_backends = Store.loaded_backends()
target = 'for {0}'.format(target) if target else ''
if len(loaded_backends) == 1:
loaded=' in loaded backend {0!r}'.format(loaded_backends[0])
else:
backend_list = ', '.join(['%r'% b for b in loaded_backends[:-1]])
loaded=' in loaded backends {0} and {1!r}'.format(backend_list,
loaded_backends[-1])
suggestion = ("If you believe this keyword is correct, please make sure "
"the backend has been imported or loaded with the "
"hv.extension.")
group = '{0} option'.format(self.group_name) if self.group_name else 'keyword'
msg=('Unexpected {group} {kw} {target}{loaded}.\n\n'
'{similarity} keywords in the currently active '
'{current_backend} renderer are: {matches}\n\n{suggestion}')
return msg.format(kw="'%s'" % self.invalid_keyword,
target=target,
group=group,
loaded=loaded, similarity=similarity,
current_backend=repr(Store.current_backend),
matches=matches,
suggestion=suggestion)
class AbbreviatedException(Exception):
"""
Raised by the abbreviate_exception context manager when it is
appropriate to present an abbreviated the traceback and exception
message in the notebook.
Particularly useful when processing style options supplied by the
user which may not be valid.
"""
def __init__(self, etype, value, traceback):
self.etype = etype
self.value = value
self.traceback = traceback
self.msg = str(value)
def __str__(self):
abbrev = '%s: %s' % (self.etype.__name__, self.msg)
msg = ('To view the original traceback, catch this exception '
'and call print_traceback() method.')
return '%s\n\n%s' % (abbrev, msg)
def print_traceback(self):
"""
Print the traceback of the exception wrapped by the AbbreviatedException.
"""
traceback.print_exception(self.etype, self.value, self.traceback)
class abbreviated_exception(object):
"""
Context manager used to to abbreviate tracebacks using an
AbbreviatedException when a backend may raise an error due to
incorrect style options.
"""
def __enter__(self):
return self
def __exit__(self, etype, value, traceback):
if isinstance(value, Exception):
raise AbbreviatedException(etype, value, traceback)
@contextmanager
def options_policy(skip_invalid, warn_on_skip):
"""
Context manager to temporarily set the skip_invalid and warn_on_skip
class parameters on Options.
"""
settings = (Options.skip_invalid, Options.warn_on_skip)
(Options.skip_invalid, Options.warn_on_skip) = (skip_invalid, warn_on_skip)
yield
(Options.skip_invalid, Options.warn_on_skip) = settings
class Keywords(param.Parameterized):
"""
A keywords objects represents a set of Python keywords. It is
list-like and ordered but it is also a set without duplicates. When
passed as **kwargs, Python keywords are not ordered but this class
always lists keywords in sorted order.
In addition to containing the list of keywords, Keywords has an
optional target which describes what the keywords are applicable to.
This class is for internal use only and should not be in the user
namespace.
"""
values = param.List(doc="Set of keywords as a sorted list.")
target = param.String(allow_None=True, doc="""
Optional string description of what the keywords apply to.""")
def __init__(self, values=[], target=None):
strings = [isinstance(v, (str,basestring)) for v in values]
if False in strings:
raise ValueError('All keywords must be strings: {0}'.format(values))
super(Keywords, self).__init__(values=sorted(values),
target=target)
def __add__(self, other):
if (self.target and other.target) and (self.target != other.target):
raise Exception('Targets must match to combine Keywords')
target = self.target or other.target
return Keywords(sorted(set(self.values + other.values)), target=target)
def fuzzy_match(self, kw):
"""
Given a string, fuzzy match against the Keyword values,
returning a list of close matches.
"""
return difflib.get_close_matches(kw, self.values)
def __repr__(self):
if self.target:
msg = 'Keywords({values}, target={target})'
info = dict(values=self.values, target=self.target)
else:
msg = 'Keywords({values})'
info = dict(values=self.values)
return msg.format(**info)
def __str__(self): return str(self.values)
def __iter__(self): return iter(self.values)
def __bool__(self): return bool(self.values)
def __nonzero__(self): return bool(self.values)
def __contains__(self, val): return val in self.values
class Cycle(param.Parameterized):
"""
A simple container class that specifies cyclic options. A typical
example would be to cycle the curve colors in an Overlay composed
of an arbitrary number of curves. The values may be supplied as
an explicit list or a key to look up in the default cycles
attribute.
"""
key = param.String(default='default_colors', doc="""
The key in the default_cycles dictionary used to specify the
color cycle if values is not supplied. """)
values = param.List(default=[], doc="""
The values the cycle will iterate over.""")
default_cycles = {'default_colors': []}
def __init__(self, cycle=None, **params):
if cycle is not None:
if isinstance(cycle, basestring):
params['key'] = cycle
else:
params['values'] = cycle
super(Cycle, self).__init__(**params)
self.values = self._get_values()
def __getitem__(self, num):
return self(values=self.values[:num])
def _get_values(self):
if self.values: return self.values
elif self.key:
return self.default_cycles[self.key]
else:
raise ValueError("Supply either a key or explicit values.")
def __call__(self, values=None, **params):
values = values if values else self.values
return self.__class__(**dict(self.get_param_values(), values=values, **params))
def __len__(self):
return len(self.values)
def __repr__(self):
return "%s(values=%s)" % (type(self).__name__,
[str(el) for el in self.values])
def grayscale(val):
return (val, val, val, 1.0)
class Palette(Cycle):
"""
Palettes allow easy specifying a discrete sampling
of an existing colormap. Palettes may be supplied a key
to look up a function function in the colormap class
attribute. The function should accept a float scalar
in the specified range and return a RGB(A) tuple.
The number of samples may also be specified as a
parameter.
The range and samples may conveniently be overridden
with the __getitem__ method.
"""
key = param.String(default='grayscale', doc="""
Palettes look up the Palette values based on some key.""")
range = param.NumericTuple(default=(0, 1), doc="""
The range from which the Palette values are sampled.""")
samples = param.Integer(default=32, doc="""
The number of samples in the given range to supply to
the sample_fn.""")
sample_fn = param.Callable(default=np.linspace, doc="""
The function to generate the samples, by default linear.""")
reverse = param.Boolean(default=False, doc="""
Whether to reverse the palette.""")
# A list of available colormaps
colormaps = {'grayscale': grayscale}
def __init__(self, key, **params):
super(Cycle, self).__init__(key=key, **params)
self.values = self._get_values()
def __getitem__(self, slc):
"""
Provides a convenient interface to override the
range and samples parameters of the Cycle.
Supplying a slice step or index overrides the
number of samples. Unsupplied slice values will be
inherited.
"""
(start, stop), step = self.range, self.samples
if isinstance(slc, slice):
if slc.start is not None:
start = slc.start
if slc.stop is not None:
stop = slc.stop
if slc.step is not None:
step = slc.step
else:
step = slc
return self(range=(start, stop), samples=step)
def _get_values(self):
cmap = self.colormaps[self.key]
(start, stop), steps = self.range, self.samples
samples = [cmap(n) for n in self.sample_fn(start, stop, steps)]
return samples[::-1] if self.reverse else samples
class Options(param.Parameterized):
"""
An Options object holds a collection of keyword options. In
addition, Options support (optional) keyword validation as well as
infinite indexing over the set of supplied cyclic values.
Options support inheritance of setting values via the __call__
method. By calling an Options object with additional keywords, you
can create a new Options object inheriting the parent options.
"""
allowed_keywords = param.ClassSelector(class_=Keywords, doc="""
Optional list of strings corresponding to the allowed keywords.""")
key = param.String(default=None, allow_None=True, doc="""
Optional specification of the options key name. For instance,
key could be 'plot' or 'style'.""")
merge_keywords = param.Boolean(default=True, doc="""
Whether to merge with the existing keywords if the corresponding
node already exists""")
skip_invalid = param.Boolean(default=True, doc="""
Whether all Options instances should skip invalid keywords or
raise and exception. May only be specified at the class level.""")
warn_on_skip = param.Boolean(default=True, doc="""
Whether all Options instances should generate warnings when
skipping over invalid keywords or not. May only be specified at
the class level.""")
def __init__(self, key=None, allowed_keywords=[], merge_keywords=True, **kwargs):
invalid_kws = []
for kwarg in sorted(kwargs.keys()):
if allowed_keywords and kwarg not in allowed_keywords:
if self.skip_invalid:
invalid_kws.append(kwarg)
else:
raise OptionError(kwarg, allowed_keywords)
for invalid_kw in invalid_kws:
error = OptionError(invalid_kw, allowed_keywords, group_name=key)
StoreOptions.record_skipped_option(error)
if invalid_kws and self.warn_on_skip:
self.warning("Invalid options %s, valid options are: %s"
% (repr(invalid_kws), str(allowed_keywords)))
self.kwargs = {k:v for k,v in kwargs.items() if k not in invalid_kws}
self._options = self._expand_options(kwargs)
allowed_keywords = (allowed_keywords if isinstance(allowed_keywords, Keywords)
else Keywords(allowed_keywords))
super(Options, self).__init__(allowed_keywords=allowed_keywords,
merge_keywords=merge_keywords, key=key)
def keywords_target(self, target):
"""
Helper method to easily set the target on the allowed_keywords Keywords.
"""
self.allowed_keywords.target = target
return self
def filtered(self, allowed):
"""
Return a new Options object that is filtered by the specified
list of keys. Mutating self.kwargs to filter is unsafe due to
the option expansion that occurs on initialization.
"""
kws = {k:v for k,v in self.kwargs.items() if k in allowed}
return self.__class__(key=self.key,
allowed_keywords=self.allowed_keywords,
merge_keywords=self.merge_keywords, **kws)
def __call__(self, allowed_keywords=None, **kwargs):
"""
Create a new Options object that inherits the parent options.
"""
allowed_keywords=self.allowed_keywords if allowed_keywords in [None,[]] else allowed_keywords
inherited_style = dict(allowed_keywords=allowed_keywords, **kwargs)
return self.__class__(key=self.key, **dict(self.kwargs, **inherited_style))
def _expand_options(self, kwargs):
"""
Expand out Cycle objects into multiple sets of keyword values.
To elaborate, the full Cartesian product over the supplied
Cycle objects is expanded into a list, allowing infinite,
cyclic indexing in the __getitem__ method."""
filter_static = dict((k,v) for (k,v) in kwargs.items() if not isinstance(v, Cycle))
filter_cycles = [(k,v) for (k,v) in kwargs.items() if isinstance(v, Cycle)]
if not filter_cycles: return [kwargs]
filter_names, filter_values = list(zip(*filter_cycles))
cyclic_tuples = list(zip(*[val.values for val in filter_values]))
return [dict(zip(filter_names, tps), **filter_static) for tps in cyclic_tuples]
def keys(self):
"The keyword names across the supplied options."
return sorted(list(self.kwargs.keys()))
def max_cycles(self, num):
"""
Truncates all contained Cycle objects to a maximum number
of Cycles and returns a new Options object with the
truncated or resampled Cycles.
"""
kwargs = {kw: (arg[num] if isinstance(arg, Cycle) else arg)
for kw, arg in self.kwargs.items()}
return self(**kwargs)
def __getitem__(self, index):
"""
Infinite cyclic indexing of options over the integers,
looping over the set of defined Cycle objects.
"""
return dict(self._options[index % len(self._options)])
@property
def options(self):
"Access of the options keywords when no cycles are defined."
if len(self._options) == 1:
return dict(self._options[0])
else:
raise Exception("The options property may only be used with non-cyclic Options.")
def __repr__(self):
kws = ', '.join("%s=%r" % (k,v) for (k,v) in self.kwargs.items())
return "%s(%s)" % (self.__class__.__name__, kws)
def __str__(self):
return repr(self)
class OptionTree(AttrTree):
"""
A subclass of AttrTree that is used to define the inheritance
relationships between a collection of Options objects. Each node
of the tree supports a group of Options objects and the leaf nodes
inherit their keyword values from parent nodes up to the root.
Supports the ability to search the tree for the closest valid path
using the find method, or compute the appropriate Options value
given an object and a mode. For a given node of the tree, the
options method computes a Options object containing the result of
inheritance for a given group up to the root of the tree.
When constructing an OptionTree, you can specify the option groups
as a list (i.e empty initial option groups at the root) or as a
dictionary (e.g groups={'style':Option()}). You can also
initialize the OptionTree with the options argument together with
the **kwargs - see StoreOptions.merge_options for more information
on the options specification syntax.
You can use the string specifier '.' to refer to the root node in
the options specification. This acts as an alternative was of
specifying the options groups of the current node. Note that this
approach method may only be used with the group lists format.
"""
def __init__(self, items=None, identifier=None, parent=None,
groups=None, options=None, **kwargs):
if groups is None:
raise ValueError('Please supply groups list or dictionary')
_groups = {g:Options() for g in groups} if isinstance(groups, list) else groups
self.__dict__['groups'] = _groups
self.__dict__['_instantiated'] = False
AttrTree.__init__(self, items, identifier, parent)
self.__dict__['_instantiated'] = True
options = StoreOptions.merge_options(_groups.keys(), options, **kwargs)
root_groups = options.pop('.', None)
if root_groups and isinstance(groups, list):
self.__dict__['groups'] = {g:Options(**root_groups.get(g,{})) for g in _groups.keys()}
elif root_groups:
raise Exception("Group specification as a dictionary only supported if "
"the root node '.' syntax not used in the options.")
if options:
StoreOptions.apply_customizations(options, self)
def _merge_options(self, identifier, group_name, options):
"""
Computes a merged Options object for the given group
name from the existing Options on the node and the
new Options which are passed in.
"""
if group_name not in self.groups:
raise KeyError("Group %s not defined on SettingTree" % group_name)
if identifier in self.children:
current_node = self[identifier]
group_options = current_node.groups[group_name]
else:
#When creating a node (nothing to merge with) ensure it is empty
group_options = Options(group_name,
allowed_keywords=self.groups[group_name].allowed_keywords)
override_kwargs = dict(options.kwargs)
old_allowed = group_options.allowed_keywords
override_kwargs['allowed_keywords'] = options.allowed_keywords + old_allowed
try:
return (group_options(**override_kwargs)
if options.merge_keywords else Options(group_name, **override_kwargs))
except OptionError as e:
raise OptionError(e.invalid_keyword,
e.allowed_keywords,
group_name=group_name,
path = self.path)
def __getitem__(self, item):
if item in self.groups:
return self.groups[item]
return super(OptionTree, self).__getitem__(item)
def __getattr__(self, identifier):
"""
Allows creating sub OptionTree instances using attribute
access, inheriting the group options.
"""
try:
return super(AttrTree, self).__getattr__(identifier)
except AttributeError: pass
if identifier.startswith('_'): raise AttributeError(str(identifier))
elif self.fixed==True: raise AttributeError(self._fixed_error % identifier)
valid_id = sanitize_identifier(identifier, escape=False)
if valid_id in self.children:
return self.__dict__[valid_id]
# When creating a intermediate child node, leave kwargs empty
self.__setattr__(identifier, {k:Options(k, allowed_keywords=v.allowed_keywords)
for k,v in self.groups.items()})
return self[identifier]
def __setattr__(self, identifier, val):
identifier = sanitize_identifier(identifier, escape=False)
new_groups = {}
if isinstance(val, dict):
group_items = val
elif isinstance(val, Options) and val.key is None:
raise AttributeError("Options object needs to have a group name specified.")
elif isinstance(val, Options):
group_items = {val.key: val}
elif isinstance(val, OptionTree):
group_items = val.groups
current_node = self[identifier] if identifier in self.children else self
for group_name in current_node.groups:
options = group_items.get(group_name, False)
if options:
new_groups[group_name] = self._merge_options(identifier, group_name, options)
else:
new_groups[group_name] = current_node.groups[group_name]
if new_groups:
data = self[identifier].items() if identifier in self.children else None
new_node = OptionTree(data, identifier=identifier, parent=self, groups=new_groups)
else:
raise ValueError('OptionTree only accepts a dictionary of Options.')
super(OptionTree, self).__setattr__(identifier, new_node)
if isinstance(val, OptionTree):
for subtree in val:
self[identifier].__setattr__(subtree.identifier, subtree)
def find(self, path, mode='node'):
"""
Find the closest node or path to an the arbitrary path that is
supplied down the tree from the given node. The mode argument
may be either 'node' or 'path' which determines the return
type.
"""
path = path.split('.') if isinstance(path, str) else list(path)
item = self
for child in path:
escaped_child = sanitize_identifier(child, escape=False)
matching_children = [c for c in item.children
if child.endswith(c) or escaped_child.endswith(c)]
matching_children = sorted(matching_children, key=lambda x: -len(x))
if matching_children:
item = item[matching_children[0]]
else:
continue
return item if mode == 'node' else item.path
def closest(self, obj, group):
"""
This method is designed to be called from the root of the
tree. Given any LabelledData object, this method will return
the most appropriate Options object, including inheritance.
In addition, closest supports custom options by checking the
object
"""
components = (obj.__class__.__name__,
group_sanitizer(obj.group),
label_sanitizer(obj.label))
target = '.'.join([c for c in components if c])
return self.find(components).options(group, target=target)
def options(self, group, target=None):
"""
Using inheritance up to the root, get the complete Options
object for the given node and the specified group.
"""
if target is None:
target = self.path
if self.groups.get(group, None) is None:
return None
if self.parent is None and target and (self is not Store.options()):
root_name = self.__class__.__name__
replacement = root_name + ('' if len(target) == len(root_name) else '.')
option_key = target.replace(replacement,'')
match = Store.options().find(option_key)
if match is not Store.options():
return match.options(group)
else:
return Options()
elif self.parent is None:
return self.groups[group]
return Options(**dict(self.parent.options(group,target=target).kwargs,
**self.groups[group].kwargs))
def __repr__(self):
"""
Evalable representation of the OptionTree.
"""
groups = self.__dict__['groups']
# Tab and group entry separators
tab, gsep = ' ', ',\n\n'
# Entry separator and group specifications
esep, gspecs = (",\n"+(tab*2)), []
for group in groups.keys():
especs, accumulator = [], []
if groups[group].kwargs != {}:
accumulator.append(('.', groups[group].kwargs))
for t, v in sorted(self.items()):
kwargs = v.groups[group].kwargs
accumulator.append(('.'.join(t), kwargs))
for (t, kws) in accumulator:
if group=='norm' and all(kws.get(k, False) is False for k in ['axiswise','framewise']):
continue
elif kws:
especs.append((t, kws))
if especs:
format_kws = [(t,'dict(%s)'
% ', '.join('%s=%r' % (k,v) for k,v in sorted(kws.items())))
for t,kws in especs]
ljust = max(len(t) for t,_ in format_kws)
sep = (tab*2) if len(format_kws) >1 else ''
entries = sep + esep.join([sep+'%r : %s' % (t.ljust(ljust),v) for t,v in format_kws])
gspecs.append(('%s%s={\n%s}' if len(format_kws)>1 else '%s%s={%s}') % (tab,group, entries))
return 'OptionTree(groups=%s,\n%s\n)' % (groups.keys(), gsep.join(gspecs))
class Compositor(param.Parameterized):
"""
A Compositor is a way of specifying an operation to be automatically
applied to Overlays that match a specified pattern upon display.
Any Operation that takes an Overlay as input may be used to define a
compositor.
For instance, a compositor may be defined to automatically display
three overlaid monochrome matrices as an RGB image as long as the
values names of those matrices match 'R', 'G' and 'B'.
"""
mode = param.ObjectSelector(default='data',
objects=['data', 'display'], doc="""
The mode of the Compositor object which may be either 'data' or
'display'.""")
operation = param.Parameter(doc="""
The Operation to apply when collapsing overlays.""")
pattern = param.String(doc="""
The overlay pattern to be processed. An overlay pattern is a
sequence of elements specified by dotted paths separated by * .
For instance the following pattern specifies three overlayed
matrices with values of 'RedChannel', 'GreenChannel' and
'BlueChannel' respectively:
'Image.RedChannel * Image.GreenChannel * Image.BlueChannel.
This pattern specification could then be associated with the RGB
operation that returns a single RGB matrix for display.""")
group = param.String(allow_None=True, doc="""
The group identifier for the output of this particular compositor""")
kwargs = param.Dict(doc="""
Optional set of parameters to pass to the operation.""")
transfer_options = param.Boolean(default=False, doc="""
Whether to transfer the options from the input to the output.""")
transfer_parameters = param.Boolean(default=False, doc="""
Whether to transfer plot options which match to the operation.""")
operations = [] # The operations that can be used to define compositors.
definitions = [] # The set of all the compositor instances
@classmethod
def strongest_match(cls, overlay, mode):
"""
Returns the single strongest matching compositor operation
given an overlay. If no matches are found, None is returned.
The best match is defined as the compositor operation with the
highest match value as returned by the match_level method.
"""
match_strength = [(op.match_level(overlay), op) for op in cls.definitions
if op.mode == mode]
matches = [(match[0], op, match[1]) for (match, op) in match_strength if match is not None]
if matches == []: return None
else: return sorted(matches)[0]
@classmethod
def collapse_element(cls, overlay, ranges=None, mode='data', backend=None):
"""
Finds any applicable compositor and applies it.
"""
from .overlay import Overlay, CompositeOverlay
unpack = False
if not isinstance(overlay, CompositeOverlay):
overlay = Overlay([overlay])
unpack = True
prev_ids = tuple()
while True:
match = cls.strongest_match(overlay, mode)
if match is None:
if unpack and len(overlay) == 1:
return overlay.values()[0]
return overlay
(_, applicable_op, (start, stop)) = match
if isinstance(overlay, Overlay):
values = overlay.values()
sliced = Overlay(values[start:stop])
else:
values = overlay.items()
sliced = overlay.clone(values[start:stop])
result = applicable_op.apply(sliced, ranges, backend)
if applicable_op.group:
result = result.relabel(group=applicable_op.group)
if isinstance(overlay, Overlay):
result = [result]
else:
result = list(zip(sliced.keys(), [result]))
overlay = overlay.clone(values[:start]+result+values[stop:])
# Guard against infinite recursion for no-ops
spec_fn = lambda x: not isinstance(x, CompositeOverlay)
new_ids = tuple(overlay.traverse(lambda x: id(x), [spec_fn]))
if new_ids == prev_ids:
return overlay
prev_ids = new_ids
@classmethod
def collapse(cls, holomap, ranges=None, mode='data'):
"""
Given a map of Overlays, apply all applicable compositors.
"""
# No potential compositors
if cls.definitions == []:
return holomap
# Apply compositors
clone = holomap.clone(shared_data=False)
data = zip(ranges[1], holomap.data.values()) if ranges else holomap.data.items()
for key, overlay in data:
clone[key] = cls.collapse_element(overlay, ranges, mode)
return clone
@classmethod
def map(cls, obj, mode='data', backend=None):
"""
Applies compositor operations to any HoloViews element or container
using the map method.
"""
from .overlay import CompositeOverlay
element_compositors = [c for c in cls.definitions if len(c._pattern_spec) == 1]
overlay_compositors = [c for c in cls.definitions if len(c._pattern_spec) > 1]
if overlay_compositors:
obj = obj.map(lambda obj: cls.collapse_element(obj, mode=mode, backend=backend),
[CompositeOverlay])
element_patterns = [c.pattern for c in element_compositors]
if element_compositors and obj.traverse(lambda x: x, element_patterns):
obj = obj.map(lambda obj: cls.collapse_element(obj, mode=mode, backend=backend),
element_patterns)
return obj
@classmethod
def register(cls, compositor):
defined_patterns = [op.pattern for op in cls.definitions]
if compositor.pattern in defined_patterns:
cls.definitions.pop(defined_patterns.index(compositor.pattern))
cls.definitions.append(compositor)
if compositor.operation not in cls.operations:
cls.operations.append(compositor.operation)
def __init__(self, pattern, operation, group, mode, transfer_options=False,
transfer_parameters=False, output_type=None, **kwargs):
self._pattern_spec, labels = [], []
for path in pattern.split('*'):
path_tuple = tuple(el.strip() for el in path.strip().split('.'))
self._pattern_spec.append(path_tuple)
if len(path_tuple) == 3:
labels.append(path_tuple[2])
if len(labels) > 1 and not all(l==labels[0] for l in labels):
raise KeyError("Mismatched labels not allowed in compositor patterns")
elif len(labels) == 1:
self.label = labels[0]
else:
self.label = ''
self._output_type = output_type
super(Compositor, self).__init__(group=group,
pattern=pattern,
operation=operation,
mode=mode,
kwargs=kwargs,
transfer_options=transfer_options,
transfer_parameters=transfer_parameters)
@property
def output_type(self):
"""
Returns the operation output_type unless explicitly overridden
in the kwargs.
"""
return self._output_type or self.operation.output_type
def _slice_match_level(self, overlay_items):
"""
Find the match strength for a list of overlay items that must
be exactly the same length as the pattern specification.
"""
level = 0
for spec, el in zip(self._pattern_spec, overlay_items):
if spec[0] != type(el).__name__:
return None
level += 1 # Types match
if len(spec) == 1: continue
group = [el.group, group_sanitizer(el.group, escape=False)]
if spec[1] in group: level += 1 # Values match
else: return None
if len(spec) == 3:
group = [el.label, label_sanitizer(el.label, escape=False)]
if (spec[2] in group):
level += 1 # Labels match
else:
return None
return level
def match_level(self, overlay):
"""
Given an overlay, return the match level and applicable slice
of the overall overlay. The level an integer if there is a
match or None if there is no match.
The level integer is the number of matching components. Higher
values indicate a stronger match.
"""
slice_width = len(self._pattern_spec)
if slice_width > len(overlay): return None
# Check all the possible slices and return the best matching one
best_lvl, match_slice = (0, None)
for i in range(len(overlay)-slice_width+1):
overlay_slice = overlay.values()[i:i+slice_width]
lvl = self._slice_match_level(overlay_slice)
if lvl is None: continue
if lvl > best_lvl:
best_lvl = lvl
match_slice = (i, i+slice_width)
return (best_lvl, match_slice) if best_lvl != 0 else None
def apply(self, value, input_ranges, backend=None):
"""
Apply the compositor on the input with the given input ranges.
"""
from .overlay import CompositeOverlay
if backend is None: backend = Store.current_backend
kwargs = {k: v for k, v in self.kwargs.items() if k != 'output_type'}
if isinstance(value, CompositeOverlay) and len(value) == 1:
value = value.values()[0]
if self.transfer_parameters:
plot_opts = Store.lookup_options(backend, value, 'plot').kwargs
kwargs.update({k: v for k, v in plot_opts.items()
if k in self.operation.params()})
transformed = self.operation(value, input_ranges=input_ranges, **kwargs)
if self.transfer_options:
Store.transfer_options(value, transformed, backend)
return transformed
class Store(object):
"""
The Store is what links up HoloViews objects to their
corresponding options and to the appropriate classes of the chosen
backend (e.g for rendering).
In addition, Store supports pickle operations that automatically
pickle and unpickle the corresponding options for a HoloViews
object.
"""
renderers = OrderedDict() # The set of available Renderers across all backends.
# A mapping from ViewableElement types to their corresponding plot
# types grouped by the backend. Set using the register method.
registry = {}
# A list of formats to be published for display on the frontend (e.g
# IPython Notebook or a GUI application)
display_formats = ['html']
# Once register_plotting_classes is called, this OptionTree is
# populated for the given backend.
_options = {}
# A list of hooks to call after registering the plot and style options
option_setters = []
# A dictionary of custom OptionTree by custom object id by backend
_custom_options = {'matplotlib':{}}
load_counter_offset = None
save_option_state = False
current_backend = 'matplotlib'
@classmethod
def options(cls, backend=None, val=None):
backend = cls.current_backend if backend is None else backend
if val is None:
return cls._options[backend]
else:
cls._options[backend] = val
@classmethod
def loaded_backends(cls):
"""
Returns a list of the backends that have been loaded, based on
the available OptionTrees.
"""
return list(cls._options.keys())
@classmethod
def custom_options(cls, val=None, backend=None):
backend = cls.current_backend if backend is None else backend
if val is None:
return cls._custom_options[backend]
else:
cls._custom_options[backend] = val
@classmethod
def load(cls, filename):
"""
Equivalent to pickle.load except that the HoloViews trees is
restored appropriately.
"""
cls.load_counter_offset = StoreOptions.id_offset()
val = pickle.load(filename)
cls.load_counter_offset = None
return val
@classmethod
def loads(cls, pickle_string):
"""
Equivalent to pickle.loads except that the HoloViews trees is
restored appropriately.
"""
cls.load_counter_offset = StoreOptions.id_offset()
val = pickle.loads(pickle_string)
cls.load_counter_offset = None
return val
@classmethod
def dump(cls, obj, file, protocol=0):
"""
Equivalent to pickle.dump except that the HoloViews option
tree is saved appropriately.
"""
cls.save_option_state = True
pickle.dump(obj, file, protocol=protocol)
cls.save_option_state = False
@classmethod
def dumps(cls, obj, protocol=0):
"""
Equivalent to pickle.dumps except that the HoloViews option
tree is saved appropriately.
"""
cls.save_option_state = True
val = pickle.dumps(obj, protocol=protocol)
cls.save_option_state = False
return val
@classmethod
def info(cls, obj, ansi=True, backend='matplotlib', visualization=True,
recursive=False, pattern=None, elements=[]):
"""
Show information about a particular object or component class
including the applicable style and plot options. Returns None if
the object is not parameterized.
"""
parameterized_object = isinstance(obj, param.Parameterized)
parameterized_class = (isinstance(obj,type)
and issubclass(obj,param.Parameterized))
info = None
if parameterized_object or parameterized_class:
info = InfoPrinter.info(obj, ansi=ansi, backend=backend,
visualization=visualization,
pattern=pattern, elements=elements)
if parameterized_object and recursive:
hierarchy = obj.traverse(lambda x: type(x))
listed = []
for c in hierarchy[1:]:
if c not in listed:
inner_info = InfoPrinter.info(c, ansi=ansi, backend=backend,
visualization=visualization,
pattern=pattern)
black = '\x1b[1;30m%s\x1b[0m' if ansi else '%s'
info += '\n\n' + (black % inner_info)
listed.append(c)
return info
@classmethod
def lookup_options(cls, backend, obj, group):
# Current custom_options dict may not have entry for obj.id
if obj.id in cls._custom_options[backend]:
return cls._custom_options[backend][obj.id].closest(obj, group)
else:
return cls._options[backend].closest(obj, group)
@classmethod
def lookup(cls, backend, obj):
"""
Given an object, lookup the corresponding customized option
tree if a single custom tree is applicable.
"""
ids = set([el for el in obj.traverse(lambda x: x.id) if el is not None])
if len(ids) == 0:
raise Exception("Object does not own a custom options tree")
elif len(ids) != 1:
idlist = ",".join([str(el) for el in sorted(ids)])
raise Exception("Object contains elements combined across "
"multiple custom trees (ids %s)" % idlist)
return cls._custom_options[backend][list(ids)[0]]
@classmethod
def transfer_options(cls, obj, new_obj, backend=None):
"""
Transfers options for all backends from one object to another.
Drops any options defined in the supplied drop list.
"""
backend = cls.current_backend if backend is None else backend
type_name = type(new_obj).__name__
group = type_name if obj.group == type(obj).__name__ else obj.group
spec = '.'.join([s for s in (type_name, group, obj.label) if s])
options = []
for group in ['plot', 'style', 'norm']:
opts = cls.lookup_options(backend, obj, group)
if opts and opts.kwargs: options.append(Options(group, **opts.kwargs))
if options:
StoreOptions.set_options(new_obj, {spec: options}, backend)
@classmethod
def add_style_opts(cls, component, new_options, backend=None):
"""
Given a component such as an Element (e.g. Image, Curve) or a
container (e.g Layout) specify new style options to be
accepted by the corresponding plotting class.
Note: This is supplied for advanced users who know which
additional style keywords are appropriate for the
corresponding plotting class.
"""
backend = cls.current_backend if backend is None else backend
if component not in cls.registry[backend]:
raise ValueError("Component %r not registered to a plotting class" % component)
if not isinstance(new_options, list) or not all(isinstance(el, str) for el in new_options):
raise ValueError("Please supply a list of style option keyword strings")
with param.logging_level('CRITICAL'):
for option in new_options:
if option not in cls.registry[backend][component].style_opts:
plot_class = cls.registry[backend][component]
plot_class.style_opts = sorted(plot_class.style_opts+[option])
cls._options[backend][component.name] = Options('style', merge_keywords=True, allowed_keywords=new_options)
@classmethod
def register(cls, associations, backend, style_aliases={}):
"""
Register the supplied dictionary of associations between
elements and plotting classes to the specified backend.
"""
from .overlay import CompositeOverlay
if backend not in cls.registry:
cls.registry[backend] = {}
cls.registry[backend].update(associations)
groups = ['style', 'plot', 'norm']
if backend not in cls._options:
cls._options[backend] = OptionTree([], groups=groups)
if backend not in cls._custom_options:
cls._custom_options[backend] = {}
for view_class, plot in cls.registry[backend].items():
expanded_opts = [opt for key in plot.style_opts
for opt in style_aliases.get(key, [])]
style_opts = sorted(set(opt for opt in (expanded_opts + plot.style_opts)
if opt not in plot._disabled_opts))
plot_opts = [k for k in plot.params().keys() if k not in ['name']]
with param.logging_level('CRITICAL'):
plot.style_opts = style_opts
plot_opts = Keywords(plot_opts, target=view_class.__name__)
style_opts = Keywords(style_opts, target=view_class.__name__)
opt_groups = {'plot': Options(allowed_keywords=plot_opts)}
if not isinstance(view_class, CompositeOverlay) or hasattr(plot, 'style_opts'):
opt_groups.update({'style': Options(allowed_keywords=style_opts),
'norm': Options(framewise=False, axiswise=False,
allowed_keywords=['framewise',
'axiswise'])})
name = view_class.__name__
cls._options[backend][name] = opt_groups
class StoreOptions(object):
"""
A collection of utilities for advanced users for creating and
setting customized option trees on the Store. Designed for use by
either advanced users or the %opts line and cell magics which use
this machinery.
This class also holds general classmethods for working with
OptionTree instances: as OptionTrees are designed for attribute
access it is best to minimize the number of methods implemented on
that class and implement the necessary utilities on StoreOptions
instead.
Lastly this class offers a means to record all OptionErrors
generated by an option specification. This is used for validation
purposes.
"""
#=======================#
# OptionError recording #
#=======================#
_errors_recorded = None
@classmethod
def start_recording_skipped(cls):
"""
Start collecting OptionErrors for all skipped options recorded
with the record_skipped_option method
"""
cls._errors_recorded = []
@classmethod
def stop_recording_skipped(cls):
"""
Stop collecting OptionErrors recorded with the
record_skipped_option method and return them
"""
if cls._errors_recorded is None:
raise Exception('Cannot stop recording before it is started')
recorded = cls._errors_recorded[:]
cls._errors_recorded = None
return recorded
@classmethod
def record_skipped_option(cls, error):
"""
Record the OptionError associated with a skipped option if
currently recording
"""
if cls._errors_recorded is not None:
cls._errors_recorded.append(error)
#===============#
# ID management #
#===============#
@classmethod
def get_object_ids(cls, obj):
return set(el for el
in obj.traverse(lambda x: getattr(x, 'id', None)))
@classmethod
def tree_to_dict(cls, tree):
"""
Given an OptionTree, convert it into the equivalent dictionary format.
"""
specs = {}
for k in tree.keys():
spec_key = '.'.join(k)
specs[spec_key] = {}
for grp in tree[k].groups:
kwargs = tree[k].groups[grp].kwargs
if kwargs:
specs[spec_key][grp] = kwargs
return specs
@classmethod
def propagate_ids(cls, obj, match_id, new_id, applied_keys):
"""
Recursively propagate an id through an object for components
matching the applied_keys. This method can only be called if
there is a tree with a matching id in Store.custom_options
"""
if not new_id in Store.custom_options():
raise AssertionError("The set_ids method requires "
"Store.custom_options to contain"
" a tree with id %d" % new_id)
def propagate(o):
if o.id == match_id or (o.__class__.__name__ == 'DynamicMap'):
setattr(o, 'id', new_id)
obj.traverse(propagate, specs=set(applied_keys) | {'DynamicMap'})
@classmethod
def capture_ids(cls, obj):
"""
Given an list of ids, capture a list of ids that can be
restored using the restore_ids.
"""
return obj.traverse(lambda o: getattr(o, 'id'))
@classmethod
def restore_ids(cls, obj, ids):
"""
Given an list of ids as captured with capture_ids, restore the
ids. Note the structure of an object must not change between
the calls to capture_ids and restore_ids.
"""
ids = iter(ids)
obj.traverse(lambda o: setattr(o, 'id', next(ids)))
@classmethod
def apply_customizations(cls, spec, options):
"""
Apply the given option specs to the supplied options tree.
"""
for key in sorted(spec.keys()):
if isinstance(spec[key], (list, tuple)):
customization = {v.key:v for v in spec[key]}
else:
customization = {k:(Options(**v) if isinstance(v, dict) else v)
for k,v in spec[key].items()}
# Set the Keywords target on Options from the {type} part of the key.
customization = {k:v.keywords_target(key.split('.')[0])
for k,v in customization.items()}
options[str(key)] = customization
return options
@classmethod
def validate_spec(cls, spec, backends=None):
"""
Given a specification, validated it against the options tree for
the specified backends by raising OptionError for invalid
options. If backends is None, validates against all the
currently loaded backend.
Only useful when invalid keywords generate exceptions instead of
skipping i.e Options.skip_invalid is False.
"""
loaded_backends = Store.loaded_backends()if backends is None else backends
error_info = {}
backend_errors = defaultdict(set)
for backend in loaded_backends:
cls.start_recording_skipped()
with options_policy(skip_invalid=True, warn_on_skip=False):
options = OptionTree(items=Store.options(backend).data.items(),
groups=Store.options(backend).groups)
cls.apply_customizations(spec, options)
for error in cls.stop_recording_skipped():
error_key = (error.invalid_keyword,
error.allowed_keywords.target,
error.group_name)
error_info[error_key+(backend,)] = error.allowed_keywords
backend_errors[error_key].add(backend)
for ((keyword, target, group_name), backends) in backend_errors.items():
# If the keyword failed for the target across all loaded backends...
if set(backends) == set(loaded_backends):
key = (keyword, target, group_name, Store.current_backend)
raise OptionError(keyword,
group_name=group_name,
allowed_keywords=error_info[key])
@classmethod
def validation_error_message(cls, spec, backends=None):
"""
Returns an options validation error message if there are any
invalid keywords. Otherwise returns None.
"""
try:
cls.validate_spec(spec, backends=backends)
except OptionError as e:
return e.format_options_error()
@classmethod
def expand_compositor_keys(cls, spec):
"""
Expands compositor definition keys into {type}.{group}
keys. For instance a compositor operation returning a group
string 'Image' of element type RGB expands to 'RGB.Image'.
"""
expanded_spec={}
applied_keys = []
compositor_defs = {el.group:el.output_type.__name__
for el in Compositor.definitions}
for key, val in spec.items():
if key not in compositor_defs:
expanded_spec[key] = val
else:
# Send id to Overlays
applied_keys = ['Overlay']
type_name = compositor_defs[key]
expanded_spec[str(type_name+'.'+key)] = val
return expanded_spec, applied_keys
@classmethod
def create_custom_trees(cls, obj, options=None):
"""
Returns the appropriate set of customized subtree clones for
an object, suitable for merging with Store.custom_options (i.e
with the ids appropriately offset). Note if an object has no
integer ids a new OptionTree is built.
The id_mapping return value is a list mapping the ids that
need to be matched as set to their new values.
"""
clones, id_mapping = {}, []
obj_ids = cls.get_object_ids(obj)
offset = cls.id_offset()
obj_ids = [None] if len(obj_ids)==0 else obj_ids
for tree_id in obj_ids:
if tree_id is not None and tree_id in Store.custom_options():
original = Store.custom_options()[tree_id]
clone = OptionTree(items = original.items(),
groups = original.groups)
clones[tree_id + offset + 1] = clone
id_mapping.append((tree_id, tree_id + offset + 1))
else:
clone = OptionTree(groups=Store.options().groups)
clones[offset] = clone
id_mapping.append((tree_id, offset))
# Nodes needed to ensure allowed_keywords is respected
for k in Store.options():
if k in [(opt.split('.')[0],) for opt in options]:
group = {grp:Options(
allowed_keywords=opt.allowed_keywords)
for (grp, opt) in
Store.options()[k].groups.items()}
clone[k] = group
return {k:cls.apply_customizations(options, t) if options else t
for k,t in clones.items()}, id_mapping
@classmethod
def merge_options(cls, groups, options=None,**kwargs):
"""
Given a full options dictionary and options groups specified
as a keywords, return the full set of merged options:
>>> options={'Curve':{'style':dict(color='b')}}
>>> style={'Curve':{'linewidth':10 }}
>>> merged = StoreOptions.merge_options(['style'], options, style=style)
>>> sorted(merged['Curve']['style'].items())
[('color', 'b'), ('linewidth', 10)]
"""
groups = set(groups)
if (options is not None and set(options.keys()) <= groups):
kwargs, options = options, None
elif (options is not None and any(k in groups for k in options)):
raise Exception("All keys must be a subset of %s"
% ', '.join(groups))
options = {} if (options is None) else dict(**options)
all_keys = set(k for d in kwargs.values() for k in d)
for spec_key in all_keys:
additions = {}
for k, d in kwargs.items():
if spec_key in d:
kws = d[spec_key]
additions.update({k:kws})
if spec_key not in options:
options[spec_key] = {}
for key in additions:
if key in options[spec_key]:
options[spec_key][key].update(additions[key])
else:
options[spec_key][key] = additions[key]
return options
@classmethod
def state(cls, obj, state=None):
"""
Method to capture and restore option state. When called
without any state supplied, the current state is
returned. Then if this state is supplied back in a later call
using the same object, the original state is restored.
"""
if state is None:
ids = cls.capture_ids(obj)
original_custom_keys = set(Store.custom_options().keys())
return (ids, original_custom_keys)
else:
(ids, original_custom_keys) = state
current_custom_keys = set(Store.custom_options().keys())
for key in current_custom_keys.difference(original_custom_keys):
del Store.custom_options()[key]
cls.restore_ids(obj, ids)
@classmethod
@contextmanager
def options(cls, obj, options=None, **kwargs):
"""
Context-manager for temporarily setting options on an object
(if options is None, no options will be set) . Once the
context manager exits, both the object and the Store will be
left in exactly the same state they were in before the context
manager was used.
See holoviews.core.options.set_options function for more
information on the options specification format.
"""
if (options is None) and kwargs == {}: yield
else:
optstate = cls.state(obj)
groups = Store.options().groups.keys()
options = cls.merge_options(groups, options, **kwargs)
cls.set_options(obj, options)
yield
if options is not None:
cls.state(obj, state=optstate)
@classmethod
def id_offset(cls):
"""
Compute an appropriate offset for future id values given the set
of ids currently defined across backends.
"""
max_ids = []
for backend in Store.renderers.keys():
store_ids = Store.custom_options(backend=backend).keys()
max_id = max(store_ids)+1 if len(store_ids) > 0 else 0
max_ids.append(max_id)
# If no backends defined (e.g plotting not imported) return zero
return max(max_ids) if len(max_ids) else 0
@classmethod
def update_backends(cls, id_mapping, custom_trees, backend=None):
"""
Given the id_mapping from previous ids to new ids and the new
custom tree dictionary, update the current backend with the
supplied trees and update the keys in the remaining backends to
stay linked with the current object.
"""
# Update the custom option entries for the current backend
Store.custom_options(backend=backend).update(custom_trees)
# Update the entries in other backends so the ids match correctly
for backend in [k for k in Store.renderers.keys() if k != Store.current_backend]:
for (old_id, new_id) in id_mapping:
tree = Store._custom_options[backend].pop(old_id, None)
if tree is not None:
Store._custom_options[backend][new_id] = tree
@classmethod
def set_options(cls, obj, options=None, backend=None, **kwargs):
"""
Pure Python function for customize HoloViews objects in terms of
their style, plot and normalization options.
The options specification is a dictionary containing the target
for customization as a {type}.{group}.{label} keys. An example of
such a key is 'Image' which would customize all Image components
in the object. The key 'Image.Channel' would only customize Images
in the object that have the group 'Channel'.
The corresponding value is then a list of Option objects specified
with an appropriate category ('plot', 'style' or 'norm'). For
instance, using the keys described above, the specs could be:
{'Image:[Options('style', cmap='jet')]}
Or setting two types of option at once:
{'Image.Channel':[Options('plot', size=50),
Options('style', cmap='Blues')]}
Relationship to the %%opts magic
----------------------------------
This function matches the functionality supplied by the %%opts
cell magic in the IPython extension. In fact, you can use the same
syntax as the IPython cell magic to achieve the same customization
as shown above:
from holoviews.util.parser import OptsSpec
set_options(my_image, OptsSpec.parse("Image (cmap='jet')"))
Then setting both plot and style options:
set_options(my_image, OptsSpec.parse("Image [size=50] (cmap='Blues')"))
"""
# Note that an alternate, more verbose and less recommended
# syntax can also be used:
# {'Image.Channel:{'plot': Options(size=50),
# 'style': Options('style', cmap='Blues')]}
options = cls.merge_options(Store.options(backend=backend).groups.keys(), options, **kwargs)
spec, compositor_applied = cls.expand_compositor_keys(options)
custom_trees, id_mapping = cls.create_custom_trees(obj, spec)
cls.update_backends(id_mapping, custom_trees)
for (match_id, new_id) in id_mapping:
cls.propagate_ids(obj, match_id, new_id, compositor_applied+list(spec.keys()))
return obj
| 1 | 20,025 | Glad to see this generalized to support the backend argument. | holoviz-holoviews | py |
@@ -1781,3 +1781,11 @@ func (a *WebAPI) GetInsightApplicationCount(ctx context.Context, req *webservice
UpdatedAt: c.UpdatedAt,
}, nil
}
+
+func (a *WebAPI) ListDeploymentChains(ctx context.Context, req *webservice.ListDeploymentChainsRequest) (*webservice.ListDeploymentChainsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "not yet implemented")
+}
+
+func (a *WebAPI) GetDeploymentChain(ctx context.Context, req *webservice.GetDeploymentChainRequest) (*webservice.GetDeploymentChainResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "not yet implemented")
+} | 1 | // Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package grpcapi
import (
"bytes"
"context"
"encoding/gob"
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/google/uuid"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/pipe-cd/pipe/pkg/app/api/applicationlivestatestore"
"github.com/pipe-cd/pipe/pkg/app/api/commandstore"
"github.com/pipe-cd/pipe/pkg/app/api/service/webservice"
"github.com/pipe-cd/pipe/pkg/app/api/stagelogstore"
"github.com/pipe-cd/pipe/pkg/cache"
"github.com/pipe-cd/pipe/pkg/cache/memorycache"
"github.com/pipe-cd/pipe/pkg/cache/rediscache"
"github.com/pipe-cd/pipe/pkg/config"
"github.com/pipe-cd/pipe/pkg/datastore"
"github.com/pipe-cd/pipe/pkg/filestore"
"github.com/pipe-cd/pipe/pkg/insight/insightstore"
"github.com/pipe-cd/pipe/pkg/model"
"github.com/pipe-cd/pipe/pkg/redis"
"github.com/pipe-cd/pipe/pkg/rpc/rpcauth"
)
type encrypter interface {
Encrypt(text string) (string, error)
}
// WebAPI implements the behaviors for the gRPC definitions of WebAPI.
type WebAPI struct {
applicationStore datastore.ApplicationStore
environmentStore datastore.EnvironmentStore
deploymentStore datastore.DeploymentStore
pipedStore datastore.PipedStore
projectStore datastore.ProjectStore
apiKeyStore datastore.APIKeyStore
stageLogStore stagelogstore.Store
applicationLiveStateStore applicationlivestatestore.Store
commandStore commandstore.Store
insightStore insightstore.Store
encrypter encrypter
appProjectCache cache.Cache
deploymentProjectCache cache.Cache
pipedProjectCache cache.Cache
envProjectCache cache.Cache
pipedStatCache cache.Cache
insightCache cache.Cache
redis redis.Redis
projectsInConfig map[string]config.ControlPlaneProject
logger *zap.Logger
}
// NewWebAPI creates a new WebAPI instance.
func NewWebAPI(
ctx context.Context,
ds datastore.DataStore,
fs filestore.Store,
sls stagelogstore.Store,
alss applicationlivestatestore.Store,
cmds commandstore.Store,
is insightstore.Store,
psc cache.Cache,
rd redis.Redis,
projs map[string]config.ControlPlaneProject,
encrypter encrypter,
logger *zap.Logger,
) *WebAPI {
a := &WebAPI{
applicationStore: datastore.NewApplicationStore(ds),
environmentStore: datastore.NewEnvironmentStore(ds),
deploymentStore: datastore.NewDeploymentStore(ds),
pipedStore: datastore.NewPipedStore(ds),
projectStore: datastore.NewProjectStore(ds),
apiKeyStore: datastore.NewAPIKeyStore(ds),
stageLogStore: sls,
applicationLiveStateStore: alss,
commandStore: cmds,
insightStore: is,
projectsInConfig: projs,
encrypter: encrypter,
appProjectCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
deploymentProjectCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
pipedProjectCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
envProjectCache: memorycache.NewTTLCache(ctx, 24*time.Hour, 3*time.Hour),
pipedStatCache: psc,
insightCache: rediscache.NewTTLCache(rd, 3*time.Hour),
redis: rd,
logger: logger.Named("web-api"),
}
return a
}
// Register registers all handling of this service into the specified gRPC server.
func (a *WebAPI) Register(server *grpc.Server) {
webservice.RegisterWebServiceServer(server, a)
}
func (a *WebAPI) AddEnvironment(ctx context.Context, req *webservice.AddEnvironmentRequest) (*webservice.AddEnvironmentResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
env := model.Environment{
Id: uuid.New().String(),
Name: req.Name,
Desc: req.Desc,
ProjectId: claims.Role.ProjectId,
}
err = a.environmentStore.AddEnvironment(ctx, &env)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "The environment already exists")
}
if err != nil {
a.logger.Error("failed to create environment", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to create environment")
}
return &webservice.AddEnvironmentResponse{}, nil
}
func (a *WebAPI) UpdateEnvironmentDesc(ctx context.Context, req *webservice.UpdateEnvironmentDescRequest) (*webservice.UpdateEnvironmentDescResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
func (a *WebAPI) ListEnvironments(ctx context.Context, req *webservice.ListEnvironmentsRequest) (*webservice.ListEnvironmentsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
},
}
envs, err := a.environmentStore.ListEnvironments(ctx, opts)
if err != nil {
a.logger.Error("failed to get environments", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get environments")
}
return &webservice.ListEnvironmentsResponse{
Environments: envs,
}, nil
}
func (a *WebAPI) EnableEnvironment(ctx context.Context, req *webservice.EnableEnvironmentRequest) (*webservice.EnableEnvironmentResponse, error) {
if err := a.updateEnvironmentEnable(ctx, req.EnvironmentId, true); err != nil {
return nil, err
}
return &webservice.EnableEnvironmentResponse{}, nil
}
func (a *WebAPI) DisableEnvironment(ctx context.Context, req *webservice.DisableEnvironmentRequest) (*webservice.DisableEnvironmentResponse, error) {
if err := a.updateEnvironmentEnable(ctx, req.EnvironmentId, false); err != nil {
return nil, err
}
return &webservice.DisableEnvironmentResponse{}, nil
}
// DeleteEnvironment deletes the given environment and all applications that belong to it.
// It returns a FailedPrecondition error if any Piped is still using that environment.
func (a *WebAPI) DeleteEnvironment(ctx context.Context, req *webservice.DeleteEnvironmentRequest) (*webservice.DeleteEnvironmentResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if err := a.validateEnvBelongsToProject(ctx, req.EnvironmentId, claims.Role.ProjectId); err != nil {
return nil, err
}
// Check if no Piped has permission to the given environment.
pipeds, err := a.pipedStore.ListPipeds(ctx, datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
{
Field: "EnvIds",
Operator: datastore.OperatorContains,
Value: req.EnvironmentId,
},
{
Field: "Disabled",
Operator: datastore.OperatorEqual,
Value: false,
},
},
})
if err != nil {
a.logger.Error("failed to fetch Pipeds linked to the given environment",
zap.String("env-id", req.EnvironmentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to validate the deletion operation")
}
if len(pipeds) > 0 {
pipedNames := make([]string, 0, len(pipeds))
for _, p := range pipeds {
pipedNames = append(pipedNames, p.Name)
}
return nil, status.Errorf(
codes.FailedPrecondition,
"Found Pipeds linked the environment to be deleted. Please remove this environment from all Pipeds (%s) on the Piped settings page",
strings.Join(pipedNames, ","),
)
}
// Delete all applications that belongs to the given env.
apps, _, err := a.applicationStore.ListApplications(ctx, datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
{
Field: "EnvId",
Operator: datastore.OperatorEqual,
Value: req.EnvironmentId,
},
},
})
if err != nil {
a.logger.Error("failed to fetch applications that belongs to the given environment",
zap.String("env-id", req.EnvironmentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to fetch applications that belongs to the given environment")
}
for _, app := range apps {
if app.ProjectId != claims.Role.ProjectId {
continue
}
err := a.applicationStore.DeleteApplication(ctx, app.Id)
if err == nil {
continue
}
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.Internal, "The application is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "Invalid value to delete")
default:
a.logger.Error("failed to delete the application",
zap.String("application-id", app.Id),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to delete the application")
}
}
if err := a.environmentStore.DeleteEnvironment(ctx, req.EnvironmentId); err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.NotFound, "The environment is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "Invalid value to delete")
default:
a.logger.Error("failed to delete the environment",
zap.String("env-id", req.EnvironmentId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to delete the environment")
}
}
return &webservice.DeleteEnvironmentResponse{}, nil
}
func (a *WebAPI) updateEnvironmentEnable(ctx context.Context, envID string, enable bool) error {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return err
}
if err := a.validateEnvBelongsToProject(ctx, envID, claims.Role.ProjectId); err != nil {
return err
}
var updater func(context.Context, string) error
if enable {
updater = a.environmentStore.EnableEnvironment
} else {
updater = a.environmentStore.DisableEnvironment
}
if err := updater(ctx, envID); err != nil {
switch err {
case datastore.ErrNotFound:
return status.Error(codes.NotFound, "The environment is not found")
case datastore.ErrInvalidArgument:
return status.Error(codes.InvalidArgument, "Invalid value for update")
default:
a.logger.Error("failed to update the environment",
zap.String("env-id", envID),
zap.Error(err),
)
return status.Error(codes.Internal, "Failed to update the environment")
}
}
return nil
}
// validateEnvBelongsToProject checks if the given piped belongs to the given project.
// It gives back error unless the env belongs to the project.
func (a *WebAPI) validateEnvBelongsToProject(ctx context.Context, envID, projectID string) error {
eid, err := a.envProjectCache.Get(envID)
if err == nil {
if projectID != eid {
return status.Error(codes.PermissionDenied, "Requested environment doesn't belong to the project you logged in")
}
return nil
}
env, err := getEnvironment(ctx, a.environmentStore, envID, a.logger)
if err != nil {
return err
}
a.envProjectCache.Put(envID, env.ProjectId)
if projectID != env.ProjectId {
return status.Error(codes.PermissionDenied, "Requested environment doesn't belong to the project you logged in")
}
return nil
}
func (a *WebAPI) RegisterPiped(ctx context.Context, req *webservice.RegisterPipedRequest) (*webservice.RegisterPipedResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
key, keyHash, err := model.GeneratePipedKey()
if err != nil {
a.logger.Error("failed to generate piped key", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to generate the piped key")
}
piped := model.Piped{
Id: uuid.New().String(),
Name: req.Name,
Desc: req.Desc,
ProjectId: claims.Role.ProjectId,
EnvIds: req.EnvIds,
}
if err := piped.AddKey(keyHash, claims.Subject, time.Now()); err != nil {
return nil, status.Error(codes.FailedPrecondition, fmt.Sprintf("Failed to create key: %v", err))
}
err = a.pipedStore.AddPiped(ctx, &piped)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "The piped already exists")
}
if err != nil {
a.logger.Error("failed to register piped", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to register piped")
}
return &webservice.RegisterPipedResponse{
Id: piped.Id,
Key: key,
}, nil
}
func (a *WebAPI) UpdatePiped(ctx context.Context, req *webservice.UpdatePipedRequest) (*webservice.UpdatePipedResponse, error) {
updater := func(ctx context.Context, pipedID string) error {
return a.pipedStore.UpdatePiped(ctx, req.PipedId, func(p *model.Piped) error {
p.Name = req.Name
p.Desc = req.Desc
p.EnvIds = req.EnvIds
return nil
})
}
if err := a.updatePiped(ctx, req.PipedId, updater); err != nil {
return nil, err
}
return &webservice.UpdatePipedResponse{}, nil
}
func (a *WebAPI) RecreatePipedKey(ctx context.Context, req *webservice.RecreatePipedKeyRequest) (*webservice.RecreatePipedKeyResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
key, keyHash, err := model.GeneratePipedKey()
if err != nil {
a.logger.Error("failed to generate piped key", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to generate the piped key")
}
updater := func(ctx context.Context, pipedID string) error {
return a.pipedStore.AddKey(ctx, pipedID, keyHash, claims.Subject, time.Now())
}
if err := a.updatePiped(ctx, req.Id, updater); err != nil {
return nil, err
}
return &webservice.RecreatePipedKeyResponse{
Key: key,
}, nil
}
func (a *WebAPI) DeleteOldPipedKeys(ctx context.Context, req *webservice.DeleteOldPipedKeysRequest) (*webservice.DeleteOldPipedKeysResponse, error) {
if _, err := rpcauth.ExtractClaims(ctx); err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
updater := func(ctx context.Context, pipedID string) error {
return a.pipedStore.DeleteOldKeys(ctx, pipedID)
}
if err := a.updatePiped(ctx, req.PipedId, updater); err != nil {
return nil, err
}
return &webservice.DeleteOldPipedKeysResponse{}, nil
}
func (a *WebAPI) EnablePiped(ctx context.Context, req *webservice.EnablePipedRequest) (*webservice.EnablePipedResponse, error) {
if err := a.updatePiped(ctx, req.PipedId, a.pipedStore.EnablePiped); err != nil {
return nil, err
}
return &webservice.EnablePipedResponse{}, nil
}
func (a *WebAPI) DisablePiped(ctx context.Context, req *webservice.DisablePipedRequest) (*webservice.DisablePipedResponse, error) {
if err := a.updatePiped(ctx, req.PipedId, a.pipedStore.DisablePiped); err != nil {
return nil, err
}
return &webservice.DisablePipedResponse{}, nil
}
func (a *WebAPI) updatePiped(ctx context.Context, pipedID string, updater func(context.Context, string) error) error {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return err
}
if err := a.validatePipedBelongsToProject(ctx, pipedID, claims.Role.ProjectId); err != nil {
return err
}
if err := updater(ctx, pipedID); err != nil {
switch err {
case datastore.ErrNotFound:
return status.Error(codes.InvalidArgument, "The piped is not found")
case datastore.ErrInvalidArgument:
return status.Error(codes.InvalidArgument, "Invalid value for update")
default:
a.logger.Error("failed to update the piped",
zap.String("piped-id", pipedID),
zap.Error(err),
)
// TODO: Improve error handling, instead of considering all as Internal error like this
// we should check the error type to decide to pass its message to the web client or just a generic message.
return status.Error(codes.Internal, "Failed to update the piped")
}
}
return nil
}
func (a *WebAPI) ListPipeds(ctx context.Context, req *webservice.ListPipedsRequest) (*webservice.ListPipedsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
},
}
if req.Options != nil {
if req.Options.Enabled != nil {
opts.Filters = append(opts.Filters, datastore.ListFilter{
Field: "Disabled",
Operator: datastore.OperatorEqual,
Value: !req.Options.Enabled.GetValue(),
})
}
}
pipeds, err := a.pipedStore.ListPipeds(ctx, opts)
if err != nil {
a.logger.Error("failed to get pipeds", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get pipeds")
}
// Check piped connection status if necessary.
// The connection status of piped determined by its submitted stat in pipedStatCache.
if req.WithStatus {
for i := range pipeds {
sv, err := a.pipedStatCache.Get(pipeds[i].Id)
if errors.Is(err, cache.ErrNotFound) {
pipeds[i].Status = model.Piped_OFFLINE
continue
}
if err != nil {
pipeds[i].Status = model.Piped_UNKNOWN
a.logger.Error("failed to get piped stat from the cache", zap.Error(err))
continue
}
ps := model.PipedStat{}
if err = model.UnmarshalPipedStat(sv, &ps); err != nil {
pipeds[i].Status = model.Piped_UNKNOWN
a.logger.Error("unable to unmarshal the piped stat", zap.Error(err))
continue
}
if ps.IsStaled(model.PipedStatsRetention) {
pipeds[i].Status = model.Piped_OFFLINE
continue
}
pipeds[i].Status = model.Piped_ONLINE
}
}
// Redact all sensitive data inside piped message before sending to the client.
for i := range pipeds {
pipeds[i].RedactSensitiveData()
}
return &webservice.ListPipedsResponse{
Pipeds: pipeds,
}, nil
}
func (a *WebAPI) GetPiped(ctx context.Context, req *webservice.GetPipedRequest) (*webservice.GetPipedResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
piped, err := getPiped(ctx, a.pipedStore, req.PipedId, a.logger)
if err != nil {
return nil, err
}
if err := a.validatePipedBelongsToProject(ctx, req.PipedId, claims.Role.ProjectId); err != nil {
return nil, err
}
// Redact all sensitive data inside piped message before sending to the client.
piped.RedactSensitiveData()
return &webservice.GetPipedResponse{
Piped: piped,
}, nil
}
func (a *WebAPI) UpdatePipedDesiredVersion(ctx context.Context, req *webservice.UpdatePipedDesiredVersionRequest) (*webservice.UpdatePipedDesiredVersionResponse, error) {
updater := func(ctx context.Context, pipedID string) error {
return a.pipedStore.UpdatePiped(ctx, pipedID, func(p *model.Piped) error {
p.DesiredVersion = req.Version
return nil
})
}
for _, pipedID := range req.PipedIds {
if err := a.updatePiped(ctx, pipedID, updater); err != nil {
return nil, err
}
}
return &webservice.UpdatePipedDesiredVersionResponse{}, nil
}
// validatePipedBelongsToProject checks if the given piped belongs to the given project.
// It gives back error unless the piped belongs to the project.
func (a *WebAPI) validatePipedBelongsToProject(ctx context.Context, pipedID, projectID string) error {
pid, err := a.pipedProjectCache.Get(pipedID)
if err == nil {
if pid != projectID {
return status.Error(codes.PermissionDenied, "Requested piped doesn't belong to the project you logged in")
}
return nil
}
piped, err := getPiped(ctx, a.pipedStore, pipedID, a.logger)
if err != nil {
return err
}
a.pipedProjectCache.Put(pipedID, piped.ProjectId)
if piped.ProjectId != projectID {
return status.Error(codes.PermissionDenied, "Requested piped doesn't belong to the project you logged in")
}
return nil
}
func (a *WebAPI) ListUnregisteredApplications(ctx context.Context, _ *webservice.ListUnregisteredApplicationsRequest) (*webservice.ListUnregisteredApplicationsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
// Collect all apps that belong to the project.
key := makeUnregisteredAppsCacheKey(claims.Role.ProjectId)
c := rediscache.NewHashCache(a.redis, key)
// pipedToApps assumes to be a map["piped-id"][]byte(slice of *model.ApplicationInfo encoded by encoding/gob)
pipedToApps, err := c.GetAll()
if errors.Is(err, cache.ErrNotFound) {
return &webservice.ListUnregisteredApplicationsResponse{}, nil
}
if err != nil {
a.logger.Error("failed to get unregistered apps", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get unregistered apps")
}
// Integrate all apps cached for each Piped.
allApps := make([]*model.ApplicationInfo, 0)
for _, as := range pipedToApps {
b, ok := as.([]byte)
if !ok {
return nil, status.Error(codes.Internal, "Unexpected data cached")
}
dec := gob.NewDecoder(bytes.NewReader(b))
var apps []*model.ApplicationInfo
if err := dec.Decode(&apps); err != nil {
a.logger.Error("failed to decode the unregistered apps", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to decode the unregistered apps")
}
allApps = append(allApps, apps...)
}
if len(allApps) == 0 {
return &webservice.ListUnregisteredApplicationsResponse{}, nil
}
sort.Slice(allApps, func(i, j int) bool {
return allApps[i].Path < allApps[j].Path
})
return &webservice.ListUnregisteredApplicationsResponse{
Applications: allApps,
}, nil
}
// TODO: Validate the specified piped to ensure that it belongs to the specified environment.
func (a *WebAPI) AddApplication(ctx context.Context, req *webservice.AddApplicationRequest) (*webservice.AddApplicationResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
piped, err := getPiped(ctx, a.pipedStore, req.PipedId, a.logger)
if err != nil {
return nil, err
}
if piped.ProjectId != claims.Role.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested piped does not belong to your project")
}
gitpath, err := makeGitPath(
req.GitPath.Repo.Id,
req.GitPath.Path,
req.GitPath.ConfigFilename,
piped,
a.logger,
)
if err != nil {
return nil, err
}
app := model.Application{
Id: uuid.New().String(),
Name: req.Name,
EnvId: req.EnvId,
PipedId: req.PipedId,
ProjectId: claims.Role.ProjectId,
GitPath: gitpath,
Kind: req.Kind,
CloudProvider: req.CloudProvider,
Description: req.Description,
}
err = a.applicationStore.AddApplication(ctx, &app)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "The application already exists")
}
if err != nil {
a.logger.Error("failed to create application", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to create application")
}
return &webservice.AddApplicationResponse{
ApplicationId: app.Id,
}, nil
}
func (a *WebAPI) UpdateApplication(ctx context.Context, req *webservice.UpdateApplicationRequest) (*webservice.UpdateApplicationResponse, error) {
updater := func(app *model.Application) error {
app.Name = req.Name
app.EnvId = req.EnvId
app.PipedId = req.PipedId
app.Kind = req.Kind
app.CloudProvider = req.CloudProvider
return nil
}
if err := a.updateApplication(ctx, req.ApplicationId, req.PipedId, updater); err != nil {
return nil, err
}
return &webservice.UpdateApplicationResponse{}, nil
}
func (a *WebAPI) UpdateApplicationDescription(ctx context.Context, req *webservice.UpdateApplicationDescriptionRequest) (*webservice.UpdateApplicationDescriptionResponse, error) {
updater := func(app *model.Application) error {
app.Description = req.Description
return nil
}
if err := a.updateApplication(ctx, req.ApplicationId, "", updater); err != nil {
return nil, err
}
return &webservice.UpdateApplicationDescriptionResponse{}, nil
}
func (a *WebAPI) updateApplication(ctx context.Context, id, pipedID string, updater func(app *model.Application) error) error {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return err
}
// Ensure that the specified piped is assignable for this application.
if pipedID != "" {
piped, err := getPiped(ctx, a.pipedStore, pipedID, a.logger)
if err != nil {
return err
}
if piped.ProjectId != claims.Role.ProjectId {
return status.Error(codes.InvalidArgument, "Requested piped does not belong to your project")
}
}
err = a.applicationStore.UpdateApplication(ctx, id, updater)
if err != nil {
a.logger.Error("failed to update application", zap.Error(err))
return status.Error(codes.Internal, "Failed to update application")
}
return nil
}
func (a *WebAPI) EnableApplication(ctx context.Context, req *webservice.EnableApplicationRequest) (*webservice.EnableApplicationResponse, error) {
if err := a.updateApplicationEnable(ctx, req.ApplicationId, true); err != nil {
return nil, err
}
return &webservice.EnableApplicationResponse{}, nil
}
func (a *WebAPI) DisableApplication(ctx context.Context, req *webservice.DisableApplicationRequest) (*webservice.DisableApplicationResponse, error) {
if err := a.updateApplicationEnable(ctx, req.ApplicationId, false); err != nil {
return nil, err
}
return &webservice.DisableApplicationResponse{}, nil
}
func (a *WebAPI) DeleteApplication(ctx context.Context, req *webservice.DeleteApplicationRequest) (*webservice.DeleteApplicationResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if err := a.validateAppBelongsToProject(ctx, req.ApplicationId, claims.Role.ProjectId); err != nil {
return nil, err
}
if err := a.applicationStore.DeleteApplication(ctx, req.ApplicationId); err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.NotFound, "The application is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "Invalid value to delete")
default:
a.logger.Error("failed to delete the application",
zap.String("application-id", req.ApplicationId),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to delete the application")
}
}
return &webservice.DeleteApplicationResponse{}, nil
}
func (a *WebAPI) updateApplicationEnable(ctx context.Context, appID string, enable bool) error {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return err
}
if err := a.validateAppBelongsToProject(ctx, appID, claims.Role.ProjectId); err != nil {
return err
}
var updater func(context.Context, string) error
if enable {
updater = a.applicationStore.EnableApplication
} else {
updater = a.applicationStore.DisableApplication
}
if err := updater(ctx, appID); err != nil {
switch err {
case datastore.ErrNotFound:
return status.Error(codes.NotFound, "The application is not found")
case datastore.ErrInvalidArgument:
return status.Error(codes.InvalidArgument, "Invalid value for update")
default:
a.logger.Error("failed to update the application",
zap.String("application-id", appID),
zap.Error(err),
)
return status.Error(codes.Internal, "Failed to update the application")
}
}
return nil
}
func (a *WebAPI) ListApplications(ctx context.Context, req *webservice.ListApplicationsRequest) (*webservice.ListApplicationsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
orders := []datastore.Order{
{
Field: "UpdatedAt",
Direction: datastore.Desc,
},
{
Field: "Id",
Direction: datastore.Asc,
},
}
filters := []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
}
if o := req.Options; o != nil {
if o.Enabled != nil {
filters = append(filters, datastore.ListFilter{
Field: "Disabled",
Operator: datastore.OperatorEqual,
Value: !o.Enabled.GetValue(),
})
}
// Allowing multiple so that it can do In Query later.
// Currently only the first value is used.
if len(o.Kinds) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "Kind",
Operator: datastore.OperatorEqual,
Value: o.Kinds[0],
})
}
if len(o.SyncStatuses) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "SyncState.Status",
Operator: datastore.OperatorEqual,
Value: o.SyncStatuses[0],
})
}
if len(o.EnvIds) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "EnvId",
Operator: datastore.OperatorEqual,
Value: o.EnvIds[0],
})
}
if o.Name != "" {
filters = append(filters, datastore.ListFilter{
Field: "Name",
Operator: datastore.OperatorEqual,
Value: o.Name,
})
}
}
apps, _, err := a.applicationStore.ListApplications(ctx, datastore.ListOptions{
Filters: filters,
Orders: orders,
})
if err != nil {
a.logger.Error("failed to get applications", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get applications")
}
if len(req.Options.Labels) == 0 {
return &webservice.ListApplicationsResponse{
Applications: apps,
}, nil
}
// NOTE: Filtering by labels is done by the application-side because we need to create composite indexes for every combination in the filter.
filtered := make([]*model.Application, 0, len(apps))
for _, a := range apps {
if a.ContainLabels(req.Options.Labels) {
filtered = append(filtered, a)
}
}
return &webservice.ListApplicationsResponse{
Applications: filtered,
}, nil
}
func (a *WebAPI) SyncApplication(ctx context.Context, req *webservice.SyncApplicationRequest) (*webservice.SyncApplicationResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
app, err := getApplication(ctx, a.applicationStore, req.ApplicationId, a.logger)
if err != nil {
return nil, err
}
if claims.Role.ProjectId != app.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested application does not belong to your project")
}
cmd := model.Command{
Id: uuid.New().String(),
PipedId: app.PipedId,
ApplicationId: app.Id,
ProjectId: app.ProjectId,
Type: model.Command_SYNC_APPLICATION,
Commander: claims.Subject,
SyncApplication: &model.Command_SyncApplication{
ApplicationId: app.Id,
SyncStrategy: req.SyncStrategy,
},
}
if err := addCommand(ctx, a.commandStore, &cmd, a.logger); err != nil {
return nil, err
}
return &webservice.SyncApplicationResponse{
CommandId: cmd.Id,
}, nil
}
func (a *WebAPI) GetApplication(ctx context.Context, req *webservice.GetApplicationRequest) (*webservice.GetApplicationResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
app, err := getApplication(ctx, a.applicationStore, req.ApplicationId, a.logger)
if err != nil {
return nil, err
}
if app.ProjectId != claims.Role.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested application does not belong to your project")
}
return &webservice.GetApplicationResponse{
Application: app,
}, nil
}
func (a *WebAPI) GenerateApplicationSealedSecret(ctx context.Context, req *webservice.GenerateApplicationSealedSecretRequest) (*webservice.GenerateApplicationSealedSecretResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
piped, err := getPiped(ctx, a.pipedStore, req.PipedId, a.logger)
if err != nil {
return nil, err
}
if err := a.validatePipedBelongsToProject(ctx, req.PipedId, claims.Role.ProjectId); err != nil {
return nil, err
}
se := model.GetSecretEncryptionInPiped(piped)
pubkey, err := getEncriptionKey(se)
if err != nil {
return nil, err
}
ciphertext, err := encrypt(req.Data, pubkey, req.Base64Encoding, a.logger)
if err != nil {
return nil, err
}
return &webservice.GenerateApplicationSealedSecretResponse{
Data: ciphertext,
}, nil
}
// validateAppBelongsToProject checks if the given application belongs to the given project.
// It gives back error unless the application belongs to the project.
func (a *WebAPI) validateAppBelongsToProject(ctx context.Context, appID, projectID string) error {
pid, err := a.appProjectCache.Get(appID)
if err == nil {
if pid != projectID {
return status.Error(codes.PermissionDenied, "Requested application doesn't belong to the project you logged in")
}
return nil
}
app, err := getApplication(ctx, a.applicationStore, appID, a.logger)
if err != nil {
return err
}
a.appProjectCache.Put(appID, app.ProjectId)
if app.ProjectId != projectID {
return status.Error(codes.PermissionDenied, "Requested application doesn't belong to the project you logged in")
}
return nil
}
func (a *WebAPI) ListDeployments(ctx context.Context, req *webservice.ListDeploymentsRequest) (*webservice.ListDeploymentsResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
orders := []datastore.Order{
{
Field: "UpdatedAt",
Direction: datastore.Desc,
},
{
Field: "Id",
Direction: datastore.Asc,
},
}
filters := []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
{
Field: "UpdatedAt",
Operator: datastore.OperatorGreaterThanOrEqual,
Value: req.PageMinUpdatedAt,
},
}
if o := req.Options; o != nil {
// Allowing multiple so that it can do In Query later.
// Currently only the first value is used.
if len(o.Statuses) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "Status",
Operator: datastore.OperatorEqual,
Value: o.Statuses[0],
})
}
if len(o.Kinds) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "Kind",
Operator: datastore.OperatorEqual,
Value: o.Kinds[0],
})
}
if len(o.ApplicationIds) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "ApplicationId",
Operator: datastore.OperatorEqual,
Value: o.ApplicationIds[0],
})
}
if len(o.EnvIds) > 0 {
filters = append(filters, datastore.ListFilter{
Field: "EnvId",
Operator: datastore.OperatorEqual,
Value: o.EnvIds[0],
})
}
if o.ApplicationName != "" {
filters = append(filters, datastore.ListFilter{
Field: "ApplicationName",
Operator: datastore.OperatorEqual,
Value: o.ApplicationName,
})
}
}
pageSize := int(req.PageSize)
options := datastore.ListOptions{
Filters: filters,
Orders: orders,
Limit: pageSize,
Cursor: req.Cursor,
}
deployments, cursor, err := a.deploymentStore.ListDeployments(ctx, options)
if err != nil {
a.logger.Error("failed to get deployments", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get deployments")
}
labels := req.Options.Labels
if len(labels) == 0 || len(deployments) == 0 {
return &webservice.ListDeploymentsResponse{
Deployments: deployments,
Cursor: cursor,
}, nil
}
// Start filtering them by labels.
//
// NOTE: Filtering by labels is done by the application-side because we need to create composite indexes for every combination in the filter.
// We don't want to depend on any other search engine, that's why it filters here.
filtered := make([]*model.Deployment, 0, len(deployments))
for _, d := range deployments {
if d.ContainLabels(labels) {
filtered = append(filtered, d)
}
}
// Stop running additional queries for more data, and return filtered deployments immediately with
// current cursor if the size before filtering is already less than the page size.
if len(deployments) < pageSize {
return &webservice.ListDeploymentsResponse{
Deployments: filtered,
Cursor: cursor,
}, nil
}
// Repeat the query until the number of filtered deployments reaches the page size,
// or until it finishes scanning to page_min_updated_at.
for len(filtered) < pageSize {
options.Cursor = cursor
deployments, cursor, err = a.deploymentStore.ListDeployments(ctx, options)
if err != nil {
a.logger.Error("failed to get deployments", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get deployments")
}
if len(deployments) == 0 {
break
}
for _, d := range deployments {
if d.ContainLabels(labels) {
filtered = append(filtered, d)
}
}
// We've already specified UpdatedAt >= req.PageMinUpdatedAt, so we need to check just equality.
if deployments[len(deployments)-1].UpdatedAt == req.PageMinUpdatedAt {
break
}
}
// TODO: Think about possibility that the response of ListDeployments exceeds the page size
return &webservice.ListDeploymentsResponse{
Deployments: filtered,
Cursor: cursor,
}, nil
}
func (a *WebAPI) GetDeployment(ctx context.Context, req *webservice.GetDeploymentRequest) (*webservice.GetDeploymentResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
deployment, err := getDeployment(ctx, a.deploymentStore, req.DeploymentId, a.logger)
if err != nil {
return nil, err
}
if claims.Role.ProjectId != deployment.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested deployment does not belong to your project")
}
return &webservice.GetDeploymentResponse{
Deployment: deployment,
}, nil
}
// validateDeploymentBelongsToProject checks if the given deployment belongs to the given project.
// It gives back error unless the deployment belongs to the project.
func (a *WebAPI) validateDeploymentBelongsToProject(ctx context.Context, deploymentID, projectID string) error {
pid, err := a.deploymentProjectCache.Get(deploymentID)
if err == nil {
if pid != projectID {
return status.Error(codes.PermissionDenied, "Requested deployment doesn't belong to the project you logged in")
}
return nil
}
deployment, err := getDeployment(ctx, a.deploymentStore, deploymentID, a.logger)
if err != nil {
return err
}
a.deploymentProjectCache.Put(deploymentID, deployment.ProjectId)
if deployment.ProjectId != projectID {
return status.Error(codes.PermissionDenied, "Requested deployment doesn't belong to the project you logged in")
}
return nil
}
func (a *WebAPI) GetStageLog(ctx context.Context, req *webservice.GetStageLogRequest) (*webservice.GetStageLogResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if err := a.validateDeploymentBelongsToProject(ctx, req.DeploymentId, claims.Role.ProjectId); err != nil {
return nil, err
}
blocks, completed, err := a.stageLogStore.FetchLogs(ctx, req.DeploymentId, req.StageId, req.RetriedCount, req.OffsetIndex)
if errors.Is(err, stagelogstore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "The stage log not found")
}
if err != nil {
a.logger.Error("failed to get stage logs", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get stage logs")
}
return &webservice.GetStageLogResponse{
Blocks: blocks,
Completed: completed,
}, nil
}
func (a *WebAPI) CancelDeployment(ctx context.Context, req *webservice.CancelDeploymentRequest) (*webservice.CancelDeploymentResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
deployment, err := getDeployment(ctx, a.deploymentStore, req.DeploymentId, a.logger)
if err != nil {
return nil, err
}
if claims.Role.ProjectId != deployment.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested deployment does not belong to your project")
}
if model.IsCompletedDeployment(deployment.Status) {
return nil, status.Errorf(codes.FailedPrecondition, "could not cancel the deployment because it was already completed")
}
cmd := model.Command{
Id: uuid.New().String(),
PipedId: deployment.PipedId,
ApplicationId: deployment.ApplicationId,
ProjectId: deployment.ProjectId,
DeploymentId: req.DeploymentId,
Type: model.Command_CANCEL_DEPLOYMENT,
Commander: claims.Subject,
CancelDeployment: &model.Command_CancelDeployment{
DeploymentId: req.DeploymentId,
ForceRollback: req.ForceRollback,
ForceNoRollback: req.ForceNoRollback,
},
}
if err := addCommand(ctx, a.commandStore, &cmd, a.logger); err != nil {
return nil, err
}
return &webservice.CancelDeploymentResponse{
CommandId: cmd.Id,
}, nil
}
func (a *WebAPI) ApproveStage(ctx context.Context, req *webservice.ApproveStageRequest) (*webservice.ApproveStageResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
deployment, err := getDeployment(ctx, a.deploymentStore, req.DeploymentId, a.logger)
if err != nil {
return nil, err
}
if err := validateApprover(deployment.Stages, claims.Subject, req.StageId); err != nil {
return nil, err
}
if err := a.validateDeploymentBelongsToProject(ctx, req.DeploymentId, claims.Role.ProjectId); err != nil {
return nil, err
}
stage, ok := deployment.StageStatusMap()[req.StageId]
if !ok {
return nil, status.Error(codes.FailedPrecondition, "The stage was not found in the deployment")
}
if model.IsCompletedStage(stage) {
return nil, status.Errorf(codes.FailedPrecondition, "Could not approve the stage because it was already completed")
}
commandID := uuid.New().String()
cmd := model.Command{
Id: commandID,
PipedId: deployment.PipedId,
ApplicationId: deployment.ApplicationId,
ProjectId: deployment.ProjectId,
DeploymentId: req.DeploymentId,
StageId: req.StageId,
Type: model.Command_APPROVE_STAGE,
Commander: claims.Subject,
ApproveStage: &model.Command_ApproveStage{
DeploymentId: req.DeploymentId,
StageId: req.StageId,
},
}
if err := addCommand(ctx, a.commandStore, &cmd, a.logger); err != nil {
return nil, err
}
return &webservice.ApproveStageResponse{
CommandId: commandID,
}, nil
}
// No error means that the given commander is valid.
func validateApprover(stages []*model.PipelineStage, commander, stageID string) error {
var approvers []string
for _, s := range stages {
if s.Id != stageID {
continue
}
if as := s.Metadata["Approvers"]; as != "" {
approvers = strings.Split(as, ",")
}
break
}
if len(approvers) == 0 {
// Anyone can approve the deployment pipeline
return nil
}
for _, ap := range approvers {
if ap == commander {
return nil
}
}
return status.Error(codes.PermissionDenied, fmt.Sprintf("You can't approve this deployment because you (%s) are not in the approver list: %v", commander, approvers))
}
func (a *WebAPI) GetApplicationLiveState(ctx context.Context, req *webservice.GetApplicationLiveStateRequest) (*webservice.GetApplicationLiveStateResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if err := a.validateAppBelongsToProject(ctx, req.ApplicationId, claims.Role.ProjectId); err != nil {
return nil, err
}
snapshot, err := a.applicationLiveStateStore.GetStateSnapshot(ctx, req.ApplicationId)
if errors.Is(err, filestore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "Application live state not found")
}
if err != nil {
a.logger.Error("failed to get application live state", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get application live state")
}
return &webservice.GetApplicationLiveStateResponse{
Snapshot: snapshot,
}, nil
}
// GetProject gets the specified porject without sensitive data.
func (a *WebAPI) GetProject(ctx context.Context, req *webservice.GetProjectRequest) (*webservice.GetProjectResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
project, err := a.getProject(ctx, claims.Role.ProjectId)
if err != nil {
return nil, err
}
// Redact all sensitive data inside project message before sending to the client.
project.RedactSensitiveData()
return &webservice.GetProjectResponse{
Project: project,
}, nil
}
func (a *WebAPI) getProject(ctx context.Context, projectID string) (*model.Project, error) {
if p, ok := a.projectsInConfig[projectID]; ok {
return &model.Project{
Id: p.Id,
Desc: p.Desc,
StaticAdmin: &model.ProjectStaticUser{
Username: p.StaticAdmin.Username,
PasswordHash: p.StaticAdmin.PasswordHash,
},
}, nil
}
project, err := a.projectStore.GetProject(ctx, projectID)
if errors.Is(err, datastore.ErrNotFound) {
return nil, status.Error(codes.NotFound, "The project is not found")
}
if err != nil {
a.logger.Error("failed to get project", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to get project")
}
return project, nil
}
// UpdateProjectStaticAdmin updates the static admin user settings.
func (a *WebAPI) UpdateProjectStaticAdmin(ctx context.Context, req *webservice.UpdateProjectStaticAdminRequest) (*webservice.UpdateProjectStaticAdminResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if _, ok := a.projectsInConfig[claims.Role.ProjectId]; ok {
return nil, status.Error(codes.FailedPrecondition, "Failed to update a debug project specified in the control-plane configuration")
}
if err := a.projectStore.UpdateProjectStaticAdmin(ctx, claims.Role.ProjectId, req.Username, req.Password); err != nil {
a.logger.Error("failed to update static admin", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to update static admin")
}
return &webservice.UpdateProjectStaticAdminResponse{}, nil
}
// EnableStaticAdmin enables static admin login.
func (a *WebAPI) EnableStaticAdmin(ctx context.Context, req *webservice.EnableStaticAdminRequest) (*webservice.EnableStaticAdminResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if _, ok := a.projectsInConfig[claims.Role.ProjectId]; ok {
return nil, status.Error(codes.FailedPrecondition, "Failed to update a debug project specified in the control-plane configuration")
}
if err := a.projectStore.EnableStaticAdmin(ctx, claims.Role.ProjectId); err != nil {
a.logger.Error("failed to enable static admin login", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to enable static admin login")
}
return &webservice.EnableStaticAdminResponse{}, nil
}
// DisableStaticAdmin disables static admin login.
func (a *WebAPI) DisableStaticAdmin(ctx context.Context, req *webservice.DisableStaticAdminRequest) (*webservice.DisableStaticAdminResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if _, ok := a.projectsInConfig[claims.Role.ProjectId]; ok {
return nil, status.Error(codes.FailedPrecondition, "Failed to update a debug project specified in the control-plane configuration")
}
if err := a.projectStore.DisableStaticAdmin(ctx, claims.Role.ProjectId); err != nil {
a.logger.Error("failed to disenable static admin login", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to disenable static admin login")
}
return &webservice.DisableStaticAdminResponse{}, nil
}
// UpdateProjectSSOConfig updates the sso settings.
func (a *WebAPI) UpdateProjectSSOConfig(ctx context.Context, req *webservice.UpdateProjectSSOConfigRequest) (*webservice.UpdateProjectSSOConfigResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if _, ok := a.projectsInConfig[claims.Role.ProjectId]; ok {
return nil, status.Error(codes.FailedPrecondition, "Failed to update a debug project specified in the control-plane configuration")
}
if err := req.Sso.Encrypt(a.encrypter); err != nil {
a.logger.Error("failed to encrypt sensitive data in sso configurations", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to encrypt sensitive data in sso configurations")
}
if err := a.projectStore.UpdateProjectSSOConfig(ctx, claims.Role.ProjectId, req.Sso); err != nil {
a.logger.Error("failed to update project single sign on settings", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to update project single sign on settings")
}
return &webservice.UpdateProjectSSOConfigResponse{}, nil
}
// UpdateProjectRBACConfig updates the sso settings.
func (a *WebAPI) UpdateProjectRBACConfig(ctx context.Context, req *webservice.UpdateProjectRBACConfigRequest) (*webservice.UpdateProjectRBACConfigResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if _, ok := a.projectsInConfig[claims.Role.ProjectId]; ok {
return nil, status.Error(codes.FailedPrecondition, "Failed to update a debug project specified in the control-plane configuration")
}
if err := a.projectStore.UpdateProjectRBACConfig(ctx, claims.Role.ProjectId, req.Rbac); err != nil {
a.logger.Error("failed to update project single sign on settings", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to update project single sign on settings")
}
return &webservice.UpdateProjectRBACConfigResponse{}, nil
}
// GetMe gets information about the current user.
func (a *WebAPI) GetMe(ctx context.Context, req *webservice.GetMeRequest) (*webservice.GetMeResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
return &webservice.GetMeResponse{
Subject: claims.Subject,
AvatarUrl: claims.AvatarURL,
ProjectId: claims.Role.ProjectId,
ProjectRole: claims.Role.ProjectRole,
}, nil
}
func (a *WebAPI) GetCommand(ctx context.Context, req *webservice.GetCommandRequest) (*webservice.GetCommandResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
cmd, err := getCommand(ctx, a.commandStore, req.CommandId, a.logger)
if err != nil {
return nil, err
}
if claims.Role.ProjectId != cmd.ProjectId {
return nil, status.Error(codes.InvalidArgument, "Requested command does not belong to your project")
}
return &webservice.GetCommandResponse{
Command: cmd,
}, nil
}
func (a *WebAPI) GenerateAPIKey(ctx context.Context, req *webservice.GenerateAPIKeyRequest) (*webservice.GenerateAPIKeyResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
id := uuid.New().String()
key, hash, err := model.GenerateAPIKey(id)
if err != nil {
a.logger.Error("failed to generate API key", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to generate API key")
}
apiKey := model.APIKey{
Id: id,
Name: req.Name,
KeyHash: hash,
ProjectId: claims.Role.ProjectId,
Role: req.Role,
Creator: claims.Subject,
}
err = a.apiKeyStore.AddAPIKey(ctx, &apiKey)
if errors.Is(err, datastore.ErrAlreadyExists) {
return nil, status.Error(codes.AlreadyExists, "The API key already exists")
}
if err != nil {
a.logger.Error("failed to create API key", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to create API key")
}
return &webservice.GenerateAPIKeyResponse{
Key: key,
}, nil
}
func (a *WebAPI) DisableAPIKey(ctx context.Context, req *webservice.DisableAPIKeyRequest) (*webservice.DisableAPIKeyResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
if err := a.apiKeyStore.DisableAPIKey(ctx, req.Id, claims.Role.ProjectId); err != nil {
switch err {
case datastore.ErrNotFound:
return nil, status.Error(codes.InvalidArgument, "The API key is not found")
case datastore.ErrInvalidArgument:
return nil, status.Error(codes.InvalidArgument, "Invalid value for update")
default:
a.logger.Error("failed to disable the API key",
zap.String("apikey-id", req.Id),
zap.Error(err),
)
return nil, status.Error(codes.Internal, "Failed to disable the API key")
}
}
return &webservice.DisableAPIKeyResponse{}, nil
}
func (a *WebAPI) ListAPIKeys(ctx context.Context, req *webservice.ListAPIKeysRequest) (*webservice.ListAPIKeysResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
opts := datastore.ListOptions{
Filters: []datastore.ListFilter{
{
Field: "ProjectId",
Operator: datastore.OperatorEqual,
Value: claims.Role.ProjectId,
},
},
}
if req.Options != nil {
if req.Options.Enabled != nil {
opts.Filters = append(opts.Filters, datastore.ListFilter{
Field: "Disabled",
Operator: datastore.OperatorEqual,
Value: !req.Options.Enabled.GetValue(),
})
}
}
apiKeys, err := a.apiKeyStore.ListAPIKeys(ctx, opts)
if err != nil {
a.logger.Error("failed to list API keys", zap.Error(err))
return nil, status.Error(codes.Internal, "Failed to list API keys")
}
// Redact all sensitive data inside API key before sending to the client.
for i := range apiKeys {
apiKeys[i].RedactSensitiveData()
}
return &webservice.ListAPIKeysResponse{
Keys: apiKeys,
}, nil
}
// GetInsightData returns the accumulated insight data.
func (a *WebAPI) GetInsightData(ctx context.Context, req *webservice.GetInsightDataRequest) (*webservice.GetInsightDataResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
count := int(req.DataPointCount)
from := time.Unix(req.RangeFrom, 0)
chunks, err := insightstore.LoadChunksFromCache(a.insightCache, claims.Role.ProjectId, req.ApplicationId, req.MetricsKind, req.Step, from, count)
if err != nil {
a.logger.Error("failed to load chunks from cache", zap.Error(err))
chunks, err = a.insightStore.LoadChunks(ctx, claims.Role.ProjectId, req.ApplicationId, req.MetricsKind, req.Step, from, count)
if err != nil {
a.logger.Error("failed to load chunks from insightstore", zap.Error(err))
return nil, err
}
if err := insightstore.PutChunksToCache(a.insightCache, chunks); err != nil {
a.logger.Error("failed to put chunks to cache", zap.Error(err))
}
}
idp, err := chunks.ExtractDataPoints(req.Step, from, count)
if err != nil {
a.logger.Error("failed to extract data points from chunks", zap.Error(err))
}
var updateAt int64
for _, c := range chunks {
accumulatedTo := c.GetAccumulatedTo()
if accumulatedTo > updateAt {
updateAt = accumulatedTo
}
}
return &webservice.GetInsightDataResponse{
UpdatedAt: updateAt,
DataPoints: idp,
Type: model.InsightResultType_MATRIX,
Matrix: []*model.InsightSampleStream{
{
DataPoints: idp,
},
},
}, nil
}
func (a *WebAPI) GetInsightApplicationCount(ctx context.Context, req *webservice.GetInsightApplicationCountRequest) (*webservice.GetInsightApplicationCountResponse, error) {
claims, err := rpcauth.ExtractClaims(ctx)
if err != nil {
a.logger.Error("failed to authenticate the current user", zap.Error(err))
return nil, err
}
// TODO: Cache application counts in the cache service.
c, err := a.insightStore.LoadApplicationCounts(ctx, claims.Role.ProjectId)
if err != nil {
if err == filestore.ErrNotFound {
return nil, status.Error(codes.NotFound, "Not found")
}
a.logger.Error("failed to load application counts", zap.Error(err))
return nil, status.Error(codes.Internal, "failed to load application counts")
}
counts := make([]*model.InsightApplicationCount, 0, len(c.Counts))
for i := range c.Counts {
counts = append(counts, &c.Counts[i])
}
return &webservice.GetInsightApplicationCountResponse{
Counts: counts,
UpdatedAt: c.UpdatedAt,
}, nil
}
| 1 | 23,380 | `ctx` is unused in ListDeploymentChains | pipe-cd-pipe | go |
@@ -154,7 +154,7 @@ func (e *Executor) reportRequiringApproval(ctx context.Context) {
func (e *Executor) getMentionedAccounts(ctx context.Context, event model.NotificationEventType) ([]string, error) {
ds, err := e.TargetDSP.GetReadOnly(ctx, e.LogPersister)
if err != nil {
- return nil, fmt.Errorf("failed to prepare running deploy source data: %w", err)
+ return nil, fmt.Errorf("failed to prepare running deploy source data: (%w)", err)
}
if ds.GenericDeploymentConfig.DeploymentNotification == nil { | 1 | // Copyright 2020 The PipeCD Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package waitapproval
import (
"context"
"fmt"
"time"
"go.uber.org/zap"
"github.com/pipe-cd/pipe/pkg/app/piped/executor"
"github.com/pipe-cd/pipe/pkg/model"
)
const (
approvedByKey = "ApprovedBy"
)
type Executor struct {
executor.Input
}
type registerer interface {
Register(stage model.Stage, f executor.Factory) error
}
// Register registers this executor factory into a given registerer.
func Register(r registerer) {
f := func(in executor.Input) executor.Executor {
return &Executor{
Input: in,
}
}
r.Register(model.StageWaitApproval, f)
}
// Execute starts waiting until an approval from one of the specified users.
func (e *Executor) Execute(sig executor.StopSignal) model.StageStatus {
var (
originalStatus = e.Stage.Status
ctx = sig.Context()
ticker = time.NewTicker(5 * time.Second)
)
defer ticker.Stop()
timeout := e.StageConfig.WaitApprovalStageOptions.Timeout.Duration()
timer := time.NewTimer(timeout)
e.reportRequiringApproval(ctx)
e.LogPersister.Info("Waiting for an approval...")
for {
select {
case <-ticker.C:
if commander, ok := e.checkApproval(ctx); ok {
e.reportApproved(ctx, commander)
e.LogPersister.Infof("Got an approval from %s", commander)
return model.StageStatus_STAGE_SUCCESS
}
case s := <-sig.Ch():
switch s {
case executor.StopSignalCancel:
return model.StageStatus_STAGE_CANCELLED
case executor.StopSignalTerminate:
return originalStatus
default:
return model.StageStatus_STAGE_FAILURE
}
case <-timer.C:
e.LogPersister.Errorf("Timed out %v", timeout)
return model.StageStatus_STAGE_FAILURE
}
}
}
func (e *Executor) checkApproval(ctx context.Context) (string, bool) {
var approveCmd *model.ReportableCommand
commands := e.CommandLister.ListCommands()
for i, cmd := range commands {
if cmd.GetApproveStage() != nil {
approveCmd = &commands[i]
break
}
}
if approveCmd == nil {
return "", false
}
metadata := map[string]string{
approvedByKey: approveCmd.Commander,
}
if ori, ok := e.MetadataStore.GetStageMetadata(e.Stage.Id); ok {
for k, v := range ori {
metadata[k] = v
}
}
if err := e.MetadataStore.SetStageMetadata(ctx, e.Stage.Id, metadata); err != nil {
e.LogPersister.Errorf("Unabled to save approver information to deployment, %v", err)
return "", false
}
if err := approveCmd.Report(ctx, model.CommandStatus_COMMAND_SUCCEEDED, nil, nil); err != nil {
e.Logger.Error("failed to report handled command", zap.Error(err))
}
return approveCmd.Commander, true
}
func (e *Executor) reportApproved(ctx context.Context, approver string) {
accounts, err := e.getMentionedAccounts(ctx, model.NotificationEventType_EVENT_DEPLOYMENT_APPROVED)
if err != nil {
e.Logger.Error("failed to get the list of accounts", zap.Error(err))
}
e.Notifier.Notify(model.NotificationEvent{
Type: model.NotificationEventType_EVENT_DEPLOYMENT_APPROVED,
Metadata: &model.NotificationEventDeploymentApproved{
Deployment: e.Deployment,
EnvName: e.EnvName,
Approver: approver,
MentionedAccounts: accounts,
},
})
}
func (e *Executor) reportRequiringApproval(ctx context.Context) {
accounts, err := e.getMentionedAccounts(ctx, model.NotificationEventType_EVENT_DEPLOYMENT_WAIT_APPROVAL)
if err != nil {
e.Logger.Error("failed to get the list of accounts", zap.Error(err))
}
e.Notifier.Notify(model.NotificationEvent{
Type: model.NotificationEventType_EVENT_DEPLOYMENT_WAIT_APPROVAL,
Metadata: &model.NotificationEventDeploymentWaitApproval{
Deployment: e.Deployment,
EnvName: e.EnvName,
MentionedAccounts: accounts,
},
})
}
func (e *Executor) getMentionedAccounts(ctx context.Context, event model.NotificationEventType) ([]string, error) {
ds, err := e.TargetDSP.GetReadOnly(ctx, e.LogPersister)
if err != nil {
return nil, fmt.Errorf("failed to prepare running deploy source data: %w", err)
}
if ds.GenericDeploymentConfig.DeploymentNotification == nil {
// There is no event to mention users.
return nil, nil
}
for _, v := range ds.GenericDeploymentConfig.DeploymentNotification.Mentions {
if e := "EVENT_" + v.Event; e == event.String() {
return v.Slack, nil
}
}
return nil, nil
}
| 1 | 20,737 | I'd say the format like `"xxx: %w"` is more convention when wrapping an error basically. You refered to anything like this? | pipe-cd-pipe | go |
@@ -65,7 +65,7 @@ const (
endpoint = "https://127.0.0.1:2379"
testTimeout = time.Second * 10
manageTickerTime = time.Second * 15
- learnerMaxStallTime = time.Minute * 1
+ learnerMaxStallTime = time.Minute * 5
// defaultDialTimeout is intentionally short so that connections timeout within the testTimeout defined above
defaultDialTimeout = 2 * time.Second | 1 | package etcd
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/pkg/errors"
certutil "github.com/rancher/dynamiclistener/cert"
"github.com/rancher/k3s/pkg/clientaccess"
"github.com/rancher/k3s/pkg/daemons/config"
"github.com/rancher/k3s/pkg/daemons/executor"
"github.com/rancher/k3s/pkg/version"
"github.com/robfig/cron/v3"
"github.com/sirupsen/logrus"
etcd "go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/clientv3/snapshot"
"go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
"go.etcd.io/etcd/etcdserver/etcdserverpb"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilnet "k8s.io/apimachinery/pkg/util/net"
)
type ETCD struct {
client *etcd.Client
config *config.Control
name string
runtime *config.ControlRuntime
address string
cron *cron.Cron
}
type learnerProgress struct {
ID uint64 `json:"id,omitempty"`
Name string `json:"name,omitempty"`
RaftAppliedIndex uint64 `json:"raftAppliedIndex,omitempty"`
LastProgress metav1.Time `json:"lastProgress,omitempty"`
}
// NewETCD creates a new value of type
// ETCD with an initialized cron value.
func NewETCD() *ETCD {
return &ETCD{
cron: cron.New(),
}
}
var learnerProgressKey = version.Program + "/etcd/learnerProgress"
const (
snapshotPrefix = "etcd-snapshot-"
endpoint = "https://127.0.0.1:2379"
testTimeout = time.Second * 10
manageTickerTime = time.Second * 15
learnerMaxStallTime = time.Minute * 1
// defaultDialTimeout is intentionally short so that connections timeout within the testTimeout defined above
defaultDialTimeout = 2 * time.Second
// other defaults from k8s.io/apiserver/pkg/storage/storagebackend/factory/etcd3.go
defaultKeepAliveTime = 30 * time.Second
defaultKeepAliveTimeout = 10 * time.Second
maxBackupRetention = 5
)
// Members contains a slice that holds all
// members of the cluster.
type Members struct {
Members []*etcdserverpb.Member `json:"members"`
}
// EndpointName returns the name of the endpoint.
func (e *ETCD) EndpointName() string {
return "etcd"
}
// Test ensures that the local node is a voting member of the target cluster.
// If it is still a learner or not a part of the cluster, an error is raised.
func (e *ETCD) Test(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, testTimeout)
defer cancel()
status, err := e.client.Status(ctx, endpoint)
if err != nil {
return err
}
if status.IsLearner {
return errors.New("this server has not yet been promoted from learner to voting member")
}
members, err := e.client.MemberList(ctx)
if err != nil {
return err
}
var memberNameUrls []string
for _, member := range members.Members {
for _, peerURL := range member.PeerURLs {
if peerURL == e.peerURL() && e.name == member.Name {
return nil
}
}
if len(member.PeerURLs) > 0 {
memberNameUrls = append(memberNameUrls, member.Name+"="+member.PeerURLs[0])
}
}
return errors.Errorf("this server is a not a member of the etcd cluster. Found %v, expect: %s=%s", memberNameUrls, e.name, e.address)
}
// etcdDBDir returns the path to dataDir/db/etcd
func etcdDBDir(config *config.Control) string {
return filepath.Join(config.DataDir, "db", "etcd")
}
// walDir returns the path to etcdDBDir/member/wal
func walDir(config *config.Control) string {
return filepath.Join(etcdDBDir(config), "member", "wal")
}
// nameFile returns the path to etcdDBDir/name
func nameFile(config *config.Control) string {
return filepath.Join(etcdDBDir(config), "name")
}
// ResetFile returns the path to etcdDBDir/reset-flag
func ResetFile(config *config.Control) string {
return filepath.Join(config.DataDir, "db", "reset-flag")
}
// IsInitialized checks to see if a WAL directory exists. If so, we assume that etcd
// has already been brought up at least once.
func (e *ETCD) IsInitialized(ctx context.Context, config *config.Control) (bool, error) {
dir := walDir(config)
if s, err := os.Stat(dir); err == nil && s.IsDir() {
return true, nil
} else if os.IsNotExist(err) {
return false, nil
} else {
return false, errors.Wrapf(err, "invalid state for wal directory %s", dir)
}
}
// Reset resets an etcd node
func (e *ETCD) Reset(ctx context.Context) error {
// Wait for etcd to come up as a new single-node cluster, then exit
go func() {
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for range t.C {
if err := e.Test(ctx); err == nil {
members, err := e.client.MemberList(ctx)
if err != nil {
continue
}
if len(members.Members) == 1 && members.Members[0].Name == e.name {
logrus.Infof("Etcd is running, restart without --cluster-reset flag now. Backup and delete ${datadir}/server/db on each peer etcd server and rejoin the nodes")
os.Exit(0)
}
}
}
}()
// If asked to restore from a snapshot, do so
if e.config.ClusterResetRestorePath != "" {
info, err := os.Stat(e.config.ClusterResetRestorePath)
if os.IsNotExist(err) {
return fmt.Errorf("etcd: snapshot path does not exist: %s", e.config.ClusterResetRestorePath)
}
if info.IsDir() {
return fmt.Errorf("etcd: snapshot path must be a file, not a directory: %s", e.config.ClusterResetRestorePath)
}
if err := e.Restore(ctx); err != nil {
return err
}
}
if err := e.setName(true); err != nil {
return err
}
// touch a file to avoid multiple resets
if err := ioutil.WriteFile(ResetFile(e.config), []byte{}, 0600); err != nil {
return err
}
return e.newCluster(ctx, true)
}
// Start starts the datastore
func (e *ETCD) Start(ctx context.Context, clientAccessInfo *clientaccess.Info) error {
existingCluster, err := e.IsInitialized(ctx, e.config)
if err != nil {
return errors.Wrapf(err, "configuration validation failed")
}
e.config.Runtime.ClusterControllerStart = func(ctx context.Context) error {
Register(ctx, e, e.config.Runtime.Core.Core().V1().Node())
return nil
}
if !e.config.EtcdDisableSnapshots {
e.setSnapshotFunction(ctx)
e.cron.Start()
}
go e.manageLearners(ctx)
if existingCluster {
//check etcd dir permission
etcdDir := etcdDBDir(e.config)
info, err := os.Stat(etcdDir)
if err != nil {
return err
}
if info.Mode() != 0700 {
if err := os.Chmod(etcdDir, 0700); err != nil {
return err
}
}
opt, err := executor.CurrentETCDOptions()
if err != nil {
return err
}
return e.cluster(ctx, false, opt)
}
if clientAccessInfo == nil {
return e.newCluster(ctx, false)
}
err = e.join(ctx, clientAccessInfo)
return errors.Wrap(err, "joining etcd cluster")
}
// join attempts to add a member to an existing cluster
func (e *ETCD) join(ctx context.Context, clientAccessInfo *clientaccess.Info) error {
clientURLs, memberList, err := e.clientURLs(ctx, clientAccessInfo)
if err != nil {
return err
}
client, err := getClient(ctx, e.runtime, clientURLs...)
if err != nil {
return err
}
defer client.Close()
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
var (
cluster []string
add = true
)
members, err := client.MemberList(ctx)
if err != nil {
logrus.Errorf("Failed to get member list from etcd cluster. Will assume this member is already added")
members = &etcd.MemberListResponse{
Members: append(memberList.Members, &etcdserverpb.Member{
Name: e.name,
PeerURLs: []string{e.peerURL()},
}),
}
add = false
}
for _, member := range members.Members {
for _, peer := range member.PeerURLs {
u, err := url.Parse(peer)
if err != nil {
return err
}
// An uninitialized member won't have a name
if u.Hostname() == e.address && (member.Name == e.name || member.Name == "") {
add = false
}
if member.Name == "" && u.Hostname() == e.address {
member.Name = e.name
}
if len(member.PeerURLs) > 0 {
cluster = append(cluster, fmt.Sprintf("%s=%s", member.Name, member.PeerURLs[0]))
}
}
}
if add {
logrus.Infof("Adding %s to etcd cluster %v", e.peerURL(), cluster)
if _, err = client.MemberAddAsLearner(ctx, []string{e.peerURL()}); err != nil {
return err
}
cluster = append(cluster, fmt.Sprintf("%s=%s", e.name, e.peerURL()))
}
logrus.Infof("Starting etcd for cluster %v", cluster)
return e.cluster(ctx, false, executor.InitialOptions{
Cluster: strings.Join(cluster, ","),
State: "existing",
})
}
// Register configures a new etcd client and adds db info routes for the http request handler.
func (e *ETCD) Register(ctx context.Context, config *config.Control, handler http.Handler) (http.Handler, error) {
e.config = config
e.runtime = config.Runtime
client, err := getClient(ctx, e.runtime, endpoint)
if err != nil {
return nil, err
}
e.client = client
address, err := getAdvertiseAddress(config.PrivateIP)
if err != nil {
return nil, err
}
e.address = address
e.config.Datastore.Endpoint = endpoint
e.config.Datastore.Config.CAFile = e.runtime.ETCDServerCA
e.config.Datastore.Config.CertFile = e.runtime.ClientETCDCert
e.config.Datastore.Config.KeyFile = e.runtime.ClientETCDKey
if err := e.setName(false); err != nil {
return nil, err
}
tombstoneFile := filepath.Join(etcdDBDir(e.config), "tombstone")
if _, err := os.Stat(tombstoneFile); err == nil {
logrus.Infof("tombstone file has been detected, removing data dir to rejoin the cluster")
if _, err := backupDirWithRetention(etcdDBDir(e.config), maxBackupRetention); err != nil {
return nil, err
}
}
return e.handler(handler), err
}
// setName sets a unique name for this cluster member. The first time this is called,
// or if force is set to true, a new name will be generated and written to disk. The persistent
// name is used on subsequent calls.
func (e *ETCD) setName(force bool) error {
fileName := nameFile(e.config)
data, err := ioutil.ReadFile(fileName)
if os.IsNotExist(err) || force {
h, err := os.Hostname()
if err != nil {
return err
}
e.name = strings.SplitN(h, ".", 2)[0] + "-" + uuid.New().String()[:8]
if err := os.MkdirAll(filepath.Dir(fileName), 0700); err != nil {
return err
}
return ioutil.WriteFile(fileName, []byte(e.name), 0600)
} else if err != nil {
return err
}
e.name = string(data)
return nil
}
// handler wraps the handler with routes for database info
func (e *ETCD) handler(next http.Handler) http.Handler {
mux := mux.NewRouter()
mux.Handle("/db/info", e.infoHandler())
mux.NotFoundHandler = next
return mux
}
// infoHandler returns etcd cluster information. This is used by new members when joining the custer.
func (e *ETCD) infoHandler() http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), 2*time.Second)
defer cancel()
members, err := e.client.MemberList(ctx)
if err != nil {
json.NewEncoder(rw).Encode(&Members{
Members: []*etcdserverpb.Member{
{
Name: e.name,
PeerURLs: []string{e.peerURL()},
ClientURLs: []string{e.clientURL()},
},
},
})
return
}
rw.Header().Set("Content-Type", "application/json")
json.NewEncoder(rw).Encode(&Members{
Members: members.Members,
})
})
}
// getClient returns an etcd client connected to the specified endpoints
func getClient(ctx context.Context, runtime *config.ControlRuntime, endpoints ...string) (*etcd.Client, error) {
cfg, err := getClientConfig(ctx, runtime, endpoints...)
if err != nil {
return nil, err
}
return etcd.New(*cfg)
}
//getClientConfig generates an etcd client config connected to the specified endpoints
func getClientConfig(ctx context.Context, runtime *config.ControlRuntime, endpoints ...string) (*etcd.Config, error) {
tlsConfig, err := toTLSConfig(runtime)
if err != nil {
return nil, err
}
cfg := &etcd.Config{
Endpoints: endpoints,
TLS: tlsConfig,
Context: ctx,
DialTimeout: defaultDialTimeout,
DialKeepAliveTime: defaultKeepAliveTime,
DialKeepAliveTimeout: defaultKeepAliveTimeout,
}
return cfg, nil
}
// toTLSConfig converts the ControlRuntime configuration to TLS configuration suitable
// for use by etcd.
func toTLSConfig(runtime *config.ControlRuntime) (*tls.Config, error) {
clientCert, err := tls.LoadX509KeyPair(runtime.ClientETCDCert, runtime.ClientETCDKey)
if err != nil {
return nil, err
}
pool, err := certutil.NewPool(runtime.ETCDServerCA)
if err != nil {
return nil, err
}
return &tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{clientCert},
}, nil
}
// getAdvertiseAddress returns the IP address best suited for advertising to clients
func getAdvertiseAddress(advertiseIP string) (string, error) {
ip := advertiseIP
if ip == "" {
ipAddr, err := utilnet.ChooseHostInterface()
if err != nil {
return "", err
}
ip = ipAddr.String()
}
return ip, nil
}
// newCluster returns options to set up etcd for a new cluster
func (e *ETCD) newCluster(ctx context.Context, reset bool) error {
return e.cluster(ctx, reset, executor.InitialOptions{
AdvertisePeerURL: fmt.Sprintf("https://%s:2380", e.address),
Cluster: fmt.Sprintf("%s=https://%s:2380", e.name, e.address),
State: "new",
})
}
// peerURL returns the peer access address for the local node
func (e *ETCD) peerURL() string {
return fmt.Sprintf("https://%s:2380", e.address)
}
// clientURL returns the client access address for the local node
func (e *ETCD) clientURL() string {
return fmt.Sprintf("https://%s:2379", e.address)
}
// metricsURL returns the metrics access address
func (e *ETCD) metricsURL(expose bool) string {
if expose {
return fmt.Sprintf("http://%s:2381", e.address)
}
return "http://127.0.0.1:2381"
}
// cluster returns ETCDConfig for a cluster
func (e *ETCD) cluster(ctx context.Context, forceNew bool, options executor.InitialOptions) error {
return executor.ETCD(executor.ETCDConfig{
Name: e.name,
InitialOptions: options,
ForceNewCluster: forceNew,
ListenClientURLs: fmt.Sprintf(e.clientURL() + ",https://127.0.0.1:2379"),
ListenMetricsURLs: e.metricsURL(e.config.EtcdExposeMetrics),
ListenPeerURLs: e.peerURL(),
AdvertiseClientURLs: e.clientURL(),
DataDir: etcdDBDir(e.config),
ServerTrust: executor.ServerTrust{
CertFile: e.config.Runtime.ServerETCDCert,
KeyFile: e.config.Runtime.ServerETCDKey,
ClientCertAuth: true,
TrustedCAFile: e.config.Runtime.ETCDServerCA,
},
PeerTrust: executor.PeerTrust{
CertFile: e.config.Runtime.PeerServerClientETCDCert,
KeyFile: e.config.Runtime.PeerServerClientETCDKey,
ClientCertAuth: true,
TrustedCAFile: e.config.Runtime.ETCDPeerCA,
},
ElectionTimeout: 5000,
HeartbeatInterval: 500,
Logger: "zap",
LogOutputs: []string{"stderr"},
})
}
// removePeer removes a peer from the cluster. The peer ID and IP address must both match.
func (e *ETCD) removePeer(ctx context.Context, id, address string) error {
members, err := e.client.MemberList(ctx)
if err != nil {
return err
}
for _, member := range members.Members {
if member.Name != id {
continue
}
for _, peerURL := range member.PeerURLs {
u, err := url.Parse(peerURL)
if err != nil {
return err
}
if u.Hostname() == address {
if e.address == address {
return errors.New("node has been deleted from the cluster")
}
logrus.Infof("Removing name=%s id=%d address=%s from etcd", member.Name, member.ID, address)
_, err := e.client.MemberRemove(ctx, member.ID)
if err == rpctypes.ErrGRPCMemberNotFound {
return nil
}
return err
}
}
}
return nil
}
// manageLearners monitors the etcd cluster to ensure that learners are making progress towards
// being promoted to full voting member. The checks only run on the cluster member that is
// the etcd leader.
func (e *ETCD) manageLearners(ctx context.Context) error {
t := time.NewTicker(manageTickerTime)
defer t.Stop()
for range t.C {
ctx, cancel := context.WithTimeout(ctx, testTimeout)
defer cancel()
// Check to see if the local node is the leader. Only the leader should do learner management.
if status, err := e.client.Status(ctx, endpoint); err != nil {
logrus.Errorf("Failed to check local etcd status for learner management: %v", err)
continue
} else if status.Header.MemberId != status.Leader {
continue
}
progress, err := e.getLearnerProgress(ctx)
if err != nil {
logrus.Errorf("Failed to get recorded learner progress from etcd: %v", err)
continue
}
members, err := e.client.MemberList(ctx)
if err != nil {
logrus.Errorf("Failed to get etcd members for learner management: %v", err)
continue
}
for _, member := range members.Members {
if member.IsLearner {
if err := e.trackLearnerProgress(ctx, progress, member); err != nil {
logrus.Errorf("Failed to track learner progress towards promotion: %v", err)
}
break
}
}
}
return nil
}
// trackLearnerProcess attempts to promote a learner. If it cannot be promoted, progress through the raft index is tracked.
// If the learner does not make any progress in a reasonable amount of time, it is evicted from the cluster.
func (e *ETCD) trackLearnerProgress(ctx context.Context, progress *learnerProgress, member *etcdserverpb.Member) error {
// Try to promote it. If it can be promoted, no further tracking is necessary
if _, err := e.client.MemberPromote(ctx, member.ID); err != nil {
logrus.Debugf("Unable to promote learner %s: %v", member.Name, err)
} else {
logrus.Infof("Promoted learner %s", member.Name)
return nil
}
now := time.Now()
// If this is the first time we've tracked this member's progress, reset stats
if progress.Name != member.Name || progress.ID != member.ID {
progress.ID = member.ID
progress.Name = member.Name
progress.RaftAppliedIndex = 0
progress.LastProgress.Time = now
}
// Update progress by retrieving status from the member's first reachable client URL
for _, ep := range member.ClientURLs {
ctx, cancel := context.WithTimeout(ctx, defaultDialTimeout)
defer cancel()
status, err := e.client.Status(ctx, ep)
if err != nil {
logrus.Debugf("Failed to get etcd status from learner %s at %s: %v", member.Name, ep, err)
continue
}
if progress.RaftAppliedIndex < status.RaftAppliedIndex {
logrus.Debugf("Learner %s has progressed from RaftAppliedIndex %d to %d", progress.Name, progress.RaftAppliedIndex, status.RaftAppliedIndex)
progress.RaftAppliedIndex = status.RaftAppliedIndex
progress.LastProgress.Time = now
}
break
}
// Warn if the learner hasn't made any progress
if !progress.LastProgress.Time.Equal(now) {
logrus.Warnf("Learner %s stalled at RaftAppliedIndex=%d for %s", progress.Name, progress.RaftAppliedIndex, now.Sub(progress.LastProgress.Time).String())
}
// See if it's time to evict yet
if now.Sub(progress.LastProgress.Time) > learnerMaxStallTime {
if _, err := e.client.MemberRemove(ctx, member.ID); err != nil {
return err
}
logrus.Warnf("Removed learner %s from etcd cluster", member.Name)
return nil
}
return e.setLearnerProgress(ctx, progress)
}
// getLearnerProgress returns the stored learnerProgress struct as retrieved from etcd
func (e *ETCD) getLearnerProgress(ctx context.Context) (*learnerProgress, error) {
progress := &learnerProgress{}
value, err := e.client.Get(ctx, learnerProgressKey)
if err != nil {
return nil, err
}
if value.Count < 1 {
return progress, nil
}
if err := json.NewDecoder(bytes.NewBuffer(value.Kvs[0].Value)).Decode(progress); err != nil {
return nil, err
}
return progress, nil
}
// setLearnerProgress stores the learnerProgress struct to etcd
func (e *ETCD) setLearnerProgress(ctx context.Context, status *learnerProgress) error {
w := &bytes.Buffer{}
if err := json.NewEncoder(w).Encode(status); err != nil {
return err
}
_, err := e.client.Put(ctx, learnerProgressKey, w.String())
return err
}
// clientURLs returns a list of all non-learner etcd cluster member client access URLs
func (e *ETCD) clientURLs(ctx context.Context, clientAccessInfo *clientaccess.Info) ([]string, Members, error) {
var memberList Members
resp, err := clientaccess.Get("/db/info", clientAccessInfo)
if err != nil {
return nil, memberList, err
}
if err := json.Unmarshal(resp, &memberList); err != nil {
return nil, memberList, err
}
var clientURLs []string
for _, member := range memberList.Members {
// excluding learner member from the client list
if member.IsLearner {
continue
}
clientURLs = append(clientURLs, member.ClientURLs...)
}
return clientURLs, memberList, nil
}
// snapshotDir ensures that the snapshot directory exists, and then returns its path.
func snapshotDir(config *config.Control) (string, error) {
if config.EtcdSnapshotDir == "" {
// we have to create the snapshot dir if we are using
// the default snapshot dir if it doesn't exist
defaultSnapshotDir := filepath.Join(config.DataDir, "db", "snapshots")
s, err := os.Stat(defaultSnapshotDir)
if err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(defaultSnapshotDir, 0700); err != nil {
return "", err
}
return defaultSnapshotDir, nil
}
return "", err
}
if s.IsDir() {
return defaultSnapshotDir, nil
}
}
return config.EtcdSnapshotDir, nil
}
// preSnapshotSetup checks to see if the necessary components are in place
// to perform an Etcd snapshot. This is necessary primarily for on-demand
// snapshots since they're performed before normal Etcd setup is completed.
func (e *ETCD) preSnapshotSetup(ctx context.Context, config *config.Control) error {
if e.client == nil {
if e.config == nil {
e.config = config
}
client, err := getClient(ctx, e.config.Runtime, endpoint)
if err != nil {
return err
}
e.client = client
}
if e.runtime == nil {
e.runtime = config.Runtime
}
return nil
}
// Snapshot attempts to save a new snapshot to the configured directory, and then clean up any old
// snapshots in excess of the retention limits. This method is used in the internal cron snapshot
// system as well as used to do on-demand snapshots.
func (e *ETCD) Snapshot(ctx context.Context, config *config.Control) error {
if err := e.preSnapshotSetup(ctx, config); err != nil {
return err
}
status, err := e.client.Status(ctx, endpoint)
if err != nil {
return errors.Wrap(err, "failed to check etcd status for snapshot")
}
if status.IsLearner {
logrus.Warnf("Skipping snapshot: not supported for learner")
return nil
}
snapshotDir, err := snapshotDir(e.config)
if err != nil {
return errors.Wrap(err, "failed to get the snapshot dir")
}
cfg, err := getClientConfig(ctx, e.runtime, endpoint)
if err != nil {
return errors.Wrap(err, "failed to get config for etcd snapshot")
}
snapshotName := fmt.Sprintf("%s-%d", e.config.EtcdSnapshotName, time.Now().Unix())
snapshotPath := filepath.Join(snapshotDir, snapshotName)
logrus.Infof("Saving etcd snapshot to %s", snapshotPath)
if err := snapshot.NewV3(nil).Save(ctx, *cfg, snapshotPath); err != nil {
return errors.Wrap(err, "failed to save snapshot")
}
// check if we need to perform a retention check
if e.config.EtcdSnapshotRetention >= 1 {
if err := snapshotRetention(e.config.EtcdSnapshotRetention, snapshotDir); err != nil {
return errors.Wrap(err, "failed to apply snapshot retention")
}
}
return nil
}
// setSnapshotFunction schedules snapshots at the configured interval
func (e *ETCD) setSnapshotFunction(ctx context.Context) {
e.cron.AddFunc(e.config.EtcdSnapshotCron, func() {
if err := e.Snapshot(ctx, e.config); err != nil {
logrus.Error(err)
}
})
}
// Restore performs a restore of the ETCD datastore from
// the given snapshot path. This operation exists upon
// completion.
func (e *ETCD) Restore(ctx context.Context) error {
// check the old etcd data dir
oldDataDir := etcdDBDir(e.config) + "-old-" + strconv.Itoa(int(time.Now().Unix()))
if e.config.ClusterResetRestorePath == "" {
return errors.New("no etcd restore path was specified")
}
// make sure snapshot exists before restoration
if _, err := os.Stat(e.config.ClusterResetRestorePath); err != nil {
return err
}
// move the data directory to a temp path
if err := os.Rename(etcdDBDir(e.config), oldDataDir); err != nil {
return err
}
logrus.Infof("Pre-restore etcd database moved to %s", oldDataDir)
sManager := snapshot.NewV3(nil)
if err := sManager.Restore(snapshot.RestoreConfig{
SnapshotPath: e.config.ClusterResetRestorePath,
Name: e.name,
OutputDataDir: etcdDBDir(e.config),
OutputWALDir: walDir(e.config),
PeerURLs: []string{e.peerURL()},
InitialCluster: e.name + "=" + e.peerURL(),
}); err != nil {
return err
}
return nil
}
// snapshotRetention iterates through the snapshots and removes the oldest
// leaving the desired number of snapshots.
func snapshotRetention(retention int, snapshotDir string) error {
var snapshotFiles []os.FileInfo
if err := filepath.Walk(snapshotDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasPrefix(info.Name(), snapshotPrefix) {
snapshotFiles = append(snapshotFiles, info)
}
return nil
}); err != nil {
return err
}
if len(snapshotFiles) <= retention {
return nil
}
sort.Slice(snapshotFiles, func(i, j int) bool {
return snapshotFiles[i].Name() < snapshotFiles[j].Name()
})
return os.Remove(filepath.Join(snapshotDir, snapshotFiles[0].Name()))
}
// backupDirWithRetention will move the dir to a backup dir
// and will keep only maxBackupRetention of dirs.
func backupDirWithRetention(dir string, maxBackupRetention int) (string, error) {
backupDir := dir + "-backup-" + strconv.Itoa(int(time.Now().Unix()))
if _, err := os.Stat(dir); err != nil {
return "", nil
}
files, err := ioutil.ReadDir(filepath.Dir(dir))
if err != nil {
return "", err
}
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime().After(files[j].ModTime())
})
count := 0
for _, f := range files {
if strings.HasPrefix(f.Name(), filepath.Base(dir)+"-backup") && f.IsDir() {
count++
if count > maxBackupRetention {
if err := os.RemoveAll(filepath.Join(filepath.Dir(dir), f.Name())); err != nil {
return "", err
}
}
}
}
// move the directory to a temp path
if err := os.Rename(dir, backupDir); err != nil {
return "", err
}
return backupDir, nil
}
| 1 | 9,114 | This seems relatively high, is it the recommended value from the etcd folks? Or is this debugging cruft? | k3s-io-k3s | go |
@@ -10,11 +10,11 @@ import (
"google.golang.org/grpc/status"
)
-type peerTrackerAttestor struct {
+type PeerTrackerAttestor struct {
Attestor attestor.Attestor
}
-func (a peerTrackerAttestor) Attest(ctx context.Context) ([]*common.Selector, error) {
+func (a PeerTrackerAttestor) Attest(ctx context.Context) ([]*common.Selector, error) {
watcher, ok := peertracker.WatcherFromContext(ctx)
if !ok {
return nil, status.Error(codes.Internal, "peer tracker watcher missing from context") | 1 | package endpoints
import (
"context"
attestor "github.com/spiffe/spire/pkg/agent/attestor/workload"
"github.com/spiffe/spire/pkg/common/peertracker"
"github.com/spiffe/spire/proto/spire/common"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type peerTrackerAttestor struct {
Attestor attestor.Attestor
}
func (a peerTrackerAttestor) Attest(ctx context.Context) ([]*common.Selector, error) {
watcher, ok := peertracker.WatcherFromContext(ctx)
if !ok {
return nil, status.Error(codes.Internal, "peer tracker watcher missing from context")
}
selectors := a.Attestor.Attest(ctx, int(watcher.PID()))
// Ensure that the original caller is still alive so that we know we didn't
// attest some other process that happened to be assigned the original PID
if err := watcher.IsAlive(); err != nil {
return nil, status.Errorf(codes.Unauthenticated, "could not verify existence of the original caller: %v", err)
}
return selectors, nil
}
| 1 | 17,680 | This requires updating the name in the `endpoints` tests, please run `make test`. | spiffe-spire | go |
@@ -37,6 +37,10 @@ std::vector<HostAddr> toHosts(const std::string& peersStr) {
int main(int argc, char *argv[]) {
folly::init(&argc, &argv, true);
+ if (FLAGS_data_path.empty()) {
+ LOG(FATAL) << "Meta Data Path should not empty";
+ return EXIT_FAILURE;
+ }
LOG(INFO) << "Starting Meta HTTP Service";
nebula::WebService::registerHandler("/meta", [] { | 1 | /* Copyright (c) 2018 - present, VE Software Inc. All rights reserved
*
* This source code is licensed under Apache 2.0 License
* (found in the LICENSE.Apache file in the root directory)
*/
#include "base/Base.h"
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include "meta/MetaServiceHandler.h"
#include "meta/MetaHttpHandler.h"
#include "webservice/WebService.h"
#include "network/NetworkUtils.h"
#include "kvstore/PartManager.h"
DEFINE_int32(port, 45500, "Meta daemon listening port");
DEFINE_string(data_path, "", "Root data path");
DEFINE_string(peers, "", "It is a list of IPs split by comma,"
"the ips number equals replica number."
"If empty, it means replica is 1");
DEFINE_string(local_ip, "", "Local ip speicified for NetworkUtils::getLocalIP");
DECLARE_string(part_man_type);
namespace nebula {
std::vector<HostAddr> toHosts(const std::string& peersStr) {
std::vector<HostAddr> hosts;
std::vector<std::string> peers;
folly::split(",", peersStr, peers, true);
std::transform(peers.begin(), peers.end(), hosts.begin(), [](auto& p) {
return network::NetworkUtils::toHostAddr(folly::trimWhitespace(p));
});
return hosts;
}
} // namespace nebula
int main(int argc, char *argv[]) {
folly::init(&argc, &argv, true);
LOG(INFO) << "Starting Meta HTTP Service";
nebula::WebService::registerHandler("/meta", [] {
return new nebula::meta::MetaHttpHandler();
});
auto status = nebula::WebService::start();
if (!status.ok()) {
LOG(ERROR) << "Failed to start web service: " << status;
return EXIT_FAILURE;
}
LOG(INFO) << "Starting the meta Daemon on port " << FLAGS_port;
auto result = nebula::network::NetworkUtils::getLocalIP(FLAGS_local_ip);
CHECK(result.ok()) << result.status();
uint32_t localIP;
CHECK(nebula::network::NetworkUtils::ipv4ToInt(result.value(), localIP));
CHECK_EQ("memory", FLAGS_part_man_type);
nebula::kvstore::MemPartManager* partMan
= reinterpret_cast<nebula::kvstore::MemPartManager*>(
nebula::kvstore::PartManager::instance());
// The meta server has only one space, one part.
partMan->addPart(0, 0, nebula::toHosts(FLAGS_peers));
nebula::kvstore::KVOptions options;
options.local_ = nebula::HostAddr(localIP, FLAGS_port);
options.dataPaths_ = {FLAGS_data_path};
std::unique_ptr<nebula::kvstore::KVStore> kvstore(
nebula::kvstore::KVStore::instance(std::move(options)));
auto handler = std::make_shared<nebula::meta::MetaServiceHandler>(kvstore.get());
auto server = std::make_shared<apache::thrift::ThriftServer>();
CHECK(!!server) << "Failed to create the thrift server";
server->setInterface(handler);
server->setPort(FLAGS_port);
server->serve(); // Will wait until the server shuts down
LOG(INFO) << "The storage Daemon on port " << FLAGS_port << " stopped";
}
| 1 | 15,662 | LOG(FATAL) means coredump, LOG(ERROR) is better here. | vesoft-inc-nebula | cpp |
@@ -533,13 +533,13 @@ nsCommandProcessor.prototype.execute = function(jsonCommandString,
* Changes the context of the caller to the specified window.
* @param {fxdriver.CommandResponse} response The response object to send the
* command response in.
- * @param {{name: string}} parameters The command parameters.
+ * @param {{handle: string}} parameters The command parameters.
* @param {number} opt_searchAttempt Which attempt this is at finding the
* window to switch to.
*/
nsCommandProcessor.prototype.switchToWindow = function(response, parameters,
opt_searchAttempt) {
- var lookFor = parameters.name;
+ var lookFor = parameters.handle;
var matches = function(win, lookFor) {
return !win.closed &&
(win.top && win.top.fxdriver) && | 1 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
/**
* @fileoverview Contains a Javascript implementation for
* nsICommandProcessor.idl. The implemented XPCOM component is exposed to
* the content page as a global property so that it can be used from
* unpriviledged code.
*/
goog.provide('fxdriver.CommandResponse');
goog.require('FirefoxDriver');
goog.require('Utils');
goog.require('WebElement');
goog.require('bot.ErrorCode');
goog.require('bot.locators');
goog.require('bot.userAgent');
goog.require('fxdriver.Timer');
goog.require('fxdriver.error');
goog.require('fxdriver.logging');
goog.require('fxdriver.modals');
goog.require('fxdriver.moz');
goog.require('fxdriver.profiler');
goog.require('goog.array');
goog.require('goog.log');
goog.require('wdSessionStoreService');
/**
* Encapsulates the result of a command to the {@code nsCommandProcessor}.
* @param {Object} command JSON object describing the command to execute.
* @param {nsIResponseHandler} responseHandler The handler to send the response
* to.
* @constructor
*/
fxdriver.CommandResponse = function(command, responseHandler) {
this.statusBarLabel_ = null;
this.responseHandler_ = responseHandler;
this.json_ = {
name: command ? command.name : 'Unknown command',
sessionId: command['sessionId'],
status: bot.ErrorCode.SUCCESS,
value: ''
};
if (goog.isObject(this.json_['sessionId'])) {
this.json_['sessionId'] = this.json_['sessionId']['value'];
}
this.session = null;
};
fxdriver.CommandResponse.prototype = {
/**
* Updates the extension status label to indicate we are about to execute a
* command.
* @param {window} win The content window that the command will be executed on.
*/
startCommand: function(win) {
this.statusBarLabel_ = win.document.getElementById('fxdriver-label');
if (this.statusBarLabel_) {
this.statusBarLabel_.style.color = 'red';
}
},
/**
* Sends the encapsulated response to the registered callback.
*/
send: function() {
if (this.responseSent_) {
// We shouldn't ever send the same response twice.
return;
}
// Indicate that we are no longer executing a command.
if (this.statusBarLabel_) {
this.statusBarLabel_.style.color = 'black';
}
this.responseHandler_.handleResponse(JSON.stringify(this.json_));
// Neuter ourselves
this.responseSent_ = true;
},
/**
* Sends a WebDriver error response.
* @param {WebDriverError} e The error to send.
*/
sendError: function(e) {
// if (e instanceof WebDriverError) won't work here since
// WebDriverError is defined in the utils.js subscript which is
// loaded independently in this component and in the main driver
// component.
this.status = e.isWebDriverError ? e.code : bot.ErrorCode.UNKNOWN_ERROR;
this.value = fxdriver.error.toJSON(e);
this.send();
},
set name(name) { this.json_.name = name; },
get name() { return this.json_.name; },
get sessionId() { return this.json_.sessionId; },
set sessionId(sessionId) { this.json_.sessionId = sessionId; },
set status(newStatus) { this.json_.status = newStatus; },
get status() { return this.json_.status; },
set value(val) { this.json_.value = val; },
get value() { return this.json_.value; }
};
/**
* Handles executing a command from the {@code CommandProcessor} once the window
* has fully loaded.
* @param {FirefoxDriver} driver The FirefoxDriver instance to execute the
* command with.
* @param {Object} command JSON object describing the command to execute.
* @param {fxdriver.CommandResponse} response The response object to send the
* command response in.
* @param {Number} opt_sleepDelay The amount of time to wait before attempting
* the command again if the window is not ready.
* @constructor
*/
var DelayedCommand = function(driver, command, response, opt_sleepDelay) {
this.driver_ = driver;
this.command_ = command;
this.response_ = response;
this.onBlank_ = false;
this.sleepDelay_ = opt_sleepDelay || DelayedCommand.DEFAULT_SLEEP_DELAY;
var activeWindow = response.session.getWindow();
try {
if (!activeWindow || activeWindow.closed) {
this.loadGroup_ = {
isPending: function() { return false; }
};
} else {
var webNav = activeWindow.
QueryInterface(Components.interfaces.nsIInterfaceRequestor).
getInterface(Components.interfaces.nsIWebNavigation);
this.loadGroup_ = webNav.
QueryInterface(Components.interfaces.nsIInterfaceRequestor).
getInterface(Components.interfaces.nsILoadGroup);
}
} catch (ex) {
// Well this sucks. This can happen if the DOM gets trashed or if the window
// is unexpectedly closed. We need to report this error to the user so they
// can let us (webdriver-eng) know that the FirefoxDriver is busted.
response.sendError(ex);
// Re-throw the error so the command will be aborted.
throw ex;
}
};
/**
* Default amount of time, in milliseconds, to wait before (re)attempting a
* {@code DelayedCommand}.
* @type {Number}
*/
DelayedCommand.DEFAULT_SLEEP_DELAY = 100;
/**
* @private {goog.log.Logger}
* @const
*/
DelayedCommand.LOG_ = fxdriver.logging.getLogger('fxdriver.DelayedCommand');
/**
* Executes the command after the specified delay.
* @param {Number} ms The delay in milliseconds.
*/
DelayedCommand.prototype.execute = function(ms) {
if (this.response_.session.getWaitForPageLoad() && !this.yieldedForBackgroundExecution_) {
this.yieldedForBackgroundExecution_ = true;
fxdriver.profiler.log(
{'event': 'YIELD_TO_PAGE_LOAD', 'startorend': 'start'});
}
var self = this;
this.driver_.window.setTimeout(function() {
self.executeInternal_();
}, ms);
};
/**
* @return {boolean} Whether this instance should delay execution of its
* command for a pending request in the current window's nsILoadGroup.
*/
DelayedCommand.prototype.shouldDelayExecutionForPendingRequest_ = function() {
if (!this.response_.session.getWaitForPageLoad()) {
return false;
}
if (this.loadGroup_.isPending()) {
var hasOnLoadBlocker = false;
var numPending = 0;
var requests = this.loadGroup_.requests;
while (requests.hasMoreElements()) {
var request = null;
var rawRequest = requests.getNext();
try {
request = rawRequest.QueryInterface(Components.interfaces.nsIRequest);
} catch (e) {
// This may happen for pages that use WebSockets.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=765618
goog.log.info(DelayedCommand.LOG_,
'Ignoring non-nsIRequest: ' + rawRequest);
continue;
}
var isPending = false;
try {
isPending = request.isPending();
} catch (e) {
// Normal during page load, which means we should just return "true"
return true;
}
if (isPending) {
numPending += 1;
hasOnLoadBlocker = hasOnLoadBlocker ||
(request.name == 'about:document-onload-blocker');
if (numPending > 1) {
// More than one pending request, need to wait.
return true;
}
}
}
if (numPending && !hasOnLoadBlocker) {
goog.log.info(DelayedCommand.LOG_,
'Ignoring pending about:document-onload-blocker ' +
'request');
// If we only have one pending request and it is not a
// document-onload-blocker, we need to wait. We do not wait for
// document-onload-blocker requests since these are created when
// one of document.[open|write|writeln] is called. If document.close is
// never called, the document-onload-blocker request will not be
// completed.
return true;
}
}
fxdriver.profiler.log(
{'event': 'YIELD_TO_PAGE_LOAD', 'startorend': 'end'});
return false;
};
DelayedCommand.prototype.checkPreconditions_ = function(preconditions, respond, parameters) {
if (!preconditions) {
return;
}
var toThrow = null;
var length = preconditions.length;
for (var i = 0; i < length; i++) {
toThrow = preconditions[i](respond.session.getDocument(), parameters);
if (toThrow) {
throw toThrow;
}
}
};
/**
* Attempts to execute the command. If the window is not ready for the command
* to execute, will set a timeout to try again.
* @private
*/
DelayedCommand.prototype.executeInternal_ = function() {
if (this.shouldDelayExecutionForPendingRequest_()) {
return this.execute(this.sleepDelay_);
}
// Ugh! New windows open on "about:blank" before going to their
// destination URL. This check attempts to tell the difference between a
// newly opened window and someone actually wanting to do something on
// about:blank.
if (this.driver_.window.location == 'about:blank' && !this.onBlank_) {
this.onBlank_ = true;
return this.execute(this.sleepDelay_);
} else {
try {
this.response_.name = this.command_.name;
// TODO(simon): This is rampantly ugly, but allows an alert to kill the command
// TODO(simon): This is never cleared, but _should_ be okay, because send wipes itself
this.driver_.response_ = this.response_;
var response = this.response_;
DelayedCommand.execTimer = new fxdriver.Timer();
var startTime = new Date().getTime();
var endTime = startTime + this.response_.session.getImplicitWait();
var name = this.command_.name;
var driverFunction = this.driver_[name] || WebElement[name];
var parameters = this.command_.parameters;
var func = goog.bind(driverFunction, this.driver_,
this.response_, parameters);
var guards = goog.bind(this.checkPreconditions_, this,
driverFunction.preconditions, this.response_, parameters);
var toExecute = function() {
try {
guards();
func();
} catch (e) {
if (new Date().getTime() < endTime) {
DelayedCommand.execTimer.setTimeout(toExecute, 100);
} else {
if (!e.isWebDriverError) {
goog.log.error(
DelayedCommand.LOG_,
'Exception caught by driver: ' + name + '(' + parameters + ')',
e);
}
response.sendError(e);
}
}
};
toExecute();
} catch (e) {
if (!e.isWebDriverError) {
goog.log.error(DelayedCommand.LOG_,
'Exception caught by driver: ' + this.command_.name +
'(' + this.command_.parameters + ')', e);
}
this.response_.sendError(e);
}
}
};
/**
* Class for dispatching WebDriver requests. Handles window locating commands
* (e.g. switching, searching, etc.), all other commands are executed with the
* {@code FirefoxDriver} through reflection. Note this is a singleton class.
* @constructor
*/
var nsCommandProcessor = function() {
this.wrappedJSObject = this;
this.wm = Components.classes['@mozilla.org/appshell/window-mediator;1'].
getService(Components.interfaces.nsIWindowMediator);
};
/**
* @private {goog.log.Logger}
* @const
*/
nsCommandProcessor.LOG_ = fxdriver.logging.getLogger(
'fxdriver.nsCommandProcessor');
/**
* Flags for the {@code nsIClassInfo} interface.
* @type {Number}
*/
nsCommandProcessor.prototype.flags =
Components.interfaces.nsIClassInfo.DOM_OBJECT;
/**
* Implementaiton language detail for the {@code nsIClassInfo} interface.
* @type {String}
*/
nsCommandProcessor.prototype.implementationLanguage =
Components.interfaces.nsIProgrammingLanguage.JAVASCRIPT;
/**
* Processes a command request for the {@code FirefoxDriver}.
* @param {string} jsonCommandString The command to execute, specified in a
* JSON string.
* @param {nsIResponseHandler} responseHandler The callback to send the response
* to.
*/
nsCommandProcessor.prototype.execute = function(jsonCommandString,
responseHandler) {
var command, response;
try {
command = JSON.parse(jsonCommandString);
} catch (ex) {
response = JSON.stringify({
'status': bot.ErrorCode.UNKNOWN_ERROR,
'value': 'Error parsing command: "' + jsonCommandString + '"'
});
responseHandler.handleResponse(response);
return;
}
response = new fxdriver.CommandResponse(command, responseHandler);
// These commands do not require a session.
if (command.name == 'newSession' ||
command.name == 'quit' ||
command.name == 'getStatus' ||
command.name == 'getWindowHandles') {
goog.log.info(nsCommandProcessor.LOG_,
'Received command: ' + command.name);
try {
this[command.name](response, command.parameters);
} catch (ex) {
response.sendError(ex);
}
return;
}
var sessionId = command.sessionId;
if (!sessionId) {
response.sendError(new WebDriverError(bot.ErrorCode.UNKNOWN_ERROR,
'No session ID specified'));
return;
}
try {
response.session = Components.
classes['@googlecode.com/webdriver/wdsessionstoreservice;1'].
getService(Components.interfaces.nsISupports).
wrappedJSObject.
getSession(sessionId).
wrappedJSObject;
} catch (ex) {
response.sendError(new WebDriverError(bot.ErrorCode.UNKNOWN_ERROR,
'Session not found: ' + sessionId));
return;
}
goog.log.info(nsCommandProcessor.LOG_, 'Received command: ' + command.name);
if (command.name == 'getSessionCapabilities' ||
command.name == 'switchToWindow' ||
command.name == 'getLog' ||
command.name == 'getAvailableLogTypes') {
return this[command.name](response, command.parameters);
}
var sessionWindow = response.session.getChromeWindow();
var driver = sessionWindow.fxdriver; // TODO(jmleyba): We only need to store an ID on the window!
if (!driver) {
response.sendError(new WebDriverError(bot.ErrorCode.UNKNOWN_ERROR,
'Session [' + response.session.getId() + '] has no driver.' +
' The browser window may have been closed.'));
return;
}
try {
var contentWindow = sessionWindow.getBrowser().contentWindow;
if (!contentWindow) {
response.sendError(new WebDriverError(bot.ErrorCode.NO_SUCH_WINDOW,
'Window not found. The browser window may have been closed.'));
return;
}
} catch (ff45) {
response.sendError(new WebDriverError(bot.ErrorCode.NO_SUCH_WINDOW,
'Window not found. The browser window may have been closed.'));
return;
}
if (driver.modalOpen) {
if (command.name != 'getAlertText' &&
command.name != 'setAlertValue' &&
command.name != 'acceptAlert' &&
command.name != 'dismissAlert') {
var modalText = driver.modalOpen;
var unexpectedAlertBehaviour = fxdriver.modals.getUnexpectedAlertBehaviour();
switch (unexpectedAlertBehaviour) {
case 'accept':
fxdriver.modals.closeUnhandledAlert(response, driver, true);
break;
case 'ignore':
// do nothing, ignore the alert
response.sendError(new WebDriverError(bot.ErrorCode.UNEXPECTED_ALERT_OPEN,
'Modal dialog present', {alert: {text: modalText}}));
break;
// Dismiss is the default
case 'dismiss':
default:
fxdriver.modals.closeUnhandledAlert(response, driver, false);
break;
}
return;
}
}
if (typeof driver[command.name] != 'function' && typeof WebElement[command.name] != 'function') {
response.sendError(new WebDriverError(bot.ErrorCode.UNKNOWN_COMMAND,
'Unrecognised command: ' + command.name));
goog.log.error(nsCommandProcessor.LOG_,
'Unknown command: ' + command.name);
return;
}
if(command.name == 'get' || command.name == 'refresh') {
response.session.setWaitForPageLoad(false);
}
// TODO: should we delay commands if the page is reloaded on itself?
// var pageLoadTimeout = response.session.getPageLoadTimeout();
// var shouldWaitForPageLoad = response.session.getWaitForPageLoad();
// if (pageLoadTimeout != 0 && shouldWaitForPageLoad) {
// driver.window.setTimeout(function () {
// response.session.setWaitForPageLoad(false);
// }, pageLoadTimeout);
// }
response.startCommand(sessionWindow);
new DelayedCommand(driver, command, response).execute(0);
};
/**
* Changes the context of the caller to the specified window.
* @param {fxdriver.CommandResponse} response The response object to send the
* command response in.
* @param {{name: string}} parameters The command parameters.
* @param {number} opt_searchAttempt Which attempt this is at finding the
* window to switch to.
*/
nsCommandProcessor.prototype.switchToWindow = function(response, parameters,
opt_searchAttempt) {
var lookFor = parameters.name;
var matches = function(win, lookFor) {
return !win.closed &&
(win.top && win.top.fxdriver) &&
(win.content && win.content.name == lookFor) ||
(win.top && win.top.fxdriver && win.top.fxdriver.id == lookFor);
};
var windowFound = this.searchWindows_('navigator:browser', function(win) {
if (matches(win, lookFor)) {
win.focus();
if (win.top.fxdriver) {
response.session.setChromeWindow(win.top);
response.value = response.session.getId();
response.send();
} else {
response.sendError(new WebDriverError(bot.ErrorCode.UNKNOWN_ERROR,
'No driver found attached to top window!'));
}
// Found the desired window, stop the search.
return true;
}
});
// It is possible that the window won't be found on the first attempt. This is
// typically true for anchors with a target attribute set. This search could
// execute before the target window has finished loaded, meaning the content
// window won't have a name or FirefoxDriver instance yet (see matches above).
// If we don't find the window, set a timeout and try again.
if (!windowFound) {
// TODO(jmleyba): We should be sniffing the current windows to detect if
// one is still loading vs. a brute force "try again"
var searchAttempt = opt_searchAttempt || 0;
if (searchAttempt > 3) {
response.sendError(new WebDriverError(bot.ErrorCode.NO_SUCH_WINDOW,
'Unable to locate window "' + lookFor + '"'));
} else {
var self = this;
this.wm.getMostRecentWindow('navigator:browser').
setTimeout(function() {
self.switchToWindow(response, parameters, (searchAttempt + 1));
}, 500);
}
}
};
/**
* Retrieves a list of all known FirefoxDriver windows.
* @param {fxdriver.CommandResponse} response The response object to send the
* command response in.
*/
nsCommandProcessor.prototype.getWindowHandles = function(response) {
var res = [];
this.searchWindows_('navigator:browser', function(win) {
if (win.top && win.top.fxdriver) {
res.push(win.top.fxdriver.id);
}
});
response.value = res;
response.send();
};
/**
* Retrieves the log for the given type.
*
* @param {!fxdriver.CommandResponse} response The response object to send the
* response in.
* @param {!Object.<string, *>} parameters The parameters for the call.
*/
nsCommandProcessor.prototype.getLog = function(response, parameters) {
var res = fxdriver.logging.getLog(parameters.type);
// Convert log level object to string
goog.array.forEach(res, function(entry) {
entry.level = entry.level.name;
});
response.value = res;
response.send();
};
/**
* Retrieves available log types.
*
* @param {!fxdriver.CommandResponse} response The response object to send the
* response in.
* @param {Object.<string, *>} parameters The parameters for the call.
*/
nsCommandProcessor.prototype.getAvailableLogTypes = function(response,
parameters) {
response.value = fxdriver.logging.getAvailableLogTypes();
response.send();
};
/**
* Searches over a selection of windows, calling a visitor function on each
* window found in the search.
* @param {?string} search_criteria The category of windows to search or
* {@code null} to search all windows.
* @param {function(!Window)} visitor_fn A visitor function to call with each
* window. The function may return true to indicate that the window search
* should abort early.
* @return {boolean} Whether the visitor function short circuited the search.
*/
nsCommandProcessor.prototype.searchWindows_ = function(search_criteria,
visitor_fn) {
var allWindows = this.wm.getEnumerator(search_criteria);
while (allWindows.hasMoreElements()) {
var win = allWindows.getNext();
if (visitor_fn(win)) {
return true;
}
}
return false;
};
/**
* Responds with general status information about this process.
* @param {fxdriver.CommandResponse} response The object to send the command
* response in.
*/
nsCommandProcessor.prototype.getStatus = function(response) {
var xulRuntime = Components.classes['@mozilla.org/xre/app-info;1'].
getService(Components.interfaces.nsIXULRuntime);
response.value = {
'os': {
'arch': (function() {
try {
// See https://developer.mozilla.org/en/XPCOM_ABI
return (xulRuntime.XPCOMABI || 'unknown').split('-')[0];
} catch (ignored) {
return 'unknown';
}
})(),
// See https://developer.mozilla.org/en/OS_TARGET
'name': xulRuntime.OS,
'version': 'unknown'
},
// TODO: load these values from build.properties
'build': {
'revision': 'unknown',
'time': 'unknown',
'version': 'unknown'
}
};
response.send();
};
/**
* Locates the most recently used FirefoxDriver window.
* @param {fxdriver.CommandResponse} response The object to send the command
* response in.
*/
nsCommandProcessor.prototype.newSession = function(response, parameters) {
var win = this.wm.getMostRecentWindow('navigator:browser');
var driver = win.fxdriver;
if (!driver) {
response.sendError(new WebDriverError(bot.ErrorCode.UNKNOWN_ERROR,
'No drivers associated with the window'));
} else {
var sessionStore = Components.
classes['@googlecode.com/webdriver/wdsessionstoreservice;1'].
getService(Components.interfaces.nsISupports);
var desiredCapabilities = parameters['desiredCapabilities'];
var requiredCapabilities = parameters['requiredCapabilities'];
var session = sessionStore.wrappedJSObject.createSession(response,
desiredCapabilities, requiredCapabilities, driver);
session = session.wrappedJSObject; // XPConnect...
session.setChromeWindow(win);
if ('elementScrollBehavior' in desiredCapabilities) {
session.elementScrollBehavior = desiredCapabilities['elementScrollBehavior'];
}
response.session = session;
response.sessionId = session.getId();
goog.log.info(nsCommandProcessor.LOG_,
'Created a new session with id: ' + session.getId());
this.getSessionCapabilities(response);
}
response.send();
};
/**
* Describes a session.
* @param {fxdriver.CommandResponse} response The object to send the command
* response in.
*/
nsCommandProcessor.prototype.getSessionCapabilities = function(response) {
var appInfo = Components.classes['@mozilla.org/xre/app-info;1'].
getService(Components.interfaces.nsIXULAppInfo);
var xulRuntime = Components.classes['@mozilla.org/xre/app-info;1'].
getService(Components.interfaces.nsIXULRuntime);
response.value = {
'cssSelectorsEnabled': true,
'browserName': 'firefox',
'handlesAlerts': true,
'javascriptEnabled': true,
'nativeEvents': false,
// See https://developer.mozilla.org/en/OS_TARGET
'platform': (xulRuntime.OS == 'WINNT' ? 'WINDOWS' : xulRuntime.OS),
'rotatable': false,
'takesScreenshot': true,
'version': appInfo.version
};
var prefStore = fxdriver.moz.getService('@mozilla.org/preferences-service;1',
'nsIPrefService');
for (var cap in wdSessionStoreService.CAPABILITY_PREFERENCE_MAPPING) {
var pref = wdSessionStoreService.CAPABILITY_PREFERENCE_MAPPING[cap];
try {
response.value[cap] = prefStore.getBoolPref(pref);
} catch (e) {
try {
response.value[cap] = prefStore.getIntPref(pref);
} catch (e) {
try {
response.value[cap] = prefStore.getCharPref(pref);
} catch (e) {
}
}
}
}
response.send();
};
/**
* Forcefully shuts down the Firefox application.
* @param {fxdriver.CommandResponse} response The object to send the command
* response in.
*/
nsCommandProcessor.prototype.quit = function(response) {
// Go ahead and respond to the command request to acknowledge that we are
// shutting down. We do this because once we force a quit, there's no way
// to respond. Clients will just have to trust that this shutdown didn't
// fail. Or they could monitor the PID. Either way, not much we can do about
// it in here.
response.send();
wdSession.quitBrowser(500);
};
nsCommandProcessor.prototype.getInterfaces = function(count) {
var ifaces = [
Components.interfaces.nsICommandProcessor,
Components.interfaces.nsISupports
];
count.value = ifaces.length;
return ifaces;
};
nsCommandProcessor.prototype.QueryInterface = function(aIID) {
if (!aIID.equals(Components.interfaces.nsICommandProcessor) &&
!aIID.equals(Components.interfaces.nsISupports)) {
throw Components.results.NS_ERROR_NO_INTERFACE;
}
return this;
};
nsCommandProcessor.CLASS_ID =
Components.ID('{692e5117-a4a2-4b00-99f7-0685285b4db5}');
nsCommandProcessor.CLASS_NAME = 'Firefox WebDriver CommandProcessor';
nsCommandProcessor.CONTRACT_ID =
'@googlecode.com/webdriver/command-processor;1';
/**
* Factory object for obtaining a reference to the singleton instance of
* {@code CommandProcessor}.
*/
nsCommandProcessor.Factory = {
instance_: null,
createInstance: function(aOuter, aIID) {
if (aOuter != null) {
throw Components.results.NS_ERROR_NO_AGGREGATION;
}
if (!this.instance_) {
this.instance_ = new nsCommandProcessor();
}
return this.instance_.QueryInterface(aIID);
}
};
/**
* Module definition for registering this XPCOM component.
*/
nsCommandProcessor.Module = {
firstTime_: true,
registerSelf: function(aCompMgr, aFileSpec, aLocation, aType) {
if (this.firstTime_) {
this.firstTime_ = false;
throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
}
aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar).
registerFactoryLocation(
nsCommandProcessor.CLASS_ID,
nsCommandProcessor.CLASS_NAME,
nsCommandProcessor.CONTRACT_ID,
aFileSpec, aLocation, aType);
},
unregisterSelf: function(aCompMgr, aLocation) {
aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar).
unregisterFactoryLocation(nsCommandProcessor.CLASS_ID, aLocation);
},
getClassObject: function(aCompMgr, aCID, aIID) {
if (!aIID.equals(Components.interfaces.nsIFactory)) {
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
} else if (!aCID.equals(nsCommandProcessor.CLASS_ID)) {
throw Components.results.NS_ERROR_NO_INTERFACE;
}
return nsCommandProcessor.Factory;
},
canUnload: function() {
return true;
}
};
/**
* Module initialization.
*/
NSGetModule = function() {
return nsCommandProcessor.Module;
};
nsCommandProcessor.prototype.classID = nsCommandProcessor.CLASS_ID;
fxdriver.moz.load('resource://gre/modules/XPCOMUtils.jsm');
if (XPCOMUtils.generateNSGetFactory) {
/** @const */ NSGetFactory = XPCOMUtils.generateNSGetFactory([nsCommandProcessor]);
}
| 1 | 13,586 | /javascript/firefox-driver is the Selenium implementation of a WebDriver for Firefox. Since it generally isn't W3C compatible, it shouldn't change. We can just drop this change. | SeleniumHQ-selenium | js |
@@ -375,6 +375,12 @@ func UnmarshalService(in []byte) (interface{}, error) {
m.BackendServiceConfig.Image.HealthCheck.applyIfNotSet(newDefaultContainerHealthCheck())
}
return m, nil
+ case ScheduledJobType:
+ m := newDefaultScheduledJob()
+ if err := yaml.Unmarshal(in, m); err != nil {
+ return nil, fmt.Errorf("unmarshal to scheduled job: %w", err)
+ }
+ return m, nil
default:
return nil, &ErrInvalidSvcManifestType{Type: typeVal}
} | 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package manifest provides functionality to create Manifest files.
package manifest
import (
"errors"
"fmt"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/copilot-cli/internal/pkg/template"
"gopkg.in/yaml.v3"
)
const (
// LoadBalancedWebServiceType is a web service with a load balancer and Fargate as compute.
LoadBalancedWebServiceType = "Load Balanced Web Service"
// BackendServiceType is a service that cannot be accessed from the internet but can be reached from other services.
BackendServiceType = "Backend Service"
defaultSidecarPort = "80"
defaultFluentbitImage = "amazon/aws-for-fluent-bit:latest"
)
var (
errUnmarshalBuildOpts = errors.New("can't unmarshal build field into string or compose-style map")
errUnmarshalCountOpts = errors.New(`unmarshal "count" field to an integer or autoscaling configuration`)
)
var dockerfileDefaultName = "Dockerfile"
// ServiceTypes are the supported service manifest types.
var ServiceTypes = []string{
LoadBalancedWebServiceType,
BackendServiceType,
}
// Range is a number range with maximum and minimum values.
type Range string
// Parse parses Range string and returns the min and max values.
// For example: 1-100 returns 1 and 100.
func (r Range) Parse() (min int, max int, err error) {
minMax := strings.Split(string(r), "-")
if len(minMax) != 2 {
return 0, 0, fmt.Errorf("invalid range value %s. Should be in format of ${min}-${max}", string(r))
}
min, err = strconv.Atoi(minMax[0])
if err != nil {
return 0, 0, fmt.Errorf("cannot convert minimum value %s to integer", minMax[0])
}
max, err = strconv.Atoi(minMax[1])
if err != nil {
return 0, 0, fmt.Errorf("cannot convert maximum value %s to integer", minMax[1])
}
return min, max, nil
}
// Service holds the basic data that every service manifest file needs to have.
type Service struct {
Name *string `yaml:"name"`
Type *string `yaml:"type"` // must be one of the supported manifest types.
}
// ServiceImage represents the service's container image.
type ServiceImage struct {
Build BuildArgsOrString `yaml:"build"` // Path to the Dockerfile.
}
// BuildConfig populates a docker.BuildArguments struct from the fields available in the manifest.
// Prefer the following hierarchy:
// 1. Specific dockerfile, specific context
// 2. Specific dockerfile, context = dockerfile dir
// 3. "Dockerfile" located in context dir
// 4. "Dockerfile" located in ws root.
func (s *ServiceImage) BuildConfig(rootDirectory string) *DockerBuildArgs {
df := s.dockerfile()
ctx := s.context()
if df != "" && ctx != "" {
return &DockerBuildArgs{
Dockerfile: aws.String(filepath.Join(rootDirectory, df)),
Context: aws.String(filepath.Join(rootDirectory, ctx)),
Args: s.args(),
}
}
if df != "" && ctx == "" {
return &DockerBuildArgs{
Dockerfile: aws.String(filepath.Join(rootDirectory, df)),
Context: aws.String(filepath.Join(rootDirectory, filepath.Dir(df))),
Args: s.args(),
}
}
if df == "" && ctx != "" {
return &DockerBuildArgs{
Dockerfile: aws.String(filepath.Join(rootDirectory, ctx, dockerfileDefaultName)),
Context: aws.String(filepath.Join(rootDirectory, ctx)),
Args: s.args(),
}
}
return &DockerBuildArgs{
Dockerfile: aws.String(filepath.Join(rootDirectory, dockerfileDefaultName)),
Context: aws.String(rootDirectory),
Args: s.args(),
}
}
// dockerfile returns the path to the service's Dockerfile. If no dockerfile is specified,
// returns "".
func (s *ServiceImage) dockerfile() string {
// Prefer to use the "Dockerfile" string in BuildArgs. Otherwise,
// "BuildString". If no dockerfile specified, return "".
if s.Build.BuildArgs.Dockerfile != nil {
return aws.StringValue(s.Build.BuildArgs.Dockerfile)
}
var dfPath string
if s.Build.BuildString != nil {
dfPath = aws.StringValue(s.Build.BuildString)
}
return dfPath
}
// context returns the build context directory if it exists, otherwise an empty string.
func (s *ServiceImage) context() string {
return aws.StringValue(s.Build.BuildArgs.Context)
}
// args returns the args section, if it exists, to override args in the dockerfile.
// Otherwise it returns an empty map.
func (s *ServiceImage) args() map[string]string {
return s.Build.BuildArgs.Args
}
// BuildArgsOrString is a custom type which supports unmarshaling yaml which
// can either be of type string or type DockerBuildArgs.
type BuildArgsOrString struct {
BuildString *string
BuildArgs DockerBuildArgs
}
// UnmarshalYAML overrides the default YAML unmarshaling logic for the BuildArgsOrString
// struct, allowing it to perform more complex unmarshaling behavior.
// This method implements the yaml.Unmarshaler (v2) interface.
func (b *BuildArgsOrString) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&b.BuildArgs); err != nil {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
}
if !b.BuildArgs.isEmpty() {
// Unmarshaled successfully to b.BuildArgs, return.
return nil
}
if err := unmarshal(&b.BuildString); err != nil {
return errUnmarshalBuildOpts
}
return nil
}
// DockerBuildArgs represents the options specifiable under the "build" field
// of Docker Compose services. For more information, see:
// https://docs.docker.com/compose/compose-file/#build
type DockerBuildArgs struct {
Context *string `yaml:"context,omitempty"`
Dockerfile *string `yaml:"dockerfile,omitempty"`
Args map[string]string `yaml:"args,omitempty"`
}
func (b *DockerBuildArgs) isEmpty() bool {
if b.Context == nil && b.Dockerfile == nil && b.Args == nil {
return true
}
return false
}
// ServiceImageWithPort represents a container image with an exposed port.
type ServiceImageWithPort struct {
ServiceImage `yaml:",inline"`
Port *uint16 `yaml:"port"`
}
// LogConfig holds configuration for Firelens to route your logs.
type LogConfig struct {
Image *string `yaml:"image"`
Destination map[string]string `yaml:"destination,flow"`
EnableMetadata *bool `yaml:"enableMetadata"`
SecretOptions map[string]string `yaml:"secretOptions"`
ConfigFile *string `yaml:"configFilePath"`
}
func (lc *LogConfig) logConfigOpts() *template.LogConfigOpts {
return &template.LogConfigOpts{
Image: lc.image(),
ConfigFile: lc.ConfigFile,
EnableMetadata: lc.enableMetadata(),
Destination: lc.Destination,
SecretOptions: lc.SecretOptions,
}
}
func (lc *LogConfig) image() *string {
if lc.Image == nil {
return aws.String(defaultFluentbitImage)
}
return lc.Image
}
func (lc *LogConfig) enableMetadata() *string {
if lc.EnableMetadata == nil {
// Enable ecs log metadata by default.
return aws.String("true")
}
return aws.String(strconv.FormatBool(*lc.EnableMetadata))
}
// Sidecar holds configuration for all sidecar containers in a service.
type Sidecar struct {
Sidecars map[string]*SidecarConfig `yaml:"sidecars"`
}
// Options converts the service's sidecar configuration into a format parsable by the templates pkg.
func (s *Sidecar) Options() ([]*template.SidecarOpts, error) {
if s.Sidecars == nil {
return nil, nil
}
var sidecars []*template.SidecarOpts
for name, config := range s.Sidecars {
port, protocol, err := parsePortMapping(config.Port)
if err != nil {
return nil, err
}
sidecars = append(sidecars, &template.SidecarOpts{
Name: aws.String(name),
Image: config.Image,
Port: port,
Protocol: protocol,
CredsParam: config.CredsParam,
})
}
return sidecars, nil
}
// SidecarConfig represents the configurable options for setting up a sidecar container.
type SidecarConfig struct {
Port *string `yaml:"port"`
Image *string `yaml:"image"`
CredsParam *string `yaml:"credentialsParameter"`
}
// TaskConfig represents the resource boundaries and environment variables for the containers in the task.
type TaskConfig struct {
CPU *int `yaml:"cpu"`
Memory *int `yaml:"memory"`
Count Count `yaml:"count"`
Variables map[string]string `yaml:"variables"`
Secrets map[string]string `yaml:"secrets"`
}
// Count is a custom type which supports unmarshaling yaml which
// can either be of type int or type Autoscaling.
type Count struct {
Value *int // 0 is a valid value, so we want the default value to be nil.
Autoscaling Autoscaling // Mutually exclusive with Value.
}
// UnmarshalYAML overrides the default YAML unmarshaling logic for the Count
// struct, allowing it to perform more complex unmarshaling behavior.
// This method implements the yaml.Unmarshaler (v2) interface.
func (a *Count) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&a.Autoscaling); err != nil {
switch err.(type) {
case *yaml.TypeError:
break
default:
return err
}
}
if !a.Autoscaling.IsEmpty() {
return nil
}
if err := unmarshal(&a.Value); err != nil {
return errUnmarshalCountOpts
}
return nil
}
// Autoscaling represents the configurable options for Auto Scaling.
type Autoscaling struct {
Range Range `yaml:"range"`
CPU *int `yaml:"cpu_percentage"`
Memory *int `yaml:"memory_percentage"`
Requests *int `yaml:"requests"`
ResponseTime *time.Duration `yaml:"response_time"`
}
// Options converts the service's Auto Scaling configuration into a format parsable
// by the templates pkg.
func (a *Autoscaling) Options() (*template.AutoscalingOpts, error) {
if a.IsEmpty() {
return nil, nil
}
min, max, err := a.Range.Parse()
if err != nil {
return nil, err
}
autoscalingOpts := template.AutoscalingOpts{
MinCapacity: &min,
MaxCapacity: &max,
}
if a.CPU != nil {
autoscalingOpts.CPU = aws.Float64(float64(*a.CPU))
}
if a.Memory != nil {
autoscalingOpts.Memory = aws.Float64(float64(*a.Memory))
}
if a.Requests != nil {
autoscalingOpts.Requests = aws.Float64(float64(*a.Requests))
}
if a.ResponseTime != nil {
responseTime := float64(*a.ResponseTime) / float64(time.Second)
autoscalingOpts.ResponseTime = aws.Float64(responseTime)
}
return &autoscalingOpts, nil
}
// IsEmpty returns whether Autoscaling is empty.
func (a *Autoscaling) IsEmpty() bool {
return a.Range == "" && a.CPU == nil && a.Memory == nil &&
a.Requests == nil && a.ResponseTime == nil
}
// ServiceProps contains properties for creating a new service manifest.
type ServiceProps struct {
Name string
Dockerfile string
}
// UnmarshalService deserializes the YAML input stream into a service manifest object.
// If an error occurs during deserialization, then returns the error.
// If the service type in the manifest is invalid, then returns an ErrInvalidManifestType.
func UnmarshalService(in []byte) (interface{}, error) {
am := Service{}
if err := yaml.Unmarshal(in, &am); err != nil {
return nil, fmt.Errorf("unmarshal to service manifest: %w", err)
}
typeVal := aws.StringValue(am.Type)
switch typeVal {
case LoadBalancedWebServiceType:
m := newDefaultLoadBalancedWebService()
if err := yaml.Unmarshal(in, m); err != nil {
return nil, fmt.Errorf("unmarshal to load balanced web service: %w", err)
}
return m, nil
case BackendServiceType:
m := newDefaultBackendService()
if err := yaml.Unmarshal(in, m); err != nil {
return nil, fmt.Errorf("unmarshal to backend service: %w", err)
}
if m.BackendServiceConfig.Image.HealthCheck != nil {
// Make sure that unset fields in the healthcheck gets a default value.
m.BackendServiceConfig.Image.HealthCheck.applyIfNotSet(newDefaultContainerHealthCheck())
}
return m, nil
default:
return nil, &ErrInvalidSvcManifestType{Type: typeVal}
}
}
func durationp(v time.Duration) *time.Duration {
return &v
}
// Valid sidecar portMapping example: 2000/udp, or 2000 (default to be tcp).
func parsePortMapping(s *string) (port *string, protocol *string, err error) {
if s == nil {
// default port for sidecar container to be 80.
return aws.String(defaultSidecarPort), nil, nil
}
portProtocol := strings.Split(*s, "/")
switch len(portProtocol) {
case 1:
return aws.String(portProtocol[0]), nil, nil
case 2:
return aws.String(portProtocol[0]), aws.String(portProtocol[1]), nil
default:
return nil, nil, fmt.Errorf("cannot parse port mapping from %s", *s)
}
}
| 1 | 15,001 | It's a bit weird to have `svc.go` to include a `ScheduledJobType`...should we rename this file? | aws-copilot-cli | go |
@@ -55,7 +55,7 @@ const licenseHeaderPrefix = "// The MIT License (MIT)"
var (
// directories to be excluded
- dirBlacklist = []string{"vendor/"}
+ dirBlacklist = []string{"tpb/"}
// default perms for the newly created files
defaultFilePerms = os.FileMode(0644)
) | 1 | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
type (
// task that adds license header to source
// files, if they don't already exist
addLicenseHeaderTask struct {
license string // license header string to add
config *config // root directory of the project source
}
// command line config params
config struct {
rootDir string
verifyOnly bool
}
)
// licenseFileName is the name of the license file
const licenseFileName = "LICENSE"
// unique prefix that identifies a license header
const licenseHeaderPrefixOld = "// Copyright (c)"
const licenseHeaderPrefix = "// The MIT License (MIT)"
var (
// directories to be excluded
dirBlacklist = []string{"vendor/"}
// default perms for the newly created files
defaultFilePerms = os.FileMode(0644)
)
// command line utility that adds license header
// to the source files. Usage as follows:
//
// ./cmd/tools/copyright/licensegen.go
func main() {
var cfg config
flag.StringVar(&cfg.rootDir, "rootDir", ".", "project root directory")
flag.BoolVar(&cfg.verifyOnly, "verifyOnly", false,
"don't automatically add headers, just verify all files")
flag.Parse()
task := newAddLicenseHeaderTask(&cfg)
if err := task.run(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func newAddLicenseHeaderTask(cfg *config) *addLicenseHeaderTask {
return &addLicenseHeaderTask{
config: cfg,
}
}
func (task *addLicenseHeaderTask) run() error {
data, err := ioutil.ReadFile(task.config.rootDir + "/" + licenseFileName)
if err != nil {
return fmt.Errorf("error reading license file, errr=%v", err.Error())
}
task.license, err = commentOutLines(string(data))
if err != nil {
return fmt.Errorf("copyright header failed to comment out lines, err=%v", err.Error())
}
err = filepath.Walk(task.config.rootDir, task.handleFile)
if err != nil {
return fmt.Errorf("copyright header check failed, err=%v", err.Error())
}
return nil
}
func (task *addLicenseHeaderTask) handleFile(path string, fileInfo os.FileInfo, err error) error {
if err != nil {
return err
}
if fileInfo.IsDir() && strings.HasPrefix(fileInfo.Name(), "_vendor-") {
return filepath.SkipDir
}
if fileInfo.IsDir() {
return nil
}
if !mustProcessPath(path) {
return nil
}
if !strings.HasSuffix(fileInfo.Name(), ".go") {
return nil
}
// Used as part of the cli to write licence headers on files, does not use user supplied input so marked as nosec
// #nosec
f, err := os.Open(path)
if err != nil {
return err
}
scanner := bufio.NewScanner(f)
readLineSucc := scanner.Scan()
if !readLineSucc {
return fmt.Errorf("fail to read first line of file %v", path)
}
firstLine := strings.TrimSpace(scanner.Text())
if err := scanner.Err(); err != nil {
return err
}
f.Close()
if strings.Contains(firstLine, licenseHeaderPrefixOld) || strings.Contains(firstLine, licenseHeaderPrefix) {
return nil // file already has the copyright header
}
// at this point, src file is missing the header
if task.config.verifyOnly {
if !isFileAutogenerated(path) {
return fmt.Errorf("%v missing license header", path)
}
}
// Used as part of the cli to write licence headers on files, does not use user supplied input so marked as nosec
// #nosec
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return ioutil.WriteFile(path, []byte(task.license+string(data)), defaultFilePerms)
}
func isFileAutogenerated(path string) bool {
return strings.HasPrefix(path, ".gen")
}
func mustProcessPath(path string) bool {
for _, d := range dirBlacklist {
if strings.HasPrefix(path, d) {
return false
}
}
return true
}
// returns true if the error type is an EOF
func isEOF(err error) bool {
return err == io.EOF || err == io.ErrUnexpectedEOF
}
func commentOutLines(str string) (string, error) {
var lines []string
scanner := bufio.NewScanner(strings.NewReader(str))
for scanner.Scan() {
lines = append(lines, "// "+scanner.Text()+"\n")
}
lines = append(lines, "\n")
if err := scanner.Err(); err != nil {
return "", err
}
return strings.Join(lines, ""), nil
}
| 1 | 9,012 | For some reason `protoc` doesn't copy license header from `proto` files to generated code. But this code will never be checked in, so it is ok. | temporalio-temporal | go |
@@ -898,7 +898,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
PreparedQuery<TemporaryBasal> preparedQuery2 = queryBuilder2.prepare();
List<TemporaryBasal> trList2 = getDaoTemporaryBasal().query(preparedQuery2);
- if (trList2.size() > 0) {
+ if (trList2.size() > 0 && trList2.get(0).pumpId == 0) { // don't update existing record if it has a pumpId
old = trList2.get(0);
old.copyFromPump(tempBasal); | 1 | package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import androidx.annotation.Nullable;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.PercentageSplitter;
import info.nightscout.androidaps.utils.ToastUtils;
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
* data-structure (and not the DB content) should be contained in here (meaning DDL and not SQL).
* <p>
* This class can safely be called from Services, but should not call Services to avoid circular dependencies.
* One major issue with this (right now) are the scheduled events, which are put into the service. Therefor all
* direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings";
public static final String DATABASE_TEMPORARYBASALS = "TemporaryBasals";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
public static final String DATABASE_TEMPTARGETS = "TempTargets";
public static final String DATABASE_DANARHISTORY = "DanaRHistory";
public static final String DATABASE_DBREQUESTS = "DBRequests";
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs";
public static final String DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets";
public static final String DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs";
public static final String DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs";
private static final int DATABASE_VERSION = 11;
public static Long earliestDataChange = null;
private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledBgPost = null;
private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemBasalsPost = null;
private static final ScheduledExecutorService tempTargetWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTemTargetPost = null;
private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledExtendedBolusPost = null;
private static final ScheduledExecutorService careportalEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledCareportalEventPost = null;
private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledProfileSwitchEventPost = null;
private int oldVersion = 0;
private int newVersion = 0;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
onCreate(getWritableDatabase(), getConnectionSource());
//onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
if (L.isEnabled(L.DATABASE))
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
this.oldVersion = oldVersion;
this.newVersion = newVersion;
if (oldVersion < 7) {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
} else if (oldVersion < 10) {
TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
"WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
} else if (oldVersion < 11) {
database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\"");
database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\"");
}
} catch (SQLException e) {
log.error("Can't drop databases", e);
throw new RuntimeException(e);
}
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
log.info("Do nothing for downgrading...");
log.debug("oldVersion: {}, newVersion: {}", oldVersion, newVersion);
}
public int getOldVersion() {
return oldVersion;
}
public int getNewVersion() {
return newVersion;
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
}
public long size(String database) {
return DatabaseUtils.queryNumEntries(getReadableDatabase(), database);
}
// --------------------- DB resets ---------------------
public void resetDatabases() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
TableUtils.dropTable(connectionSource, DbRequest.class, true);
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
scheduleBgChange(null); // trigger refresh
scheduleTemporaryBasalChange();
scheduleExtendedBolusChange();
scheduleTemporaryTargetChange();
scheduleCareportalEventChange();
scheduleProfileSwitchChange();
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
RxBus.INSTANCE.send(new EventRefreshOverview("resetDatabases"));
}
},
3000
);
}
public void resetTempTargets() {
try {
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryTargetChange();
}
public void resetTemporaryBasals() {
try {
TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.getPlugin().setFakingStatus(false);
scheduleTemporaryBasalChange();
}
public void resetExtededBoluses() {
try {
TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public void resetCareportalEvents() {
try {
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public void resetProfileSwitch() {
try {
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleProfileSwitchChange();
}
public void resetTDDs() {
try {
TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
// ------------------ getDao -------------------------------------------
private Dao<TempTarget, Long> getDaoTempTargets() throws SQLException {
return getDao(TempTarget.class);
}
private Dao<BgReading, Long> getDaoBgReadings() throws SQLException {
return getDao(BgReading.class);
}
private Dao<DanaRHistoryRecord, String> getDaoDanaRHistory() throws SQLException {
return getDao(DanaRHistoryRecord.class);
}
private Dao<TDD, String> getDaoTDD() throws SQLException {
return getDao(TDD.class);
}
private Dao<DbRequest, String> getDaoDbRequest() throws SQLException {
return getDao(DbRequest.class);
}
private Dao<TemporaryBasal, Long> getDaoTemporaryBasal() throws SQLException {
return getDao(TemporaryBasal.class);
}
private Dao<ExtendedBolus, Long> getDaoExtendedBolus() throws SQLException {
return getDao(ExtendedBolus.class);
}
private Dao<CareportalEvent, Long> getDaoCareportalEvents() throws SQLException {
return getDao(CareportalEvent.class);
}
private Dao<ProfileSwitch, Long> getDaoProfileSwitch() throws SQLException {
return getDao(ProfileSwitch.class);
}
private Dao<InsightPumpID, Long> getDaoInsightPumpID() throws SQLException {
return getDao(InsightPumpID.class);
}
private Dao<InsightBolusID, Long> getDaoInsightBolusID() throws SQLException {
return getDao(InsightBolusID.class);
}
private Dao<InsightHistoryOffset, String> getDaoInsightHistoryOffset() throws SQLException {
return getDao(InsightHistoryOffset.class);
}
public static long roundDateToSec(long date) {
long rounded = date - date % 1000;
if (rounded != date)
if (L.isEnabled(L.DATABASE))
log.debug("Rounding " + date + " to " + rounded);
return rounded;
}
// ------------------- BgReading handling -----------------------
public boolean createIfNotExists(BgReading bgReading, String from) {
try {
bgReading.date = roundDateToSec(bgReading.date);
BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) {
getDaoBgReadings().create(bgReading);
if (L.isEnabled(L.DATABASE))
log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange(bgReading);
return true;
}
if (!old.isEqual(bgReading)) {
if (L.isEnabled(L.DATABASE))
log.debug("BG: Similiar found: " + old.toString());
old.copyFrom(bgReading);
getDaoBgReadings().update(old);
if (L.isEnabled(L.DATABASE))
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange(bgReading);
return false;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void update(BgReading bgReading) {
bgReading.date = roundDateToSec(bgReading.date);
try {
getDaoBgReadings().update(bgReading);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleBgChange(@Nullable final BgReading bgReading) {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
RxBus.INSTANCE.send(new EventNewBG(bgReading));
scheduledBgPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledBgPost != null)
scheduledBgPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledBgPost = bgWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
* Return last BgReading from database or null if db is empty
*/
@Nullable
public static BgReading lastBg() {
List<BgReading> bgList = IobCobCalculatorPlugin.getPlugin().getBgReadings();
if (bgList == null)
return null;
for (int i = 0; i < bgList.size(); i++)
if (bgList.get(i).value >= 39)
return bgList.get(i);
return null;
}
/*
* Return bg reading if not old ( <9 min )
* or null if older
*/
@Nullable
public static BgReading actualBg() {
BgReading lastBg = lastBg();
if (lastBg == null)
return null;
if (lastBg.date > System.currentTimeMillis() - 9 * 60 * 1000)
return lastBg;
return null;
}
public List<BgReading> getBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills).and().ge("value", 39).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<BgReading> getBgreadingsDataFromTime(long start, long end, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", start, end).and().ge("value", 39).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
try {
Dao<BgReading, Long> daoBgreadings = getDaoBgReadings();
List<BgReading> bgReadings;
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<BgReading>();
}
// ------------------- TDD handling -----------------------
public void createOrUpdateTDD(TDD tdd) {
try {
Dao<TDD, String> dao = getDaoTDD();
dao.createOrUpdate(tdd);
} catch (SQLException e) {
ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception");
log.error("Unhandled exception", e);
}
}
public List<TDD> getTDDs() {
List<TDD> tddList;
try {
QueryBuilder<TDD, String> queryBuilder = getDaoTDD().queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(10L);
PreparedQuery<TDD> preparedQuery = queryBuilder.prepare();
tddList = getDaoTDD().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
tddList = new ArrayList<>();
}
return tddList;
}
public List<TDD> getTDDsForLastXDays(int days) {
List<TDD> tddList;
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DAY_OF_YEAR, (-1) * days);
try {
QueryBuilder<TDD, String> queryBuilder = getDaoTDD().queryBuilder();
queryBuilder.orderBy("date", false);
Where<TDD, String> where = queryBuilder.where();
where.ge("date", gc.getTimeInMillis());
PreparedQuery<TDD> preparedQuery = queryBuilder.prepare();
tddList = getDaoTDD().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
tddList = new ArrayList<>();
}
return tddList;
}
// ------------- DbRequests handling -------------------
public void create(DbRequest dbr) {
try {
getDaoDbRequest().create(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public int delete(DbRequest dbr) {
try {
return getDaoDbRequest().delete(dbr);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public int deleteDbRequest(String nsClientId) {
try {
return getDaoDbRequest().deleteById(nsClientId);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return 0;
}
public void deleteDbRequestbyMongoId(String action, String id) {
try {
QueryBuilder<DbRequest, String> queryBuilder = getDaoDbRequest().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", id).and().eq("action", action);
queryBuilder.limit(10L);
PreparedQuery<DbRequest> preparedQuery = queryBuilder.prepare();
List<DbRequest> dbList = getDaoDbRequest().query(preparedQuery);
for (DbRequest r : dbList) {
delete(r);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public void deleteAllDbRequests() {
try {
TableUtils.clearTable(connectionSource, DbRequest.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public CloseableIterator getDbRequestInterator() {
try {
return getDaoDbRequest().closeableIterator();
} catch (SQLException e) {
log.error("Unhandled exception", e);
return null;
}
}
// -------------------- TEMPTARGET HANDLING -------------------
public static void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
earliestDataChange = newDate;
return;
}
if (newDate < earliestDataChange) {
earliestDataChange = newDate;
}
}
// ---------------- TempTargets handling ---------------
public List<TempTarget> getTemptargetsDataFromTime(long mills, boolean ascending) {
try {
Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
List<TempTarget> tempTargets;
QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TempTarget>();
}
public List<TempTarget> getTemptargetsDataFromTime(long from, long to, boolean ascending) {
try {
Dao<TempTarget, Long> daoTempTargets = getDaoTempTargets();
List<TempTarget> tempTargets;
QueryBuilder<TempTarget, Long> queryBuilder = daoTempTargets.queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", from, to);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
tempTargets = daoTempTargets.query(preparedQuery);
return tempTargets;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TempTarget>();
}
public boolean createOrUpdate(TempTarget tempTarget) {
try {
TempTarget old;
tempTarget.date = roundDateToSec(tempTarget.date);
if (tempTarget.source == Source.NIGHTSCOUT) {
old = getDaoTempTargets().queryForId(tempTarget.date);
if (old != null) {
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
return false;
}
// find by NS _id
if (tempTarget._id != null) {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempTarget._id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> trList = getDaoTempTargets().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempTarget)) {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
}
}
getDaoTempTargets().create(tempTarget);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(TempTarget tempTarget) {
try {
getDaoTempTargets().delete(tempTarget);
scheduleTemporaryTargetChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange");
RxBus.INSTANCE.send(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemTargetPost != null)
scheduledTemTargetPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemTargetPost = tempTargetWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "58795998aa86647ba4d68ce7",
"enteredBy": "",
"eventType": "Temporary Target",
"reason": "Eating Soon",
"targetTop": 80,
"targetBottom": 80,
"duration": 120,
"created_at": "2017-01-13T22:50:00.782Z",
"carbs": null,
"insulin": null
}
*/
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try {
String units = JsonHelper.safeGetString(trJson, "units", Constants.MGDL);
TempTarget tempTarget = new TempTarget()
.date(trJson.getLong("mills"))
.duration(JsonHelper.safeGetInt(trJson, "duration"))
.low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
.high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
.reason(JsonHelper.safeGetString(trJson, "reason", ""))
._id(trJson.getString("_id"))
.source(Source.NIGHTSCOUT);
createOrUpdate(tempTarget);
} catch (JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteTempTargetById(String _id) {
TempTarget stored = findTempTargetById(_id);
if (stored != null) {
log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public TempTarget findTempTargetById(String _id) {
try {
QueryBuilder<TempTarget, Long> queryBuilder = getDaoTempTargets().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TempTarget> preparedQuery = queryBuilder.prepare();
List<TempTarget> list = getDaoTempTargets().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
// ----------------- DanaRHistory handling --------------------
public void createOrUpdate(DanaRHistoryRecord record) {
try {
getDaoDanaRHistory().createOrUpdate(record);
//If it is a TDD, store it for stats also.
if (record.recordCode == RecordTypes.RECORD_TYPE_DAILY) {
createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0));
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
List<DanaRHistoryRecord> historyList;
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
queryBuilder.orderBy("recordDate", false);
Where where = queryBuilder.where();
where.eq("recordCode", type);
queryBuilder.limit(200L);
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
historyList = getDaoDanaRHistory().query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
historyList = new ArrayList<>();
}
return historyList;
}
public void updateDanaRHistoryRecordId(JSONObject trJson) {
try {
QueryBuilder<DanaRHistoryRecord, String> queryBuilder = getDaoDanaRHistory().queryBuilder();
Where where = queryBuilder.where();
where.ge("bytes", trJson.get(DanaRNSHistorySync.DANARSIGNATURE));
PreparedQuery<DanaRHistoryRecord> preparedQuery = queryBuilder.prepare();
List<DanaRHistoryRecord> list = getDaoDanaRHistory().query(preparedQuery);
if (list.size() == 0) {
// Record does not exists. Ignore
} else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (L.isEnabled(L.DATABASE))
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record);
} else {
// already set
}
}
} catch (SQLException | JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
// ------------ TemporaryBasal handling ---------------
//return true if new record was created
public boolean createOrUpdate(TemporaryBasal tempBasal) {
try {
TemporaryBasal old;
tempBasal.date = roundDateToSec(tempBasal.date);
if (tempBasal.source == Source.PUMP) {
// check for changed from pump change in NS
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", tempBasal.pumpId);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false;
}
// search by date (in case its standard record that has become pump record)
QueryBuilder<TemporaryBasal, Long> queryBuilder2 = getDaoTemporaryBasal().queryBuilder();
Where where2 = queryBuilder2.where();
where2.eq("date", tempBasal.date);
PreparedQuery<TemporaryBasal> preparedQuery2 = queryBuilder2.prepare();
List<TemporaryBasal> trList2 = getDaoTemporaryBasal().query(preparedQuery2);
if (trList2.size() > 0) {
old = trList2.get(0);
old.copyFromPump(tempBasal);
old.source = Source.PUMP;
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
getDaoTemporaryBasal().update(old);
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return false;
}
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.NIGHTSCOUT) {
old = getDaoTemporaryBasal().queryForId(tempBasal.date);
if (old != null) {
if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute"
// so far ignore, do not convert back because it may not be accurate
return false;
}
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
return false;
}
// find by NS _id
if (tempBasal._id != null) {
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", tempBasal._id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(tempBasal)) {
long oldDate = old.date;
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
return true;
}
}
}
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(TemporaryBasal tempBasal) {
try {
getDaoTemporaryBasal().delete(tempBasal);
updateEarliestDataChange(tempBasal.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleTemporaryBasalChange();
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TemporaryBasal>();
}
public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long from, long to, boolean ascending) {
try {
List<TemporaryBasal> tempbasals;
QueryBuilder<TemporaryBasal, Long> queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", from, to);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
tempbasals = getDaoTemporaryBasal().query(preparedQuery);
return tempbasals;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<TemporaryBasal>();
}
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempBasalChange");
RxBus.INSTANCE.send(new EventReloadTempBasalData());
RxBus.INSTANCE.send(new EventTempBasalChange());
if (earliestDataChange != null)
RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledTemBasalsPost != null)
scheduledTemBasalsPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id": "59232e1ddd032d04218dab00",
"eventType": "Temp Basal",
"duration": 60,
"percent": -50,
"created_at": "2017-05-22T18:29:57Z",
"enteredBy": "AndroidAPS",
"notes": "Basal Temp Start 50% 60.0 min",
"NSCLIENT_ID": 1495477797863,
"mills": 1495477797000,
"mgdl": 194.5,
"endmills": 1495481397000
}
*/
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus()
.source(Source.NIGHTSCOUT)
.date(trJson.getLong("mills"))
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
.durationInMinutes(trJson.getInt("duration"))
.insulin(trJson.getDouble("originalExtendedAmount"))
._id(trJson.getString("_id"));
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
extendedBolus.durationInMinutes = 0;
extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id");
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
createOrUpdate(extendedBolus);
} else {
TemporaryBasal tempBasal = new TemporaryBasal()
.date(trJson.getLong("mills"))
.source(Source.NIGHTSCOUT)
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
if (trJson.has("duration")) {
tempBasal.durationInMinutes = trJson.getInt("duration");
}
if (trJson.has("percent")) {
tempBasal.percentRate = trJson.getInt("percent") + 100;
tempBasal.isAbsolute = false;
}
if (trJson.has("absolute")) {
tempBasal.absoluteRate = trJson.getDouble("absolute");
tempBasal.isAbsolute = true;
}
tempBasal._id = trJson.getString("_id");
createOrUpdate(tempBasal);
}
} catch (JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange();
}
}
public TemporaryBasal findTempBasalById(String _id) {
try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
queryBuilder = getDaoTemporaryBasal().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);
if (list.size() != 1) {
return null;
} else {
return list.get(0);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public TemporaryBasal findTempBasalByPumpId(Long pumpId) {
try {
QueryBuilder<TemporaryBasal, Long> queryBuilder = null;
queryBuilder = getDaoTemporaryBasal().queryBuilder();
queryBuilder.orderBy("date", false);
Where where = queryBuilder.where();
where.eq("pumpId", pumpId);
PreparedQuery<TemporaryBasal> preparedQuery = queryBuilder.prepare();
List<TemporaryBasal> list = getDaoTemporaryBasal().query(preparedQuery);
if (list.size() > 0)
return list.get(0);
else
return null;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
// ------------ ExtendedBolus handling ---------------
public boolean createOrUpdate(ExtendedBolus extendedBolus) {
try {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
ExtendedBolus old;
extendedBolus.date = roundDateToSec(extendedBolus.date);
if (extendedBolus.source == Source.PUMP) {
// if pumpId == 0 do not check for existing pumpId
// used with pumps without history
// and insight where record as added first without pumpId
// and then is record updated with pumpId
if (extendedBolus.pumpId == 0) {
getDaoExtendedBolus().createOrUpdate(extendedBolus);
} else {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("pumpId", extendedBolus.pumpId);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 1) {
log.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId);
return false;
}
getDaoExtendedBolus().createOrUpdate(extendedBolus);
}
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.NIGHTSCOUT) {
old = getDaoExtendedBolus().queryForId(extendedBolus.date);
if (old != null) {
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
return false;
}
// find by NS _id
if (extendedBolus._id != null) {
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", extendedBolus._id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> trList = getDaoExtendedBolus().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(extendedBolus)) {
long oldDate = old.date;
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
return true;
}
}
}
getDaoExtendedBolus().create(extendedBolus);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus);
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
try {
return getDaoExtendedBolus().queryBuilder()
.where().eq("pumpId", pumpId)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void delete(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().delete(extendedBolus);
updateEarliestDataChange(extendedBolus.date);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleExtendedBolusChange();
}
public List<ExtendedBolus> getExtendedBolusDataFromTime(long mills, boolean ascending) {
try {
List<ExtendedBolus> extendedBoluses;
QueryBuilder<ExtendedBolus, Long> queryBuilder = getDaoExtendedBolus().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
return extendedBoluses;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<ExtendedBolus>();
}
public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange();
}
}
public ExtendedBolus findExtendedBolusById(String _id) {
try {
QueryBuilder<ExtendedBolus, Long> queryBuilder = null;
queryBuilder = getDaoExtendedBolus().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ExtendedBolus> preparedQuery = queryBuilder.prepare();
List<ExtendedBolus> list = getDaoExtendedBolus().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
/*
{
"_id": "5924898d577eb0880e355337",
"eventType": "Combo Bolus",
"duration": 120,
"splitNow": 0,
"splitExt": 100,
"enteredinsulin": 1,
"relative": 1,
"created_at": "2017-05-23T19:12:14Z",
"enteredBy": "AndroidAPS",
"NSCLIENT_ID": 1495566734628,
"mills": 1495566734000,
"mgdl": 106
}
*/
public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(json);
if (extendedBolus != null)
createOrUpdate(extendedBolus);
}
private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange");
RxBus.INSTANCE.send(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledExtendedBolusPost != null)
scheduledExtendedBolusPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
}
// ------------ CareportalEvent handling ---------------
public void createOrUpdate(CareportalEvent careportalEvent) {
careportalEvent.date = careportalEvent.date - careportalEvent.date % 1000;
try {
getDaoCareportalEvents().createOrUpdate(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public void delete(CareportalEvent careportalEvent) {
try {
getDaoCareportalEvents().delete(careportalEvent);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
scheduleCareportalEventChange();
}
public CareportalEvent getCareportalEventFromTimestamp(long timestamp) {
try {
return getDaoCareportalEvents().queryForId(timestamp);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
@Nullable
public CareportalEvent getLastCareportalEvent(String event) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", false);
Where where = queryBuilder.where();
where.eq("eventType", event);
queryBuilder.limit(1L);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
if (careportalEvents.size() == 1)
return careportalEvents.get(0);
else
return null;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public List<CareportalEvent> getCareportalEventsFromTime(long mills, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<CareportalEvent> getCareportalEvents(long start, long end, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.between("date", start, end);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public void preprocessOpenAPSOfflineEvents(List<CareportalEvent> list) {
OverlappingIntervals offlineEvents = new OverlappingIntervals();
for (int i = 0; i < list.size(); i++) {
CareportalEvent event = list.get(i);
if (!event.eventType.equals(CareportalEvent.OPENAPSOFFLINE)) continue;
offlineEvents.add(event);
}
}
public List<CareportalEvent> getCareportalEventsFromTime(long mills, String type, boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where();
where.ge("date", mills).and().eq("eventType", type);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<CareportalEvent> getCareportalEvents(boolean ascending) {
try {
List<CareportalEvent> careportalEvents;
QueryBuilder<CareportalEvent, Long> queryBuilder = getDaoCareportalEvents().queryBuilder();
queryBuilder.orderBy("date", ascending);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
careportalEvents = getDaoCareportalEvents().query(preparedQuery);
preprocessOpenAPSOfflineEvents(careportalEvents);
return careportalEvents;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public void deleteCareportalEventById(String _id) {
try {
QueryBuilder<CareportalEvent, Long> queryBuilder;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
if (list.size() == 1) {
CareportalEvent record = list.get(0);
if (L.isEnabled(L.DATABASE))
log.debug("Removing CareportalEvent record from database: " + record.toString());
delete(record);
} else {
if (L.isEnabled(L.DATABASE))
log.debug("CareportalEvent not found database: " + _id);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public void createCareportalEventFromJsonIfNotExists(JSONObject trJson) {
try {
QueryBuilder<CareportalEvent, Long> queryBuilder;
queryBuilder = getDaoCareportalEvents().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", trJson.getString("_id")).or().eq("date", trJson.getLong("mills"));
PreparedQuery<CareportalEvent> preparedQuery = queryBuilder.prepare();
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
CareportalEvent careportalEvent;
if (list.size() == 0) {
careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT;
if (L.isEnabled(L.DATABASE))
log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
careportalEvent = list.get(0);
if (L.isEnabled(L.DATABASE))
log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
return;
}
careportalEvent.date = trJson.getLong("mills");
careportalEvent.eventType = trJson.getString("eventType");
careportalEvent.json = trJson.toString();
careportalEvent._id = trJson.getString("_id");
createOrUpdate(careportalEvent);
} catch (SQLException | JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange");
RxBus.INSTANCE.send(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledCareportalEventPost != null)
scheduledCareportalEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledCareportalEventPost = careportalEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
// ---------------- ProfileSwitch handling ---------------
public List<ProfileSwitch> getProfileSwitchData(boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<ProfileSwitch> getProfileSwitchEventsFromTime(long mills, boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
Where where = queryBuilder.where();
where.ge("date", mills);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public List<ProfileSwitch> getProfileSwitchEventsFromTime(long from, long to, boolean ascending) {
try {
Dao<ProfileSwitch, Long> daoProfileSwitch = getDaoProfileSwitch();
List<ProfileSwitch> profileSwitches;
QueryBuilder<ProfileSwitch, Long> queryBuilder = daoProfileSwitch.queryBuilder();
queryBuilder.orderBy("date", ascending);
queryBuilder.limit(100L);
Where where = queryBuilder.where();
where.between("date", from, to);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
profileSwitches = daoProfileSwitch.query(preparedQuery);
return profileSwitches;
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return new ArrayList<>();
}
public boolean createOrUpdate(ProfileSwitch profileSwitch) {
try {
ProfileSwitch old;
profileSwitch.date = roundDateToSec(profileSwitch.date);
if (profileSwitch.source == Source.NIGHTSCOUT) {
old = getDaoProfileSwitch().queryForId(profileSwitch.date);
if (old != null) {
if (!old.isEqual(profileSwitch)) {
profileSwitch.source = old.source;
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
return false;
}
// find by NS _id
if (profileSwitch._id != null) {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", profileSwitch._id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> trList = getDaoProfileSwitch().query(preparedQuery);
if (trList.size() > 0) {
old = trList.get(0);
if (!old.isEqual(profileSwitch)) {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
}
}
// look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch);
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return false;
}
public void delete(ProfileSwitch profileSwitch) {
try {
getDaoProfileSwitch().delete(profileSwitch);
scheduleProfileSwitchChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventProfileNeedsUpdate");
RxBus.INSTANCE.send(new EventReloadProfileSwitchData());
RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
scheduledProfileSwitchEventPost = null;
}
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
if (scheduledProfileSwitchEventPost != null)
scheduledProfileSwitchEventPost.cancel(false);
Runnable task = new PostRunnable();
final int sec = 1;
scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
}
/*
{
"_id":"592fa43ed97496a80da913d2",
"created_at":"2017-06-01T05:20:06Z",
"eventType":"Profile Switch",
"profile":"2016 +30%",
"units":"mmol",
"enteredBy":"sony",
"NSCLIENT_ID":1496294454309,
}
*/
public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
try {
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = trJson.getLong("mills");
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
profileSwitch._id = trJson.getString("_id");
profileSwitch.profileName = trJson.getString("profile");
profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
profileSwitch.source = Source.NIGHTSCOUT;
if (trJson.has("timeshift"))
profileSwitch.timeshift = trJson.getInt("timeshift");
if (trJson.has("percentage"))
profileSwitch.percentage = trJson.getInt("percentage");
if (trJson.has("profileJson"))
profileSwitch.profileJson = trJson.getString("profileJson");
else {
ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
if (profileInterface != null) {
ProfileStore store = profileInterface.getProfile();
if (store != null) {
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
if (L.isEnabled(L.DATABASE))
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
} else {
if (L.isEnabled(L.DATABASE))
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
if (L.isEnabled(L.DATABASE))
log.debug("No active profile interface. Ignoring: " + trJson.toString());
return;
}
}
if (trJson.has("profilePlugin"))
profileSwitch.profilePlugin = trJson.getString("profilePlugin");
createOrUpdate(profileSwitch);
} catch (JSONException e) {
log.error("Unhandled exception: " + trJson.toString(), e);
}
}
public void deleteProfileSwitchById(String _id) {
ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) {
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}
}
public ProfileSwitch findProfileSwitchById(String _id) {
try {
QueryBuilder<ProfileSwitch, Long> queryBuilder = getDaoProfileSwitch().queryBuilder();
Where where = queryBuilder.where();
where.eq("_id", _id);
PreparedQuery<ProfileSwitch> preparedQuery = queryBuilder.prepare();
List<ProfileSwitch> list = getDaoProfileSwitch().query(preparedQuery);
if (list.size() == 1) {
return list.get(0);
} else {
return null;
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
// ---------------- Insight history handling ---------------
public void createOrUpdate(InsightHistoryOffset offset) {
try {
getDaoInsightHistoryOffset().createOrUpdate(offset);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) {
try {
return getDaoInsightHistoryOffset().queryForId(pumpSerial);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightBolusID bolusID) {
try {
getDaoInsightBolusID().createOrUpdate(bolusID);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) {
try {
return getDaoInsightBolusID().queryBuilder()
.where().eq("pumpSerial", pumpSerial)
.and().eq("bolusID", bolusID)
.and().between("timestamp", timestamp - 259200000, timestamp + 259200000)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightPumpID pumpID) {
try {
getDaoInsightPumpID().createOrUpdate(pumpID);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) {
try {
return getDaoInsightPumpID().queryBuilder()
.orderBy("timestamp", false)
.where().eq("pumpSerial", pumpSerial)
.and().in("eventType", "PumpStopped", "PumpPaused")
.and().lt("timestamp", before)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
// ---------------- Food handling ---------------
}
| 1 | 31,963 | I don't know what the implications of this change are for pumps other than the insight but i would add `|| trList2.get(0).pumpId == temporaryBasal.pumpId` in case we see the same pump event again, in order to not duplicate it in the database. | MilosKozak-AndroidAPS | java |
@@ -29,8 +29,8 @@ type (
Address crypto.Digest
)
-// ChecksumAddress is a representation of the short address with a checksum
-type ChecksumAddress struct {
+// checksumAddress is a representation of the short address with a checksum
+type checksumAddress struct {
shortAddress Address
checksum []byte
} | 1 | // Copyright (C) 2019 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package basics
import (
"bytes"
"encoding/base32"
"fmt"
"github.com/algorand/go-algorand/crypto"
)
type (
// Address is a unique identifier corresponding to ownership of money
Address crypto.Digest
)
// ChecksumAddress is a representation of the short address with a checksum
type ChecksumAddress struct {
shortAddress Address
checksum []byte
}
const (
checksumLength = 4
)
// GetChecksumAddress returns the short address with its checksum as a string
// Checksum in Algorand are the last 4 bytes of the shortAddress Hash. H(Address)[28:]
func (addr Address) GetChecksumAddress() *ChecksumAddress {
shortAddressHash := crypto.Hash(addr[:])
return &ChecksumAddress{addr, shortAddressHash[len(shortAddressHash)-checksumLength:]}
}
// GetUserAddress returns the human-readable, checksummed version of the address
func (addr Address) GetUserAddress() string {
return addr.GetChecksumAddress().String()
}
// IsValid returns true if the address is valid, false otherwise
func (addr ChecksumAddress) IsValid() bool {
shortAddressHash := crypto.Hash(addr.shortAddress[:])
return bytes.Equal(shortAddressHash[len(shortAddressHash)-checksumLength:], addr.checksum)
}
// Address returns the address's Address
func (addr ChecksumAddress) Address() Address {
return addr.shortAddress
}
// UnmarshalChecksumAddress tries to unmarshal the checksummed address string.
func UnmarshalChecksumAddress(address string) (Address, error) {
decoded, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(address)
if err != nil {
return Address{}, fmt.Errorf("failed to decode address %s to base 32", address)
}
var short Address
if len(decoded) < len(short) {
return Address{}, fmt.Errorf("decoded bad address: %v", address)
}
copy(short[:], decoded[:len(short)])
checksumAddr := ChecksumAddress{short, decoded[len(decoded)-checksumLength:]}
if !checksumAddr.IsValid() {
return Address{}, fmt.Errorf("address %s is malformed, checksum verification failed", address)
}
// Validate that we had a canonical string representation
if checksumAddr.String() != address {
return Address{}, fmt.Errorf("address %s is non-canonical", address)
}
return short, nil
}
// String returns a string representation of ChecksumAddress
func (addr *ChecksumAddress) String() string {
var addrWithChecksum []byte
addrWithChecksum = append(addr.shortAddress[:], addr.checksum...)
return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(addrWithChecksum)
}
func (addr Address) String() string {
return fmt.Sprintf("%v", crypto.Digest(addr))
}
// MarshalText returns the address string as an array of bytes
func (addr Address) MarshalText() ([]byte, error) {
return []byte(addr.String()), nil
}
// UnmarshalText initializes the Address from an array of bytes.
func (addr *Address) UnmarshalText(text []byte) error {
d, err := crypto.DigestFromString(string(text))
if err == nil {
*addr = Address(d)
}
return err
}
| 1 | 35,458 | is there anything still referencing `checksumAddress` or can we just delete it? | algorand-go-algorand | go |
@@ -18,6 +18,7 @@ var (
// ClusterDeployment conditions that could indicate provisioning problems with a cluster
// First condition appearing True will be used in the metric labels.
provisioningDelayCondition = [...]hivev1.ClusterDeploymentConditionType{
+ hivev1.RequirementsMetCondition,
hivev1.DNSNotReadyCondition,
hivev1.InstallLaunchErrorCondition,
hivev1.ProvisionFailedCondition, | 1 | package metrics
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
hivev1 "github.com/openshift/hive/apis/hive/v1"
controllerutils "github.com/openshift/hive/pkg/controller/utils"
)
var (
// ClusterDeployment conditions that could indicate provisioning problems with a cluster
// First condition appearing True will be used in the metric labels.
provisioningDelayCondition = [...]hivev1.ClusterDeploymentConditionType{
hivev1.DNSNotReadyCondition,
hivev1.InstallLaunchErrorCondition,
hivev1.ProvisionFailedCondition,
hivev1.AuthenticationFailureClusterDeploymentCondition,
hivev1.InstallImagesNotResolvedCondition,
}
)
// provisioning underway metrics collected through a custom prometheus collector
type provisioningUnderwayCollector struct {
client client.Client
// minDuration, when non-zero, is the minimum duration afer which clusters provisioning
// will start becomming part of this metric. When set to zero, all clusters provisioning
// will be included in the metric.
minDuration time.Duration
// metricClusterDeploymentProvisionUnderwaySeconds is a prometheus metric for the number of seconds
// between when a still provisioning cluster was created and now.
metricClusterDeploymentProvisionUnderwaySeconds *prometheus.Desc
}
// collects the metrics for provisioningUnderwayCollector
func (cc provisioningUnderwayCollector) Collect(ch chan<- prometheus.Metric) {
ccLog := log.WithField("controller", "metrics")
ccLog.Info("calculating provisioning underway metrics across all ClusterDeployments")
// Load all ClusterDeployments so we can accumulate facts about them.
clusterDeployments := &hivev1.ClusterDeploymentList{}
err := cc.client.List(context.Background(), clusterDeployments)
if err != nil {
log.WithError(err).Error("error listing cluster deployments")
return
}
for _, cd := range clusterDeployments.Items {
if cd.DeletionTimestamp != nil {
continue
}
if cd.Spec.Installed {
continue
}
// Add install failure details for stuck provision
condition, reason := getKnownConditions(cd.Status.Conditions)
platform := cd.Labels[hivev1.HiveClusterPlatformLabel]
imageSet := "none"
if cd.Spec.Provisioning != nil && cd.Spec.Provisioning.ImageSetRef != nil {
imageSet = cd.Spec.Provisioning.ImageSetRef.Name
}
elapsedDuration := time.Since(cd.CreationTimestamp.Time)
if cc.minDuration.Seconds() > 0 && elapsedDuration < cc.minDuration {
continue // skip reporting the metric for clusterdeployment until the elapsed time is at least minDuration
}
// For installing clusters we report the seconds since the cluster was created.
ch <- prometheus.MustNewConstMetric(
cc.metricClusterDeploymentProvisionUnderwaySeconds,
prometheus.GaugeValue,
elapsedDuration.Seconds(),
cd.Name,
cd.Namespace,
GetClusterDeploymentType(&cd),
condition,
reason,
platform,
imageSet,
)
}
}
func (cc provisioningUnderwayCollector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(cc, ch)
}
var (
metricClusterDeploymentProvisionUnderwaySecondsDesc = prometheus.NewDesc(
"hive_cluster_deployment_provision_underway_seconds",
"Length of time a cluster has been provisioning.",
[]string{"cluster_deployment", "namespace", "cluster_type", "condition", "reason", "platform", "image_set"},
nil,
)
)
func newProvisioningUnderwaySecondsCollector(client client.Client, minimum time.Duration) prometheus.Collector {
return provisioningUnderwayCollector{
client: client,
metricClusterDeploymentProvisionUnderwaySeconds: metricClusterDeploymentProvisionUnderwaySecondsDesc,
minDuration: minimum,
}
}
// provisioning underway install restarts metrics collected through a custom prometheus collector
type provisioningUnderwayInstallRestartsCollector struct {
client client.Client
// minRestarts, when non-zero, is the minimum restarts after which clusters provisioning
// will start becoming part of the metric. When set to zero, all clusters provisioning
// will be included in the metric.
minRestarts int
// metricClusterDeploymentProvisionUnderwayInstallRestarts is a prometheus metric for the number of install
// restarts for a still provisioning cluster.
metricClusterDeploymentProvisionUnderwayInstallRestarts *prometheus.Desc
}
// collects the metrics for provisioningUnderwayInstallRestartsCollector
func (cc provisioningUnderwayInstallRestartsCollector) Collect(ch chan<- prometheus.Metric) {
ccLog := log.WithField("controller", "metrics")
ccLog.Info("calculating provisioning underway install restarts metrics across all ClusterDeployments")
// Load all ClusterDeployments so we can accumulate facts about them.
clusterDeployments := &hivev1.ClusterDeploymentList{}
err := cc.client.List(context.Background(), clusterDeployments)
if err != nil {
log.WithError(err).Error("error listing cluster deployments")
return
}
for _, cd := range clusterDeployments.Items {
if cd.DeletionTimestamp != nil {
continue
}
if cd.Spec.Installed {
continue
}
// Add install failure details for stuck provision
condition, reason := getKnownConditions(cd.Status.Conditions)
platform := cd.Labels[hivev1.HiveClusterPlatformLabel]
imageSet := "none"
if cd.Spec.Provisioning != nil && cd.Spec.Provisioning.ImageSetRef != nil {
imageSet = cd.Spec.Provisioning.ImageSetRef.Name
}
restarts := cd.Status.InstallRestarts
if restarts == 0 {
continue // skip reporting the metric for clusterdeployment that hasn't restarted at all
}
if cc.minRestarts > 0 && restarts < cc.minRestarts {
continue // skip reporting the metric for clusterdeployment until the InstallRestarts is at least minRestarts
}
// For installing clusters we report the seconds since the cluster was created.
ch <- prometheus.MustNewConstMetric(
cc.metricClusterDeploymentProvisionUnderwayInstallRestarts,
prometheus.GaugeValue,
float64(restarts),
cd.Name,
cd.Namespace,
GetClusterDeploymentType(&cd),
condition,
reason,
platform,
imageSet,
)
}
}
func (cc provisioningUnderwayInstallRestartsCollector) Describe(ch chan<- *prometheus.Desc) {
prometheus.DescribeByCollect(cc, ch)
}
var (
provisioningUnderwayInstallRestartsCollectorDesc = prometheus.NewDesc(
"hive_cluster_deployment_provision_underway_install_restarts",
"Number install restarts for a cluster that has been provisioning.",
[]string{"cluster_deployment", "namespace", "cluster_type", "condition", "reason", "platform", "image_set"},
nil,
)
)
func newProvisioningUnderwayInstallRestartsCollector(client client.Client, minimum int) prometheus.Collector {
return provisioningUnderwayInstallRestartsCollector{
client: client,
metricClusterDeploymentProvisionUnderwayInstallRestarts: provisioningUnderwayInstallRestartsCollectorDesc,
minRestarts: minimum,
}
}
func getKnownConditions(conditions []hivev1.ClusterDeploymentCondition) (condition, reason string) {
condition, reason = "Unknown", "Unknown"
for _, delayCondition := range provisioningDelayCondition {
if cdCondition := controllerutils.FindClusterDeploymentCondition(conditions,
delayCondition); cdCondition != nil {
if cdCondition.Status == corev1.ConditionTrue {
condition = string(delayCondition)
if cdCondition.Reason != "" {
reason = cdCondition.Reason
}
break
}
}
}
return condition, reason
}
| 1 | 19,221 | The reason I didn't suggest it before is because I didn't want alerts for every tried - but not updated provision, but I can see a value in it from OSD perspective | openshift-hive | go |
@@ -2,8 +2,10 @@ if Rails.env.production? || Rails.env.staging?
require 'rack/rewrite'
Rails.configuration.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
- r301 %r{.*}, "http://#{HOST}$&", if: Proc.new { |rack_env|
- rack_env['SERVER_NAME'] != "#{HOST}"
- }
+ r301(
+ %r{.*},
+ "http://#{ENV['APP_DOMAIN']}$&",
+ if: proc { |rack_env| rack_env['SERVER_NAME'] != "#{ENV['APP_DOMAIN']}" }
+ )
end
end | 1 | if Rails.env.production? || Rails.env.staging?
require 'rack/rewrite'
Rails.configuration.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do
r301 %r{.*}, "http://#{HOST}$&", if: Proc.new { |rack_env|
rack_env['SERVER_NAME'] != "#{HOST}"
}
end
end
| 1 | 10,331 | Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping. | thoughtbot-upcase | rb |
@@ -61,8 +61,12 @@ func GroupActions(actions []*Action) (beforeGets, getList, writeList, afterGets
agets := map[interface{}]*Action{}
cgets := map[interface{}]*Action{}
writes := map[interface{}]*Action{}
+ var nilkeys []*Action
for _, a := range actions {
- if a.Kind == Get {
+ if a.Key == nil {
+ // Probably a Create.
+ nilkeys = append(nilkeys, a)
+ } else if a.Kind == Get {
// If there was a prior write with this key, make sure this get
// happens after the writes.
if _, ok := writes[a.Key]; ok { | 1 | // Copyright 2019 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package driver
import (
"reflect"
"sort"
"sync"
"github.com/google/uuid"
)
// UniqueString generates a string that is unique with high probability.
// Driver implementations can use it to generate keys for Create actions.
func UniqueString() string { return uuid.New().String() }
// SplitActions divides the actions slice into sub-slices much like strings.Split.
// The split function should report whether two consecutive actions should be split,
// that is, should be in different sub-slices. The first argument to split is the
// last action of the sub-slice currently under construction; the second argument is
// the action being considered for addition to that sub-slice.
// SplitActions doesn't change the order of the input slice.
func SplitActions(actions []*Action, split func(a, b *Action) bool) [][]*Action {
var (
groups [][]*Action // the actions, split; the return value
cur []*Action // the group currently being constructed
)
collect := func() { // called when the current group is known to be finished
if len(cur) > 0 {
groups = append(groups, cur)
cur = nil
}
}
for _, a := range actions {
if len(cur) > 0 && split(cur[len(cur)-1], a) {
collect()
}
cur = append(cur, a)
}
collect()
return groups
}
// GroupActions separates actions into four sets: writes, gets that must happen before the writes,
// gets that must happen after the writes, and gets that can happen concurrently with the writes.
func GroupActions(actions []*Action) (beforeGets, getList, writeList, afterGets []*Action) {
// maps from key to action
bgets := map[interface{}]*Action{}
agets := map[interface{}]*Action{}
cgets := map[interface{}]*Action{}
writes := map[interface{}]*Action{}
for _, a := range actions {
if a.Kind == Get {
// If there was a prior write with this key, make sure this get
// happens after the writes.
if _, ok := writes[a.Key]; ok {
agets[a.Key] = a
} else {
cgets[a.Key] = a
}
} else {
// This is a write. A prior get on the same key was put into cgets; move
// it to bgets because it has to happen before writes.
if g, ok := cgets[a.Key]; ok {
delete(cgets, a.Key)
bgets[a.Key] = g
}
writes[a.Key] = a
}
}
vals := func(m map[interface{}]*Action) []*Action {
var as []*Action
for _, v := range m {
as = append(as, v)
}
// Sort so the order is always the same for replay.
sort.Slice(as, func(i, j int) bool { return as[i].Index < as[j].Index })
return as
}
return vals(bgets), vals(cgets), vals(writes), vals(agets)
}
// AsFunc creates and returns an "as function" that behaves as follows:
// If its argument is a pointer to the same type as val, the argument is set to val
// and the function returns true. Otherwise, the function returns false.
func AsFunc(val interface{}) func(interface{}) bool {
rval := reflect.ValueOf(val)
wantType := reflect.PtrTo(rval.Type())
return func(i interface{}) bool {
if i == nil {
return false
}
ri := reflect.ValueOf(i)
if ri.Type() != wantType {
return false
}
ri.Elem().Set(rval)
return true
}
}
// GroupByFieldPath collect the Get actions into groups with the same set of
// field paths.
func GroupByFieldPath(gets []*Action) [][]*Action {
// This is quadratic in the worst case, but it's unlikely that there would be
// many Gets with different field paths.
var groups [][]*Action
seen := map[*Action]bool{}
for len(seen) < len(gets) {
var g []*Action
for _, a := range gets {
if !seen[a] {
if len(g) == 0 || fpsEqual(g[0].FieldPaths, a.FieldPaths) {
g = append(g, a)
seen[a] = true
}
}
}
groups = append(groups, g)
}
return groups
}
// Report whether two lists of field paths are equal.
func fpsEqual(fps1, fps2 [][]string) bool {
// TODO?: We really care about sets of field paths, but that's too tedious to determine.
if len(fps1) != len(fps2) {
return false
}
for i, fp1 := range fps1 {
if !FieldPathsEqual(fp1, fps2[i]) {
return false
}
}
return true
}
// FieldPathsEqual reports whether two field paths are equal.
func FieldPathsEqual(fp1, fp2 []string) bool {
if len(fp1) != len(fp2) {
return false
}
for i, s1 := range fp1 {
if s1 != fp2[i] {
return false
}
}
return true
}
// FieldPathEqualsField reports whether a field path equals a field.
// This is a convenience for FieldPathsEqual(fp, []string{s}).
func FieldPathEqualsField(fp []string, s string) bool {
return len(fp) == 1 && fp[0] == s
}
// Throttle is used to limit the number of outstanding activities, like RPCs.
// It acts like a combination of a semaphore and a WaitGroup.
type Throttle struct {
c chan struct{} // token semaphore
wg sync.WaitGroup
}
// NewThrottle returns a Throttle that will allow max calls to Acquire that
// are not matched with Release calls before blocking.
// If max is <= 0, there is no throttling: Acquire always returns immediately.
func NewThrottle(max int) *Throttle {
t := &Throttle{}
if max > 0 {
t.c = make(chan struct{}, max)
}
return t
}
// Acquire blocks until a token is available, then acquires it and returns.
// Acquire is deliberately not sensitive to context.Context, because it assumes
// that whatever acquires a token will be context-sensitive, and thus will release
// the token when the context is done.
func (t *Throttle) Acquire() {
t.wg.Add(1)
if t.c != nil {
t.c <- struct{}{}
}
}
// Release releases a token obtained by Acquire.
func (t *Throttle) Release() {
if t.c != nil {
<-t.c
}
t.wg.Done()
}
// Wait blocks goroutine until the number of calls to Release matches the number of
// calls to Acquire.
func (t *Throttle) Wait() {
t.wg.Wait()
}
| 1 | 19,875 | I believe Key is not necessarily nil, it could be empty string. Probably better check a.Kind == Create | google-go-cloud | go |
@@ -89,7 +89,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
}
}
- public Task WriteAsync<T>(Func<PipeWriter, T, long> callback, T state)
+ public Task WriteAsync<T>(Func<PipeWriter, T, long> callback, T state, CancellationToken cancellationToken)
{
lock (_contextLock)
{ | 1 | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
{
public class Http1OutputProducer : IHttpOutputProducer
{
private static readonly ReadOnlyMemory<byte> _continueBytes = new ReadOnlyMemory<byte>(Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n"));
private static readonly byte[] _bytesHttpVersion11 = Encoding.ASCII.GetBytes("HTTP/1.1 ");
private static readonly byte[] _bytesEndHeaders = Encoding.ASCII.GetBytes("\r\n\r\n");
private static readonly ReadOnlyMemory<byte> _endChunkedResponseBytes = new ReadOnlyMemory<byte>(Encoding.ASCII.GetBytes("0\r\n\r\n"));
private readonly string _connectionId;
private readonly ConnectionContext _connectionContext;
private readonly ITimeoutControl _timeoutControl;
private readonly IKestrelTrace _log;
private readonly IBytesWrittenFeature _transportBytesWrittenFeature;
private readonly StreamSafePipeFlusher _flusher;
// This locks access to to all of the below fields
private readonly object _contextLock = new object();
private bool _completed = false;
private bool _aborted;
private long _unflushedBytes;
private long _totalBytesCommitted;
private readonly PipeWriter _pipeWriter;
public Http1OutputProducer(
PipeWriter pipeWriter,
string connectionId,
ConnectionContext connectionContext,
IKestrelTrace log,
ITimeoutControl timeoutControl,
IBytesWrittenFeature transportBytesWrittenFeature)
{
_pipeWriter = pipeWriter;
_connectionId = connectionId;
_connectionContext = connectionContext;
_timeoutControl = timeoutControl;
_log = log;
_transportBytesWrittenFeature = transportBytesWrittenFeature;
_flusher = new StreamSafePipeFlusher(pipeWriter, timeoutControl);
}
public Task WriteDataAsync(ReadOnlySpan<byte> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
return WriteAsync(buffer, cancellationToken);
}
public Task WriteStreamSuffixAsync()
{
return WriteAsync(_endChunkedResponseBytes.Span);
}
public Task FlushAsync(CancellationToken cancellationToken = default)
{
return WriteAsync(Constants.EmptyData, cancellationToken);
}
public void Write<T>(Func<PipeWriter, T, long> callback, T state)
{
lock (_contextLock)
{
if (_completed)
{
return;
}
var buffer = _pipeWriter;
var bytesCommitted = callback(buffer, state);
_unflushedBytes += bytesCommitted;
_totalBytesCommitted += bytesCommitted;
}
}
public Task WriteAsync<T>(Func<PipeWriter, T, long> callback, T state)
{
lock (_contextLock)
{
if (_completed)
{
return Task.CompletedTask;
}
var buffer = _pipeWriter;
var bytesCommitted = callback(buffer, state);
_unflushedBytes += bytesCommitted;
_totalBytesCommitted += bytesCommitted;
}
return FlushAsync();
}
public void WriteResponseHeaders(int statusCode, string reasonPhrase, HttpResponseHeaders responseHeaders)
{
lock (_contextLock)
{
if (_completed)
{
return;
}
var buffer = _pipeWriter;
var writer = new BufferWriter<PipeWriter>(buffer);
writer.Write(_bytesHttpVersion11);
var statusBytes = ReasonPhrases.ToStatusBytes(statusCode, reasonPhrase);
writer.Write(statusBytes);
responseHeaders.CopyTo(ref writer);
writer.Write(_bytesEndHeaders);
writer.Commit();
_unflushedBytes += writer.BytesCommitted;
_totalBytesCommitted += writer.BytesCommitted;
}
}
public void Dispose()
{
lock (_contextLock)
{
if (_completed)
{
return;
}
_log.ConnectionDisconnect(_connectionId);
_completed = true;
_pipeWriter.Complete();
var unsentBytes = _totalBytesCommitted - _transportBytesWrittenFeature.TotalBytesWritten;
if (unsentBytes > 0)
{
// unsentBytes should never be over 64KB in the default configuration.
_timeoutControl.StartTimingWrite((int)Math.Min(unsentBytes, int.MaxValue));
_pipeWriter.OnReaderCompleted((ex, state) => ((ITimeoutControl)state).StopTimingWrite(), _timeoutControl);
}
}
}
public void Abort(ConnectionAbortedException error)
{
// Abort can be called after Dispose if there's a flush timeout.
// It's important to still call _lifetimeFeature.Abort() in this case.
lock (_contextLock)
{
if (_aborted)
{
return;
}
_aborted = true;
_connectionContext.Abort(error);
if (!_completed)
{
_log.ConnectionDisconnect(_connectionId);
_completed = true;
_pipeWriter.Complete();
}
}
}
public Task Write100ContinueAsync()
{
return WriteAsync(_continueBytes.Span);
}
private Task WriteAsync(
ReadOnlySpan<byte> buffer,
CancellationToken cancellationToken = default)
{
lock (_contextLock)
{
if (_completed)
{
return Task.CompletedTask;
}
var writer = new BufferWriter<PipeWriter>(_pipeWriter);
if (buffer.Length > 0)
{
writer.Write(buffer);
_unflushedBytes += buffer.Length;
_totalBytesCommitted += buffer.Length;
}
writer.Commit();
var bytesWritten = _unflushedBytes;
_unflushedBytes = 0;
return _flusher.FlushAsync(bytesWritten, this, cancellationToken);
}
}
}
}
| 1 | 16,464 | This is only used for headers and therefore isn't used. | aspnet-KestrelHttpServer | .cs |
@@ -15,11 +15,13 @@ import (
// ProviderCommand defines the shell command to be run for one of the commands (db pull, etc.)
type ProviderCommand struct {
- Command string `yaml:"command"`
- Service string `yaml:"service,omitempty"`
+ Command string `yaml:"command"`
+ Service string `yaml:"service,omitempty"`
+ SkipImport bool `yaml:"skip_import"`
}
// ProviderInfo defines the provider
+// @todo: CodePullCommand unused
type ProviderInfo struct {
EnvironmentVariables map[string]string `yaml:"environment_variables"`
AuthCommand ProviderCommand `yaml:"auth_command"` | 1 | package ddevapp
import (
"github.com/drud/ddev/pkg/output"
"os"
"path/filepath"
"fmt"
"github.com/drud/ddev/pkg/fileutil"
"github.com/drud/ddev/pkg/util"
"gopkg.in/yaml.v2"
)
// ProviderCommand defines the shell command to be run for one of the commands (db pull, etc.)
type ProviderCommand struct {
Command string `yaml:"command"`
Service string `yaml:"service,omitempty"`
}
// ProviderInfo defines the provider
type ProviderInfo struct {
EnvironmentVariables map[string]string `yaml:"environment_variables"`
AuthCommand ProviderCommand `yaml:"auth_command"`
DBPullCommand ProviderCommand `yaml:"db_pull_command"`
FilesPullCommand ProviderCommand `yaml:"files_pull_command"`
CodePullCommand ProviderCommand `yaml:"code_pull_command,omitempty"`
DBPushCommand ProviderCommand `yaml:"db_push_command"`
FilesPushCommand ProviderCommand `yaml:"files_push_command"`
}
// Provider provides generic-specific import functionality.
type Provider struct {
ProviderType string `yaml:"provider"`
app *DdevApp `yaml:"-"`
ProviderInfo `yaml:"providers"`
}
// Init handles loading data from saved config.
func (p *Provider) Init(pType string, app *DdevApp) error {
p.app = app
configPath := app.GetConfigPath(filepath.Join("providers", pType+".yaml"))
if !fileutil.FileExists(configPath) {
return fmt.Errorf("no configuration exists for %s provider - it should be at %s", pType, configPath)
}
err := p.Read(configPath)
if err != nil {
return err
}
p.ProviderType = pType
app.ProviderInstance = p
return nil
}
// Pull performs an import of db and files
func (app *DdevApp) Pull(provider *Provider, skipDbArg bool, skipFilesArg bool, skipImportArg bool) error {
var err error
err = app.ProcessHooks("pre-pull")
if err != nil {
return fmt.Errorf("Failed to process pre-pull hooks: %v", err)
}
if app.SiteStatus() != SiteRunning {
util.Warning("Project is not currently running. Starting project before performing pull.")
err = app.Start()
if err != nil {
return err
}
}
if provider.AuthCommand.Command != "" {
output.UserOut.Print("Authenticating...")
err := provider.app.ExecOnHostOrService(provider.AuthCommand.Service, provider.injectedEnvironment()+"; "+provider.AuthCommand.Command)
if err != nil {
return err
}
}
if skipDbArg {
output.UserOut.Println("Skipping database pull.")
} else {
output.UserOut.Println("Downloading database...")
fileLocation, importPath, err := provider.GetBackup("database")
if err != nil {
return err
}
err = app.MutagenSyncFlush()
if err != nil {
return err
}
output.UserOut.Printf("Database downloaded to: %s", fileLocation)
if skipImportArg {
output.UserOut.Println("Skipping database import.")
} else {
output.UserOut.Println("Importing database...")
err = app.ImportDB(fileLocation, importPath, true, false, "db")
if err != nil {
return err
}
}
}
if skipFilesArg {
output.UserOut.Println("Skipping files pull.")
} else {
output.UserOut.Println("Downloading files...")
fileLocation, importPath, err := provider.GetBackup("files")
if err != nil {
return err
}
err = app.MutagenSyncFlush()
if err != nil {
return err
}
output.UserOut.Printf("Files downloaded to: %s", fileLocation)
if skipImportArg {
output.UserOut.Println("Skipping files import.")
} else {
output.UserOut.Println("Importing files...")
err = app.ImportFiles(fileLocation, importPath)
if err != nil {
return err
}
}
}
err = app.ProcessHooks("post-pull")
if err != nil {
return fmt.Errorf("Failed to process post-pull hooks: %v", err)
}
return nil
}
// Push pushes db and files up to upstream hosting provider
func (app *DdevApp) Push(provider *Provider, skipDbArg bool, skipFilesArg bool) error {
var err error
err = app.ProcessHooks("pre-push")
if err != nil {
return fmt.Errorf("Failed to process pre-push hooks: %v", err)
}
if app.SiteStatus() != SiteRunning {
util.Warning("Project is not currently running. Starting project before performing push.")
err = app.Start()
if err != nil {
return err
}
}
if provider.AuthCommand.Command != "" {
output.UserOut.Print("Authenticating...")
err := provider.app.ExecOnHostOrService(provider.AuthCommand.Service, provider.injectedEnvironment()+"; "+provider.AuthCommand.Command)
if err != nil {
return err
}
}
if skipDbArg {
output.UserOut.Println("Skipping database push.")
} else {
output.UserOut.Println("Uploading database...")
err = provider.UploadDB()
if err != nil {
return err
}
output.UserOut.Printf("Database uploaded")
}
if skipFilesArg {
output.UserOut.Println("Skipping files push.")
} else {
output.UserOut.Println("Uploading files...")
err = provider.UploadFiles()
if err != nil {
return err
}
output.UserOut.Printf("Files uploaded")
}
err = app.ProcessHooks("post-push")
if err != nil {
return fmt.Errorf("Failed to process post-push hooks: %v", err)
}
return nil
}
// GetBackup will create and download a backup
// Valid values for backupType are "database" or "files".
// returns fileURL, importPath, error
func (p *Provider) GetBackup(backupType string) (string, string, error) {
var err error
var filePath string
if backupType != "database" && backupType != "files" {
return "", "", fmt.Errorf("could not get backup: %s is not a valid backup type", backupType)
}
// Set the import path blank to use the root of the archive by default.
importPath := ""
p.prepDownloadDir()
switch backupType {
case "database":
filePath, err = p.getDatabaseBackup()
case "files":
filePath, err = p.getFilesBackup()
default:
return "", "", fmt.Errorf("could not get backup: %s is not a valid backup type", backupType)
}
if err != nil {
return "", "", err
}
return filePath, importPath, nil
}
// UploadDB is used by Push to push the database to hosting provider
func (p *Provider) UploadDB() error {
_ = os.RemoveAll(p.getDownloadDir())
_ = os.Mkdir(p.getDownloadDir(), 0755)
if p.DBPushCommand.Command == "" {
util.Warning("No DBPushCommand is defined for provider %s", p.ProviderType)
return nil
}
err := p.app.ExportDB(p.app.GetConfigPath(".downloads/db.sql.gz"), true, "")
if err != nil {
return err
}
s := p.DBPushCommand.Service
if s == "" {
s = "web"
}
err = p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.DBPushCommand.Command)
if err != nil {
util.Failed("Failed to exec %s on %s: %v", p.DBPushCommand.Command, s, err)
}
return nil
}
// UploadFiles is used by Push to push the user-generated files to the hosting provider
func (p *Provider) UploadFiles() error {
_ = os.RemoveAll(p.getDownloadDir())
_ = os.Mkdir(p.getDownloadDir(), 0755)
if p.FilesPullCommand.Command == "" {
util.Warning("No FilesPushCommand is defined for provider %s", p.ProviderType)
return nil
}
s := p.FilesPushCommand.Service
if s == "" {
s = "web"
}
err := p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.FilesPushCommand.Command)
if err != nil {
util.Failed("Failed to exec %s on %s: %v", p.FilesPushCommand.Command, s, err)
}
return nil
}
// prepDownloadDir ensures the download cache directories are created and writeable.
func (p *Provider) prepDownloadDir() {
destDir := p.getDownloadDir()
filesDir := filepath.Join(destDir, "files")
_ = os.RemoveAll(destDir)
err := os.MkdirAll(filesDir, 0755)
util.CheckErr(err)
}
func (p *Provider) getDownloadDir() string {
destDir := p.app.GetConfigPath(".downloads")
return destDir
}
func (p *Provider) getFilesBackup() (filename string, error error) {
destDir := filepath.Join(p.getDownloadDir(), "files")
_ = os.RemoveAll(destDir)
_ = os.MkdirAll(destDir, 0755)
s := p.FilesPullCommand.Service
if s == "" {
s = "web"
}
err := p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.FilesPullCommand.Command)
if err != nil {
util.Failed("Failed to exec %s on %s: %v", p.FilesPullCommand.Command, s, err)
}
return filepath.Join(p.getDownloadDir(), "files"), nil
}
// getDatabaseBackup retrieves database using `generic backup database`, then
// describe until it appears, then download it.
func (p *Provider) getDatabaseBackup() (filename string, error error) {
_ = os.RemoveAll(p.getDownloadDir())
_ = os.Mkdir(p.getDownloadDir(), 0755)
if p.DBPullCommand.Command == "" {
util.Warning("No DBPullCommand is defined for provider")
return "", nil
}
s := p.DBPullCommand.Service
if s == "" {
s = "web"
}
err := p.app.ExecOnHostOrService(s, p.injectedEnvironment()+"; "+p.DBPullCommand.Command)
if err != nil {
return "", fmt.Errorf("Failed to exec %s on %s: %v", p.DBPullCommand.Command, s, err)
}
return filepath.Join(p.getDownloadDir(), "db.sql.gz"), nil
}
// Write the generic provider configuration to a specified location on disk.
func (p *Provider) Write(configPath string) error {
return nil
}
// Read generic provider configuration from a specified location on disk.
func (p *Provider) Read(configPath string) error {
source, err := os.ReadFile(configPath)
if err != nil {
return err
}
// Read config values from file.
err = yaml.Unmarshal(source, &p.ProviderInfo)
if err != nil {
return err
}
return nil
}
// Validate ensures that the current configuration is valid (i.e. the configured pantheon site/environment exists)
func (p *Provider) Validate() error {
return nil
}
// injectedEnvironment() returns a string with environment variables that should be injected
// before a command.
func (p *Provider) injectedEnvironment() string {
s := "export "
for k, v := range p.EnvironmentVariables {
s = s + fmt.Sprintf(" %s=%s ", k, v)
}
return s
}
| 1 | 15,667 | Wouldn't it make sense to add a files_import_command and a db_import_command, which could be empty? I guess that leads to potential backward-compatibility problems, but it's worth thinking about. Perhaps add an import-api version to solve that? Overall, I think the actual db import logic and files import logic should be moved into the yaml file. What you you think of that? | drud-ddev | php |
@@ -0,0 +1,15 @@
+// DO NOT EDIT: This file is autogenerated via the builtin command.
+
+package csv
+
+import ast "github.com/influxdata/flux/ast"
+
+var FluxTestPackages = []*ast.Package{&ast.Package{
+ BaseNode: ast.BaseNode{
+ Errors: nil,
+ Loc: nil,
+ },
+ Files: []*ast.File{},
+ Package: "csv_test",
+ Path: "csv",
+}} | 1 | 1 | 15,740 | Why do we have this here? I'm not concerned about it really, just curious. | influxdata-flux | go |
|
@@ -28,11 +28,11 @@ import (
type DeltaAction uint64
const (
- // SetBytesAction indicates that a TEAL byte slice should be stored at a key
- SetBytesAction DeltaAction = 1
-
// SetUintAction indicates that a Uint should be stored at a key
- SetUintAction DeltaAction = 2
+ SetUintAction DeltaAction = 1
+
+ // SetBytesAction indicates that a TEAL byte slice should be stored at a key
+ SetBytesAction DeltaAction = 2
// DeleteAction indicates that the value for a particular key should be deleted
DeleteAction DeltaAction = 3 | 1 | // Copyright (C) 2019-2020 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package basics
import (
"encoding/hex"
"fmt"
"github.com/algorand/go-algorand/config"
)
// DeltaAction is an enum of actions that may be performed when applying a
// delta to a TEAL key/value store
type DeltaAction uint64
const (
// SetBytesAction indicates that a TEAL byte slice should be stored at a key
SetBytesAction DeltaAction = 1
// SetUintAction indicates that a Uint should be stored at a key
SetUintAction DeltaAction = 2
// DeleteAction indicates that the value for a particular key should be deleted
DeleteAction DeltaAction = 3
)
// ValueDelta links a DeltaAction with a value to be set
type ValueDelta struct {
_struct struct{} `codec:",omitempty,omitemptyarray"`
Action DeltaAction `codec:"at"`
Bytes string `codec:"bs"`
Uint uint64 `codec:"ui"`
}
// ToTealValue converts a ValueDelta into a TealValue if possible, and returns
// ok = false with a value of 0 TealUint if the conversion is not possible.
func (vd *ValueDelta) ToTealValue() (value TealValue, ok bool) {
switch vd.Action {
case SetBytesAction:
value.Type = TealBytesType
value.Bytes = vd.Bytes
ok = true
case SetUintAction:
value.Type = TealUintType
value.Uint = vd.Uint
ok = true
case DeleteAction:
value.Type = TealUintType
ok = false
default:
value.Type = TealUintType
ok = false
}
return value, ok
}
// StateDelta is a map from key/value store keys to ValueDeltas, indicating
// what should happen for that key
//msgp:allocbound StateDelta config.MaxStateDeltaKeys
type StateDelta map[string]ValueDelta
// Equal checks whether two StateDeltas are equal. We don't check for nilness
// equality because an empty map will encode/decode as nil. So if our generated
// map is empty but not nil, we want to equal a decoded nil off the wire.
func (sd StateDelta) Equal(o StateDelta) bool {
// Lengths should be the same
if len(sd) != len(o) {
return false
}
// All keys and deltas should be the same
for k, v := range sd {
// Other StateDelta must contain key
ov, ok := o[k]
if !ok {
return false
}
// Other StateDelta must have same value for key
if ov != v {
return false
}
}
return true
}
// Valid checks whether the keys and values in a StateDelta conform to the
// consensus parameters' maximum lengths
func (sd StateDelta) Valid(proto *config.ConsensusParams) error {
if len(sd) > 0 && proto.MaxAppKeyLen == 0 {
return fmt.Errorf("delta not empty, but proto.MaxAppKeyLen is 0 (why did we make a delta?)")
}
for key, delta := range sd {
if len(key) > proto.MaxAppKeyLen {
return fmt.Errorf("key too long: length was %d, maximum is %d", len(key), proto.MaxAppKeyLen)
}
switch delta.Action {
case SetBytesAction:
if len(delta.Bytes) > proto.MaxAppBytesValueLen {
return fmt.Errorf("cannot set value for key 0x%x, too long: length was %d, maximum is %d", key, len(delta.Bytes), proto.MaxAppBytesValueLen)
}
case SetUintAction:
case DeleteAction:
default:
return fmt.Errorf("unknown delta action: %v", delta.Action)
}
}
return nil
}
// EvalDelta stores StateDeltas for an application's global key/value store, as
// well as StateDeltas for some number of accounts holding local state for that
// application
type EvalDelta struct {
_struct struct{} `codec:",omitempty,omitemptyarray"`
GlobalDelta StateDelta `codec:"gd"`
// When decoding EvalDeltas, the integer key represents an offset into
// [txn.Sender, txn.Accounts[0], txn.Accounts[1], ...]
LocalDeltas map[uint64]StateDelta `codec:"ld,allocbound=config.MaxEvalDeltaAccounts"`
}
// Equal compares two EvalDeltas and returns whether or not they are
// equivalent. It does not care about nilness equality of LocalDeltas,
// because the msgpack codec will encode/decode an empty map as nil, and we want
// an empty generated EvalDelta to equal an empty one we decode off the wire.
func (ed EvalDelta) Equal(o EvalDelta) bool {
// LocalDeltas length should be the same
if len(ed.LocalDeltas) != len(o.LocalDeltas) {
return false
}
// All keys and local StateDeltas should be the same
for k, v := range ed.LocalDeltas {
// Other LocalDelta must have value for key
ov, ok := o.LocalDeltas[k]
if !ok {
return false
}
// Other LocalDelta must have same value for key
if !ov.Equal(v) {
return false
}
}
// GlobalDeltas must be equal
if !ed.GlobalDelta.Equal(o.GlobalDelta) {
return false
}
return true
}
// StateSchema sets maximums on the number of each type that may be stored
type StateSchema struct {
_struct struct{} `codec:",omitempty,omitemptyarray"`
NumUint uint64 `codec:"nui"`
NumByteSlice uint64 `codec:"nbs"`
}
// AddSchema adds two StateSchemas together
func (sm StateSchema) AddSchema(osm StateSchema) (out StateSchema) {
out.NumUint = AddSaturate(sm.NumUint, osm.NumUint)
out.NumByteSlice = AddSaturate(sm.NumByteSlice, osm.NumByteSlice)
return
}
// SubSchema subtracts one StateSchema from another
func (sm StateSchema) SubSchema(osm StateSchema) (out StateSchema) {
out.NumUint = SubSaturate(sm.NumUint, osm.NumUint)
out.NumByteSlice = SubSaturate(sm.NumByteSlice, osm.NumByteSlice)
return
}
// NumEntries counts the total number of values that may be stored for particular schema
func (sm StateSchema) NumEntries() (tot uint64) {
tot = AddSaturate(tot, sm.NumUint)
tot = AddSaturate(tot, sm.NumByteSlice)
return tot
}
// MinBalance computes the MinBalance requirements for a StateSchema based on
// the consensus parameters
func (sm StateSchema) MinBalance(proto *config.ConsensusParams) (res MicroAlgos) {
// Flat cost for each key/value pair
flatCost := MulSaturate(proto.SchemaMinBalancePerEntry, sm.NumEntries())
// Cost for uints
uintCost := MulSaturate(proto.SchemaUintMinBalance, sm.NumUint)
// Cost for byte slices
bytesCost := MulSaturate(proto.SchemaBytesMinBalance, sm.NumByteSlice)
// Sum the separate costs
var min uint64
min = AddSaturate(min, flatCost)
min = AddSaturate(min, uintCost)
min = AddSaturate(min, bytesCost)
res.Raw = min
return res
}
// TealType is an enum of the types in a TEAL program: Bytes and Uint
type TealType uint64
const (
// TealBytesType represents the type of a byte slice in a TEAL program
TealBytesType TealType = 1
// TealUintType represents the type of a uint in a TEAL program
TealUintType TealType = 2
)
func (tt TealType) String() string {
switch tt {
case TealBytesType:
return "b"
case TealUintType:
return "u"
}
return "?"
}
// TealValue contains type information and a value, representing a value in a
// TEAL program
type TealValue struct {
_struct struct{} `codec:",omitempty,omitemptyarray"`
Type TealType `codec:"tt"`
Bytes string `codec:"tb"`
Uint uint64 `codec:"ui"`
}
// ToValueDelta creates ValueDelta from TealValue
func (tv *TealValue) ToValueDelta() (vd ValueDelta) {
if tv.Type == TealUintType {
vd.Action = SetUintAction
vd.Uint = tv.Uint
} else {
vd.Action = SetBytesAction
vd.Bytes = tv.Bytes
}
return
}
func (tv *TealValue) String() string {
if tv.Type == TealBytesType {
return hex.EncodeToString([]byte(tv.Bytes))
}
return fmt.Sprintf("%d", tv.Uint)
}
// TealKeyValue represents a key/value store for use in an application's
// LocalState or GlobalState
//msgp:allocbound TealKeyValue encodedMaxKeyValueEntries
type TealKeyValue map[string]TealValue
// Clone returns a copy of a TealKeyValue that may be modified without
// affecting the original
func (tk TealKeyValue) Clone() TealKeyValue {
if tk == nil {
return nil
}
res := make(TealKeyValue, len(tk))
for k, v := range tk {
res[k] = v
}
return res
}
// ToStateSchema calculates the number of each value type in a TealKeyValue and
// reprsents the result as a StateSchema
func (tk TealKeyValue) ToStateSchema() (schema StateSchema, err error) {
for _, value := range tk {
switch value.Type {
case TealBytesType:
schema.NumByteSlice++
case TealUintType:
schema.NumUint++
default:
err = fmt.Errorf("unknown type %v", value.Type)
return StateSchema{}, err
}
}
return schema, nil
}
// SatisfiesSchema returns an error indicating whether or not a particular
// TealKeyValue store meets the requirements set by a StateSchema on how
// many values of each type are allowed
func (tk TealKeyValue) SatisfiesSchema(schema StateSchema) error {
calc, err := tk.ToStateSchema()
if err != nil {
return err
}
// Check against the schema
if calc.NumUint > schema.NumUint {
return fmt.Errorf("store integer count %d exceeds schema integer count %d", calc.NumUint, schema.NumUint)
}
if calc.NumByteSlice > schema.NumByteSlice {
return fmt.Errorf("store bytes count %d exceeds schema bytes count %d", calc.NumByteSlice, schema.NumByteSlice)
}
return nil
}
| 1 | 39,833 | @justicz Why are these switched here? | algorand-go-algorand | go |
@@ -0,0 +1,7 @@
+describe 'GET /help' do
+ it "displays successfully" do
+ get '/help'
+ expect(response.status).to eq(200)
+ expect(response.body).to include('FAQ')
+ end
+end | 1 | 1 | 13,289 | Maybe verify that an anchor was created -- that the markdown was processed? | 18F-C2 | rb |
|
@@ -64,7 +64,7 @@ public abstract class TwoPhaseIterator {
TwoPhaseIteratorAsDocIdSetIterator(TwoPhaseIterator twoPhaseIterator) {
this.twoPhaseIterator = twoPhaseIterator;
- this.approximation = twoPhaseIterator.approximation;
+ this.approximation = twoPhaseIterator.approximation();
}
@Override | 1 | /*
* 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.lucene.search;
import java.io.IOException;
import java.util.Objects;
/**
* Returned by {@link Scorer#twoPhaseIterator()}
* to expose an approximation of a {@link DocIdSetIterator}.
* When the {@link #approximation()}'s
* {@link DocIdSetIterator#nextDoc()} or {@link DocIdSetIterator#advance(int)}
* return, {@link #matches()} needs to be checked in order to know whether the
* returned doc ID actually matches.
* @lucene.experimental
*/
public abstract class TwoPhaseIterator {
protected final DocIdSetIterator approximation;
/** Takes the approximation to be returned by {@link #approximation}. Not null. */
protected TwoPhaseIterator(DocIdSetIterator approximation) {
this.approximation = Objects.requireNonNull(approximation);
}
/** Return a {@link DocIdSetIterator} view of the provided
* {@link TwoPhaseIterator}. */
public static DocIdSetIterator asDocIdSetIterator(TwoPhaseIterator twoPhaseIterator) {
return new TwoPhaseIteratorAsDocIdSetIterator(twoPhaseIterator);
}
/**
* If the given {@link DocIdSetIterator} has been created with
* {@link #asDocIdSetIterator}, then this will return the wrapped
* {@link TwoPhaseIterator}. Otherwise this returns {@code null}.
*/
public static TwoPhaseIterator unwrap(DocIdSetIterator iterator) {
if (iterator instanceof TwoPhaseIteratorAsDocIdSetIterator) {
return ((TwoPhaseIteratorAsDocIdSetIterator) iterator).twoPhaseIterator;
} else {
return null;
}
}
private static class TwoPhaseIteratorAsDocIdSetIterator extends DocIdSetIterator {
final TwoPhaseIterator twoPhaseIterator;
final DocIdSetIterator approximation;
TwoPhaseIteratorAsDocIdSetIterator(TwoPhaseIterator twoPhaseIterator) {
this.twoPhaseIterator = twoPhaseIterator;
this.approximation = twoPhaseIterator.approximation;
}
@Override
public int docID() {
return approximation.docID();
}
@Override
public int nextDoc() throws IOException {
return doNext(approximation.nextDoc());
}
@Override
public int advance(int target) throws IOException {
return doNext(approximation.advance(target));
}
private int doNext(int doc) throws IOException {
for (;; doc = approximation.nextDoc()) {
if (doc == NO_MORE_DOCS) {
return NO_MORE_DOCS;
} else if (twoPhaseIterator.matches()) {
return doc;
}
}
}
@Override
public long cost() {
return approximation.cost();
}
}
/** Return an approximation. The returned {@link DocIdSetIterator} is a
* superset of the matching documents, and each match needs to be confirmed
* with {@link #matches()} in order to know whether it matches or not. */
public DocIdSetIterator approximation() {
return approximation;
}
/** Return whether the current doc ID that {@link #approximation()} is on matches. This
* method should only be called when the iterator is positioned -- ie. not
* when {@link DocIdSetIterator#docID()} is {@code -1} or
* {@link DocIdSetIterator#NO_MORE_DOCS} -- and at most once. */
public abstract boolean matches() throws IOException;
/** An estimate of the expected cost to determine that a single document {@link #matches()}.
* This can be called before iterating the documents of {@link #approximation()}.
* Returns an expected cost in number of simple operations like addition, multiplication,
* comparing two numbers and indexing an array.
* The returned value must be positive.
*/
public abstract float matchCost();
}
| 1 | 31,940 | Is this just a minor improvement or is it necessary? If just some minor improvement, I recommend you don't touch Lucene in a Solr PR. | apache-lucene-solr | java |
@@ -63,7 +63,4 @@ public interface ReadOnlyPDClient {
/** Close underlining resources */
void close() throws InterruptedException;
-
- /** Get associated session * @return the session associated to client */
- TiSession getSession();
} | 1 | /*
* Copyright 2017 PingCAP, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pingcap.tikv;
import com.google.protobuf.ByteString;
import com.pingcap.tikv.meta.TiTimestamp;
import com.pingcap.tikv.region.TiRegion;
import com.pingcap.tikv.util.BackOffer;
import java.util.concurrent.Future;
import org.tikv.kvproto.Metapb.Store;
/** Readonly PD client including only reading related interface Supposed for TiDB-like use cases */
public interface ReadOnlyPDClient {
/**
* Get Timestamp from Placement Driver
*
* @return a timestamp object
*/
TiTimestamp getTimestamp(BackOffer backOffer);
/**
* Get Region from PD by key specified
*
* @param key key in bytes for locating a region
* @return the region whose startKey and endKey range covers the given key
*/
TiRegion getRegionByKey(BackOffer backOffer, ByteString key);
Future<TiRegion> getRegionByKeyAsync(BackOffer backOffer, ByteString key);
/**
* Get Region by Region Id
*
* @param id Region Id
* @return the region corresponding to the given Id
*/
TiRegion getRegionByID(BackOffer backOffer, long id);
Future<TiRegion> getRegionByIDAsync(BackOffer backOffer, long id);
/**
* Get Store by StoreId
*
* @param storeId StoreId
* @return the Store corresponding to the given Id
*/
Store getStore(BackOffer backOffer, long storeId);
Future<Store> getStoreAsync(BackOffer backOffer, long storeId);
/** Close underlining resources */
void close() throws InterruptedException;
/** Get associated session * @return the session associated to client */
TiSession getSession();
}
| 1 | 9,203 | why delete this method? | pingcap-tispark | java |
@@ -15,13 +15,17 @@
package com.google.api.codegen.transformer;
import com.google.api.codegen.config.MethodContext;
+import com.google.api.codegen.config.OutputContext;
import com.google.api.codegen.metacode.InitCodeNode;
import com.google.api.codegen.viewmodel.CallingForm;
import com.google.api.codegen.viewmodel.ImportSectionView;
-import com.google.api.codegen.viewmodel.OutputView;
import java.util.Collections;
-import java.util.List;
+/**
+ * An implementation of SampleImportTransformer. Subclasses of this class can choose to override
+ * `addSampleBodyImports`, `addOutputImports` and `addInitCodeImports` to save language-specific
+ * types to the type table. Currently used by Java.
+ */
public class StandardSampleImportTransformer implements SampleImportTransformer {
private final ImportSectionTransformer importSectionTransformer; | 1 | /* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.codegen.transformer;
import com.google.api.codegen.config.MethodContext;
import com.google.api.codegen.metacode.InitCodeNode;
import com.google.api.codegen.viewmodel.CallingForm;
import com.google.api.codegen.viewmodel.ImportSectionView;
import com.google.api.codegen.viewmodel.OutputView;
import java.util.Collections;
import java.util.List;
public class StandardSampleImportTransformer implements SampleImportTransformer {
private final ImportSectionTransformer importSectionTransformer;
public StandardSampleImportTransformer(ImportSectionTransformer importSectionTransformer) {
this.importSectionTransformer = importSectionTransformer;
}
public void addSampleBodyImports(MethodContext context, CallingForm form) {
// default behavior: no types used in the sample body need to be imported
}
public void addOutputImports(MethodContext context, List<OutputView> views) {
// default behavior: no types used in the output part of a sample need to be imported
}
public void addInitCodeImports(
MethodContext context, ImportTypeTable initCodeTypeTable, Iterable<InitCodeNode> nodes) {
// by default, copy over all types from initCodeTypeTable
initCodeTypeTable
.getImports()
.values()
.forEach(t -> context.getTypeTable().getAndSaveNicknameFor(t));
}
public ImportSectionView generateImportSection(MethodContext context) {
return importSectionTransformer.generateImportSection(
context, Collections.<InitCodeNode>emptyList());
}
}
| 1 | 29,015 | Does this transform only the `MethodContext`, or also the `OutputContext`? (Looking at the other files, I gather it's the latter.) Might be helpful to mention that here. | googleapis-gapic-generator | java |
@@ -1,15 +1,17 @@
# A part of NonVisual Desktop Access (NVDA)
-# Copyright (C) 2009-2018 NV Access Limited, Aleksey Sadovoy, James Teh, Joseph Lee, Tuukka Ojala
+# Copyright (C) 2009-2020 NV Access Limited, Aleksey Sadovoy, James Teh, Joseph Lee, Tuukka Ojala
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.htmlimport appModuleHandler
import calendar
import collections
import time
-
import api
import appModuleHandler
+from NVDAObjects.IAccessible import getNVDAObjectFromEvent
import ui
+import windowUtils
+import winUser
# A named tuple for holding the elapsed and total playing times from Foobar2000's status bar
statusBarTimes = collections.namedtuple('StatusBarTimes', ['elapsed', 'total']) | 1 | # A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2009-2018 NV Access Limited, Aleksey Sadovoy, James Teh, Joseph Lee, Tuukka Ojala
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.htmlimport appModuleHandler
import calendar
import collections
import time
import api
import appModuleHandler
import ui
# A named tuple for holding the elapsed and total playing times from Foobar2000's status bar
statusBarTimes = collections.namedtuple('StatusBarTimes', ['elapsed', 'total'])
def getParsingFormat(interval):
"""Attempts to find a suitable parsing format string for a HH:MM:SS, MM:SS or SS -style time interval."""
timeParts = len(interval.split(":"))
if timeParts == 1:
return "%S"
elif timeParts == 2:
return "%M:%S"
elif timeParts == 3:
return "%H:%M:%S"
else:
return None
def getOutputFormat(seconds):
"""Returns a format string for the given number of seconds with the least leading zeros."""
if seconds < 60:
return "%S"
elif seconds < 3600:
return "%M:%S"
else:
return "%H:%M:%S"
def parseIntervalToTimestamp(interval):
"""Parses a HH:MM:SS, MM:SS or SS -style interval to a timestamp."""
format = getParsingFormat(interval)
return calendar.timegm(time.strptime(interval.strip(), format))
class AppModule(appModuleHandler.AppModule):
statusBar=None
def event_gainFocus(self, obj, nextHandler):
if not self.statusBar: self.statusBar=api.getStatusBar()
nextHandler()
def getElapsedAndTotal(self):
empty = statusBarTimes(None, None)
if not self.statusBar: return empty
statusBarContents = self.statusBar.firstChild.name
try:
playingTimes = statusBarContents.split("|")[4].split("/")
return statusBarTimes(playingTimes[0], playingTimes[1])
except IndexError:
return empty
def getElapsedAndTotalIfPlaying(self):
elapsedAndTotalTime = self.getElapsedAndTotal()
if elapsedAndTotalTime.elapsed is None and elapsedAndTotalTime.total is None:
# Translators: Reported when no track is playing in Foobar 2000.
ui.message(_("No track playing"))
return elapsedAndTotalTime
def script_reportRemainingTime(self,gesture):
elapsedTime, totalTime = self.getElapsedAndTotalIfPlaying()
if elapsedTime is not None and totalTime is not None:
parsedElapsedTime = parseIntervalToTimestamp(elapsedTime)
parsedTotalTime = parseIntervalToTimestamp(totalTime)
remainingTime = parsedTotalTime - parsedElapsedTime
msg = time.strftime(getOutputFormat(remainingTime), time.gmtime(remainingTime))
ui.message(msg)
# Translators: The description of an NVDA command for reading the remaining time of the currently playing track in Foobar 2000.
script_reportRemainingTime.__doc__ = _("Reports the remaining time of the currently playing track, if any")
def script_reportElapsedTime(self,gesture):
elapsedTime = self.getElapsedAndTotalIfPlaying()[0]
if elapsedTime is not None:
ui.message(elapsedTime)
# Translators: The description of an NVDA command for reading the elapsed time of the currently playing track in Foobar 2000.
script_reportElapsedTime.__doc__ = _("Reports the elapsed time of the currently playing track, if any")
def script_reportTotalTime(self,gesture):
totalTime = self.getElapsedAndTotalIfPlaying()[1]
if totalTime is not None:
ui.message(totalTime)
# Translators: The description of an NVDA command for reading the length of the currently playing track in Foobar 2000.
script_reportTotalTime.__doc__ = _("Reports the length of the currently playing track, if any")
__gestures = {
"kb:control+shift+r": "reportRemainingTime",
"kb:control+shift+e": "reportElapsedTime",
"kb:control+shift+t": "reportTotalTime",
}
| 1 | 29,361 | Could you please clean-up this line while at it? | nvaccess-nvda | py |
@@ -50,6 +50,11 @@ type PubSubSpec struct {
// This brings in CloudEventOverrides and Sink.
duckv1.SourceSpec `json:",inline"`
+ // ServiceAccount is the GCP service account which has required permissions to poll from a Cloud Pub/Sub subscription.
+ // If not specified, defaults to use secret.
+ // +optional
+ ServiceAccount *string `json:"serviceAccount,omitempty"`
+
// Secret is the credential to use to poll from a Cloud Pub/Sub subscription.
// If not specified, defaults to:
// Name: google-cloud-key | 1 | /*
Copyright 2019 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"knative.dev/pkg/apis"
"knative.dev/pkg/apis/duck"
duckv1 "knative.dev/pkg/apis/duck/v1"
)
// PubSub is an Implementable "duck type".
var _ duck.Implementable = (*PubSub)(nil)
// +genduck
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// PubSub is a shared type that GCP sources which create a
// Topic / PullSubscription will use.
// This duck type is intended to allow implementors of GCP sources
// which use PubSub for their transport.
type PubSub struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PubSubSpec `json:"spec"`
Status PubSubStatus `json:"status"`
}
type PubSubSpec struct {
// This brings in CloudEventOverrides and Sink.
duckv1.SourceSpec `json:",inline"`
// Secret is the credential to use to poll from a Cloud Pub/Sub subscription.
// If not specified, defaults to:
// Name: google-cloud-key
// Key: key.json
// +optional
Secret *corev1.SecretKeySelector `json:"secret,omitempty"`
// Project is the ID of the Google Cloud Project that the PubSub Topic exists in.
// If omitted, defaults to same as the cluster.
// +optional
Project string `json:"project,omitempty"`
}
// PubSubStatus shows how we expect folks to embed Addressable in
// their Status field.
type PubSubStatus struct {
// This brings in duck/v1beta1 Status as well as SinkURI
duckv1.SourceStatus
// ProjectID is the project ID of the Topic, might have been resolved.
// +optional
ProjectID string `json:"projectId,omitempty"`
// TopicID where the notifications are sent to.
// +optional
TopicID string `json:"topicId,omitempty"`
// SubscriptionID is the created subscription ID.
// +optional
SubscriptionID string `json:"subscriptionId,omitempty"`
}
const (
// TopicReady has status True when the PubSub Topic is ready.
TopicReady apis.ConditionType = "TopicReady"
// PullSubscriptionReay has status True when the PullSubscription is ready.
PullSubscriptionReady apis.ConditionType = "PullSubscriptionReady"
)
// IsReady returns true if the resource is ready overall.
func (ss *PubSubStatus) IsReady() bool {
for _, c := range ss.Conditions {
switch c.Type {
// Look for the "happy" condition, which is the only condition that
// we can reliably understand to be the overall state of the resource.
case apis.ConditionReady, apis.ConditionSucceeded:
return c.IsTrue()
}
}
return false
}
var (
// Verify PubSub resources meet duck contracts.
_ duck.Populatable = (*PubSub)(nil)
_ apis.Listable = (*PubSub)(nil)
)
// GetFullType implements duck.Implementable
func (*PubSub) GetFullType() duck.Populatable {
return &PubSub{}
}
// Populate implements duck.Populatable
func (s *PubSub) Populate() {
s.Spec.Sink = duckv1.Destination{
URI: &apis.URL{
Scheme: "https",
Host: "tableflip.dev",
RawQuery: "flip=mattmoor",
},
}
s.Spec.CloudEventOverrides = &duckv1.CloudEventOverrides{
Extensions: map[string]string{"boosh": "kakow"},
}
s.Spec.Secret = &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{Name: "secret"},
Key: "secretkey",
}
s.Status.ObservedGeneration = 42
s.Status.Conditions = duckv1.Conditions{{
// Populate ALL fields
Type: duckv1.SourceConditionSinkProvided,
Status: corev1.ConditionTrue,
LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))},
}}
s.Status.SinkURI = &apis.URL{
Scheme: "https",
Host: "tableflip.dev",
RawQuery: "flip=mattmoor",
}
s.Status.ProjectID = "projectid"
s.Status.TopicID = "topicid"
s.Status.SubscriptionID = "subscriptionid"
}
// GetListType implements apis.Listable
func (*PubSub) GetListType() runtime.Object {
return &PubSubList{}
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// PubSubList is a list of PubSub resources
type PubSubList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata"`
Items []PubSub `json:"items"`
}
| 1 | 11,100 | no need to use a pointer. Just string and check for != "" | google-knative-gcp | go |
@@ -133,7 +133,9 @@ public class RestServerVerticle extends AbstractVerticle {
serverOptions.setIdleTimeout(TransportConfig.getConnectionIdleTimeoutInSeconds());
serverOptions.setCompressionSupported(TransportConfig.getCompressed());
serverOptions.setMaxHeaderSize(TransportConfig.getMaxHeaderSize());
-
+ if (endpointObject.isHttp2Enabled()) {
+ serverOptions.setUseAlpn(true);
+ }
if (endpointObject.isSslEnabled()) {
SSLOptionFactory factory =
SSLOptionFactory.createSSLOptionFactory(SSL_KEY, null); | 1 | /*
* 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.servicecomb.transport.rest.vertx;
import java.util.List;
import org.apache.servicecomb.core.Endpoint;
import org.apache.servicecomb.core.transport.AbstractTransport;
import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils;
import org.apache.servicecomb.foundation.ssl.SSLCustom;
import org.apache.servicecomb.foundation.ssl.SSLOption;
import org.apache.servicecomb.foundation.ssl.SSLOptionFactory;
import org.apache.servicecomb.foundation.vertx.VertxTLSBuilder;
import org.apache.servicecomb.transport.rest.vertx.accesslog.AccessLogConfiguration;
import org.apache.servicecomb.transport.rest.vertx.accesslog.impl.AccessLogHandler;
import org.apache.servicecomb.transport.rest.vertx.accesslog.parser.impl.DefaultAccessLogPatternParser;
import org.apache.servicecomb.transport.rest.vertx.trace.TracePrepareHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.ext.web.Router;
public class RestServerVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(RestServerVerticle.class);
private static final String SSL_KEY = "rest.provider";
private Endpoint endpoint;
private URIEndpointObject endpointObject;
@Override
public void init(Vertx vertx, Context context) {
super.init(vertx, context);
this.endpoint = (Endpoint) context.config().getValue(AbstractTransport.ENDPOINT_KEY);
this.endpointObject = (URIEndpointObject) endpoint.getAddress();
}
@Override
public void start(Future<Void> startFuture) throws Exception {
try {
super.start();
// 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可
if (endpointObject == null) {
LOGGER.warn("rest listen address is not configured, will not start.");
startFuture.complete();
return;
}
Router mainRouter = Router.router(vertx);
mountTracePrepareHandler(mainRouter);
mountAccessLogHandler(mainRouter);
initDispatcher(mainRouter);
HttpServer httpServer = createHttpServer();
httpServer.requestHandler(mainRouter::accept);
startListen(httpServer, startFuture);
} catch (Throwable e) {
// vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
LOGGER.error("", e);
throw e;
}
}
private void mountTracePrepareHandler(Router mainRouter) {
mainRouter.route().handler(new TracePrepareHandler());
}
private void mountAccessLogHandler(Router mainRouter) {
if (AccessLogConfiguration.INSTANCE.getAccessLogEnabled()) {
String pattern = AccessLogConfiguration.INSTANCE.getAccesslogPattern();
LOGGER.info("access log enabled, pattern = {}", pattern);
mainRouter.route()
.handler(new AccessLogHandler(
pattern,
new DefaultAccessLogPatternParser()));
}
}
private void initDispatcher(Router mainRouter) {
List<VertxHttpDispatcher> dispatchers = SPIServiceUtils.getSortedService(VertxHttpDispatcher.class);
for (VertxHttpDispatcher dispatcher : dispatchers) {
dispatcher.init(mainRouter);
}
}
private void startListen(HttpServer server, Future<Void> startFuture) {
server.listen(endpointObject.getPort(), endpointObject.getHostOrIp(), ar -> {
if (ar.succeeded()) {
LOGGER.info("rest listen success. address={}:{}",
endpointObject.getHostOrIp(),
ar.result().actualPort());
startFuture.complete();
return;
}
String msg = String.format("rest listen failed, address=%s:%d",
endpointObject.getHostOrIp(),
endpointObject.getPort());
LOGGER.error(msg, ar.cause());
startFuture.fail(ar.cause());
});
}
private HttpServer createHttpServer() {
HttpServerOptions serverOptions = createDefaultHttpServerOptions();
return vertx.createHttpServer(serverOptions);
}
private HttpServerOptions createDefaultHttpServerOptions() {
HttpServerOptions serverOptions = new HttpServerOptions();
serverOptions.setUsePooledBuffers(true);
serverOptions.setIdleTimeout(TransportConfig.getConnectionIdleTimeoutInSeconds());
serverOptions.setCompressionSupported(TransportConfig.getCompressed());
serverOptions.setMaxHeaderSize(TransportConfig.getMaxHeaderSize());
if (endpointObject.isSslEnabled()) {
SSLOptionFactory factory =
SSLOptionFactory.createSSLOptionFactory(SSL_KEY, null);
SSLOption sslOption;
if (factory == null) {
sslOption = SSLOption.buildFromYaml(SSL_KEY);
} else {
sslOption = factory.createSSLOption();
}
SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
}
return serverOptions;
}
}
| 1 | 9,300 | this means h2 mode? but how h2c can work? | apache-servicecomb-java-chassis | java |
@@ -1,9 +1,9 @@
# -*- coding: UTF-8 -*-
-#appModules/explorer.py
-#A part of NonVisual Desktop Access (NVDA)
-#Copyright (C) 2006-2019 NV Access Limited, Joseph Lee, Łukasz Golonka
-#This file is covered by the GNU General Public License.
-#See the file COPYING for more details.
+# appModules/explorer.py
+# A part of NonVisual Desktop Access (NVDA)
+# Copyright (C) 2006-2019 NV Access Limited, Joseph Lee, Łukasz Golonka, Julien Cochuyt
+# This file is covered by the GNU General Public License.
+# See the file COPYING for more details.
"""App module for Windows Explorer (aka Windows shell and renamed to File Explorer in Windows 8).
Provides workarounds for controls such as identifying Start button, notification area and others. | 1 | # -*- coding: UTF-8 -*-
#appModules/explorer.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2019 NV Access Limited, Joseph Lee, Łukasz Golonka
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
"""App module for Windows Explorer (aka Windows shell and renamed to File Explorer in Windows 8).
Provides workarounds for controls such as identifying Start button, notification area and others.
"""
from comtypes import COMError
import time
import appModuleHandler
import controlTypes
import winUser
import winVersion
import api
import speech
import eventHandler
import mouseHandler
from NVDAObjects.window import Window
from NVDAObjects.IAccessible import IAccessible, List
from NVDAObjects.UIA import UIA
from NVDAObjects.window.edit import RichEdit50, EditTextInfo
# Suppress incorrect Win 10 Task switching window focus
class MultitaskingViewFrameWindow(UIA):
shouldAllowUIAFocusEvent=False
# Suppress focus ancestry for task switching list items if alt is held down (alt+tab)
class MultitaskingViewFrameListItem(UIA):
def _get_container(self):
if winUser.getAsyncKeyState(winUser.VK_MENU)&32768:
return api.getDesktopObject()
else:
return super(MultitaskingViewFrameListItem,self).container
# Support for Win8 start screen search suggestions.
class SuggestionListItem(UIA):
def event_UIA_elementSelected(self):
speech.cancelSpeech()
api.setNavigatorObject(self, isFocus=True)
self.reportFocus()
super(SuggestionListItem,self).event_UIA_elementSelected()
# Windows 8 hack: Class to disable incorrect focus on windows 8 search box (containing the already correctly focused edit field)
class SearchBoxClient(IAccessible):
shouldAllowIAccessibleFocusEvent=False
# Class for menu items for Windows Places and Frequently used Programs (in start menu)
# Also used for desktop items
class SysListView32EmittingDuplicateFocusEvents(IAccessible):
# #474: When focus moves to these items, an extra focus is fired on the parent
# However NVDA redirects it to the real focus.
# But this means double focus events on the item, so filter the second one out
# #2988: Also seen when coming back to the Windows 7 desktop from different applications.
def _get_shouldAllowIAccessibleFocusEvent(self):
res = super().shouldAllowIAccessibleFocusEvent
if not res:
return False
focus = eventHandler.lastQueuedFocusObject
if type(focus)!=type(self) or (self.event_windowHandle,self.event_objectID,self.event_childID)!=(focus.event_windowHandle,focus.event_objectID,focus.event_childID):
return True
return False
class NotificationArea(IAccessible):
"""The Windows notification area, a.k.a. system tray.
"""
def event_gainFocus(self):
if mouseHandler.lastMouseEventTime < time.time() - 0.2:
# This focus change was not caused by a mouse event.
# If the mouse is on another toolbar control, the notification area toolbar will rudely
# bounce the focus back to the object under the mouse after a brief pause.
# Moving the mouse to the focus object isn't a good solution because
# sometimes, the focus can't be moved away from the object under the mouse.
# Therefore, move the mouse out of the way.
winUser.setCursorPos(0, 0)
if self.role == controlTypes.ROLE_TOOLBAR:
# Sometimes, the toolbar itself receives the focus instead of the focused child.
# However, the focused child still has the focused state.
for child in self.children:
if child.hasFocus:
# Redirect the focus to the focused child.
eventHandler.executeEvent("gainFocus", child)
return
# We've really landed on the toolbar itself.
# This was probably caused by moving the mouse out of the way in a previous focus event.
# This previous focus event is no longer useful, so cancel speech.
speech.cancelSpeech()
if eventHandler.isPendingEvents("gainFocus"):
return
super(NotificationArea, self).event_gainFocus()
class GridTileElement(UIA):
role=controlTypes.ROLE_TABLECELL
def _get_description(self):
name=self.name
descriptionStrings=[]
for child in self.children:
description=child.basicText
if not description or description==name: continue
descriptionStrings.append(description)
return " ".join(descriptionStrings)
return description
class GridListTileElement(UIA):
role=controlTypes.ROLE_TABLECELL
description=None
class GridGroup(UIA):
"""A group in the Windows 8 Start Menu.
"""
presentationType=UIA.presType_content
# Normally the name is the first tile which is rather redundant
# However some groups have custom header text which should be read instead
def _get_name(self):
child=self.firstChild
if isinstance(child,UIA):
try:
automationID=child.UIAElement.currentAutomationID
except COMError:
automationID=None
if automationID=="GridListGroupHeader":
return child.name
class ImmersiveLauncher(UIA):
# When the Windows 8 start screen opens, focus correctly goes to the first tile, but then incorrectly back to the root of the window.
# Ignore focus events on this object.
shouldAllowUIAFocusEvent=False
class StartButton(IAccessible):
"""For Windows 8.1 and 10 Start buttons to be recognized as proper buttons and to suppress selection announcement."""
role = controlTypes.ROLE_BUTTON
def _get_states(self):
# #5178: Selection announcement should be suppressed.
# Borrowed from Mozilla objects in NVDAObjects/IAccessible/Mozilla.py.
states = super(StartButton, self).states
states.discard(controlTypes.STATE_SELECTED)
return states
CHAR_LTR_MARK = u'\u200E'
CHAR_RTL_MARK = u'\u200F'
class UIProperty(UIA):
#Used for columns in Windows Explorer Details view.
#These can contain dates that include unwanted left-to-right and right-to-left indicator characters.
def _get_value(self):
value = super(UIProperty, self).value
if value is None:
return value
return value.replace(CHAR_LTR_MARK,'').replace(CHAR_RTL_MARK,'')
class ReadOnlyEditBox(IAccessible):
#Used for read-only edit boxes in a properties window.
#These can contain dates that include unwanted left-to-right and right-to-left indicator characters.
def _get_windowText(self):
windowText = super(ReadOnlyEditBox, self).windowText
if windowText is not None:
return windowText.replace(CHAR_LTR_MARK,'').replace(CHAR_RTL_MARK,'')
return windowText
class MetadataEditField(RichEdit50):
""" Used for metadata edit fields in Windows Explorer in Windows 7.
By default these fields would use ITextDocumentTextInfo ,
but to avoid Windows Explorer crashes we need to use EditTextInfo here. """
@classmethod
def _get_TextInfo(cls):
if ((winVersion.winVersion.major, winVersion.winVersion.minor) == (6, 1)):
cls.TextInfo = EditTextInfo
else:
cls.TextInfo = super().TextInfo
return cls.TextInfo
class AppModule(appModuleHandler.AppModule):
def chooseNVDAObjectOverlayClasses(self, obj, clsList):
windowClass = obj.windowClassName
role = obj.role
if windowClass in ("Search Box","UniversalSearchBand") and role==controlTypes.ROLE_PANE and isinstance(obj,IAccessible):
clsList.insert(0,SearchBoxClient)
return # Optimization: return early to avoid comparing class names and roles that will never match.
if windowClass == "ToolbarWindow32":
if role != controlTypes.ROLE_POPUPMENU:
try:
# The toolbar's immediate parent is its window object, so we need to go one further.
toolbarParent = obj.parent.parent
if role != controlTypes.ROLE_TOOLBAR:
# Toolbar item.
toolbarParent = toolbarParent.parent
except AttributeError:
toolbarParent = None
if toolbarParent and toolbarParent.windowClassName == "SysPager":
clsList.insert(0, NotificationArea)
return
if windowClass == "Edit" and controlTypes.STATE_READONLY in obj.states:
clsList.insert(0, ReadOnlyEditBox)
return # Optimization: return early to avoid comparing class names and roles that will never match.
if windowClass == "SysListView32":
if(
role == controlTypes.ROLE_MENUITEM
or(
role == controlTypes.ROLE_LISTITEM
and obj.simpleParent
and obj.simpleParent.simpleParent
and obj.simpleParent.simpleParent == api.getDesktopObject()
)
):
clsList.insert(0, SysListView32EmittingDuplicateFocusEvents)
return # Optimization: return early to avoid comparing class names and roles that will never match.
# #5178: Start button in Windows 8.1 and 10 should not have been a list in the first place.
if windowClass == "Start" and role in (controlTypes.ROLE_LIST, controlTypes.ROLE_BUTTON):
if role == controlTypes.ROLE_LIST:
clsList.remove(List)
clsList.insert(0, StartButton)
return # Optimization: return early to avoid comparing class names and roles that will never match.
if windowClass == 'RICHEDIT50W' and obj.windowControlID == 256:
clsList.insert(0, MetadataEditField)
return # Optimization: return early to avoid comparing class names and roles that will never match.
if isinstance(obj, UIA):
uiaClassName = obj.UIAElement.cachedClassName
if uiaClassName == "GridTileElement":
clsList.insert(0, GridTileElement)
elif uiaClassName == "GridListTileElement":
clsList.insert(0, GridListTileElement)
elif uiaClassName == "GridGroup":
clsList.insert(0, GridGroup)
elif uiaClassName == "ImmersiveLauncher" and role == controlTypes.ROLE_PANE:
clsList.insert(0, ImmersiveLauncher)
elif uiaClassName == "ListViewItem" and obj.UIAElement.cachedAutomationId.startswith('Suggestion_'):
clsList.insert(0, SuggestionListItem)
elif uiaClassName == "MultitaskingViewFrame" and role == controlTypes.ROLE_WINDOW:
clsList.insert(0, MultitaskingViewFrameWindow)
# Windows 10 task switch list
elif role == controlTypes.ROLE_LISTITEM and (
# RS4 and below we can match on a window class
windowClass == "MultitaskingViewFrame" or
# RS5 and above we must look for a particular UIA automationID on the list
isinstance(obj.parent,UIA) and obj.parent.UIAElement.cachedAutomationID=="SwitchItemListControl"
):
clsList.insert(0, MultitaskingViewFrameListItem)
elif uiaClassName == "UIProperty" and role == controlTypes.ROLE_EDITABLETEXT:
clsList.insert(0, UIProperty)
def event_NVDAObject_init(self, obj):
windowClass = obj.windowClassName
role = obj.role
if windowClass == "ToolbarWindow32" and role == controlTypes.ROLE_POPUPMENU:
parent = obj.parent
if parent and parent.windowClassName == "SysPager" and not (obj.windowStyle & 0x80):
# This is the menu for a group of icons on the task bar, which Windows stupidly names "Application".
obj.name = None
return
if windowClass == "#32768":
# Standard menu.
parent = obj.parent
if parent and not parent.parent:
# Context menu.
# We don't trust the names that Explorer gives to context menus, so better to have no name at all.
obj.name = None
return
if windowClass == "DV2ControlHost" and role == controlTypes.ROLE_PANE:
# Windows 7 start menu.
obj.presentationType=obj.presType_content
obj.isPresentableFocusAncestor = True
# In Windows 7, the description of this pane is extremely verbose help text, so nuke it.
obj.description = None
return
# The Address bar is embedded inside a progressbar, how strange.
# Lets hide that
if windowClass=="msctls_progress32" and winUser.getClassName(winUser.getAncestor(obj.windowHandle,winUser.GA_PARENT))=="Address Band Root":
obj.presentationType=obj.presType_layout
return
if windowClass == "DirectUIHWND" and role == controlTypes.ROLE_LIST:
if obj.parent and obj.parent.parent:
parent = obj.parent.parent.parent
if parent is not None and parent.windowClassName == "Desktop Search Open View":
# List containing search results in Windows 7 start menu.
# Its name is not useful so discard it.
obj.name = None
return
def event_gainFocus(self, obj, nextHandler):
wClass = obj.windowClassName
if wClass == "ToolbarWindow32" and obj.role == controlTypes.ROLE_MENUITEM and obj.parent.role == controlTypes.ROLE_MENUBAR and eventHandler.isPendingEvents("gainFocus"):
# When exiting a menu, Explorer fires focus on the top level menu item before it returns to the previous focus.
# Unfortunately, this focus event always occurs in a subsequent cycle, so the event limiter doesn't eliminate it.
# Therefore, if there is a pending focus event, don't bother handling this event.
return
if wClass in ("ForegroundStaging", "LauncherTipWnd", "ApplicationManager_DesktopShellWindow"):
# #5116: The Windows 10 Task View fires foreground/focus on this weird invisible window and foreground staging screen before and after it appears.
# This causes NVDA to report "unknown", so ignore it.
# We can't do this using shouldAllowIAccessibleFocusEvent because this isn't checked for foreground.
# #8137: also seen when opening quick link menu (Windows+X) on Windows 8 and later.
return
if wClass == "WorkerW" and obj.role == controlTypes.ROLE_PANE and obj.name is None:
# #6671: Never allow WorkerW thread to send gain focus event, as it causes 'pane" to be announced when minimizing windows or moving to desktop.
return
nextHandler()
def isGoodUIAWindow(self, hwnd):
# #9204: shell raises window open event for emoji panel in build 18305 and later.
if winVersion.isWin10(version=1903) and winUser.getClassName(hwnd) == "ApplicationFrameWindow":
return True
return False
def event_UIA_window_windowOpen(self, obj, nextHandler):
# Send UIA window open event to input app window.
if isinstance(obj, UIA) and obj.UIAElement.cachedClassName == "ApplicationFrameWindow":
inputPanelWindow = obj.firstChild
inputPanelAppName = (
# 19H2 and earlier
"windowsinternal_composableshell_experiences_textinput_inputapp",
# 20H1 and later
"textinputhost"
)
if inputPanelWindow and inputPanelWindow.appModule.appName in inputPanelAppName:
eventHandler.executeEvent("UIA_window_windowOpen", inputPanelWindow)
return
nextHandler()
| 1 | 29,558 | This line should not be there | nvaccess-nvda | py |
@@ -120,7 +120,12 @@ func (t *trie) Start(ctx context.Context) error {
return t.dao.Commit(t.cb)
}
-func (t *trie) Stop(ctx context.Context) error { return t.lifecycle.OnStop(ctx) }
+func (t *trie) Stop(ctx context.Context) error {
+ t.mutex.Lock()
+ defer t.mutex.Unlock()
+
+ return t.lifecycle.OnStop(ctx)
+}
// TrieDB return the underlying DB instance
func (t *trie) TrieDB() db.KVStore { | 1 | // Copyright (c) 2018 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
package trie
import (
"context"
"sync"
"github.com/pkg/errors"
"github.com/iotexproject/iotex-core/db"
"github.com/iotexproject/iotex-core/pkg/hash"
"github.com/iotexproject/iotex-core/pkg/lifecycle"
)
var (
// AccountKVNameSpace is the bucket name for account trie
AccountKVNameSpace = "Account"
// CodeKVNameSpace is the bucket name for code
CodeKVNameSpace = "Code"
// ContractKVNameSpace is the bucket name for contract data storage
ContractKVNameSpace = "Contract"
// CandidateKVNameSpace is the bucket name for candidate data storage
CandidateKVNameSpace = "Candidate"
// ErrInvalidTrie indicates something wrong causing invalid operation
ErrInvalidTrie = errors.New("invalid trie operation")
// ErrNotExist indicates entry does not exist
ErrNotExist = errors.New("not exist in trie")
// EmptyRoot is the root hash of an empty trie
EmptyRoot = hash.Hash32B{0xe, 0x57, 0x51, 0xc0, 0x26, 0xe5, 0x43, 0xb2, 0xe8, 0xab, 0x2e, 0xb0, 0x60, 0x99,
0xda, 0xa1, 0xd1, 0xe5, 0xdf, 0x47, 0x77, 0x8f, 0x77, 0x87, 0xfa, 0xab, 0x45, 0xcd, 0xf1, 0x2f, 0xe3, 0xa8}
)
type (
// Trie is the interface of Merkle Patricia Trie
Trie interface {
lifecycle.StartStopper
TrieDB() db.KVStore // return the underlying DB instance
Upsert([]byte, []byte) error // insert a new entry
Get([]byte) ([]byte, error) // retrieve an existing entry
Delete([]byte) error // delete an entry
Commit() error // commit the state changes in a batch
RootHash() hash.Hash32B // returns trie's root hash
SetRoot(hash.Hash32B) error // set a new root to trie
}
// trie implements the Trie interface
trie struct {
lifecycle lifecycle.Lifecycle
mutex sync.RWMutex
root patricia
rootHash hash.Hash32B
bucket string // bucket name to store the nodes
numEntry uint64 // number of entries added to the trie
numBranch uint64
numExt uint64
numLeaf uint64
cb db.CachedBatch // cached batch for pending writes
dao db.KVStore // the underlying storage DB
}
)
// NewTrie creates a trie with DB filename
func NewTrie(kvStore db.KVStore, name string, root hash.Hash32B) (Trie, error) {
if kvStore == nil {
return nil, errors.Wrapf(ErrInvalidTrie, "try to create trie with empty KV store")
}
t := &trie{
cb: db.NewCachedBatch(),
dao: kvStore,
rootHash: root,
bucket: name,
numEntry: 1,
numBranch: 1,
}
t.lifecycle.Add(kvStore)
return t, nil
}
// NewTrieSharedBatch creates a trie with a shared batch
func NewTrieSharedBatch(kvStore db.KVStore, batch db.CachedBatch, name string, root hash.Hash32B) (Trie, error) {
if kvStore == nil || batch == nil {
return nil, errors.Wrapf(ErrInvalidTrie, "try to create trie with empty KV store")
}
t := &trie{
cb: batch,
dao: kvStore,
rootHash: root,
bucket: name,
numEntry: 1,
numBranch: 1}
return t, nil
}
func (t *trie) Start(ctx context.Context) error {
t.lifecycle.OnStart(ctx)
t.mutex.Lock()
defer t.mutex.Unlock()
if t.rootHash != EmptyRoot {
var err error
t.root, err = getPatricia(t.rootHash[:], t.dao, t.bucket, t.cb)
return err
}
// initial empty trie
t.root = &branch{}
if _, err := putPatricia(t.root, t.bucket, t.cb); err != nil {
return err
}
return t.dao.Commit(t.cb)
}
func (t *trie) Stop(ctx context.Context) error { return t.lifecycle.OnStop(ctx) }
// TrieDB return the underlying DB instance
func (t *trie) TrieDB() db.KVStore {
return t.dao
}
// Upsert a new entry
func (t *trie) Upsert(key, value []byte) error {
t.mutex.Lock()
defer t.mutex.Unlock()
_, err := t.root.upsert(key, value, 0, t.dao, t.bucket, t.cb)
// update root hash
t.rootHash = t.root.hash()
return err
}
// Get an existing entry
func (t *trie) Get(key []byte) ([]byte, error) {
t.mutex.RLock()
defer t.mutex.RUnlock()
return t.root.get(key, 0, t.dao, t.bucket, t.cb)
}
// Delete an entry
func (t *trie) Delete(key []byte) error {
t.mutex.Lock()
defer t.mutex.Unlock()
_, err := t.root.delete(key, 0, t.dao, t.bucket, t.cb)
// update root hash
t.rootHash = t.root.hash()
return err
}
// Commit local cached <k, v> in a batch
func (t *trie) Commit() error {
t.mutex.Lock()
defer t.mutex.Unlock()
return t.dao.Commit(t.cb)
}
// RootHash returns the root hash of merkle patricia trie
func (t *trie) RootHash() hash.Hash32B {
t.mutex.RLock()
defer t.mutex.RUnlock()
return t.rootHash
}
// SetRoot sets the root trie
func (t *trie) SetRoot(rootHash hash.Hash32B) error {
t.mutex.Lock()
defer t.mutex.Unlock()
root, err := getPatricia(rootHash[:], t.dao, t.bucket, t.cb)
if err != nil {
return errors.Wrapf(err, "failed to set root %x", rootHash[:])
}
t.root = root
t.rootHash = rootHash
return nil
}
| 1 | 13,119 | why do we need lock here? if needed, then we also need to lock in Start()? | iotexproject-iotex-core | go |
@@ -415,6 +415,8 @@ void ProtocolGame::parsePacket(NetworkMessage& msg)
}
}
+ addGameTask(&Game::playerExecuteParsePacketEvent, player->getID(), recvbyte, new NetworkMessage(msg));
+
switch (recvbyte) {
case 0x14: g_dispatcher.addTask(createTask(std::bind(&ProtocolGame::logout, getThis(), true, false))); break;
case 0x1D: addGameTask(&Game::playerReceivePingBack, player->getID()); break; | 1 | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2019 Mark Samman <mark.samman@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include <boost/range/adaptor/reversed.hpp>
#include "protocolgame.h"
#include "outputmessage.h"
#include "player.h"
#include "configmanager.h"
#include "actions.h"
#include "game.h"
#include "iologindata.h"
#include "iomarket.h"
#include "waitlist.h"
#include "ban.h"
#include "scheduler.h"
extern ConfigManager g_config;
extern Actions actions;
extern CreatureEvents* g_creatureEvents;
extern Chat* g_chat;
void ProtocolGame::release()
{
//dispatcher thread
if (player && player->client == shared_from_this()) {
player->client.reset();
player->decrementReferenceCounter();
player = nullptr;
}
OutputMessagePool::getInstance().removeProtocolFromAutosend(shared_from_this());
Protocol::release();
}
void ProtocolGame::login(const std::string& name, uint32_t accountId, OperatingSystem_t operatingSystem)
{
//dispatcher thread
Player* foundPlayer = g_game.getPlayerByName(name);
if (!foundPlayer || g_config.getBoolean(ConfigManager::ALLOW_CLONES)) {
player = new Player(getThis());
player->setName(name);
player->incrementReferenceCounter();
player->setID();
if (!IOLoginData::preloadPlayer(player, name)) {
disconnectClient("Your character could not be loaded.");
return;
}
if (IOBan::isPlayerNamelocked(player->getGUID())) {
disconnectClient("Your character has been namelocked.");
return;
}
if (g_game.getGameState() == GAME_STATE_CLOSING && !player->hasFlag(PlayerFlag_CanAlwaysLogin)) {
disconnectClient("The game is just going down.\nPlease try again later.");
return;
}
if (g_game.getGameState() == GAME_STATE_CLOSED && !player->hasFlag(PlayerFlag_CanAlwaysLogin)) {
disconnectClient("Server is currently closed.\nPlease try again later.");
return;
}
if (g_config.getBoolean(ConfigManager::ONE_PLAYER_ON_ACCOUNT) && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && g_game.getPlayerByAccount(player->getAccount())) {
disconnectClient("You may only login with one character\nof your account at the same time.");
return;
}
if (!player->hasFlag(PlayerFlag_CannotBeBanned)) {
BanInfo banInfo;
if (IOBan::isAccountBanned(accountId, banInfo)) {
if (banInfo.reason.empty()) {
banInfo.reason = "(none)";
}
std::ostringstream ss;
if (banInfo.expiresAt > 0) {
ss << "Your account has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason;
} else {
ss << "Your account has been permanently banned by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason;
}
disconnectClient(ss.str());
return;
}
}
WaitingList& waitingList = WaitingList::getInstance();
if (!waitingList.clientLogin(player)) {
uint32_t currentSlot = waitingList.getClientSlot(player);
uint32_t retryTime = WaitingList::getTime(currentSlot);
std::ostringstream ss;
ss << "Too many players online.\nYou are at place "
<< currentSlot << " on the waiting list.";
auto output = OutputMessagePool::getOutputMessage();
output->addByte(0x16);
output->addString(ss.str());
output->addByte(retryTime);
send(output);
disconnect();
return;
}
if (!IOLoginData::loadPlayerById(player, player->getGUID())) {
disconnectClient("Your character could not be loaded.");
return;
}
player->setOperatingSystem(operatingSystem);
if (!g_game.placeCreature(player, player->getLoginPosition())) {
if (!g_game.placeCreature(player, player->getTemplePosition(), false, true)) {
disconnectClient("Temple position is wrong. Contact the administrator.");
return;
}
}
if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) {
player->registerCreatureEvent("ExtendedOpcode");
}
player->lastIP = player->getIP();
player->lastLoginSaved = std::max<time_t>(time(nullptr), player->lastLoginSaved + 1);
acceptPackets = true;
} else {
if (eventConnect != 0 || !g_config.getBoolean(ConfigManager::REPLACE_KICK_ON_LOGIN)) {
//Already trying to connect
disconnectClient("You are already logged in.");
return;
}
if (foundPlayer->client) {
foundPlayer->disconnect();
foundPlayer->isConnecting = true;
eventConnect = g_scheduler.addEvent(createSchedulerTask(1000, std::bind(&ProtocolGame::connect, getThis(), foundPlayer->getID(), operatingSystem)));
} else {
connect(foundPlayer->getID(), operatingSystem);
}
}
OutputMessagePool::getInstance().addProtocolToAutosend(shared_from_this());
}
void ProtocolGame::connect(uint32_t playerId, OperatingSystem_t operatingSystem)
{
eventConnect = 0;
Player* foundPlayer = g_game.getPlayerByID(playerId);
if (!foundPlayer || foundPlayer->client) {
disconnectClient("You are already logged in.");
return;
}
if (isConnectionExpired()) {
//ProtocolGame::release() has been called at this point and the Connection object
//no longer exists, so we return to prevent leakage of the Player.
return;
}
player = foundPlayer;
player->incrementReferenceCounter();
g_chat->removeUserFromAllChannels(*player);
player->clearModalWindows();
player->setOperatingSystem(operatingSystem);
player->isConnecting = false;
player->client = getThis();
sendAddCreature(player, player->getPosition(), 0, false);
player->lastIP = player->getIP();
player->lastLoginSaved = std::max<time_t>(time(nullptr), player->lastLoginSaved + 1);
acceptPackets = true;
}
void ProtocolGame::logout(bool displayEffect, bool forced)
{
//dispatcher thread
if (!player) {
return;
}
if (!player->isRemoved()) {
if (!forced) {
if (!player->isAccessPlayer()) {
if (player->getTile()->hasFlag(TILESTATE_NOLOGOUT)) {
player->sendCancelMessage(RETURNVALUE_YOUCANNOTLOGOUTHERE);
return;
}
if (!player->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) && player->hasCondition(CONDITION_INFIGHT)) {
player->sendCancelMessage(RETURNVALUE_YOUMAYNOTLOGOUTDURINGAFIGHT);
return;
}
}
//scripting event - onLogout
if (!g_creatureEvents->playerLogout(player)) {
//Let the script handle the error message
return;
}
}
if (displayEffect && player->getHealth() > 0) {
g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF);
}
}
disconnect();
g_game.removeCreature(player);
}
void ProtocolGame::onRecvFirstMessage(NetworkMessage& msg)
{
if (g_game.getGameState() == GAME_STATE_SHUTDOWN) {
disconnect();
return;
}
OperatingSystem_t operatingSystem = static_cast<OperatingSystem_t>(msg.get<uint16_t>());
version = msg.get<uint16_t>();
msg.skipBytes(7); // U32 client version, U8 client type, U16 dat revision
if (!Protocol::RSA_decrypt(msg)) {
disconnect();
return;
}
xtea::key key;
key[0] = msg.get<uint32_t>();
key[1] = msg.get<uint32_t>();
key[2] = msg.get<uint32_t>();
key[3] = msg.get<uint32_t>();
enableXTEAEncryption();
setXTEAKey(std::move(key));
if (operatingSystem >= CLIENTOS_OTCLIENT_LINUX) {
NetworkMessage opcodeMessage;
opcodeMessage.addByte(0x32);
opcodeMessage.addByte(0x00);
opcodeMessage.add<uint16_t>(0x00);
writeToOutputBuffer(opcodeMessage);
}
msg.skipBytes(1); // gamemaster flag
std::string sessionKey = msg.getString();
auto sessionArgs = explodeString(sessionKey, "\n", 4);
if (sessionArgs.size() != 4) {
disconnect();
return;
}
std::string& accountName = sessionArgs[0];
std::string& password = sessionArgs[1];
std::string& token = sessionArgs[2];
uint32_t tokenTime = 0;
try {
tokenTime = std::stoul(sessionArgs[3]);
} catch (const std::invalid_argument&) {
disconnectClient("Malformed token packet.");
return;
} catch (const std::out_of_range&) {
disconnectClient("Token time is too long.");
return;
}
if (accountName.empty()) {
disconnectClient("You must enter your account name.");
return;
}
std::string characterName = msg.getString();
uint32_t timeStamp = msg.get<uint32_t>();
uint8_t randNumber = msg.getByte();
if (challengeTimestamp != timeStamp || challengeRandom != randNumber) {
disconnect();
return;
}
if (version < CLIENT_VERSION_MIN || version > CLIENT_VERSION_MAX) {
std::ostringstream ss;
ss << "Only clients with protocol " << CLIENT_VERSION_STR << " allowed!";
disconnectClient(ss.str());
return;
}
if (g_game.getGameState() == GAME_STATE_STARTUP) {
disconnectClient("Gameworld is starting up. Please wait.");
return;
}
if (g_game.getGameState() == GAME_STATE_MAINTAIN) {
disconnectClient("Gameworld is under maintenance. Please re-connect in a while.");
return;
}
BanInfo banInfo;
if (IOBan::isIpBanned(getIP(), banInfo)) {
if (banInfo.reason.empty()) {
banInfo.reason = "(none)";
}
std::ostringstream ss;
ss << "Your IP has been banned until " << formatDateShort(banInfo.expiresAt) << " by " << banInfo.bannedBy << ".\n\nReason specified:\n" << banInfo.reason;
disconnectClient(ss.str());
return;
}
uint32_t accountId = IOLoginData::gameworldAuthentication(accountName, password, characterName, token, tokenTime);
if (accountId == 0) {
disconnectClient("Account name or password is not correct.");
return;
}
g_dispatcher.addTask(createTask(std::bind(&ProtocolGame::login, getThis(), characterName, accountId, operatingSystem)));
}
void ProtocolGame::onConnect()
{
auto output = OutputMessagePool::getOutputMessage();
static std::random_device rd;
static std::ranlux24 generator(rd());
static std::uniform_int_distribution<uint16_t> randNumber(0x00, 0xFF);
// Skip checksum
output->skipBytes(sizeof(uint32_t));
// Packet length & type
output->add<uint16_t>(0x0006);
output->addByte(0x1F);
// Add timestamp & random number
challengeTimestamp = static_cast<uint32_t>(time(nullptr));
output->add<uint32_t>(challengeTimestamp);
challengeRandom = randNumber(generator);
output->addByte(challengeRandom);
// Go back and write checksum
output->skipBytes(-12);
output->add<uint32_t>(adlerChecksum(output->getOutputBuffer() + sizeof(uint32_t), 8));
send(output);
}
void ProtocolGame::disconnectClient(const std::string& message) const
{
auto output = OutputMessagePool::getOutputMessage();
output->addByte(0x14);
output->addString(message);
send(output);
disconnect();
}
void ProtocolGame::writeToOutputBuffer(const NetworkMessage& msg)
{
auto out = getOutputBuffer(msg.getLength());
out->append(msg);
}
void ProtocolGame::parsePacket(NetworkMessage& msg)
{
if (!acceptPackets || g_game.getGameState() == GAME_STATE_SHUTDOWN || msg.getLength() <= 0) {
return;
}
uint8_t recvbyte = msg.getByte();
if (!player) {
if (recvbyte == 0x0F) {
disconnect();
}
return;
}
//a dead player can not performs actions
if (player->isRemoved() || player->getHealth() <= 0) {
if (recvbyte == 0x0F) {
disconnect();
return;
}
if (recvbyte != 0x14) {
return;
}
}
switch (recvbyte) {
case 0x14: g_dispatcher.addTask(createTask(std::bind(&ProtocolGame::logout, getThis(), true, false))); break;
case 0x1D: addGameTask(&Game::playerReceivePingBack, player->getID()); break;
case 0x1E: addGameTask(&Game::playerReceivePing, player->getID()); break;
case 0x32: parseExtendedOpcode(msg); break; //otclient extended opcode
case 0x64: parseAutoWalk(msg); break;
case 0x65: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTH); break;
case 0x66: addGameTask(&Game::playerMove, player->getID(), DIRECTION_EAST); break;
case 0x67: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTH); break;
case 0x68: addGameTask(&Game::playerMove, player->getID(), DIRECTION_WEST); break;
case 0x69: addGameTask(&Game::playerStopAutoWalk, player->getID()); break;
case 0x6A: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHEAST); break;
case 0x6B: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHEAST); break;
case 0x6C: addGameTask(&Game::playerMove, player->getID(), DIRECTION_SOUTHWEST); break;
case 0x6D: addGameTask(&Game::playerMove, player->getID(), DIRECTION_NORTHWEST); break;
case 0x6F: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_NORTH); break;
case 0x70: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_EAST); break;
case 0x71: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_SOUTH); break;
case 0x72: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerTurn, player->getID(), DIRECTION_WEST); break;
case 0x77: parseEquipObject(msg); break;
case 0x78: parseThrow(msg); break;
case 0x79: parseLookInShop(msg); break;
case 0x7A: parsePlayerPurchase(msg); break;
case 0x7B: parsePlayerSale(msg); break;
case 0x7C: addGameTask(&Game::playerCloseShop, player->getID()); break;
case 0x7D: parseRequestTrade(msg); break;
case 0x7E: parseLookInTrade(msg); break;
case 0x7F: addGameTask(&Game::playerAcceptTrade, player->getID()); break;
case 0x80: addGameTask(&Game::playerCloseTrade, player->getID()); break;
case 0x82: parseUseItem(msg); break;
case 0x83: parseUseItemEx(msg); break;
case 0x84: parseUseWithCreature(msg); break;
case 0x85: parseRotateItem(msg); break;
case 0x87: parseCloseContainer(msg); break;
case 0x88: parseUpArrowContainer(msg); break;
case 0x89: parseTextWindow(msg); break;
case 0x8A: parseHouseWindow(msg); break;
case 0x8B: parseWrapItem(msg); break;
case 0x8C: parseLookAt(msg); break;
case 0x8D: parseLookInBattleList(msg); break;
case 0x8E: /* join aggression */ break;
case 0x96: parseSay(msg); break;
case 0x97: addGameTask(&Game::playerRequestChannels, player->getID()); break;
case 0x98: parseOpenChannel(msg); break;
case 0x99: parseCloseChannel(msg); break;
case 0x9A: parseOpenPrivateChannel(msg); break;
case 0x9E: addGameTask(&Game::playerCloseNpcChannel, player->getID()); break;
case 0xA0: parseFightModes(msg); break;
case 0xA1: parseAttack(msg); break;
case 0xA2: parseFollow(msg); break;
case 0xA3: parseInviteToParty(msg); break;
case 0xA4: parseJoinParty(msg); break;
case 0xA5: parseRevokePartyInvite(msg); break;
case 0xA6: parsePassPartyLeadership(msg); break;
case 0xA7: addGameTask(&Game::playerLeaveParty, player->getID()); break;
case 0xA8: parseEnableSharedPartyExperience(msg); break;
case 0xAA: addGameTask(&Game::playerCreatePrivateChannel, player->getID()); break;
case 0xAB: parseChannelInvite(msg); break;
case 0xAC: parseChannelExclude(msg); break;
case 0xBE: addGameTask(&Game::playerCancelAttackAndFollow, player->getID()); break;
case 0xC9: /* update tile */ break;
case 0xCA: parseUpdateContainer(msg); break;
case 0xCB: parseBrowseField(msg); break;
case 0xCC: parseSeekInContainer(msg); break;
case 0xD2: addGameTask(&Game::playerRequestOutfit, player->getID()); break;
case 0xD3: parseSetOutfit(msg); break;
case 0xD4: parseToggleMount(msg); break;
case 0xDC: parseAddVip(msg); break;
case 0xDD: parseRemoveVip(msg); break;
case 0xDE: parseEditVip(msg); break;
case 0xE6: parseBugReport(msg); break;
case 0xE7: /* thank you */ break;
case 0xE8: parseDebugAssert(msg); break;
case 0xF0: addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerShowQuestLog, player->getID()); break;
case 0xF1: parseQuestLine(msg); break;
case 0xF2: parseRuleViolationReport(msg); break;
case 0xF3: /* get object info */ break;
case 0xF4: parseMarketLeave(); break;
case 0xF5: parseMarketBrowse(msg); break;
case 0xF6: parseMarketCreateOffer(msg); break;
case 0xF7: parseMarketCancelOffer(msg); break;
case 0xF8: parseMarketAcceptOffer(msg); break;
case 0xF9: parseModalWindowAnswer(msg); break;
default:
// std::cout << "Player: " << player->getName() << " sent an unknown packet header: 0x" << std::hex << static_cast<uint16_t>(recvbyte) << std::dec << "!" << std::endl;
break;
}
if (msg.isOverrun()) {
disconnect();
}
}
void ProtocolGame::GetTileDescription(const Tile* tile, NetworkMessage& msg)
{
msg.add<uint16_t>(0x00); //environmental effects
int32_t count;
Item* ground = tile->getGround();
if (ground) {
msg.addItem(ground);
count = 1;
} else {
count = 0;
}
const TileItemVector* items = tile->getItemList();
if (items) {
for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) {
msg.addItem(*it);
count++;
if (count == 9 && tile->getPosition() == player->getPosition()) {
break;
} else if (count == 10) {
return;
}
}
}
const CreatureVector* creatures = tile->getCreatures();
if (creatures) {
bool playerAdded = false;
for (const Creature* creature : boost::adaptors::reverse(*creatures)) {
if (!player->canSeeCreature(creature)) {
continue;
}
if (tile->getPosition() == player->getPosition() && count == 9 && !playerAdded) {
creature = player;
}
if (creature->getID() == player->getID()) {
playerAdded = true;
}
bool known;
uint32_t removedKnown;
checkCreatureAsKnown(creature->getID(), known, removedKnown);
AddCreature(msg, creature, known, removedKnown);
if (++count == 10) {
return;
}
}
}
if (items) {
for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) {
msg.addItem(*it);
if (++count == 10) {
return;
}
}
}
}
void ProtocolGame::GetMapDescription(int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, NetworkMessage& msg)
{
int32_t skip = -1;
int32_t startz, endz, zstep;
if (z > 7) {
startz = z - 2;
endz = std::min<int32_t>(MAP_MAX_LAYERS - 1, z + 2);
zstep = 1;
} else {
startz = 7;
endz = 0;
zstep = -1;
}
for (int32_t nz = startz; nz != endz + zstep; nz += zstep) {
GetFloorDescription(msg, x, y, nz, width, height, z - nz, skip);
}
if (skip >= 0) {
msg.addByte(skip);
msg.addByte(0xFF);
}
}
void ProtocolGame::GetFloorDescription(NetworkMessage& msg, int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, int32_t offset, int32_t& skip)
{
for (int32_t nx = 0; nx < width; nx++) {
for (int32_t ny = 0; ny < height; ny++) {
Tile* tile = g_game.map.getTile(x + nx + offset, y + ny + offset, z);
if (tile) {
if (skip >= 0) {
msg.addByte(skip);
msg.addByte(0xFF);
}
skip = 0;
GetTileDescription(tile, msg);
} else if (skip == 0xFE) {
msg.addByte(0xFF);
msg.addByte(0xFF);
skip = -1;
} else {
++skip;
}
}
}
}
void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool& known, uint32_t& removedKnown)
{
auto result = knownCreatureSet.insert(id);
if (!result.second) {
known = true;
return;
}
known = false;
if (knownCreatureSet.size() > 1300) {
// Look for a creature to remove
for (auto it = knownCreatureSet.begin(), end = knownCreatureSet.end(); it != end; ++it) {
Creature* creature = g_game.getCreatureByID(*it);
if (!canSee(creature)) {
removedKnown = *it;
knownCreatureSet.erase(it);
return;
}
}
// Bad situation. Let's just remove anyone.
auto it = knownCreatureSet.begin();
if (*it == id) {
++it;
}
removedKnown = *it;
knownCreatureSet.erase(it);
} else {
removedKnown = 0;
}
}
bool ProtocolGame::canSee(const Creature* c) const
{
if (!c || !player || c->isRemoved()) {
return false;
}
if (!player->canSeeCreature(c)) {
return false;
}
return canSee(c->getPosition());
}
bool ProtocolGame::canSee(const Position& pos) const
{
return canSee(pos.x, pos.y, pos.z);
}
bool ProtocolGame::canSee(int32_t x, int32_t y, int32_t z) const
{
if (!player) {
return false;
}
const Position& myPos = player->getPosition();
if (myPos.z <= 7) {
//we are on ground level or above (7 -> 0)
//view is from 7 -> 0
if (z > 7) {
return false;
}
} else if (myPos.z >= 8) {
//we are underground (8 -> 15)
//view is +/- 2 from the floor we stand on
if (std::abs(myPos.getZ() - z) > 2) {
return false;
}
}
//negative offset means that the action taken place is on a lower floor than ourself
int32_t offsetz = myPos.getZ() - z;
if ((x >= myPos.getX() - 8 + offsetz) && (x <= myPos.getX() + 9 + offsetz) &&
(y >= myPos.getY() - 6 + offsetz) && (y <= myPos.getY() + 7 + offsetz)) {
return true;
}
return false;
}
// Parse methods
void ProtocolGame::parseChannelInvite(NetworkMessage& msg)
{
const std::string name = msg.getString();
addGameTask(&Game::playerChannelInvite, player->getID(), name);
}
void ProtocolGame::parseChannelExclude(NetworkMessage& msg)
{
const std::string name = msg.getString();
addGameTask(&Game::playerChannelExclude, player->getID(), name);
}
void ProtocolGame::parseOpenChannel(NetworkMessage& msg)
{
uint16_t channelId = msg.get<uint16_t>();
addGameTask(&Game::playerOpenChannel, player->getID(), channelId);
}
void ProtocolGame::parseCloseChannel(NetworkMessage& msg)
{
uint16_t channelId = msg.get<uint16_t>();
addGameTask(&Game::playerCloseChannel, player->getID(), channelId);
}
void ProtocolGame::parseOpenPrivateChannel(NetworkMessage& msg)
{
const std::string receiver = msg.getString();
addGameTask(&Game::playerOpenPrivateChannel, player->getID(), receiver);
}
void ProtocolGame::parseAutoWalk(NetworkMessage& msg)
{
uint8_t numdirs = msg.getByte();
if (numdirs == 0 || (msg.getBufferPosition() + numdirs) != (msg.getLength() + 8)) {
return;
}
msg.skipBytes(numdirs);
std::forward_list<Direction> path;
for (uint8_t i = 0; i < numdirs; ++i) {
uint8_t rawdir = msg.getPreviousByte();
switch (rawdir) {
case 1: path.push_front(DIRECTION_EAST); break;
case 2: path.push_front(DIRECTION_NORTHEAST); break;
case 3: path.push_front(DIRECTION_NORTH); break;
case 4: path.push_front(DIRECTION_NORTHWEST); break;
case 5: path.push_front(DIRECTION_WEST); break;
case 6: path.push_front(DIRECTION_SOUTHWEST); break;
case 7: path.push_front(DIRECTION_SOUTH); break;
case 8: path.push_front(DIRECTION_SOUTHEAST); break;
default: break;
}
}
if (path.empty()) {
return;
}
addGameTask(&Game::playerAutoWalk, player->getID(), path);
}
void ProtocolGame::parseSetOutfit(NetworkMessage& msg)
{
Outfit_t newOutfit;
newOutfit.lookType = msg.get<uint16_t>();
newOutfit.lookHead = msg.getByte();
newOutfit.lookBody = msg.getByte();
newOutfit.lookLegs = msg.getByte();
newOutfit.lookFeet = msg.getByte();
newOutfit.lookAddons = msg.getByte();
newOutfit.lookMount = msg.get<uint16_t>();
addGameTask(&Game::playerChangeOutfit, player->getID(), newOutfit);
}
void ProtocolGame::parseToggleMount(NetworkMessage& msg)
{
bool mount = msg.getByte() != 0;
addGameTask(&Game::playerToggleMount, player->getID(), mount);
}
void ProtocolGame::parseUseItem(NetworkMessage& msg)
{
Position pos = msg.getPosition();
uint16_t spriteId = msg.get<uint16_t>();
uint8_t stackpos = msg.getByte();
uint8_t index = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseItem, player->getID(), pos, stackpos, index, spriteId);
}
void ProtocolGame::parseUseItemEx(NetworkMessage& msg)
{
Position fromPos = msg.getPosition();
uint16_t fromSpriteId = msg.get<uint16_t>();
uint8_t fromStackPos = msg.getByte();
Position toPos = msg.getPosition();
uint16_t toSpriteId = msg.get<uint16_t>();
uint8_t toStackPos = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseItemEx, player->getID(), fromPos, fromStackPos, fromSpriteId, toPos, toStackPos, toSpriteId);
}
void ProtocolGame::parseUseWithCreature(NetworkMessage& msg)
{
Position fromPos = msg.getPosition();
uint16_t spriteId = msg.get<uint16_t>();
uint8_t fromStackPos = msg.getByte();
uint32_t creatureId = msg.get<uint32_t>();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerUseWithCreature, player->getID(), fromPos, fromStackPos, creatureId, spriteId);
}
void ProtocolGame::parseCloseContainer(NetworkMessage& msg)
{
uint8_t cid = msg.getByte();
addGameTask(&Game::playerCloseContainer, player->getID(), cid);
}
void ProtocolGame::parseUpArrowContainer(NetworkMessage& msg)
{
uint8_t cid = msg.getByte();
addGameTask(&Game::playerMoveUpContainer, player->getID(), cid);
}
void ProtocolGame::parseUpdateContainer(NetworkMessage& msg)
{
uint8_t cid = msg.getByte();
addGameTask(&Game::playerUpdateContainer, player->getID(), cid);
}
void ProtocolGame::parseThrow(NetworkMessage& msg)
{
Position fromPos = msg.getPosition();
uint16_t spriteId = msg.get<uint16_t>();
uint8_t fromStackpos = msg.getByte();
Position toPos = msg.getPosition();
uint8_t count = msg.getByte();
if (toPos != fromPos) {
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerMoveThing, player->getID(), fromPos, spriteId, fromStackpos, toPos, count);
}
}
void ProtocolGame::parseLookAt(NetworkMessage& msg)
{
Position pos = msg.getPosition();
msg.skipBytes(2); // spriteId
uint8_t stackpos = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookAt, player->getID(), pos, stackpos);
}
void ProtocolGame::parseLookInBattleList(NetworkMessage& msg)
{
uint32_t creatureId = msg.get<uint32_t>();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInBattleList, player->getID(), creatureId);
}
void ProtocolGame::parseSay(NetworkMessage& msg)
{
std::string receiver;
uint16_t channelId;
SpeakClasses type = static_cast<SpeakClasses>(msg.getByte());
switch (type) {
case TALKTYPE_PRIVATE_TO:
case TALKTYPE_PRIVATE_RED_TO:
receiver = msg.getString();
channelId = 0;
break;
case TALKTYPE_CHANNEL_Y:
case TALKTYPE_CHANNEL_R1:
channelId = msg.get<uint16_t>();
break;
default:
channelId = 0;
break;
}
const std::string text = msg.getString();
if (text.length() > 255) {
return;
}
addGameTask(&Game::playerSay, player->getID(), channelId, type, receiver, text);
}
void ProtocolGame::parseFightModes(NetworkMessage& msg)
{
uint8_t rawFightMode = msg.getByte(); // 1 - offensive, 2 - balanced, 3 - defensive
uint8_t rawChaseMode = msg.getByte(); // 0 - stand while fightning, 1 - chase opponent
uint8_t rawSecureMode = msg.getByte(); // 0 - can't attack unmarked, 1 - can attack unmarked
// uint8_t rawPvpMode = msg.getByte(); // pvp mode introduced in 10.0
fightMode_t fightMode;
if (rawFightMode == 1) {
fightMode = FIGHTMODE_ATTACK;
} else if (rawFightMode == 2) {
fightMode = FIGHTMODE_BALANCED;
} else {
fightMode = FIGHTMODE_DEFENSE;
}
addGameTask(&Game::playerSetFightModes, player->getID(), fightMode, rawChaseMode != 0, rawSecureMode != 0);
}
void ProtocolGame::parseAttack(NetworkMessage& msg)
{
uint32_t creatureId = msg.get<uint32_t>();
// msg.get<uint32_t>(); creatureId (same as above)
addGameTask(&Game::playerSetAttackedCreature, player->getID(), creatureId);
}
void ProtocolGame::parseFollow(NetworkMessage& msg)
{
uint32_t creatureId = msg.get<uint32_t>();
// msg.get<uint32_t>(); creatureId (same as above)
addGameTask(&Game::playerFollowCreature, player->getID(), creatureId);
}
void ProtocolGame::parseEquipObject(NetworkMessage& msg)
{
uint16_t spriteId = msg.get<uint16_t>();
// msg.get<uint8_t>();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerEquipItem, player->getID(), spriteId);
}
void ProtocolGame::parseTextWindow(NetworkMessage& msg)
{
uint32_t windowTextId = msg.get<uint32_t>();
const std::string newText = msg.getString();
addGameTask(&Game::playerWriteItem, player->getID(), windowTextId, newText);
}
void ProtocolGame::parseHouseWindow(NetworkMessage& msg)
{
uint8_t doorId = msg.getByte();
uint32_t id = msg.get<uint32_t>();
const std::string text = msg.getString();
addGameTask(&Game::playerUpdateHouseWindow, player->getID(), doorId, id, text);
}
void ProtocolGame::parseWrapItem(NetworkMessage& msg)
{
Position pos = msg.getPosition();
uint16_t spriteId = msg.get<uint16_t>();
uint8_t stackpos = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerWrapItem, player->getID(), pos, stackpos, spriteId);
}
void ProtocolGame::parseLookInShop(NetworkMessage& msg)
{
uint16_t id = msg.get<uint16_t>();
uint8_t count = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInShop, player->getID(), id, count);
}
void ProtocolGame::parsePlayerPurchase(NetworkMessage& msg)
{
uint16_t id = msg.get<uint16_t>();
uint8_t count = msg.getByte();
uint8_t amount = msg.getByte();
bool ignoreCap = msg.getByte() != 0;
bool inBackpacks = msg.getByte() != 0;
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerPurchaseItem, player->getID(), id, count, amount, ignoreCap, inBackpacks);
}
void ProtocolGame::parsePlayerSale(NetworkMessage& msg)
{
uint16_t id = msg.get<uint16_t>();
uint8_t count = msg.getByte();
uint8_t amount = msg.getByte();
bool ignoreEquipped = msg.getByte() != 0;
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerSellItem, player->getID(), id, count, amount, ignoreEquipped);
}
void ProtocolGame::parseRequestTrade(NetworkMessage& msg)
{
Position pos = msg.getPosition();
uint16_t spriteId = msg.get<uint16_t>();
uint8_t stackpos = msg.getByte();
uint32_t playerId = msg.get<uint32_t>();
addGameTask(&Game::playerRequestTrade, player->getID(), pos, stackpos, playerId, spriteId);
}
void ProtocolGame::parseLookInTrade(NetworkMessage& msg)
{
bool counterOffer = (msg.getByte() == 0x01);
uint8_t index = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerLookInTrade, player->getID(), counterOffer, index);
}
void ProtocolGame::parseAddVip(NetworkMessage& msg)
{
const std::string name = msg.getString();
addGameTask(&Game::playerRequestAddVip, player->getID(), name);
}
void ProtocolGame::parseRemoveVip(NetworkMessage& msg)
{
uint32_t guid = msg.get<uint32_t>();
addGameTask(&Game::playerRequestRemoveVip, player->getID(), guid);
}
void ProtocolGame::parseEditVip(NetworkMessage& msg)
{
uint32_t guid = msg.get<uint32_t>();
const std::string description = msg.getString();
uint32_t icon = std::min<uint32_t>(10, msg.get<uint32_t>()); // 10 is max icon in 9.63
bool notify = msg.getByte() != 0;
addGameTask(&Game::playerRequestEditVip, player->getID(), guid, description, icon, notify);
}
void ProtocolGame::parseRotateItem(NetworkMessage& msg)
{
Position pos = msg.getPosition();
uint16_t spriteId = msg.get<uint16_t>();
uint8_t stackpos = msg.getByte();
addGameTaskTimed(DISPATCHER_TASK_EXPIRATION, &Game::playerRotateItem, player->getID(), pos, stackpos, spriteId);
}
void ProtocolGame::parseRuleViolationReport(NetworkMessage& msg)
{
uint8_t reportType = msg.getByte();
uint8_t reportReason = msg.getByte();
const std::string& targetName = msg.getString();
const std::string& comment = msg.getString();
std::string translation;
if (reportType == REPORT_TYPE_NAME) {
translation = msg.getString();
} else if (reportType == REPORT_TYPE_STATEMENT) {
translation = msg.getString();
msg.get<uint32_t>(); // statement id, used to get whatever player have said, we don't log that.
}
addGameTask(&Game::playerReportRuleViolation, player->getID(), targetName, reportType, reportReason, comment, translation);
}
void ProtocolGame::parseBugReport(NetworkMessage& msg)
{
uint8_t category = msg.getByte();
std::string message = msg.getString();
Position position;
if (category == BUG_CATEGORY_MAP) {
position = msg.getPosition();
}
addGameTask(&Game::playerReportBug, player->getID(), message, position, category);
}
void ProtocolGame::parseDebugAssert(NetworkMessage& msg)
{
if (debugAssertSent) {
return;
}
debugAssertSent = true;
std::string assertLine = msg.getString();
std::string date = msg.getString();
std::string description = msg.getString();
std::string comment = msg.getString();
addGameTask(&Game::playerDebugAssert, player->getID(), assertLine, date, description, comment);
}
void ProtocolGame::parseInviteToParty(NetworkMessage& msg)
{
uint32_t targetId = msg.get<uint32_t>();
addGameTask(&Game::playerInviteToParty, player->getID(), targetId);
}
void ProtocolGame::parseJoinParty(NetworkMessage& msg)
{
uint32_t targetId = msg.get<uint32_t>();
addGameTask(&Game::playerJoinParty, player->getID(), targetId);
}
void ProtocolGame::parseRevokePartyInvite(NetworkMessage& msg)
{
uint32_t targetId = msg.get<uint32_t>();
addGameTask(&Game::playerRevokePartyInvitation, player->getID(), targetId);
}
void ProtocolGame::parsePassPartyLeadership(NetworkMessage& msg)
{
uint32_t targetId = msg.get<uint32_t>();
addGameTask(&Game::playerPassPartyLeadership, player->getID(), targetId);
}
void ProtocolGame::parseEnableSharedPartyExperience(NetworkMessage& msg)
{
bool sharedExpActive = msg.getByte() == 1;
addGameTask(&Game::playerEnableSharedPartyExperience, player->getID(), sharedExpActive);
}
void ProtocolGame::parseQuestLine(NetworkMessage& msg)
{
uint16_t questId = msg.get<uint16_t>();
addGameTask(&Game::playerShowQuestLine, player->getID(), questId);
}
void ProtocolGame::parseMarketLeave()
{
addGameTask(&Game::playerLeaveMarket, player->getID());
}
void ProtocolGame::parseMarketBrowse(NetworkMessage& msg)
{
uint16_t browseId = msg.get<uint16_t>();
if (browseId == MARKETREQUEST_OWN_OFFERS) {
addGameTask(&Game::playerBrowseMarketOwnOffers, player->getID());
} else if (browseId == MARKETREQUEST_OWN_HISTORY) {
addGameTask(&Game::playerBrowseMarketOwnHistory, player->getID());
} else {
addGameTask(&Game::playerBrowseMarket, player->getID(), browseId);
}
}
void ProtocolGame::parseMarketCreateOffer(NetworkMessage& msg)
{
uint8_t type = msg.getByte();
uint16_t spriteId = msg.get<uint16_t>();
uint16_t amount = msg.get<uint16_t>();
uint32_t price = msg.get<uint32_t>();
bool anonymous = (msg.getByte() != 0);
addGameTask(&Game::playerCreateMarketOffer, player->getID(), type, spriteId, amount, price, anonymous);
}
void ProtocolGame::parseMarketCancelOffer(NetworkMessage& msg)
{
uint32_t timestamp = msg.get<uint32_t>();
uint16_t counter = msg.get<uint16_t>();
addGameTask(&Game::playerCancelMarketOffer, player->getID(), timestamp, counter);
}
void ProtocolGame::parseMarketAcceptOffer(NetworkMessage& msg)
{
uint32_t timestamp = msg.get<uint32_t>();
uint16_t counter = msg.get<uint16_t>();
uint16_t amount = msg.get<uint16_t>();
addGameTask(&Game::playerAcceptMarketOffer, player->getID(), timestamp, counter, amount);
}
void ProtocolGame::parseModalWindowAnswer(NetworkMessage& msg)
{
uint32_t id = msg.get<uint32_t>();
uint8_t button = msg.getByte();
uint8_t choice = msg.getByte();
addGameTask(&Game::playerAnswerModalWindow, player->getID(), id, button, choice);
}
void ProtocolGame::parseBrowseField(NetworkMessage& msg)
{
const Position& pos = msg.getPosition();
addGameTask(&Game::playerBrowseField, player->getID(), pos);
}
void ProtocolGame::parseSeekInContainer(NetworkMessage& msg)
{
uint8_t containerId = msg.getByte();
uint16_t index = msg.get<uint16_t>();
addGameTask(&Game::playerSeekInContainer, player->getID(), containerId, index);
}
// Send methods
void ProtocolGame::sendOpenPrivateChannel(const std::string& receiver)
{
NetworkMessage msg;
msg.addByte(0xAD);
msg.addString(receiver);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string& playerName, ChannelEvent_t channelEvent)
{
NetworkMessage msg;
msg.addByte(0xF3);
msg.add<uint16_t>(channelId);
msg.addString(playerName);
msg.addByte(channelEvent);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureOutfit(const Creature* creature, const Outfit_t& outfit)
{
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
msg.addByte(0x8E);
msg.add<uint32_t>(creature->getID());
AddOutfit(msg, outfit);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureLight(const Creature* creature)
{
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
AddCreatureLight(msg, creature);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendWorldLight(LightInfo lightInfo)
{
NetworkMessage msg;
AddWorldLight(msg, lightInfo);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureWalkthrough(const Creature* creature, bool walkthrough)
{
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
msg.addByte(0x92);
msg.add<uint32_t>(creature->getID());
msg.addByte(walkthrough ? 0x00 : 0x01);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureShield(const Creature* creature)
{
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
msg.addByte(0x91);
msg.add<uint32_t>(creature->getID());
msg.addByte(player->getPartyShield(creature->getPlayer()));
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureSkull(const Creature* creature)
{
if (g_game.getWorldType() != WORLD_TYPE_PVP) {
return;
}
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
msg.addByte(0x90);
msg.add<uint32_t>(creature->getID());
msg.addByte(player->getSkullClient(creature));
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureType(uint32_t creatureId, uint8_t creatureType)
{
NetworkMessage msg;
msg.addByte(0x95);
msg.add<uint32_t>(creatureId);
msg.addByte(creatureType);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureHelpers(uint32_t creatureId, uint16_t helpers)
{
NetworkMessage msg;
msg.addByte(0x94);
msg.add<uint32_t>(creatureId);
msg.add<uint16_t>(helpers);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureSquare(const Creature* creature, SquareColor_t color)
{
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
msg.addByte(0x93);
msg.add<uint32_t>(creature->getID());
msg.addByte(0x01);
msg.addByte(color);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendTutorial(uint8_t tutorialId)
{
NetworkMessage msg;
msg.addByte(0xDC);
msg.addByte(tutorialId);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendAddMarker(const Position& pos, uint8_t markType, const std::string& desc)
{
NetworkMessage msg;
msg.addByte(0xDD);
msg.addPosition(pos);
msg.addByte(markType);
msg.addString(desc);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendReLoginWindow(uint8_t unfairFightReduction)
{
NetworkMessage msg;
msg.addByte(0x28);
msg.addByte(0x00);
msg.addByte(unfairFightReduction);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendStats()
{
NetworkMessage msg;
AddPlayerStats(msg);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendBasicData()
{
NetworkMessage msg;
msg.addByte(0x9F);
if (player->isPremium()) {
msg.addByte(1);
msg.add<uint32_t>(time(nullptr) + (player->premiumDays * 86400));
} else {
msg.addByte(0);
msg.add<uint32_t>(0);
}
msg.addByte(player->getVocation()->getClientId());
msg.add<uint16_t>(0xFF); // number of known spells
for (uint8_t spellId = 0x00; spellId < 0xFF; spellId++) {
msg.addByte(spellId);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendTextMessage(const TextMessage& message)
{
NetworkMessage msg;
msg.addByte(0xB4);
msg.addByte(message.type);
switch (message.type) {
case MESSAGE_DAMAGE_DEALT:
case MESSAGE_DAMAGE_RECEIVED:
case MESSAGE_DAMAGE_OTHERS: {
msg.addPosition(message.position);
msg.add<uint32_t>(message.primary.value);
msg.addByte(message.primary.color);
msg.add<uint32_t>(message.secondary.value);
msg.addByte(message.secondary.color);
break;
}
case MESSAGE_HEALED:
case MESSAGE_HEALED_OTHERS:
case MESSAGE_EXPERIENCE:
case MESSAGE_EXPERIENCE_OTHERS: {
msg.addPosition(message.position);
msg.add<uint32_t>(message.primary.value);
msg.addByte(message.primary.color);
break;
}
case MESSAGE_GUILD:
case MESSAGE_PARTY_MANAGEMENT:
case MESSAGE_PARTY:
msg.add<uint16_t>(message.channelId);
break;
default: {
break;
}
}
msg.addString(message.text);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendClosePrivate(uint16_t channelId)
{
NetworkMessage msg;
msg.addByte(0xB3);
msg.add<uint16_t>(channelId);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatePrivateChannel(uint16_t channelId, const std::string& channelName)
{
NetworkMessage msg;
msg.addByte(0xB2);
msg.add<uint16_t>(channelId);
msg.addString(channelName);
msg.add<uint16_t>(0x01);
msg.addString(player->getName());
msg.add<uint16_t>(0x00);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendChannelsDialog()
{
NetworkMessage msg;
msg.addByte(0xAB);
const ChannelList& list = g_chat->getChannelList(*player);
msg.addByte(list.size());
for (ChatChannel* channel : list) {
msg.add<uint16_t>(channel->getId());
msg.addString(channel->getName());
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendChannel(uint16_t channelId, const std::string& channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers)
{
NetworkMessage msg;
msg.addByte(0xAC);
msg.add<uint16_t>(channelId);
msg.addString(channelName);
if (channelUsers) {
msg.add<uint16_t>(channelUsers->size());
for (const auto& it : *channelUsers) {
msg.addString(it.second->getName());
}
} else {
msg.add<uint16_t>(0x00);
}
if (invitedUsers) {
msg.add<uint16_t>(invitedUsers->size());
for (const auto& it : *invitedUsers) {
msg.addString(it.second->getName());
}
} else {
msg.add<uint16_t>(0x00);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendChannelMessage(const std::string& author, const std::string& text, SpeakClasses type, uint16_t channel)
{
NetworkMessage msg;
msg.addByte(0xAA);
msg.add<uint32_t>(0x00);
msg.addString(author);
msg.add<uint16_t>(0x00);
msg.addByte(type);
msg.add<uint16_t>(channel);
msg.addString(text);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendIcons(uint16_t icons)
{
NetworkMessage msg;
msg.addByte(0xA2);
msg.add<uint16_t>(icons);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendContainer(uint8_t cid, const Container* container, bool hasParent, uint16_t firstIndex)
{
NetworkMessage msg;
msg.addByte(0x6E);
msg.addByte(cid);
if (container->getID() == ITEM_BROWSEFIELD) {
msg.addItem(ITEM_BAG, 1);
msg.addString("Browse Field");
} else {
msg.addItem(container);
msg.addString(container->getName());
}
msg.addByte(container->capacity());
msg.addByte(hasParent ? 0x01 : 0x00);
msg.addByte(container->isUnlocked() ? 0x01 : 0x00); // Drag and drop
msg.addByte(container->hasPagination() ? 0x01 : 0x00); // Pagination
uint32_t containerSize = container->size();
msg.add<uint16_t>(containerSize);
msg.add<uint16_t>(firstIndex);
if (firstIndex < containerSize) {
uint8_t itemsToSend = std::min<uint32_t>(std::min<uint32_t>(container->capacity(), containerSize - firstIndex), std::numeric_limits<uint8_t>::max());
msg.addByte(itemsToSend);
for (auto it = container->getItemList().begin() + firstIndex, end = it + itemsToSend; it != end; ++it) {
msg.addItem(*it);
}
} else {
msg.addByte(0x00);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendShop(Npc* npc, const ShopInfoList& itemList)
{
NetworkMessage msg;
msg.addByte(0x7A);
msg.addString(npc->getName());
uint16_t itemsToSend = std::min<size_t>(itemList.size(), std::numeric_limits<uint16_t>::max());
msg.add<uint16_t>(itemsToSend);
uint16_t i = 0;
for (auto it = itemList.begin(); i < itemsToSend; ++it, ++i) {
AddShopItem(msg, *it);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCloseShop()
{
NetworkMessage msg;
msg.addByte(0x7C);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendSaleItemList(const std::list<ShopInfo>& shop)
{
NetworkMessage msg;
msg.addByte(0x7B);
msg.add<uint64_t>(player->getMoney() + player->getBankBalance());
std::map<uint16_t, uint32_t> saleMap;
if (shop.size() <= 5) {
// For very small shops it's not worth it to create the complete map
for (const ShopInfo& shopInfo : shop) {
if (shopInfo.sellPrice == 0) {
continue;
}
int8_t subtype = -1;
const ItemType& itemType = Item::items[shopInfo.itemId];
if (itemType.hasSubType() && !itemType.stackable) {
subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType);
}
uint32_t count = player->getItemTypeCount(shopInfo.itemId, subtype);
if (count > 0) {
saleMap[shopInfo.itemId] = count;
}
}
} else {
// Large shop, it's better to get a cached map of all item counts and use it
// We need a temporary map since the finished map should only contain items
// available in the shop
std::map<uint32_t, uint32_t> tempSaleMap;
player->getAllItemTypeCount(tempSaleMap);
// We must still check manually for the special items that require subtype matches
// (That is, fluids such as potions etc., actually these items are very few since
// health potions now use their own ID)
for (const ShopInfo& shopInfo : shop) {
if (shopInfo.sellPrice == 0) {
continue;
}
int8_t subtype = -1;
const ItemType& itemType = Item::items[shopInfo.itemId];
if (itemType.hasSubType() && !itemType.stackable) {
subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType);
}
if (subtype != -1) {
uint32_t count;
if (!itemType.isFluidContainer() && !itemType.isSplash()) {
count = player->getItemTypeCount(shopInfo.itemId, subtype); // This shop item requires extra checks
} else {
count = subtype;
}
if (count > 0) {
saleMap[shopInfo.itemId] = count;
}
} else {
std::map<uint32_t, uint32_t>::const_iterator findIt = tempSaleMap.find(shopInfo.itemId);
if (findIt != tempSaleMap.end() && findIt->second > 0) {
saleMap[shopInfo.itemId] = findIt->second;
}
}
}
}
uint8_t itemsToSend = std::min<size_t>(saleMap.size(), std::numeric_limits<uint8_t>::max());
msg.addByte(itemsToSend);
uint8_t i = 0;
for (std::map<uint16_t, uint32_t>::const_iterator it = saleMap.begin(); i < itemsToSend; ++it, ++i) {
msg.addItemId(it->first);
msg.addByte(std::min<uint32_t>(it->second, std::numeric_limits<uint8_t>::max()));
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketEnter(uint32_t depotId)
{
NetworkMessage msg;
msg.addByte(0xF6);
msg.add<uint64_t>(player->getBankBalance());
msg.addByte(std::min<uint32_t>(IOMarket::getPlayerOfferCount(player->getGUID()), std::numeric_limits<uint8_t>::max()));
DepotChest* depotChest = player->getDepotChest(depotId, false);
if (!depotChest) {
msg.add<uint16_t>(0x00);
writeToOutputBuffer(msg);
return;
}
player->setInMarket(true);
std::map<uint16_t, uint32_t> depotItems;
std::forward_list<Container*> containerList { depotChest, player->getInbox() };
do {
Container* container = containerList.front();
containerList.pop_front();
for (Item* item : container->getItemList()) {
Container* c = item->getContainer();
if (c && !c->empty()) {
containerList.push_front(c);
continue;
}
const ItemType& itemType = Item::items[item->getID()];
if (itemType.wareId == 0) {
continue;
}
if (c && (!itemType.isContainer() || c->capacity() != itemType.maxItems)) {
continue;
}
if (!item->hasMarketAttributes()) {
continue;
}
depotItems[itemType.wareId] += Item::countByType(item, -1);
}
} while (!containerList.empty());
uint16_t itemsToSend = std::min<size_t>(depotItems.size(), std::numeric_limits<uint16_t>::max());
msg.add<uint16_t>(itemsToSend);
uint16_t i = 0;
for (std::map<uint16_t, uint32_t>::const_iterator it = depotItems.begin(); i < itemsToSend; ++it, ++i) {
msg.add<uint16_t>(it->first);
msg.add<uint16_t>(std::min<uint32_t>(0xFFFF, it->second));
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketLeave()
{
NetworkMessage msg;
msg.addByte(0xF7);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketBrowseItem(uint16_t itemId, const MarketOfferList& buyOffers, const MarketOfferList& sellOffers)
{
NetworkMessage msg;
msg.addByte(0xF9);
msg.addItemId(itemId);
msg.add<uint32_t>(buyOffers.size());
for (const MarketOffer& offer : buyOffers) {
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
msg.addString(offer.playerName);
}
msg.add<uint32_t>(sellOffers.size());
for (const MarketOffer& offer : sellOffers) {
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
msg.addString(offer.playerName);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketAcceptOffer(const MarketOfferEx& offer)
{
NetworkMessage msg;
msg.addByte(0xF9);
msg.addItemId(offer.itemId);
if (offer.type == MARKETACTION_BUY) {
msg.add<uint32_t>(0x01);
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
msg.addString(offer.playerName);
msg.add<uint32_t>(0x00);
} else {
msg.add<uint32_t>(0x00);
msg.add<uint32_t>(0x01);
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
msg.addString(offer.playerName);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketBrowseOwnOffers(const MarketOfferList& buyOffers, const MarketOfferList& sellOffers)
{
NetworkMessage msg;
msg.addByte(0xF9);
msg.add<uint16_t>(MARKETREQUEST_OWN_OFFERS);
msg.add<uint32_t>(buyOffers.size());
for (const MarketOffer& offer : buyOffers) {
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.addItemId(offer.itemId);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
}
msg.add<uint32_t>(sellOffers.size());
for (const MarketOffer& offer : sellOffers) {
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.addItemId(offer.itemId);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketCancelOffer(const MarketOfferEx& offer)
{
NetworkMessage msg;
msg.addByte(0xF9);
msg.add<uint16_t>(MARKETREQUEST_OWN_OFFERS);
if (offer.type == MARKETACTION_BUY) {
msg.add<uint32_t>(0x01);
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.addItemId(offer.itemId);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
msg.add<uint32_t>(0x00);
} else {
msg.add<uint32_t>(0x00);
msg.add<uint32_t>(0x01);
msg.add<uint32_t>(offer.timestamp);
msg.add<uint16_t>(offer.counter);
msg.addItemId(offer.itemId);
msg.add<uint16_t>(offer.amount);
msg.add<uint32_t>(offer.price);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketBrowseOwnHistory(const HistoryMarketOfferList& buyOffers, const HistoryMarketOfferList& sellOffers)
{
uint32_t i = 0;
std::map<uint32_t, uint16_t> counterMap;
uint32_t buyOffersToSend = std::min<uint32_t>(buyOffers.size(), 810 + std::max<int32_t>(0, 810 - sellOffers.size()));
uint32_t sellOffersToSend = std::min<uint32_t>(sellOffers.size(), 810 + std::max<int32_t>(0, 810 - buyOffers.size()));
NetworkMessage msg;
msg.addByte(0xF9);
msg.add<uint16_t>(MARKETREQUEST_OWN_HISTORY);
msg.add<uint32_t>(buyOffersToSend);
for (auto it = buyOffers.begin(); i < buyOffersToSend; ++it, ++i) {
msg.add<uint32_t>(it->timestamp);
msg.add<uint16_t>(counterMap[it->timestamp]++);
msg.addItemId(it->itemId);
msg.add<uint16_t>(it->amount);
msg.add<uint32_t>(it->price);
msg.addByte(it->state);
}
counterMap.clear();
i = 0;
msg.add<uint32_t>(sellOffersToSend);
for (auto it = sellOffers.begin(); i < sellOffersToSend; ++it, ++i) {
msg.add<uint32_t>(it->timestamp);
msg.add<uint16_t>(counterMap[it->timestamp]++);
msg.addItemId(it->itemId);
msg.add<uint16_t>(it->amount);
msg.add<uint32_t>(it->price);
msg.addByte(it->state);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMarketDetail(uint16_t itemId)
{
NetworkMessage msg;
msg.addByte(0xF8);
msg.addItemId(itemId);
const ItemType& it = Item::items[itemId];
if (it.armor != 0) {
msg.addString(std::to_string(it.armor));
} else {
msg.add<uint16_t>(0x00);
}
if (it.attack != 0) {
// TODO: chance to hit, range
// example:
// "attack +x, chance to hit +y%, z fields"
if (it.abilities && it.abilities->elementType != COMBAT_NONE && it.abilities->elementDamage != 0) {
std::ostringstream ss;
ss << it.attack << " physical +" << it.abilities->elementDamage << ' ' << getCombatName(it.abilities->elementType);
msg.addString(ss.str());
} else {
msg.addString(std::to_string(it.attack));
}
} else {
msg.add<uint16_t>(0x00);
}
if (it.isContainer()) {
msg.addString(std::to_string(it.maxItems));
} else {
msg.add<uint16_t>(0x00);
}
if (it.defense != 0) {
if (it.extraDefense != 0) {
std::ostringstream ss;
ss << it.defense << ' ' << std::showpos << it.extraDefense << std::noshowpos;
msg.addString(ss.str());
} else {
msg.addString(std::to_string(it.defense));
}
} else {
msg.add<uint16_t>(0x00);
}
if (!it.description.empty()) {
const std::string& descr = it.description;
if (descr.back() == '.') {
msg.addString(std::string(descr, 0, descr.length() - 1));
} else {
msg.addString(descr);
}
} else {
msg.add<uint16_t>(0x00);
}
if (it.decayTime != 0) {
std::ostringstream ss;
ss << it.decayTime << " seconds";
msg.addString(ss.str());
} else {
msg.add<uint16_t>(0x00);
}
if (it.abilities) {
std::ostringstream ss;
bool separator = false;
for (size_t i = 0; i < COMBAT_COUNT; ++i) {
if (it.abilities->absorbPercent[i] == 0) {
continue;
}
if (separator) {
ss << ", ";
} else {
separator = true;
}
ss << getCombatName(indexToCombatType(i)) << ' ' << std::showpos << it.abilities->absorbPercent[i] << std::noshowpos << '%';
}
msg.addString(ss.str());
} else {
msg.add<uint16_t>(0x00);
}
if (it.minReqLevel != 0) {
msg.addString(std::to_string(it.minReqLevel));
} else {
msg.add<uint16_t>(0x00);
}
if (it.minReqMagicLevel != 0) {
msg.addString(std::to_string(it.minReqMagicLevel));
} else {
msg.add<uint16_t>(0x00);
}
msg.addString(it.vocationString);
msg.addString(it.runeSpellName);
if (it.abilities) {
std::ostringstream ss;
bool separator = false;
for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; i++) {
if (!it.abilities->skills[i]) {
continue;
}
if (separator) {
ss << ", ";
} else {
separator = true;
}
ss << getSkillName(i) << ' ' << std::showpos << it.abilities->skills[i] << std::noshowpos;
}
if (it.abilities->stats[STAT_MAGICPOINTS] != 0) {
if (separator) {
ss << ", ";
} else {
separator = true;
}
ss << "magic level " << std::showpos << it.abilities->stats[STAT_MAGICPOINTS] << std::noshowpos;
}
if (it.abilities->speed != 0) {
if (separator) {
ss << ", ";
}
ss << "speed " << std::showpos << (it.abilities->speed >> 1) << std::noshowpos;
}
msg.addString(ss.str());
} else {
msg.add<uint16_t>(0x00);
}
if (it.charges != 0) {
msg.addString(std::to_string(it.charges));
} else {
msg.add<uint16_t>(0x00);
}
std::string weaponName = getWeaponName(it.weaponType);
if (it.slotPosition & SLOTP_TWO_HAND) {
if (!weaponName.empty()) {
weaponName += ", two-handed";
} else {
weaponName = "two-handed";
}
}
msg.addString(weaponName);
if (it.weight != 0) {
std::ostringstream ss;
if (it.weight < 10) {
ss << "0.0" << it.weight;
} else if (it.weight < 100) {
ss << "0." << it.weight;
} else {
std::string weightString = std::to_string(it.weight);
weightString.insert(weightString.end() - 2, '.');
ss << weightString;
}
ss << " oz";
msg.addString(ss.str());
} else {
msg.add<uint16_t>(0x00);
}
MarketStatistics* statistics = IOMarket::getInstance().getPurchaseStatistics(itemId);
if (statistics) {
msg.addByte(0x01);
msg.add<uint32_t>(statistics->numTransactions);
msg.add<uint32_t>(std::min<uint64_t>(std::numeric_limits<uint32_t>::max(), statistics->totalPrice));
msg.add<uint32_t>(statistics->highestPrice);
msg.add<uint32_t>(statistics->lowestPrice);
} else {
msg.addByte(0x00);
}
statistics = IOMarket::getInstance().getSaleStatistics(itemId);
if (statistics) {
msg.addByte(0x01);
msg.add<uint32_t>(statistics->numTransactions);
msg.add<uint32_t>(std::min<uint64_t>(std::numeric_limits<uint32_t>::max(), statistics->totalPrice));
msg.add<uint32_t>(statistics->highestPrice);
msg.add<uint32_t>(statistics->lowestPrice);
} else {
msg.addByte(0x00);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendQuestLog()
{
NetworkMessage msg;
msg.addByte(0xF0);
msg.add<uint16_t>(g_game.quests.getQuestsCount(player));
for (const Quest& quest : g_game.quests.getQuests()) {
if (quest.isStarted(player)) {
msg.add<uint16_t>(quest.getID());
msg.addString(quest.getName());
msg.addByte(quest.isCompleted(player));
}
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendQuestLine(const Quest* quest)
{
NetworkMessage msg;
msg.addByte(0xF1);
msg.add<uint16_t>(quest->getID());
msg.addByte(quest->getMissionsCount(player));
for (const Mission& mission : quest->getMissions()) {
if (mission.isStarted(player)) {
msg.addString(mission.getName(player));
msg.addString(mission.getDescription(player));
}
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendTradeItemRequest(const std::string& traderName, const Item* item, bool ack)
{
NetworkMessage msg;
if (ack) {
msg.addByte(0x7D);
} else {
msg.addByte(0x7E);
}
msg.addString(traderName);
if (const Container* tradeContainer = item->getContainer()) {
std::list<const Container*> listContainer {tradeContainer};
std::list<const Item*> itemList {tradeContainer};
while (!listContainer.empty()) {
const Container* container = listContainer.front();
listContainer.pop_front();
for (Item* containerItem : container->getItemList()) {
Container* tmpContainer = containerItem->getContainer();
if (tmpContainer) {
listContainer.push_back(tmpContainer);
}
itemList.push_back(containerItem);
}
}
msg.addByte(itemList.size());
for (const Item* listItem : itemList) {
msg.addItem(listItem);
}
} else {
msg.addByte(0x01);
msg.addItem(item);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCloseTrade()
{
NetworkMessage msg;
msg.addByte(0x7F);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCloseContainer(uint8_t cid)
{
NetworkMessage msg;
msg.addByte(0x6F);
msg.addByte(cid);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureTurn(const Creature* creature, uint32_t stackPos)
{
if (!canSee(creature)) {
return;
}
NetworkMessage msg;
msg.addByte(0x6B);
msg.addPosition(creature->getPosition());
msg.addByte(stackPos);
msg.add<uint16_t>(0x63);
msg.add<uint32_t>(creature->getID());
msg.addByte(creature->getDirection());
msg.addByte(player->canWalkthroughEx(creature) ? 0x00 : 0x01);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureSay(const Creature* creature, SpeakClasses type, const std::string& text, const Position* pos/* = nullptr*/)
{
NetworkMessage msg;
msg.addByte(0xAA);
static uint32_t statementId = 0;
msg.add<uint32_t>(++statementId);
msg.addString(creature->getName());
//Add level only for players
if (const Player* speaker = creature->getPlayer()) {
msg.add<uint16_t>(speaker->getLevel());
} else {
msg.add<uint16_t>(0x00);
}
msg.addByte(type);
if (pos) {
msg.addPosition(*pos);
} else {
msg.addPosition(creature->getPosition());
}
msg.addString(text);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendToChannel(const Creature* creature, SpeakClasses type, const std::string& text, uint16_t channelId)
{
NetworkMessage msg;
msg.addByte(0xAA);
static uint32_t statementId = 0;
msg.add<uint32_t>(++statementId);
if (!creature) {
msg.add<uint32_t>(0x00);
} else if (type == TALKTYPE_CHANNEL_R2) {
msg.add<uint32_t>(0x00);
type = TALKTYPE_CHANNEL_R1;
} else {
msg.addString(creature->getName());
//Add level only for players
if (const Player* speaker = creature->getPlayer()) {
msg.add<uint16_t>(speaker->getLevel());
} else {
msg.add<uint16_t>(0x00);
}
}
msg.addByte(type);
msg.add<uint16_t>(channelId);
msg.addString(text);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendPrivateMessage(const Player* speaker, SpeakClasses type, const std::string& text)
{
NetworkMessage msg;
msg.addByte(0xAA);
static uint32_t statementId = 0;
msg.add<uint32_t>(++statementId);
if (speaker) {
msg.addString(speaker->getName());
msg.add<uint16_t>(speaker->getLevel());
} else {
msg.add<uint32_t>(0x00);
}
msg.addByte(type);
msg.addString(text);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCancelTarget()
{
NetworkMessage msg;
msg.addByte(0xA3);
msg.add<uint32_t>(0x00);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendChangeSpeed(const Creature* creature, uint32_t speed)
{
NetworkMessage msg;
msg.addByte(0x8F);
msg.add<uint32_t>(creature->getID());
msg.add<uint16_t>(creature->getBaseSpeed() / 2);
msg.add<uint16_t>(speed / 2);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCancelWalk()
{
NetworkMessage msg;
msg.addByte(0xB5);
msg.addByte(player->getDirection());
writeToOutputBuffer(msg);
}
void ProtocolGame::sendSkills()
{
NetworkMessage msg;
AddPlayerSkills(msg);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendPing()
{
NetworkMessage msg;
msg.addByte(0x1D);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendPingBack()
{
NetworkMessage msg;
msg.addByte(0x1E);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendDistanceShoot(const Position& from, const Position& to, uint8_t type)
{
NetworkMessage msg;
msg.addByte(0x85);
msg.addPosition(from);
msg.addPosition(to);
msg.addByte(type);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendMagicEffect(const Position& pos, uint8_t type)
{
if (!canSee(pos)) {
return;
}
NetworkMessage msg;
msg.addByte(0x83);
msg.addPosition(pos);
msg.addByte(type);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendCreatureHealth(const Creature* creature)
{
NetworkMessage msg;
msg.addByte(0x8C);
msg.add<uint32_t>(creature->getID());
if (creature->isHealthHidden()) {
msg.addByte(0x00);
} else {
msg.addByte(std::ceil((static_cast<double>(creature->getHealth()) / std::max<int32_t>(creature->getMaxHealth(), 1)) * 100));
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendFYIBox(const std::string& message)
{
NetworkMessage msg;
msg.addByte(0x15);
msg.addString(message);
writeToOutputBuffer(msg);
}
//tile
void ProtocolGame::sendMapDescription(const Position& pos)
{
NetworkMessage msg;
msg.addByte(0x64);
msg.addPosition(player->getPosition());
GetMapDescription(pos.x - 8, pos.y - 6, pos.z, 18, 14, msg);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendAddTileItem(const Position& pos, uint32_t stackpos, const Item* item)
{
if (!canSee(pos)) {
return;
}
NetworkMessage msg;
msg.addByte(0x6A);
msg.addPosition(pos);
msg.addByte(stackpos);
msg.addItem(item);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendUpdateTileItem(const Position& pos, uint32_t stackpos, const Item* item)
{
if (!canSee(pos)) {
return;
}
NetworkMessage msg;
msg.addByte(0x6B);
msg.addPosition(pos);
msg.addByte(stackpos);
msg.addItem(item);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendRemoveTileThing(const Position& pos, uint32_t stackpos)
{
if (!canSee(pos)) {
return;
}
NetworkMessage msg;
RemoveTileThing(msg, pos, stackpos);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendUpdateTile(const Tile* tile, const Position& pos)
{
if (!canSee(pos)) {
return;
}
NetworkMessage msg;
msg.addByte(0x69);
msg.addPosition(pos);
if (tile) {
GetTileDescription(tile, msg);
msg.addByte(0x00);
msg.addByte(0xFF);
} else {
msg.addByte(0x01);
msg.addByte(0xFF);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendPendingStateEntered()
{
NetworkMessage msg;
msg.addByte(0x0A);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendEnterWorld()
{
NetworkMessage msg;
msg.addByte(0x0F);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendFightModes()
{
NetworkMessage msg;
msg.addByte(0xA7);
msg.addByte(player->fightMode);
msg.addByte(player->chaseMode);
msg.addByte(player->secureMode);
msg.addByte(PVP_MODE_DOVE);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendAddCreature(const Creature* creature, const Position& pos, int32_t stackpos, bool isLogin)
{
if (!canSee(pos)) {
return;
}
if (creature != player) {
if (stackpos != -1) {
NetworkMessage msg;
msg.addByte(0x6A);
msg.addPosition(pos);
msg.addByte(stackpos);
bool known;
uint32_t removedKnown;
checkCreatureAsKnown(creature->getID(), known, removedKnown);
AddCreature(msg, creature, known, removedKnown);
writeToOutputBuffer(msg);
}
if (isLogin) {
sendMagicEffect(pos, CONST_ME_TELEPORT);
}
return;
}
NetworkMessage msg;
msg.addByte(0x17);
msg.add<uint32_t>(player->getID());
msg.add<uint16_t>(0x32); // beat duration (50)
msg.addDouble(Creature::speedA, 3);
msg.addDouble(Creature::speedB, 3);
msg.addDouble(Creature::speedC, 3);
// can report bugs?
if (player->getAccountType() >= ACCOUNT_TYPE_TUTOR) {
msg.addByte(0x01);
} else {
msg.addByte(0x00);
}
msg.addByte(0x00); // can change pvp framing option
msg.addByte(0x00); // expert mode button enabled
msg.add<uint16_t>(0x00); // URL (string) to ingame store images
msg.add<uint16_t>(25); // premium coin package size
writeToOutputBuffer(msg);
sendPendingStateEntered();
sendEnterWorld();
sendMapDescription(pos);
if (isLogin) {
sendMagicEffect(pos, CONST_ME_TELEPORT);
}
for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) {
sendInventoryItem(static_cast<slots_t>(i), player->getInventoryItem(static_cast<slots_t>(i)));
}
sendStats();
sendSkills();
//gameworld light-settings
sendWorldLight(g_game.getWorldLightInfo());
//player light level
sendCreatureLight(creature);
sendVIPEntries();
sendBasicData();
player->sendIcons();
}
void ProtocolGame::sendMoveCreature(const Creature* creature, const Position& newPos, int32_t newStackPos, const Position& oldPos, int32_t oldStackPos, bool teleport)
{
if (creature == player) {
if (oldStackPos >= 10) {
sendMapDescription(newPos);
} else if (teleport) {
NetworkMessage msg;
RemoveTileThing(msg, oldPos, oldStackPos);
writeToOutputBuffer(msg);
sendMapDescription(newPos);
} else {
NetworkMessage msg;
if (oldPos.z == 7 && newPos.z >= 8) {
RemoveTileThing(msg, oldPos, oldStackPos);
} else {
msg.addByte(0x6D);
msg.addPosition(oldPos);
msg.addByte(oldStackPos);
msg.addPosition(newPos);
}
if (newPos.z > oldPos.z) {
MoveDownCreature(msg, creature, newPos, oldPos);
} else if (newPos.z < oldPos.z) {
MoveUpCreature(msg, creature, newPos, oldPos);
}
if (oldPos.y > newPos.y) { // north, for old x
msg.addByte(0x65);
GetMapDescription(oldPos.x - 8, newPos.y - 6, newPos.z, 18, 1, msg);
} else if (oldPos.y < newPos.y) { // south, for old x
msg.addByte(0x67);
GetMapDescription(oldPos.x - 8, newPos.y + 7, newPos.z, 18, 1, msg);
}
if (oldPos.x < newPos.x) { // east, [with new y]
msg.addByte(0x66);
GetMapDescription(newPos.x + 9, newPos.y - 6, newPos.z, 1, 14, msg);
} else if (oldPos.x > newPos.x) { // west, [with new y]
msg.addByte(0x68);
GetMapDescription(newPos.x - 8, newPos.y - 6, newPos.z, 1, 14, msg);
}
writeToOutputBuffer(msg);
}
} else if (canSee(oldPos) && canSee(creature->getPosition())) {
if (teleport || (oldPos.z == 7 && newPos.z >= 8) || oldStackPos >= 10) {
sendRemoveTileThing(oldPos, oldStackPos);
sendAddCreature(creature, newPos, newStackPos, false);
} else {
NetworkMessage msg;
msg.addByte(0x6D);
msg.addPosition(oldPos);
msg.addByte(oldStackPos);
msg.addPosition(creature->getPosition());
writeToOutputBuffer(msg);
}
} else if (canSee(oldPos)) {
sendRemoveTileThing(oldPos, oldStackPos);
} else if (canSee(creature->getPosition())) {
sendAddCreature(creature, newPos, newStackPos, false);
}
}
void ProtocolGame::sendInventoryItem(slots_t slot, const Item* item)
{
NetworkMessage msg;
if (item) {
msg.addByte(0x78);
msg.addByte(slot);
msg.addItem(item);
} else {
msg.addByte(0x79);
msg.addByte(slot);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendItems()
{
NetworkMessage msg;
msg.addByte(0xF5);
const std::vector<uint16_t>& inventory = Item::items.getInventory();
msg.add<uint16_t>(inventory.size() + 11);
for (uint16_t i = 1; i <= 11; i++) {
msg.add<uint16_t>(i);
msg.addByte(0); //always 0
msg.add<uint16_t>(1); // always 1
}
for (auto clientId : inventory) {
msg.add<uint16_t>(clientId);
msg.addByte(0); //always 0
msg.add<uint16_t>(1);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const Item* item)
{
NetworkMessage msg;
msg.addByte(0x70);
msg.addByte(cid);
msg.add<uint16_t>(slot);
msg.addItem(item);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, const Item* item)
{
NetworkMessage msg;
msg.addByte(0x71);
msg.addByte(cid);
msg.add<uint16_t>(slot);
msg.addItem(item);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, const Item* lastItem)
{
NetworkMessage msg;
msg.addByte(0x72);
msg.addByte(cid);
msg.add<uint16_t>(slot);
if (lastItem) {
msg.addItem(lastItem);
} else {
msg.add<uint16_t>(0x00);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendTextWindow(uint32_t windowTextId, Item* item, uint16_t maxlen, bool canWrite)
{
NetworkMessage msg;
msg.addByte(0x96);
msg.add<uint32_t>(windowTextId);
msg.addItem(item);
if (canWrite) {
msg.add<uint16_t>(maxlen);
msg.addString(item->getText());
} else {
const std::string& text = item->getText();
msg.add<uint16_t>(text.size());
msg.addString(text);
}
const std::string& writer = item->getWriter();
if (!writer.empty()) {
msg.addString(writer);
} else {
msg.add<uint16_t>(0x00);
}
time_t writtenDate = item->getDate();
if (writtenDate != 0) {
msg.addString(formatDateShort(writtenDate));
} else {
msg.add<uint16_t>(0x00);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendTextWindow(uint32_t windowTextId, uint32_t itemId, const std::string& text)
{
NetworkMessage msg;
msg.addByte(0x96);
msg.add<uint32_t>(windowTextId);
msg.addItem(itemId, 1);
msg.add<uint16_t>(text.size());
msg.addString(text);
msg.add<uint16_t>(0x00);
msg.add<uint16_t>(0x00);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendHouseWindow(uint32_t windowTextId, const std::string& text)
{
NetworkMessage msg;
msg.addByte(0x97);
msg.addByte(0x00);
msg.add<uint32_t>(windowTextId);
msg.addString(text);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendOutfitWindow()
{
NetworkMessage msg;
msg.addByte(0xC8);
Outfit_t currentOutfit = player->getDefaultOutfit();
Mount* currentMount = g_game.mounts.getMountByID(player->getCurrentMount());
if (currentMount) {
currentOutfit.lookMount = currentMount->clientId;
}
AddOutfit(msg, currentOutfit);
std::vector<ProtocolOutfit> protocolOutfits;
if (player->isAccessPlayer()) {
static const std::string gamemasterOutfitName = "Gamemaster";
protocolOutfits.emplace_back(gamemasterOutfitName, 75, 0);
}
const auto& outfits = Outfits::getInstance().getOutfits(player->getSex());
protocolOutfits.reserve(outfits.size());
for (const Outfit& outfit : outfits) {
uint8_t addons;
if (!player->getOutfitAddons(outfit, addons)) {
continue;
}
protocolOutfits.emplace_back(outfit.name, outfit.lookType, addons);
if (protocolOutfits.size() == 100) { // Game client doesn't allow more than 100 outfits
break;
}
}
msg.addByte(protocolOutfits.size());
for (const ProtocolOutfit& outfit : protocolOutfits) {
msg.add<uint16_t>(outfit.lookType);
msg.addString(outfit.name);
msg.addByte(outfit.addons);
}
std::vector<const Mount*> mounts;
for (const Mount& mount : g_game.mounts.getMounts()) {
if (player->hasMount(&mount)) {
mounts.push_back(&mount);
}
}
msg.addByte(mounts.size());
for (const Mount* mount : mounts) {
msg.add<uint16_t>(mount->clientId);
msg.addString(mount->name);
}
writeToOutputBuffer(msg);
}
void ProtocolGame::sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus)
{
NetworkMessage msg;
msg.addByte(0xD3);
msg.add<uint32_t>(guid);
msg.addByte(newStatus);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendVIP(uint32_t guid, const std::string& name, const std::string& description, uint32_t icon, bool notify, VipStatus_t status)
{
NetworkMessage msg;
msg.addByte(0xD2);
msg.add<uint32_t>(guid);
msg.addString(name);
msg.addString(description);
msg.add<uint32_t>(std::min<uint32_t>(10, icon));
msg.addByte(notify ? 0x01 : 0x00);
msg.addByte(status);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendVIPEntries()
{
const std::forward_list<VIPEntry>& vipEntries = IOLoginData::getVIPEntries(player->getAccount());
for (const VIPEntry& entry : vipEntries) {
VipStatus_t vipStatus = VIPSTATUS_ONLINE;
Player* vipPlayer = g_game.getPlayerByGUID(entry.guid);
if (!vipPlayer || vipPlayer->isInGhostMode() || player->isAccessPlayer()) {
vipStatus = VIPSTATUS_OFFLINE;
}
sendVIP(entry.guid, entry.name, entry.description, entry.icon, entry.notify, vipStatus);
}
}
void ProtocolGame::sendSpellCooldown(uint8_t spellId, uint32_t time)
{
NetworkMessage msg;
msg.addByte(0xA4);
msg.addByte(spellId);
msg.add<uint32_t>(time);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time)
{
NetworkMessage msg;
msg.addByte(0xA5);
msg.addByte(groupId);
msg.add<uint32_t>(time);
writeToOutputBuffer(msg);
}
void ProtocolGame::sendModalWindow(const ModalWindow& modalWindow)
{
NetworkMessage msg;
msg.addByte(0xFA);
msg.add<uint32_t>(modalWindow.id);
msg.addString(modalWindow.title);
msg.addString(modalWindow.message);
msg.addByte(modalWindow.buttons.size());
for (const auto& it : modalWindow.buttons) {
msg.addString(it.first);
msg.addByte(it.second);
}
msg.addByte(modalWindow.choices.size());
for (const auto& it : modalWindow.choices) {
msg.addString(it.first);
msg.addByte(it.second);
}
msg.addByte(modalWindow.defaultEscapeButton);
msg.addByte(modalWindow.defaultEnterButton);
msg.addByte(modalWindow.priority ? 0x01 : 0x00);
writeToOutputBuffer(msg);
}
////////////// Add common messages
void ProtocolGame::AddCreature(NetworkMessage& msg, const Creature* creature, bool known, uint32_t remove)
{
CreatureType_t creatureType = creature->getType();
const Player* otherPlayer = creature->getPlayer();
if (known) {
msg.add<uint16_t>(0x62);
msg.add<uint32_t>(creature->getID());
} else {
msg.add<uint16_t>(0x61);
msg.add<uint32_t>(remove);
msg.add<uint32_t>(creature->getID());
msg.addByte(creatureType);
msg.addString(creature->getName());
}
if (creature->isHealthHidden()) {
msg.addByte(0x00);
} else {
msg.addByte(std::ceil((static_cast<double>(creature->getHealth()) / std::max<int32_t>(creature->getMaxHealth(), 1)) * 100));
}
msg.addByte(creature->getDirection());
if (!creature->isInGhostMode() && !creature->isInvisible()) {
AddOutfit(msg, creature->getCurrentOutfit());
} else {
static Outfit_t outfit;
AddOutfit(msg, outfit);
}
LightInfo lightInfo = creature->getCreatureLight();
msg.addByte(player->isAccessPlayer() ? 0xFF : lightInfo.level);
msg.addByte(lightInfo.color);
msg.add<uint16_t>(creature->getStepSpeed() / 2);
msg.addByte(player->getSkullClient(creature));
msg.addByte(player->getPartyShield(otherPlayer));
if (!known) {
msg.addByte(player->getGuildEmblem(otherPlayer));
}
if (creatureType == CREATURETYPE_MONSTER) {
const Creature* master = creature->getMaster();
if (master) {
const Player* masterPlayer = master->getPlayer();
if (masterPlayer) {
if (masterPlayer == player) {
creatureType = CREATURETYPE_SUMMON_OWN;
} else {
creatureType = CREATURETYPE_SUMMON_OTHERS;
}
}
}
}
msg.addByte(creatureType); // Type (for summons)
msg.addByte(creature->getSpeechBubble());
msg.addByte(0xFF); // MARK_UNMARKED
if (otherPlayer) {
msg.add<uint16_t>(otherPlayer->getHelpers());
} else {
msg.add<uint16_t>(0x00);
}
msg.addByte(player->canWalkthroughEx(creature) ? 0x00 : 0x01);
}
void ProtocolGame::AddPlayerStats(NetworkMessage& msg)
{
msg.addByte(0xA0);
msg.add<uint16_t>(std::min<int32_t>(player->getHealth(), std::numeric_limits<uint16_t>::max()));
msg.add<uint16_t>(std::min<int32_t>(player->getMaxHealth(), std::numeric_limits<uint16_t>::max()));
msg.add<uint32_t>(player->getFreeCapacity());
msg.add<uint32_t>(player->getCapacity());
msg.add<uint64_t>(player->getExperience());
msg.add<uint16_t>(player->getLevel());
msg.addByte(player->getLevelPercent());
msg.add<uint16_t>(100); // base xp gain rate
msg.add<uint16_t>(0); // xp voucher
msg.add<uint16_t>(0); // low level bonus
msg.add<uint16_t>(0); // xp boost
msg.add<uint16_t>(100); // stamina multiplier (100 = x1.0)
msg.add<uint16_t>(std::min<int32_t>(player->getMana(), std::numeric_limits<uint16_t>::max()));
msg.add<uint16_t>(std::min<int32_t>(player->getMaxMana(), std::numeric_limits<uint16_t>::max()));
msg.addByte(std::min<uint32_t>(player->getMagicLevel(), std::numeric_limits<uint8_t>::max()));
msg.addByte(std::min<uint32_t>(player->getBaseMagicLevel(), std::numeric_limits<uint8_t>::max()));
msg.addByte(player->getMagicLevelPercent());
msg.addByte(player->getSoul());
msg.add<uint16_t>(player->getStaminaMinutes());
msg.add<uint16_t>(player->getBaseSpeed() / 2);
Condition* condition = player->getCondition(CONDITION_REGENERATION);
msg.add<uint16_t>(condition ? condition->getTicks() / 1000 : 0x00);
msg.add<uint16_t>(player->getOfflineTrainingTime() / 60 / 1000);
msg.add<uint16_t>(0); // xp boost time (seconds)
msg.addByte(0); // enables exp boost in the store
}
void ProtocolGame::AddPlayerSkills(NetworkMessage& msg)
{
msg.addByte(0xA1);
for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) {
msg.add<uint16_t>(std::min<int32_t>(player->getSkillLevel(i), std::numeric_limits<uint16_t>::max()));
msg.add<uint16_t>(player->getBaseSkill(i));
msg.addByte(player->getSkillPercent(i));
}
for (uint8_t i = SPECIALSKILL_FIRST; i <= SPECIALSKILL_LAST; ++i) {
msg.add<uint16_t>(std::min<int32_t>(100, player->varSpecialSkills[i]));
msg.add<uint16_t>(0);
}
}
void ProtocolGame::AddOutfit(NetworkMessage& msg, const Outfit_t& outfit)
{
msg.add<uint16_t>(outfit.lookType);
if (outfit.lookType != 0) {
msg.addByte(outfit.lookHead);
msg.addByte(outfit.lookBody);
msg.addByte(outfit.lookLegs);
msg.addByte(outfit.lookFeet);
msg.addByte(outfit.lookAddons);
} else {
msg.addItemId(outfit.lookTypeEx);
}
msg.add<uint16_t>(outfit.lookMount);
}
void ProtocolGame::AddWorldLight(NetworkMessage& msg, LightInfo lightInfo)
{
msg.addByte(0x82);
msg.addByte((player->isAccessPlayer() ? 0xFF : lightInfo.level));
msg.addByte(lightInfo.color);
}
void ProtocolGame::AddCreatureLight(NetworkMessage& msg, const Creature* creature)
{
LightInfo lightInfo = creature->getCreatureLight();
msg.addByte(0x8D);
msg.add<uint32_t>(creature->getID());
msg.addByte((player->isAccessPlayer() ? 0xFF : lightInfo.level));
msg.addByte(lightInfo.color);
}
//tile
void ProtocolGame::RemoveTileThing(NetworkMessage& msg, const Position& pos, uint32_t stackpos)
{
if (stackpos >= 10) {
return;
}
msg.addByte(0x6C);
msg.addPosition(pos);
msg.addByte(stackpos);
}
void ProtocolGame::MoveUpCreature(NetworkMessage& msg, const Creature* creature, const Position& newPos, const Position& oldPos)
{
if (creature != player) {
return;
}
//floor change up
msg.addByte(0xBE);
//going to surface
if (newPos.z == 7) {
int32_t skip = -1;
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 5, 18, 14, 3, skip); //(floor 7 and 6 already set)
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 4, 18, 14, 4, skip);
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 3, 18, 14, 5, skip);
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 2, 18, 14, 6, skip);
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 1, 18, 14, 7, skip);
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, 0, 18, 14, 8, skip);
if (skip >= 0) {
msg.addByte(skip);
msg.addByte(0xFF);
}
}
//underground, going one floor up (still underground)
else if (newPos.z > 7) {
int32_t skip = -1;
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, oldPos.getZ() - 3, 18, 14, 3, skip);
if (skip >= 0) {
msg.addByte(skip);
msg.addByte(0xFF);
}
}
//moving up a floor up makes us out of sync
//west
msg.addByte(0x68);
GetMapDescription(oldPos.x - 8, oldPos.y - 5, newPos.z, 1, 14, msg);
//north
msg.addByte(0x65);
GetMapDescription(oldPos.x - 8, oldPos.y - 6, newPos.z, 18, 1, msg);
}
void ProtocolGame::MoveDownCreature(NetworkMessage& msg, const Creature* creature, const Position& newPos, const Position& oldPos)
{
if (creature != player) {
return;
}
//floor change down
msg.addByte(0xBF);
//going from surface to underground
if (newPos.z == 8) {
int32_t skip = -1;
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z, 18, 14, -1, skip);
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z + 1, 18, 14, -2, skip);
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z + 2, 18, 14, -3, skip);
if (skip >= 0) {
msg.addByte(skip);
msg.addByte(0xFF);
}
}
//going further down
else if (newPos.z > oldPos.z && newPos.z > 8 && newPos.z < 14) {
int32_t skip = -1;
GetFloorDescription(msg, oldPos.x - 8, oldPos.y - 6, newPos.z + 2, 18, 14, -3, skip);
if (skip >= 0) {
msg.addByte(skip);
msg.addByte(0xFF);
}
}
//moving down a floor makes us out of sync
//east
msg.addByte(0x66);
GetMapDescription(oldPos.x + 9, oldPos.y - 7, newPos.z, 1, 14, msg);
//south
msg.addByte(0x67);
GetMapDescription(oldPos.x - 8, oldPos.y + 7, newPos.z, 18, 1, msg);
}
void ProtocolGame::AddShopItem(NetworkMessage& msg, const ShopInfo& item)
{
const ItemType& it = Item::items[item.itemId];
msg.add<uint16_t>(it.clientId);
if (it.isSplash() || it.isFluidContainer()) {
msg.addByte(serverFluidToClient(item.subType));
} else {
msg.addByte(0x00);
}
msg.addString(item.realName);
msg.add<uint32_t>(it.weight);
msg.add<uint32_t>(item.buyPrice);
msg.add<uint32_t>(item.sellPrice);
}
void ProtocolGame::parseExtendedOpcode(NetworkMessage& msg)
{
uint8_t opcode = msg.getByte();
const std::string& buffer = msg.getString();
// process additional opcodes via lua script event
addGameTask(&Game::parsePlayerExtendedOpcode, player->getID(), opcode, buffer);
}
| 1 | 17,115 | this should be on default-switch, uhm? else you will handle twice (c++ and lua). I'm just saying... | otland-forgottenserver | cpp |
@@ -60,7 +60,7 @@ public class Program
// turn off the above default. i.e any
// instrument which does not match any views
// gets dropped.
- // .AddView(instrumentName: "*", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop })
+ // .AddView(instrumentName: "*", MetricStreamConfiguration.Drop)
.AddConsoleExporter()
.Build();
| 1 | // <copyright file="Program.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Diagnostics.Metrics;
using OpenTelemetry;
using OpenTelemetry.Metrics;
public class Program
{
private static readonly Meter Meter1 = new Meter("CompanyA.ProductA.Library1", "1.0");
private static readonly Meter Meter2 = new Meter("CompanyA.ProductB.Library2", "1.0");
public static void Main(string[] args)
{
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(Meter1.Name)
.AddMeter(Meter2.Name)
// Rename an instrument to new name.
.AddView(instrumentName: "MyCounter", name: "MyCounterRenamed")
// Change Histogram bounds
.AddView(instrumentName: "MyHistogram", new HistogramConfiguration() { BucketBounds = new double[] { 10, 20 } })
// For the instrument "MyCounterCustomTags", aggregate with only the keys "tag1", "tag2".
.AddView(instrumentName: "MyCounterCustomTags", new MetricStreamConfiguration() { TagKeys = new string[] { "tag1", "tag2" } })
// Drop the instrument "MyCounterDrop".
.AddView(instrumentName: "MyCounterDrop", MetricStreamConfiguration.Drop)
// Advanced selection criteria and config via Func<Instrument, MetricStreamConfiguration>
.AddView((instrument) =>
{
if (instrument.Meter.Name.Equals("CompanyA.ProductB.Library2") &&
instrument.GetType().Name.Contains("Histogram"))
{
return new HistogramConfiguration() { BucketBounds = new double[] { 10, 20 } };
}
return null;
})
// An instrument which does not match any views
// gets processed with default behavior. (SDK default)
// Uncommenting the following line will
// turn off the above default. i.e any
// instrument which does not match any views
// gets dropped.
// .AddView(instrumentName: "*", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop })
.AddConsoleExporter()
.Build();
var random = new Random();
var counter = Meter1.CreateCounter<long>("MyCounter");
for (int i = 0; i < 20000; i++)
{
counter.Add(1, new("tag1", "value1"), new("tag2", "value2"));
}
var histogram = Meter1.CreateHistogram<long>("MyHistogram");
for (int i = 0; i < 20000; i++)
{
histogram.Record(random.Next(1, 1000), new("tag1", "value1"), new("tag2", "value2"));
}
var counterCustomTags = Meter1.CreateCounter<long>("MyCounterCustomTags");
for (int i = 0; i < 20000; i++)
{
counterCustomTags.Add(1, new("tag1", "value1"), new("tag2", "value2"), new("tag3", "value4"));
}
var counterDrop = Meter1.CreateCounter<long>("MyCounterDrop");
for (int i = 0; i < 20000; i++)
{
counterDrop.Add(1, new("tag1", "value1"), new("tag2", "value2"));
}
var histogram2 = Meter2.CreateHistogram<long>("MyHistogram2");
for (int i = 0; i < 20000; i++)
{
histogram2.Record(random.Next(1, 1000), new("tag1", "value1"), new("tag2", "value2"));
}
}
}
| 1 | 22,419 | unrelated minor fix | open-telemetry-opentelemetry-dotnet | .cs |
@@ -19,6 +19,7 @@ module Travis
def setup
super
cmd "nvm use #{config[:node_js]}"
+ cmd "npm config set spin false", echo: false
if npm_should_disable_strict_ssl?
cmd 'echo "### Disabling strict SSL ###"'
cmd 'npm conf set strict-ssl false' | 1 | module Travis
module Build
class Script
class NodeJs < Script
DEFAULTS = {
:node_js => '0.10'
}
def cache_slug
super << "--node-" << config[:node_js].to_s
end
def export
super
config[:node_js] ||= config[:nodejs] # some old projects use language: nodejs. MK.
set 'TRAVIS_NODE_VERSION', config[:node_js], echo: false
end
def setup
super
cmd "nvm use #{config[:node_js]}"
if npm_should_disable_strict_ssl?
cmd 'echo "### Disabling strict SSL ###"'
cmd 'npm conf set strict-ssl false'
end
setup_npm_cache if npm_cache_required?
end
def announce
super
cmd 'node --version'
cmd 'npm --version'
end
def install
uses_npm? then: "npm install #{config[:npm_args]}", fold: 'install', retry: true
end
def script
uses_npm? then: 'npm test', else: 'make test'
end
def npm_cache_required?
Array(config[:cache]).include?('npm')
end
def setup_npm_cache
if data.hosts && data.hosts[:npm_cache]
cmd 'npm config set registry http://registry.npmjs.org/', echo: false, assert: false
cmd "npm config set proxy #{data.hosts[:npm_cache]}", echo: false, assert: false
end
end
private
def uses_npm?(*args)
self.if '-f package.json', *args
end
def node_0_6?
(config[:node_js] || '').to_s.split('.')[0..1] == %w(0 6)
end
def npm_should_disable_strict_ssl?
node_0_6?
end
end
end
end
end
| 1 | 11,747 | can you add `, echo: false` to the end of this as well. I don't think we need to echo this to the log. You might need to update the spec as well. | travis-ci-travis-build | rb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.